"""A1 — Django skeleton: WEB-01, WEB-07, ARC-70, ARC-73, ADR-54, ADR-55, ADR-38, ADR-11.""" import os import subprocess import sys from pathlib import Path import pytest from django.conf import settings from django.contrib.auth import get_user_model from django.core.management import call_command from django.db import IntegrityError, connection, transaction ROOT = Path(__file__).resolve().parents[2] def _import_settings(**env: str) -> subprocess.CompletedProcess: """Import `config.settings` in a clean process with exactly the given environment.""" clean = {"PATH": os.environ["PATH"], "PYTHONPATH": str(ROOT), **env} return subprocess.run( [sys.executable, "-c", "import config.settings"], cwd=ROOT, env=clean, capture_output=True, text=True, ) # --- WEB-01 / WEB-07: the site answers, on localhost, with no domain configured --------------- @pytest.mark.django_db def test_home_answers_on_localhost(client): """WEB-07: `http://localhost` serves the placeholder home in Italian.""" response = client.get("/", HTTP_HOST="localhost") assert response.status_code == 200 assert "PLM Lottery" in response.content.decode() assert 'lang="it"' in response.content.decode() @pytest.mark.django_db def test_health_live_checks_the_database(client): """ARC-73: liveness answers 200 and says ok while the database opens.""" response = client.get("/health/live", HTTP_HOST="localhost") assert response.status_code == 200 assert response.json() == {"status": "ok"} @pytest.mark.django_db def test_health_live_reports_a_database_failure(client, monkeypatch): """ARC-73: an unreachable database is a 503, not a 200.""" def boom(*args, **kwargs): raise RuntimeError("down") monkeypatch.setattr(connection, "cursor", boom) assert client.get("/health/live", HTTP_HOST="localhost").status_code == 503 def test_unknown_host_is_refused(client): """WEB-07: only configured hosts are served; a domain is added by configuration.""" assert client.get("/", HTTP_HOST="evil.example").status_code == 400 def test_domain_comes_from_configuration_only(): """WEB-07: SITE_ADDRESS adds the host and the CSRF origin, with no code change.""" code = ( "import config.settings as s;" "assert 'lottery.example.com' in s.ALLOWED_HOSTS;" "assert 'https://lottery.example.com' in s.CSRF_TRUSTED_ORIGINS" ) result = subprocess.run( [sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, env={"PATH": os.environ["PATH"], "PYTHONPATH": str(ROOT), "DJANGO_SECRET_KEY": "k" * 60, "SITE_ADDRESS": "lottery.example.com"}, ) assert result.returncode == 0, result.stderr # --- ADR-11 analogue: refuse to start with an inadequate secret -------------------------------- def test_refuses_to_start_without_a_secret(): result = _import_settings() assert result.returncode != 0 assert "DJANGO_SECRET_KEY" in result.stderr def test_refuses_to_start_with_a_short_secret(): result = _import_settings(DJANGO_SECRET_KEY="short") assert result.returncode != 0 def test_a_long_secret_is_accepted(): assert _import_settings(DJANGO_SECRET_KEY="k" * 60).returncode == 0 # --- WEB-02: session and CSRF cookie attributes ---------------------------------------------- def test_cookies_are_secure_outside_debug(): """WEB-02: outside DEBUG the cookies are Secure, HttpOnly and SameSite.""" code = ( "import config.settings as s;" "assert s.SESSION_COOKIE_SECURE and s.CSRF_COOKIE_SECURE;" "assert s.SESSION_COOKIE_HTTPONLY;" "assert s.SESSION_COOKIE_SAMESITE == 'Lax'" ) result = subprocess.run( [sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, env={"PATH": os.environ["PATH"], "PYTHONPATH": str(ROOT), "DJANGO_SECRET_KEY": "k" * 60}, ) assert result.returncode == 0, result.stderr # --- ADR-55: SQLite shared by web and worker -------------------------------------------------- def test_sqlite_is_configured_for_two_processes(): """ADR-55: IMMEDIATE write transactions, WAL and synchronous=FULL are requested.""" options = settings.DATABASES["default"]["OPTIONS"] assert options["transaction_mode"] == "IMMEDIATE" assert "journal_mode=WAL" in options["init_command"] assert "synchronous=FULL" in options["init_command"] def test_sqlite_pragmas_apply_to_a_file_database(tmp_path): """ARC-70: on a file database the pragmas really take effect.""" code = ( "import django, os;" "os.environ['DJANGO_SETTINGS_MODULE']='config.settings';" "django.setup();" "from django.db import connection;" "c = connection.cursor();" "c.execute('PRAGMA journal_mode'); assert c.fetchone()[0] == 'wal';" "c.execute('PRAGMA synchronous'); assert c.fetchone()[0] == 2;" "c.execute('PRAGMA foreign_keys'); assert c.fetchone()[0] == 1" ) result = subprocess.run( [sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, env={"PATH": os.environ["PATH"], "PYTHONPATH": str(ROOT), "DJANGO_SECRET_KEY": "k" * 60, "DJANGO_DB_PATH": str(tmp_path / "site.sqlite3")}, ) assert result.returncode == 0, result.stderr # --- ADR-54 / ADR-38: the user model, case-insensitive usernames --------------------------------- def test_the_custom_user_model_is_in_use(): assert settings.AUTH_USER_MODEL == "accounts.User" assert get_user_model()._meta.label == "accounts.User" @pytest.mark.django_db def test_usernames_are_unique_ignoring_case(): """ADR-38: `Mario` and `mario` are the same name.""" User = get_user_model() User.objects.create_user("Mario", password="x" * 12) with pytest.raises(IntegrityError), transaction.atomic(): User.objects.create_user("mario", password="x" * 12) @pytest.mark.django_db def test_the_username_is_stored_as_typed(): User = get_user_model() User.objects.create_user("Mario", password="x" * 12) assert User.objects.get().username == "Mario" def test_passwords_use_argon2_outside_tests(): """ADR-36: Argon2 stays the password hash; the test settings only swap it for speed.""" code = ( "import config.settings as s;" "assert s.PASSWORD_HASHERS[0].endswith('Argon2PasswordHasher')" ) result = subprocess.run( [sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, env={"PATH": os.environ["PATH"], "PYTHONPATH": str(ROOT), "DJANGO_SECRET_KEY": "k" * 60}, ) assert result.returncode == 0, result.stderr # --- ADR-55: the worker is its own process ----------------------------------------------------- @pytest.mark.django_db def test_worker_runs_one_tick_and_exits(): """ARC-71: `manage.py run_worker --once` starts, ticks (opening the first round) and stops.""" from apps.lottery.models import Round call_command("run_worker", "--once") assert Round.objects.filter(status="open").count() == 1 @pytest.mark.django_db def test_migrations_are_in_sync_with_the_models(): """A model change without its migration fails here, not in production.""" call_command("makemigrations", "--check", "--dry-run")