Skip to content

Commit f2a4e89

Browse files
Refactor/test suite architecture (#62)
* docs(tests): document test-suite conventions * refactor(tests): reorganize users and celery tests * refactor(tests): reorganize medical notes tests * refactor(tests): reorganize animals tests * refactor(tests): reorganize offline snapshots tests * refactor(tests): normalize homepage and project-level tests * refactor(tests): consolidate fixtures and helpers * test: normalize pytest markers * refactor(tests): hoist function-level imports * test: enforce unused-import checks in test modules * ci: split unit and integration test jobs * docs(tests): update test execution instructions * test: use fast password hasher in test fixtures
1 parent 65376a9 commit f2a4e89

79 files changed

Lines changed: 5884 additions & 5919 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/django.yml‎

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ jobs:
6060
- name: Codespell
6161
run: uv run codespell
6262

63-
test:
63+
test-unit:
6464
runs-on: ubuntu-latest
6565
env:
6666
POSTGRES_DB: ${{ secrets.POSTGRES_DB }}
@@ -103,11 +103,54 @@ jobs:
103103
- name: Install dependencies
104104
run: uv sync
105105

106-
- name: Run tests (Django runner)
107-
run: PYTHONPATH=src uv run python manage.py test
106+
- name: Run unit tests
107+
run: uv run pytest -m "unit and not slow"
108108

109-
- name: Run tests (pytest)
110-
run: uv run pytest -m "not slow"
109+
test-integration:
110+
runs-on: ubuntu-latest
111+
env:
112+
POSTGRES_DB: ${{ secrets.POSTGRES_DB }}
113+
POSTGRES_USER: ${{ secrets.POSTGRES_USER }}
114+
POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
115+
CELERY_BROKER_URL: ${{ secrets.CELERY_BROKER_URL }}
116+
FLOWER_PORT: ${{ secrets.FLOWER_PORT }}
117+
FLOWER_BASIC_AUTH: ${{ secrets.FLOWER_BASIC_AUTH }}
118+
DB_NAME: ${{ secrets.DB_NAME }}
119+
DB_USER: ${{ secrets.DB_USER }}
120+
DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
121+
DB_HOST: ${{ secrets.DB_HOST }}
122+
DB_PORT: ${{ secrets.DB_PORT }}
123+
COUCHDB_USER: ${{ secrets.COUCHDB_USER }}
124+
COUCHDB_PASSWORD: ${{ secrets.COUCHDB_PASSWORD }}
125+
COUCHDB_PORT: ${{ secrets.COUCHDB_PORT }}
126+
COUCH_CONNECTOR: ${{ secrets.COUCH_CONNECTOR }}
127+
CELERY_BACKEND: ${{ secrets.CELERY_BACKEND }}
128+
EMAIL_BACKEND: ${{ secrets.EMAIL_BACKEND }}
129+
EMAIL_HOST: ${{ secrets.EMAIL_HOST }}
130+
EMAIL_PORT: ${{ secrets.EMAIL_PORT }}
131+
EMAIL_USE_TLS: ${{ secrets.EMAIL_USE_TLS }}
132+
EMAIL_HOST_USER: ${{ secrets.EMAIL_HOST_USER }}
133+
EMAIL_HOST_PASSWORD: ${{ secrets.EMAIL_HOST_PASSWORD }}
134+
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }}
135+
PYTHONUNBUFFERED: "1"
136+
137+
steps:
138+
- name: Checkout
139+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
140+
141+
- name: Setup uv
142+
# SHA-pinned to v10.1.0; the trailing comment only labels the SHA, it isn't the pin.
143+
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
144+
with:
145+
enable-cache: true
146+
cache-dependency-glob: "uv.lock"
147+
python-version: "3.14"
148+
149+
- name: Install dependencies
150+
run: uv sync
151+
152+
- name: Run integration tests
153+
run: uv run pytest -m "integration and not slow"
111154

112155
manifests:
113156
name: Kubernetes manifests
@@ -369,7 +412,7 @@ jobs:
369412
publish:
370413
name: Publish app image to GHCR
371414
runs-on: ubuntu-latest
372-
needs: [test, lint, manifests]
415+
needs: [lint, test-unit, test-integration, manifests]
373416
# workflow_dispatch allows publishing a sha- tag from a feature branch
374417
# (e.g. to test the branch on minikube before merge).
375418
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ just test-unit
119119
```
120120

121121
#### Integration tests
122-
Requires Docker backing services running (`just infra`).
122+
Run against a SQLite test database; no Docker backing services are needed.
123123
```powershell
124124
uv run pytest -m integration
125125
# or

‎conftest.py‎

Lines changed: 60 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,79 @@
1+
from io import BytesIO
12
from unittest.mock import MagicMock, patch
23

34
import pytest
45
from django.contrib.auth.models import User
6+
from django.core.files.uploadedfile import SimpleUploadedFile
7+
from django.test import Client, override_settings
8+
from PIL import Image as PILImage
59

610
from ahc.apps.users.models import Profile
711

12+
_DB_FIXTURES = frozenset({"db", "transactional_db", "client", "admin_client", "django_user_model", "live_server"})
813

9-
@pytest.fixture
10-
def user_profile(db):
14+
15+
def pytest_collection_modifyitems(items):
16+
"""Fail collection on a missing or inconsistent category marker — CI selects jobs by marker."""
17+
errors = []
18+
for item in items:
19+
is_unit = item.get_closest_marker("unit") is not None
20+
is_integration = item.get_closest_marker("integration") is not None
21+
if is_unit == is_integration:
22+
errors.append(f"{item.nodeid}: needs exactly one of 'unit' or 'integration'")
23+
elif is_unit and (item.get_closest_marker("django_db") or _DB_FIXTURES & set(item.fixturenames)):
24+
errors.append(f"{item.nodeid}: 'unit' test uses the database or the Django test client")
25+
if errors:
26+
raise pytest.UsageError("Invalid test category markers:\n" + "\n".join(errors))
27+
28+
29+
@pytest.fixture(scope="session", autouse=True)
30+
def fast_password_hasher():
31+
"""PBKDF2 dominates fixture setup; no test depends on the hashing algorithm."""
32+
with override_settings(PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"]):
33+
yield
34+
35+
36+
def _create_user_profile(username):
1137
"""Create a User + Profile pair, mocking image processing in Profile.save()."""
1238
mock_img = MagicMock()
1339
mock_img.height = 100
1440
mock_img.width = 100
1541
with patch("ahc.apps.users.models.Image.open", return_value=mock_img):
16-
user = User.objects.create_user(username="testuser", password="testpass123") # nosec B106
42+
user = User.objects.create_user(username=username, password="testpass123") # nosec B106
1743
return user, Profile.objects.get(user=user)
1844

1945

46+
@pytest.fixture
47+
def user_profile(db):
48+
return _create_user_profile("testuser")
49+
50+
2051
@pytest.fixture
2152
def second_user_profile(db):
2253
"""A second User + Profile for multi-user permission tests."""
23-
mock_img = MagicMock()
24-
mock_img.height = 100
25-
mock_img.width = 100
26-
with patch("ahc.apps.users.models.Image.open", return_value=mock_img):
27-
user = User.objects.create_user(username="otheruser", password="testpass123") # nosec B106
28-
return user, Profile.objects.get(user=user)
54+
return _create_user_profile("otheruser")
55+
56+
57+
@pytest.fixture
58+
def logged_in_client(db):
59+
"""Factory returning a fresh Client force-logged-in as the given user."""
60+
61+
def make(user):
62+
client = Client()
63+
client.force_login(user)
64+
return client
65+
66+
return make
67+
68+
69+
@pytest.fixture
70+
def png_upload():
71+
"""Factory for a real, minimal PNG upload — Django's ImageField validates actual image content."""
72+
73+
def make(name="avatar.png"):
74+
buf = BytesIO()
75+
PILImage.new("RGB", (10, 10), color="blue").save(buf, format="PNG")
76+
buf.seek(0)
77+
return SimpleUploadedFile(name, buf.read(), content_type="image/png")
78+
79+
return make

‎doc/testing.md‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Test suite conventions
2+
3+
This document describes how tests are organised in AHC. It is the reference for adding, moving
4+
or reviewing tests.
5+
6+
## Layout
7+
8+
Tests live in a `tests/` package inside the package they test. The layout of `tests/` mirrors
9+
the production code, so finding the tests for a module is a path lookup rather than a search.
10+
11+
| Production code | Tests |
12+
|--------------------------------|---------------------------------------------|
13+
| `{app}/models.py` | `{app}/tests/test_models.py` |
14+
| `{app}/services.py` | `{app}/tests/test_services.py` |
15+
| `{app}/services/exporter.py` | `{app}/tests/services/test_exporter.py` |
16+
| `{app}/utils_owner/views.py` | `{app}/tests/utils_owner/test_views.py` |
17+
| `ahc/views.py`, `ahc/settings.py` | `src/ahc/tests/test_views.py`, `test_csp.py` |
18+
19+
Rules:
20+
21+
- A module `x.py` maps to `test_x.py`; a package `x/` maps to a directory `tests/x/`.
22+
- A large module may map to a `tests/<module>/` directory split by area
23+
(for example `animals/tests/views/test_profile.py`, `views/test_stable.py`).
24+
- A test of a business invariant that crosses several layers stays together in
25+
`tests/test_<feature>.py` (for example `medical_notes/tests/test_deceased_write_blocking.py`).
26+
Reading the whole scenario in one place matters more than splitting it per layer.
27+
- Do not create empty placeholder test files for untested modules.
28+
- Every test directory contains an `__init__.py`. Basenames such as `test_views.py` repeat across
29+
apps, and without packages pytest fails with "import file mismatch".
30+
- Never keep a `tests.py` module next to a `tests/` package: the package shadows the module.
31+
- Test files are named `test_*.py`. Test classes are named `Test*` and do not subclass
32+
`django.test.TestCase`; write plain pytest classes and functions.
33+
34+
## Markers
35+
36+
Every test carries exactly one kind marker: `unit` or `integration`. A collection hook in the
37+
root `conftest.py` rejects tests with neither, with both, or with `unit` combined with database
38+
or Django client access.
39+
40+
| Marker | Meaning |
41+
|---------------|---------|
42+
| `unit` | An isolated component. No database, no Django request/client, no external services. It may use hermetic local resources such as `tmp_path` when they are part of the component's direct contract (for example a file sweeper tested on a temporary directory). |
43+
| `integration` | Several layers or adapters working together, or real infrastructure: ORM/database, Django client/URLconf/middleware, signals with the ORM, management commands, Celery/Redis/CouchDB. |
44+
| `regression` | Orthogonal, added on top of `unit` or `integration`. Guards a specific fixed bug; the test docstring names the PR or issue. |
45+
| `slow` | Excluded from CI runs. |
46+
| `django_db` | Technical pytest-django marker granting database access. It is not a test category. |
47+
48+
`regression` rules:
49+
50+
- Put it on the test method that guards the fixed bug. Put it on a class only when every test
51+
in the class guards the same bug.
52+
- A test merely added in a `fix(...)` commit is not a regression test by that fact alone; it has
53+
to protect against the bug that commit fixed.
54+
55+
## Fixtures
56+
57+
Fixtures live at the lowest level that serves every user.
58+
59+
| Level | What belongs there |
60+
|--------------------------------|--------------------|
61+
| Root `conftest.py` | Fixtures used by several apps: `user_profile`, `second_user_profile`, `logged_in_client`, `png_upload`, and the marker guard. |
62+
| `{app}/tests/conftest.py` | Domain fixtures used by several files of one app (for example `animal`, `snapshot_dir`). |
63+
| A subdirectory `conftest.py` | Fixtures used only by one area of an app. |
64+
| The test module or class | Fixtures used by a single file or class. |
65+
66+
- There is no central `fixtures.py`.
67+
- Plain helper functions shared by several files of one app go to `{app}/tests/helpers.py` and
68+
are imported relatively (`from ..helpers import _query`). Do not import test code through an
69+
absolute `ahc.apps...tests` path: `src/__init__.py` makes pytest import test modules as
70+
`src.ahc.apps...`, and an absolute import would load a second copy of the module.
71+
- A class-level fixture with the same name as a conftest fixture overrides it for that class.
72+
Keep the override when the test asserts on the overridden data.
73+
74+
## Parametrization
75+
76+
Parametrize only when the behaviour under test is genuinely the same and only the input differs.
77+
Separate behaviours get separate tests, even when their bodies look similar.
78+
79+
## Running tests
80+
81+
```bash
82+
uv run pytest # whole suite
83+
uv run pytest -m unit
84+
uv run pytest -m integration
85+
uv run pytest -m regression
86+
87+
just test
88+
just test-unit
89+
just test-integration
90+
just test-regression
91+
```
92+
93+
CI runs `unit` and `integration` in separate parallel jobs. Because every test is exactly one of
94+
the two, together they cover the whole suite once. The test database is SQLite
95+
(set in `settings.py` when pytest is invoked).

‎justfile‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,17 @@ format:
2424
test:
2525
uv run pytest -m "not slow"
2626

27-
# Run only unit tests
27+
# Run only unit tests (same selection as the CI test-unit job)
2828
test-unit:
29-
uv run pytest -m unit -v
29+
uv run pytest -m "unit and not slow" -v
3030

31-
# Run only integration tests
31+
# Run only integration tests (same selection as the CI test-integration job)
3232
test-integration:
33-
uv run pytest -m integration -v
33+
uv run pytest -m "integration and not slow" -v
34+
35+
# Run only tests guarding previously fixed bugs
36+
test-regression:
37+
uv run pytest -m regression -v
3438

3539
# Start Django development server
3640
runserver:

‎pyproject.toml‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,6 @@ ignore = [
6262

6363
[tool.ruff.lint.per-file-ignores]
6464
"tests/**" = ["F401", "F841"]
65-
"test_*.py" = ["F401", "F841"]
6665

6766
[tool.ruff.format]
6867
quote-style = "double"
@@ -73,11 +72,12 @@ docstring-code-line-length = 124
7372
[tool.pytest.ini_options]
7473
DJANGO_SETTINGS_MODULE = "ahc.settings"
7574
pythonpath = ["src"]
76-
python_files = ["test_*.py", "tests.py"]
75+
python_files = ["test_*.py"]
7776
addopts = "--strict-markers"
7877
markers = [
79-
"unit: fast isolated tests with no DB access",
80-
"integration: tests that use the DB or external services",
78+
"unit: isolated component test; no DB, Django test client or external services (tmp_path is fine)",
79+
"integration: collaboration of layers or real infrastructure: ORM/DB, Django client, signals, commands",
80+
"regression: guards a previously fixed bug; added on top of unit or integration",
8181
"slow: tests that take more than a few seconds",
8282
]
8383

0 commit comments

Comments
 (0)