An open source, non-profit web search engine
Set up postgres for running tests in CI
Daoud Clarke05691df9f5e6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 01f3ee9..1c49173 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -8,6 +8,21 @@ on:jobs:test:runs-on: ubuntu-latest++ services:+ postgres:+ image: postgres:15+ env:+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: test_mwmbl+ options: >-+ --health-cmd pg_isready+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5+ ports:+ - 5432:5432+steps:#----------------------------------------------# check-out repo and set-up python@@ -54,6 +69,6 @@ jobs:#----------------------------------------------- name: Run testsenv:- DJANGO_SETTINGS_MODULE: mwmbl.settings_dev+ DATABASE_URL: postgres://postgres:postgres@localhost:5432/test_mwmblrun: |poetry run pytestdiff --git a/poetry.lock b/poetry.lockindex e25e416..d8c4e78 100644--- a/poetry.lock+++ b/poetry.lock@@ -1702,6 +1702,24 @@ pluggy = ">=0.12,<2.0"[package.extras]testing = ["argcomplete", "attrs (>=19.2.0)", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"]+[[package]]+name = "pytest-django"+version = "4.11.1"+description = "A Django plugin for pytest."+optional = false+python-versions = ">=3.8"+files = [+ {file = "pytest_django-4.11.1-py3-none-any.whl", hash = "sha256:1b63773f648aa3d8541000c26929c1ea63934be1cfa674c76436966d73fe6a10"},+ {file = "pytest_django-4.11.1.tar.gz", hash = "sha256:a949141a1ee103cb0e7a20f1451d355f83f5e4a5d07bdd4dcfdd1fd0ff227991"},+]++[package.dependencies]+pytest = ">=7.0.0"++[package.extras]+docs = ["sphinx", "sphinx_rtd_theme"]+testing = ["Django", "django-configurations (>=2.0)"]+[[package]]name = "pytest-mock"version = "3.14.1"@@ -2503,4 +2521,4 @@ indexer = ["Levenshtein", "beautifulsoup4", "idna", "langdetect", "pyarrow", "py[metadata]lock-version = "2.0"python-versions = ">=3.11,<3.12"-content-hash = "c36ad090c43fbbffc4b435af3f3d0d16cc0f63eefefaa550c720075f37d95d55"+content-hash = "a7c1ab87d8f3f1cd694b1009f9e4b61369ff50d9edd1b0691b8f167a3714667f"diff --git a/pyproject.toml b/pyproject.tomlindex ea74597..59915c3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -18,6 +18,7 @@ requests = "^2.27.1"psycopg2-binary = "^2.9.3"pytest = "^7.2.1"pytest-mock = "^3.10.0"+pytest-django = "^4.5.2"# Optional dependencies do not get installed by default. Look under tool.poetry.extras section# to see which extras to use.@@ -88,3 +89,6 @@ mwmbl-crawl = "mwmbl.crawl:run"[tool.pytest.ini_options]log_cli = truelog_cli_level = "INFO"+DJANGO_SETTINGS_MODULE = "mwmbl.settings_dev"+python_files = ["tests.py", "test_*.py", "*_tests.py"]+addopts = "--reuse-db"diff --git a/test/test_evaluation_api.py b/test/test_evaluation_api.pynew file mode 100644index 0000000..cf57654--- /dev/null+++ b/test/test_evaluation_api.py@@ -0,0 +1,268 @@+import pytest+import io+from django.contrib.auth import get_user_model+from allauth.account.models import EmailAddress+from ninja_jwt.tokens import RefreshToken++from mwmbl.models import WasmEvaluationJob+++User = get_user_model()+++def user():+ """Create a test user"""+ return User.objects.create_user(+ username='testuser',+ email='[email protected]',+ password='testpass123'+ )+++def verified_user(user):+ """Create a user with verified email"""+ EmailAddress.objects.create(+ user=user,+ email='[email protected]',+ verified=True,+ primary=True+ )+ return user+++def unverified_user():+ """Create a user with unverified email"""+ user = User.objects.create_user(+ username='unverified',+ email='[email protected]',+ password='testpass123'+ )+ EmailAddress.objects.create(+ user=user,+ email='[email protected]',+ verified=False,+ primary=True+ )+ return user+++def access_token(verified_user):+ """Generate JWT access token for verified user"""+ refresh = RefreshToken.for_user(verified_user)+ return str(refresh.access_token)+++def unverified_access_token(unverified_user):+ """Generate JWT access token for unverified user"""+ refresh = RefreshToken.for_user(unverified_user)+ return str(refresh.access_token)+++def valid_wasm_bytes():+ """Create minimal valid WASM file bytes"""+ # This is a minimal WASM module with memory export+ # Generated using: wat2wasm with the following WAT:+ # (module+ # (memory (export "memory") 1)+ # )+ return bytes([+ 0x00, 0x61, 0x73, 0x6d, # WASM magic number+ 0x01, 0x00, 0x00, 0x00, # WASM version+ 0x05, 0x03, 0x01, 0x00, 0x01, # Memory section: 1 page minimum+ 0x07, 0x0a, 0x01, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00 # Export section: export "memory"+ ])+++def invalid_wasm_bytes():+ """Create invalid WASM file bytes"""+ return b'invalid wasm content'+++def test_submit_valid_wasm_file(client, verified_user, access_token, valid_wasm_bytes):+ """Test submitting a valid WASM file"""+ wasm_file = io.BytesIO(valid_wasm_bytes)+ wasm_file.name = 'test_ranker.wasm'++ response = client.post(+ '/api/v1/evaluate/submit',+ {+ 'file': wasm_file+ },+ HTTP_AUTHORIZATION=f'Bearer {access_token}'+ )++ assert response.status_code == 200++ response_data = response.json()+ assert 'job_id' in response_data+ assert response_data['status'] == 'VALIDATED'+ assert 'message' in response_data++ # Verify job was created in database+ job = WasmEvaluationJob.objects.get(id=response_data['job_id'])+ assert job.user == verified_user+ assert job.status == 'VALIDATED'+ assert job.wasm_file == valid_wasm_bytes+++def test_submit_invalid_wasm_file(client, access_token, invalid_wasm_bytes):+ """Test submitting an invalid WASM file"""+ wasm_file = io.BytesIO(invalid_wasm_bytes)+ wasm_file.name = 'invalid.wasm'++ response = client.post(+ '/api/v1/evaluate/submit',+ {+ 'file': wasm_file+ },+ HTTP_AUTHORIZATION=f'Bearer {access_token}'+ )++ assert response.status_code == 400++ response_data = response.json()+ assert response_data['status'] == 'error'+ assert 'WASM validation failed' in response_data['message']+++def test_submit_non_wasm_file(client, access_token):+ """Test submitting a file without .wasm extension"""+ text_file = io.BytesIO(b'some text content')+ text_file.name = 'test.txt'++ response = client.post(+ '/api/v1/evaluate/submit',+ {+ 'file': text_file+ },+ HTTP_AUTHORIZATION=f'Bearer {access_token}'+ )++ assert response.status_code == 400++ response_data = response.json()+ assert response_data['status'] == 'error'+ assert 'File must have .wasm extension' in response_data['message']+++def test_submit_large_file(client, access_token):+ """Test submitting a file that exceeds size limit"""+ # Create a file larger than 10MB+ large_content = b'x' * (11 * 1024 * 1024) # 11MB+ large_file = io.BytesIO(large_content)+ large_file.name = 'large.wasm'++ response = client.post(+ '/api/v1/evaluate/submit',+ {+ 'file': large_file+ },+ HTTP_AUTHORIZATION=f'Bearer {access_token}'+ )++ assert response.status_code == 400++ response_data = response.json()+ assert response_data['status'] == 'error'+ assert 'File too large' in response_data['message']+++def test_submit_without_authentication(client, valid_wasm_bytes):+ """Test submitting without JWT token"""+ wasm_file = io.BytesIO(valid_wasm_bytes)+ wasm_file.name = 'test.wasm'++ response = client.post(+ '/api/v1/evaluate/submit',+ {+ 'file': wasm_file+ }+ )++ assert response.status_code == 401+++def test_submit_with_unverified_email(client, unverified_access_token, valid_wasm_bytes):+ """Test submitting with unverified email address"""+ wasm_file = io.BytesIO(valid_wasm_bytes)+ wasm_file.name = 'test.wasm'++ response = client.post(+ '/api/v1/evaluate/submit',+ {+ 'file': wasm_file+ },+ HTTP_AUTHORIZATION=f'Bearer {unverified_access_token}'+ )++ assert response.status_code == 403++ response_data = response.json()+ assert response_data['status'] == 'error'+ assert 'Email address is not verified' in response_data['message']+++def test_submit_without_file(client, access_token):+ """Test submitting without a file"""+ response = client.post(+ '/api/v1/evaluate/submit',+ {},+ HTTP_AUTHORIZATION=f'Bearer {access_token}'+ )++ assert response.status_code == 422 # Validation error+++def test_multiple_submissions_same_user(client, verified_user, access_token, valid_wasm_bytes):+ """Test that a user can submit multiple WASM files"""+ # Submit first file+ wasm_file1 = io.BytesIO(valid_wasm_bytes)+ wasm_file1.name = 'ranker1.wasm'++ response1 = client.post(+ '/api/v1/evaluate/submit',+ {'file': wasm_file1},+ HTTP_AUTHORIZATION=f'Bearer {access_token}'+ )++ assert response1.status_code == 200+ job_id1 = response1.json()['job_id']++ # Submit second file+ wasm_file2 = io.BytesIO(valid_wasm_bytes)+ wasm_file2.name = 'ranker2.wasm'++ response2 = client.post(+ '/api/v1/evaluate/submit',+ {'file': wasm_file2},+ HTTP_AUTHORIZATION=f'Bearer {access_token}'+ )++ assert response2.status_code == 200+ job_id2 = response2.json()['job_id']++ # Verify both jobs exist and belong to the same user+ assert job_id1 != job_id2++ job1 = WasmEvaluationJob.objects.get(id=job_id1)+ job2 = WasmEvaluationJob.objects.get(id=job_id2)++ assert job1.user == verified_user+ assert job2.user == verified_user+ assert job1.status == 'VALIDATED'+ assert job2.status == 'VALIDATED'