Skip to content

Testing Philosophy

James Dunkerley edited this page Dec 3, 2026 · 4 revisions

Testing philosophy

Home · Architecture

Written against d5aad1f44 on 19 Nov 2026.

In short

  • A green test proves nothing until you have watched it fail for the reason its name gives.
  • Behaviour a modeller can see is a Gherkin scenario; everything else is plain pytest or Vitest.
  • An adapter is tested by a contract suite that runs against every backend, with real engines (git, SQLite, an embedded PostgreSQL), not mocks.
  • The suite tests its own rules: layering, naming, generated artefacts and the CI shards are all checked by tests or lint hooks.
  • Slow suites (memory, mutation) run on a schedule. Windows and macOS run nightly, or on a pull request that carries the windows or macos label.

Testing review holds the numbers and an assessment of how well this works. This page is the guide.

The layers of the suite

This diagram places each suite on the pyramid, from static checks at the bottom to the scheduled and manual layers at the top.

flowchart TB
    subgraph Manual["Scheduled, manual and on demand"]
        W["Wiki walkthroughs"]
        N["PyPSA coverage notebooks, on demand"]
        MU["Mutation tests, weekly, which run the suites on mutants"]
    end
    subgraph E2E["End to end, real backend"]
        FE["frontend Playwright journeys and visual baselines"]
        FN["frontend-next Playwright journeys"]
        DA["desktop app and update specs"]
        A11["Lighthouse accessibility audit, daily"]
    end
    subgraph Acc["Acceptance, Gherkin"]
        NEW["tests/acceptance, http and python drivers"]
        OLD["tests/features, in-process TestClient"]
        PG["The same scenarios on PostgreSQL"]
    end
    subgraph App["App-level pytest"]
        ROOT["tests/test_*.py"]
        CON["tests/contract"]
        REC["Durable recovery with killed child processes"]
        MEM["Memory bounds, nightly"]
        NB["Example notebooks run in CI"]
    end
    subgraph Unit["Unit and contract suites"]
        LIBS["libs/*/tests"]
        WH["Warehouse contracts across JSON, git and PostgreSQL"]
        FU["frontend and frontend-next Vitest"]
        DN["desktop node specs"]
        SDK["frontend-sdk Vitest"]
    end
    subgraph Static["Static and architecture"]
        L["ruff, mypy, Biome, tsc, import-linter, radon"]
        AR["Function verbs, API conformance, drift and narrowing checks"]
    end
    Manual --> E2E --> Acc --> App --> Unit --> Static
Loading

The principles

A test must be shown to fail

Written in backend/CLAUDE.md ("Tests") and .claude/skills/nightly/prove-the-test.md.

Name the one change to production code that should break the test. Make it, watch that test fail, then restore the code with the inverse edit. If the test stays green, fix the test, not the code.

The usual cause of a test that cannot fail is a fixture too thin to tell two things apart:

  • a filter test whose fixture has one matching row;
  • a fixture where every record with A also has B;
  • an assertion on a count, which the right number of wrong answers passes.

Never undo the sabotage with git checkout -- <file>. It discards the uncommitted fix in the same file (root CLAUDE.md, "Git workflow").

The same idea is applied to the suite's own lists. backend/tests/support/expected_failures.py marks each listed test xfail(strict=True), so a test that starts to pass fails the run until its line is removed.

Acceptance behaviour is a Gherkin scenario

Written in backend/CLAUDE.md ("Tests") and docs/specs/2026-10-29-four-layer-acceptance-tests-design.md.

Behaviour that crosses components, or is a workflow a modeller sees, is a scenario, written before the behaviour is built. Unit tests stay plain pytest. Two generations of the suite exist side by side.

Old suite Four-layer suite
Location backend/tests/features/, backend/tests/steps/ backend/tests/acceptance/
System under test TestClient on build_app(), in-process A real tz-ps-conductor serve for each xdist worker, or the Python library
Scenario language Names status codes, media types, problem slugs Names no route, status code, JSON body or adapter
Isolation A new warehouse for each scenario Aliased project names on a shared warehouse (support/alias.py)

New modeller behaviour goes in the four-layer suite, with both drivers. Extend the old suite only where the feature already lives there. Its layers are:

  1. Executable specification: acceptance/features/*.feature. The actor is "the modeller". See snapshot_weightings.feature.
  2. DSL: acceptance/dsl/. One module for each domain part. It holds no assert.
  3. Protocol drivers: acceptance/drivers/interfaces.py declares one Protocol for each DSL part. drivers/http/ and drivers/python_api/ implement them, and drivers/factory.py chooses by ACCEPTANCE_PROTOCOL.
  4. System under test: acceptance/support/server.py starts the server.

backend/tests/acceptance/check_layers.py enforces the split as a pre-commit hook. It refuses a feature file that holds {, /api/ or a status code, and a DSL module that makes a check.

A check that names a route, status code, media type, JSON body or problem slug is plain pytest under backend/tests/contract/.

A contract suite runs against every backend

Written in backend/CLAUDE.md ("Storage: shape of the contracts"). Architecture-Storage describes the adapters.

backend/libs/tz_ps_datawarehouse/tests/conftest.py parametrises the fixtures every contract test uses:

  • networks and projects run over the JSON, git and PostgreSQL warehouses, each reached directly and through the async form;
  • run_store, import_store and export_store run over SQLite, SQLite through the async form, and PostgreSQL.

PostgreSQL is a real embedded server, started by tz_ps_testing.postgresql. A test written once therefore runs about three times.

A second form uses inheritance. tz_ps_testing.object_store_contract.ObjectStoreContract is a class pytest does not collect. The local object store's suite subclasses it, and so does the suite of InMemoryObjectStore, so the fake used in other tests is held to the same contract as the real adapter.

In a scenario, name the warehouse by what it keeps, versioned or unversioned, through the storage_by_backend fixture. Never name the adapter.

A guarantee a backend does not keep is asserted, not skipped

Written in backend/CLAUDE.md ("Tests").

A non-versioned warehouse gives fixed answers where a versioned one keeps history. The contract suite reads the keeps_every_version fixture and asserts both, as test_network_warehouse_contract.py does:

assert info.authoring_run_id == (RUN if keeps_every_version else None)

Memory is bounded for each value, in a child process

tz_ps_testing.rss_growth measures the resident memory of a child process, because tracemalloc does not see what numpy and DuckDB hold. calculate_growth_for_each_added_value runs two sizes so the fixed cost of the process cancels, and build_median_growth takes the median of several runs. backend/tests/test_series_write_memory.py and test_import_memory.py are examples. Such a test takes the memory marker.

Recovery is tested by killing a real process

backend/tests/test_durable_recovery.py starts a child from backend/tests/support/durable_child.py, kills it while the solver is mid-solve, and starts a second runtime on the same SQLite files, which must continue the solve. The import, export and workflow recovery tests follow the same pattern. Architecture-Execution describes the runtime they test.

The architecture is tested

Check Where What it pins
Import contracts [tool.importlinter] in backend/pyproject.toml; backend/tests/test_import_contracts.py The layering of the workspace members
Function verbs backend/tests/test_function_verbs.py The verb table in backend/CLAUDE.md. function_verbs_allow_list.txt holds the exceptions and only shrinks
API conformance backend/tests/features/api_contract_conformance.feature The served OpenAPI against contracts/openapi/core-api.yaml, both ways
Generated artefacts make registry-check, calliope-registry-check, models-check, grammar-check, release-manifest-check; make -C frontend-sdk drift That committed generated code matches its source
Narrowing make registry-narrowing-check, calliope-registry-narrowing-check That a bump does not make an attribute accept less, which would leave stored networks unreadable
Shards backend/tests/test_shards.py That the primary CI selectors, plus the mutation-kit selector, collect each test id once. Other jobs repeat scenarios on purpose
Frontend layers frontend/biome.json; frontend-next/lint/*.grit with frontend-next/scripts/biome-lint.test.ts Which layer may import which
Maintainability backend/ci_scripts/maintainability_report.py Each in-scope source file at radon grade A. The generated parser is left out

Architecture-Build-CI-and-Release covers the workflows that run these.

Examples are tests

backend/tests/test_examples_notebooks.py executes every notebook under docs/examples/. The PyPSA ports each build an upstream PyPSA example through Conductor, solve it, build it again in PyPSA and compare the answers. Each known gap is asserted, so a gap that closes fails the notebook. docs/examples/pypsa/COVERAGE.md is the report they back.

The frontends are tested through what the user sees

Written in frontend/CLAUDE.md ("Testing"), frontend/src/test/CLAUDE.md and frontend/e2e/CLAUDE.md.

  • Unit tests use Vitest, Testing Library and the MSW handlers that Orval generates into frontend-sdk. No backend runs. Render through renderWithRouter or renderWithQuery from src/test/render.tsx, never the bare render.
  • Journeys use Playwright against the real backend. In frontend/, each worker starts its own tz-ps-conductor serve on a fresh git warehouse, serving the bundled app from the same origin. Data is seeded over HTTP through e2e/support/seed.ts.
  • Visual baselines are taken through expectScreen in a pinned Docker image, because glyphs differ between operating systems.
  • Accessibility is audited daily by Lighthouse (frontend/scripts/a11y-audit.ts).

The desktop shell keeps its logic in modules that import nothing from Electron, so desktop/tests can run them in plain Node. app.spec.ts drives the packaged shape. See Architecture-Frontends-and-Desktop.

Walkthroughs are exploratory acceptance

A walkthrough builds an upstream example in the app's UI, checks the answer and records its findings as issues. See Walkthroughs.

Which test does a change need

If you changed Write In
Behaviour a modeller sees through the API or the library A scenario, with its DSL method and both drivers backend/tests/acceptance/
A route's status code, media type, problem slug or headers A plain pytest check backend/tests/contract/
An existing scenario of a feature that still lives in the old suite A change or addition beside it, not new coverage backend/tests/features/ and backend/tests/steps/
Logic inside one workspace member A plain pytest unit test backend/libs/<member>/tests/
A port, or an adapter behind one A case in the contract suite, which every adapter then runs backend/libs/tz_ps_datawarehouse/tests/test_*_contract.py, or ObjectStoreContract
A database schema A migration test for that revision backend/libs/tz_ps_datawarehouse/tests/test_migration_*.py
How much memory an operation holds A test marked memory, measured with tz_ps_testing.rss_growth backend/tests/
A solve, import or export that must survive a restart A child-process test backend/tests/test_durable_*.py with a child in backend/tests/support/
Anything that needs Calliope The same kind of test, marked as a Calliope test A file whose path holds calliope, or @pytest.mark.calliope, or @calliope on the feature
The OpenAPI contract Nothing new: the conformance feature and make -C frontend-sdk drift must pass contracts/openapi/core-api.yaml
A screen or component A Vitest test through renderWithRouter Beside the code, as *.test.tsx
A flow that needs the real API, routing or layout A Playwright journey frontend/e2e/ or frontend-next/e2e/
What a screen looks like An expectScreen baseline frontend/e2e/, updated with make -C frontend e2e-update-snapshots
Desktop logic A node project spec desktop/tests/
A CI script or workflow A plain pytest test that reads the file backend/tests/

Running the suites

Run everything through make or uv run, never a bare pytest.

Command What it runs
make -C backend test Every backend test, pytest -n auto
make -C backend test-bdd Both acceptance suites, printed as Given/When/Then, serially
make -C backend test-bdd-postgresql The acceptance suites on the PostgreSQL warehouse
cd backend && ACCEPTANCE_PROTOCOL=python uv run pytest tests/acceptance The four-layer suite through the Python library
cd backend && uv run pytest -m memory The memory tests
make -C backend pypsa-coverage The PyPSA coverage notebooks
make -C backend coverage Everything, with coverage
make -C backend mutation-check Lists tests that fail only under mutmut
make -C backend lint and make -C backend maintainability The static gates
make -C frontend test, make -C frontend-next test, make -C frontend-sdk test The Vitest suites
make e2e (root) Builds, bundles and runs the frontend journeys
make -C frontend e2e-visual The journeys in the pinned image, with screenshots compared
make -C frontend-next e2e The frontend-next journeys
make -C desktop test The desktop node specs
make -C desktop smoke The desktop app specs, against a real backend. Needs the root make bundle and a fully synced backend/.venv
make check (root) Lint, every unit suite, drift checks, typecheck and build. Not the journeys

The backend gate before a commit is make lint, make test, make test-bdd, the four registry checks and make maintainability (backend/CLAUDE.md, "The gate").

Rules that trip people up

Markers

Markers are declared in backend/pyproject.toml.

Marker Effect
calliope Runs only in CI's Calliope shard. backend/conftest.py sets it from the file path, and skips a marked test where Calliope is not installed. A Calliope test that misses the mark fails on every other shard. Do not guard with skipif on find_spec("calliope")
memory Runs nightly, never on a pull request
inspects_code For a test that reads names, signatures or stack frames. Mutation runs leave it out, because mutmut's wrappers change all three
mutation_kit The mutation kit's own tests. Weekly only
pypsa_coverage Skipped unless --pypsa-coverage is given
pypsa_weightings The coverage notebooks that CI does run
python_only, http_only, own_server Feature tags in the four-layer suite: skip under the other driver, or start a fresh server
slow Spawns and kills a subprocess. Informational

There is no PostgreSQL marker. PostgreSQL is a fixture parameter in the library suites and the --versioned-warehouse=postgresql option in the acceptance suites.

Waits

A test in backend/tests/ that waits on a solve, an import or a child process uses wait_until from backend/tests/support/waits.py, never a deadline of its own. Its 180-second limit only catches a hang, so do not lower it. Never prove that something did not happen by waiting it out.

In a journey, wait on what the user sees, never on a timeout.

The shared step namespace

Every module in backend/tests/steps/ is star-imported into backend/tests/test_features.py. A duplicate fixture name or step wording silently overwrites another. Give state fixtures feature-specific names, define shared wording once, and add the star-import for a new steps module.

Expected failures

A scenario that fails on PostgreSQL until a later part of that warehouse is built is a line in backend/tests/postgresql_expected_failures.txt, under its reason. The list is strict: remove the line when the scenario passes. A line that names no collected test fails the run.

Other rules

  • Paths. Reach a file outside the test's own folder through tz_ps_testing.paths (BACKEND, REPOSITORY), never by counting parents of __file__. mutmut runs the suite from a copy one folder deeper.
  • Shared fixtures. A fixture more than one member needs goes in backend/libs/tz_ps_testing, never in another member's conftest.py.
  • Suite settings. A wrong option, environment variable or list file raises pytest.UsageError, so the run stops before any test.
  • OpenTelemetry. Never reset a global provider in the test process. Use backend/tests/support/telemetry_child.py.
  • Log records. Never assert an exact count of exported log records. Find the record by its body.
  • Faker values. Never assert on a name or total from a generated faker body. They are random.
  • Grid tests. Keep jsdom grid fixtures to ten rows or fewer.
  • Staging. Stage a new file before make lint. It checks tracked files only.

Known gaps and debt

  • Two acceptance styles. Most scenarios are still in the old suite (backend/tests/features/), which runs in-process and names HTTP detail. backend/tests/component/, which the design names, does not exist yet.
  • Skips in contract suites. backend/libs/tz_ps_datawarehouse/tests/ holds 14 pytest.skip("this backend ...") calls. Eight skip a guarantee PostgreSQL does not keep (run values, rename), which the rule says to assert. The rest have a premise that needs a particular backend.
  • Fixed sleeps. backend/tests/steps/run_cancellations.py and steps/api_lifecycle.py still sleep a fixed time, against the waits rule. The rule itself covers backend/tests/ only, not libs/*/tests.
  • Mutation testing gates nothing and no run has finished whole. It publishes partial results. See Testing review.
  • frontend-next journeys. They share one backend and warehouse and have no visual baselines (frontend-next/playwright.config.ts).

Clone this wiki locally