# Test system

Runtime dependencies decide the level; product domains follow module names in `openprogram/`. When a test fits several levels, the strongest dependency wins. Each production defect gets one regression test through the lowest public boundary.

## Levels

| Level | May use | May not use |
| --- | --- | --- |
| `contracts` | AST, tracked files, manifests, registries, schemas | External services; source text in place of behaviour |
| `unit` | Memory objects, pure functions, local fakes, one module's temporary files, controlled cleanable threads inside production modules | TestClient, sockets, subprocesses, threads or pools created by tests, fixed sleeps |
| `component` | `tmp_path`, temporary SQLite, TestClient, fake providers, controlled threads | External networks, real credentials |
| `integration` | Loopback HTTP and WS, real subprocesses, several production modules | External services |
| `e2e` | Public CLI, real worker, built Web, browser | The developer's real HOME, existing build outputs |
| `live` | Real providers, channels, remote services | Ordinary PR checks; runs manually |

```
tests/
  contracts/{agent,core,execution,providers,repository,security}/
  unit/<product-domain>/
  component/<product-domain>/
  integration/<product-domain>/
  e2e/{agent,config,context,web}/
  live/{app,providers}/
  support/
  conftest.py
```

At most level and product-domain depth; no tracked test directly at a level root. Markers describe capabilities only: `slow`, `browser`, `sandbox`, `live`, `macos`. Strict markers, strict config, strict xfail; `-m 'not live and not browser'` by default; one test over 120 s fails.

## Isolation

| Scope | Rule |
| --- | --- |
| Repository contracts | Read only Git-tracked files, so clean checkouts and ones with ignored or nested repositories give identical results. Callers supply roots to generic scanners |
| Top-level `conftest.py` | Keeps only what prevents access to real user state; domain fixtures stay local. Temporary HOME has deterministic cleanup |
| Every test process | Each xdist worker included, clears inherited `GIT_DIR`-style variables and installs an audit hook (`tests/support/host_guard.py`). It refuses a git command that would change the checkout the suite runs from, any write inside its `.git` or the real `~/.openprogram*`, and a Python child started with HOME unset or set to the real home |
| A test file copied to a scratch folder, or run with `--noconftest` | Keeps the real HOME, so the path layer refuses by itself: while `PYTEST_CURRENT_TEST` is set, `get_state_dir()` raises when its folder sits in the account's own home, read from the account record and not from `HOME` |
| State paths and the Worker's endpoint files | Come through that function, so such a test can neither register a project or conversation in `~/.openprogram*` nor find the stable or development instance. Child processes inherit the variable; `OPENPROGRAM_TEST_REAL_HOME=1` allows the real folder |
| A refused test | Fails by name; a session-end check of `.git/config` and of worktrees registered from the run's HOME covers child processes |
| Product code | Never falls back to the process's working directory for a repository: a worktree is made only from a path the call passes, the turn's worktree, the conversation's project folder or the configured default folder |
| Concurrent results | Event, Condition or deadline-based waits |
| Threads | Tests do not replace global thread classes or create real threads or pools. Background resources in production modules are joined or closed at teardown |

**Unit guards**

- Structural contracts detect direct and aliased resource imports, direct sleep imports and thread-class replacement.
- Autouse runtime guards intercept thread creation, pool construction and fixed waits in test code.
- Only module-qualified `asyncio.sleep(0)`, positional or keyword, is allowed as a scheduling yield.
- Merge-turn tests own their temporary SessionStore. The fixture registers close right after construction, so every outcome drains index writes and joins timers before the guard runs.
- History-page objects use the local name `historyWindow`, keeping source checks for browser `window` unambiguous.

## Tools

| Tool | Used for | Limit |
| --- | --- | --- |
| [pytest](https://docs.pytest.org/en/stable/explanation/goodpractices.html) | All Python levels | No JavaScript, no fixture process isolation |
| [pytest-xdist](https://pytest-xdist.readthedocs.io/) | Fixed `-n 4`, three consecutive runs by hand after infrastructure changes | Cannot repair shared state. `-n auto` is only for the affected-tests selection, never a stability or release run. |
| [node:test](https://nodejs.org/api/test.html) | Pure Web TypeScript and JavaScript, `apps/web/tests/*.test.mjs` | No DOM |
| [Vitest](https://vitest.dev/guide/) | CLI only | Not installed again for Web |
| [Playwright](https://playwright.dev/docs/best-practices) | `tests/e2e/web`, built pages, public behaviour; the Python browser extra and managed Chromium | Does not replace lower levels |
| [GitHub Actions](https://docs.github.com/en/actions/using-jobs/using-a-matrix-for-your-jobs) | Jobs by level, using the local commands | Defines no test semantics |

Rejected: tox, nox, arbitrary global coverage thresholds. Web source checks in `apps/web/scripts/check-*.mjs` stay only when source structure itself is contractual.

## Full run

Routine changes run `scripts/testing/affected_tests.py` only. The full suite is the jobs below, in the `CI` workflow, started by hand before a release.

| Job | Runs |
| --- | --- |
| `quality` | Ruff, release shell syntax, contracts, docs |
| `unit` | Python 3.11, 3.12, 3.13, no fail-fast |
| `component`, `integration` | Python 3.12 |
| `e2e`, `browser` | Non-browser e2e; built Web in a browser |
| `coverage` | Unit branch coverage, XML uploaded first, then a floor of 40 at six-digit precision. The floor is never above the measured baseline; raising it needs meaningful tests. |
| `web`, `cli`, `desktop` | Package scripts: Web check and build; CLI typecheck, Vitest, build; desktop `npm run check` (VM and fake Electron) |
| `macos-desktop-install`, `macos-native-verification` | `-m macos` distribution tests; self-update native processes |
| `windows-core`, `windows-desktop` | Windows regressions and desktop |

Python commands use `uv run --locked`. Commands: [Full suite](https://github.com/Fzkuji/OpenProgram/blob/main/.github/CONTRIBUTING.md#full-suite).

## Acceptance

- No unhandled-thread warnings (they are errors); three consecutive fixed-worker runs with no worker crash.
- Required Python suites have zero failures; known defects cannot stay in a completed state.
- Component behaviour without frontend artifacts and e2e behaviour with built CSP are verified separately.
- Test-count, skip and xfail changes are recorded across migrations.
- npm risks are audited per workspace with compatible upgrades only, never `npm audit fix --force`.
- Top-level contracts stop root development scripts, undeclared directories and deleted source paths returning to guides.

**Changing the test system**

One batch at a time: reproduce through a public or shared boundary, fix the minimum shared cause, run affected tests, pass independent specification and quality review, commit. Do not implement a Python control-flow interpreter or split tests by line count.

## Implementation status

Implemented: level-first directories, unit guards, coverage floor, jobs above.
