From df7fceb7b4f368e53f3376747d1900d59e9d9570 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 09:01:51 +0000 Subject: [PATCH 1/4] build(format): configure ruff for formatting and import order, checked in CI and pre-commit (#324) ruff formats (black's style, 120 columns, the flake8 line length) and orders imports, over .py files only. flake8 stays the lint. scripts/lint.sh, which the free-tier job runs, now also checks formatting and import order; `make format` rewrites. pre-commit gains the ruff-check and ruff-format hooks, at the version requirements-dev.lock installs. Made ready for the formatting commit that follows, so that commit changes layout only: - flake8 ignores E203 (whitespace before ':'), in .flake8 and scripts/lint.sh alike. It is incompatible with black-style slices such as x[a + 1 :], as flake8's own documentation says. - Two tests no longer depend on where a line breaks: an f-string's dict comprehension moved into a variable, and a lambda carrying '# noqa: E731' became a def. The formatter would have split the noqa onto another line. csv_loader/ is excluded until #431-#435 merge, so those PRs do not all conflict. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011T6WqmGuQidunwiFfwKeBs --- .flake8 | 4 +- .pre-commit-config.yaml | 14 ++- Makefile | 7 +- README.md | 18 ++- alembic/versions/0006_append_only_audit.py | 5 +- e2e/conftest.py | 2 + pyproject.toml | 26 +++++ requirements-a11y.lock | 20 ++++ requirements-dev.lock | 22 ++++ requirements-dev.txt | 3 + scripts/lint.sh | 14 ++- tests/system/test_issue_05_import_summary.py | 3 +- tests/system/test_reports_and_policy.py | 5 +- tests/unit/test_streamlit_api_client.py | 2 + tests/unit/test_streamlit_exports.py | 2 + tests/unit/test_streamlit_files.py | 2 + tests/unit/test_streamlit_history.py | 2 + tests/unit/test_streamlit_outcomes.py | 2 + tests/unit/test_streamlit_upload.py | 2 + tests/unit/test_streamlit_upload_model.py | 2 + tests/unit/test_tool_config.py | 109 ++++++++++++++++--- 21 files changed, 240 insertions(+), 26 deletions(-) diff --git a/.flake8 b/.flake8 index acf39e3..33b8113 100644 --- a/.flake8 +++ b/.flake8 @@ -1,6 +1,8 @@ # flake8 reads this file; it does not read pyproject.toml (#324). Editors and the pre-commit hook pick it up. # scripts/lint.sh, which CI runs, passes the same options on its command line, and # tests/unit/test_tool_config.py fails if the two disagree. +# E203 (whitespace before ":") is off because the formatter (ruff, #324) writes slices as `x[a + 1 :]`, as black does; +# flake8's documentation lists E203 as incompatible with that style. [flake8] max-line-length = 120 -extend-ignore = E501,E221,E272 +extend-ignore = E501,E221,E272,E203 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0e166a0..aa22313 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,15 +4,25 @@ # pre-commit install (Windows PowerShell too: pre-commit runs these hooks itself) # pre-commit run --all-files (optional: check the whole tree now) # +# ruff import order (fixed in place) and formatting, as pyproject.toml [tool.ruff] configures them; a +# commit the hook changed stops, so you can look at the change and stage it # flake8 the lint options in .flake8, which match scripts/lint.sh (the CI lint) # bandit as scripts/lint.sh runs it: medium severity and up, not over test code (tests/, e2e/) # gitleaks the secret scan, with the repository's .gitleaks.toml, over the staged changes (#326) # mypy the type check configured in pyproject.toml (#323) # gap-registers tests/unit/test_gap_registers_agree.py, when a gap register or the VCRM changes # -# No formatter yet: adopting one means reformatting the codebase, which #324 wants as a separate one-off commit. -# Versions: flake8 and bandit are the minimums requirements-dev.txt asks for; gitleaks is the one security-scan.yml runs. +# Versions: ruff, flake8 and bandit are the minimums requirements-dev.txt asks for; gitleaks is the one +# security-scan.yml runs. repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.17.6 + hooks: + - id: ruff-check + args: ["--fix"] + - id: ruff-format + types_or: [python] # not Markdown: see include in pyproject.toml [tool.ruff] + - repo: https://github.com/PyCQA/flake8 rev: 7.3.0 hooks: diff --git a/Makefile b/Makefile index 9479555..72d14d3 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ .PHONY: test-free test-gate test-evals test-e2e test-all coverage \ test-unit test-system test-egress-blocked check-bundle security-evidence test-sit test-performance test-accessibility test-uat \ - lint lint-diff typecheck health \ + lint lint-diff format typecheck health \ eval-list eval-compare eval-summary select-tests \ csv-load csv-list csv-demo @@ -114,6 +114,11 @@ lint: lint-diff: bash scripts/lint_diff.sh +# Format the code and order imports (#324), configured in pyproject.toml [tool.ruff]. `make lint` only checks. +format: + python3 -m ruff check --fix --quiet . + python3 -m ruff format --quiet . + # Static type check (#323): api/ and streamlit_app/, configured in pyproject.toml [tool.mypy]. The free-tier CI job # runs it after the lint, and the pre-commit hook runs the same command. typecheck: diff --git a/README.md b/README.md index b03e4db..c9b8ae1 100644 --- a/README.md +++ b/README.md @@ -304,7 +304,8 @@ python evals\runner.py --tiers p,i,s,e # 27 scenarios: Tier P 23, I 1, S 1, E | `quality-gate.yml` — `integration-postgres` | ubuntu | the check named **integration (postgres service)**: passes only if the shards, the egress job and the coverage gate all passed (or were all skipped for a documentation-only change) | | `python-validator-tests.yml` | windows | database-free markers | -The `free-tier` job also runs the lint (`make lint`) and the type check (`make typecheck`). +The `free-tier` job also runs the lint (`make lint`, which includes the format and import-order check) and the type +check (`make typecheck`). ### Local checks (pre-commit) @@ -319,13 +320,26 @@ pre-commit run --all-files # optional: check the whole tree now | Hook | Checks | Configured in | |---|---|---| +| ruff-check | import order, fixed in place | `pyproject.toml` `[tool.ruff]` | +| ruff-format | formatting (black's style, 120 columns), fixed in place | `pyproject.toml` `[tool.ruff]` | | flake8 | the CI lint options | `.flake8` (kept equal to `scripts/lint.sh` by a test) | | bandit | security lint, medium severity and up, not over `tests/` or `e2e/` | `.pre-commit-config.yaml` | | gitleaks | secrets in the staged changes | `.gitleaks.toml` | | mypy | static types in `api/` and `streamlit_app/` (#323) | `pyproject.toml` `[tool.mypy]` | | gap-registers | the gap registers in `docs/` agree with `docs/VCRM.md` | `tests/unit/test_gap_registers_agree.py` | -Run any of them alone with `make typecheck`, `make lint` or `pre-commit run --all-files`. +Run any of them alone with `make typecheck`, `make lint` or `pre-commit run --all-files`. `make format` +formats the whole tree and orders its imports. When a ruff hook changes a file the commit stops: look at the change, +`git add` it and commit again. + +The tree was formatted in one commit, listed in `.git-blame-ignore-revs`. GitHub's blame view skips it already; for +`git blame` on your machine, run once per clone: + +```bash +git config blame.ignoreRevsFile .git-blame-ignore-revs +``` + +`csv_loader/` is not formatted yet (`pyproject.toml` explains why); it is checked once it is. `./preflight.sh` (or `preflight.ps1`) warns if the hooks are not installed. --- diff --git a/alembic/versions/0006_append_only_audit.py b/alembic/versions/0006_append_only_audit.py index 1c5af86..712fe69 100644 --- a/alembic/versions/0006_append_only_audit.py +++ b/alembic/versions/0006_append_only_audit.py @@ -68,7 +68,7 @@ def upgrade() -> None: 'before_value', r.before_value, 'after_value', r.after_value)::text, 'UTF8')), 'hex') $$""") # Chain the rows that already exist, oldest first. - op.execute(f"""DO $$ + chain = f"""DO $$ DECLARE r RECORD; prev TEXT := NULL; BEGIN FOR r IN SELECT * FROM {t} ORDER BY id LOOP @@ -77,7 +77,8 @@ def upgrade() -> None: SELECT {s}.audit_row_hash(prev, a) INTO prev FROM {t} a WHERE a.id = r.id; UPDATE {t} SET row_hash = prev WHERE id = r.id; END LOOP; - END $$""".replace("TG_SCHEMA_PLACEHOLDER", _literal(settings.UPLOADS_SCHEMA))) # nosec B608 # {s}, {t} are quoted identifiers; the value is escaped by _literal + END $$""" # nosec B608 # {s}, {t} are quoted identifiers; the value is escaped by _literal + op.execute(chain.replace("TG_SCHEMA_PLACEHOLDER", _literal(settings.UPLOADS_SCHEMA))) op.execute(f""" CREATE FUNCTION {s}.audit_chain() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN diff --git a/e2e/conftest.py b/e2e/conftest.py index 5210cd5..6af82e6 100644 --- a/e2e/conftest.py +++ b/e2e/conftest.py @@ -31,6 +31,8 @@ from api.db import Conn # noqa: E402 from scripts import pg_login # noqa: E402 (its server_available asks whether PostgreSQL is there) +# Keeps preflight, and the imports after it, in the order they were written. +# isort: split import preflight # noqa: E402 from api.services import accounts # noqa: E402 from api.tenancy import drop_tenant_role, migrate_tenant, schema_for # noqa: E402 diff --git a/pyproject.toml b/pyproject.toml index 2fca180..02f5939 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,6 +6,7 @@ # on its command line; tests/unit/test_tool_config.py fails if the two disagree. # pytest pytest.ini (it takes precedence over this file, and moving it would churn every test job) # coverage .coveragerc (tests/unit/test_ci_quality_gate.py keeps its scope in step with the Makefile and CI) +# ruff formats the code and orders imports (below); flake8 stays the lint, so the CI lint did not change. [project] name = "postgre-data-migration-app" @@ -51,3 +52,28 @@ warn_return_any = true [[tool.mypy.overrides]] module = ["pandas", "pandas.*", "openpyxl", "openpyxl.*"] ignore_missing_imports = true + +# ── Formatting and import order (#324) ─────────────────────────────────────────────────────────────────────────── +# `make format` rewrites; scripts/lint.sh (CI's free-tier job) and the pre-commit hooks only check. ruff is used here +# for those two jobs alone: flake8 (.flake8) is still the lint. The one-off commit that formatted the tree is listed +# in .git-blame-ignore-revs, so `git blame` skips it. +[tool.ruff] +line-length = 120 # the same as flake8's max-line-length (.flake8); a test keeps the two equal +target-version = "py312" +# Pages import their siblings as top-level modules (`import api_client`), and evals/runner.py imports gap_report the +# same way; listing the folders here sorts those imports as first-party, as they are. +src = [".", "streamlit_app", "evals"] +# Python files only. ruff would also format the Python examples inside Markdown, and the docs' examples are +# written for reading, not run. +include = ["*.py"] +# Checked even when a file is passed by name, as scripts/lint.sh and pre-commit do. +force-exclude = true +# csv_loader/ is not formatted yet: five open PRs (#431-#435) change it, and reformatting under them would conflict +# every one. It is formatted in a commit of its own once they have merged; remove this line then. +extend-exclude = ["csv_loader"] + +[tool.ruff.lint] +select = ["I"] # import order only (isort's rules); everything else is flake8's job + +[tool.ruff.format] +# black's style (ruff's default), at the line length above. diff --git a/requirements-a11y.lock b/requirements-a11y.lock index 50308a5..7136d15 100644 --- a/requirements-a11y.lock +++ b/requirements-a11y.lock @@ -2041,6 +2041,26 @@ rpds-py==2026.9.1 \ # via # jsonschema # referencing +ruff==0.17.6 \ + --hash=sha256:0692088e6b33455572fb18465e891b443f196e98dc1986825685c77ff6f4c5ac \ + --hash=sha256:084d9c8f5ec718e7eba007dba339e7cb4f7571d2f267558ae080bf428fb6a69b \ + --hash=sha256:1939b3d701c7b6981b7cf93473de5bf88b129b9ba84efaed5154cc517c44634d \ + --hash=sha256:1a0bea6aa1216e0ec4cd35d3dbccec0d772a7c2aad28ec9c6e82571dff2c20b0 \ + --hash=sha256:2b04276561331300325040bdca21460770029ec574d4c479099e39e8ad1ed43c \ + --hash=sha256:3db61f5015600543a581b07fa7f6f64afa0eeedefe16034cadd88c4074087582 \ + --hash=sha256:435241c61af5909a022f76219d3d1bf24730dc1bf0acabb5ddf4b569ab3cbb30 \ + --hash=sha256:6a12c50a33936dc00db2be21ba25fb168a8b95c55eda2a3ac85005af69885e4b \ + --hash=sha256:9cd2fd9923e9806b8b6b67a3469e2258e84bd4d21e45d5a1a690afdfb9c8e57d \ + --hash=sha256:9d44ef2140402043fd6f689ef541858b80883a8b0a02e38539ef0614ebe57d0c \ + --hash=sha256:9fbddc08577592e283c265d865e0182de6e33db185494db7b06290d989d888e5 \ + --hash=sha256:aa3b08254a732acba246891089a152c47c5733dc36b8ecb76ce8602f8326e5e4 \ + --hash=sha256:b5aba93b3db4b70c5697e4fee6e0d5b9c8452a9a3a03679611cadc25915a2173 \ + --hash=sha256:c2f4af6670b7a0501904e881bb3f1f24bd0d964dec1eedbd85f0eb73786e1128 \ + --hash=sha256:d006bbb2945edb17b0ce6a0c1b5f5a8d81ba11dbac294a0a925effa22ce34feb \ + --hash=sha256:d8b14e1473dc86ab9069cf7a2ba5041dc012f59110201844ed04cfddf07055a0 \ + --hash=sha256:fb589e032806bb942e4fb526f30b80a1a64112147ed9f1d38cc3de2e255b6f45 \ + --hash=sha256:fd661702202a89c00a4c9d0339008805fa5876bfa1c57e165495c2e62230dfbf + # via -r requirements-dev.txt sqlalchemy==2.1.9 \ --hash=sha256:0970970fe6bc64e1718d85acf45a32728e5d33817de4c89a8bf6d5b3a3fa4f4d \ --hash=sha256:0b44f50bd32fac29e12fce362f37a8b7e8f1e4d0dea02dcc837f00b5238ef5fc \ diff --git a/requirements-dev.lock b/requirements-dev.lock index 4c3d142..d7b351f 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -2069,6 +2069,28 @@ rpds-py==2026.9.1 \ # -c requirements-a11y.lock (versions only) # jsonschema # referencing +ruff==0.17.6 \ + --hash=sha256:0692088e6b33455572fb18465e891b443f196e98dc1986825685c77ff6f4c5ac \ + --hash=sha256:084d9c8f5ec718e7eba007dba339e7cb4f7571d2f267558ae080bf428fb6a69b \ + --hash=sha256:1939b3d701c7b6981b7cf93473de5bf88b129b9ba84efaed5154cc517c44634d \ + --hash=sha256:1a0bea6aa1216e0ec4cd35d3dbccec0d772a7c2aad28ec9c6e82571dff2c20b0 \ + --hash=sha256:2b04276561331300325040bdca21460770029ec574d4c479099e39e8ad1ed43c \ + --hash=sha256:3db61f5015600543a581b07fa7f6f64afa0eeedefe16034cadd88c4074087582 \ + --hash=sha256:435241c61af5909a022f76219d3d1bf24730dc1bf0acabb5ddf4b569ab3cbb30 \ + --hash=sha256:6a12c50a33936dc00db2be21ba25fb168a8b95c55eda2a3ac85005af69885e4b \ + --hash=sha256:9cd2fd9923e9806b8b6b67a3469e2258e84bd4d21e45d5a1a690afdfb9c8e57d \ + --hash=sha256:9d44ef2140402043fd6f689ef541858b80883a8b0a02e38539ef0614ebe57d0c \ + --hash=sha256:9fbddc08577592e283c265d865e0182de6e33db185494db7b06290d989d888e5 \ + --hash=sha256:aa3b08254a732acba246891089a152c47c5733dc36b8ecb76ce8602f8326e5e4 \ + --hash=sha256:b5aba93b3db4b70c5697e4fee6e0d5b9c8452a9a3a03679611cadc25915a2173 \ + --hash=sha256:c2f4af6670b7a0501904e881bb3f1f24bd0d964dec1eedbd85f0eb73786e1128 \ + --hash=sha256:d006bbb2945edb17b0ce6a0c1b5f5a8d81ba11dbac294a0a925effa22ce34feb \ + --hash=sha256:d8b14e1473dc86ab9069cf7a2ba5041dc012f59110201844ed04cfddf07055a0 \ + --hash=sha256:fb589e032806bb942e4fb526f30b80a1a64112147ed9f1d38cc3de2e255b6f45 \ + --hash=sha256:fd661702202a89c00a4c9d0339008805fa5876bfa1c57e165495c2e62230dfbf + # via + # -c requirements-a11y.lock (versions only) + # -r requirements-dev.txt sqlalchemy==2.1.9 \ --hash=sha256:0970970fe6bc64e1718d85acf45a32728e5d33817de4c89a8bf6d5b3a3fa4f4d \ --hash=sha256:0b44f50bd32fac29e12fce362f37a8b7e8f1e4d0dea02dcc837f00b5238ef5fc \ diff --git a/requirements-dev.txt b/requirements-dev.txt index 64cad33..3d50685 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -24,3 +24,6 @@ types-psycopg2>=2.9.21 # #324: local hooks before each commit (.pre-commit-config.yaml). Run `pre-commit install` once per clone. pre-commit>=4.7.0 + +# #324: code formatter and import order (pyproject.toml [tool.ruff]); flake8 above stays the lint. +ruff>=0.17.6 diff --git a/scripts/lint.sh b/scripts/lint.sh index 07c6141..fdac236 100644 --- a/scripts/lint.sh +++ b/scripts/lint.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# scripts/lint.sh — flake8 + bandit over every tracked Python file. +# scripts/lint.sh — flake8 + bandit + the ruff format and import-order checks over every tracked Python file. # Mirrors: bun run slop (full slop-scan report in gstack) # # Scope is discovered from git, not listed by hand (#322). A hand-kept list had fallen behind twice: it named 14 of @@ -9,6 +9,8 @@ # flake8 every tracked .py file # bandit every tracked .py file except test code (a tests/ folder at any depth, and e2e/), where its findings are # about fixtures and asserts +# ruff `ruff format --check` and the import order (#324), over the same files as flake8 less the paths +# pyproject.toml [tool.ruff] excludes. It only checks; `make format` rewrites. # # LINT_EXCLUDE below skips exact paths from BOTH tools. Give each entry a reason. It is empty today, and # tests/unit/test_lint_scope.py fails if a tracked file is outside the scope and not named here. @@ -64,7 +66,7 @@ fi echo -e "\n${YELLOW}=== flake8 (style + logic): ${#LINT_FILES[@]} files ===${NC}" if python3 -m flake8 "${LINT_FILES[@]}" \ --max-line-length=120 \ - --extend-ignore=E501,E221,E272; then + --extend-ignore=E501,E221,E272,E203; then echo -e "${GREEN}✓ flake8 clean${NC}" else echo -e "${RED}✗ flake8 found issues — fix before merging${NC}" @@ -81,4 +83,12 @@ else exit 1 fi +echo -e "\n${YELLOW}=== ruff (format + import order, #324) ===${NC}" +if python3 -m ruff format --check --quiet "${LINT_FILES[@]}" && python3 -m ruff check --quiet "${LINT_FILES[@]}"; then + echo -e "${GREEN}✓ formatted, imports in order${NC}" +else + echo -e "${RED}✗ not formatted or imports out of order: run 'make format' and commit the result${NC}" + exit 1 +fi + echo -e "\n${GREEN}All lint checks passed.${NC}\n" diff --git a/tests/system/test_issue_05_import_summary.py b/tests/system/test_issue_05_import_summary.py index a0ecc5b..1e52a4c 100644 --- a/tests/system/test_issue_05_import_summary.py +++ b/tests/system/test_issue_05_import_summary.py @@ -155,10 +155,11 @@ def test_failed_rows_are_reported_with_detail(self): def test_counts_reconcile_for_a_clean_file(self): body = self._upload(f"col_a\n{self.tag}-1\n{self.tag}-2\n{self.tag}-3\n") + summary = {k: body[k] for k in SUMMARY_FIELDS} self.assertEqual( body["totalRows"], body["insertedRows"] + body["duplicateRowsSkipped"] + body["failedRows"], - f"counts do not reconcile: {({k: body[k] for k in SUMMARY_FIELDS})}", + f"counts do not reconcile: {summary}", ) def test_counts_reconcile_for_a_mixed_file(self): diff --git a/tests/system/test_reports_and_policy.py b/tests/system/test_reports_and_policy.py index f2d148e..db02da9 100644 --- a/tests/system/test_reports_and_policy.py +++ b/tests/system/test_reports_and_policy.py @@ -219,8 +219,9 @@ def test_every_outcome_can_be_filtered_and_failures_say_why(self): def test_filters_combine(self): self.upload("up", "a.csv", f"k\n{self.tag}a\n") self.upload("ad", "b.csv", f"k\n{self.tag}b\n") - listing = lambda **p: self.client.get("/api/csv/uploads", headers=self.auth["au"], # noqa: E731 - params={"file": self.tag, **p}).json() + def listing(**p): + return self.client.get("/api/csv/uploads", headers=self.auth["au"], params={"file": self.tag, **p}).json() + self.assertEqual(len(listing()), 2) self.assertEqual([u["uploader"] for u in listing(uploader=f"{self.slug}_ad")], [f"{self.slug}_ad"]) self.assertEqual(len(listing(status="imported")), 2) diff --git a/tests/unit/test_streamlit_api_client.py b/tests/unit/test_streamlit_api_client.py index 32361d6..43c03de 100644 --- a/tests/unit/test_streamlit_api_client.py +++ b/tests/unit/test_streamlit_api_client.py @@ -8,6 +8,8 @@ import requests from tests.unit import streamlit_harness # noqa: F401 (puts streamlit_app on the path) +# The imports below need the path the import above sets up, so the import sort must not move them up. +# isort: split import api_client # noqa: E402 diff --git a/tests/unit/test_streamlit_exports.py b/tests/unit/test_streamlit_exports.py index 6ee4a6b..6d655b0 100644 --- a/tests/unit/test_streamlit_exports.py +++ b/tests/unit/test_streamlit_exports.py @@ -12,6 +12,8 @@ from openpyxl import load_workbook from tests.unit import streamlit_harness # noqa: F401 (puts streamlit_app on the path) +# The imports below need the path the import above sets up, so the import sort must not move them up. +# isort: split import exports as x # noqa: E402 diff --git a/tests/unit/test_streamlit_files.py b/tests/unit/test_streamlit_files.py index 3009417..66a4584 100644 --- a/tests/unit/test_streamlit_files.py +++ b/tests/unit/test_streamlit_files.py @@ -12,6 +12,8 @@ import streamlit as st from tests.unit.streamlit_harness import errors, screen, widget +# The imports below need the path the import above sets up, so the import sort must not move them up. +# isort: split import api_client # noqa: E402 import files_model as f # noqa: E402 diff --git a/tests/unit/test_streamlit_history.py b/tests/unit/test_streamlit_history.py index 4b7af43..c942e1c 100644 --- a/tests/unit/test_streamlit_history.py +++ b/tests/unit/test_streamlit_history.py @@ -13,6 +13,8 @@ import streamlit as st from tests.unit.streamlit_harness import errors, screen, widget +# The imports below need the path the import above sets up, so the import sort must not move them up. +# isort: split import api_client # noqa: E402 import history_model as h # noqa: E402 diff --git a/tests/unit/test_streamlit_outcomes.py b/tests/unit/test_streamlit_outcomes.py index 89fff17..dc11eb1 100644 --- a/tests/unit/test_streamlit_outcomes.py +++ b/tests/unit/test_streamlit_outcomes.py @@ -7,6 +7,8 @@ import pytest from tests.unit import streamlit_harness # noqa: F401 (puts streamlit_app on the path) +# The imports below need the path the import above sets up, so the import sort must not move them up. +# isort: split import api_client # noqa: E402 import outcomes as o # noqa: E402 diff --git a/tests/unit/test_streamlit_upload.py b/tests/unit/test_streamlit_upload.py index b26a9e6..ad2ee54 100644 --- a/tests/unit/test_streamlit_upload.py +++ b/tests/unit/test_streamlit_upload.py @@ -14,6 +14,8 @@ from streamlit.testing.v1 import AppTest from tests.unit.streamlit_harness import APP_DIR, ROLES, errors, later, widget +# The imports below need the path the import above sets up, so the import sort must not move them up. +# isort: split import api_client # noqa: E402 import upload_model as u # noqa: E402 diff --git a/tests/unit/test_streamlit_upload_model.py b/tests/unit/test_streamlit_upload_model.py index 2e039ed..dabaaef 100644 --- a/tests/unit/test_streamlit_upload_model.py +++ b/tests/unit/test_streamlit_upload_model.py @@ -11,6 +11,8 @@ import pytest from tests.unit.streamlit_harness import APP_DIR +# The imports below need the path the import above sets up, so the import sort must not move them up. +# isort: split import upload_model as u # noqa: E402 diff --git a/tests/unit/test_tool_config.py b/tests/unit/test_tool_config.py index 65872fa..09e6fef 100644 --- a/tests/unit/test_tool_config.py +++ b/tests/unit/test_tool_config.py @@ -3,7 +3,8 @@ The lint options are written in two places, because flake8 does not read pyproject.toml: .flake8 (editors and the pre-commit hook) and scripts/lint.sh (CI). The secret scan's version is in .pre-commit-config.yaml and in security-scan.yml. The type check is configured in pyproject.toml and run by `make typecheck` from the free-tier job. -These tests fail when one copy changes and the other does not, or when the type check is quietly switched off. +The formatter (ruff) is configured in pyproject.toml, checked by scripts/lint.sh and run by a pre-commit hook. +These tests fail when one copy changes and the other does not, or when a check is quietly switched off. """ from __future__ import annotations @@ -48,7 +49,7 @@ def _hook_ids() -> set[str]: def test_pre_commit_runs_the_checks_324_asks_for(): - assert {"flake8", "bandit", "gitleaks", "mypy", "gap-registers"} <= _hook_ids() + assert {"ruff-check", "ruff-format", "flake8", "bandit", "gitleaks", "mypy", "gap-registers"} <= _hook_ids() def test_pre_commit_gitleaks_is_the_version_ci_runs(): @@ -90,11 +91,24 @@ def test_type_check_is_not_silenced(): # Every flag `mypy --strict` turns on (mypy 2.x), split between the global section and the api/ override. -STRICT_GLOBAL = {"warn_unused_configs", "warn_unused_ignores", "warn_redundant_casts", "strict_equality", - "extra_checks", "check_untyped_defs"} -STRICT_API = {"no_implicit_reexport", "disallow_untyped_decorators", "disallow_untyped_defs", - "disallow_incomplete_defs", "disallow_any_generics", "disallow_untyped_calls", - "disallow_subclassing_any", "warn_return_any"} +STRICT_GLOBAL = { + "warn_unused_configs", + "warn_unused_ignores", + "warn_redundant_casts", + "strict_equality", + "extra_checks", + "check_untyped_defs", +} +STRICT_API = { + "no_implicit_reexport", + "disallow_untyped_decorators", + "disallow_untyped_defs", + "disallow_incomplete_defs", + "disallow_any_generics", + "disallow_untyped_calls", + "disallow_subclassing_any", + "warn_return_any", +} def test_every_package_gets_the_strict_flags_that_need_no_annotations(): @@ -121,9 +135,15 @@ def test_the_loader_result_type_declares_every_key_the_loaders_set(): declared = set(get_type_hints(LoadResult)) used: set[str] = set() - trees = [ast.parse((ROOT / path).read_text(encoding="utf-8")) for path in ( - "api/services/dynamic_loader.py", "api/services/te_loader.py", "api/services/load_common.py", - "api/services/staged_import.py")] + trees = [ + ast.parse((ROOT / path).read_text(encoding="utf-8")) + for path in ( + "api/services/dynamic_loader.py", + "api/services/te_loader.py", + "api/services/load_common.py", + "api/services/staged_import.py", + ) + ] # Only the upload route: the preview route also calls its dict `result`, but that is build_preview's shape. routes = ast.parse((ROOT / "api/routers/csv_routes.py").read_text(encoding="utf-8")) trees += [n for n in ast.walk(routes) if isinstance(n, ast.FunctionDef) and n.name == "upload"] @@ -131,9 +151,13 @@ def test_the_loader_result_type_declares_every_key_the_loaders_set(): for node in ast.walk(tree): if isinstance(node, ast.Call) and getattr(node.func, "id", "") in ("ok_result", "rows_failed"): used |= {k.arg for k in node.keywords if k.arg} - if (isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) - and node.value.id == "result" and isinstance(node.slice, ast.Constant) - and isinstance(node.slice.value, str)): + if ( + isinstance(node, ast.Subscript) + and isinstance(node.value, ast.Name) + and node.value.id == "result" + and isinstance(node.slice, ast.Constant) + and isinstance(node.slice.value, str) + ): used.add(node.slice.value) assert used, "found no result keys; the loaders' structure changed, so update this test" assert used <= declared, f"set but not declared in LoadResult: {sorted(used - declared)}" @@ -146,3 +170,62 @@ def test_ci_runs_the_type_check(): makefile = (ROOT / "Makefile").read_text(encoding="utf-8") target = re.search(r"^typecheck:\n\t(.+)$", makefile, re.M) assert target and target.group(1).strip() == "python3 -m mypy", "`make typecheck` runs mypy from its config" + + +# ── Formatting and import order (#324) ──────────────────────────────────────────────────────────────────────── + + +def _ruff() -> dict: + return tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))["tool"]["ruff"] + + +def test_the_formatter_wraps_at_the_lint_line_length(): + cfg = configparser.ConfigParser() + cfg.read(ROOT / ".flake8") + assert _ruff()["line-length"] == int(cfg["flake8"]["max-line-length"]) + + +def test_ruff_only_orders_imports_and_leaves_the_lint_to_flake8(): + """Two linters with different rules would disagree; flake8 is the one CI's lint options are tested against.""" + assert _ruff()["lint"]["select"] == ["I"] + + +def test_only_python_files_are_formatted(): + """ruff also formats Python code blocks inside Markdown; the docs' examples are not code the formatter owns.""" + assert _ruff()["include"] == ["*.py"] + hook = next(h for r in _pre_commit()["repos"] for h in r["hooks"] if h["id"] == "ruff-format") + assert hook.get("types_or") == ["python"], "the ruff-format hook would format Markdown files" + + +def test_files_named_on_the_command_line_are_still_excluded(): + """scripts/lint.sh and pre-commit pass files by name; without force-exclude ruff would check excluded ones.""" + assert _ruff()["force-exclude"] is True + + +def test_every_excluded_path_exists(): + """An exclusion outliving its folder hides nothing, and the comment telling someone to remove it is then lost.""" + missing = [p for p in _ruff().get("extend-exclude", []) if not (ROOT / p).exists()] + assert not missing, f"pyproject.toml [tool.ruff] extend-exclude names paths that do not exist: {missing}" + + +def test_the_ci_lint_checks_formatting_and_import_order(): + text = (ROOT / "scripts" / "lint.sh").read_text(encoding="utf-8") + assert re.search(r"python3 -m ruff format --check\b", text), "scripts/lint.sh does not run `ruff format --check`" + assert re.search(r"python3 -m ruff check\b", text), "scripts/lint.sh does not run `ruff check` (import order)" + + +def test_pre_commit_ruff_is_the_version_ci_installs(): + rev = next(r["rev"] for r in _pre_commit()["repos"] if r["repo"].endswith("/ruff-pre-commit")) + lock = (ROOT / "requirements-dev.lock").read_text(encoding="utf-8") + locked = re.search(r"^ruff==([\d.]+)", lock, re.M) + assert locked, "requirements-dev.lock has no ruff; CI's lint would not find it" + assert rev == f"v{locked.group(1)}", f"pre-commit runs ruff {rev}, CI installs ruff {locked.group(1)}" + + +def test_blame_ignore_revs_lists_only_full_commit_ids(): + """git and GitHub skip a line they cannot read as a full 40-character id, so a short one ignores nothing.""" + lines = (ROOT / ".git-blame-ignore-revs").read_text(encoding="utf-8").splitlines() + revs = [ln.strip() for ln in lines if ln.strip() and not ln.lstrip().startswith("#")] + assert revs, ".git-blame-ignore-revs lists no commit" + bad = [r for r in revs if not re.fullmatch(r"[0-9a-f]{40}", r)] + assert not bad, f"not full commit ids: {bad}" From 20cd32e8e8a203e9db27091cd74f861c5509e994 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 11:16:58 +0000 Subject: [PATCH 2/4] style: format the tree with ruff and order its imports (#324) Mechanical: `make format` (ruff 0.17.6, pyproject.toml [tool.ruff]) over every tracked .py file except csv_loader/. Nothing else changed. Each file's syntax tree is the same before and after, apart from the order and grouping of its imports. The one exception is a module docstring's indentation in tests/unit/test_config.py, and nothing reads that docstring. Listed in .git-blame-ignore-revs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011T6WqmGuQidunwiFfwKeBs --- alembic/env.py | 3 +- alembic/versions/0001_baseline.py | 1 - alembic/versions/0002_registry_unique.py | 2 +- alembic/versions/0003_import_counts.py | 1 - alembic/versions/0004_control_schema.py | 1 - alembic/versions/0005_login_lockout.py | 1 - alembic/versions/0006_append_only_audit.py | 16 +- alembic/versions/0007_preserved_uploads.py | 13 +- alembic/versions/0008_review.py | 13 +- alembic/versions/0009_type_provenance.py | 13 +- alembic/versions/0010_versioned_datasets.py | 40 +- alembic/versions/0011_approval_and_import.py | 26 +- .../versions/0012_session_idle_and_purge.py | 1 - alembic_te/env.py | 3 +- .../versions/te0002_program_consistency.py | 142 +++-- api/auth.py | 24 +- api/bodylimit.py | 21 +- api/concurrency.py | 6 +- api/db.py | 129 ++-- api/main.py | 17 +- api/oidc.py | 12 +- api/policy.py | 6 +- api/ratelimit.py | 18 +- api/routers/audit_routes.py | 77 ++- api/routers/auth_routes.py | 24 +- api/routers/csv_routes.py | 138 +++-- api/routers/import_routes.py | 31 +- api/routers/policy_routes.py | 8 +- api/routers/review_routes.py | 12 +- api/routers/te_routes.py | 5 +- api/services/accounts.py | 227 ++++--- api/services/audit.py | 53 +- api/services/csv_parse.py | 18 +- api/services/destructive_ops.py | 20 +- api/services/dynamic_loader.py | 265 ++++++--- api/services/load_common.py | 58 +- api/services/originals.py | 100 +++- api/services/results.py | 5 +- api/services/review.py | 205 +++++-- api/services/staged_import.py | 553 +++++++++++++----- api/services/te_loader.py | 131 +++-- api/tenancy.py | 140 +++-- build/csv/validator.py | 43 +- container/smoke_test.py | 33 +- e2e/conftest.py | 106 +++- e2e/preflight.py | 34 +- e2e/streamlit_helpers.py | 3 +- e2e/test_react_ui.py | 3 +- e2e/test_streamlit_history.py | 20 +- e2e/test_streamlit_review.py | 27 +- e2e/test_streamlit_shell.py | 18 +- e2e/test_streamlit_upload.py | 37 +- evals/gap_report.py | 81 ++- evals/runner.py | 497 ++++++++-------- scripts/check_bundle_egress.py | 45 +- scripts/check_coverage_floors.py | 5 +- scripts/check_oidc.py | 101 +++- scripts/ci_changes.py | 20 +- scripts/ci_gate.py | 1 + scripts/ci_shards.py | 18 +- scripts/create_app_role.py | 59 +- scripts/create_tenant_admin.py | 54 +- scripts/eval_compare.py | 35 +- scripts/eval_list.py | 21 +- scripts/eval_summary.py | 24 +- scripts/fix_api_imports.py | 25 +- scripts/fix_inserted_rows_count.py | 29 +- scripts/health_check.py | 33 +- scripts/perf_import.py | 147 +++-- scripts/pg_login.py | 69 ++- scripts/sample_verification_run.py | 219 ++++--- scripts/security_audit.py | 66 ++- scripts/select_tests.py | 49 +- scripts/test_catalogue.py | 66 ++- scripts/test_report.py | 70 ++- streamlit_app/api_client.py | 7 +- streamlit_app/auth.py | 25 +- streamlit_app/exports.py | 72 ++- streamlit_app/files_model.py | 24 +- streamlit_app/history_model.py | 116 +++- streamlit_app/outcomes.py | 37 +- streamlit_app/review_model.py | 22 +- streamlit_app/upload_model.py | 49 +- streamlit_app/views/files.py | 27 +- streamlit_app/views/history.py | 89 ++- streamlit_app/views/review.py | 58 +- streamlit_app/views/upload.py | 125 +++- tests/accessibility/axe_baseline.py | 18 +- tests/accessibility/conftest.py | 110 +++- tests/accessibility/stub_api.py | 179 ++++-- tests/accessibility/test_accessibility.py | 3 + tests/conftest.py | 29 +- tests/egress_guard.py | 18 +- tests/oidc_stub.py | 33 +- tests/performance/test_import_scale.py | 10 +- tests/system/test_accounts.py | 49 +- tests/system/test_api_coverage.py | 157 ++--- tests/system/test_api_integration.py | 142 +++-- tests/system/test_audit_append_only.py | 23 +- tests/system/test_check_oidc.py | 44 +- tests/system/test_concurrent_migrations.py | 33 +- tests/system/test_create_tenant_admin.py | 167 ++++-- tests/system/test_egress_network_blocked.py | 3 +- tests/system/test_failed_uploads.py | 5 +- tests/system/test_header_mapping.py | 29 +- tests/system/test_import_counts.py | 39 +- .../system/test_issue_04_multi_file_upload.py | 32 +- tests/system/test_issue_05_import_summary.py | 29 +- tests/system/test_issue_regressions.py | 81 ++- tests/system/test_loader_responses_golden.py | 51 +- tests/system/test_migrations.py | 256 +++++--- tests/system/test_oidc.py | 13 +- tests/system/test_oidc_https.py | 44 +- tests/system/test_original_bytes.py | 17 +- tests/system/test_password_rehash.py | 11 +- tests/system/test_password_reset.py | 68 ++- tests/system/test_preserved_uploads.py | 33 +- tests/system/test_ragged_rows.py | 30 +- tests/system/test_registry_race.py | 35 +- tests/system/test_reports_and_policy.py | 71 ++- .../system/test_require_type_confirmation.py | 12 +- tests/system/test_review.py | 81 ++- tests/system/test_review_cases.py | 96 ++- tests/system/test_roles.py | 44 +- tests/system/test_runtime_role.py | 124 ++-- tests/system/test_runtime_role_per_env.py | 62 +- tests/system/test_session_idle_and_purge.py | 79 ++- tests/system/test_sessions_required.py | 60 +- tests/system/test_staged_import.py | 174 ++++-- tests/system/test_te_cannot_drop_dataset.py | 18 +- tests/system/test_te_import_all_or_nothing.py | 53 +- tests/system/test_te_loader_integration.py | 77 +-- tests/system/test_te_reupload_registry.py | 44 +- tests/system/test_tenant_isolation.py | 129 ++-- tests/system/test_tenant_te_migrations.py | 221 ++++--- tests/system/test_type_provenance.py | 42 +- tests/system/test_upload_atomic_records.py | 62 +- tests/system/test_versioned_datasets.py | 64 +- .../environments/_contract.py | 29 +- .../environments/test_env_dev.py | 3 + .../environments/test_env_prod.py | 3 + .../environments/test_env_staging.py | 3 + .../environments/test_env_test.py | 3 + .../test_csv_loader_arbitrary_shapes.py | 41 +- tests/system_integration/test_e2e_pipeline.py | 132 +++-- tests/system_integration/test_parity.py | 90 +-- tests/unit/streamlit_harness.py | 10 +- tests/unit/test_a11y_baseline.py | 10 +- tests/unit/test_api_hardening.py | 33 +- tests/unit/test_api_key_not_logged.py | 10 +- tests/unit/test_api_unit.py | 35 +- tests/unit/test_body_limit.py | 44 +- .../test_bootstrap_requires_migrations.py | 1 + tests/unit/test_ci_parallel_jobs.py | 81 ++- tests/unit/test_ci_quality_gate.py | 20 +- tests/unit/test_ci_shards.py | 69 ++- tests/unit/test_cloudshell_setup.py | 55 +- tests/unit/test_concurrent_import_limit.py | 16 +- tests/unit/test_config.py | 101 ++-- tests/unit/test_container_bundle.py | 81 ++- tests/unit/test_container_bundle_sbom.py | 17 +- tests/unit/test_container_image_hardening.py | 21 +- tests/unit/test_csv_utilise.py | 4 +- tests/unit/test_csv_validator.py | 1 + tests/unit/test_db_init_pool.py | 64 +- tests/unit/test_deploy_all_prereqs.py | 57 +- tests/unit/test_docker_image_secrets.py | 13 +- tests/unit/test_e2e_preflight.py | 33 +- tests/unit/test_egress_firewall_script.py | 24 +- tests/unit/test_egress_guard.py | 14 +- tests/unit/test_egress_network_control.py | 58 +- tests/unit/test_evals_runner.py | 11 +- tests/unit/test_evals_tier_e_x.py | 108 ++-- tests/unit/test_gap_registers_agree.py | 43 +- tests/unit/test_image_scan_workflow.py | 5 +- tests/unit/test_infer_type_leading_zeros.py | 43 +- tests/unit/test_infra_private_access.py | 11 +- .../unit/test_issue_322_security_findings.py | 1 + tests/unit/test_lint_scope.py | 13 +- tests/unit/test_load_common.py | 44 +- tests/unit/test_makefile_categories.py | 1 + .../unit/test_offline_streamlit_packaging.py | 37 +- tests/unit/test_oidc_https_jwks.py | 33 +- tests/unit/test_open_issues.py | 5 +- tests/unit/test_password_hash_cost.py | 27 +- tests/unit/test_pg_login.py | 80 ++- tests/unit/test_preflight_ps1.py | 23 +- .../unit/test_preflight_sh_without_timeout.py | 19 +- tests/unit/test_preview_fast_path.py | 15 +- tests/unit/test_prod_db_naming.py | 71 ++- tests/unit/test_prod_health_and_docs.py | 15 +- tests/unit/test_prod_web_apps_terraform.py | 9 +- tests/unit/test_rate_limit_behind_a_proxy.py | 15 +- tests/unit/test_regression.py | 97 +-- tests/unit/test_reproducible_builds.py | 25 +- tests/unit/test_sample_verification_run.py | 29 +- tests/unit/test_security.py | 38 +- tests/unit/test_security_audit.py | 84 ++- tests/unit/test_security_scan_workflow.py | 10 +- tests/unit/test_session_settings_docs.py | 1 + tests/unit/test_snapshot.py | 20 +- tests/unit/test_sovereignty.py | 117 +++- tests/unit/test_sql_no_bom.py | 1 + tests/unit/test_streamlit_api_client.py | 17 +- tests/unit/test_streamlit_exports.py | 116 +++- tests/unit/test_streamlit_files.py | 75 ++- tests/unit/test_streamlit_history.py | 282 +++++++-- tests/unit/test_streamlit_outcomes.py | 135 +++-- tests/unit/test_streamlit_review.py | 194 ++++-- tests/unit/test_streamlit_shell.py | 96 ++- tests/unit/test_streamlit_upload.py | 165 +++++- tests/unit/test_streamlit_upload_model.py | 88 ++- tests/unit/test_test_report_exit_codes.py | 11 +- tests/unit/test_test_report_paths.py | 1 + tests/unit/test_tier_s_threshold.py | 4 +- tests/unit/test_tooling_issues.py | 114 ++-- 216 files changed, 8208 insertions(+), 3909 deletions(-) diff --git a/alembic/env.py b/alembic/env.py index 034e6f8..6464675 100644 --- a/alembic/env.py +++ b/alembic/env.py @@ -8,11 +8,12 @@ import sys from pathlib import Path -from alembic import context from sqlalchemy import create_engine, text from sqlalchemy.engine import URL from sqlalchemy.pool import NullPool +from alembic import context + sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from api.config import settings # noqa: E402 diff --git a/alembic/versions/0001_baseline.py b/alembic/versions/0001_baseline.py index 5380f22..560bee2 100644 --- a/alembic/versions/0001_baseline.py +++ b/alembic/versions/0001_baseline.py @@ -9,7 +9,6 @@ """ from alembic import op - from api.config import settings revision = "0001" diff --git a/alembic/versions/0002_registry_unique.py b/alembic/versions/0002_registry_unique.py index 57d0d47..afc6d77 100644 --- a/alembic/versions/0002_registry_unique.py +++ b/alembic/versions/0002_registry_unique.py @@ -13,9 +13,9 @@ Create Date: 2026-10-26 """ -from alembic import op from sqlalchemy import text +from alembic import op from api.config import settings revision = "0002" diff --git a/alembic/versions/0003_import_counts.py b/alembic/versions/0003_import_counts.py index feda44e..b60254c 100644 --- a/alembic/versions/0003_import_counts.py +++ b/alembic/versions/0003_import_counts.py @@ -11,7 +11,6 @@ """ from alembic import op - from api.config import settings revision = "0003" diff --git a/alembic/versions/0004_control_schema.py b/alembic/versions/0004_control_schema.py index e8f6c17..ed756fc 100644 --- a/alembic/versions/0004_control_schema.py +++ b/alembic/versions/0004_control_schema.py @@ -9,7 +9,6 @@ """ from alembic import context, op - from api.config import settings revision = "0004" diff --git a/alembic/versions/0005_login_lockout.py b/alembic/versions/0005_login_lockout.py index 94385f0..7e4c5ba 100644 --- a/alembic/versions/0005_login_lockout.py +++ b/alembic/versions/0005_login_lockout.py @@ -8,7 +8,6 @@ """ from alembic import context, op - from api.config import settings revision = "0005" diff --git a/alembic/versions/0006_append_only_audit.py b/alembic/versions/0006_append_only_audit.py index 712fe69..201268e 100644 --- a/alembic/versions/0006_append_only_audit.py +++ b/alembic/versions/0006_append_only_audit.py @@ -21,7 +21,6 @@ """ from alembic import op - from api.config import settings revision = "0006" @@ -98,12 +97,15 @@ def upgrade() -> None: END $$""") # The trigger takes the id under its lock; the column default would take a second one. op.execute(f"ALTER TABLE {t} ALTER COLUMN id DROP DEFAULT") - op.execute(f"CREATE TRIGGER audit_chain BEFORE INSERT ON {t} " - f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_chain()") - op.execute(f"CREATE TRIGGER audit_no_change BEFORE UPDATE OR DELETE ON {t} " - f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()") - op.execute(f"CREATE TRIGGER audit_no_truncate BEFORE TRUNCATE ON {t} " - f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()") + op.execute(f"CREATE TRIGGER audit_chain BEFORE INSERT ON {t} FOR EACH ROW EXECUTE FUNCTION {s}.audit_chain()") + op.execute( + f"CREATE TRIGGER audit_no_change BEFORE UPDATE OR DELETE ON {t} " + f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()" + ) + op.execute( + f"CREATE TRIGGER audit_no_truncate BEFORE TRUNCATE ON {t} " + f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()" + ) def downgrade() -> None: diff --git a/alembic/versions/0007_preserved_uploads.py b/alembic/versions/0007_preserved_uploads.py index f0f1fe4..34e9fb7 100644 --- a/alembic/versions/0007_preserved_uploads.py +++ b/alembic/versions/0007_preserved_uploads.py @@ -19,7 +19,6 @@ """ from alembic import op - from api.config import settings revision = "0007" @@ -69,10 +68,14 @@ def upgrade() -> None: USING ERRCODE = 'insufficient_privilege'; END $$""") for t in _TABLES: - op.execute(f"CREATE TRIGGER {t}_no_change BEFORE UPDATE OR DELETE ON {s}.{t} " - f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()") - op.execute(f"CREATE TRIGGER {t}_no_truncate BEFORE TRUNCATE ON {s}.{t} " - f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()") + op.execute( + f"CREATE TRIGGER {t}_no_change BEFORE UPDATE OR DELETE ON {s}.{t} " + f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()" + ) + op.execute( + f"CREATE TRIGGER {t}_no_truncate BEFORE TRUNCATE ON {s}.{t} " + f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()" + ) def downgrade() -> None: diff --git a/alembic/versions/0008_review.py b/alembic/versions/0008_review.py index 115f5dd..98377bc 100644 --- a/alembic/versions/0008_review.py +++ b/alembic/versions/0008_review.py @@ -18,7 +18,6 @@ """ from alembic import op - from api.config import settings revision = "0008" @@ -56,10 +55,14 @@ def upgrade() -> None: edited_at TIMESTAMPTZ NOT NULL DEFAULT now())""") for t in _TABLES: op.execute(f"CREATE INDEX {t}_by_row ON {s}.{t} (upload_id, row_number, id)") - op.execute(f"CREATE TRIGGER {t}_no_change BEFORE UPDATE OR DELETE ON {s}.{t} " - f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()") - op.execute(f"CREATE TRIGGER {t}_no_truncate BEFORE TRUNCATE ON {s}.{t} " - f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()") + op.execute( + f"CREATE TRIGGER {t}_no_change BEFORE UPDATE OR DELETE ON {s}.{t} " + f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()" + ) + op.execute( + f"CREATE TRIGGER {t}_no_truncate BEFORE TRUNCATE ON {s}.{t} " + f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()" + ) def downgrade() -> None: diff --git a/alembic/versions/0009_type_provenance.py b/alembic/versions/0009_type_provenance.py index 75a573e..af53c2a 100644 --- a/alembic/versions/0009_type_provenance.py +++ b/alembic/versions/0009_type_provenance.py @@ -15,7 +15,6 @@ """ from alembic import op - from api.config import settings revision = "0009" @@ -30,11 +29,15 @@ def _schema() -> str: def upgrade() -> None: s = _schema() - op.execute(f"ALTER TABLE {s}.csv_files ADD COLUMN IF NOT EXISTS types_provenance TEXT " - "CHECK (types_provenance IN ('inferred_unconfirmed', 'user_confirmed'))") + op.execute( + f"ALTER TABLE {s}.csv_files ADD COLUMN IF NOT EXISTS types_provenance TEXT " + "CHECK (types_provenance IN ('inferred_unconfirmed', 'user_confirmed'))" + ) # s is the dialect-quoted schema identifier from settings, never request input. - op.execute(f"UPDATE {s}.csv_files SET types_provenance = 'inferred_unconfirmed' " # nosec B608 - "WHERE mode = 'dynamic' AND types_provenance IS NULL") + op.execute( + f"UPDATE {s}.csv_files SET types_provenance = 'inferred_unconfirmed' " # nosec B608 + "WHERE mode = 'dynamic' AND types_provenance IS NULL" + ) def downgrade() -> None: diff --git a/alembic/versions/0010_versioned_datasets.py b/alembic/versions/0010_versioned_datasets.py index e44f679..5fdab48 100644 --- a/alembic/versions/0010_versioned_datasets.py +++ b/alembic/versions/0010_versioned_datasets.py @@ -25,9 +25,9 @@ Create Date: 2026-11-09 """ -from alembic import op from sqlalchemy import text +from alembic import op from api.config import settings revision = "0010" @@ -35,8 +35,10 @@ branch_labels = None depends_on = None -_SLUG = ("COALESCE(NULLIF(trim(both '_' from left(trim(both '_' from regexp_replace(" - "lower(regexp_replace(file_name, '\\.csv$', '', 'i')), '[^a-z0-9]+', '_', 'g')), 40)), ''), 'dataset')") +_SLUG = ( + "COALESCE(NULLIF(trim(both '_' from left(trim(both '_' from regexp_replace(" + "lower(regexp_replace(file_name, '\\.csv$', '', 'i')), '[^a-z0-9]+', '_', 'g')), 40)), ''), 'dataset')" +) def _schema() -> str: @@ -54,8 +56,9 @@ def upgrade() -> None: WHERE f.id = n.id""") # nosec B608 op.execute(f"ALTER TABLE {s}.csv_files ADD CONSTRAINT csv_files_dataset_version_key UNIQUE (dataset, version)") op.execute(f"ALTER TABLE {s}.csv_files DROP CONSTRAINT csv_files_file_name_key") - op.execute(f"CREATE UNIQUE INDEX csv_files_non_dynamic_file_name ON {s}.csv_files (file_name) " - "WHERE mode <> 'dynamic'") + op.execute( + f"CREATE UNIQUE INDEX csv_files_non_dynamic_file_name ON {s}.csv_files (file_name) WHERE mode <> 'dynamic'" + ) op.execute(f"""CREATE TABLE {s}.row_flags ( upload_id BIGINT NOT NULL REFERENCES {s}.uploads (id), row_number INTEGER NOT NULL CHECK (row_number > 0), @@ -64,22 +67,33 @@ def upgrade() -> None: matched_file_name TEXT NOT NULL, matched_version INTEGER NOT NULL, PRIMARY KEY (upload_id, row_number, kind))""") - op.execute(f"CREATE TRIGGER row_flags_no_change BEFORE UPDATE OR DELETE ON {s}.row_flags " - f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()") - op.execute(f"CREATE TRIGGER row_flags_no_truncate BEFORE TRUNCATE ON {s}.row_flags " - f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()") + op.execute( + f"CREATE TRIGGER row_flags_no_change BEFORE UPDATE OR DELETE ON {s}.row_flags " + f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()" + ) + op.execute( + f"CREATE TRIGGER row_flags_no_truncate BEFORE TRUNCATE ON {s}.row_flags " + f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()" + ) def downgrade() -> None: s = _schema() - dupes = op.get_bind().execute(text( - f"SELECT file_name, count(*) FROM {s}.csv_files GROUP BY file_name HAVING count(*) > 1" # nosec B608 - )).fetchall() + dupes = ( + op.get_bind() + .execute( + text( + f"SELECT file_name, count(*) FROM {s}.csv_files GROUP BY file_name HAVING count(*) > 1" # nosec B608 + ) + ) + .fetchall() + ) if dupes: listed = ", ".join(f"{name!r} x{count}" for name, count in dupes[:10]) raise RuntimeError( f"Cannot restore UNIQUE (file_name) on {settings.UPLOADS_SCHEMA}.csv_files: versioned datasets " - f"share a file name ({listed}). Delete the older versions first, then downgrade.") + f"share a file name ({listed}). Delete the older versions first, then downgrade." + ) op.execute(f"DROP TABLE IF EXISTS {s}.row_flags") op.execute(f"DROP INDEX IF EXISTS {s}.csv_files_non_dynamic_file_name") op.execute(f"ALTER TABLE {s}.csv_files ADD CONSTRAINT csv_files_file_name_key UNIQUE (file_name)") diff --git a/alembic/versions/0011_approval_and_import.py b/alembic/versions/0011_approval_and_import.py index 9f4bb1f..c96be37 100644 --- a/alembic/versions/0011_approval_and_import.py +++ b/alembic/versions/0011_approval_and_import.py @@ -24,9 +24,9 @@ Create Date: 2026-11-09 """ -from alembic import context, op from sqlalchemy import text +from alembic import context, op from api.config import settings revision = "0011" @@ -57,8 +57,10 @@ def upgrade() -> None: op.execute(f"ALTER TABLE {_tenants()} ADD COLUMN allow_self_approval BOOLEAN NOT NULL DEFAULT false") op.execute(f"ALTER TABLE {s}.uploads DROP CONSTRAINT uploads_status_check") op.execute(f"ALTER TABLE {s}.uploads ADD CONSTRAINT uploads_status_check CHECK (status IN ({_STATUSES}))") - op.execute(f"ALTER TABLE {s}.uploads ADD COLUMN types_provenance TEXT " - "CHECK (types_provenance IN ('inferred_unconfirmed', 'user_confirmed'))") + op.execute( + f"ALTER TABLE {s}.uploads ADD COLUMN types_provenance TEXT " + "CHECK (types_provenance IN ('inferred_unconfirmed', 'user_confirmed'))" + ) op.execute(f"""CREATE TABLE {s}.submissions ( id BIGSERIAL PRIMARY KEY, upload_id BIGINT NOT NULL REFERENCES {s}.uploads (id), @@ -93,10 +95,14 @@ def upgrade() -> None: for t in ("submissions", "approvals"): op.execute(f"CREATE INDEX {t}_by_upload ON {s}.{t} (upload_id, id)") for t in _TABLES: - op.execute(f"CREATE TRIGGER {t}_no_change BEFORE UPDATE OR DELETE ON {s}.{t} " - f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()") - op.execute(f"CREATE TRIGGER {t}_no_truncate BEFORE TRUNCATE ON {s}.{t} " - f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()") + op.execute( + f"CREATE TRIGGER {t}_no_change BEFORE UPDATE OR DELETE ON {s}.{t} " + f"FOR EACH ROW EXECUTE FUNCTION {s}.audit_reject_change()" + ) + op.execute( + f"CREATE TRIGGER {t}_no_truncate BEFORE TRUNCATE ON {s}.{t} " + f"FOR EACH STATEMENT EXECUTE FUNCTION {s}.audit_reject_change()" + ) def downgrade() -> None: @@ -105,8 +111,10 @@ def downgrade() -> None: # rather than rewrite an insert-only table; nothing has been dropped yet. staged = op.get_bind().execute(text(f"SELECT count(*) FROM {s}.uploads WHERE status = 'staged'")).scalar() # nosec B608 if staged: - raise RuntimeError(f"Cannot downgrade {settings.UPLOADS_SCHEMA}: {staged} upload(s) are staged. " - "Import them or leave the schema at 0011.") + raise RuntimeError( + f"Cannot downgrade {settings.UPLOADS_SCHEMA}: {staged} upload(s) are staged. " + "Import them or leave the schema at 0011." + ) for t in reversed(_TABLES): op.execute(f"DROP TABLE IF EXISTS {s}.{t}") op.execute(f"ALTER TABLE {s}.uploads DROP COLUMN types_provenance") diff --git a/alembic/versions/0012_session_idle_and_purge.py b/alembic/versions/0012_session_idle_and_purge.py index f52ef3f..35abc90 100644 --- a/alembic/versions/0012_session_idle_and_purge.py +++ b/alembic/versions/0012_session_idle_and_purge.py @@ -11,7 +11,6 @@ """ from alembic import context, op - from api.config import settings revision = "0012" diff --git a/alembic_te/env.py b/alembic_te/env.py index fe6fd0c..efcf8fc 100644 --- a/alembic_te/env.py +++ b/alembic_te/env.py @@ -13,11 +13,12 @@ import sys from pathlib import Path -from alembic import context from sqlalchemy import create_engine from sqlalchemy.engine import URL from sqlalchemy.pool import NullPool +from alembic import context + sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from api.config import settings # noqa: E402 diff --git a/alembic_te/versions/te0002_program_consistency.py b/alembic_te/versions/te0002_program_consistency.py index 774352b..23b96ea 100644 --- a/alembic_te/versions/te0002_program_consistency.py +++ b/alembic_te/versions/te0002_program_consistency.py @@ -24,9 +24,10 @@ Create Date: 2026-11-09 """ -from alembic import op from psycopg2 import sql +from alembic import op + revision = "te0002" down_revision = "te0001" branch_labels = None @@ -107,8 +108,12 @@ def _tbl(schema: str, table: str) -> sql.Composable: def _has_constraint(cur, schema: str, table: str, name: str) -> bool: - cur.execute(sql.SQL("SELECT 1 FROM pg_constraint WHERE conrelid = {}::regclass AND conname = %s").format( - sql.Literal(f'"{schema}"."{table}"')), (name,)) + cur.execute( + sql.SQL("SELECT 1 FROM pg_constraint WHERE conrelid = {}::regclass AND conname = %s").format( + sql.Literal(f'"{schema}"."{table}"') + ), + (name,), + ) return cur.fetchone() is not None @@ -118,27 +123,43 @@ def _add_constraint(cur, schema: str, table: str, name: str, definition: sql.Com if isinstance(definition, str) and definition.startswith("UNIQUE"): # A tenant cloned after #177 but before provisioning kept the template's names has this # constraint under a default name. Adopt it; a second copy would be a redundant index. - cur.execute("SELECT conname FROM pg_constraint WHERE conrelid = %s::regclass AND contype = 'u' " - "AND pg_get_constraintdef(oid) = %s", (f'"{schema}"."{table}"', definition)) + cur.execute( + "SELECT conname FROM pg_constraint WHERE conrelid = %s::regclass AND contype = 'u' " + "AND pg_get_constraintdef(oid) = %s", + (f'"{schema}"."{table}"', definition), + ) row = cur.fetchone() if row: - cur.execute(sql.SQL("ALTER TABLE {} RENAME CONSTRAINT {} TO {}").format( - _tbl(schema, table), sql.Identifier(row[0]), sql.Identifier(name))) + cur.execute( + sql.SQL("ALTER TABLE {} RENAME CONSTRAINT {} TO {}").format( + _tbl(schema, table), sql.Identifier(row[0]), sql.Identifier(name) + ) + ) return - cur.execute(sql.SQL("ALTER TABLE {} ADD CONSTRAINT {} {}").format( - _tbl(schema, table), sql.Identifier(name), - definition if isinstance(definition, sql.Composable) else sql.SQL(definition))) + cur.execute( + sql.SQL("ALTER TABLE {} ADD CONSTRAINT {} {}").format( + _tbl(schema, table), + sql.Identifier(name), + definition if isinstance(definition, sql.Composable) else sql.SQL(definition), + ) + ) def _drop_constraint(cur, schema: str, table: str, name: str, if_exists: bool = False) -> None: - cur.execute(sql.SQL("ALTER TABLE {} DROP CONSTRAINT {}{}").format( - _tbl(schema, table), sql.SQL("IF EXISTS " if if_exists else ""), sql.Identifier(name))) + cur.execute( + sql.SQL("ALTER TABLE {} DROP CONSTRAINT {}{}").format( + _tbl(schema, table), sql.SQL("IF EXISTS " if if_exists else ""), sql.Identifier(name) + ) + ) def _toggle_updated_at(cur, schema: str, tables: tuple[str, ...], action: str) -> None: for table in tables: - cur.execute(sql.SQL("SELECT 1 FROM pg_trigger WHERE tgrelid = {}::regclass AND tgname = 'trg_updated_at'") - .format(sql.Literal(f'"{schema}"."{table}"'))) + cur.execute( + sql.SQL("SELECT 1 FROM pg_trigger WHERE tgrelid = {}::regclass AND tgname = 'trg_updated_at'").format( + sql.Literal(f'"{schema}"."{table}"') + ) + ) if cur.fetchone(): statement = sql.SQL("ALTER TABLE {} {} TRIGGER trg_updated_at") cur.execute(statement.format(_tbl(schema, table), sql.SQL(action))) @@ -146,12 +167,25 @@ def _toggle_updated_at(cur, schema: str, tables: tuple[str, ...], action: str) - def upgrade() -> None: schema, cur = _schema(), _cursor() - t = {name: _tbl(schema, name) for name in - ("test_phases", "requirements", "test_cases", "vcrm_entries", "test_events", "test_results", - "defect_reports")} - - cur.execute(sql.SQL("CREATE OR REPLACE FUNCTION {}.te_fill_program_id() RETURNS TRIGGER LANGUAGE plpgsql AS ") - .format(sql.Identifier(schema)) + sql.SQL(_FILL_FUNCTION_BODY)) + t = { + name: _tbl(schema, name) + for name in ( + "test_phases", + "requirements", + "test_cases", + "vcrm_entries", + "test_events", + "test_results", + "defect_reports", + ) + } + + cur.execute( + sql.SQL("CREATE OR REPLACE FUNCTION {}.te_fill_program_id() RETURNS TRIGGER LANGUAGE plpgsql AS ").format( + sql.Identifier(schema) + ) + + sql.SQL(_FILL_FUNCTION_BODY) + ) # 1. program_id columns, nullable until backfilled for table in _PROGRAM_TABLES: @@ -159,17 +193,22 @@ def upgrade() -> None: # 2. backfill from the parent each row already depends on _toggle_updated_at(cur, schema, ("test_cases", "test_events"), "DISABLE") - for child, parent, key in (("test_cases", "test_phases", "phase_id"), - ("test_events", "test_phases", "phase_id"), - ("vcrm_entries", "requirements", "req_id"), - ("test_results", "test_events", "event_id")): - cur.execute(sql.SQL("UPDATE {c} c SET program_id = p.program_id FROM {p} p " - "WHERE c.{k} = p.{k} AND c.program_id IS NULL").format( - c=t[child], p=t[parent], k=sql.Identifier(key))) + for child, parent, key in ( + ("test_cases", "test_phases", "phase_id"), + ("test_events", "test_phases", "phase_id"), + ("vcrm_entries", "requirements", "req_id"), + ("test_results", "test_events", "event_id"), + ): + cur.execute( + sql.SQL( + "UPDATE {c} c SET program_id = p.program_id FROM {p} p WHERE c.{k} = p.{k} AND c.program_id IS NULL" + ).format(c=t[child], p=t[parent], k=sql.Identifier(key)) + ) _toggle_updated_at(cur, schema, ("test_cases", "test_events"), "ENABLE") # 3. refuse to constrain data that already violates BR-07, and say which rows to triage - cur.execute(sql.SQL(""" + cur.execute( + sql.SQL(""" SELECT string_agg(msg, E'\\n') FROM ( SELECT 'vcrm_entries ' || v.vcrm_id || ': requirement in program ' || v.program_id || ', test case in program ' || c.program_id AS msg @@ -183,11 +222,14 @@ def upgrade() -> None: || ', result in program ' || x.program_id FROM {df} d JOIN {rs} x ON x.result_id = d.result_id WHERE x.program_id <> d.program_id LIMIT 50 - ) m""").format(vc=t["vcrm_entries"], tc=t["test_cases"], rs=t["test_results"], df=t["defect_reports"])) + ) m""").format(vc=t["vcrm_entries"], tc=t["test_cases"], rs=t["test_results"], df=t["defect_reports"]) + ) (bad,) = cur.fetchone() if bad: - raise RuntimeError(f"Tenant schema {schema!r}: cross-program references found (BR-07). " - f"Nothing was changed. Fix or remove these rows, then re-run:\n{bad}") + raise RuntimeError( + f"Tenant schema {schema!r}: cross-program references found (BR-07). " + f"Nothing was changed. Fix or remove these rows, then re-run:\n{bad}" + ) # 4. NOT NULL, composite-key targets, composite FKs for table in _PROGRAM_TABLES: @@ -199,24 +241,34 @@ def upgrade() -> None: "SELECT c.conname FROM pg_constraint c JOIN pg_attribute a " "ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1] " "WHERE c.contype = 'f' AND cardinality(c.conkey) = 1 AND c.conrelid = %s::regclass " - "AND a.attname = %s", (f'"{schema}"."{table}"', column)) + "AND a.attname = %s", + (f'"{schema}"."{table}"', column), + ) for (conname,) in cur.fetchall(): _drop_constraint(cur, schema, table, conname) for table, name, definition in _UNIQUES: _add_constraint(cur, schema, table, name, definition) for table, name, column, parent, on_delete in _COMPOSITE_FKS: - _add_constraint(cur, schema, table, name, sql.SQL( - "FOREIGN KEY ({col}, program_id) REFERENCES {parent}({col}, program_id){action}").format( - col=sql.Identifier(column), parent=_tbl(schema, parent), action=sql.SQL(on_delete))) + _add_constraint( + cur, + schema, + table, + name, + sql.SQL("FOREIGN KEY ({col}, program_id) REFERENCES {parent}({col}, program_id){action}").format( + col=sql.Identifier(column), parent=_tbl(schema, parent), action=sql.SQL(on_delete) + ), + ) # 5. fill program_id from the parent on INSERT when the caller omitted it for table, parent, key, fk in _FILL_TRIGGERS: cur.execute(sql.SQL("DROP TRIGGER IF EXISTS trg_fill_program_id ON {}").format(t[table])) - cur.execute(sql.SQL("CREATE TRIGGER trg_fill_program_id BEFORE INSERT ON {} FOR EACH ROW " - "EXECUTE FUNCTION {}.te_fill_program_id({}, {}, {})").format( - t[table], sql.Identifier(schema), sql.Literal(parent), sql.Literal(key), - sql.Literal(fk))) + cur.execute( + sql.SQL( + "CREATE TRIGGER trg_fill_program_id BEFORE INSERT ON {} FOR EACH ROW " + "EXECUTE FUNCTION {}.te_fill_program_id({}, {}, {})" + ).format(t[table], sql.Identifier(schema), sql.Literal(parent), sql.Literal(key), sql.Literal(fk)) + ) def downgrade() -> None: @@ -227,9 +279,15 @@ def downgrade() -> None: for table, name, *_ in _COMPOSITE_FKS: _drop_constraint(cur, schema, table, name, if_exists=True) for table, column, parent, on_delete in _SINGLE_FKS: - cur.execute(sql.SQL("ALTER TABLE {} ADD FOREIGN KEY ({}) REFERENCES {}({}){}").format( - _tbl(schema, table), sql.Identifier(column), _tbl(schema, parent), sql.Identifier(column), - sql.SQL(on_delete))) + cur.execute( + sql.SQL("ALTER TABLE {} ADD FOREIGN KEY ({}) REFERENCES {}({}){}").format( + _tbl(schema, table), + sql.Identifier(column), + _tbl(schema, parent), + sql.Identifier(column), + sql.SQL(on_delete), + ) + ) for table, name, _definition in _UNIQUES: _drop_constraint(cur, schema, table, name, if_exists=True) for table in _PROGRAM_TABLES: diff --git a/api/auth.py b/api/auth.py index 0370c6f..074a2d9 100644 --- a/api/auth.py +++ b/api/auth.py @@ -11,7 +11,8 @@ the default ``API_ENV=dev`` on its own, requires a session. """ -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Callable +from typing import Any from fastapi import Depends, Header, HTTPException from starlette.concurrency import run_in_threadpool @@ -21,9 +22,6 @@ from api.services.accounts import session_for from api.services.audit import acting_as from api.tenancy import tenant -from typing import Any -from collections.abc import Callable - ANONYMOUS_ACTOR = "anonymous" @@ -53,7 +51,7 @@ def _live_session(token: str) -> dict[str, Any]: with Conn() as conn, conn.cursor() as cur: session = session_for(cur, token) if session is not None: - conn.commit() # session_for records the use (#296); nothing else was written, and a close would roll it back + conn.commit() # session_for records the use (#296); nothing else was written, and a close would roll it back if session is None: raise HTTPException(status_code=401, detail="Session expired or invalid; sign in again") return session @@ -85,13 +83,13 @@ async def tenant_scope(authorization: str = Header(default="")) -> AsyncIterator # M2c (#94): which roles may perform each action. docs/ROLES.md shows the same # table, and tests/system/test_roles.py checks that the two agree. PERMISSIONS: dict[str, frozenset[str]] = { - "preview": frozenset({"uploader", "tenant_admin"}), - "upload": frozenset({"uploader", "tenant_admin"}), - "list_files": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), - "read_rows": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), - "list_te": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), + "preview": frozenset({"uploader", "tenant_admin"}), + "upload": frozenset({"uploader", "tenant_admin"}), + "list_files": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), + "read_rows": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), + "list_te": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), "delete_file": frozenset({"tenant_admin"}), - "read_audit": frozenset({"tenant_admin", "auditor"}), + "read_audit": frozenset({"tenant_admin", "auditor"}), "reset_password": frozenset({"tenant_admin"}), "review_rows": frozenset({"reviewer", "tenant_admin"}), "submit_import": frozenset({"uploader", "tenant_admin"}), @@ -110,6 +108,6 @@ def allow(action: str) -> Callable[..., None]: def check(session: dict[str, Any] | None = Depends(tenant_scope)) -> None: if session is not None and session["role"] not in roles: - raise HTTPException(status_code=403, - detail=f"Role '{session['role']}' may not {action.replace('_', ' ')}") + raise HTTPException(status_code=403, detail=f"Role '{session['role']}' may not {action.replace('_', ' ')}") + return check diff --git a/api/bodylimit.py b/api/bodylimit.py index 6211869..d24f3eb 100644 --- a/api/bodylimit.py +++ b/api/bodylimit.py @@ -14,11 +14,13 @@ breaks (a fully quoted CSV is about 1.7 times its size), and base64 adds a third, so a tighter cap would refuse files that are within the file limit. The routes keep their own exact checks on the decoded file as a second line of defence. """ + from __future__ import annotations -from api.config import settings from starlette.types import ASGIApp, Message, Receive, Scope, Send +from api.config import settings + _REFUSAL = b'{"detail":"Request body too large"}' @@ -40,12 +42,17 @@ def _declared_length(scope: Scope) -> int | None: async def _refuse(send: Send) -> None: - await send({ - "type": "http.response.start", - "status": 413, - "headers": [(b"content-type", b"application/json"), (b"content-length", str(len(_REFUSAL)).encode()), - (b"connection", b"close")], - }) + await send( + { + "type": "http.response.start", + "status": 413, + "headers": [ + (b"content-type", b"application/json"), + (b"content-length", str(len(_REFUSAL)).encode()), + (b"connection", b"close"), + ], + } + ) await send({"type": "http.response.body", "body": _REFUSAL}) diff --git a/api/concurrency.py b/api/concurrency.py index 010aa5b..4e9e801 100644 --- a/api/concurrency.py +++ b/api/concurrency.py @@ -45,8 +45,10 @@ def import_slot() -> Iterator[None]: if _active >= limit: raise HTTPException( status_code=503, - detail=(f"Too many imports are running on this server (the limit is {limit}). " - f"Try again in {RETRY_AFTER_SECONDS} seconds."), + detail=( + f"Too many imports are running on this server (the limit is {limit}). " + f"Try again in {RETRY_AFTER_SECONDS} seconds." + ), headers={"Retry-After": str(RETRY_AFTER_SECONDS)}, ) _active += 1 diff --git a/api/db.py b/api/db.py index 85e2f37..28deed3 100644 --- a/api/db.py +++ b/api/db.py @@ -7,8 +7,9 @@ import sys import time from collections.abc import Callable, Iterator +from concurrent.futures import Future, ThreadPoolExecutor +from concurrent.futures import TimeoutError as FuturesTimeout from contextlib import contextmanager -from concurrent.futures import Future, ThreadPoolExecutor, TimeoutError as FuturesTimeout from pathlib import Path from types import TracebackType from typing import TYPE_CHECKING, Any, Literal @@ -48,8 +49,10 @@ class DatabaseConnectError(psycopg2.OperationalError): # nobody has listed, or one in another language, still fails fast. _SERVER_SENT = re.compile(r"(?:^|failed: )[^\s:]+: ") # The exceptions: the server is up but cannot take the connection yet (SQLSTATE 57P03 and 53300). -_SERVER_BUSY = re.compile(r"the database system is|sorry, too many clients|remaining connection slots" - r"|too many connections for|could not fork new process") +_SERVER_BUSY = re.compile( + r"the database system is|sorry, too many clients|remaining connection slots" + r"|too many connections for|could not fork new process" +) # Client-side, but waiting cannot supply a password or add SSL to the server. _CLIENT_CONFIG = re.compile(r"no password supplied|does not support SSL") # ponytail: a server whose lc_messages is not English words "starting up" in its own language, so it @@ -59,12 +62,12 @@ class DatabaseConnectError(psycopg2.OperationalError): def _is_permanent(exc: Exception) -> bool: msg = str(exc) - return bool(_CLIENT_CONFIG.search(msg)) or ( - bool(_SERVER_SENT.search(msg)) and not _SERVER_BUSY.search(msg)) + return bool(_CLIENT_CONFIG.search(msg)) or (bool(_SERVER_SENT.search(msg)) and not _SERVER_BUSY.search(msg)) -def _connect_error(exc: Exception, user: str, creds: str, *, attempts: int = 0, - permanent: bool = False, purpose: str = "") -> DatabaseConnectError: +def _connect_error( + exc: Exception, user: str, creds: str, *, attempts: int = 0, permanent: bool = False, purpose: str = "" +) -> DatabaseConnectError: """``purpose`` says what the login was for (e.g. " to run the database migrations"), where the login differs from the one the person might expect.""" msg = f"Could not connect to PostgreSQL at {settings.PG_HOST}:{settings.PG_PORT} as {user}{purpose}" @@ -74,7 +77,8 @@ def _connect_error(exc: Exception, user: str, creds: str, *, attempts: int = 0, msg += f" after {attempts} attempts." if attempts else "." check = f"Check {creds} (and PGDATABASE, PGHOST, PGPORT)" return DatabaseConnectError( - f"{msg}\n {str(exc).strip()}\n{check}{'.' if permanent else ' and that the server is running.'}") + f"{msg}\n {str(exc).strip()}\n{check}{'.' if permanent else ' and that the server is running.'}" + ) def init_pool(max_attempts: int = 30, base_delay: float = 1.0) -> None: @@ -101,7 +105,9 @@ def init_pool(max_attempts: int = 30, base_delay: float = 1.0) -> None: host=settings.PG_HOST, port=settings.PG_PORT, user=user, - password=(settings.APP_DB_PASSWORD if settings.APP_DB_USER else settings.PG_PASSWORD).get_secret_value(), + password=( + settings.APP_DB_PASSWORD if settings.APP_DB_USER else settings.PG_PASSWORD + ).get_secret_value(), dbname=settings.PG_DATABASE, ) if attempt > 1: @@ -114,7 +120,10 @@ def init_pool(max_attempts: int = 30, base_delay: float = 1.0) -> None: delay = min(base_delay * (2 ** (attempt - 1)), 10.0) logger.warning( "Postgres not reachable (attempt %d/%d): %s. Retrying in %.1fs.", - attempt, max_attempts, str(exc).split("\n")[0][:120], delay, + attempt, + max_attempts, + str(exc).split("\n")[0][:120], + delay, ) time.sleep(delay) else: @@ -124,9 +133,7 @@ def init_pool(max_attempts: int = 30, base_delay: float = 1.0) -> None: # BUG-030: worker count = maxconn + a few, so a burst of concurrent # requests can all queue their getconn() calls without the executor # itself becoming the bottleneck. - _getconn_executor = ThreadPoolExecutor( - max_workers=_MAXCONN + 4, thread_name_prefix="pool-getconn" - ) + _getconn_executor = ThreadPoolExecutor(max_workers=_MAXCONN + 4, thread_name_prefix="pool-getconn") def close_pool() -> None: @@ -163,12 +170,12 @@ def _return_late_conn(fut: Future[connection]) -> None: conn = fut.result(timeout=0) _pool.putconn(conn) logger.warning( - "getconn() succeeded after the %.1fs timeout; returning " - "the connection to the pool.", + "getconn() succeeded after the %.1fs timeout; returning the connection to the pool.", settings.POOL_GETCONN_TIMEOUT, ) except Exception: # noqa: BLE001 — timeout retry: best-effort pass + future.add_done_callback(_return_late_conn) raise psycopg2.pool.PoolError( f"Could not obtain a database connection within " @@ -206,8 +213,9 @@ def __enter__(self) -> connection: raise return self._conn - def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, - tb: TracebackType | None) -> Literal[False]: + def __exit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + ) -> Literal[False]: # __enter__ refused to borrow without a pool, so there is one to return the connection to. assert _pool is not None # nosec B101 — narrows the type for mypy; not a runtime check conn, close = self._conn, False @@ -264,10 +272,11 @@ def bootstrap() -> None: # Deferred imports so pytest collection of api/ doesn't pull in Alembic # unless bootstrap() is actually called (e.g. in the lifespan handler, # which is only invoked by tests using TestClient as a context manager). - from alembic import command from alembic.config import Config from sqlalchemy.exc import OperationalError as SQLAlchemyOperationalError + from alembic import command + alembic_ini = alembic_ini_path() if not alembic_ini.exists(): @@ -291,9 +300,13 @@ def bootstrap() -> None: return cfg = Config(str(alembic_ini)) - logger.info("Running alembic upgrade head against %s@%s:%s/%s", - settings.PG_USER, settings.PG_HOST, settings.PG_PORT, - settings.PG_DATABASE) + logger.info( + "Running alembic upgrade head against %s@%s:%s/%s", + settings.PG_USER, + settings.PG_HOST, + settings.PG_PORT, + settings.PG_DATABASE, + ) try: command.upgrade(cfg, "head") except SQLAlchemyOperationalError as exc: @@ -305,18 +318,24 @@ def bootstrap() -> None: # The migrations log in as the owner (PGUSER), not as the runtime role the pool # uses, so a pool that connected fine can still stop here. Raise the short, named # error instead of SQLAlchemy's chained traceback (~70 lines on Windows). - raise _connect_error(orig, settings.PG_USER, "PGUSER / PGPASSWORD", permanent=True, - purpose=" to run the database migrations") from None + raise _connect_error( + orig, settings.PG_USER, "PGUSER / PGPASSWORD", permanent=True, purpose=" to run the database migrations" + ) from None with owner_connect() as conn, conn.cursor() as cur: - for schema, create in ((settings.UPLOADS_SCHEMA, True), (settings.CONTROL_SCHEMA, False), - (settings.TE_SCHEMA, False)): + for schema, create in ( + (settings.UPLOADS_SCHEMA, True), + (settings.CONTROL_SCHEMA, False), + (settings.TE_SCHEMA, False), + ): grant_runtime(cur, schema, create=create) _migrate_existing_tenants() logger.info("Alembic migrations complete") if not settings.APP_DB_USER: - logger.warning("APP_DB_USER is not set: the API connects as the owner %r, so the database " - "doesn't stop it changing the audit log (M3d). See docs/QUICKSTART.md.", - settings.PG_USER) + logger.warning( + "APP_DB_USER is not set: the API connects as the owner %r, so the database " + "doesn't stop it changing the audit log (M3d). See docs/QUICKSTART.md.", + settings.PG_USER, + ) @contextmanager @@ -324,8 +343,13 @@ def owner_connect() -> Iterator[connection]: """A connection as the owner (PG_USER): for migrations, provisioning and grants, never requests. Closed on exit; the caller commits.""" try: - conn = psycopg2.connect(host=settings.PG_HOST, port=settings.PG_PORT, user=settings.PG_USER, - password=settings.PG_PASSWORD.get_secret_value(), dbname=settings.PG_DATABASE) + conn = psycopg2.connect( + host=settings.PG_HOST, + port=settings.PG_PORT, + user=settings.PG_USER, + password=settings.PG_PASSWORD.get_secret_value(), + dbname=settings.PG_DATABASE, + ) except psycopg2.OperationalError as exc: raise _connect_error(exc, settings.PG_USER, "PGUSER / PGPASSWORD", permanent=_is_permanent(exc)) from exc try: @@ -344,8 +368,20 @@ def run_cli(main: Callable[[], int]) -> int: # Tables the runtime role may only read and insert (M3, #107). Triggers also stop the owner. -APPEND_ONLY = ("audit_log", "uploads", "upload_blobs", "source_rows", "row_decisions", "cell_edits", - "row_flags", "submissions", "approvals", "imports", "alembic_version", "alembic_version_te") +APPEND_ONLY = ( + "audit_log", + "uploads", + "upload_blobs", + "source_rows", + "row_decisions", + "cell_edits", + "row_flags", + "submissions", + "approvals", + "imports", + "alembic_version", + "alembic_version_te", +) def grant_runtime(cur: cursor, schema: str, create: bool) -> None: @@ -369,21 +405,27 @@ def grant_schema(cur: cursor, schema: str, role: str, create: bool) -> None: if cur.fetchone() is None: return s, r = sql.Identifier(schema), sql.Identifier(role) - cur.execute(sql.SQL("GRANT USAGE{} ON SCHEMA {} TO {}").format( - sql.SQL(", CREATE") if create else sql.SQL(""), s, r)) + cur.execute( + sql.SQL("GRANT USAGE{} ON SCHEMA {} TO {}").format(sql.SQL(", CREATE") if create else sql.SQL(""), s, r) + ) cur.execute(sql.SQL("GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA {} TO {}").format(s, r)) cur.execute(sql.SQL("GRANT USAGE, SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA {} TO {}").format(s, r)) - cur.execute("SELECT relname FROM pg_class WHERE relnamespace = %s::regnamespace AND relname = ANY(%s)", - (schema, list(APPEND_ONLY))) + cur.execute( + "SELECT relname FROM pg_class WHERE relnamespace = %s::regnamespace AND relname = ANY(%s)", + (schema, list(APPEND_ONLY)), + ) for (table,) in cur.fetchall(): - cur.execute(sql.SQL("REVOKE UPDATE, DELETE, TRUNCATE ON {}.{} FROM {}").format( - s, sql.Identifier(table), r)) + cur.execute(sql.SQL("REVOKE UPDATE, DELETE, TRUNCATE ON {}.{} FROM {}").format(s, sql.Identifier(table), r)) cur.execute("SELECT to_regclass(%s)", (f'"{schema}".csv_files',)) if create and fetch_one(cur)[0] is not None: - cur.execute(sql.SQL( - "SELECT c.relname FROM {}.csv_files f JOIN pg_class c ON c.relname = f.table_name " - "AND c.relnamespace = %s::regnamespace WHERE f.mode = 'dynamic' " - "AND pg_get_userbyid(c.relowner) <> %s").format(s), (schema, role)) + cur.execute( + sql.SQL( + "SELECT c.relname FROM {}.csv_files f JOIN pg_class c ON c.relname = f.table_name " + "AND c.relnamespace = %s::regnamespace WHERE f.mode = 'dynamic' " + "AND pg_get_userbyid(c.relowner) <> %s" + ).format(s), + (schema, role), + ) for (table,) in cur.fetchall(): cur.execute(sql.SQL("ALTER TABLE {}.{} OWNER TO {}").format(s, sql.Identifier(table), r)) cur.connection.commit() @@ -410,8 +452,7 @@ def _migrate_existing_tenants() -> None: from api.tenancy import migrate_tenant with owner_connect() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT slug FROM {}.tenants ORDER BY id").format( - sql.Identifier(settings.CONTROL_SCHEMA))) + cur.execute(sql.SQL("SELECT slug FROM {}.tenants ORDER BY id").format(sql.Identifier(settings.CONTROL_SCHEMA))) slugs = [r[0] for r in cur.fetchall()] for slug in slugs: migrate_tenant(slug) diff --git a/api/main.py b/api/main.py index eb6e428..5581586 100644 --- a/api/main.py +++ b/api/main.py @@ -9,7 +9,9 @@ import logging import os +from collections.abc import AsyncIterator from contextlib import asynccontextmanager +from typing import Any import psycopg2.pool from fastapi import FastAPI, Request @@ -20,11 +22,8 @@ from api.bodylimit import BodyLimitMiddleware from api.config import settings from api.ratelimit import rate_limit_middleware -from api.routers import (audit_routes, auth_routes, csv_routes, import_routes, policy_routes, review_routes, - te_routes) +from api.routers import audit_routes, auth_routes, csv_routes, import_routes, policy_routes, review_routes, te_routes from api.services import accounts -from typing import Any -from collections.abc import AsyncIterator logger = logging.getLogger(__name__) @@ -70,8 +69,9 @@ def _purge_old_sessions() -> None: if removed: logger.info("Purged %d ended session row(s).", removed) except Exception: # noqa: BLE001 - logger.warning("Could not purge old sessions at start-up; scripts/purge_sessions.py can do it later.", - exc_info=True) + logger.warning( + "Could not purge old sessions at start-up; scripts/purge_sessions.py can do it later.", exc_info=True + ) @asynccontextmanager @@ -155,15 +155,14 @@ def health() -> dict[str, Any]: # up. Otherwise a half-bootstrapped API reports "ok" and then every /upload # call throws UndefinedTable. from psycopg2 import sql as _sql + try: with db.Conn() as conn: with conn.cursor() as cur: cur.execute("SELECT version()") pg_version = db.fetch_one(cur)[0] cur.execute( - _sql.SQL("SELECT 1 FROM {}.csv_files LIMIT 0").format( - _sql.Identifier(settings.UPLOADS_SCHEMA) - ) + _sql.SQL("SELECT 1 FROM {}.csv_files LIMIT 0").format(_sql.Identifier(settings.UPLOADS_SCHEMA)) ) body: dict[str, Any] = {"status": "ok"} # #291 (BR-54): /api/health is open to anyone who can reach the port, so outside dev it says diff --git a/api/oidc.py b/api/oidc.py index c8ebdd0..765343a 100644 --- a/api/oidc.py +++ b/api/oidc.py @@ -10,13 +10,13 @@ from functools import lru_cache from pathlib import Path +from typing import Any from urllib.parse import urlparse from urllib.request import url2pathname import jwt from api.config import settings -from typing import Any ALGORITHMS = ["RS256", "ES256"] # Seconds to wait for the IdP's key set. PyJWT's default is 30, which would hold a request thread that long for @@ -73,8 +73,14 @@ def verify(id_token: str) -> dict[str, Any]: ``username_from`` hides the reason; this keeps it, for scripts/check_oidc.py. """ key = _signing_key(id_token) - return jwt.decode(id_token, key, algorithms=ALGORITHMS, audience=settings.OIDC_AUDIENCE, - issuer=settings.OIDC_ISSUER, options={"require": ["exp", "iat", "iss", "aud"]}) + return jwt.decode( + id_token, + key, + algorithms=ALGORITHMS, + audience=settings.OIDC_AUDIENCE, + issuer=settings.OIDC_ISSUER, + options={"require": ["exp", "iat", "iss", "aud"]}, + ) def username_from(id_token: str) -> str | None: diff --git a/api/policy.py b/api/policy.py index 913c065..ccdb95c 100644 --- a/api/policy.py +++ b/api/policy.py @@ -12,10 +12,11 @@ from __future__ import annotations +from typing import Any + from fastapi import Response from api.config import CLASSIFICATIONS, settings -from typing import Any HEADER = "X-Data-Classification" @@ -25,7 +26,8 @@ def check_config(classification: str, retention_years: int) -> None: if classification == "PROTECTED": raise RuntimeError( "DATA_CLASSIFICATION=PROTECTED is not supported. PROTECTED needs IRAP-assessed hosting and " - "ISM PROTECTED controls (#49); the design target is OFFICIAL: Sensitive.") + "ISM PROTECTED controls (#49); the design target is OFFICIAL: Sensitive." + ) if classification not in CLASSIFICATIONS: raise RuntimeError(f"DATA_CLASSIFICATION must be one of {', '.join(CLASSIFICATIONS)}; got {classification!r}.") if retention_years < 1: diff --git a/api/ratelimit.py b/api/ratelimit.py index 2bc9e1f..16909a8 100644 --- a/api/ratelimit.py +++ b/api/ratelimit.py @@ -27,12 +27,12 @@ import threading import time from collections import OrderedDict, deque +from collections.abc import Awaitable, Callable from fastapi import Request from fastapi.responses import JSONResponse, Response from api.config import settings -from collections.abc import Awaitable, Callable # Hard cap on distinct client buckets held in memory. _MAX_TRACKED_CLIENTS = 4096 @@ -45,8 +45,9 @@ def __init__(self) -> None: self._buckets: OrderedDict[tuple[str, str], deque[float]] = OrderedDict() self._lock = threading.Lock() - def check(self, client: str, scope: str, max_requests: int, - window_seconds: float, now: float | None = None) -> tuple[bool, float]: + def check( + self, client: str, scope: str, max_requests: int, window_seconds: float, now: float | None = None + ) -> tuple[bool, float]: """Record a hit and report whether it is allowed. Returns ``(allowed, retry_after_seconds)``. ``retry_after_seconds`` is 0 @@ -115,21 +116,14 @@ async def rate_limit_middleware(request: Request, call_next: Callable[[Request], else: scope, budget = "read", settings.RATE_LIMIT_READS_PER_MINUTE - allowed, retry_after = limiter.check( - _client_id(request), scope, budget, 60.0 - ) + allowed, retry_after = limiter.check(_client_id(request), scope, budget, 60.0) if not allowed: # Integer seconds, minimum 1 — Retry-After: 0 tells a client to retry # instantly, which would defeat the limit. seconds = max(1, int(retry_after + 0.999)) return JSONResponse( status_code=429, - content={ - "detail": ( - f"Rate limit exceeded for {scope} requests " - f"({budget}/minute). Retry in {seconds}s." - ) - }, + content={"detail": (f"Rate limit exceeded for {scope} requests ({budget}/minute). Retry in {seconds}s.")}, headers={"Retry-After": str(seconds)}, ) return await call_next(request) diff --git a/api/routers/audit_routes.py b/api/routers/audit_routes.py index 5ba5544..d4a19bf 100644 --- a/api/routers/audit_routes.py +++ b/api/routers/audit_routes.py @@ -11,18 +11,18 @@ import json from datetime import datetime +from typing import Any from fastapi import APIRouter, Depends, HTTPException, Query, Response from psycopg2 import sql from api import policy from api.auth import allow, tenant_scope -from api.tenancy import uploads_schema -from api.db import Conn, fetch_one from api.config import settings +from api.db import Conn, fetch_one from api.services.audit import VALID_ACTIONS, verify_chain from api.services.reports import csv_text, like_pattern -from typing import Any +from api.tenancy import uploads_schema router = APIRouter( prefix="/api/audit", @@ -37,11 +37,7 @@ def audit_log(limit: int = 50, offset: int = 0) -> dict[str, Any]: offset = max(0, offset) with Conn() as conn: with conn.cursor() as cur: - cur.execute( - sql.SQL("SELECT COUNT(*) FROM {}.audit_log").format( - sql.Identifier(uploads_schema()) - ) - ) + cur.execute(sql.SQL("SELECT COUNT(*) FROM {}.audit_log").format(sql.Identifier(uploads_schema()))) total = fetch_one(cur)[0] cur.execute( sql.SQL( @@ -75,8 +71,18 @@ def audit_verify() -> dict[str, Any]: return verify_chain(cur) -_EVENT_COLUMNS = ("id", "performed_at", "actor", "action", "file_id", "file_name", "table_name", "mode", - "before_value", "after_value") +_EVENT_COLUMNS = ( + "id", + "performed_at", + "actor", + "action", + "file_id", + "file_name", + "table_name", + "mode", + "before_value", + "after_value", +) @router.get("/events", dependencies=[Depends(allow("read_audit"))], response_model=None) @@ -122,18 +128,47 @@ def audit_events( with Conn() as conn, conn.cursor() as cur: cur.execute(sql.SQL("SELECT count(*) FROM {}.audit_log{}").format(schema, clause), params) total = fetch_one(cur)[0] - cur.execute(sql.SQL("SELECT {} FROM {}.audit_log{} ORDER BY id DESC LIMIT %s OFFSET %s").format( - sql.SQL(", ").join(sql.Identifier(c) for c in _EVENT_COLUMNS), schema, clause), [*params, limit, offset]) + cur.execute( + sql.SQL("SELECT {} FROM {}.audit_log{} ORDER BY id DESC LIMIT %s OFFSET %s").format( + sql.SQL(", ").join(sql.Identifier(c) for c in _EVENT_COLUMNS), schema, clause + ), + [*params, limit, offset], + ) rows = cur.fetchall() marking = {policy.HEADER: settings.DATA_CLASSIFICATION} if format == "csv": - table_rows = [[r[0], r[1].isoformat(), *r[2:8], *(None if v is None else json.dumps(v) for v in r[8:])] - for r in rows] + table_rows = [ + [r[0], r[1].isoformat(), *r[2:8], *(None if v is None else json.dumps(v) for v in r[8:])] for r in rows + ] text = csv_text(list(_EVENT_COLUMNS), table_rows) - return Response(text, media_type="text/csv", headers={ - **marking, "Content-Disposition": 'attachment; filename="audit-events.csv"', - "X-Total-Count": str(total)}) - entries = [{"id": str(r[0]), "performedAt": r[1].isoformat(), "actor": r[2], "action": r[3], "fileId": r[4], - "fileName": r[5], "tableName": r[6], "mode": r[7], "before": r[8], "after": r[9]} for r in rows] - return {"classification": settings.DATA_CLASSIFICATION, "total": total, "limit": limit, "offset": offset, - "entries": entries} + return Response( + text, + media_type="text/csv", + headers={ + **marking, + "Content-Disposition": 'attachment; filename="audit-events.csv"', + "X-Total-Count": str(total), + }, + ) + entries = [ + { + "id": str(r[0]), + "performedAt": r[1].isoformat(), + "actor": r[2], + "action": r[3], + "fileId": r[4], + "fileName": r[5], + "tableName": r[6], + "mode": r[7], + "before": r[8], + "after": r[9], + } + for r in rows + ] + return { + "classification": settings.DATA_CLASSIFICATION, + "total": total, + "limit": limit, + "offset": offset, + "entries": entries, + } diff --git a/api/routers/auth_routes.py b/api/routers/auth_routes.py index c5f7d89..f4ffea1 100644 --- a/api/routers/auth_routes.py +++ b/api/routers/auth_routes.py @@ -7,16 +7,17 @@ from __future__ import annotations +from typing import Any + from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel, Field +from api import oidc from api.auth import PERMISSIONS, bearer_token, require_session from api.db import Conn, acting_role -from api import oidc from api.services import accounts from api.services.audit import acting_as, write_audit from api.tenancy import tenant -from typing import Any router = APIRouter(prefix="/api/auth", tags=["auth"]) @@ -83,8 +84,9 @@ class ChangePasswordRequest(BaseModel): @router.post("/password") -def change_password(req: ChangePasswordRequest, token: str = Depends(bearer_token), - session: dict[str, Any] = Depends(require_session)) -> dict[str, Any]: +def change_password( + req: ChangePasswordRequest, token: str = Depends(bearer_token), session: dict[str, Any] = Depends(require_session) +) -> dict[str, Any]: """Change your own password (#117). This session stays signed in; all others end. A wrong current password is 400, not 401, so the browser keeps the session, @@ -92,8 +94,7 @@ def change_password(req: ChangePasswordRequest, token: str = Depends(bearer_toke """ with Conn() as conn: with conn.cursor() as cur: - ok = accounts.change_password(cur, session["userId"], token, - req.currentPassword, req.newPassword) + ok = accounts.change_password(cur, session["userId"], token, req.currentPassword, req.newPassword) conn.commit() if not ok: raise HTTPException(status_code=400, detail="Current password is incorrect") @@ -105,8 +106,9 @@ class ResetPasswordRequest(BaseModel): @router.post("/users/{username}/password") -def reset_password(username: str, req: ResetPasswordRequest, - session: dict[str, Any] = Depends(require_session)) -> dict[str, Any]: +def reset_password( + username: str, req: ResetPasswordRequest, session: dict[str, Any] = Depends(require_session) +) -> dict[str, Any]: """A tenant admin sets a member's password, unlocking the account and ending its sessions (#117). Audited in the tenant's audit log.""" if session["role"] not in PERMISSIONS["reset_password"]: @@ -122,6 +124,8 @@ def reset_password(username: str, req: ResetPasswordRequest, if result == "missing": raise HTTPException(status_code=404, detail="No such user in this tenant") if result == "shared": - raise HTTPException(status_code=409, detail="This user is also in another tenant. " - "An operator must reset it with scripts/reset_password.py") + raise HTTPException( + status_code=409, + detail="This user is also in another tenant. An operator must reset it with scripts/reset_password.py", + ) return {"status": "ok"} diff --git a/api/routers/csv_routes.py b/api/routers/csv_routes.py index 18441a1..056f093 100644 --- a/api/routers/csv_routes.py +++ b/api/routers/csv_routes.py @@ -6,29 +6,29 @@ import binascii import logging from datetime import datetime +from typing import Any from urllib.parse import quote from fastapi import APIRouter, Depends, HTTPException, Query, Response from psycopg2 import sql +from psycopg2.extensions import cursor from pydantic import BaseModel, Field from api import policy from api.auth import allow, tenant_scope from api.concurrency import import_slot from api.config import settings -from api.tenancy import uploads_schema from api.db import Conn from api.services.audit import coerce_file_id, write_audit from api.services.csv_parse import build_preview from api.services.dynamic_loader import upload_dynamic from api.services.originals import record_upload, store_upload -from api.services.type_confirmation import require_confirmed_types from api.services.reports import like_pattern +from api.services.results import LoadResult from api.services.staged_import import derive_state, state_columns, state_join from api.services.te_loader import match_te_table, upload_te -from typing import Any -from psycopg2.extensions import cursor -from api.services.results import LoadResult +from api.services.type_confirmation import require_confirmed_types +from api.tenancy import uploads_schema logger = logging.getLogger(__name__) @@ -66,8 +66,9 @@ class UploadRequest(BaseModel): typesConfirmed: bool = Field( default=False, description="A person confirmed `types` (#195); the registry records `user_confirmed`, else `inferred_unconfirmed`. " - "A server started with API_REQUIRE_TYPE_CONFIRMATION=true answers 422 to a dynamic upload " - "unless this is true and `types` is sent (#242).") + "A server started with API_REQUIRE_TYPE_CONFIRMATION=true answers 422 to a dynamic upload " + "unless this is true and `types` is sent (#242).", + ) @router.post("/preview", dependencies=[Depends(allow("preview"))]) @@ -124,10 +125,12 @@ def record_with_load(cur: cursor, result: LoadResult) -> None: # Any failure rolls the load back; wrapping it keeps it out of the loaders' psycopg2 handlers. try: flags = result.pop("_duplicateFlags", None) - recorded["uploadId"] = store_upload(cur, req.fileName, req.content, req.mode, result, - original=original, flags=flags) - write_audit(cur, "upload", coerce_file_id(result.get("fileId")), req.fileName, - result.get("tableName"), req.mode) + recorded["uploadId"] = store_upload( + cur, req.fileName, req.content, req.mode, result, original=original, flags=flags + ) + write_audit( + cur, "upload", coerce_file_id(result.get("fileId")), req.fileName, result.get("tableName"), req.mode + ) except Exception as exc: # noqa: BLE001 — any failure here must undo the load raise RecordFailed(str(exc)) from exc @@ -151,9 +154,16 @@ def load() -> LoadResult: mapping = [m.model_dump() for m in req.headerMapping] if req.headerMapping else None def load() -> LoadResult: - return upload_dynamic(req.fileName, req.content, req.types, req.overwrite, session=session, - header_mapping=mapping, types_confirmed=req.typesConfirmed, - on_commit=record_with_load) + return upload_dynamic( + req.fileName, + req.content, + req.types, + req.overwrite, + session=session, + header_mapping=mapping, + types_confirmed=req.typesConfirmed, + on_commit=record_with_load, + ) else: raise HTTPException(422, f"Unknown mode '{req.mode}' — use 'dynamic' or 'te'") @@ -166,7 +176,7 @@ def load() -> LoadResult: "status": "error", "reason": "record_failed", "message": "The upload couldn't be recorded, so nothing was imported. Try again; " - "if it keeps failing, contact your administrator.", + "if it keeps failing, contact your administrator.", "logs": [], } @@ -244,22 +254,47 @@ def list_uploads( raise HTTPException(422, f"Unknown status {status!r}; expected one of {list(_UPLOAD_STATUSES)}") where: list[sql.Composable] = [] params: list[object] = [] - for clause, value in (("u.status = %s", status), ("u.uploader = %s", uploader), - ("u.file_name ILIKE %s ESCAPE '\\'", None if file is None else like_pattern(file)), - ("u.uploaded_at >= %s", date_from), ("u.uploaded_at < %s", date_to)): + for clause, value in ( + ("u.status = %s", status), + ("u.uploader = %s", uploader), + ("u.file_name ILIKE %s ESCAPE '\\'", None if file is None else like_pattern(file)), + ("u.uploaded_at >= %s", date_from), + ("u.uploaded_at < %s", date_to), + ): if value is not None: where.append(sql.SQL(clause)) params.append(value) where_sql = sql.SQL(" WHERE ") + sql.SQL(" AND ").join(where) if where else sql.SQL("") with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL( - "SELECT u.id, u.file_name, u.sha256, u.byte_size, u.uploader, u.mode, u.status, u.total_rows, " - "u.imported_rows, u.failed_rows, u.csv_file_id, u.uploaded_at, {reason}, {cols} " - "FROM {s}.uploads u {join}{where} ORDER BY u.id DESC LIMIT %s OFFSET %s" - ).format(reason=sql.SQL(_FAILURE_REASON), cols=state_columns(), s=sql.Identifier(uploads_schema()), - join=state_join(), where=where_sql), [*params, max(1, min(limit, 500)), max(0, offset)]) - keys = ("id", "file_name", "sha256", "byte_size", "uploader", "mode", "status", "total_rows", - "imported_rows", "failed_rows", "csv_file_id", "uploaded_at", "failure_reason") + cur.execute( + sql.SQL( + "SELECT u.id, u.file_name, u.sha256, u.byte_size, u.uploader, u.mode, u.status, u.total_rows, " + "u.imported_rows, u.failed_rows, u.csv_file_id, u.uploaded_at, {reason}, {cols} " + "FROM {s}.uploads u {join}{where} ORDER BY u.id DESC LIMIT %s OFFSET %s" + ).format( + reason=sql.SQL(_FAILURE_REASON), + cols=state_columns(), + s=sql.Identifier(uploads_schema()), + join=state_join(), + where=where_sql, + ), + [*params, max(1, min(limit, 500)), max(0, offset)], + ) + keys = ( + "id", + "file_name", + "sha256", + "byte_size", + "uploader", + "mode", + "status", + "total_rows", + "imported_rows", + "failed_rows", + "csv_file_id", + "uploaded_at", + "failure_reason", + ) out = [] for r in cur.fetchall(): u = dict(zip(keys, r[:13])) @@ -277,10 +312,13 @@ def upload_detail(upload_id: int) -> dict[str, Any]: """One upload's outcome, why its rows failed, and its step log (M3c, #107). Stored on the server, so any session in the tenant can read them.""" with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL( - "SELECT u.status, u.total_rows, u.imported_rows, u.failed_rows, u.row_errors, u.logs, u.uploader, " - "u.file_name, {cols} FROM {s}.uploads u {join} WHERE u.id = %s" - ).format(cols=state_columns(), s=sql.Identifier(uploads_schema()), join=state_join()), (upload_id,)) + cur.execute( + sql.SQL( + "SELECT u.status, u.total_rows, u.imported_rows, u.failed_rows, u.row_errors, u.logs, u.uploader, " + "u.file_name, {cols} FROM {s}.uploads u {join} WHERE u.id = %s" + ).format(cols=state_columns(), s=sql.Identifier(uploads_schema()), join=state_join()), + (upload_id,), + ) row = cur.fetchone() if row is None: raise HTTPException(404, "No such upload") @@ -292,17 +330,26 @@ def upload_detail(upload_id: int) -> dict[str, Any]: def upload_original(upload_id: int) -> Response: """The file exactly as it was uploaded (M3b; BR-24).""" with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL( - "SELECT u.file_name, u.sha256, b.content FROM {s}.uploads u " - "JOIN {s}.upload_blobs b ON b.upload_id = u.id WHERE u.id = %s" - ).format(s=sql.Identifier(uploads_schema())), (upload_id,)) + cur.execute( + sql.SQL( + "SELECT u.file_name, u.sha256, b.content FROM {s}.uploads u " + "JOIN {s}.upload_blobs b ON b.upload_id = u.id WHERE u.id = %s" + ).format(s=sql.Identifier(uploads_schema())), + (upload_id,), + ) row = cur.fetchone() if row is None: raise HTTPException(404, "No such upload") name, digest, content = row - return Response(bytes(content), media_type="text/csv", headers={ - "Content-Disposition": f"attachment; filename*=UTF-8''{quote(name)}", - "X-Content-SHA256": digest, policy.HEADER: settings.DATA_CLASSIFICATION}) + return Response( + bytes(content), + media_type="text/csv", + headers={ + "Content-Disposition": f"attachment; filename*=UTF-8''{quote(name)}", + "X-Content-SHA256": digest, + policy.HEADER: settings.DATA_CLASSIFICATION, + }, + ) @router.get("/tables/{table_name}/rows", dependencies=[Depends(allow("read_rows"))]) @@ -314,9 +361,7 @@ def table_rows(table_name: str, limit: int = 50) -> dict[str, Any]: with conn.cursor() as cur: # Only serve tables that are registered uploads cur.execute( - sql.SQL("SELECT 1 FROM {}.csv_files WHERE table_name = %s").format( - sql.Identifier(uploads_schema()) - ), + sql.SQL("SELECT 1 FROM {}.csv_files WHERE table_name = %s").format(sql.Identifier(uploads_schema())), (table_name,), ) if cur.fetchone() is None: @@ -343,15 +388,14 @@ def delete_file(file_id: int) -> dict[str, Any]: if not settings.allow_destructive: raise HTTPException( 403, - "Destructive operations are disabled. " - "Set API_ALLOW_DESTRUCTIVE=true to enable DELETE.", + "Destructive operations are disabled. Set API_ALLOW_DESTRUCTIVE=true to enable DELETE.", ) with Conn() as conn: with conn.cursor() as cur: cur.execute( - sql.SQL( - "SELECT table_name, mode, file_name FROM {}.csv_files WHERE id = %s" - ).format(sql.Identifier(uploads_schema())), + sql.SQL("SELECT table_name, mode, file_name FROM {}.csv_files WHERE id = %s").format( + sql.Identifier(uploads_schema()) + ), (file_id,), ) row = cur.fetchone() @@ -375,9 +419,7 @@ def delete_file(file_id: int) -> dict[str, Any]: ) ) cur.execute( - sql.SQL("DELETE FROM {}.csv_files WHERE id = %s").format( - sql.Identifier(uploads_schema()) - ), + sql.SQL("DELETE FROM {}.csv_files WHERE id = %s").format(sql.Identifier(uploads_schema())), (file_id,), ) # Persist audit record so deletions are traceable after the table is diff --git a/api/routers/import_routes.py b/api/routers/import_routes.py index 2da944a..ffab162 100644 --- a/api/routers/import_routes.py +++ b/api/routers/import_routes.py @@ -4,8 +4,11 @@ import base64 import binascii +from collections.abc import Callable +from typing import Any, TypeVar from fastapi import APIRouter, Depends, Header, HTTPException +from psycopg2.extensions import cursor from pydantic import BaseModel, Field from api import policy @@ -16,14 +19,14 @@ from api.routers.csv_routes import HeaderRename from api.services import staged_import from api.services.type_confirmation import require_confirmed_types -from typing import Any -from psycopg2.extensions import cursor -from collections.abc import Callable -from typing import TypeVar T = TypeVar("T") -router = APIRouter(prefix="/api/csv/uploads", tags=["import"], dependencies=[Depends(tenant_scope), Depends(policy.mark_classification)]) +router = APIRouter( + prefix="/api/csv/uploads", + tags=["import"], + dependencies=[Depends(tenant_scope), Depends(policy.mark_classification)], +) class StageRequest(BaseModel): @@ -33,8 +36,9 @@ class StageRequest(BaseModel): typesConfirmed: bool = Field( default=False, description="A person confirmed `types` (#195); the import records it in the registry. " - "A server started with API_REQUIRE_TYPE_CONFIRMATION=true answers 422 unless this is true " - "and `types` is sent (#242).") + "A server started with API_REQUIRE_TYPE_CONFIRMATION=true answers 422 unless this is true " + "and `types` is sent (#242).", + ) headerMapping: list[HeaderRename] | None = Field(default=None, max_length=1000) contentBase64: str | None = None # the file's bytes as uploaded, kept as the preserved original (#185) @@ -90,11 +94,13 @@ def stage(req: StageRequest) -> dict[str, Any]: @router.get("/{upload_id}/workflow", dependencies=[Depends(allow("read_rows"))]) def workflow(upload_id: int) -> dict[str, Any]: """The upload's state, its latest submission, approval and import, and the history of each.""" + def read(cur: cursor, uid: int) -> dict[str, Any]: st = staged_import.state_of(cur, uid) if st is None: raise staged_import.WorkflowError(404, "No such upload") return {**st, "history": staged_import.history(cur, uid)} + return _run(read, upload_id, commit=False) @@ -104,13 +110,18 @@ def submit(upload_id: int, req: SubmitRequest | None = None) -> dict[str, Any]: @router.post("/{upload_id}/approval", dependencies=[Depends(allow("approve_import"))]) -def approval(upload_id: int, req: ApprovalRequest, session: dict[str, Any] | None = Depends(tenant_scope)) -> dict[str, Any]: +def approval( + upload_id: int, req: ApprovalRequest, session: dict[str, Any] | None = Depends(tenant_scope) +) -> dict[str, Any]: return _run(staged_import.decide_approval, upload_id, req.decision, req.reason, session) @router.post("/{upload_id}/import", dependencies=[Depends(allow("run_import")), Depends(import_slot)]) -def run_import(upload_id: int, idempotency_key: str = Header(default="", alias="Idempotency-Key"), - session: dict[str, Any] | None = Depends(tenant_scope)) -> dict[str, Any]: +def run_import( + upload_id: int, + idempotency_key: str = Header(default="", alias="Idempotency-Key"), + session: dict[str, Any] | None = Depends(tenant_scope), +) -> dict[str, Any]: """Import an approved upload in one transaction. Send an Idempotency-Key and reuse it to retry.""" try: return staged_import.import_upload(upload_id, idempotency_key, session) diff --git a/api/routers/policy_routes.py b/api/routers/policy_routes.py index ff40e5d..9609b23 100644 --- a/api/routers/policy_routes.py +++ b/api/routers/policy_routes.py @@ -2,14 +2,16 @@ from __future__ import annotations +from typing import Any + from fastapi import APIRouter, Depends from api import policy from api.auth import tenant_scope -from typing import Any -router = APIRouter(prefix="/api/policy", tags=["policy"], - dependencies=[Depends(tenant_scope), Depends(policy.mark_classification)]) +router = APIRouter( + prefix="/api/policy", tags=["policy"], dependencies=[Depends(tenant_scope), Depends(policy.mark_classification)] +) @router.get("") diff --git a/api/routers/review_routes.py b/api/routers/review_routes.py index b95c0f5..7ae1cde 100644 --- a/api/routers/review_routes.py +++ b/api/routers/review_routes.py @@ -2,6 +2,9 @@ from __future__ import annotations +from collections.abc import Callable +from typing import Any, TypeVar + from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel @@ -9,13 +12,14 @@ from api.auth import allow, tenant_scope from api.db import Conn from api.services import review -from typing import Any -from collections.abc import Callable -from typing import TypeVar T = TypeVar("T") -router = APIRouter(prefix="/api/csv/uploads", tags=["review"], dependencies=[Depends(tenant_scope), Depends(policy.mark_classification)]) +router = APIRouter( + prefix="/api/csv/uploads", + tags=["review"], + dependencies=[Depends(tenant_scope), Depends(policy.mark_classification)], +) class DecisionRequest(BaseModel): diff --git a/api/routers/te_routes.py b/api/routers/te_routes.py index c473347..96d66fe 100644 --- a/api/routers/te_routes.py +++ b/api/routers/te_routes.py @@ -1,13 +1,14 @@ """T&E schema endpoints — table list with row counts for the fixed 12 tables.""" +from typing import Any + from fastapi import APIRouter, Depends from api import policy from api.auth import allow, tenant_scope from api.config import TE_TABLES -from api.tenancy import te_schema from api.db import Conn -from typing import Any +from api.tenancy import te_schema # BUG-035: auth is applied per-router (see csv_routes.py for the rationale). router = APIRouter( diff --git a/api/services/accounts.py b/api/services/accounts.py index 9d24770..a82567e 100644 --- a/api/services/accounts.py +++ b/api/services/accounts.py @@ -13,10 +13,10 @@ from typing import Any, NamedTuple from psycopg2 import sql +from psycopg2.extensions import cursor from api.config import settings from api.db import fetch_one -from psycopg2.extensions import cursor ROLES = ("uploader", "reviewer", "tenant_admin", "auditor") MIN_PASSWORD = 12 @@ -80,7 +80,7 @@ def _q(query: str) -> sql.Composed: class Existing(NamedTuple): tenant: bool # a tenant with this slug exists - user: bool # a user with this username exists; usernames are unique across all tenants + user: bool # a user with this username exists; usernames are unique across all tenants member: bool # that user is already a member of that tenant @@ -90,13 +90,17 @@ def existing(cur: cursor, slug: str, username: str) -> Existing: Lets a caller refuse to create a duplicate with a clear message, instead of failing on the database's unique key after the person has already typed a password. """ - cur.execute(_q( - "SELECT EXISTS (SELECT 1 FROM {c}.tenants WHERE slug = %s), " - "EXISTS (SELECT 1 FROM {c}.users WHERE username = %s), " - "EXISTS (SELECT 1 FROM {c}.users u " - "JOIN {c}.memberships m ON m.user_id = u.id " - "JOIN {c}.tenants t ON t.id = m.tenant_id " - "WHERE t.slug = %s AND u.username = %s)"), (slug, username, slug, username)) + cur.execute( + _q( + "SELECT EXISTS (SELECT 1 FROM {c}.tenants WHERE slug = %s), " + "EXISTS (SELECT 1 FROM {c}.users WHERE username = %s), " + "EXISTS (SELECT 1 FROM {c}.users u " + "JOIN {c}.memberships m ON m.user_id = u.id " + "JOIN {c}.tenants t ON t.id = m.tenant_id " + "WHERE t.slug = %s AND u.username = %s)" + ), + (slug, username, slug, username), + ) return Existing(*fetch_one(cur)) @@ -123,16 +127,19 @@ def set_self_approval(cur: cursor, slug: str, allowed: bool) -> None: def create_user(cur: cursor, username: str, password: str) -> int: - cur.execute(_q("INSERT INTO {c}.users (username, password_hash) VALUES (%s, %s) RETURNING id"), - (username, hash_password(password))) + cur.execute( + _q("INSERT INTO {c}.users (username, password_hash) VALUES (%s, %s) RETURNING id"), + (username, hash_password(password)), + ) return int(fetch_one(cur)[0]) def add_membership(cur: cursor, user_id: int, tenant_id: int, role: str) -> None: if role not in ROLES: raise ValueError(f"Unknown role {role!r}; expected one of {ROLES}") - cur.execute(_q("INSERT INTO {c}.memberships (user_id, tenant_id, role) VALUES (%s, %s, %s)"), - (user_id, tenant_id, role)) + cur.execute( + _q("INSERT INTO {c}.memberships (user_id, tenant_id, role) VALUES (%s, %s, %s)"), (user_id, tenant_id, role) + ) def login(cur: cursor, tenant_slug: str, username: str, password: str) -> dict[str, Any] | None: @@ -142,13 +149,17 @@ def login(cur: cursor, tenant_slug: str, username: str, password: str) -> dict[s Wrong tenant, unknown user, wrong password, inactive user and locked account (#102) all return None, so a caller cannot tell which one failed. """ - cur.execute(_q( - "SELECT u.id, u.password_hash, u.is_active, t.id, m.role, " - "COALESCE(u.locked_until > now(), false) " - "FROM {c}.users u " - "LEFT JOIN {c}.tenants t ON t.slug = %s " - "LEFT JOIN {c}.memberships m ON m.user_id = u.id AND m.tenant_id = t.id " - "WHERE u.username = %s"), (tenant_slug, username)) + cur.execute( + _q( + "SELECT u.id, u.password_hash, u.is_active, t.id, m.role, " + "COALESCE(u.locked_until > now(), false) " + "FROM {c}.users u " + "LEFT JOIN {c}.tenants t ON t.slug = %s " + "LEFT JOIN {c}.memberships m ON m.user_id = u.id AND m.tenant_id = t.id " + "WHERE u.username = %s" + ), + (tenant_slug, username), + ) row = cur.fetchone() stored = row[1] if row else _DUMMY_HASH ok = verify_password(password, stored) @@ -161,8 +172,10 @@ def login(cur: cursor, tenant_slug: str, username: str, password: str) -> dict[s return None if needs_rehash(stored): _upgrade_hash(cur, row[0], stored, password) - cur.execute(_q("UPDATE {c}.users SET failed_logins = 0, first_failed_at = NULL, " - "locked_until = NULL WHERE id = %s"), (row[0],)) + cur.execute( + _q("UPDATE {c}.users SET failed_logins = 0, first_failed_at = NULL, locked_until = NULL WHERE id = %s"), + (row[0],), + ) return _new_session(cur, row[0], row[3], username, tenant_slug, row[4]) @@ -172,8 +185,10 @@ def _upgrade_hash(cur: cursor, user_id: int, old_hash: str, password: str) -> bo The condition keeps a password changed between the check and this update from being undone. Returns whether a row was changed. The caller commits. """ - cur.execute(_q("UPDATE {c}.users SET password_hash = %s WHERE id = %s AND password_hash = %s"), - (hash_password(password), user_id, old_hash)) + cur.execute( + _q("UPDATE {c}.users SET password_hash = %s WHERE id = %s AND password_hash = %s"), + (hash_password(password), user_id, old_hash), + ) return cur.rowcount == 1 @@ -183,39 +198,58 @@ def login_trusted(cur: cursor, tenant_slug: str, username: str) -> dict[str, Any Authorisation stays local: the user must already exist, be active and be a member of the tenant. Nobody is created from IdP claims. """ - cur.execute(_q( - "SELECT u.id, t.id, m.role FROM {c}.users u " - "JOIN {c}.tenants t ON t.slug = %s " - "JOIN {c}.memberships m ON m.user_id = u.id AND m.tenant_id = t.id " - "WHERE u.username = %s AND u.is_active"), (tenant_slug, username)) + cur.execute( + _q( + "SELECT u.id, t.id, m.role FROM {c}.users u " + "JOIN {c}.tenants t ON t.slug = %s " + "JOIN {c}.memberships m ON m.user_id = u.id AND m.tenant_id = t.id " + "WHERE u.username = %s AND u.is_active" + ), + (tenant_slug, username), + ) row = cur.fetchone() return _new_session(cur, row[0], row[1], username, tenant_slug, row[2]) if row else None -def _new_session(cur: cursor, user_id: int, tenant_id: int, username: str, tenant_slug: str, role: str) -> dict[str, Any]: +def _new_session( + cur: cursor, user_id: int, tenant_id: int, username: str, tenant_slug: str, role: str +) -> dict[str, Any]: token = secrets.token_urlsafe(32) - cur.execute(_q( - "INSERT INTO {c}.sessions (token_hash, user_id, tenant_id, expires_at) " - "VALUES (%s, %s, %s, now() + make_interval(hours => %s)) RETURNING expires_at"), - (_token_hash(token), user_id, tenant_id, settings.SESSION_TTL_HOURS)) + cur.execute( + _q( + "INSERT INTO {c}.sessions (token_hash, user_id, tenant_id, expires_at) " + "VALUES (%s, %s, %s, now() + make_interval(hours => %s)) RETURNING expires_at" + ), + (_token_hash(token), user_id, tenant_id, settings.SESSION_TTL_HOURS), + ) expires_at = fetch_one(cur)[0] - return {"token": token, "expiresAt": expires_at.isoformat(), "username": username, - "tenant": tenant_slug, "role": role} + return { + "token": token, + "expiresAt": expires_at.isoformat(), + "username": username, + "tenant": tenant_slug, + "role": role, + } def _record_failure(cur: cursor, user_id: int) -> None: """Count a wrong password; lock the account once the window's limit is reached (#102).""" - cur.execute(_q( - "UPDATE {c}.users SET " - "failed_logins = CASE WHEN first_failed_at > now() - make_interval(mins => %(m)s) " - " THEN failed_logins + 1 ELSE 1 END, " - "first_failed_at = CASE WHEN first_failed_at > now() - make_interval(mins => %(m)s) " - " THEN first_failed_at ELSE now() END " - "WHERE id = %(id)s RETURNING failed_logins"), - {"m": settings.LOGIN_LOCKOUT_MINUTES, "id": user_id}) + cur.execute( + _q( + "UPDATE {c}.users SET " + "failed_logins = CASE WHEN first_failed_at > now() - make_interval(mins => %(m)s) " + " THEN failed_logins + 1 ELSE 1 END, " + "first_failed_at = CASE WHEN first_failed_at > now() - make_interval(mins => %(m)s) " + " THEN first_failed_at ELSE now() END " + "WHERE id = %(id)s RETURNING failed_logins" + ), + {"m": settings.LOGIN_LOCKOUT_MINUTES, "id": user_id}, + ) if fetch_one(cur)[0] >= settings.LOGIN_MAX_FAILURES: - cur.execute(_q("UPDATE {c}.users SET locked_until = now() + make_interval(mins => %s) " - "WHERE id = %s"), (settings.LOGIN_LOCKOUT_MINUTES, user_id)) + cur.execute( + _q("UPDATE {c}.users SET locked_until = now() + make_interval(mins => %s) WHERE id = %s"), + (settings.LOGIN_LOCKOUT_MINUTES, user_id), + ) def session_for(cur: cursor, token: str) -> dict[str, Any] | None: @@ -225,21 +259,31 @@ def session_for(cur: cursor, token: str) -> dict[str, Any] | None: minutes (#296). A hit records the use; the caller commits, or the record is lost. """ idle = settings.SESSION_IDLE_MINUTES - cur.execute(_q( - "SELECT u.id, u.username, t.id, t.slug, m.role, s.expires_at, t.allow_self_approval " - "FROM {c}.sessions s " - "JOIN {c}.users u ON u.id = s.user_id AND u.is_active " - "JOIN {c}.tenants t ON t.id = s.tenant_id " - "JOIN {c}.memberships m ON m.user_id = u.id AND m.tenant_id = t.id " - "WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > now() " - "AND (%s <= 0 OR s.last_seen_at > now() - make_interval(mins => %s))"), - (_token_hash(token), idle, idle)) + cur.execute( + _q( + "SELECT u.id, u.username, t.id, t.slug, m.role, s.expires_at, t.allow_self_approval " + "FROM {c}.sessions s " + "JOIN {c}.users u ON u.id = s.user_id AND u.is_active " + "JOIN {c}.tenants t ON t.id = s.tenant_id " + "JOIN {c}.memberships m ON m.user_id = u.id AND m.tenant_id = t.id " + "WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > now() " + "AND (%s <= 0 OR s.last_seen_at > now() - make_interval(mins => %s))" + ), + (_token_hash(token), idle, idle), + ) row = cur.fetchone() if not row: return None _touch(cur, _token_hash(token)) - return {"userId": row[0], "username": row[1], "tenantId": row[2], "tenant": row[3], - "role": row[4], "expiresAt": row[5].isoformat(), "allowSelfApproval": bool(row[6])} + return { + "userId": row[0], + "username": row[1], + "tenantId": row[2], + "tenant": row[3], + "role": row[4], + "expiresAt": row[5].isoformat(), + "allowSelfApproval": bool(row[6]), + } def _touch(cur: cursor, token_hash: str) -> None: @@ -249,10 +293,14 @@ def _touch(cur: cursor, token_hash: str) -> None: looks idle because the write was skipped. """ idle = settings.SESSION_IDLE_MINUTES - gap = max(1, min(60, idle * 15)) if idle > 0 else 60 # seconds: a quarter of the idle limit, at most a minute - cur.execute(_q("UPDATE {c}.sessions SET last_seen_at = now() " - "WHERE token_hash = %s AND last_seen_at < now() - make_interval(secs => %s)"), - (token_hash, gap)) + gap = max(1, min(60, idle * 15)) if idle > 0 else 60 # seconds: a quarter of the idle limit, at most a minute + cur.execute( + _q( + "UPDATE {c}.sessions SET last_seen_at = now() " + "WHERE token_hash = %s AND last_seen_at < now() - make_interval(secs => %s)" + ), + (token_hash, gap), + ) def purge_sessions(cur: cursor) -> int: @@ -261,29 +309,42 @@ def purge_sessions(cur: cursor) -> int: Ended means expired, revoked, or (when the idle limit is on) idle for longer than the limit. A live session, one that ended recently, and every user and membership are left alone. The caller commits. """ - cur.execute(_q( - "DELETE FROM {c}.sessions WHERE " - "expires_at < now() - make_interval(days => %(grace)s) " - "OR revoked_at < now() - make_interval(days => %(grace)s) " - "OR (%(idle)s > 0 AND last_seen_at < now() - make_interval(days => %(grace)s) " - " - make_interval(mins => %(idle)s))"), - {"grace": settings.SESSION_PURGE_GRACE_DAYS, "idle": settings.SESSION_IDLE_MINUTES}) + cur.execute( + _q( + "DELETE FROM {c}.sessions WHERE " + "expires_at < now() - make_interval(days => %(grace)s) " + "OR revoked_at < now() - make_interval(days => %(grace)s) " + "OR (%(idle)s > 0 AND last_seen_at < now() - make_interval(days => %(grace)s) " + " - make_interval(mins => %(idle)s))" + ), + {"grace": settings.SESSION_PURGE_GRACE_DAYS, "idle": settings.SESSION_IDLE_MINUTES}, + ) return cur.rowcount def revoke(cur: cursor, token: str) -> None: - cur.execute(_q("UPDATE {c}.sessions SET revoked_at = now() " - "WHERE token_hash = %s AND revoked_at IS NULL"), (_token_hash(token),)) + cur.execute( + _q("UPDATE {c}.sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL"), + (_token_hash(token),), + ) def _set_password(cur: cursor, user_id: int, password: str, keep_token: str | None = None) -> None: """New hash, lockout cleared, and every session revoked except ``keep_token`` (#117).""" - cur.execute(_q("UPDATE {c}.users SET password_hash = %s, failed_logins = 0, " - "first_failed_at = NULL, locked_until = NULL WHERE id = %s"), - (hash_password(password), user_id)) - cur.execute(_q("UPDATE {c}.sessions SET revoked_at = now() WHERE user_id = %s " - "AND revoked_at IS NULL AND token_hash IS DISTINCT FROM %s"), - (user_id, _token_hash(keep_token) if keep_token else None)) + cur.execute( + _q( + "UPDATE {c}.users SET password_hash = %s, failed_logins = 0, " + "first_failed_at = NULL, locked_until = NULL WHERE id = %s" + ), + (hash_password(password), user_id), + ) + cur.execute( + _q( + "UPDATE {c}.sessions SET revoked_at = now() WHERE user_id = %s " + "AND revoked_at IS NULL AND token_hash IS DISTINCT FROM %s" + ), + (user_id, _token_hash(keep_token) if keep_token else None), + ) def change_password(cur: cursor, user_id: int, token: str, current: str, new: str) -> bool: @@ -304,11 +365,15 @@ def reset_password(cur: cursor, tenant_id: int, username: str, new: str) -> str: of its sessions. Returns "ok", "missing" (not a member of ``tenant_id``) or "shared": a user who is also in another tenant is refused, because the password is global and one tenant's admin must not take over the others.""" - cur.execute(_q("SELECT u.id, EXISTS (SELECT 1 FROM {c}.memberships o " - "WHERE o.user_id = u.id AND o.tenant_id <> %s) " - "FROM {c}.users u JOIN {c}.memberships m " - "ON m.user_id = u.id AND m.tenant_id = %s WHERE u.username = %s"), - (tenant_id, tenant_id, username)) + cur.execute( + _q( + "SELECT u.id, EXISTS (SELECT 1 FROM {c}.memberships o " + "WHERE o.user_id = u.id AND o.tenant_id <> %s) " + "FROM {c}.users u JOIN {c}.memberships m " + "ON m.user_id = u.id AND m.tenant_id = %s WHERE u.username = %s" + ), + (tenant_id, tenant_id, username), + ) row = cur.fetchone() if not row: return "missing" diff --git a/api/services/audit.py b/api/services/audit.py index 1c77d49..9a2a387 100644 --- a/api/services/audit.py +++ b/api/services/audit.py @@ -17,23 +17,24 @@ import json import logging +from collections.abc import Iterator from contextlib import contextmanager from contextvars import ContextVar +from typing import Any from psycopg2 import sql +from psycopg2.extensions import cursor from api.db import fetch_one from api.tenancy import uploads_schema -from typing import Any -from psycopg2.extensions import cursor -from collections.abc import Iterator logger = logging.getLogger(__name__) # Actions the log is allowed to record. A typo becomes a loud failure here rather # than an unqueryable string in the table. -VALID_ACTIONS = frozenset({"upload", "delete", "password_reset", "row_decision", "cell_edit", - "submit", "approve", "reject", "import"}) +VALID_ACTIONS = frozenset( + {"upload", "delete", "password_reset", "row_decision", "cell_edit", "submit", "approve", "reject", "import"} +) # Who is acting (M3a, #107). tenant_scope sets it per request: the signed-in # username, or "anonymous" under the local-dev anonymous opt-in (#298; the shared @@ -54,9 +55,16 @@ def acting_as(actor: str) -> Iterator[None]: _actor.reset(token) -def write_audit(cur: cursor, action: str, file_id: int | None, file_name: str | None, - table_name: str | None, mode: str | None, - before: dict[str, Any] | None = None, after: dict[str, Any] | None = None) -> None: +def write_audit( + cur: cursor, + action: str, + file_id: int | None, + file_name: str | None, + table_name: str | None, + mode: str | None, + before: dict[str, Any] | None = None, + after: dict[str, Any] | None = None, +) -> None: """Insert one audit row using the caller's cursor. Use this when you already hold a transaction and want the audit row to @@ -71,9 +79,16 @@ def write_audit(cur: cursor, action: str, file_id: int | None, file_name: str | "(action, file_id, file_name, table_name, mode, actor, before_value, after_value) " "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)" ).format(sql.Identifier(uploads_schema())), - (action, file_id, file_name, table_name, mode, _actor.get(), - None if before is None else json.dumps(before), - None if after is None else json.dumps(after)), + ( + action, + file_id, + file_name, + table_name, + mode, + _actor.get(), + None if before is None else json.dumps(before), + None if after is None else json.dumps(after), + ), ) @@ -81,13 +96,15 @@ def verify_chain(cur: cursor) -> dict[str, Any]: """Recompute the audit hash chain (M3a). Returns the row count and the first row whose link or hash doesn't match, or None if the chain is intact.""" schema = sql.Identifier(uploads_schema()) - cur.execute(sql.SQL( - "SELECT count(*), min(id) FILTER (WHERE prev_hash IS DISTINCT FROM expected_prev " - " OR row_hash IS DISTINCT FROM {s}.audit_row_hash(prev_hash, r)) " - "FROM (SELECT a AS r, a.id, a.prev_hash, a.row_hash, " - " lag(a.row_hash) OVER (ORDER BY a.id) AS expected_prev " - " FROM {s}.audit_log a) t" - ).format(s=schema)) + cur.execute( + sql.SQL( + "SELECT count(*), min(id) FILTER (WHERE prev_hash IS DISTINCT FROM expected_prev " + " OR row_hash IS DISTINCT FROM {s}.audit_row_hash(prev_hash, r)) " + "FROM (SELECT a AS r, a.id, a.prev_hash, a.row_hash, " + " lag(a.row_hash) OVER (ORDER BY a.id) AS expected_prev " + " FROM {s}.audit_log a) t" + ).format(s=schema) + ) rows, first_bad = fetch_one(cur) return {"rows": rows, "intact": first_bad is None, "firstBadId": first_bad} diff --git a/api/services/csv_parse.py b/api/services/csv_parse.py index f8dc1af..5563f44 100644 --- a/api/services/csv_parse.py +++ b/api/services/csv_parse.py @@ -10,9 +10,9 @@ import csv import io import re +from collections.abc import Callable from datetime import datetime, timezone from typing import Any, Optional -from collections.abc import Callable ALLOWED_TYPES = ["int8", "numeric", "date", "timestamptz", "boolean", "text"] @@ -175,9 +175,7 @@ def _base_column_name(header: str, idx: int) -> str: return base -def apply_header_mapping( - headers: list[str], mapping: list[dict[str, Any]] | None -) -> tuple[list[str], str | None]: +def apply_header_mapping(headers: list[str], mapping: list[dict[str, Any]] | None) -> tuple[list[str], str | None]: """Apply user-confirmed header renames (#186) to the raw header row. ``mapping`` is a list of ``{"original": ..., "renamed": ...}``. A blank @@ -206,8 +204,10 @@ def apply_header_mapping( for base, idxs in by_base.items(): if len(idxs) > 1 and renamed_idx.intersection(idxs): clash = next(i for i in idxs if i in renamed_idx) - return headers, (f'Renaming a column to "{mapped[clash]}" would give two columns the ' - f'name "{base}". Choose a different name.') + return headers, ( + f'Renaming a column to "{mapped[clash]}" would give two columns the ' + f'name "{base}". Choose a different name.' + ) return mapped, None @@ -222,8 +222,10 @@ def extra_cells(raw: list[str], width: int) -> list[str]: def ragged_row_reason(raw: list[str], width: int) -> str: - return (f"Row has {len(raw)} cells but the header has {width}; " - f"the extra value(s) would be lost, so the row was not imported.") + return ( + f"Row has {len(raw)} cells but the header has {width}; " + f"the extra value(s) would be lost, so the row was not imported." + ) def valid_identifier(name: str) -> bool: diff --git a/api/services/destructive_ops.py b/api/services/destructive_ops.py index 796ec7c..7d1bfd1 100644 --- a/api/services/destructive_ops.py +++ b/api/services/destructive_ops.py @@ -7,12 +7,13 @@ from __future__ import annotations +from typing import Any + from fastapi import HTTPException from psycopg2 import sql +from psycopg2.extensions import cursor from api.auth import PERMISSIONS -from typing import Any -from psycopg2.extensions import cursor def authorized_drop_table(cur: cursor, session: dict[str, Any] | None, schema: str, table_name: str) -> None: @@ -24,15 +25,10 @@ def authorized_drop_table(cur: cursor, session: dict[str, Any] | None, schema: s Raises HTTP 403 if the session's role lacks ``delete_file``. """ _require_delete(session) - cur.execute( - sql.SQL("DROP TABLE IF EXISTS {}.{}").format( - sql.Identifier(schema), sql.Identifier(table_name) - ) - ) + cur.execute(sql.SQL("DROP TABLE IF EXISTS {}.{}").format(sql.Identifier(schema), sql.Identifier(table_name))) -def safe_cleanup_prior(cur: cursor, session: dict[str, Any] | None, schema: str, - table_name: str, mode: str) -> None: +def safe_cleanup_prior(cur: cursor, session: dict[str, Any] | None, schema: str, table_name: str, mode: str) -> None: """Drop a prior dynamic-mode table during overwrite, with auth check. Only drops when the prior entry is dynamic mode and the table name starts @@ -41,11 +37,7 @@ def safe_cleanup_prior(cur: cursor, session: dict[str, Any] | None, schema: str, """ _require_delete(session) if mode == "dynamic" and table_name.startswith("csv_"): - cur.execute( - sql.SQL("DROP TABLE IF EXISTS {}.{}").format( - sql.Identifier(schema), sql.Identifier(table_name) - ) - ) + cur.execute(sql.SQL("DROP TABLE IF EXISTS {}.{}").format(sql.Identifier(schema), sql.Identifier(table_name))) def _require_delete(session: dict[str, Any] | None) -> None: diff --git a/api/services/dynamic_loader.py b/api/services/dynamic_loader.py index 59d6dc9..ba92d38 100644 --- a/api/services/dynamic_loader.py +++ b/api/services/dynamic_loader.py @@ -16,8 +16,8 @@ import logging import re from collections.abc import Callable -from typing import Any from dataclasses import dataclass, field +from typing import Any import psycopg2.errors from psycopg2 import sql @@ -25,7 +25,6 @@ from psycopg2.extras import execute_values from api.config import settings -from api.tenancy import uploads_schema from api.db import Conn, fetch_one from api.services.csv_parse import ( ALLOWED_TYPES, @@ -38,6 +37,7 @@ from api.services.load_common import RowErrors, ok_result, ragged, rows_failed, too_many_rows from api.services.load_common import log as _log from api.services.results import DuplicateFlag, LoadResult, LogEntry, SchemaCheck +from api.tenancy import uploads_schema logger = logging.getLogger(__name__) @@ -60,31 +60,45 @@ def dataset_slug(file_name: str) -> str: return s[:40].strip("_") or "dataset" -_SYSTEM_COLUMNS = ("_id", "_row_hash", "_created_at", "_source_row_id", "_import_id") # the last two: staged imports (M6) +_SYSTEM_COLUMNS = ( + "_id", + "_row_hash", + "_created_at", + "_source_row_id", + "_import_id", +) # the last two: staged imports (M6) _UDT = {"boolean": "bool"} # information_schema udt_name where it differs from our type name -def _schema_diff(cur: cursor, schema: str, prior_table: str, columns: list[str], - col_types: list[str]) -> SchemaCheck | None: +def _schema_diff( + cur: cursor, schema: str, prior_table: str, columns: list[str], col_types: list[str] +) -> SchemaCheck | None: """How the new columns compare with the previous version's. None if that table is gone. Additions are compatible; a removed or retyped column is not. Informational only: the previous version's table is never altered, so nothing destructive can happen here. """ - cur.execute("SELECT column_name, udt_name FROM information_schema.columns " - "WHERE table_schema = %s AND table_name = %s", (schema, prior_table)) + cur.execute( + "SELECT column_name, udt_name FROM information_schema.columns WHERE table_schema = %s AND table_name = %s", + (schema, prior_table), + ) old = {n: t for n, t in cur.fetchall() if n not in _SYSTEM_COLUMNS} if not old: return None new = {c: _UDT.get(t, t) for c, t in zip(columns, col_types)} removed = [c for c in old if c not in new] changed = [{"column": c, "was": old[c], "now": new[c]} for c in new if c in old and old[c] != new[c]] - return {"compatible": not removed and not changed, - "added": [c for c in new if c not in old], "removed": removed, "changed": changed} + return { + "compatible": not removed and not changed, + "added": [c for c in new if c not in old], + "removed": removed, + "changed": changed, + } -def _earlier_version_matches(cur: cursor, schema: str, priors: list[tuple[Any, ...]], hashes: list[str], - rows: list[int]) -> list[DuplicateFlag]: +def _earlier_version_matches( + cur: cursor, schema: str, priors: list[tuple[Any, ...]], hashes: list[str], rows: list[int] +) -> list[DuplicateFlag]: """Rows (by number) whose hash is already in an earlier version's table. Newest matching version wins. ``priors`` is newest first: (registry id, file name, table name, version). A prior whose @@ -101,8 +115,12 @@ def _earlier_version_matches(cur: cursor, schema: str, priors: list[tuple[Any, . cur.execute("SAVEPOINT prior_table") try: for i in range(0, len(todo), 5000): - cur.execute(sql.SQL("SELECT _row_hash FROM {}.{} WHERE _row_hash = ANY(%s)").format( - sql.Identifier(schema), sql.Identifier(table_name)), (todo[i:i + 5000],)) + cur.execute( + sql.SQL("SELECT _row_hash FROM {}.{} WHERE _row_hash = ANY(%s)").format( + sql.Identifier(schema), sql.Identifier(table_name) + ), + (todo[i : i + 5000],), + ) hits += [h for (h,) in cur.fetchall()] except psycopg2.errors.UndefinedTable: cur.execute("ROLLBACK TO SAVEPOINT prior_table") @@ -110,8 +128,14 @@ def _earlier_version_matches(cur: cursor, schema: str, priors: list[tuple[Any, . cur.execute("RELEASE SAVEPOINT prior_table") for h in hits: pending.discard(h) - flags.append({"rowNumber": by_hash[h], "matchedFileId": str(file_id), - "matchedFileName": file_name, "matchedVersion": version}) + flags.append( + { + "rowNumber": by_hash[h], + "matchedFileId": str(file_id), + "matchedFileName": file_name, + "matchedVersion": version, + } + ) return sorted(flags, key=lambda f: f["rowNumber"]) @@ -162,8 +186,18 @@ def upload_dynamic( provenance = "user_confirmed" if (types and types_confirmed) else "inferred_unconfirmed" try: - return _do_upload(file_name, types, overwrite, logs, schema, rows, file_hash, - session=session, types_provenance=provenance, on_commit=on_commit) + return _do_upload( + file_name, + types, + overwrite, + logs, + schema, + rows, + file_hash, + session=session, + types_provenance=provenance, + on_commit=on_commit, + ) except psycopg2.errors.UniqueViolation: # #81: an identical concurrent upload won a race that _do_upload could # not settle itself (e.g. both creating csv_ at once). Nothing @@ -216,8 +250,9 @@ def _structure_problem(rows: list[list[str]], logs: list[LogEntry]) -> LoadResul return None -def _apply_header_mapping(rows: list[list[str]], header_mapping: list[dict[str, Any]] | None, - logs: list[LogEntry]) -> tuple[list[list[str]], LoadResult | None]: +def _apply_header_mapping( + rows: list[list[str]], header_mapping: list[dict[str, Any]] | None, logs: list[LogEntry] +) -> tuple[list[list[str]], LoadResult | None]: """``rows`` with the confirmed header renames applied (#186), or the error response for an invalid mapping.""" mapped_headers, mapping_error = apply_header_mapping(rows[0], header_mapping) if mapping_error: @@ -251,7 +286,9 @@ def _do_upload( # ponytail: held through row casting; take it just before the insert if big same-name uploads queue. cur.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (f"{schema}.{dataset}",)) if overwrite: - _log(logs, "overwrite", "Overwrite is not supported (decision 2): storing a new version instead", "warn") + _log( + logs, "overwrite", "Overwrite is not supported (decision 2): storing a new version instead", "warn" + ) duplicate = _same_content(cur, schema, file_hash, logs) if duplicate: @@ -287,31 +324,82 @@ def _do_upload( # still loaded, but flagged. The user decides per row (decision 3), through review. flags = _earlier_version_matches(cur, schema, priors, [r[-1] for r in cast.to_insert], cast.insert_rows) if flags: - _log(logs, "cross_upload_duplicates", f"{len(flags)} rows already exist in an earlier version", - "warn", count=len(flags)) + _log( + logs, + "cross_upload_duplicates", + f"{len(flags)} rows already exist in an earlier version", + "warn", + count=len(flags), + ) inserted = _insert(cur, schema, table_name, columns, cast.to_insert) _log(logs, "insert", f"Inserted {inserted} rows", count=inserted) - registered = _register(conn, cur, schema, file_name, file_hash, table_name, inserted, columns, - len(data_rows), cast, types_provenance, dataset, version, logs) + registered = _register( + conn, + cur, + schema, + file_name, + file_hash, + table_name, + inserted, + columns, + len(data_rows), + cast, + types_provenance, + dataset, + version, + logs, + ) if isinstance(registered, dict): return registered _log(logs, "done", f"Import complete for {file_name}") - result = _ok(registered, table_name, len(data_rows), inserted, cast, columns, col_types, - types_provenance, logs, dataset, version, schema_check, flags) + result = _ok( + registered, + table_name, + len(data_rows), + inserted, + cast, + columns, + col_types, + types_provenance, + logs, + dataset, + version, + schema_check, + flags, + ) if on_commit is not None: on_commit(cur, result) conn.commit() return result -def _ok(file_id: object, table_name: str, total_rows: int, inserted: int, cast: CastRows, columns: list[str], - col_types: list[str], types_provenance: str, logs: list[LogEntry], dataset: str, version: int, - schema_check: SchemaCheck | None, flags: list[DuplicateFlag]) -> LoadResult: +def _ok( + file_id: object, + table_name: str, + total_rows: int, + inserted: int, + cast: CastRows, + columns: list[str], + col_types: list[str], + types_provenance: str, + logs: list[LogEntry], + dataset: str, + version: int, + schema_check: SchemaCheck | None, + flags: list[DuplicateFlag], +) -> LoadResult: return ok_result( - file_id, table_name, total_rows, inserted, cast.duplicates, cast.errors.failed, columns, col_types, + file_id, + table_name, + total_rows, + inserted, + cast.duplicates, + cast.errors.failed, + columns, + col_types, typesProvenance=types_provenance, rowErrors=cast.errors.items, logs=logs, @@ -319,7 +407,7 @@ def _ok(file_id: object, table_name: str, total_rows: int, inserted: int, cast: version=version, schemaCheck=schema_check, duplicateRowsAcrossUploads=len(flags), - crossUploadDuplicates=flags[:settings.MAX_ROW_ERRORS_REPORTED], + crossUploadDuplicates=flags[: settings.MAX_ROW_ERRORS_REPORTED], # Full list for store_upload, which stores it; the route removes it before replying. _duplicateFlags=flags, # Never overwritten (decision 2). Kept so older clients reading these fields still work. @@ -332,9 +420,9 @@ def _same_content(cur: cursor, schema: str, file_hash: str, logs: list[LogEntry] """Exact-file duplicate check (BR-28). The registry is per tenant, so this is a per-tenant check.""" _log(logs, "duplicate_check", "Checking existing content hash") cur.execute( - sql.SQL( - "SELECT file_name, table_name, row_count FROM {}.csv_files WHERE file_hash = %s" - ).format(sql.Identifier(schema)), + sql.SQL("SELECT file_name, table_name, row_count FROM {}.csv_files WHERE file_hash = %s").format( + sql.Identifier(schema) + ), (file_hash,), ) content_match = cur.fetchone() @@ -355,8 +443,7 @@ def _versions(cur: cursor, schema: str, dataset: str, logs: list[LogEntry]) -> t """Earlier versions of this dataset, newest first, and the version this upload becomes.""" cur.execute( sql.SQL( - "SELECT id, file_name, table_name, version FROM {}.csv_files " - "WHERE dataset = %s ORDER BY version DESC" + "SELECT id, file_name, table_name, version FROM {}.csv_files WHERE dataset = %s ORDER BY version DESC" ).format(sql.Identifier(schema)), (dataset,), ) @@ -366,8 +453,9 @@ def _versions(cur: cursor, schema: str, dataset: str, logs: list[LogEntry]) -> t return priors, version -def _columns_and_types(header: list[str], types: list[str] | None, - logs: list[LogEntry]) -> tuple[list[str], list[str]] | LoadResult: +def _columns_and_types( + header: list[str], types: list[str] | None, logs: list[LogEntry] +) -> tuple[list[str], list[str]] | LoadResult: """The table's column names and types, or the error response if the header or the types cannot be used.""" columns = sanitize_columns(header) if not columns: @@ -398,27 +486,37 @@ def _columns_and_types(header: list[str], types: list[str] | None, return columns, col_types -def _compare_with_previous(cur: cursor, schema: str, priors: list[tuple[Any, ...]], columns: list[str], col_types: list[str], - logs: list[LogEntry]) -> SchemaCheck | None: +def _compare_with_previous( + cur: cursor, + schema: str, + priors: list[tuple[Any, ...]], + columns: list[str], + col_types: list[str], + logs: list[LogEntry], +) -> SchemaCheck | None: """How the columns compare with the previous version's. Informational: its table is never altered.""" if not priors: return None schema_check = _schema_diff(cur, schema, priors[0][2], columns, col_types) if schema_check: - schema_check["comparedTo"] = {"fileName": priors[0][1], "version": priors[0][3], - "tableName": priors[0][2]} - _log(logs, "schema_check", "Columns match the previous version" if schema_check["compatible"] - else "Columns differ from the previous version", - "info" if schema_check["compatible"] else "warn") + schema_check["comparedTo"] = {"fileName": priors[0][1], "version": priors[0][3], "tableName": priors[0][2]} + _log( + logs, + "schema_check", + "Columns match the previous version" + if schema_check["compatible"] + else "Columns differ from the previous version", + "info" if schema_check["compatible"] else "warn", + ) return schema_check -def _create_table(cur: cursor, schema: str, table_name: str, columns: list[str], col_types: list[str], - logs: list[LogEntry]) -> None: +def _create_table( + cur: cursor, schema: str, table_name: str, columns: list[str], col_types: list[str], logs: list[LogEntry] +) -> None: """Plain CREATE, not IF NOT EXISTS: a name clash must fail, not append to a stranger's table.""" col_defs = sql.SQL(", ").join( - sql.SQL("{} {}").format(sql.Identifier(c), sql.SQL(_TYPE_SQL[t])) - for c, t in zip(columns, col_types) + sql.SQL("{} {}").format(sql.Identifier(c), sql.SQL(_TYPE_SQL[t])) for c, t in zip(columns, col_types) ) _log(logs, "create_table", f"create table {table_name} ({len(columns)} cols)") cur.execute( @@ -445,9 +543,9 @@ def row_hash(cells: list[str]) -> str: A U+001F join was vulnerable: cells containing U+001F caused distinct rows to hash identically (silent data loss). """ - return "v2:" + hashlib.sha256( - json.dumps(cells, ensure_ascii=False, separators=(",", ":")).encode("utf-8") - ).hexdigest() + return ( + "v2:" + hashlib.sha256(json.dumps(cells, ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest() + ) def cast_rows(data_rows: list[list[str]], columns: list[str], col_types: list[str]) -> CastRows: @@ -472,8 +570,9 @@ def cast_rows(data_rows: list[list[str]], columns: list[str], col_types: list[st return out -def _cast_cells(raw: list[str], columns: list[str], col_types: list[str], row_number: int, - errors: RowErrors) -> tuple[list[Any], list[str]] | None: +def _cast_cells( + raw: list[str], columns: list[str], col_types: list[str], row_number: int, errors: RowErrors +) -> tuple[list[Any], list[str]] | None: """The cast values and raw cells of one row (a short row's missing cells are empty), or None if a cell failed.""" values: list[Any] = [] cells: list[str] = [] @@ -488,8 +587,9 @@ def _cast_cells(raw: list[str], columns: list[str], col_types: list[str], row_nu return values, cells -def _every_row_failed(errors: RowErrors, total_rows: int, columns: list[str], col_types: list[str], - logs: list[LogEntry]) -> LoadResult: +def _every_row_failed( + errors: RowErrors, total_rows: int, columns: list[str], col_types: list[str], logs: list[LogEntry] +) -> LoadResult: msg = f"None of the {total_rows} rows could be imported, so nothing was saved." e = errors.first() if e: @@ -502,28 +602,37 @@ def _insert(cur: cursor, schema: str, table_name: str, columns: list[str], to_in inserted = 0 if not to_insert: return inserted - insert_cols = sql.SQL(", ").join( - [sql.Identifier(c) for c in columns] + [sql.Identifier("_row_hash")] - ) + insert_cols = sql.SQL(", ").join([sql.Identifier(c) for c in columns] + [sql.Identifier("_row_hash")]) # RETURNING + fetch=True is deliberate: execute_values pages at 100 # by default and cur.rowcount reflects only the last page, which # under-counted every file over 100 rows. Counting returned rows is # page-size independent. See docs/DEFECT_INSERTED_ROWS.md. - stmt = sql.SQL( - "INSERT INTO {}.{} ({}) VALUES %s " - "ON CONFLICT (_row_hash) DO NOTHING RETURNING 1" - ).format(sql.Identifier(schema), sql.Identifier(table_name), insert_cols) + stmt = sql.SQL("INSERT INTO {}.{} ({}) VALUES %s ON CONFLICT (_row_hash) DO NOTHING RETURNING 1").format( + sql.Identifier(schema), sql.Identifier(table_name), insert_cols + ) for i in range(0, len(to_insert), 500): - chunk = to_insert[i:i + 500] - returned = execute_values( - cur, stmt.as_string(cur), chunk, fetch=True) + chunk = to_insert[i : i + 500] + returned = execute_values(cur, stmt.as_string(cur), chunk, fetch=True) inserted += len(returned) return inserted -def _register(conn: connection, cur: cursor, schema: str, file_name: str, file_hash: str, table_name: str, inserted: int, - columns: list[str], total_rows: int, cast: CastRows, types_provenance: str, dataset: str, - version: int, logs: list[LogEntry]) -> int | LoadResult: +def _register( + conn: connection, + cur: cursor, + schema: str, + file_name: str, + file_hash: str, + table_name: str, + inserted: int, + columns: list[str], + total_rows: int, + cast: CastRows, + types_provenance: str, + dataset: str, + version: int, + logs: list[LogEntry], +) -> int | LoadResult: """Add the upload to csv_files and return its id, or the "duplicate_file" response if it lost a race. The duplicate checks above are racy (check-then-act, no lock held across the row-casting work), so a @@ -538,16 +647,26 @@ def _register(conn: connection, cur: cursor, schema: str, file_name: str, file_h "total_rows, duplicate_rows_skipped, failed_rows, types_provenance, dataset, version) " "VALUES (%s, %s, %s, 'dynamic', %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id" ).format(sql.Identifier(schema)), - (file_name, file_hash, table_name, inserted, columns, - total_rows, cast.duplicates, cast.errors.failed, types_provenance, dataset, version), + ( + file_name, + file_hash, + table_name, + inserted, + columns, + total_rows, + cast.duplicates, + cast.errors.failed, + types_provenance, + dataset, + version, + ), ) return int(fetch_one(cur)[0]) except psycopg2.errors.UniqueViolation: conn.rollback() cur.execute( sql.SQL( - "SELECT file_name, table_name, row_count FROM {}.csv_files " - "WHERE file_name = %s OR file_hash = %s" + "SELECT file_name, table_name, row_count FROM {}.csv_files WHERE file_name = %s OR file_hash = %s" ).format(sql.Identifier(schema)), (file_name, file_hash), ) diff --git a/api/services/load_common.py b/api/services/load_common.py index a7d103b..d02726f 100644 --- a/api/services/load_common.py +++ b/api/services/load_common.py @@ -78,23 +78,35 @@ def too_many_rows(data_row_count: int, logs: list[LogEntry]) -> LoadResult | Non } -def rows_failed(text: str, errors: RowErrors, total_rows: int, entries: list[LogEntry], - **fields: Unpack[LoadFields]) -> LoadResult: +def rows_failed( + text: str, errors: RowErrors, total_rows: int, entries: list[LogEntry], **fields: Unpack[LoadFields] +) -> LoadResult: """The response when rows failed and nothing was saved (#123, #170, #289). ``text`` is the message and ``entries`` the logs. ``fields`` follow ``failedRows`` and come before ``logs``, in the order given (tests/system/test_loader_responses_golden.py pins the order). """ log(entries, "error", text, "error") - result: LoadResult = {"status": "error", "message": text, "rowErrors": errors.items, - "totalRows": total_rows, "failedRows": errors.failed} + result: LoadResult = { + "status": "error", + "message": text, + "rowErrors": errors.items, + "totalRows": total_rows, + "failedRows": errors.failed, + } result.update(cast(LoadResult, fields)) # the keywords were checked against LoadFields at the call result["logs"] = entries return result -def insert_with_row_fallback(cur: cursor, batch_stmt: sql.Composable, row_stmt: sql.Composable, - rows: Sequence[tuple[int, list[Any]]], errors: RowErrors, chunk_size: int = 500) -> int: +def insert_with_row_fallback( + cur: cursor, + batch_stmt: sql.Composable, + row_stmt: sql.Composable, + rows: Sequence[tuple[int, list[Any]]], + errors: RowErrors, + chunk_size: int = 500, +) -> int: """Insert ``(row number, values)`` pairs in batches; when a batch fails, retry it a row at a time. A constraint (FK, UNIQUE, CHECK) or a cast the database makes itself fails the whole batch, so the batch is @@ -103,7 +115,7 @@ def insert_with_row_fallback(cur: cursor, batch_stmt: sql.Composable, row_stmt: """ inserted = 0 for start in range(0, len(rows), chunk_size): - chunk = rows[start:start + chunk_size] + chunk = rows[start : start + chunk_size] cur.execute("SAVEPOINT chunk_sp") try: execute_values(cur, batch_stmt.as_string(cur), [v for _, v in chunk]) @@ -116,8 +128,9 @@ def insert_with_row_fallback(cur: cursor, batch_stmt: sql.Composable, row_stmt: return inserted -def _insert_one_by_one(cur: cursor, row_stmt: sql.Composable, chunk: Sequence[tuple[int, list[Any]]], - errors: RowErrors) -> int: +def _insert_one_by_one( + cur: cursor, row_stmt: sql.Composable, chunk: Sequence[tuple[int, list[Any]]], errors: RowErrors +) -> int: inserted = 0 for row_number, values in chunk: cur.execute("SAVEPOINT row_sp") @@ -132,12 +145,29 @@ def _insert_one_by_one(cur: cursor, row_stmt: sql.Composable, chunk: Sequence[tu return inserted -def ok_result(file_id: object, table_name: str, total_rows: int, inserted: int, duplicates: int, failed: int, - cols: list[str], col_types: list[str], **fields: Unpack[LoadFields]) -> LoadResult: +def ok_result( + file_id: object, + table_name: str, + total_rows: int, + inserted: int, + duplicates: int, + failed: int, + cols: list[str], + col_types: list[str], + **fields: Unpack[LoadFields], +) -> LoadResult: """The "ok" response of a load: ``cols`` and ``col_types`` are its ``columns`` and ``types``. ``fields`` follow ``types``, in the order given.""" - result: LoadResult = {"status": "ok", "fileId": str(file_id), "tableName": table_name, "totalRows": total_rows, - "insertedRows": inserted, "duplicateRowsSkipped": duplicates, "failedRows": failed, - "columns": cols, "types": col_types} + result: LoadResult = { + "status": "ok", + "fileId": str(file_id), + "tableName": table_name, + "totalRows": total_rows, + "insertedRows": inserted, + "duplicateRowsSkipped": duplicates, + "failedRows": failed, + "columns": cols, + "types": col_types, + } result.update(cast(LoadResult, fields)) # the keywords were checked against LoadFields at the call return result diff --git a/api/services/originals.py b/api/services/originals.py index 34d9f4e..dddd819 100644 --- a/api/services/originals.py +++ b/api/services/originals.py @@ -18,15 +18,15 @@ import logging from psycopg2 import sql +from psycopg2.extensions import cursor from psycopg2.extras import Json, execute_values from api.config import settings from api.db import Conn, fetch_one from api.services.audit import coerce_file_id, current_actor from api.services.csv_parse import parse_csv -from api.tenancy import uploads_schema -from psycopg2.extensions import cursor from api.services.results import DuplicateFlag, LoadResult +from api.tenancy import uploads_schema logger = logging.getLogger(__name__) @@ -40,8 +40,16 @@ def outcome(result: LoadResult) -> str: return _STATUS.get(str(status), "failed") -def store_upload(cur: cursor, file_name: str, content: str, mode: str, result: LoadResult, *, - original: bytes | None = None, flags: list[DuplicateFlag] | None = None) -> int: +def store_upload( + cur: cursor, + file_name: str, + content: str, + mode: str, + result: LoadResult, + *, + original: bytes | None = None, + flags: list[DuplicateFlag] | None = None, +) -> int: """Insert the upload, its bytes, its parsed rows and any row flags using the caller's cursor. Raises on failure and doesn't commit: the staged flow (M6) treats a failed store as a failed @@ -58,34 +66,76 @@ def store_upload(cur: cursor, file_name: str, content: str, mode: str, result: L # Keep the reason a rejected or failed attempt was given, so reports can say why (M7, BR-35). if result.get("message") and not ok and not any(entry.get("message") == result["message"] for entry in logs): logs.append({"step": "result", "level": "error", "message": result["message"]}) - cur.execute(sql.SQL( - "INSERT INTO {}.uploads (file_name, sha256, byte_size, uploader, mode, status, " - "total_rows, imported_rows, failed_rows, csv_file_id, row_errors, logs, columns, column_types, " - "types_provenance) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id").format(s), - (file_name, hashlib.sha256(data).hexdigest(), len(data), current_actor(), mode, - outcome(result), result.get("totalRows"), result.get("insertedRows"), - result.get("failedRows"), coerce_file_id(result.get("fileId")) if ok else None, - Json((result.get("rowErrors") or [])[:settings.MAX_ROW_ERRORS_REPORTED]), - Json(logs), result.get("columns"), result.get("types"), result.get("typesProvenance"))) + cur.execute( + sql.SQL( + "INSERT INTO {}.uploads (file_name, sha256, byte_size, uploader, mode, status, " + "total_rows, imported_rows, failed_rows, csv_file_id, row_errors, logs, columns, column_types, " + "types_provenance) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id" + ).format(s), + ( + file_name, + hashlib.sha256(data).hexdigest(), + len(data), + current_actor(), + mode, + outcome(result), + result.get("totalRows"), + result.get("insertedRows"), + result.get("failedRows"), + coerce_file_id(result.get("fileId")) if ok else None, + Json((result.get("rowErrors") or [])[: settings.MAX_ROW_ERRORS_REPORTED]), + Json(logs), + result.get("columns"), + result.get("types"), + result.get("typesProvenance"), + ), + ) upload_id = int(fetch_one(cur)[0]) - cur.execute(sql.SQL("INSERT INTO {}.upload_blobs (upload_id, content) VALUES (%s, %s)").format(s), - (upload_id, data)) + cur.execute( + sql.SQL("INSERT INTO {}.upload_blobs (upload_id, content) VALUES (%s, %s)").format(s), (upload_id, data) + ) rows = parse_csv(content) # ponytail: second parse after the loader's; share it if uploads get slow if rows: - execute_values(cur, sql.SQL("INSERT INTO {}.source_rows (upload_id, row_number, cells) VALUES %s") - .format(s).as_string(cur), [(upload_id, n, r) for n, r in enumerate(rows)], - page_size=1000) + execute_values( + cur, + sql.SQL("INSERT INTO {}.source_rows (upload_id, row_number, cells) VALUES %s").format(s).as_string(cur), + [(upload_id, n, r) for n, r in enumerate(rows)], + page_size=1000, + ) if flags: - execute_values(cur, sql.SQL("INSERT INTO {}.row_flags (upload_id, row_number, kind, " - "matched_file_id, matched_file_name, matched_version) VALUES %s") - .format(s).as_string(cur), - [(upload_id, f["rowNumber"], "duplicate_of_earlier_version", int(f["matchedFileId"]), - f["matchedFileName"], f["matchedVersion"]) for f in flags], page_size=1000) + execute_values( + cur, + sql.SQL( + "INSERT INTO {}.row_flags (upload_id, row_number, kind, " + "matched_file_id, matched_file_name, matched_version) VALUES %s" + ) + .format(s) + .as_string(cur), + [ + ( + upload_id, + f["rowNumber"], + "duplicate_of_earlier_version", + int(f["matchedFileId"]), + f["matchedFileName"], + f["matchedVersion"], + ) + for f in flags + ], + page_size=1000, + ) return upload_id -def record_upload(file_name: str, content: str, mode: str, result: LoadResult, *, - original: bytes | None = None, flags: list[DuplicateFlag] | None = None) -> int | None: +def record_upload( + file_name: str, + content: str, + mode: str, + result: LoadResult, + *, + original: bytes | None = None, + flags: list[DuplicateFlag] | None = None, +) -> int | None: """Record an attempt that loaded nothing, in its own transaction. Returns the upload id, or None on failure.""" try: with Conn() as conn: diff --git a/api/services/results.py b/api/services/results.py index bdad32a..554c1eb 100644 --- a/api/services/results.py +++ b/api/services/results.py @@ -12,8 +12,9 @@ from typing import Any, Literal, NotRequired, Required, TypedDict - -Status = Literal["ok", "error", "duplicate_file", "invalid_structure", "staged"] # "staged": api/services/staged_import.stage +Status = Literal[ + "ok", "error", "duplicate_file", "invalid_structure", "staged" +] # "staged": api/services/staged_import.stage class LogEntry(TypedDict): diff --git a/api/services/review.py b/api/services/review.py index 67822d3..074e7fe 100644 --- a/api/services/review.py +++ b/api/services/review.py @@ -8,15 +8,16 @@ from __future__ import annotations +from typing import Any + from psycopg2 import sql +from psycopg2.extensions import cursor from api.db import fetch_one from api.services.audit import current_actor, write_audit from api.services.csv_parse import cast_value, extra_cells, ragged_row_reason, sanitize_columns from api.services.staged_import import state_of from api.tenancy import uploads_schema -from typing import Any -from psycopg2.extensions import cursor MAX_PAGE = 500 @@ -34,11 +35,15 @@ def _s() -> sql.Identifier: def _upload(cur: cursor, upload_id: int) -> dict[str, Any]: - cur.execute(sql.SQL( - "SELECT u.file_name, u.columns, u.column_types, h.cells, u.mode, u.row_errors, " - " (SELECT count(*) FROM {s}.source_rows r WHERE r.upload_id = u.id AND r.row_number > 0) " - "FROM {s}.uploads u LEFT JOIN {s}.source_rows h ON h.upload_id = u.id AND h.row_number = 0 " - "WHERE u.id = %s").format(s=_s()), (upload_id,)) + cur.execute( + sql.SQL( + "SELECT u.file_name, u.columns, u.column_types, h.cells, u.mode, u.row_errors, " + " (SELECT count(*) FROM {s}.source_rows r WHERE r.upload_id = u.id AND r.row_number > 0) " + "FROM {s}.uploads u LEFT JOIN {s}.source_rows h ON h.upload_id = u.id AND h.row_number = 0 " + "WHERE u.id = %s" + ).format(s=_s()), + (upload_id,), + ) row = cur.fetchone() if row is None: raise ReviewError(404, "No such upload") @@ -50,24 +55,36 @@ def _upload(cur: cursor, upload_id: int) -> dict[str, Any]: # type failures, which _validate finds again; these carry only the database's reason. # ponytail: stored list is capped at MAX_ROW_ERRORS_REPORTED, rows past the cap show no # database reason; edited rows aren't re-checked against constraints until M6's import. - db_errors = {e["rowNumber"]: e["reason"] for e in (stored_errors or []) - if mode == "te" and "column" not in e and "rowNumber" in e} + db_errors = { + e["rowNumber"]: e["reason"] + for e in (stored_errors or []) + if mode == "te" and "column" not in e and "rowNumber" in e + } return {"fileName": name, "columns": columns, "types": types, "total": total, "_dbErrors": db_errors} def _flags(cur: cursor, upload_id: int, numbers: list[int]) -> dict[str, Any]: """Rows that duplicate an earlier version of the dataset (M5, BR-29); the user decides per row.""" - cur.execute(sql.SQL( - "SELECT row_number, matched_file_name, matched_version FROM {}.row_flags " - "WHERE upload_id = %s AND row_number = ANY(%s)").format(_s()), (upload_id, numbers)) + cur.execute( + sql.SQL( + "SELECT row_number, matched_file_name, matched_version FROM {}.row_flags " + "WHERE upload_id = %s AND row_number = ANY(%s)" + ).format(_s()), + (upload_id, numbers), + ) return {n: {"fileName": f, "version": v} for n, f, v in cur.fetchall()} def _validate(cells: list[str], raw: list[str], columns: list[str], types: list[str]) -> list[dict[str, Any]]: errors: list[dict[str, Any]] = [] if extra_cells(raw, len(columns)): - errors.append({"column": "(beyond header)", "value": extra_cells(raw, len(columns))[0], - "reason": ragged_row_reason(raw, len(columns))}) + errors.append( + { + "column": "(beyond header)", + "value": extra_cells(raw, len(columns))[0], + "reason": ragged_row_reason(raw, len(columns)), + } + ) for name, value, col_type in zip(columns, cells, types): ok, _, reason = cast_value(value, col_type) if not ok: @@ -75,34 +92,56 @@ def _validate(cells: list[str], raw: list[str], columns: list[str], types: list[ return errors -def _latest(cur: cursor, upload_id: int, - numbers: list[int]) -> tuple[dict[int, dict[str, Any]], dict[int, dict[int, str]]]: +def _latest( + cur: cursor, upload_id: int, numbers: list[int] +) -> tuple[dict[int, dict[str, Any]], dict[int, dict[int, str]]]: """The current decision per row and the current value per edited cell.""" - cur.execute(sql.SQL( - "SELECT DISTINCT ON (row_number) row_number, decision, reason, actor FROM {}.row_decisions " - "WHERE upload_id = %s AND row_number = ANY(%s) ORDER BY row_number, id DESC").format(_s()), - (upload_id, numbers)) + cur.execute( + sql.SQL( + "SELECT DISTINCT ON (row_number) row_number, decision, reason, actor FROM {}.row_decisions " + "WHERE upload_id = %s AND row_number = ANY(%s) ORDER BY row_number, id DESC" + ).format(_s()), + (upload_id, numbers), + ) decisions = {n: {"decision": d, "reason": r, "actor": a} for n, d, r, a in cur.fetchall()} - cur.execute(sql.SQL( - "SELECT DISTINCT ON (row_number, column_index) row_number, column_index, new_value " - "FROM {}.cell_edits WHERE upload_id = %s AND row_number = ANY(%s) " - "ORDER BY row_number, column_index, id DESC").format(_s()), (upload_id, numbers)) + cur.execute( + sql.SQL( + "SELECT DISTINCT ON (row_number, column_index) row_number, column_index, new_value " + "FROM {}.cell_edits WHERE upload_id = %s AND row_number = ANY(%s) " + "ORDER BY row_number, column_index, id DESC" + ).format(_s()), + (upload_id, numbers), + ) edits: dict[int, dict[int, str]] = {} for n, c, v in cur.fetchall(): edits.setdefault(n, {})[c] = v return decisions, edits -def _rows(cur: cursor, upload_id: int, meta: dict[str, Any], numbers: list[int] | None = None, - offset: int = 0, limit: int = 100) -> list[dict[str, Any]]: +def _rows( + cur: cursor, + upload_id: int, + meta: dict[str, Any], + numbers: list[int] | None = None, + offset: int = 0, + limit: int = 100, +) -> list[dict[str, Any]]: if numbers is None: - cur.execute(sql.SQL( - "SELECT row_number, cells FROM {}.source_rows WHERE upload_id = %s AND row_number > 0 " - "ORDER BY row_number OFFSET %s LIMIT %s").format(_s()), (upload_id, offset, limit)) + cur.execute( + sql.SQL( + "SELECT row_number, cells FROM {}.source_rows WHERE upload_id = %s AND row_number > 0 " + "ORDER BY row_number OFFSET %s LIMIT %s" + ).format(_s()), + (upload_id, offset, limit), + ) else: - cur.execute(sql.SQL( - "SELECT row_number, cells FROM {}.source_rows WHERE upload_id = %s AND row_number = ANY(%s) " - "ORDER BY row_number").format(_s()), (upload_id, numbers)) + cur.execute( + sql.SQL( + "SELECT row_number, cells FROM {}.source_rows WHERE upload_id = %s AND row_number = ANY(%s) " + "ORDER BY row_number" + ).format(_s()), + (upload_id, numbers), + ) source = cur.fetchall() decisions, edits = _latest(cur, upload_id, [n for n, _ in source]) duplicates = _flags(cur, upload_id, [n for n, _ in source]) @@ -115,29 +154,42 @@ def _rows(cur: cursor, upload_id: int, meta: dict[str, Any], numbers: list[int] errors = _validate(current, raw, meta["columns"], meta["types"]) if n in meta["_dbErrors"] and n not in edits: errors.append({"column": "(database)", "value": "", "reason": meta["_dbErrors"][n]}) - out.append({ - "rowNumber": n, "original": original, "current": current, - "editedColumns": sorted(edits.get(n, {})), - "decision": decision["decision"] if decision else "include", - "decisionReason": decision["reason"] if decision else None, - "duplicateOfEarlierVersion": duplicates.get(n), - "errors": errors, - }) + out.append( + { + "rowNumber": n, + "original": original, + "current": current, + "editedColumns": sorted(edits.get(n, {})), + "decision": decision["decision"] if decision else "include", + "decisionReason": decision["reason"] if decision else None, + "duplicateOfEarlierVersion": duplicates.get(n), + "errors": errors, + } + ) return out def page(cur: cursor, upload_id: int, offset: int, limit: int) -> dict[str, Any]: meta = _upload(cur, upload_id) offset, limit = max(0, offset), max(1, min(limit, MAX_PAGE)) - cur.execute(sql.SQL( - "SELECT (SELECT count(*) FROM (SELECT DISTINCT ON (row_number) decision FROM {s}.row_decisions " - " WHERE upload_id = %s ORDER BY row_number, id DESC) d WHERE decision = 'exclude'), " - " (SELECT count(DISTINCT row_number) FROM {s}.cell_edits WHERE upload_id = %s)").format(s=_s()), - (upload_id, upload_id)) + cur.execute( + sql.SQL( + "SELECT (SELECT count(*) FROM (SELECT DISTINCT ON (row_number) decision FROM {s}.row_decisions " + " WHERE upload_id = %s ORDER BY row_number, id DESC) d WHERE decision = 'exclude'), " + " (SELECT count(DISTINCT row_number) FROM {s}.cell_edits WHERE upload_id = %s)" + ).format(s=_s()), + (upload_id, upload_id), + ) excluded, edited = fetch_one(cur) public = {k: v for k, v in meta.items() if k != "_dbErrors"} - return {**public, "offset": offset, "limit": limit, "excludedRows": excluded, "editedRows": edited, - "rows": _rows(cur, upload_id, meta, offset=offset, limit=limit)} + return { + **public, + "offset": offset, + "limit": limit, + "excludedRows": excluded, + "editedRows": edited, + "rows": _rows(cur, upload_id, meta, offset=offset, limit=limit), + } def _check_row(meta: dict[str, Any], row_number: int) -> None: @@ -167,12 +219,22 @@ def decide(cur: cursor, upload_id: int, row_number: int, decision: str, reason: raise ReviewError(422, "decision must be 'include' or 'exclude'") reason = _reason(reason) [before] = _rows(cur, upload_id, meta, numbers=[row_number]) - cur.execute(sql.SQL("INSERT INTO {}.row_decisions (upload_id, row_number, decision, reason, actor) " - "VALUES (%s, %s, %s, %s, %s)").format(_s()), - (upload_id, row_number, decision, reason, current_actor())) - write_audit(cur, "row_decision", None, meta["fileName"], None, None, - before={"upload": upload_id, "row": row_number, "decision": before["decision"]}, - after={"upload": upload_id, "row": row_number, "decision": decision, "reason": reason}) + cur.execute( + sql.SQL( + "INSERT INTO {}.row_decisions (upload_id, row_number, decision, reason, actor) VALUES (%s, %s, %s, %s, %s)" + ).format(_s()), + (upload_id, row_number, decision, reason, current_actor()), + ) + write_audit( + cur, + "row_decision", + None, + meta["fileName"], + None, + None, + before={"upload": upload_id, "row": row_number, "decision": before["decision"]}, + after={"upload": upload_id, "row": row_number, "decision": decision, "reason": reason}, + ) [after] = _rows(cur, upload_id, meta, numbers=[row_number]) return after @@ -191,12 +253,24 @@ def edit(cur: cursor, upload_id: int, row_number: int, column: str, value: str, old = before["current"][index] if value == old: raise ReviewError(422, "The new value is the same as the current one") - cur.execute(sql.SQL("INSERT INTO {}.cell_edits (upload_id, row_number, column_index, old_value, new_value, " - "reason, actor) VALUES (%s, %s, %s, %s, %s, %s, %s)").format(_s()), - (upload_id, row_number, index, old, value, reason, current_actor())) + cur.execute( + sql.SQL( + "INSERT INTO {}.cell_edits (upload_id, row_number, column_index, old_value, new_value, " + "reason, actor) VALUES (%s, %s, %s, %s, %s, %s, %s)" + ).format(_s()), + (upload_id, row_number, index, old, value, reason, current_actor()), + ) cell = {"upload": upload_id, "row": row_number, "column": names[index]} - write_audit(cur, "cell_edit", None, meta["fileName"], None, None, - before={**cell, "value": old}, after={**cell, "value": value, "reason": reason}) + write_audit( + cur, + "cell_edit", + None, + meta["fileName"], + None, + None, + before={**cell, "value": old}, + after={**cell, "value": value, "reason": reason}, + ) [after] = _rows(cur, upload_id, meta, numbers=[row_number]) return after @@ -205,12 +279,15 @@ def history(cur: cursor, upload_id: int, row_number: int) -> list[dict[str, Any] """Every decision and edit on one row, oldest first.""" meta = _upload(cur, upload_id) _check_row(meta, row_number) - cur.execute(sql.SQL( - "SELECT 'decision', decided_at, actor, reason, decision, NULL::int, NULL, NULL FROM {s}.row_decisions " - " WHERE upload_id = %s AND row_number = %s " - "UNION ALL SELECT 'edit', edited_at, actor, reason, NULL, column_index, old_value, new_value " - " FROM {s}.cell_edits WHERE upload_id = %s AND row_number = %s ORDER BY 2").format(s=_s()), - (upload_id, row_number, upload_id, row_number)) + cur.execute( + sql.SQL( + "SELECT 'decision', decided_at, actor, reason, decision, NULL::int, NULL, NULL FROM {s}.row_decisions " + " WHERE upload_id = %s AND row_number = %s " + "UNION ALL SELECT 'edit', edited_at, actor, reason, NULL, column_index, old_value, new_value " + " FROM {s}.cell_edits WHERE upload_id = %s AND row_number = %s ORDER BY 2" + ).format(s=_s()), + (upload_id, row_number, upload_id, row_number), + ) out = [] for kind, at, actor, reason, decision, index, old, new in cur.fetchall(): entry = {"kind": kind, "at": at.isoformat(), "actor": actor, "reason": reason} diff --git a/api/services/staged_import.py b/api/services/staged_import.py index 8876266..7575417 100644 --- a/api/services/staged_import.py +++ b/api/services/staged_import.py @@ -28,9 +28,11 @@ import io import json import logging +from typing import Any, cast import psycopg2.errors from psycopg2 import sql +from psycopg2.extensions import connection, cursor from api.config import settings from api.db import Conn, fetch_one @@ -47,10 +49,8 @@ ) from api.services.dynamic_loader import _TYPE_SQL, _earlier_version_matches, _schema_diff, dataset_slug from api.services.originals import store_upload -from api.tenancy import uploads_schema -from typing import Any, cast -from psycopg2.extensions import connection, cursor from api.services.results import DuplicateFlag, LoadResult, SchemaCheck +from api.tenancy import uploads_schema logger = logging.getLogger(__name__) @@ -76,13 +76,17 @@ def _s() -> sql.Identifier: def _row_hash(cells: list[str]) -> str: # Same scheme as dynamic_loader (#178): JSON, so no cell content can make two rows collide. - return "v2:" + hashlib.sha256(json.dumps(cells, ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest() + return ( + "v2:" + hashlib.sha256(json.dumps(cells, ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest() + ) # -- staging --------------------------------------------------------------------------------- -def prepare(content: str, types: list[str] | None, - header_mapping: list[dict[str, Any]] | None) -> tuple[list[list[str]], list[str], list[str]]: + +def prepare( + content: str, types: list[str] | None, header_mapping: list[dict[str, Any]] | None +) -> tuple[list[list[str]], list[str], list[str]]: """Parse and check a CSV the way the dynamic loader does. Returns (rows, columns, types) or raises. ponytail: duplicates the loader's structural checks; the loader's own path goes away once @@ -92,37 +96,51 @@ def prepare(content: str, types: list[str] | None, if not rows: raise WorkflowError(422, "This CSV is empty — no header row and no data rows were detected.", reason="empty") if len(rows) == 1: - raise WorkflowError(422, "This CSV has a header row but no data rows. Add at least one data row.", - reason="header_only") + raise WorkflowError( + 422, "This CSV has a header row but no data rows. Add at least one data row.", reason="header_only" + ) if all((c or "").strip() == "" for c in rows[0]): - raise WorkflowError(422, "This CSV's first row is blank, so no column headers were detected.", - reason="no_columns") + raise WorkflowError( + 422, "This CSV's first row is blank, so no column headers were detected.", reason="no_columns" + ) mapped, error = apply_header_mapping(rows[0], header_mapping) if error: raise WorkflowError(422, error, reason="invalid_header_mapping") if len(rows) - 1 > settings.MAX_ROWS: - raise WorkflowError(422, f"CSV has {len(rows) - 1} data rows; the API accepts at most {settings.MAX_ROWS}.", - reason="too_many_rows") + raise WorkflowError( + 422, + f"CSV has {len(rows) - 1} data rows; the API accepts at most {settings.MAX_ROWS}.", + reason="too_many_rows", + ) columns = sanitize_columns(mapped) if not columns: raise WorkflowError(422, "No columns found in the CSV header.", reason="no_columns") if len(set(columns)) != len(columns): dupe = next(c for i, c in enumerate(columns) if columns.index(c) != i) - raise WorkflowError(422, f'Duplicate sanitized column name "{dupe}" — rename headers in the CSV.', - reason="duplicate_columns") + raise WorkflowError( + 422, f'Duplicate sanitized column name "{dupe}" — rename headers in the CSV.', reason="duplicate_columns" + ) if any(not valid_identifier(c) for c in columns): raise WorkflowError(422, "Column headers could not be converted to safe identifiers.", reason="bad_columns") if types is not None and len(types) != len(columns): - raise WorkflowError(422, f"Provided {len(types)} column types but the CSV has {len(columns)} columns.", - reason="bad_types") + raise WorkflowError( + 422, f"Provided {len(types)} column types but the CSV has {len(columns)} columns.", reason="bad_types" + ) col_types = types if types else ["text"] * len(columns) if any(t not in ALLOWED_TYPES for t in col_types): raise WorkflowError(422, "Unsupported column type provided.", reason="bad_types") return rows, columns, col_types -def stage(cur: cursor, file_name: str, content: str, types: list[str] | None, header_mapping: list[dict[str, Any]] | None, - original: bytes | None, types_confirmed: bool = False) -> dict[str, Any]: +def stage( + cur: cursor, + file_name: str, + content: str, + types: list[str] | None, + header_mapping: list[dict[str, Any]] | None, + original: bytes | None, + types_confirmed: bool = False, +) -> dict[str, Any]: """Store an upload for review without importing it. Every attempt is recorded (BR-23). Returns a result dict whose ``status`` is ``staged``, ``duplicate_file`` or ``invalid_structure``, @@ -136,18 +154,28 @@ def stage(cur: cursor, file_name: str, content: str, types: list[str] | None, he result.update(cast(LoadResult, exc.extra)) # WorkflowError's fields (reason, ...), after the message as before return {**result, "uploadId": str(store_upload(cur, file_name, content, "dynamic", result, original=original))} - cur.execute(sql.SQL("SELECT file_name, table_name, row_count FROM {}.csv_files WHERE file_hash = %s") - .format(_s()), (sha,)) + cur.execute( + sql.SQL("SELECT file_name, table_name, row_count FROM {}.csv_files WHERE file_hash = %s").format(_s()), (sha,) + ) match = cur.fetchone() if match: - result = {"status": "duplicate_file", "reason": "content", "existingFileName": match[0], - "tableName": match[1], "existingRowCount": match[2] or 0} + result = { + "status": "duplicate_file", + "reason": "content", + "existingFileName": match[0], + "tableName": match[1], + "existingRowCount": match[2] or 0, + } return {**result, "uploadId": str(store_upload(cur, file_name, content, "dynamic", result, original=original))} # BR-29: flag rows already in an earlier version of this dataset, so the reviewer sees them before approving. dataset = dataset_slug(file_name) - cur.execute(sql.SQL("SELECT id, file_name, table_name, version FROM {}.csv_files WHERE dataset = %s " - "ORDER BY version DESC").format(_s()), (dataset,)) + cur.execute( + sql.SQL( + "SELECT id, file_name, table_name, version FROM {}.csv_files WHERE dataset = %s ORDER BY version DESC" + ).format(_s()), + (dataset,), + ) priors = cur.fetchall() flags: list[DuplicateFlag] = [] if priors: @@ -164,27 +192,41 @@ def stage(cur: cursor, file_name: str, content: str, types: list[str] | None, he # #195: the registry says whether a person confirmed the types; the import records it. provenance = "user_confirmed" if (types and types_confirmed) else "inferred_unconfirmed" - result = {"status": "staged", "totalRows": len(rows) - 1, "columns": columns, "types": col_types, - "typesProvenance": provenance} + result = { + "status": "staged", + "totalRows": len(rows) - 1, + "columns": columns, + "types": col_types, + "typesProvenance": provenance, + } upload_id = store_upload(cur, file_name, content, "dynamic", result, original=original, flags=flags) - return {**result, "uploadId": str(upload_id), "state": "staged", "dataset": dataset, - "duplicateRowsAcrossUploads": len(flags), - "crossUploadDuplicates": flags[:settings.MAX_ROW_ERRORS_REPORTED]} + return { + **result, + "uploadId": str(upload_id), + "state": "staged", + "dataset": dataset, + "duplicateRowsAcrossUploads": len(flags), + "crossUploadDuplicates": flags[: settings.MAX_ROW_ERRORS_REPORTED], + } # -- state ----------------------------------------------------------------------------------- + def state_columns() -> sql.Composed: """Select-list part for an ``uploads u`` query that also has ``state_join()``: has_import, sub_id, decision.""" - return sql.SQL("EXISTS (SELECT 1 FROM {s}.imports i WHERE i.upload_id = u.id) AS has_import, " - "w.sub_id, w.decision").format(s=_s()) + return sql.SQL( + "EXISTS (SELECT 1 FROM {s}.imports i WHERE i.upload_id = u.id) AS has_import, w.sub_id, w.decision" + ).format(s=_s()) def state_join() -> sql.Composed: """The latest submission of ``u`` and its approval decision, if any.""" - return sql.SQL("LEFT JOIN LATERAL (SELECT sb.id AS sub_id, a.decision FROM {s}.submissions sb " - "LEFT JOIN {s}.approvals a ON a.submission_id = sb.id WHERE sb.upload_id = u.id " - "ORDER BY sb.id DESC LIMIT 1) w ON true").format(s=_s()) + return sql.SQL( + "LEFT JOIN LATERAL (SELECT sb.id AS sub_id, a.decision FROM {s}.submissions sb " + "LEFT JOIN {s}.approvals a ON a.submission_id = sb.id WHERE sb.upload_id = u.id " + "ORDER BY sb.id DESC LIMIT 1) w ON true" + ).format(s=_s()) def derive_state(status: str, has_import: bool, sub_id: int | None, decision: str | None) -> str: @@ -199,34 +241,71 @@ def derive_state(status: str, has_import: bool, sub_id: int | None, decision: st def state_of(cur: cursor, upload_id: int) -> dict[str, Any] | None: """The upload's workflow state with its latest submission, approval and import. None if there is no such upload.""" - cur.execute(sql.SQL("SELECT u.status, u.uploader, u.file_name, u.sha256, u.types_provenance, {cols} " - "FROM {s}.uploads u {join} WHERE u.id = %s") - .format(cols=state_columns(), s=_s(), join=state_join()), (upload_id,)) + cur.execute( + sql.SQL( + "SELECT u.status, u.uploader, u.file_name, u.sha256, u.types_provenance, {cols} " + "FROM {s}.uploads u {join} WHERE u.id = %s" + ).format(cols=state_columns(), s=_s(), join=state_join()), + (upload_id,), + ) row = cur.fetchone() if row is None: return None status, uploader, file_name, sha, provenance, has_import, sub_id, decision = row - out = {"uploadId": str(upload_id), "state": derive_state(status, has_import, sub_id, decision), - "fileName": file_name, "uploader": uploader, "sha256": sha, "typesProvenance": provenance, - "submission": None, "approval": None, "import": None} + out = { + "uploadId": str(upload_id), + "state": derive_state(status, has_import, sub_id, decision), + "fileName": file_name, + "uploader": uploader, + "sha256": sha, + "typesProvenance": provenance, + "submission": None, + "approval": None, + "import": None, + } if sub_id is not None: - cur.execute(sql.SQL("SELECT submitter, note, submitted_at FROM {}.submissions WHERE id = %s").format(_s()), - (sub_id,)) + cur.execute( + sql.SQL("SELECT submitter, note, submitted_at FROM {}.submissions WHERE id = %s").format(_s()), (sub_id,) + ) who, note, at = fetch_one(cur) out["submission"] = {"id": str(sub_id), "submitter": who, "note": note, "at": at.isoformat()} - cur.execute(sql.SQL("SELECT id, decision, reason, approver, decisions_upto, edits_upto, decided_at " - "FROM {}.approvals WHERE submission_id = %s").format(_s()), (sub_id,)) + cur.execute( + sql.SQL( + "SELECT id, decision, reason, approver, decisions_upto, edits_upto, decided_at " + "FROM {}.approvals WHERE submission_id = %s" + ).format(_s()), + (sub_id,), + ) a = cur.fetchone() if a: - out["approval"] = {"id": str(a[0]), "decision": a[1], "reason": a[2], "approver": a[3], - "decisionsUpto": a[4], "editsUpto": a[5], "at": a[6].isoformat()} + out["approval"] = { + "id": str(a[0]), + "decision": a[1], + "reason": a[2], + "approver": a[3], + "decisionsUpto": a[4], + "editsUpto": a[5], + "at": a[6].isoformat(), + } if has_import: - cur.execute(sql.SQL("SELECT id, idempotency_key, rows_in, rows_excluded, rows_edited, rows_duplicate, " - "rows_imported, csv_file_id, table_name, importer, imported_at FROM {}.imports " - "WHERE upload_id = %s").format(_s()), (upload_id,)) + cur.execute( + sql.SQL( + "SELECT id, idempotency_key, rows_in, rows_excluded, rows_edited, rows_duplicate, " + "rows_imported, csv_file_id, table_name, importer, imported_at FROM {}.imports " + "WHERE upload_id = %s" + ).format(_s()), + (upload_id,), + ) i = fetch_one(cur) - out["import"] = {"id": str(i[0]), "idempotencyKey": i[1], "reconciliation": _reconciliation(*i[2:7]), - "fileId": str(i[7]), "tableName": i[8], "importer": i[9], "at": i[10].isoformat()} + out["import"] = { + "id": str(i[0]), + "idempotencyKey": i[1], + "reconciliation": _reconciliation(*i[2:7]), + "fileId": str(i[7]), + "tableName": i[8], + "importer": i[9], + "at": i[10].isoformat(), + } return out @@ -236,17 +315,22 @@ def _reconciliation(rows_in: int, excluded: int, edited: int, duplicate: int, im def history(cur: cursor, upload_id: int) -> list[dict[str, Any]]: """Every submission, decision and import on an upload, oldest first.""" - cur.execute(sql.SQL( - "SELECT 'submitted', submitted_at, submitter, note FROM {s}.submissions WHERE upload_id = %s " - "UNION ALL SELECT CASE decision WHEN 'approve' THEN 'approved' ELSE 'rejected' END, decided_at, approver, reason " - "FROM {s}.approvals WHERE upload_id = %s " - "UNION ALL SELECT 'imported', imported_at, importer, NULL FROM {s}.imports WHERE upload_id = %s " - "ORDER BY 2").format(s=_s()), (upload_id,) * 3) + cur.execute( + sql.SQL( + "SELECT 'submitted', submitted_at, submitter, note FROM {s}.submissions WHERE upload_id = %s " + "UNION ALL SELECT CASE decision WHEN 'approve' THEN 'approved' ELSE 'rejected' END, decided_at, approver, reason " + "FROM {s}.approvals WHERE upload_id = %s " + "UNION ALL SELECT 'imported', imported_at, importer, NULL FROM {s}.imports WHERE upload_id = %s " + "ORDER BY 2" + ).format(s=_s()), + (upload_id,) * 3, + ) return [{"event": e, "at": at.isoformat(), "actor": who, "note": note} for e, at, who, note in cur.fetchall()] # -- submit and decide ----------------------------------------------------------------------- + def _require(cur: cursor, upload_id: int) -> dict[str, Any]: st = state_of(cur, upload_id) if st is None: @@ -261,12 +345,23 @@ def submit(cur: cursor, upload_id: int, note: str | None) -> dict[str, Any]: raise WorkflowError(409, "This upload was imported directly and has no approval workflow", state="legacy") if st["state"] not in ("staged", "rejected"): raise WorkflowError(409, f"This upload is already {st['state']}", state=st["state"]) - cur.execute(sql.SQL("INSERT INTO {}.submissions (upload_id, submitter, note) VALUES (%s, %s, %s) RETURNING id") - .format(_s()), (upload_id, current_actor(), (note or "").strip() or None)) + cur.execute( + sql.SQL("INSERT INTO {}.submissions (upload_id, submitter, note) VALUES (%s, %s, %s) RETURNING id").format( + _s() + ), + (upload_id, current_actor(), (note or "").strip() or None), + ) sub_id = fetch_one(cur)[0] - write_audit(cur, "submit", None, st["fileName"], None, "dynamic", - before={"upload": upload_id, "state": st["state"]}, - after={"upload": upload_id, "submission": sub_id, "note": (note or "").strip() or None}) + write_audit( + cur, + "submit", + None, + st["fileName"], + None, + "dynamic", + before={"upload": upload_id, "state": st["state"]}, + after={"upload": upload_id, "submission": sub_id, "note": (note or "").strip() or None}, + ) return _require(cur, upload_id) @@ -276,7 +371,9 @@ def _self_approval_allowed(session: dict[str, Any]) -> bool: return bool(session.get("allowSelfApproval")) -def decide_approval(cur: cursor, upload_id: int, decision: str, reason: str | None, session: dict[str, Any] | None) -> dict[str, Any]: +def decide_approval( + cur: cursor, upload_id: int, decision: str, reason: str | None, session: dict[str, Any] | None +) -> dict[str, Any]: """Approve or reject the pending submission. The caller commits. Approving needs every non-excluded row to pass validation (otherwise the import couldn't run), @@ -285,41 +382,72 @@ def decide_approval(cur: cursor, upload_id: int, decision: str, reason: str | No """ st = _require(cur, upload_id) if st["state"] != "submitted": - raise WorkflowError(409, f"This upload is {st['state']}; only a submitted upload can be approved or rejected", - state=st["state"]) + raise WorkflowError( + 409, f"This upload is {st['state']}; only a submitted upload can be approved or rejected", state=st["state"] + ) if decision not in ("approve", "reject"): raise WorkflowError(422, "decision must be 'approve' or 'reject'") reason = (reason or "").strip() or None if decision == "reject" and not reason: raise WorkflowError(422, "A reason is required to reject") - if decision == "approve" and session is not None and session["username"] in (st["uploader"], st["submission"]["submitter"]): + if ( + decision == "approve" + and session is not None + and session["username"] in (st["uploader"], st["submission"]["submitter"]) + ): if not _self_approval_allowed(session): - raise WorkflowError(403, "You uploaded or submitted this data, so another member must approve it. " - "A tenant with a single user can allow self-approval.") - cur.execute(sql.SQL("SELECT COALESCE(max(id), 0) FROM {}.row_decisions WHERE upload_id = %s").format(_s()), - (upload_id,)) + raise WorkflowError( + 403, + "You uploaded or submitted this data, so another member must approve it. " + "A tenant with a single user can allow self-approval.", + ) + cur.execute( + sql.SQL("SELECT COALESCE(max(id), 0) FROM {}.row_decisions WHERE upload_id = %s").format(_s()), (upload_id,) + ) decisions_upto = fetch_one(cur)[0] - cur.execute(sql.SQL("SELECT COALESCE(max(id), 0) FROM {}.cell_edits WHERE upload_id = %s").format(_s()), - (upload_id,)) + cur.execute( + sql.SQL("SELECT COALESCE(max(id), 0) FROM {}.cell_edits WHERE upload_id = %s").format(_s()), (upload_id,) + ) edits_upto = fetch_one(cur)[0] if decision == "approve": plan = effective_rows(cur, upload_id, decisions_upto, edits_upto) if plan["invalid"]: - raise WorkflowError(422, f"{plan['invalid']} row(s) still fail validation. Exclude or edit them, then approve.", - invalidRows=plan["invalid"], rowErrors=plan["errors"]) - cur.execute(sql.SQL("INSERT INTO {}.approvals (submission_id, upload_id, decision, reason, approver, " - "decisions_upto, edits_upto) VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id").format(_s()), - (int(st["submission"]["id"]), upload_id, decision, reason, current_actor(), decisions_upto, edits_upto)) + raise WorkflowError( + 422, + f"{plan['invalid']} row(s) still fail validation. Exclude or edit them, then approve.", + invalidRows=plan["invalid"], + rowErrors=plan["errors"], + ) + cur.execute( + sql.SQL( + "INSERT INTO {}.approvals (submission_id, upload_id, decision, reason, approver, " + "decisions_upto, edits_upto) VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id" + ).format(_s()), + (int(st["submission"]["id"]), upload_id, decision, reason, current_actor(), decisions_upto, edits_upto), + ) approval_id = fetch_one(cur)[0] - write_audit(cur, decision, None, st["fileName"], None, "dynamic", - before={"upload": upload_id, "state": "submitted"}, - after={"upload": upload_id, "submission": int(st["submission"]["id"]), "approval": approval_id, - "decision": decision, "reason": reason}) + write_audit( + cur, + decision, + None, + st["fileName"], + None, + "dynamic", + before={"upload": upload_id, "state": "submitted"}, + after={ + "upload": upload_id, + "submission": int(st["submission"]["id"]), + "approval": approval_id, + "decision": decision, + "reason": reason, + }, + ) return _require(cur, upload_id) # -- the rows an import would load ----------------------------------------------------------- + def effective_rows(cur: cursor, upload_id: int, decisions_upto: int, edits_upto: int) -> dict[str, Any]: """What an import of this upload loads, as of the given decision and edit ids (BR-33, BR-34). @@ -330,21 +458,43 @@ def effective_rows(cur: cursor, upload_id: int, decisions_upto: int, edits_upto: """ cur.execute(sql.SQL("SELECT columns, column_types FROM {}.uploads WHERE id = %s").format(_s()), (upload_id,)) columns, types = fetch_one(cur) - cur.execute(sql.SQL("SELECT DISTINCT ON (row_number) row_number, decision FROM {}.row_decisions " - "WHERE upload_id = %s AND id <= %s ORDER BY row_number, id DESC").format(_s()), - (upload_id, decisions_upto)) + cur.execute( + sql.SQL( + "SELECT DISTINCT ON (row_number) row_number, decision FROM {}.row_decisions " + "WHERE upload_id = %s AND id <= %s ORDER BY row_number, id DESC" + ).format(_s()), + (upload_id, decisions_upto), + ) excluded = {n for n, d in cur.fetchall() if d == "exclude"} - cur.execute(sql.SQL("SELECT DISTINCT ON (row_number, column_index) row_number, column_index, new_value " - "FROM {}.cell_edits WHERE upload_id = %s AND id <= %s " - "ORDER BY row_number, column_index, id DESC").format(_s()), (upload_id, edits_upto)) + cur.execute( + sql.SQL( + "SELECT DISTINCT ON (row_number, column_index) row_number, column_index, new_value " + "FROM {}.cell_edits WHERE upload_id = %s AND id <= %s " + "ORDER BY row_number, column_index, id DESC" + ).format(_s()), + (upload_id, edits_upto), + ) edits: dict[int, dict[int, str]] = {} for n, c, v in cur.fetchall(): edits.setdefault(n, {})[c] = v - cur.execute(sql.SQL("SELECT row_number, cells FROM {}.source_rows WHERE upload_id = %s AND row_number > 0 " - "ORDER BY row_number").format(_s()), (upload_id,)) + cur.execute( + sql.SQL( + "SELECT row_number, cells FROM {}.source_rows WHERE upload_id = %s AND row_number > 0 ORDER BY row_number" + ).format(_s()), + (upload_id,), + ) width = len(columns) - out = {"rowsIn": 0, "excluded": 0, "edited": 0, "duplicate": 0, "invalid": 0, "valid": [], "errors": [], - "columns": columns, "types": types} + out = { + "rowsIn": 0, + "excluded": 0, + "edited": 0, + "duplicate": 0, + "invalid": 0, + "valid": [], + "errors": [], + "columns": columns, + "types": types, + } seen: set[str] = set() for n, raw in cur.fetchall(): out["rowsIn"] += 1 @@ -357,8 +507,11 @@ def effective_rows(cur: cursor, upload_id: int, decisions_upto: int, edits_upto: cells = [changed[c] if c in changed else (raw[c] if c < len(raw) else "") for c in range(width)] error: dict[str, str | None] | None = None if extra_cells(raw, width): - error = {"column": "(beyond header)", "value": extra_cells(raw, width)[0], - "reason": ragged_row_reason(raw, width)} + error = { + "column": "(beyond header)", + "value": extra_cells(raw, width)[0], + "reason": ragged_row_reason(raw, width), + } values: list[Any] = [] for c in range(width): if error: @@ -383,6 +536,7 @@ def effective_rows(cur: cursor, upload_id: int, decisions_upto: int, edits_upto: # -- the import ------------------------------------------------------------------------------ + def _copy_text(v: object) -> str: return ("true" if v else "false") if isinstance(v, bool) else str(v) @@ -399,8 +553,14 @@ def _copy_data(rows: list[tuple[Any, ...]]) -> io.StringIO: def _replay(st: dict[str, Any]) -> dict[str, Any]: i = st["import"] - return {"status": "ok", "replayed": True, "importId": i["id"], "fileId": i["fileId"], "tableName": i["tableName"], - "reconciliation": i["reconciliation"]} + return { + "status": "ok", + "replayed": True, + "importId": i["id"], + "fileId": i["fileId"], + "tableName": i["tableName"], + "reconciliation": i["reconciliation"], + } def import_upload(upload_id: int, key: str, session: dict[str, Any] | None) -> dict[str, Any]: @@ -423,42 +583,85 @@ def import_upload(upload_id: int, key: str, session: dict[str, Any] | None) -> d if st["import"]: if st["import"]["idempotencyKey"] == key: return _replay(st) - raise WorkflowError(409, "This upload has already been imported", state="imported", - importId=st["import"]["id"]) + raise WorkflowError( + 409, "This upload has already been imported", state="imported", importId=st["import"]["id"] + ) if st["state"] != "approved": - raise WorkflowError(409, f"This upload is {st['state']}; only an approved upload can be imported", - state=st["state"]) + raise WorkflowError( + 409, f"This upload is {st['state']}; only an approved upload can be imported", state=st["state"] + ) approval = st["approval"] plan = effective_rows(cur, upload_id, approval["decisionsUpto"], approval["editsUpto"]) if plan["invalid"]: # approval checked this; only a bug or manual DB change gets here - raise WorkflowError(422, f"{plan['invalid']} approved row(s) fail validation", invalidRows=plan["invalid"], - rowErrors=plan["errors"]) + raise WorkflowError( + 422, + f"{plan['invalid']} approved row(s) fail validation", + invalidRows=plan["invalid"], + rowErrors=plan["errors"], + ) columns, col_types, valid = plan["columns"], plan["types"], plan["valid"] counts = _reconciliation(plan["rowsIn"], plan["excluded"], plan["edited"], plan["duplicate"], len(valid)) dataset, version, table_name, schema_check = _next_version(cur, schema, st["fileName"], columns, col_types) - file_id, import_id = _register_import(conn, cur, upload_id, key, st, int(approval["id"]), table_name, - columns, len(valid), counts, dataset, version) + file_id, import_id = _register_import( + conn, + cur, + upload_id, + key, + st, + int(approval["id"]), + table_name, + columns, + len(valid), + counts, + dataset, + version, + ) _checkpoint("registered") _create_and_fill(conn, cur, schema, table_name, import_id, columns, col_types, valid) - write_audit(cur, "import", file_id, st["fileName"], table_name, "dynamic", - before={"upload": upload_id, "state": "approved"}, - after={"upload": upload_id, "import": import_id, "approval": int(approval["id"]), - "table": table_name, "reconciliation": counts}) + write_audit( + cur, + "import", + file_id, + st["fileName"], + table_name, + "dynamic", + before={"upload": upload_id, "state": "approved"}, + after={ + "upload": upload_id, + "import": import_id, + "approval": int(approval["id"]), + "table": table_name, + "reconciliation": counts, + }, + ) conn.commit() - return {"status": "ok", "replayed": False, "importId": str(import_id), "fileId": str(file_id), - "tableName": table_name, "dataset": dataset, "version": version, "reconciliation": counts, - "schemaCheck": schema_check} - - -def _next_version(cur: cursor, schema: str, file_name: str, columns: list[str], - col_types: list[str]) -> tuple[str, int, str, SchemaCheck | None]: + return { + "status": "ok", + "replayed": False, + "importId": str(import_id), + "fileId": str(file_id), + "tableName": table_name, + "dataset": dataset, + "version": version, + "reconciliation": counts, + "schemaCheck": schema_check, + } + + +def _next_version( + cur: cursor, schema: str, file_name: str, columns: list[str], col_types: list[str] +) -> tuple[str, int, str, SchemaCheck | None]: """The dataset, the version this import becomes, its table name, and how it compares with the previous one.""" # Same per-dataset lock as the loader, so versions are never handed out twice (M5). dataset = dataset_slug(file_name) cur.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (f"{schema}.{dataset}",)) - cur.execute(sql.SQL("SELECT id, file_name, table_name, version FROM {}.csv_files WHERE dataset = %s " - "ORDER BY version DESC").format(_s()), (dataset,)) + cur.execute( + sql.SQL( + "SELECT id, file_name, table_name, version FROM {}.csv_files WHERE dataset = %s ORDER BY version DESC" + ).format(_s()), + (dataset,), + ) priors = cur.fetchall() version = priors[0][3] + 1 if priors else 1 table_name = f"csv_{dataset}_v{version}" @@ -466,52 +669,112 @@ def _next_version(cur: cursor, schema: str, file_name: str, columns: list[str], return dataset, version, table_name, schema_check -def _register_import(conn: connection, cur: cursor, upload_id: int, key: str, st: dict[str, Any], approval_id: int, table_name: str, - columns: list[str], imported: int, counts: dict[str, Any], dataset: str, version: int) -> tuple[int, int]: +def _register_import( + conn: connection, + cur: cursor, + upload_id: int, + key: str, + st: dict[str, Any], + approval_id: int, + table_name: str, + columns: list[str], + imported: int, + counts: dict[str, Any], + dataset: str, + version: int, +) -> tuple[int, int]: """The csv_files row and the imports record. Returns their ids. Refuses bytes that were imported meanwhile.""" try: - cur.execute(sql.SQL( - "INSERT INTO {}.csv_files (file_name, file_hash, table_name, mode, row_count, column_names, " - "total_rows, duplicate_rows_skipped, failed_rows, types_provenance, dataset, version) " - "VALUES (%s, %s, %s, 'dynamic', %s, %s, %s, %s, 0, %s, %s, %s) RETURNING id").format(_s()), - (st["fileName"], st["sha256"], table_name, imported, columns, counts["rowsIn"], - counts["duplicate"], st["typesProvenance"] or "inferred_unconfirmed", dataset, version)) + cur.execute( + sql.SQL( + "INSERT INTO {}.csv_files (file_name, file_hash, table_name, mode, row_count, column_names, " + "total_rows, duplicate_rows_skipped, failed_rows, types_provenance, dataset, version) " + "VALUES (%s, %s, %s, 'dynamic', %s, %s, %s, %s, 0, %s, %s, %s) RETURNING id" + ).format(_s()), + ( + st["fileName"], + st["sha256"], + table_name, + imported, + columns, + counts["rowsIn"], + counts["duplicate"], + st["typesProvenance"] or "inferred_unconfirmed", + dataset, + version, + ), + ) except psycopg2.errors.UniqueViolation: conn.rollback() # the same bytes were imported meanwhile (exact-file dedup, BR-28) raise WorkflowError(409, "These exact file contents were already imported", state="duplicate_file") from None file_id = int(fetch_one(cur)[0]) - cur.execute(sql.SQL( - "INSERT INTO {}.imports (upload_id, approval_id, idempotency_key, rows_in, rows_excluded, " - "rows_edited, rows_duplicate, rows_imported, csv_file_id, table_name, importer) " - "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id").format(_s()), - (upload_id, approval_id, key, counts["rowsIn"], counts["excluded"], counts["edited"], - counts["duplicate"], imported, file_id, table_name, current_actor())) + cur.execute( + sql.SQL( + "INSERT INTO {}.imports (upload_id, approval_id, idempotency_key, rows_in, rows_excluded, " + "rows_edited, rows_duplicate, rows_imported, csv_file_id, table_name, importer) " + "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id" + ).format(_s()), + ( + upload_id, + approval_id, + key, + counts["rowsIn"], + counts["excluded"], + counts["edited"], + counts["duplicate"], + imported, + file_id, + table_name, + current_actor(), + ), + ) return file_id, int(fetch_one(cur)[0]) -def _create_and_fill(conn: connection, cur: cursor, schema: str, table_name: str, import_id: int, columns: list[str], - col_types: list[str], valid: list[Any]) -> None: +def _create_and_fill( + conn: connection, + cur: cursor, + schema: str, + table_name: str, + import_id: int, + columns: list[str], + col_types: list[str], + valid: list[Any], +) -> None: """Create the dataset's table and fill it through a temporary staging table, checking every row arrived.""" target, staging = sql.Identifier(schema, table_name), sql.Identifier(f"_stg_{import_id}") - col_defs = sql.SQL(", ").join(sql.SQL("{} {}").format(sql.Identifier(c), sql.SQL(_TYPE_SQL[t])) - for c, t in zip(columns, col_types)) + col_defs = sql.SQL(", ").join( + sql.SQL("{} {}").format(sql.Identifier(c), sql.SQL(_TYPE_SQL[t])) for c, t in zip(columns, col_types) + ) cols = sql.SQL(", ").join(sql.Identifier(c) for c in columns) # Plain CREATE: a name clash must fail the import, not append to another table. - cur.execute(sql.SQL("CREATE TABLE {} (_id BIGSERIAL PRIMARY KEY, {}, _row_hash TEXT NOT NULL UNIQUE, " - "_created_at TIMESTAMPTZ NOT NULL DEFAULT now(), " - "_source_row_id INTEGER NOT NULL, _import_id BIGINT NOT NULL)") - .format(target, col_defs)) - cur.execute(sql.SQL("CREATE TEMP TABLE {} (_source_row_id INTEGER, {}, _row_hash TEXT) ON COMMIT DROP") - .format(staging, col_defs)) + cur.execute( + sql.SQL( + "CREATE TABLE {} (_id BIGSERIAL PRIMARY KEY, {}, _row_hash TEXT NOT NULL UNIQUE, " + "_created_at TIMESTAMPTZ NOT NULL DEFAULT now(), " + "_source_row_id INTEGER NOT NULL, _import_id BIGINT NOT NULL)" + ).format(target, col_defs) + ) + cur.execute( + sql.SQL("CREATE TEMP TABLE {} (_source_row_id INTEGER, {}, _row_hash TEXT) ON COMMIT DROP").format( + staging, col_defs + ) + ) try: cur.copy_expert( sql.SQL("COPY {} (_source_row_id, {}, _row_hash) FROM STDIN WITH (FORMAT csv, NULL '\\N')") - .format(staging, cols).as_string(cur), - _copy_data([(n, *values, h) for n, values, h in valid])) + .format(staging, cols) + .as_string(cur), + _copy_data([(n, *values, h) for n, values, h in valid]), + ) _checkpoint("staged") - cur.execute(sql.SQL("INSERT INTO {t} ({c}, _row_hash, _source_row_id, _import_id) " - "SELECT {c}, _row_hash, _source_row_id, %s FROM {s} ORDER BY _source_row_id") - .format(t=target, c=cols, s=staging), (import_id,)) + cur.execute( + sql.SQL( + "INSERT INTO {t} ({c}, _row_hash, _source_row_id, _import_id) " + "SELECT {c}, _row_hash, _source_row_id, %s FROM {s} ORDER BY _source_row_id" + ).format(t=target, c=cols, s=staging), + (import_id,), + ) except psycopg2.errors.DataError as exc: conn.rollback() raise WorkflowError(422, "The database rejected the data: " + str(exc).splitlines()[0]) from None diff --git a/api/services/te_loader.py b/api/services/te_loader.py index 46f94f8..e0495ff 100644 --- a/api/services/te_loader.py +++ b/api/services/te_loader.py @@ -33,15 +33,14 @@ from psycopg2.extensions import connection, cursor from api.config import TE_TABLES -from api.tenancy import te_schema, uploads_schema from api.db import Conn, fetch_one -from api.services.destructive_ops import _require_delete from api.services.csv_parse import ( cast_value, parse_csv, pg_type_to_allowed_type, sanitize_columns, ) +from api.services.destructive_ops import _require_delete from api.services.load_common import ( RowErrors, insert_with_row_fallback, @@ -52,6 +51,7 @@ ) from api.services.load_common import log as _log from api.services.results import LoadResult, LogEntry, RowError +from api.tenancy import te_schema, uploads_schema def te_table_columns(table: str) -> list[str]: @@ -102,15 +102,21 @@ def _cleanup_prior_registry_entries(cur: cursor, file_name: str, file_hash: str) upload whose content is already a dynamic dataset before reaching here. """ cur.execute( - sql.SQL( - "DELETE FROM {s}.csv_files WHERE mode <> 'dynamic' AND (file_name = %s OR file_hash = %s)" - ).format(s=sql.Identifier(uploads_schema())), + sql.SQL("DELETE FROM {s}.csv_files WHERE mode <> 'dynamic' AND (file_name = %s OR file_hash = %s)").format( + s=sql.Identifier(uploads_schema()) + ), (file_name, file_hash), ) -def upload_te(file_name: str, content: str, target_table: str, *, session: dict[str, Any] | None = None, - on_commit: Callable[[cursor, LoadResult], None] | None = None) -> LoadResult: +def upload_te( + file_name: str, + content: str, + target_table: str, + *, + session: dict[str, Any] | None = None, + on_commit: Callable[[cursor, LoadResult], None] | None = None, +) -> LoadResult: """Load ``content`` into a T&E table. ``on_commit(cur, result)`` runs on the load's cursor just before the commit, given the "ok" result @@ -144,8 +150,7 @@ def upload_te(file_name: str, content: str, target_table: str, *, session: dict[ _log( logs, "cast_rows", - f"Client-side validated {len(data_rows)} rows → " - f"{len(to_insert)} valid, {errors.failed} type errors", + f"Client-side validated {len(data_rows)} rows → {len(to_insert)} valid, {errors.failed} type errors", "warn" if errors.failed else "info", count=len(to_insert), ) @@ -166,20 +171,24 @@ def upload_te(file_name: str, content: str, target_table: str, *, session: dict[ # Register the load in the shared registry (mode='te'), replacing any # earlier entry for this file. Only reached once a row has landed. _cleanup_prior_registry_entries(cur, file_name, file_hash) - file_id = _register(conn, cur, file_name, file_hash, target_table, inserted, columns, - len(data_rows), errors.failed, logs) + file_id = _register( + conn, cur, file_name, file_hash, target_table, inserted, columns, len(data_rows), errors.failed, logs + ) if isinstance(file_id, dict): return file_id _log(logs, "done", f"T&E load complete: {inserted} rows into {target_table}", count=inserted) - result = _ok_result(file_id, target_table, data_rows, inserted, errors.failed, columns, - col_types, errors.items, logs) + result = _ok_result( + file_id, target_table, data_rows, inserted, errors.failed, columns, col_types, errors.items, logs + ) if on_commit is not None: on_commit(cur, result) conn.commit() return result -def _check_file(content: str, target_table: str, logs: list[LogEntry]) -> tuple[list[list[str]], list[str]] | LoadResult: +def _check_file( + content: str, target_table: str, logs: list[LogEntry] +) -> tuple[list[list[str]], list[str]] | LoadResult: """The parsed rows and sanitized columns, or the error response if the file cannot load into ``target_table``. The CSV's sanitized headers must all be existing columns of the target table. @@ -210,15 +219,14 @@ def _check_file(content: str, target_table: str, logs: list[LogEntry]) -> tuple[ if not table_cols: return { "status": "error", - "message": f'T&E table "{target_table}" not found in schema {te_schema()}. ' - "Run deploy_all.sh dev first.", + "message": f'T&E table "{target_table}" not found in schema {te_schema()}. Run deploy_all.sh dev first.', "logs": logs, } unknown = [c for c in columns if c not in table_cols] if unknown: return { "status": "error", - "message": f'CSV columns not present in {te_schema()}.{target_table}: {", ".join(unknown)}', + "message": f"CSV columns not present in {te_schema()}.{target_table}: {', '.join(unknown)}", "logs": logs, } _log(logs, "validate_columns", f"All {len(columns)} CSV columns exist on {target_table}") @@ -244,10 +252,7 @@ def _insert_statements(target_table: str, columns: list[str]) -> tuple[sql.Compo def _cast_types(cur: cursor, target_table: str, columns: list[str], logs: list[LogEntry]) -> list[str | None]: """BUG-028: each column's type to validate against, from one lookup; None where Postgres must cast it.""" col_pg_types = _te_column_types(cur, target_table) - col_types: list[str | None] = [ - pg_type_to_allowed_type(col_pg_types.get(c, "text")) - for c in columns - ] + col_types: list[str | None] = [pg_type_to_allowed_type(col_pg_types.get(c, "text")) for c in columns] unmapped = [c for c, t in zip(columns, col_types) if t is None] if unmapped: _log( @@ -259,8 +264,9 @@ def _cast_types(cur: cursor, target_table: str, columns: list[str], logs: list[L return col_types -def _check_earlier_loads(cur: cursor, file_name: str, file_hash: str, session: dict[str, Any] | None, - logs: list[LogEntry]) -> LoadResult | None: +def _check_earlier_loads( + cur: cursor, file_name: str, file_hash: str, session: dict[str, Any] | None, logs: list[LogEntry] +) -> LoadResult | None: """Refuse content that is already a dynamic dataset; require delete permission to replace an earlier load.""" cur.execute( sql.SQL( @@ -275,8 +281,12 @@ def _check_earlier_loads(cur: cursor, file_name: str, file_hash: str, session: d # whatever API_ALLOW_DESTRUCTIVE says. Nothing has been written yet. dataset = next((p for p in prior if p[0] == "dynamic"), None) if dataset is not None: - _log(logs, "duplicate_check", - f'Identical content is already the dataset "{dataset[1]}"; nothing was imported', "warn") + _log( + logs, + "duplicate_check", + f'Identical content is already the dataset "{dataset[1]}"; nothing was imported', + "warn", + ) return { "status": "duplicate_file", "reason": "content", @@ -284,8 +294,10 @@ def _check_earlier_loads(cur: cursor, file_name: str, file_hash: str, session: d "existingFileName": dataset[1], "tableName": dataset[2], "existingRowCount": dataset[3], - "message": (f'This file\'s content is already stored as the dataset "{dataset[1]}". ' - "A T&E upload cannot replace a dataset, so nothing was imported."), + "message": ( + f'This file\'s content is already stored as the dataset "{dataset[1]}". ' + "A T&E upload cannot replace a dataset, so nothing was imported." + ), "logs": logs, } if prior: @@ -293,8 +305,9 @@ def _check_earlier_loads(cur: cursor, file_name: str, file_hash: str, session: d return None -def cast_te_rows(data_rows: list[list[str]], columns: list[str], col_types: list[str | None], - errors: RowErrors) -> list[tuple[int, list[Any]]]: +def cast_te_rows( + data_rows: list[list[str]], columns: list[str], col_types: list[str | None], errors: RowErrors +) -> list[tuple[int, list[Any]]]: """``(source row number, values)`` for each row that passes the client-side check; failures go to ``errors``.""" to_insert: list[tuple[int, list[Any]]] = [] for r, raw in enumerate(data_rows): @@ -307,8 +320,9 @@ def cast_te_rows(data_rows: list[list[str]], columns: list[str], col_types: list return to_insert -def _cast_te_cells(raw: list[str], columns: list[str], col_types: list[str | None], row_number: int, - errors: RowErrors) -> list[Any] | None: +def _cast_te_cells( + raw: list[str], columns: list[str], col_types: list[str | None], row_number: int, errors: RowErrors +) -> list[Any] | None: """One row's values: an empty cell is NULL, an unmapped type goes to Postgres as text. None if a cell failed.""" values: list[Any] = [] for c, col_type in enumerate(col_types): @@ -327,22 +341,34 @@ def _cast_te_cells(raw: list[str], columns: list[str], col_types: list[str | Non return values -def _not_imported(errors: RowErrors, total_rows: int, target_table: str, columns: list[str], - logs: list[LogEntry]) -> LoadResult: +def _not_imported( + errors: RowErrors, total_rows: int, target_table: str, columns: list[str], logs: list[LogEntry] +) -> LoadResult: if errors.failed >= total_rows: - msg = (f"None of the {total_rows} rows could be imported into {target_table}, " - "so nothing was saved.") + msg = f"None of the {total_rows} rows could be imported into {target_table}, so nothing was saved." else: - msg = (f"{errors.failed} of the {total_rows} rows could not be imported into " - f"{target_table}, so nothing was saved. Fix them and upload the file again.") + msg = ( + f"{errors.failed} of the {total_rows} rows could not be imported into " + f"{target_table}, so nothing was saved. Fix them and upload the file again." + ) e = errors.first() if e: - msg += f' First problem: row {e["rowNumber"]}, {e.get("column", "")}: {e.get("reason", "")}' + msg += f" First problem: row {e['rowNumber']}, {e.get('column', '')}: {e.get('reason', '')}" return rows_failed(msg, errors, total_rows, logs, insertedRows=0, columns=columns) -def _register(conn: connection, cur: cursor, file_name: str, file_hash: str, target_table: str, inserted: int, columns: list[str], - total_rows: int, failed: int, logs: list[LogEntry]) -> int | LoadResult: +def _register( + conn: connection, + cur: cursor, + file_name: str, + file_hash: str, + target_table: str, + inserted: int, + columns: list[str], + total_rows: int, + failed: int, + logs: list[LogEntry], +) -> int | LoadResult: """Add the load to csv_files and return its id, or the error response if a concurrent load got there first.""" try: cur.execute( @@ -351,8 +377,7 @@ def _register(conn: connection, cur: cursor, file_name: str, file_hash: str, tar "total_rows, duplicate_rows_skipped, failed_rows) " "VALUES (%s, %s, %s, 'te', %s, %s, %s, 0, %s) RETURNING id" ).format(sql.Identifier(uploads_schema())), - (file_name, file_hash, f"{te_schema()}.{target_table}", inserted, columns, - total_rows, failed), + (file_name, file_hash, f"{te_schema()}.{target_table}", inserted, columns, total_rows, failed), ) except psycopg2.errors.UniqueViolation: # #81: a concurrent load of the same file registered first. @@ -367,11 +392,25 @@ def _register(conn: connection, cur: cursor, file_name: str, file_hash: str, tar return int(fetch_one(cur)[0]) -def _ok_result(file_id: object, target_table: str, data_rows: list[list[str]], inserted: int, failed_row_count: int, - columns: list[str], col_types: list[str | None], row_errors: list[RowError], - logs: list[LogEntry]) -> LoadResult: +def _ok_result( + file_id: object, + target_table: str, + data_rows: list[list[str]], + inserted: int, + failed_row_count: int, + columns: list[str], + col_types: list[str | None], + row_errors: list[RowError], + logs: list[LogEntry], +) -> LoadResult: return ok_result( - file_id, f"{te_schema()}.{target_table}", len(data_rows), inserted, 0, failed_row_count, columns, + file_id, + f"{te_schema()}.{target_table}", + len(data_rows), + inserted, + 0, + failed_row_count, + columns, # #190: stored with the upload so review revalidates against the target's types. # Columns Postgres casts itself (uuid, enums, ...) review as text. [t or "text" for t in col_types], diff --git a/api/tenancy.py b/api/tenancy.py index 95101a9..7519d75 100644 --- a/api/tenancy.py +++ b/api/tenancy.py @@ -16,19 +16,17 @@ import hashlib import re import threading -from contextlib import contextmanager +from collections.abc import Iterator +from contextlib import AbstractContextManager, contextmanager from contextvars import ContextVar from pathlib import Path +from typing import TYPE_CHECKING, Any from psycopg2 import sql from psycopg2.errors import InsufficientPrivilege +from psycopg2.extensions import connection, cursor from api.config import TE_TABLES, settings -from typing import Any -from psycopg2.extensions import connection, cursor -from collections.abc import Iterator -from contextlib import AbstractContextManager -from typing import TYPE_CHECKING if TYPE_CHECKING: from alembic.config import Config @@ -92,9 +90,9 @@ def migrate_tenant(slug: str) -> None: Swaps settings.UPLOADS_SCHEMA while Alembic runs, so it is serialised and must only be called from startup or a CLI, never inside a request. """ - from alembic import command from alembic.config import Config + from alembic import command from api.db import alembic_ini_path with _migrate_lock: @@ -147,22 +145,33 @@ def provision_tenant_role(cur: cursor, slug: str) -> str: f"Tenant {slug!r}: the owner {settings.PG_USER!r} may not create the tenant's database role {role!r} " f"(#297). Give it CREATEROLE, as a superuser or the server administrator: ALTER ROLE " f"{settings.PG_USER} CREATEROLE; (build/deploy_all.sh does this for the environments it deploys). " - "See DECISIONS/2026-11-24-per-tenant-db-roles.md.") from exc - cur.execute(sql.SQL("COMMENT ON ROLE {} IS {}").format(r, sql.Literal( - f"Tenant {slug} in database {settings.PG_DATABASE}: rights on schema {schema} only (#297)"))) + "See DECISIONS/2026-11-24-per-tenant-db-roles.md." + ) from exc + cur.execute( + sql.SQL("COMMENT ON ROLE {} IS {}").format( + r, sql.Literal(f"Tenant {slug} in database {settings.PG_DATABASE}: rights on schema {schema} only (#297)") + ) + ) cur.execute(sql.SQL("GRANT {} TO CURRENT_USER WITH INHERIT TRUE, SET TRUE").format(r)) grant_schema(cur, schema, role, create=True) - cur.execute(sql.SQL("ALTER DEFAULT PRIVILEGES IN SCHEMA {} GRANT SELECT, INSERT, UPDATE, DELETE " - "ON TABLES TO {}").format(s, r)) - cur.execute(sql.SQL("ALTER DEFAULT PRIVILEGES IN SCHEMA {} GRANT USAGE, SELECT, UPDATE " - "ON SEQUENCES TO {}").format(s, r)) + cur.execute( + sql.SQL("ALTER DEFAULT PRIVILEGES IN SCHEMA {} GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO {}").format( + s, r + ) + ) + cur.execute( + sql.SQL("ALTER DEFAULT PRIVILEGES IN SCHEMA {} GRANT USAGE, SELECT, UPDATE ON SEQUENCES TO {}").format(s, r) + ) runtime = settings.APP_DB_USER if runtime and runtime != settings.PG_USER: rt = sql.Identifier(runtime) cur.execute(sql.SQL("GRANT {} TO {} WITH INHERIT FALSE, SET TRUE").format(r, rt)) # Tables the runtime role created before #297 (it owned them, so a REVOKE alone would not stop it). - cur.execute("SELECT relname FROM pg_class WHERE relnamespace = %s::regnamespace AND relkind IN ('r', 'p') " - "AND pg_get_userbyid(relowner) = %s", (schema, runtime)) + cur.execute( + "SELECT relname FROM pg_class WHERE relnamespace = %s::regnamespace AND relkind IN ('r', 'p') " + "AND pg_get_userbyid(relowner) = %s", + (schema, runtime), + ) for (table,) in cur.fetchall(): cur.execute(sql.SQL("ALTER TABLE {}.{} OWNER TO {}").format(s, sql.Identifier(table), r)) cur.execute(sql.SQL("REVOKE ALL ON ALL TABLES IN SCHEMA {} FROM {}").format(s, rt)) @@ -216,8 +225,11 @@ def template_te_version(cur: cursor, template: str) -> str | None: def _te_tables_present(cur: cursor, schema: str) -> set[str]: - cur.execute("SELECT c.relname FROM pg_class c WHERE c.relnamespace = to_regnamespace(%s) " - "AND c.relkind = 'r' AND c.relname = ANY(%s)", (schema, TE_TABLES)) + cur.execute( + "SELECT c.relname FROM pg_class c WHERE c.relnamespace = to_regnamespace(%s) " + "AND c.relkind = 'r' AND c.relname = ANY(%s)", + (schema, TE_TABLES), + ) return {r[0] for r in cur.fetchall()} @@ -235,9 +247,9 @@ def migrate_te_schema(conn: connection, cur: cursor, schema: str) -> str: tenant across processes by an advisory lock, so two API workers starting together cannot both provision or upgrade the same schema. Commits. """ - from alembic import command from alembic.util import CommandError + from alembic import command from api.db import fetch_one cfg, template = _te_config(schema), settings.TE_SCHEMA @@ -254,7 +266,8 @@ def migrate_te_schema(conn: connection, cur: cursor, schema: str) -> str: if template_version is None: raise RuntimeError( f"T&E template schema {template!r} has no te_schema_version stamp; it was deployed by an " - "older build/te_core_schema.sql. Redeploy it with build/deploy_all.sh first.") + "older build/te_core_schema.sql. Redeploy it with build/deploy_all.sh first." + ) provision_te_tables(cur, schema, template) conn.commit() action, stamp = "provisioned", template_version @@ -269,9 +282,11 @@ def migrate_te_schema(conn: connection, cur: cursor, schema: str) -> str: command.stamp(cfg, stamp) command.upgrade(cfg, "head") except CommandError as exc: - raise RuntimeError(f"Tenant schema {schema!r}: {exc}. If the template is newer than this release, " - "deploy the matching release; if older, redeploy it with " - "build/deploy_all.sh.") from exc + raise RuntimeError( + f"Tenant schema {schema!r}: {exc}. If the template is newer than this release, " + "deploy the matching release; if older, redeploy it with " + "build/deploy_all.sh." + ) from exc return action finally: conn.rollback() @@ -287,15 +302,18 @@ def _use_template_names(cur: cursor, schema: str, template: str, tables: list[st that drops or renames an index by name would then work on the template and fail on every tenant. Matched on what each index is (table, columns, method), since the names differ. """ + def listing(sch: str) -> list[tuple[Any, ...]]: cur.execute( "SELECT t.relname, i.relname, pg_get_indexdef(i.oid), c.conname FROM pg_index x " "JOIN pg_class i ON i.oid = x.indexrelid JOIN pg_class t ON t.oid = x.indrelid " "LEFT JOIN pg_constraint c ON c.conindid = x.indexrelid AND c.contype = 'u' " "WHERE t.relnamespace = %s::regnamespace AND t.relname = ANY(%s) AND NOT x.indisprimary", - (sch, tables)) - return [(t, i, re.sub(r"^CREATE (UNIQUE )?INDEX \S+ ON \S+ ", r"\1", d), con) - for t, i, d, con in cur.fetchall()] + (sch, tables), + ) + return [ + (t, i, re.sub(r"^CREATE (UNIQUE )?INDEX \S+ ON \S+ ", r"\1", d), con) for t, i, d, con in cur.fetchall() + ] mine = {(t, tail): (i, con) for t, i, tail, con in listing(schema)} for table, name, tail, constraint in listing(template): @@ -303,11 +321,17 @@ def listing(sch: str) -> list[tuple[Any, ...]]: if have is None or have[0] == name: continue if constraint and have[1]: # renaming a unique constraint renames its index too - cur.execute(sql.SQL("ALTER TABLE {}.{} RENAME CONSTRAINT {} TO {}").format( - sql.Identifier(schema), sql.Identifier(table), sql.Identifier(have[1]), sql.Identifier(constraint))) + cur.execute( + sql.SQL("ALTER TABLE {}.{} RENAME CONSTRAINT {} TO {}").format( + sql.Identifier(schema), sql.Identifier(table), sql.Identifier(have[1]), sql.Identifier(constraint) + ) + ) elif not constraint and not have[1]: - cur.execute(sql.SQL("ALTER INDEX {}.{} RENAME TO {}").format( - sql.Identifier(schema), sql.Identifier(have[0]), sql.Identifier(name))) + cur.execute( + sql.SQL("ALTER INDEX {}.{} RENAME TO {}").format( + sql.Identifier(schema), sql.Identifier(have[0]), sql.Identifier(name) + ) + ) def provision_te_tables(cur: cursor, schema: str, template: str) -> int: @@ -324,20 +348,30 @@ def provision_te_tables(cur: cursor, schema: str, template: str) -> int: cur.execute("SET LOCAL search_path = pg_catalog") # makes catalog DDL schema-qualified cur.execute("SELECT quote_ident(%s), quote_ident(%s)", (template, schema)) qt, qs = fetch_one(cur) - cur.execute("SELECT relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " - "WHERE n.nspname = %s AND c.relkind = 'r' AND c.relname = ANY(%s)", (template, TE_TABLES)) + cur.execute( + "SELECT relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE n.nspname = %s AND c.relkind = 'r' AND c.relname = ANY(%s)", + (template, TE_TABLES), + ) if {r[0] for r in cur.fetchall()} != set(TE_TABLES): - raise RuntimeError(f"T&E template schema {template!r} is missing or incomplete; " - "deploy it with build/deploy_all.sh first") - cur.execute("SELECT relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " - "WHERE n.nspname = %s AND c.relname = ANY(%s)", (schema, TE_TABLES)) + raise RuntimeError( + f"T&E template schema {template!r} is missing or incomplete; deploy it with build/deploy_all.sh first" + ) + cur.execute( + "SELECT relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE n.nspname = %s AND c.relname = ANY(%s)", + (schema, TE_TABLES), + ) present = {r[0] for r in cur.fetchall()} missing = [t for t in TE_TABLES if t not in present] if not missing: return 0 for table in missing: - cur.execute(sql.SQL("CREATE TABLE {}.{} (LIKE {}.{} INCLUDING ALL)").format( - sql.Identifier(schema), sql.Identifier(table), sql.Identifier(template), sql.Identifier(table))) + cur.execute( + sql.SQL("CREATE TABLE {}.{} (LIKE {}.{} INCLUDING ALL)").format( + sql.Identifier(schema), sql.Identifier(table), sql.Identifier(template), sql.Identifier(table) + ) + ) _use_template_names(cur, schema, template, missing) def defs(query: str) -> list[tuple[Any, ...]]: @@ -345,20 +379,28 @@ def defs(query: str) -> list[tuple[Any, ...]]: return cur.fetchall() for table, name, ddl in defs( - "SELECT r.relname, c.conname, pg_get_constraintdef(c.oid) FROM pg_constraint c " - "JOIN pg_class r ON r.oid = c.conrelid JOIN pg_namespace n ON n.oid = r.relnamespace " - "WHERE n.nspname = %s AND c.contype = 'f' AND r.relname = ANY(%s) ORDER BY c.conname"): - cur.execute(sql.SQL("ALTER TABLE {}.{} ADD CONSTRAINT {} ").format( - sql.Identifier(schema), sql.Identifier(table), sql.Identifier(name)) - + sql.SQL(ddl.replace(f"REFERENCES {qt}.", f"REFERENCES {qs}."))) - cur.execute("SELECT pg_get_functiondef(p.oid) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace " - "WHERE n.nspname = %s AND p.proname IN ('set_updated_at', 'te_fill_program_id')", (template,)) + "SELECT r.relname, c.conname, pg_get_constraintdef(c.oid) FROM pg_constraint c " + "JOIN pg_class r ON r.oid = c.conrelid JOIN pg_namespace n ON n.oid = r.relnamespace " + "WHERE n.nspname = %s AND c.contype = 'f' AND r.relname = ANY(%s) ORDER BY c.conname" + ): + cur.execute( + sql.SQL("ALTER TABLE {}.{} ADD CONSTRAINT {} ").format( + sql.Identifier(schema), sql.Identifier(table), sql.Identifier(name) + ) + + sql.SQL(ddl.replace(f"REFERENCES {qt}.", f"REFERENCES {qs}.")) + ) + cur.execute( + "SELECT pg_get_functiondef(p.oid) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace " + "WHERE n.nspname = %s AND p.proname IN ('set_updated_at', 'te_fill_program_id')", + (template,), + ) for (ddl,) in cur.fetchall(): cur.execute(sql.SQL(ddl.replace(f"FUNCTION {qt}.", f"FUNCTION {qs}.", 1))) for (ddl,) in defs( - "SELECT pg_get_triggerdef(t.oid) FROM pg_trigger t JOIN pg_class r ON r.oid = t.tgrelid " - "JOIN pg_namespace n ON n.oid = r.relnamespace " - "WHERE n.nspname = %s AND NOT t.tgisinternal AND r.relname = ANY(%s)"): + "SELECT pg_get_triggerdef(t.oid) FROM pg_trigger t JOIN pg_class r ON r.oid = t.tgrelid " + "JOIN pg_namespace n ON n.oid = r.relnamespace " + "WHERE n.nspname = %s AND NOT t.tgisinternal AND r.relname = ANY(%s)" + ): cur.execute(sql.SQL(ddl.replace(f" ON {qt}.", f" ON {qs}.").replace(f"FUNCTION {qt}.", f"FUNCTION {qs}."))) cur.execute("RESET search_path") return len(missing) diff --git a/build/csv/validator.py b/build/csv/validator.py index 963f114..a8a2a47 100644 --- a/build/csv/validator.py +++ b/build/csv/validator.py @@ -4,7 +4,7 @@ import os import sys -GREEN, YELLOW, RED, NC = '\033[0;32m', '\033[1;33m', '\033[0;31m', '\033[0m' +GREEN, YELLOW, RED, NC = "\033[0;32m", "\033[1;33m", "\033[0;31m", "\033[0m" def log(m): @@ -36,10 +36,7 @@ def clean(cell): SKIP_FILE = os.environ.get("SKIP_FILE", "") FORCE_DELIM = os.environ.get("CSV_DELIMITER", "") -missing = [ - v for v in ("CSV_FILE", "VALID_CSV", "SKIP_FILE") - if not os.environ.get(v) -] +missing = [v for v in ("CSV_FILE", "VALID_CSV", "SKIP_FILE") if not os.environ.get(v)] if missing: err(f"Missing required environment variables: {', '.join(missing)}") sys.exit(1) @@ -54,8 +51,7 @@ def detect_delimiter(path): if FORCE_DELIM: return FORCE_DELIM.encode().decode("unicode_escape") try: - with open(path, "r", encoding="utf-8-sig", - errors="surrogateescape", newline="") as fh: + with open(path, "r", encoding="utf-8-sig", errors="surrogateescape", newline="") as fh: sample = fh.read(8192) if not sample: return "," @@ -66,14 +62,18 @@ def detect_delimiter(path): DELIM = detect_delimiter(CSV_FILE) label = { - ",": "comma", ";": "semicolon", "\t": "tab", "|": "pipe", + ",": "comma", + ";": "semicolon", + "\t": "tab", + "|": "pipe", }.get(DELIM, repr(DELIM)) try: - with open(CSV_FILE, "r", encoding="utf-8-sig", - errors="surrogateescape", newline="") as src, \ - open(VALID_CSV, "w", encoding="utf-8", newline="") as vf, \ - open(SKIP_FILE, "w", encoding="utf-8", newline="") as sf: + with ( + open(CSV_FILE, "r", encoding="utf-8-sig", errors="surrogateescape", newline="") as src, + open(VALID_CSV, "w", encoding="utf-8", newline="") as vf, + open(SKIP_FILE, "w", encoding="utf-8", newline="") as sf, + ): reader = csv.reader(src, delimiter=DELIM) wv = csv.writer(vf, delimiter=DELIM) ws = csv.writer(sf, delimiter=DELIM) @@ -88,8 +88,7 @@ def detect_delimiter(path): err("Header row is empty.") sys.exit(1) if any(has_bad_bytes(h) for h in headers): - err("Header row contains invalid UTF-8 bytes — " - "cannot process file.") + err("Header row contains invalid UTF-8 bytes — cannot process file.") sys.exit(1) log(f"Delimiter: {label}") log(f"Header: {ncols} columns — {' | '.join(headers)}") @@ -101,25 +100,15 @@ def detect_delimiter(path): valid = skip = 0 for n, row in enumerate(reader, start=2): if not any(c.strip() for c in row): - ws.writerow( - [clean(c) for c in row] - + ["empty row — all values blank"] - ) + ws.writerow([clean(c) for c in row] + ["empty row — all values blank"]) skip += 1 continue if any(has_bad_bytes(c) for c in row): - ws.writerow( - [clean(c) for c in row] - + [f"invalid UTF-8 bytes at line {n}"] - ) + ws.writerow([clean(c) for c in row] + [f"invalid UTF-8 bytes at line {n}"]) skip += 1 continue if len(row) != ncols: - ws.writerow( - [clean(c) for c in row] - + [f"column mismatch — expected {ncols}, " - f"got {len(row)}"] - ) + ws.writerow([clean(c) for c in row] + [f"column mismatch — expected {ncols}, got {len(row)}"]) skip += 1 continue wv.writerow(row) diff --git a/container/smoke_test.py b/container/smoke_test.py index 8966993..a0a52f9 100644 --- a/container/smoke_test.py +++ b/container/smoke_test.py @@ -17,6 +17,7 @@ Exits 0 only if every check that ran passed. """ + from __future__ import annotations import json @@ -31,8 +32,9 @@ TOTAL = 7 -def call(url: str, *, method: str = "GET", headers: dict | None = None, body: dict | None = None, - timeout: float = 15.0) -> tuple[int, str]: +def call( + url: str, *, method: str = "GET", headers: dict | None = None, body: dict | None = None, timeout: float = 15.0 +) -> tuple[int, str]: """Return (status, text). An HTTP error is a status, not an exception.""" if not url.lower().startswith(("http://", "https://")): raise ValueError(f"the smoke test only calls http(s) URLs, got {url!r}") # urlopen would follow file: @@ -91,8 +93,9 @@ def check(name: str, ok: bool, detail: str = "") -> None: check("API rejects a request without a session", status == 401, f"got HTTP {status}") if with_login: - status, text = call(f"{API}/api/auth/login", method="POST", - body={"tenant": tenant, "username": user, "password": password}) + status, text = call( + f"{API}/api/auth/login", method="POST", body={"tenant": tenant, "username": user, "password": password} + ) token = "" try: token = json.loads(text).get("token", "") if status == 200 else "" @@ -102,22 +105,28 @@ def check(name: str, ok: bool, detail: str = "") -> None: auth = {"Authorization": f"Bearer {token}"} status, text = call(f"{API}/api/auth/me", headers=auth) - check("session is tenant_admin", status == 200 and '"role":"tenant_admin"' in compact(text), - f"HTTP {status}") + check("session is tenant_admin", status == 200 and '"role":"tenant_admin"' in compact(text), f"HTTP {status}") tag = time.time_ns() # unique name and content, so the test can be re-run name = f"smoke_{tag}.csv" - status, text = call(f"{API}/api/csv/upload", method="POST", headers=auth, - body={"fileName": name, "content": f"a,b\n1,{tag}\n2,y\n"}) + status, text = call( + f"{API}/api/csv/upload", + method="POST", + headers=auth, + body={"fileName": name, "content": f"a,b\n1,{tag}\n2,y\n"}, + ) check("upload a CSV (2 rows inserted)", '"insertedRows":2' in compact(text), f"HTTP {status}: {text[:200]}") status, text = call(f"{API}/api/csv/files", headers=auth) - check("upload listed with persisted counts", status == 200 and '"total_rows":2' in compact(text), - f"HTTP {status}") + check( + "upload listed with persisted counts", status == 200 and '"total_rows":2' in compact(text), f"HTTP {status}" + ) else: # Counted as the four checks it stands for, so the run reports "3 of 7", never a pass. - print("FAIL sign-in, upload and listing checks: set SMOKE_TENANT, SMOKE_USER and SMOKE_PASSWORD " - "(the installer's first tenant admin)") + print( + "FAIL sign-in, upload and listing checks: set SMOKE_TENANT, SMOKE_USER and SMOKE_PASSWORD " + "(the installer's first tenant admin)" + ) status, text = call(f"{FRONTEND}/") check("frontend serves the app", status == 200 and " str: a = self.accounts[who] - res = requests.post(f"{self.api}/api/auth/login", timeout=30, - json={"tenant": a.tenant, "username": a.username, "password": PASSWORD}) + res = requests.post( + f"{self.api}/api/auth/login", + timeout=30, + json={"tenant": a.tenant, "username": a.username, "password": PASSWORD}, + ) res.raise_for_status() return res.json()["token"] def upload(self, who: str, name: str, content: str, **extra) -> dict: - res = requests.post(f"{self.api}/api/csv/upload", timeout=60, - headers={"Authorization": f"Bearer {self.token(who)}"}, - json={"fileName": name, "content": content, **extra}) + res = requests.post( + f"{self.api}/api/csv/upload", + timeout=60, + headers={"Authorization": f"Bearer {self.token(who)}"}, + json={"fileName": name, "content": content, **extra}, + ) res.raise_for_status() return res.json() @@ -96,8 +103,14 @@ def prerequisites(): that is missing at once (e2e/preflight.py), rather than the first error a missing piece happens to raise.""" ports = [API_PORT, WEB_PORT, SHELL_PORT] found = preflight.problems( - root=ROOT, env=os.environ, pg_host=settings.PG_HOST, pg_port=settings.PG_PORT, - probe=pg_login.server_available, ports=ports, is_free=_port_is_free) + root=ROOT, + env=os.environ, + pg_host=settings.PG_HOST, + pg_port=settings.PG_PORT, + probe=pg_login.server_available, + ports=ports, + is_free=_port_is_free, + ) if found: pytest.exit(preflight.report(found), returncode=3) @@ -123,21 +136,51 @@ def stack(): api, web, shell = (f"http://127.0.0.1:{p}" for p in (API_PORT, WEB_PORT, SHELL_PORT)) env = {**os.environ, "CORS_ORIGINS": web, "API_RATE_LIMIT_WRITES": "0", "API_RATE_LIMIT_READS": "0"} - subprocess.run(["npm", "run", "build"], cwd=ROOT / "csv-table-hub-main", check=True, capture_output=True, - env={**env, "NITRO_PRESET": "node-server", "VITE_API_BASE": api}) # VITE_API_BASE is baked in + subprocess.run( + ["npm", "run", "build"], + cwd=ROOT / "csv-table-hub-main", + check=True, + capture_output=True, + env={**env, "NITRO_PRESET": "node-server", "VITE_API_BASE": api}, + ) # VITE_API_BASE is baked in procs = [ - subprocess.Popen([sys.executable, "-m", "uvicorn", "api.main:app", "--port", str(API_PORT)], - cwd=ROOT, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True), + subprocess.Popen( + [sys.executable, "-m", "uvicorn", "api.main:app", "--port", str(API_PORT)], + cwd=ROOT, + env=env, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ), # The production build, served as the offline bundle serves it: what ships, not the dev server. - subprocess.Popen(["node", ".output/server/index.mjs"], cwd=ROOT / "csv-table-hub-main", - env={**env, "PORT": str(WEB_PORT), "HOST": "127.0.0.1"}, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True), + subprocess.Popen( + ["node", ".output/server/index.mjs"], + cwd=ROOT / "csv-table-hub-main", + env={**env, "PORT": str(WEB_PORT), "HOST": "127.0.0.1"}, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ), # The Streamlit app, started the way its README says: from its own folder, with no flag for telemetry, # so the shipped .streamlit/config.toml is what is tested. - subprocess.Popen([sys.executable, "-m", "streamlit", "run", "app.py", "--server.headless", "true", - "--server.port", str(SHELL_PORT)], - cwd=ROOT / "streamlit_app", env={**env, "API_URL": api}, stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, start_new_session=True), + subprocess.Popen( + [ + sys.executable, + "-m", + "streamlit", + "run", + "app.py", + "--server.headless", + "true", + "--server.port", + str(SHELL_PORT), + ], + cwd=ROOT / "streamlit_app", + env={**env, "API_URL": api}, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ), ] try: _wait_for(f"{api}/api/health", "the API") @@ -158,12 +201,18 @@ def stack(): with Conn() as conn, conn.cursor() as cur: for t in tenant_ids: cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(t)))) - cur.execute(sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (t,)) - drop_tenant_role(cur, t) # #297: each tenant has its own database role - cur.execute(sql.SQL("DELETE FROM {}.users WHERE username LIKE %s OR username LIKE %s OR username LIKE %s " - "OR username LIKE %s").format(sql.Identifier(settings.CONTROL_SCHEMA)), - tuple(f"{p}_{tag}" for p in ("admin", "uploader", "reviewer", "other"))) + cur.execute( + sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format(sql.Identifier(settings.CONTROL_SCHEMA)), + (t,), + ) + drop_tenant_role(cur, t) # #297: each tenant has its own database role + cur.execute( + sql.SQL( + "DELETE FROM {}.users WHERE username LIKE %s OR username LIKE %s OR username LIKE %s " + "OR username LIKE %s" + ).format(sql.Identifier(settings.CONTROL_SCHEMA)), + tuple(f"{p}_{tag}" for p in ("admin", "uploader", "reviewer", "other")), + ) conn.commit() db.close_pool() @@ -177,9 +226,12 @@ def browser(): except PlaywrightError as e: if "Executable doesn't exist" not in str(e): raise - pytest.exit("The browser tests cannot start: Playwright's Chromium is not installed for this " - "Playwright version. Run `playwright install chromium`, or set E2E_CHROMIUM to an " - "installed Chrome or Chromium.", returncode=3) + pytest.exit( + "The browser tests cannot start: Playwright's Chromium is not installed for this " + "Playwright version. Run `playwright install chromium`, or set E2E_CHROMIUM to an " + "installed Chrome or Chromium.", + returncode=3, + ) yield b b.close() diff --git a/e2e/preflight.py b/e2e/preflight.py index 449bfa2..3de8594 100644 --- a/e2e/preflight.py +++ b/e2e/preflight.py @@ -32,8 +32,10 @@ def check_browser(env: Mapping[str, str]) -> str | None: and a missing one is reported by conftest's browser fixture, which is the only place that can tell.""" override = env.get("E2E_CHROMIUM") if override and not Path(override).exists(): - return (f"E2E_CHROMIUM points at {override}, which does not exist. Unset it to use Playwright's own " - "Chromium (`playwright install chromium`), or point it at an installed Chrome or Chromium") + return ( + f"E2E_CHROMIUM points at {override}, which does not exist. Unset it to use Playwright's own " + "Chromium (`playwright install chromium`), or point it at an installed Chrome or Chromium" + ) return None @@ -43,8 +45,10 @@ def check_postgres(host: str, port: str | int, probe: Callable[[str, str], tuple up, why = probe(host, str(port)) if up: return None - return (f"PostgreSQL is not accepting connections at {host}:{port} ({why}). Start it, or set PGHOST and " - "PGPORT to where it is, and deploy the dev database (bash build/deploy_all.sh dev)") + return ( + f"PostgreSQL is not accepting connections at {host}:{port} ({why}). Start it, or set PGHOST and " + "PGPORT to where it is, and deploy the dev database (bash build/deploy_all.sh dev)" + ) def check_ports(ports: Iterable[int], is_free: Callable[[int], bool]) -> list[str]: @@ -63,12 +67,24 @@ def check_streamlit() -> str | None: return "Streamlit is not installed: pip install -r streamlit_app/requirements.txt" -def problems(*, root: Path, env: Mapping[str, str], pg_host: str, pg_port: str | int, - probe: Callable[[str, str], tuple[bool, str]], ports: Iterable[int], - is_free: Callable[[int], bool]) -> list[str]: +def problems( + *, + root: Path, + env: Mapping[str, str], + pg_host: str, + pg_port: str | int, + probe: Callable[[str, str], tuple[bool, str]], + ports: Iterable[int], + is_free: Callable[[int], bool], +) -> list[str]: """Every problem found, in the order a person would fix them. Empty when the tests can start.""" - found = [check_playwright(), check_browser(env), check_streamlit(), check_node_modules(root), - check_postgres(pg_host, pg_port, probe)] + found = [ + check_playwright(), + check_browser(env), + check_streamlit(), + check_node_modules(root), + check_postgres(pg_host, pg_port, probe), + ] return [m for m in found if m] + check_ports(ports, is_free) diff --git a/e2e/streamlit_helpers.py b/e2e/streamlit_helpers.py index 03361d7..c64b065 100644 --- a/e2e/streamlit_helpers.py +++ b/e2e/streamlit_helpers.py @@ -9,11 +9,10 @@ import re +from conftest import shell_sign_in from playwright.sync_api import TimeoutError as PlaywrightTimeoutError from playwright.sync_api import expect -from conftest import shell_sign_in - def idle(page) -> None: """Wait until the run has finished (Streamlit's "Running" indicator is gone).""" diff --git a/e2e/test_react_ui.py b/e2e/test_react_ui.py index ceefce4..cbdca30 100644 --- a/e2e/test_react_ui.py +++ b/e2e/test_react_ui.py @@ -5,9 +5,8 @@ import re import uuid -from playwright.sync_api import expect - from conftest import react_sign_in +from playwright.sync_api import expect def _tag() -> str: diff --git a/e2e/test_streamlit_history.py b/e2e/test_streamlit_history.py index 1d379aa..3cd54ce 100644 --- a/e2e/test_streamlit_history.py +++ b/e2e/test_streamlit_history.py @@ -14,10 +14,9 @@ import uuid import pytest +from conftest import shell_sign_in from openpyxl import load_workbook from playwright.sync_api import expect - -from conftest import shell_sign_in from streamlit_helpers import choose_option, click_and_download, idle, open_page PAYLOADS = ["=1+1", "+cmd|' /C calc'!A0", "-2+3", "@SUM(A1:A2)"] @@ -44,6 +43,7 @@ def _cells(page) -> str: # ── the history is the tenant's, not the browser's ───────────────────────────────────────────── + def test_an_upload_by_one_person_is_in_the_history_of_another_in_a_fresh_browser(page, stack, failing): open_page(page, stack, "reviewer", "Import history", "Import history") @@ -70,9 +70,12 @@ def test_another_tenants_history_is_empty_and_shows_none_of_this_ones(page, stac # ── filters ──────────────────────────────────────────────────────────────────────────────────── + def test_the_file_name_and_status_filters_narrow_the_list(page, stack, failing): clean = _unique("clean") - assert stack.upload("uploader", clean, f"id,name\n1,{clean}\n2,b\n", types=["int8", "text"])["status"] == "ok" # (identical bytes are a duplicate) + assert ( + stack.upload("uploader", clean, f"id,name\n1,{clean}\n2,b\n", types=["int8", "text"])["status"] == "ok" + ) # (identical bytes are a duplicate) open_page(page, stack, "reviewer", "Import history", "Import history") expect(page.get_by_role("cell", name=clean)).to_be_visible() expect(page.get_by_role("cell", name=failing)).to_be_visible() @@ -95,6 +98,7 @@ def test_the_file_name_and_status_filters_narrow_the_list(page, stack, failing): # ── one import: why rows failed, and the reports ─────────────────────────────────────────────── + def _open_import(page, stack, failing, who="reviewer"): open_page(page, stack, who, "Import history", "Import history") choose_option(page, "Details of an import", re.compile(re.escape(failing))) @@ -143,11 +147,14 @@ def test_the_download_is_named_for_the_file(page, stack, failing): page.get_by_role("button", name="Error report (CSV)").click() stem = re.sub(r"\.csv$", "", failing) - assert re.fullmatch(rf"errors-{re.escape(stem)}-\d{{4}}-\d\d-\d\dT\d\d-\d\d-\d\dZ\.csv", taken.value.suggested_filename) + assert re.fullmatch( + rf"errors-{re.escape(stem)}-\d{{4}}-\d\d-\d\dT\d\d-\d\d-\d\dZ\.csv", taken.value.suggested_filename + ) # ── a report of the whole filtered list ──────────────────────────────────────────────────────── + def test_a_report_of_every_matching_import_downloads_as_csv_and_xlsx(page, stack, failing): open_page(page, stack, "reviewer", "Import history", "Import history") page.get_by_label("File name contains").fill(failing[:12]) @@ -171,6 +178,7 @@ def test_a_report_of_every_matching_import_downloads_as_csv_and_xlsx(page, stack # ── text from a file is shown as written ─────────────────────────────────────────────────────── + def test_a_file_name_and_a_cell_that_look_like_links_are_text_not_links(page, stack): name = f"**bold**_{uuid.uuid4().hex[:6]}.csv" link = "[click here](https://evil.example/login)" @@ -183,12 +191,14 @@ def test_a_file_name_and_a_cell_that_look_like_links_are_text_not_links(page, st expect(page.get_by_role("cell", name=link, exact=False).first).to_be_visible() assert page.locator('a[href*="evil.example"]').count() == 0, "a cell must not become a link" - assert page.locator('[data-testid="stTable"] strong, [data-testid="stHeading"] strong').count() == 0, \ + assert page.locator('[data-testid="stTable"] strong, [data-testid="stHeading"] strong').count() == 0, ( "a file name must not become bold" + ) # ── the server's audit events ────────────────────────────────────────────────────────────────── + def test_roles_that_may_not_read_the_audit_log_are_not_offered_it(page, stack, failing): open_page(page, stack, "reviewer", "Import history", "Import history") diff --git a/e2e/test_streamlit_review.py b/e2e/test_streamlit_review.py index 8002907..8b580ca 100644 --- a/e2e/test_streamlit_review.py +++ b/e2e/test_streamlit_review.py @@ -12,6 +12,7 @@ import uuid import pytest +from conftest import PASSWORD, shell_sign_in from playwright.sync_api import TimeoutError as PlaywrightTimeoutError from playwright.sync_api import expect from psycopg2 import sql @@ -19,7 +20,6 @@ from api import db # noqa: F401 (the stack fixture has opened the pool) from api.config import settings from api.db import Conn -from conftest import PASSWORD, shell_sign_in # 30 rows; every seventh amount is "x", so rows 7, 14, 21 and 28 fail the int8 type. ROWS = "".join(f"{i},person{i},{'x' if i % 7 == 0 else i * 10}\n" for i in range(1, 31)) @@ -118,6 +118,7 @@ def _type_row_number(page, n: int) -> None: # ── what the old spike's tests checked, on the real screen ───────────────────────────────────────── + def test_an_uploader_can_look_but_not_change(page, stack, upload): _open_review(page, stack, "uploader", upload) expect(page.get_by_text("Only reviewers and tenant admins can make changes.")).to_be_visible() @@ -181,6 +182,7 @@ def test_signing_out_leaves_nothing_for_the_next_tenant(page, stack, upload): # ── new with this screen ──────────────────────────────────────────────────────────────────────────── + def test_the_grid_and_the_row_number_box_stay_in_step(page, stack, upload): _open_review(page, stack, "reviewer", upload) box = _row_number_box(page) @@ -199,8 +201,9 @@ def test_the_grid_and_the_row_number_box_stay_in_step(page, stack, upload): def test_a_row_chosen_on_one_page_does_not_break_the_next(page, stack): name = _unique("long") - res = stack.upload("admin", name, "id,name\n" + "".join(f"{i},p{i}\n" for i in range(1, 251)), - types=["int8", "text"]) + res = stack.upload( + "admin", name, "id,name\n" + "".join(f"{i},p{i}\n" for i in range(1, 251)), types=["int8", "text"] + ) assert res["status"] == "ok", res _open_review(page, stack, "admin", name) expect(page.get_by_label("Page (of 3)")).to_be_visible() @@ -219,7 +222,9 @@ def test_a_row_chosen_on_one_page_does_not_break_the_next(page, stack): def test_the_list_offers_every_attempt_and_can_be_cut_to_the_failed_and_partial_ones(page, stack, upload): clean = _unique("clean") - assert stack.upload("admin", clean, f"id,name\n1,{clean}\n2,b\n", types=["int8", "text"])["status"] == "ok" # (identical bytes are a duplicate) + assert ( + stack.upload("admin", clean, f"id,name\n1,{clean}\n2,b\n", types=["int8", "text"])["status"] == "ok" + ) # (identical bytes are a duplicate) _open_review(page, stack, "admin") # The tenant's other tests upload files too, so the list is long: type to narrow it, as a person would. @@ -230,7 +235,9 @@ def offered(fragment: str, option: "re.Pattern | str"): return page.get_by_role("option", name=option) expect(offered(clean[:14], re.compile(re.escape(clean) + " · Imported"))).to_be_visible() - expect(offered(upload[:14], re.compile(re.escape(upload) + r" · Partly imported · 4 of 30 rows failed"))).to_be_visible() + expect( + offered(upload[:14], re.compile(re.escape(upload) + r" · Partly imported · 4 of 30 rows failed")) + ).to_be_visible() page.keyboard.press("Escape") page.get_by_text("Only failed or partly failed uploads").click() @@ -261,9 +268,13 @@ def test_a_session_the_server_ended_sends_the_next_save_back_to_sign_in(page, st page.get_by_role("tab", name="Exclude row").click() with Conn() as conn, conn.cursor() as cur: # as the API does when a password is reset: revoke the user's sessions - cur.execute(sql.SQL("UPDATE {c}.sessions SET revoked_at = now() WHERE user_id = " - "(SELECT id FROM {c}.users WHERE username = %s)").format( - c=sql.Identifier(settings.CONTROL_SCHEMA)), (a.username,)) + cur.execute( + sql.SQL( + "UPDATE {c}.sessions SET revoked_at = now() WHERE user_id = " + "(SELECT id FROM {c}.users WHERE username = %s)" + ).format(c=sql.Identifier(settings.CONTROL_SCHEMA)), + (a.username,), + ) conn.commit() page.get_by_label("Reason to exclude this row (required)").fill("too late") page.get_by_role("button", name="Exclude this row").click() diff --git a/e2e/test_streamlit_shell.py b/e2e/test_streamlit_shell.py index 474f6b8..3d33c02 100644 --- a/e2e/test_streamlit_shell.py +++ b/e2e/test_streamlit_shell.py @@ -10,6 +10,7 @@ import re import uuid +from conftest import PASSWORD, shell_sign_in, shell_sign_in_as from playwright.sync_api import expect from psycopg2 import sql @@ -17,7 +18,6 @@ from api.config import settings from api.db import Conn from api.services import accounts -from conftest import PASSWORD, shell_sign_in, shell_sign_in_as NEW_PASSWORD = "a brand new passphrase 42" @@ -119,8 +119,10 @@ def test_changing_your_own_password_works_through_the_real_api_and_the_old_one_s _signed_in_as(page, "uploader") finally: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("DELETE FROM {}.users WHERE username = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (username,)) + cur.execute( + sql.SQL("DELETE FROM {}.users WHERE username = %s").format(sql.Identifier(settings.CONTROL_SCHEMA)), + (username,), + ) conn.commit() @@ -148,9 +150,13 @@ def test_a_session_ended_on_the_server_sends_the_next_click_back_to_sign_in(page page.get_by_role("heading", name="Change password").wait_for() with Conn() as conn, conn.cursor() as cur: # as the API does when a password is reset: revoke the user's sessions - cur.execute(sql.SQL("UPDATE {c}.sessions SET revoked_at = now() WHERE user_id = " - "(SELECT id FROM {c}.users WHERE username = %s)").format( - c=sql.Identifier(settings.CONTROL_SCHEMA)), (a.username,)) + cur.execute( + sql.SQL( + "UPDATE {c}.sessions SET revoked_at = now() WHERE user_id = " + "(SELECT id FROM {c}.users WHERE username = %s)" + ).format(c=sql.Identifier(settings.CONTROL_SCHEMA)), + (a.username,), + ) conn.commit() page.get_by_label("Current password").fill(PASSWORD) diff --git a/e2e/test_streamlit_upload.py b/e2e/test_streamlit_upload.py index 75a3a6b..ac9bb30 100644 --- a/e2e/test_streamlit_upload.py +++ b/e2e/test_streamlit_upload.py @@ -15,13 +15,13 @@ import uuid import requests +from conftest import ROOT from openpyxl import load_workbook from playwright.sync_api import expect +from streamlit_helpers import choose_option, click_and_download, idle, open_page from api.db import Conn from api.tenancy import schema_for -from conftest import ROOT -from streamlit_helpers import choose_option, click_and_download, idle, open_page NO_CANCEL = "Sent to the server; it can't be stopped now" CONFIRM = "I have checked the column names and types" @@ -67,8 +67,10 @@ def _file_row(stack, name: str) -> dict | None: def _column_types(stack, table: str) -> dict[str, str]: """What the database itself says the columns are (not what the API says it did).""" with Conn() as conn, conn.cursor() as cur: - cur.execute("SELECT column_name, data_type FROM information_schema.columns " - "WHERE table_schema = %s AND table_name = %s", (schema_for(stack.accounts["uploader"].tenant), table)) + cur.execute( + "SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = %s AND table_name = %s", + (schema_for(stack.accounts["uploader"].tenant), table), + ) return dict(cur.fetchall()) @@ -88,6 +90,7 @@ def _confirm_and_upload(page, name: str): # ── the size limit (spike Q1) ────────────────────────────────────────────────────────────── + def test_a_file_in_the_band_streamlit_would_have_refused_but_the_api_takes_is_previewed(page, stack, tmp_path): """The #254 finding: Streamlit counts a megabyte as 1,000,000 bytes, so with its limit at 50 a file of 51,000,000 bytes was refused though the API takes up to 50 MiB (52,428,800). Streamlit's limit is now 53 and the app checks the API's.""" @@ -102,9 +105,13 @@ def test_a_file_in_the_band_streamlit_would_have_refused_but_the_api_takes_is_pr expect(page.get_by_text("about", exact=False).first).to_be_visible() # a big file is previewed from its start -def test_a_file_over_the_apis_limit_is_refused_by_the_app_in_its_own_words_before_anything_is_sent(page, stack, tmp_path): +def test_a_file_over_the_apis_limit_is_refused_by_the_app_in_its_own_words_before_anything_is_sent( + page, stack, tmp_path +): _open(page, stack) - over = _sized_csv(tmp_path, _unique("too_big"), 52_900_000) # over the API's 52,428,800, under Streamlit's 53,000,000 + over = _sized_csv( + tmp_path, _unique("too_big"), 52_900_000 + ) # over the API's 52,428,800, under Streamlit's 53,000,000 _choose(page, over) @@ -127,14 +134,16 @@ def test_the_api_refuses_just_over_its_limit_whatever_the_front_end_does(stack): headers = {"Authorization": f"Bearer {stack.token('uploader')}"} over = "a,b\n" + "x,y\n" * ((50 * MIB) // 4 + 10) - res = requests.post(f"{stack.api}/api/csv/preview", headers=headers, timeout=120, - json={"fileName": "over.csv", "content": over}) + res = requests.post( + f"{stack.api}/api/csv/preview", headers=headers, timeout=120, json={"fileName": "over.csv", "content": over} + ) assert res.status_code == 413 and "too large" in res.text.lower(), (res.status_code, res.text[:200]) # ── renaming headers and choosing types (Q2) ─────────────────────────────────────────────── + def test_renaming_and_retyping_with_ordinary_widgets_is_stored_exactly_as_chosen(page, stack): name, body = _unique("widgets"), _people() _open(page, stack) @@ -172,6 +181,7 @@ def test_a_rename_that_collides_is_refused_by_the_api_and_said_in_its_words_with # ── no cancel (Q3) ───────────────────────────────────────────────────────────────────────── + def test_it_says_before_and_during_that_the_import_cannot_be_stopped_and_there_is_no_stop_button(page, stack): name = _unique("slow") _open(page, stack) @@ -188,6 +198,7 @@ def test_it_says_before_and_during_that_the_import_cannot_be_stopped_and_there_i # ── several files (Q4) ───────────────────────────────────────────────────────────────────── + def test_several_files_are_previewed_and_uploaded_in_turn(page, stack): names = [_unique(f"multi{i}") for i in range(3)] _open(page, stack) @@ -224,6 +235,7 @@ def test_two_copies_of_the_same_bytes_are_two_files_and_the_page_does_not_crash( # ── Test and Evaluation mode (Q5) ────────────────────────────────────────────────────────── + def test_te_mode_is_suggested_for_a_te_shaped_file_and_hides_the_mapping(page, stack): _open(page, stack) @@ -237,6 +249,7 @@ def test_te_mode_is_suggested_for_a_te_shaped_file_and_hides_the_mapping(page, s # ── results (Q6) ─────────────────────────────────────────────────────────────────────────── + def test_failed_rows_are_listed_with_their_reasons_and_can_be_downloaded_as_reports(page, stack): name = _unique("orgs_fail") _open(page, stack) @@ -290,6 +303,7 @@ def test_the_same_file_again_is_reported_as_already_imported_and_a_changed_one_i # ── files the screen will not send, or sends differently ─────────────────────────────────── + def test_a_file_that_is_not_utf8_is_refused_with_the_reason_and_nothing_is_imported(page, stack): name = _unique("latin") _open(page, stack) @@ -317,6 +331,7 @@ def test_a_file_with_a_byte_order_mark_loads_with_clean_headers_and_keeps_its_or # ── what other screens see, at once ──────────────────────────────────────────────────────── + def test_a_new_import_is_in_the_history_and_the_files_list_at_once_even_though_both_are_cached(page, stack): name = _unique("fresh") open_page(page, stack, "uploader", "Import history", "Import history") # fetches (and caches) the history @@ -338,7 +353,9 @@ def test_the_imported_files_page_previews_the_table_and_says_why_rows_failed(pag name = _unique("lookinside") _open(page, stack) _choose(page, _csv(name, "id,name,amount\n1,ann,10\n2,bob,x\n3,cy,30\n")) - choose_option(page, "Type of column 3", "Whole number") # the preview saw an "x" and guessed text: the person knows better + choose_option( + page, "Type of column 3", "Whole number" + ) # the preview saw an "x" and guessed text: the person knows better page.get_by_text(CONFIRM).click() page.get_by_role("button", name=f"Upload {name}").click() expect(page.get_by_text("2 of 3 rows imported")).to_be_visible() @@ -356,6 +373,7 @@ def test_the_imported_files_page_previews_the_table_and_says_why_rows_failed(pag # ── text from a file is shown as written ─────────────────────────────────────────────────── + def test_a_file_name_a_header_and_a_cell_that_look_like_links_are_text_not_links(page, stack): link = "[click here](https://evil.example/login)" name = f"**bold**_{uuid.uuid4().hex[:6]}.csv" @@ -374,6 +392,7 @@ def test_a_file_name_a_header_and_a_cell_that_look_like_links_are_text_not_links # ── who sees the page ────────────────────────────────────────────────────────────────────── + def test_a_role_that_may_not_upload_is_not_offered_the_page_but_may_see_the_files(page, stack): open_page(page, stack, "reviewer", "Imported files", "Imported files") diff --git a/evals/gap_report.py b/evals/gap_report.py index 6566c09..7ba356c 100644 --- a/evals/gap_report.py +++ b/evals/gap_report.py @@ -14,6 +14,7 @@ not by evals; mention but don't fail - DEFERRED - declared out-of-scope (BR-21, BR-22) """ + from __future__ import annotations import json @@ -21,7 +22,6 @@ from pathlib import Path from typing import Any, Dict, List, Optional - # -------------------------------------------------------------------------- # BR catalogue. Lifted from docs/VCRM.md; keep these in sync if docs/VCRM.md is edited. # `covering_evals` maps tier letter -> list of scenario folder names. @@ -114,10 +114,14 @@ "category": "Functional", "covering_evals": { "p": [ - "02_empty_file", "03_empty_header_only_newline", - "04_no_valid_rows", "07_column_mismatch_short", - "08_column_mismatch_long", "19_missing_env_vars", - "20_missing_csv_file", "23_invalid_utf8_bytes", + "02_empty_file", + "03_empty_header_only_newline", + "04_no_valid_rows", + "07_column_mismatch_short", + "08_column_mismatch_long", + "19_missing_env_vars", + "20_missing_csv_file", + "23_invalid_utf8_bytes", ], }, "baseline": "full", @@ -238,13 +242,13 @@ # Status computation STATUS_ICONS = { - "VERIFIED": "OK", - "PARTIAL": "PARTIAL", - "REGRESSION": "REGRESSION", - "SKIPPED": "SKIPPED", - "UNVERIFIED": "GAP", + "VERIFIED": "OK", + "PARTIAL": "PARTIAL", + "REGRESSION": "REGRESSION", + "SKIPPED": "SKIPPED", + "UNVERIFIED": "GAP", "OUT-OF-BAND": "OOB", - "DEFERRED": "DEFERRED", + "DEFERRED": "DEFERRED", } @@ -308,8 +312,7 @@ def compute_status(br: Dict[str, Any], by_tier: Dict[str, Dict[str, str]]) -> Di } if any_skip: if br.get("skip_means_verified"): - return {"status": "VERIFIED", - "details": details + ["Skip is the contract for this BR"]} + return {"status": "VERIFIED", "details": details + ["Skip is the contract for this BR"]} return {"status": "SKIPPED", "details": details} return {"status": "UNVERIFIED", "details": details} @@ -317,6 +320,7 @@ def compute_status(br: Dict[str, Any], by_tier: Dict[str, Dict[str, str]]) -> Di # -------------------------------------------------------------------------- # Markdown writer + def _outcomes_by_tier(summary: Dict[str, Any]) -> Dict[str, Dict[str, str]]: by_tier: Dict[str, Dict[str, str]] = {} for sc in summary.get("scenarios", []): @@ -355,7 +359,9 @@ def generate_markdown(summary: Dict[str, Any]) -> str: lines.append("Tier eval totals: " + json.dumps(totals)) lines.append("") lines.append("Auto-generated by `evals/gap_report.py` at the end of `evals/runner.py`.") - lines.append("Reflects this run's outcomes only. For the static catalogue see `docs/VCRM.md` and `docs/VCRM_GAPS.md`.") + lines.append( + "Reflects this run's outcomes only. For the static catalogue see `docs/VCRM.md` and `docs/VCRM_GAPS.md`." + ) lines.append("") lines.append("---") lines.append("") @@ -363,19 +369,27 @@ def generate_markdown(summary: Dict[str, Any]) -> str: lines.append("") lines.append("| Status | Count | Meaning |") lines.append("|--------|------:|---------|") - lines.append("| VERIFIED | " + str(counts.get("VERIFIED", 0)) + " | Baseline=full and >=1 covering eval passed |") - lines.append("| PARTIAL | " + str(counts.get("PARTIAL", 0)) + " | Baseline=partial; some aspects verified |") - lines.append("| REGRESSION | " + str(counts.get("REGRESSION", 0)) + " | A covering eval FAILED this run - investigate |") - lines.append("| SKIPPED | " + str(counts.get("SKIPPED", 0)) + " | All covering evals skipped (e.g. PG unavailable) |") - lines.append("| UNVERIFIED | " + str(counts.get("UNVERIFIED", 0)) + " | No covering eval - this is a real gap |") - lines.append("| OUT-OF-BAND | " + str(counts.get("OUT-OF-BAND", 0)) + " | Verified by PU/SQL suites, not by evals |") - lines.append("| DEFERRED | " + str(counts.get("DEFERRED", 0)) + " | Out-of-scope by project decision |") + lines.append( + "| VERIFIED | " + str(counts.get("VERIFIED", 0)) + " | Baseline=full and >=1 covering eval passed |" + ) + lines.append("| PARTIAL | " + str(counts.get("PARTIAL", 0)) + " | Baseline=partial; some aspects verified |") + lines.append( + "| REGRESSION | " + str(counts.get("REGRESSION", 0)) + " | A covering eval FAILED this run - investigate |" + ) + lines.append( + "| SKIPPED | " + str(counts.get("SKIPPED", 0)) + " | All covering evals skipped (e.g. PG unavailable) |" + ) + lines.append("| UNVERIFIED | " + str(counts.get("UNVERIFIED", 0)) + " | No covering eval - this is a real gap |") + lines.append( + "| OUT-OF-BAND | " + str(counts.get("OUT-OF-BAND", 0)) + " | Verified by PU/SQL suites, not by evals |" + ) + lines.append("| DEFERRED | " + str(counts.get("DEFERRED", 0)) + " | Out-of-scope by project decision |") lines.append("") # Spotlight any regressions or unverified regressions = [(br, st) for br, st in rows if st["status"] == "REGRESSION"] - unverified = [(br, st) for br, st in rows if st["status"] == "UNVERIFIED"] - skipped = [(br, st) for br, st in rows if st["status"] == "SKIPPED"] + unverified = [(br, st) for br, st in rows if st["status"] == "UNVERIFIED"] + skipped = [(br, st) for br, st in rows if st["status"] == "SKIPPED"] if regressions: lines.append("## REGRESSIONS - investigate before release") @@ -408,14 +422,23 @@ def generate_markdown(summary: Dict[str, Any]) -> str: lines.append("|----|--------|-------|---------------------|") for br, st in rows: evidence = "; ".join(st["details"]) if st["details"] else "-" - lines.append("| " + br["id"] + - " | " + STATUS_ICONS.get(st["status"], st["status"]) + - " | " + br["title"] + - " | " + evidence + " |") + lines.append( + "| " + + br["id"] + + " | " + + STATUS_ICONS.get(st["status"], st["status"]) + + " | " + + br["title"] + + " | " + + evidence + + " |" + ) lines.append("") lines.append("---") lines.append("") - lines.append("Companion: `docs/VCRM.md` (catalogue), `docs/VCRM_GAPS.md` (static gap analysis), `docs/TEST_CONDITIONS.md` (every test).") + lines.append( + "Companion: `docs/VCRM.md` (catalogue), `docs/VCRM_GAPS.md` (static gap analysis), `docs/TEST_CONDITIONS.md` (every test)." + ) # Ensure a single trailing newline so markdownlint MD047 passes. return "\n".join(lines) + "\n" @@ -423,6 +446,7 @@ def generate_markdown(summary: Dict[str, Any]) -> str: # -------------------------------------------------------------------------- # Public API + def generate_for_run(run_dir: Path, summary_path: Optional[Path] = None) -> Path: """Generate `VCRM_GAPS_.md` inside `run_dir`. Returns the path.""" if summary_path is None: @@ -442,6 +466,7 @@ def generate_for_run(run_dir: Path, summary_path: Optional[Path] = None) -> Path # CLI for ad-hoc use (regenerate against an existing summary.json) if __name__ == "__main__": import sys + if len(sys.argv) < 2: print("usage: python gap_report.py />") sys.exit(2) diff --git a/evals/runner.py b/evals/runner.py index 1257835..15f2bee 100644 --- a/evals/runner.py +++ b/evals/runner.py @@ -15,6 +15,7 @@ python3 evals/runner.py --only 05_mixed_valid_skipped python3 evals/runner.py --verbose """ + from __future__ import annotations import argparse @@ -31,59 +32,69 @@ from pathlib import Path from typing import Any, Dict, List, Optional - # --------------------------------------------------------------------------- # Locations -EVALS_DIR = Path(__file__).resolve().parent +EVALS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = EVALS_DIR.parent -VALIDATOR = PROJECT_ROOT / "build" / "csv" / "validator.py" +VALIDATOR = PROJECT_ROOT / "build" / "csv" / "validator.py" DATASETS_DIR = EVALS_DIR / "datasets" EXPECTED_DIR = EVALS_DIR / "expected" -REPORTS_DIR = EVALS_DIR / "reports" +REPORTS_DIR = EVALS_DIR / "reports" # --------------------------------------------------------------------------- # Pretty-printing -GREEN = "\033[0;32m" +GREEN = "\033[0;32m" YELLOW = "\033[1;33m" -RED = "\033[0;31m" -BLUE = "\033[0;34m" -DIM = "\033[2m" -NC = "\033[0m" +RED = "\033[0;31m" +BLUE = "\033[0;34m" +DIM = "\033[2m" +NC = "\033[0m" + + +def _pass(name: str) -> str: + return GREEN + "PASS" + NC + " " + name + + +def _fail(name: str) -> str: + return RED + "FAIL" + NC + " " + name + + +def _skip(name: str) -> str: + return YELLOW + "SKIP" + NC + " " + name -def _pass(name: str) -> str: return GREEN + "PASS" + NC + " " + name -def _fail(name: str) -> str: return RED + "FAIL" + NC + " " + name -def _skip(name: str) -> str: return YELLOW + "SKIP" + NC + " " + name -def _info(name: str) -> str: return BLUE + "INFO" + NC + " " + name +def _info(name: str) -> str: + return BLUE + "INFO" + NC + " " + name # --------------------------------------------------------------------------- # Data classes + class ScenarioResult: """Outcome of running a single scenario.""" def __init__(self, tier: str, name: str) -> None: - self.tier = tier - self.name = name - self.passed = False - self.skipped = False - self.errors: List[str] = [] - self.actual: Dict[str, Any] = {} + self.tier = tier + self.name = name + self.passed = False + self.skipped = False + self.errors: List[str] = [] + self.actual: Dict[str, Any] = {} self.expected: Dict[str, Any] = {} def to_dict(self) -> Dict[str, Any]: return { - "tier": self.tier, - "name": self.name, - "passed": self.passed, + "tier": self.tier, + "name": self.name, + "passed": self.passed, "skipped": self.skipped, - "errors": self.errors, - "actual": self.actual, + "errors": self.errors, + "actual": self.actual, "expected": self.expected, } @@ -91,6 +102,7 @@ def to_dict(self) -> Dict[str, Any]: # --------------------------------------------------------------------------- # Helpers + def _load_expected(tier: str, name: str) -> Optional[Dict[str, Any]]: path = EXPECTED_DIR / ("tier_" + tier) / (name + ".json") if not path.exists(): @@ -109,6 +121,7 @@ def _read_csv_rows(path: Path) -> List[List[str]]: # --------------------------------------------------------------------------- # Tier P — Python CSV validator + def _run_validator(env: Dict[str, str]) -> subprocess.CompletedProcess: return subprocess.run( [sys.executable, str(VALIDATOR)], @@ -120,7 +133,7 @@ def _run_validator(env: Dict[str, str]) -> subprocess.CompletedProcess: def run_tier_p_scenario(scenario_dir: Path) -> ScenarioResult: - name = scenario_dir.name + name = scenario_dir.name result = ScenarioResult(tier="p", name=name) expected = _load_expected("p", name) @@ -130,15 +143,15 @@ def run_tier_p_scenario(scenario_dir: Path) -> ScenarioResult: result.expected = expected runner_action = expected.get("runner_action", "default") - exp = expected.get("expected", {}) + exp = expected.get("expected", {}) with tempfile.TemporaryDirectory(prefix="eval_" + name + "_") as tmp: - tmp_path = Path(tmp) + tmp_path = Path(tmp) valid_csv = tmp_path / "valid.csv" - skip_csv = tmp_path / "skip.csv" + skip_csv = tmp_path / "skip.csv" env = { - "PATH": os.environ.get("PATH", ""), + "PATH": os.environ.get("PATH", ""), "PYTHONIOENCODING": "utf-8", } @@ -149,9 +162,9 @@ def run_tier_p_scenario(scenario_dir: Path) -> ScenarioResult: return result csv_file = tmp_path / "input.csv" shutil.copyfile(src_csv, csv_file) - env["CSV_FILE"] = str(csv_file) - env["VALID_CSV"] = str(valid_csv) - env["SKIP_FILE"] = str(skip_csv) + env["CSV_FILE"] = str(csv_file) + env["VALID_CSV"] = str(valid_csv) + env["SKIP_FILE"] = str(skip_csv) env["TABLE_NAME"] = expected.get("table_name", "people") elif runner_action == "write_long_field_file": @@ -161,26 +174,26 @@ def run_tier_p_scenario(scenario_dir: Path) -> ScenarioResult: writer = csv.writer(f) writer.writerow(["id", "payload"]) writer.writerow(["1", long_value]) - env["CSV_FILE"] = str(csv_file) - env["VALID_CSV"] = str(valid_csv) - env["SKIP_FILE"] = str(skip_csv) + env["CSV_FILE"] = str(csv_file) + env["VALID_CSV"] = str(valid_csv) + env["SKIP_FILE"] = str(skip_csv) env["TABLE_NAME"] = expected.get("table_name", "payloads") elif runner_action == "write_invalid_utf8_file": csv_file = tmp_path / "input.csv" csv_file.write_bytes(b"id,name\n1,Alice\n2,\xe9\n") - env["CSV_FILE"] = str(csv_file) - env["VALID_CSV"] = str(valid_csv) - env["SKIP_FILE"] = str(skip_csv) + env["CSV_FILE"] = str(csv_file) + env["VALID_CSV"] = str(valid_csv) + env["SKIP_FILE"] = str(skip_csv) env["TABLE_NAME"] = expected.get("table_name", "people") elif runner_action == "omit_env_vars": pass elif runner_action == "point_at_missing_file": - env["CSV_FILE"] = str(tmp_path / "does_not_exist.csv") - env["VALID_CSV"] = str(valid_csv) - env["SKIP_FILE"] = str(skip_csv) + env["CSV_FILE"] = str(tmp_path / "does_not_exist.csv") + env["VALID_CSV"] = str(valid_csv) + env["SKIP_FILE"] = str(skip_csv) env["TABLE_NAME"] = "people" else: @@ -195,8 +208,8 @@ def run_tier_p_scenario(scenario_dir: Path) -> ScenarioResult: actual: Dict[str, Any] = { "exit_code": cp.returncode, - "stdout": cp.stdout, - "stderr": cp.stderr, + "stdout": cp.stdout, + "stderr": cp.stderr, } reads_output_files = runner_action in { @@ -206,13 +219,13 @@ def run_tier_p_scenario(scenario_dir: Path) -> ScenarioResult: } if reads_output_files: - actual["valid_csv_rows"] = _read_csv_rows(valid_csv) - skip_rows = _read_csv_rows(skip_csv) - actual["skip_csv_rows"] = skip_rows + actual["valid_csv_rows"] = _read_csv_rows(valid_csv) + skip_rows = _read_csv_rows(skip_csv) + actual["skip_csv_rows"] = skip_rows actual["skip_csv_row_count"] = max(0, len(skip_rows) - 1) else: - actual["valid_csv_rows"] = None - actual["skip_csv_rows"] = None + actual["valid_csv_rows"] = None + actual["skip_csv_rows"] = None actual["skip_csv_row_count"] = None result.actual = actual @@ -220,12 +233,7 @@ def run_tier_p_scenario(scenario_dir: Path) -> ScenarioResult: errors: List[str] = [] if "exit_code" in exp and exp["exit_code"] != actual["exit_code"]: - errors.append( - "exit_code: expected " - + str(exp["exit_code"]) - + ", got " - + str(actual["exit_code"]) - ) + errors.append("exit_code: expected " + str(exp["exit_code"]) + ", got " + str(actual["exit_code"])) for needle in exp.get("stdout_contains", []) or []: if needle not in actual["stdout"]: @@ -248,10 +256,7 @@ def run_tier_p_scenario(scenario_dir: Path) -> ScenarioResult: if exp_skip_count is not None: if actual["skip_csv_row_count"] != exp_skip_count: errors.append( - "skip_csv_row_count: expected " - + str(exp_skip_count) - + ", got " - + str(actual["skip_csv_row_count"]) + "skip_csv_row_count: expected " + str(exp_skip_count) + ", got " + str(actual["skip_csv_row_count"]) ) for needle in exp.get("skip_reasons_contain", []) or []: @@ -261,10 +266,7 @@ def run_tier_p_scenario(scenario_dir: Path) -> ScenarioResult: if row: reasons.append(row[-1]) if not any(needle in r for r in reasons): - errors.append( - "skip_reasons missing substring: " + repr(needle) - + "; actual reasons: " + str(reasons) - ) + errors.append("skip_reasons missing substring: " + repr(needle) + "; actual reasons: " + str(reasons)) result.errors = errors result.passed = not errors @@ -275,6 +277,7 @@ def run_tier_p_scenario(scenario_dir: Path) -> ScenarioResult: # --------------------------------------------------------------------------- # PostgreSQL connectivity helpers (shared by Tier I + Tier S) + def _have_psql() -> bool: return shutil.which("psql") is not None @@ -292,7 +295,9 @@ def _can_connect_pg() -> bool: r = subprocess.run( ["psql", "-tA", "-c", "SELECT 1"], env=_pg_env(), - capture_output=True, text=True, timeout=5, + capture_output=True, + text=True, + timeout=5, ) return r.returncode == 0 except (subprocess.TimeoutExpired, FileNotFoundError): @@ -300,9 +305,17 @@ def _can_connect_pg() -> bool: _DEV_SEED_TABLES = [ - "organisations", "personnel", "test_programs", "temp_documents", - "test_phases", "requirements", "test_cases", "vcrm_entries", - "test_events", "test_results", "defect_reports", + "organisations", + "personnel", + "test_programs", + "temp_documents", + "test_phases", + "requirements", + "test_cases", + "vcrm_entries", + "test_events", + "test_results", + "defect_reports", ] @@ -314,7 +327,9 @@ def _count_dev_rows() -> Dict[str, Any]: r = subprocess.run( ["psql", "-tA", "-d", "te_mgmt_dev", "-c", query], env=_pg_env(), - capture_output=True, text=True, timeout=10, + capture_output=True, + text=True, + timeout=10, ) if r.returncode == 0 and r.stdout.strip().isdigit(): counts[tbl] = int(r.stdout.strip()) @@ -326,8 +341,9 @@ def _count_dev_rows() -> Dict[str, Any]: # --------------------------------------------------------------------------- # Tier I — Idempotency + def run_tier_i_scenario(scenario_dir: Path) -> ScenarioResult: - name = scenario_dir.name + name = scenario_dir.name result = ScenarioResult(tier="i", name=name) expected = _load_expected("i", name) @@ -339,10 +355,7 @@ def run_tier_i_scenario(scenario_dir: Path) -> ScenarioResult: if not _can_connect_pg(): # An unavailable prerequisite is a FAILURE, not a skip: a green run # must mean the scenario actually executed. - result.errors.append( - "PostgreSQL not reachable via psql " - "(install psql + start PG, or set PG* env vars)." - ) + result.errors.append("PostgreSQL not reachable via psql (install psql + start PG, or set PG* env vars).") return result if name == "01_deploy_dev_twice": @@ -352,9 +365,7 @@ def run_tier_i_scenario(scenario_dir: Path) -> ScenarioResult: return result -def _run_deploy_dev_twice( - result: ScenarioResult, expected: Dict[str, Any] -) -> ScenarioResult: +def _run_deploy_dev_twice(result: ScenarioResult, expected: Dict[str, Any]) -> ScenarioResult: env_dev_sql = PROJECT_ROOT / "build" / "environments" / "env_dev.sql" if not env_dev_sql.exists(): result.errors.append("Cannot find " + str(env_dev_sql)) @@ -370,12 +381,12 @@ def _run_deploy_dev_twice( counts_2 = _count_dev_rows() actual = { - "first_run_exit_code": r1.returncode, + "first_run_exit_code": r1.returncode, "second_run_exit_code": r2.returncode, - "row_counts_first": counts_1, - "row_counts_second": counts_2, + "row_counts_first": counts_1, + "row_counts_second": counts_2, "row_counts_unchanged": counts_1 == counts_2, - "tables_present": sum(1 for v in counts_2.values() if v is not None), + "tables_present": sum(1 for v in counts_2.values() if v is not None), } result.actual = actual @@ -385,30 +396,29 @@ def _run_deploy_dev_twice( if exp.get("first_run_exit_code") != actual["first_run_exit_code"]: r1_tail = r1.stderr[-400:] errors.append( - "first_run_exit_code: expected " + str(exp.get("first_run_exit_code")) - + ", got " + str(actual["first_run_exit_code"]) - + "; stderr: " + r1_tail + "first_run_exit_code: expected " + + str(exp.get("first_run_exit_code")) + + ", got " + + str(actual["first_run_exit_code"]) + + "; stderr: " + + r1_tail ) if exp.get("second_run_exit_code") != actual["second_run_exit_code"]: r2_tail = r2.stderr[-400:] errors.append( - "second_run_exit_code: expected " + str(exp.get("second_run_exit_code")) - + ", got " + str(actual["second_run_exit_code"]) - + "; stderr: " + r2_tail + "second_run_exit_code: expected " + + str(exp.get("second_run_exit_code")) + + ", got " + + str(actual["second_run_exit_code"]) + + "; stderr: " + + r2_tail ) if exp.get("row_counts_unchanged") and not actual["row_counts_unchanged"]: - drift = { - t: (counts_1.get(t), counts_2.get(t)) - for t in counts_1 - if counts_1.get(t) != counts_2.get(t) - } + drift = {t: (counts_1.get(t), counts_2.get(t)) for t in counts_1 if counts_1.get(t) != counts_2.get(t)} errors.append("row counts changed between runs: " + str(drift)) min_tables = exp.get("min_seeded_tables_present", 0) if actual["tables_present"] < min_tables: - errors.append( - "tables_present: expected >= " + str(min_tables) - + ", got " + str(actual["tables_present"]) - ) + errors.append("tables_present: expected >= " + str(min_tables) + ", got " + str(actual["tables_present"])) result.errors = errors result.passed = not errors @@ -418,8 +428,9 @@ def _run_deploy_dev_twice( # --------------------------------------------------------------------------- # Tier S — SQL suite integration + def run_tier_s_scenario(scenario_dir: Path) -> ScenarioResult: - name = scenario_dir.name + name = scenario_dir.name result = ScenarioResult(tier="s", name=name) expected = _load_expected("s", name) @@ -430,9 +441,7 @@ def run_tier_s_scenario(scenario_dir: Path) -> ScenarioResult: if not _can_connect_pg(): # Unavailable prerequisite = failure, not skip (see tier_i note above). - result.errors.append( - "PostgreSQL not reachable via psql — install/start PG and re-run." - ) + result.errors.append("PostgreSQL not reachable via psql — install/start PG and re-run.") return result if name == "01_fresh_deploy_then_all_tests_pass": @@ -442,103 +451,113 @@ def run_tier_s_scenario(scenario_dir: Path) -> ScenarioResult: return result -def _run_fresh_deploy_then_tests( - result: ScenarioResult, expected: Dict[str, Any] -) -> ScenarioResult: +def _run_fresh_deploy_then_tests(result: ScenarioResult, expected: Dict[str, Any]) -> ScenarioResult: env_dev_sql = PROJECT_ROOT / "build" / "environments" / "env_dev.sql" - run_tests = PROJECT_ROOT / "tests" / "run_all_tests.sql" + run_tests = PROJECT_ROOT / "tests" / "run_all_tests.sql" if not env_dev_sql.exists() or not run_tests.exists(): - result.errors.append( - "Cannot find " + str(env_dev_sql) + " or " + str(run_tests) - ) + result.errors.append("Cannot find " + str(env_dev_sql) + " or " + str(run_tests)) return result env = _pg_env() deploy = subprocess.run( ["psql", "-f", str(env_dev_sql)], - env=env, capture_output=True, text=True, timeout=180, + env=env, + capture_output=True, + text=True, + timeout=180, ) table_overrides = [ - "--set", "schema_name=te_dev", - "--set", "app_user=te_dev_user", - "--set", "conn_limit=10", - "--set", "tbl_organisations=organisations", - "--set", "tbl_personnel=personnel", - "--set", "tbl_test_programs=test_programs", - "--set", "tbl_temp_documents=temp_documents", - "--set", "tbl_test_phases=test_phases", - "--set", "tbl_requirements=requirements", - "--set", "tbl_test_cases=test_cases", - "--set", "tbl_vcrm_entries=vcrm_entries", - "--set", "tbl_test_events=test_events", - "--set", "tbl_test_results=test_results", - "--set", "tbl_defect_reports=defect_reports", - "--set", "tbl_evidence_artifacts=evidence_artifacts", + "--set", + "schema_name=te_dev", + "--set", + "app_user=te_dev_user", + "--set", + "conn_limit=10", + "--set", + "tbl_organisations=organisations", + "--set", + "tbl_personnel=personnel", + "--set", + "tbl_test_programs=test_programs", + "--set", + "tbl_temp_documents=temp_documents", + "--set", + "tbl_test_phases=test_phases", + "--set", + "tbl_requirements=requirements", + "--set", + "tbl_test_cases=test_cases", + "--set", + "tbl_vcrm_entries=vcrm_entries", + "--set", + "tbl_test_events=test_events", + "--set", + "tbl_test_results=test_results", + "--set", + "tbl_defect_reports=defect_reports", + "--set", + "tbl_evidence_artifacts=evidence_artifacts", ] tests = subprocess.run( ["psql", "-d", "te_mgmt_dev"] + table_overrides + ["-f", str(run_tests)], - env=env, capture_output=True, text=True, timeout=180, + env=env, + capture_output=True, + text=True, + timeout=180, ) stdout_tail = tests.stdout[-2000:] stderr_tail = tests.stderr[-400:] actual: Dict[str, Any] = { "deploy_exit_code": deploy.returncode, - "tests_exit_code": tests.returncode, - "stdout_tail": stdout_tail, - "stderr_tail": stderr_tail, + "tests_exit_code": tests.returncode, + "stdout_tail": stdout_tail, + "stderr_tail": stderr_tail, } total_assertions = None - pass_rate = None + pass_rate = None for line in tests.stdout.splitlines(): # Summary row may be plain ("159 159 0 100.0% ...") or a psql table # row ("159 | 159 | 0 | 0 | 100.0% | ..."); strip pipes first. parts = line.replace("|", " ").split() - if (len(parts) >= 4 and parts[0].isdigit() and parts[1].isdigit() - and parts[2].isdigit()): + if len(parts) >= 4 and parts[0].isdigit() and parts[1].isdigit() and parts[2].isdigit(): pct = next((p for p in parts[3:] if p.endswith("%")), None) if pct is not None: try: total_assertions = int(parts[0]) - pass_rate = float(pct.rstrip("%")) + pass_rate = float(pct.rstrip("%")) except ValueError: pass actual["total_assertions"] = total_assertions - actual["pass_rate"] = pass_rate - result.actual = actual + actual["pass_rate"] = pass_rate + result.actual = actual exp = expected.get("expected", {}) errors: List[str] = [] if exp.get("deploy_exit_code") != deploy.returncode: deploy_tail = deploy.stderr[-400:] errors.append( - "deploy_exit_code: expected " + str(exp.get("deploy_exit_code")) - + ", got " + str(deploy.returncode) - + "; stderr: " + deploy_tail + "deploy_exit_code: expected " + + str(exp.get("deploy_exit_code")) + + ", got " + + str(deploy.returncode) + + "; stderr: " + + deploy_tail ) if exp.get("tests_exit_code") != tests.returncode: - errors.append( - "tests_exit_code: expected " + str(exp.get("tests_exit_code")) - + ", got " + str(tests.returncode) - ) + errors.append("tests_exit_code: expected " + str(exp.get("tests_exit_code")) + ", got " + str(tests.returncode)) for needle in exp.get("stdout_contains", []) or []: if needle not in tests.stdout: errors.append("stdout missing substring: " + repr(needle)) min_total = exp.get("min_total_assertions", 0) if total_assertions is None or total_assertions < min_total: - errors.append( - "total_assertions: expected >= " + str(min_total) - + ", got " + str(total_assertions) - ) + errors.append("total_assertions: expected >= " + str(min_total) + ", got " + str(total_assertions)) min_rate = exp.get("min_pass_rate_percent", 0.0) if pass_rate is None or pass_rate < min_rate: - errors.append( - "pass_rate: expected >= " + str(min_rate) - + "%, got " + str(pass_rate) - ) + errors.append("pass_rate: expected >= " + str(min_rate) + "%, got " + str(pass_rate)) result.errors = errors result.passed = not errors @@ -559,10 +578,10 @@ def _run_fresh_deploy_then_tests( # position — must be identical. ENV_TARGETS = [ - ("dev", "te_mgmt_dev", "te_dev"), - ("test", "te_mgmt_test", "te_test"), + ("dev", "te_mgmt_dev", "te_dev"), + ("test", "te_mgmt_test", "te_test"), ("staging", "te_mgmt_staging", "te_staging"), - ("prod", "te_mgmt_prod", "te_prod"), + ("prod", "te_mgmt_prod", "te_prod"), ] @@ -577,11 +596,13 @@ def _deploy_env(env_name: str) -> Dict[str, Any]: if not launcher.exists(): launcher = env_dir / ("env_" + env_name + ".example.sql") if not launcher.exists(): - return {"env": env_name, "exit_code": None, - "error": "No env_" + env_name + ".sql or .example.sql found"} + return {"env": env_name, "exit_code": None, "error": "No env_" + env_name + ".sql or .example.sql found"} r = subprocess.run( ["psql", "-v", "ON_ERROR_STOP=1", "-f", str(launcher)], - env=_pg_env(), capture_output=True, text=True, timeout=180, + env=_pg_env(), + capture_output=True, + text=True, + timeout=180, ) return { "env": env_name, @@ -610,11 +631,14 @@ def _column_signature(db: str, schema: str) -> Dict[str, List[str]]: ) r = subprocess.run( ["psql", "-tA", "-v", "ON_ERROR_STOP=1", "-d", db, "--set=sch=" + schema], - input=query, env=_pg_env(), capture_output=True, text=True, timeout=30, + input=query, + env=_pg_env(), + capture_output=True, + text=True, + timeout=30, ) if r.returncode != 0: - raise RuntimeError("schema query on " + db + "." + schema + " failed: " - + r.stderr.strip()[-300:]) + raise RuntimeError("schema query on " + db + "." + schema + " failed: " + r.stderr.strip()[-300:]) sig: Dict[str, List[str]] = {} for line in r.stdout.splitlines(): parts = line.split("|") @@ -625,41 +649,47 @@ def _column_signature(db: str, schema: str) -> Dict[str, List[str]]: return sig -def _diff_signatures(ref_env: str, ref: Dict[str, List[str]], - other_env: str, other: Dict[str, List[str]]) -> List[str]: +def _diff_signatures(ref_env: str, ref: Dict[str, List[str]], other_env: str, other: Dict[str, List[str]]) -> List[str]: """Human-readable differences between two schema fingerprints.""" diffs: List[str] = [] missing = sorted(set(ref) - set(other)) - extra = sorted(set(other) - set(ref)) + extra = sorted(set(other) - set(ref)) if missing: - diffs.append(other_env + " is missing tables present in " + ref_env - + ": " + ", ".join(missing)) + diffs.append(other_env + " is missing tables present in " + ref_env + ": " + ", ".join(missing)) if extra: - diffs.append(other_env + " has tables absent from " + ref_env - + ": " + ", ".join(extra)) + diffs.append(other_env + " has tables absent from " + ref_env + ": " + ", ".join(extra)) for table in sorted(set(ref) & set(other)): if ref[table] != other[table]: - ref_cols = set(ref[table]) + ref_cols = set(ref[table]) other_cols = set(other[table]) - only_ref = sorted(ref_cols - other_cols) + only_ref = sorted(ref_cols - other_cols) only_other = sorted(other_cols - ref_cols) if only_ref or only_other: diffs.append( - "table " + table + " differs: " + ref_env + "-only [" - + ", ".join(only_ref) + "], " + other_env + "-only [" - + ", ".join(only_other) + "]" + "table " + + table + + " differs: " + + ref_env + + "-only [" + + ", ".join(only_ref) + + "], " + + other_env + + "-only [" + + ", ".join(only_other) + + "]" ) else: # Same columns, different order — still drift worth failing on, # because ordinal position is part of the deployed contract. - diffs.append("table " + table + " has the same columns in a " - "different ordinal order between " + ref_env - + " and " + other_env) + diffs.append( + "table " + table + " has the same columns in a " + "different ordinal order between " + ref_env + " and " + other_env + ) return diffs def run_tier_e_scenario(scenario_dir: Path) -> ScenarioResult: - name = scenario_dir.name + name = scenario_dir.name result = ScenarioResult(tier="e", name=name) expected = _load_expected("e", name) @@ -671,10 +701,7 @@ def run_tier_e_scenario(scenario_dir: Path) -> ScenarioResult: if not _can_connect_pg(): # Same no-skip stance as Tiers I and S (FIXES_APPLIED.md F5): a missing # prerequisite fails, so a green run always means the check really ran. - result.errors.append( - "PostgreSQL not reachable via psql " - "(install psql + start PG, or set PG* env vars)." - ) + result.errors.append("PostgreSQL not reachable via psql (install psql + start PG, or set PG* env vars).") return result if name == "01_envs_have_identical_structure": @@ -687,12 +714,9 @@ def run_tier_e_scenario(scenario_dir: Path) -> ScenarioResult: return result -def _run_envs_have_identical_structure( - result: ScenarioResult, expected: Dict[str, Any] -) -> ScenarioResult: +def _run_envs_have_identical_structure(result: ScenarioResult, expected: Dict[str, Any]) -> ScenarioResult: exp = expected.get("expected", {}) - envs_under_test = expected.get("envs_under_test", - [e[0] for e in ENV_TARGETS]) + envs_under_test = expected.get("envs_under_test", [e[0] for e in ENV_TARGETS]) targets = [t for t in ENV_TARGETS if t[0] in envs_under_test] deploys = [_deploy_env(env_name) for env_name, _, _ in targets] @@ -718,8 +742,11 @@ def _run_envs_have_identical_structure( for d in deploys: if d.get("exit_code") != 0: errors.append( - "deploy of " + d["env"] + " exited " - + str(d.get("exit_code")) + " " + "deploy of " + + d["env"] + + " exited " + + str(d.get("exit_code")) + + " " + (d.get("error") or d.get("stderr_tail") or "") ) @@ -728,8 +755,7 @@ def _run_envs_have_identical_structure( if count < min_tables: errors.append( "env " + env_name + " has " + str(count) + " tables in its " - "schema, expected >= " + str(min_tables) - + " (deploy may have partially failed)" + "schema, expected >= " + str(min_tables) + " (deploy may have partially failed)" ) if exp.get("column_signature_identical_across_envs") is True: @@ -738,14 +764,12 @@ def _run_envs_have_identical_structure( ref_env = expected.get("reference_env", "dev") ref = signatures.get(ref_env) if not ref: - errors.append("reference env " + ref_env + " returned no columns; " - "cannot compare the others against it") + errors.append("reference env " + ref_env + " returned no columns; cannot compare the others against it") else: for env_name in sorted(signatures): if env_name == ref_env: continue - diffs = _diff_signatures(ref_env, ref, env_name, - signatures[env_name]) + diffs = _diff_signatures(ref_env, ref, env_name, signatures[env_name]) errors.extend(diffs) result.actual["signature_match"] = not errors @@ -764,13 +788,14 @@ def _psql_run(db: str, sql: str) -> "subprocess.CompletedProcess[str]": """Run one SQL statement on `db`; the caller reads returncode and stderr.""" return subprocess.run( ["psql", "-d", db, "-v", "ON_ERROR_STOP=1", "-c", sql], - env=_pg_env(), capture_output=True, text=True, timeout=30, + env=_pg_env(), + capture_output=True, + text=True, + timeout=30, ) -def _run_empty_schema_negative_control( - result: ScenarioResult, expected: Dict[str, Any] -) -> ScenarioResult: +def _run_empty_schema_negative_control(result: ScenarioResult, expected: Dict[str, Any]) -> ScenarioResult: """Negative control for scenario 01: show that it can see "nothing deployed". Scenario 01 passes when every environment has the same structure as dev. That @@ -791,8 +816,7 @@ def _run_empty_schema_negative_control( ref_env = expected.get("reference_env", "dev") target = next((t for t in ENV_TARGETS if t[0] == ref_env), None) if target is None: - result.errors.append("reference_env " + ref_env + " is not one of the " - "environments in ENV_TARGETS") + result.errors.append("reference_env " + ref_env + " is not one of the environments in ENV_TARGETS") return result _, db, ref_schema = target @@ -814,12 +838,16 @@ def _run_empty_schema_negative_control( return result quoted = '"' + _EMPTY_CONTROL_SCHEMA + '"' - made = _psql_run(db, "DROP SCHEMA IF EXISTS " + quoted - + "; CREATE SCHEMA " + quoted) + made = _psql_run(db, "DROP SCHEMA IF EXISTS " + quoted + "; CREATE SCHEMA " + quoted) if made.returncode != 0: - result.errors.append("could not create the throwaway schema " - + _EMPTY_CONTROL_SCHEMA + " in " + db + ": " - + made.stderr.strip()[-300:]) + result.errors.append( + "could not create the throwaway schema " + + _EMPTY_CONTROL_SCHEMA + + " in " + + db + + ": " + + made.stderr.strip()[-300:] + ) return result errors: List[str] = [] @@ -828,8 +856,9 @@ def _run_empty_schema_negative_control( empty = _column_signature(db, _EMPTY_CONTROL_SCHEMA) except RuntimeError as exc: empty = None - errors.append("the schema query failed on an empty schema, which " - "must not be reported as 'no tables': " + str(exc)) + errors.append( + "the schema query failed on an empty schema, which must not be reported as 'no tables': " + str(exc) + ) if empty is not None: want = int(exp.get("empty_schema_tables", 0)) diffs = _diff_signatures(ref_env, ref, "empty", empty) @@ -839,10 +868,10 @@ def _run_empty_schema_negative_control( "differences_reported": len(diffs), } if len(empty) != want: - errors.append("an empty schema returned " + str(len(empty)) - + " tables, expected " + str(want)) + errors.append("an empty schema returned " + str(len(empty)) + " tables, expected " + str(want)) if exp.get("diff_reports_missing_tables") is True and not any( - " is missing tables present in " in d for d in diffs): + " is missing tables present in " in d for d in diffs + ): errors.append( "comparing " + ref_env + " (" + str(len(ref)) + " tables) with " "an empty schema reported no missing tables, so scenario 01 " @@ -851,9 +880,14 @@ def _run_empty_schema_negative_control( finally: dropped = _psql_run(db, "DROP SCHEMA IF EXISTS " + quoted) if dropped.returncode != 0: - errors.append("could not drop the throwaway schema " - + _EMPTY_CONTROL_SCHEMA + " (it is left in " + db - + "): " + dropped.stderr.strip()[-300:]) + errors.append( + "could not drop the throwaway schema " + + _EMPTY_CONTROL_SCHEMA + + " (it is left in " + + db + + "): " + + dropped.stderr.strip()[-300:] + ) result.errors = errors result.passed = not errors @@ -882,9 +916,18 @@ def _run_empty_schema_negative_control( # while telling us nothing. Structural presence is the property BR-02 asserts. _ENGINE_PLACEHOLDER_TABLES = [ - "organisations", "personnel", "test_programs", "temp_documents", - "test_phases", "requirements", "test_cases", "vcrm_entries", - "test_events", "test_results", "defect_reports", "evidence_artifacts", + "organisations", + "personnel", + "test_programs", + "temp_documents", + "test_phases", + "requirements", + "test_cases", + "vcrm_entries", + "test_events", + "test_results", + "defect_reports", + "evidence_artifacts", ] @@ -906,6 +949,7 @@ def _sqlite_structure(ddl: str) -> Dict[str, Any]: rejected — a syntax error in the SQLite schema is itself a finding. """ import sqlite3 + try: conn = sqlite3.connect(":memory:") except Exception as exc: # noqa: BLE001 @@ -913,10 +957,7 @@ def _sqlite_structure(ddl: str) -> Dict[str, Any]: try: conn.executescript(ddl) cur = conn.cursor() - cur.execute( - "SELECT name FROM sqlite_master WHERE type='table' " - "AND name NOT LIKE 'sqlite_%' ORDER BY name" - ) + cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name") tables = [r[0] for r in cur.fetchall()] out: Dict[str, List[str]] = {} for t in tables: @@ -932,7 +973,7 @@ def _sqlite_structure(ddl: str) -> Dict[str, Any]: def run_tier_x_scenario(scenario_dir: Path) -> ScenarioResult: - name = scenario_dir.name + name = scenario_dir.name result = ScenarioResult(tier="x", name=name) expected = _load_expected("x", name) @@ -948,9 +989,7 @@ def run_tier_x_scenario(scenario_dir: Path) -> ScenarioResult: return result -def _run_sqlite_schema_structure( - result: ScenarioResult, expected: Dict[str, Any] -) -> ScenarioResult: +def _run_sqlite_schema_structure(result: ScenarioResult, expected: Dict[str, Any]) -> ScenarioResult: exp = expected.get("expected", {}) ddl_path = PROJECT_ROOT / "build" / "schema" / "sqlite" / "te_core_schema.sql" if not ddl_path.exists(): @@ -978,8 +1017,7 @@ def _run_sqlite_schema_structure( # Any {{TBL_*}} the substitution missed would reach sqlite3 as a literal and # silently create a differently-named table. if leftover: - errors.append("DDL still contains unsubstituted placeholders: " - + ", ".join(sorted(set(leftover)))) + errors.append("DDL still contains unsubstituted placeholders: " + ", ".join(sorted(set(leftover)))) # Baseline guard. expected_tables is the set SQLite actually ships today, so # this passes on the known state and fails the moment it drifts either way: @@ -989,8 +1027,7 @@ def _run_sqlite_schema_structure( want, have = set(expected_tables), set(tables) missing, extra = sorted(want - have), sorted(have - want) if missing: - errors.append("expected tables absent from the SQLite DDL: " - + ", ".join(missing)) + errors.append("expected tables absent from the SQLite DDL: " + ", ".join(missing)) if extra: errors.append( "SQLite DDL defines tables not in expected_tables: " @@ -1006,8 +1043,7 @@ def _run_sqlite_schema_structure( continue # already reported by the table-set check above absent = sorted(set(want_cols) - set(have_cols)) if absent: - errors.append("table " + table + " is missing columns: " - + ", ".join(absent)) + errors.append("table " + table + " is missing columns: " + ", ".join(absent)) # The parity shortfall is recorded, not asserted — see NOTES.txt. Surfacing # it in actual output keeps it visible in every report without turning the @@ -1016,7 +1052,9 @@ def _run_sqlite_schema_structure( if known_missing: result.actual["known_missing_tables"] = known_missing result.actual["parity_note"] = ( - "SQLite ships " + str(len(tables)) + " of " + "SQLite ships " + + str(len(tables)) + + " of " + str(len(_ENGINE_PLACEHOLDER_TABLES)) + " T&E tables. Outstanding work tracked in docs/ENGINE_PARITY_TODO.md." ) @@ -1109,11 +1147,11 @@ def main() -> int: print(" skipped: " + (YELLOW if skipped else NC) + str(skipped) + NC) summary = { - "run_id": run_id, + "run_id": run_id, "started_at": datetime.now(timezone.utc).isoformat(), - "tiers": tiers, - "totals": {"total": total, "passed": passed, "failed": failed, "skipped": skipped}, - "scenarios": [r.to_dict() for r in all_results], + "tiers": tiers, + "totals": {"total": total, "passed": passed, "failed": failed, "skipped": skipped}, + "scenarios": [r.to_dict() for r in all_results], } summary_path = run_dir / "summary.json" with summary_path.open("w", encoding="utf-8") as f: @@ -1125,6 +1163,7 @@ def main() -> int: try: sys.path.insert(0, str(EVALS_DIR)) import gap_report + gap_path = gap_report.generate_for_run(run_dir, summary_path) print(" gap report: " + str(gap_path)) except Exception as exc: # noqa: BLE001 diff --git a/scripts/check_bundle_egress.py b/scripts/check_bundle_egress.py index ebdb7fd..edcb607 100644 --- a/scripts/check_bundle_egress.py +++ b/scripts/check_bundle_egress.py @@ -21,12 +21,18 @@ HOST = re.compile(r"""(?:https?|wss?)://([A-Za-z0-9._-]+)""", re.I) LOCAL = {"localhost", "127.0.0.1"} URL = r"""["'`](?:https?|wss?)://[^"'`\s]+""" -MARKUP = {".html", ".css", ".svg"} # where src=, @import and url() mean "load this"; in scripts `new URL(...)` doesn't +MARKUP = {".html", ".css", ".svg"} # where src=, @import and url() mean "load this"; in scripts `new URL(...)` doesn't LOADS = [ - ("HTML/CSS external resource", re.compile( - r"""(?:\bsrc|\bhref)\s*=\s*["'](?:https?:)?//[^"']+""" - r"""|@import\s+(?:url\()?["']?(?:https?:)?//[^;)\s]+""" - r"""|\burl\(\s*["']?(?:https?:)?//[^)]+""", re.I), MARKUP), + ( + "HTML/CSS external resource", + re.compile( + r"""(?:\bsrc|\bhref)\s*=\s*["'](?:https?:)?//[^"']+""" + r"""|@import\s+(?:url\()?["']?(?:https?:)?//[^;)\s]+""" + r"""|\burl\(\s*["']?(?:https?:)?//[^)]+""", + re.I, + ), + MARKUP, + ), ("fetch of a literal URL", re.compile(r"\bfetch\(\s*" + URL, re.I), None), ("XMLHttpRequest of a literal URL", re.compile(r"""\.open\(\s*["'][A-Za-z]+["']\s*,\s*""" + URL, re.I), None), ("sendBeacon", re.compile(r"\bsendBeacon\(\s*" + URL, re.I), None), @@ -37,7 +43,9 @@ BANNED = re.compile( r"(google-analytics|googletagmanager|doubleclick|googleapis|gstatic|sentry\.io|ingest\.sentry|posthog|mixpanel|segment\.(?:io|com)|" r"amplitude\.com|datadoghq|newrelic|nr-data|hotjar|logrocket|fullstory|bugsnag|rollbar|intercom|clarity\.ms|" - r"cdn\.jsdelivr|unpkg\.com|cdnjs|cloudflare(?:insights)?\.com|bootstrapcdn|fontawesome|typekit|lovable\.(?:dev|app))", re.I) + r"cdn\.jsdelivr|unpkg\.com|cdnjs|cloudflare(?:insights)?\.com|bootstrapcdn|fontawesome|typekit|lovable\.(?:dev|app))", + re.I, +) def scan(root: Path) -> dict: @@ -48,8 +56,11 @@ def scan(root: Path) -> dict: for label, pattern, only in LOADS: if only and path.suffix.lower() not in only: continue - loads += [f"{rel}: {label}: {m.group(0)[:100]}" for m in pattern.finditer(text) - if not any(h in m.group(0) for h in ("localhost", "127.0.0.1"))] + loads += [ + f"{rel}: {label}: {m.group(0)[:100]}" + for m in pattern.finditer(text) + if not any(h in m.group(0) for h in ("localhost", "127.0.0.1")) + ] for m in HOST.finditer(text): host = m.group(1).lower().rstrip(".") if host in LOCAL: @@ -71,15 +82,23 @@ def main(argv: list[str]) -> int: print(f"{arg}: not a directory; build the frontend first", file=sys.stderr) return 2 found = scan(root) - print(f"{arg}: {len(found['loads'])} load path(s), {len(found['banned'])} analytics/CDN host(s), " - f"{len(found['other'])} other host name(s) that are never requested") + print( + f"{arg}: {len(found['loads'])} load path(s), {len(found['banned'])} analytics/CDN host(s), " + f"{len(found['other'])} other host name(s) that are never requested" + ) for line in found["loads"] + found["banned"]: print(" FAIL", line) if found["other"]: - print(" named only (namespaces, documentation links): " + - ", ".join(f"{h} x{n}" for h, n in sorted(found["other"].items(), key=lambda kv: -kv[1]))) + print( + " named only (namespaces, documentation links): " + + ", ".join(f"{h} x{n}" for h, n in sorted(found["other"].items(), key=lambda kv: -kv[1])) + ) failed = failed or bool(found["loads"] or found["banned"]) - print("FAILED: the build can reach outside this deployment" if failed else "OK: the build requests nothing outside this deployment") + print( + "FAILED: the build can reach outside this deployment" + if failed + else "OK: the build requests nothing outside this deployment" + ) return 1 if failed else 0 diff --git a/scripts/check_coverage_floors.py b/scripts/check_coverage_floors.py index 09ca041..0f152c5 100755 --- a/scripts/check_coverage_floors.py +++ b/scripts/check_coverage_floors.py @@ -19,6 +19,7 @@ database-free tiers alone with subprocess measurement on (24 Nov 2026, a lower bound for the full suite). Raise them when the numbers rise. """ + from __future__ import annotations import json @@ -37,8 +38,8 @@ PACKAGE_FLOORS: dict[str, int] = { "api/": 90, "streamlit_app/": 92, - "build/csv/": 80, # #304: the validator (validator.py); the shell loaders are invisible to coverage.py - "evals/": 60, # #304: the runner and the gap report + "build/csv/": 80, # #304: the validator (validator.py); the shell loaders are invisible to coverage.py + "evals/": 60, # #304: the runner and the gap report } GREEN = "\033[0;32m" diff --git a/scripts/check_oidc.py b/scripts/check_oidc.py index b5bbbe4..0be23be 100644 --- a/scripts/check_oidc.py +++ b/scripts/check_oidc.py @@ -40,7 +40,7 @@ @dataclass class Result: step: str - status: str # "ok", "warn" (worth a look, doesn't fail the run) or "fail" + status: str # "ok", "warn" (worth a look, doesn't fail the run) or "fail" detail: str @@ -64,8 +64,12 @@ def check_config() -> Result: return Result("config", "fail", str(exc)) if not settings.OIDC_JWKS_URL.startswith("https://"): return Result("config", "warn", "OIDC_JWKS_URL is not https://, so the https key fetch isn't being checked") - return Result("config", "ok", f"issuer {settings.OIDC_ISSUER}, audience {settings.OIDC_AUDIENCE}, " - f"keys {settings.OIDC_JWKS_URL}, username claim {settings.OIDC_USERNAME_CLAIM!r}") + return Result( + "config", + "ok", + f"issuer {settings.OIDC_ISSUER}, audience {settings.OIDC_AUDIENCE}, " + f"keys {settings.OIDC_JWKS_URL}, username claim {settings.OIDC_USERNAME_CLAIM!r}", + ) def check_discovery() -> Result: @@ -76,11 +80,19 @@ def check_discovery() -> Result: return Result("discovery", "warn", f"could not read {url}: {exc}. Not required; the other checks still run") problems = [] if doc.get("issuer") != settings.OIDC_ISSUER: - problems.append(f"the IdP says its issuer is {doc.get('issuer')!r}, but OIDC_ISSUER is {settings.OIDC_ISSUER!r}" - " (a trailing slash or the wrong tenant id are the usual causes)") + problems.append( + f"the IdP says its issuer is {doc.get('issuer')!r}, but OIDC_ISSUER is {settings.OIDC_ISSUER!r}" + " (a trailing slash or the wrong tenant id are the usual causes)" + ) if doc.get("jwks_uri") != settings.OIDC_JWKS_URL: - problems.append(f"the IdP publishes its keys at {doc.get('jwks_uri')!r}, not OIDC_JWKS_URL {settings.OIDC_JWKS_URL!r}") - return Result("discovery", "warn" if problems else "ok", "; ".join(problems) or "issuer and key URL match what the IdP publishes") + problems.append( + f"the IdP publishes its keys at {doc.get('jwks_uri')!r}, not OIDC_JWKS_URL {settings.OIDC_JWKS_URL!r}" + ) + return Result( + "discovery", + "warn" if problems else "ok", + "; ".join(problems) or "issuer and key URL match what the IdP publishes", + ) def check_keys() -> Result: @@ -90,11 +102,15 @@ def check_keys() -> Result: except Exception as exc: # noqa: BLE001 — any failure here is what the operator needs to see hint = "" if "CERTIFICATE_VERIFY_FAILED" in str(exc) or "SSL" in str(exc): - hint = (" The host doesn't trust the IdP's certificate. For a private CA, point SSL_CERT_FILE at the CA bundle " - "(PEM) in the API's environment.") + hint = ( + " The host doesn't trust the IdP's certificate. For a private CA, point SSL_CERT_FILE at the CA bundle " + "(PEM) in the API's environment." + ) return Result("keys", "fail", f"{type(exc).__name__}: {exc}.{hint}") summary = ", ".join(f"{k.key_id or '(no kid)'} [{k.key_type}]" for k in keys) - return Result("keys", "ok" if keys else "fail", f"{len(keys)} signing key(s): {summary}" if keys else "the key set is empty") + return Result( + "keys", "ok" if keys else "fail", f"{len(keys)} signing key(s): {summary}" if keys else "the key set is empty" + ) _HINTS = { @@ -116,38 +132,60 @@ def check_token(token: str) -> Result: except jwt.PyJWTError as exc: return Result("token", "fail", f"{type(exc).__name__}: {exc}. {_HINTS['DecodeError']}") username_claim = settings.OIDC_USERNAME_CLAIM - shown = (f"alg {header.get('alg')}, kid {header.get('kid')}, iss {claims.get('iss')}, aud {claims.get('aud')}, " - f"expires in {int(claims.get('exp', 0) - time.time())} s, {username_claim} = {claims.get(username_claim)!r}") + shown = ( + f"alg {header.get('alg')}, kid {header.get('kid')}, iss {claims.get('iss')}, aud {claims.get('aud')}, " + f"expires in {int(claims.get('exp', 0) - time.time())} s, {username_claim} = {claims.get(username_claim)!r}" + ) try: verified = oidc.verify(token) except jwt.PyJWTError as exc: - return Result("token", "fail", f"{shown}. Rejected: {type(exc).__name__}: {exc}. {_HINTS.get(type(exc).__name__, '')}".rstrip()) + return Result( + "token", + "fail", + f"{shown}. Rejected: {type(exc).__name__}: {exc}. {_HINTS.get(type(exc).__name__, '')}".rstrip(), + ) username = verified.get(username_claim) if not isinstance(username, str) or not username: - return Result("token", "fail", f"{shown}. Valid, but it has no {username_claim!r} claim, so no user can be named. " - "Set OIDC_USERNAME_CLAIM to the claim that holds the username " - "(Entra ID: preferred_username, or upn in v1 tokens)") + return Result( + "token", + "fail", + f"{shown}. Valid, but it has no {username_claim!r} claim, so no user can be named. " + "Set OIDC_USERNAME_CLAIM to the claim that holds the username " + "(Entra ID: preferred_username, or upn in v1 tokens)", + ) return Result("token", "ok", f"{shown}. Signature, issuer, audience and expiry verified") def check_api(api_url: str, tenant: str, token: str) -> Result: url = api_url.rstrip("/") + "/api/auth/oidc" - request = urllib.request.Request(url, data=json.dumps({"tenant": tenant, "idToken": token}).encode(), - headers={"Content-Type": "application/json"}, method="POST") + request = urllib.request.Request( + url, + data=json.dumps({"tenant": tenant, "idToken": token}).encode(), + headers={"Content-Type": "application/json"}, + method="POST", + ) try: with _open(request) as res: session = json.loads(res.read().decode("utf-8")) except urllib.error.HTTPError as exc: - hint = {401: "the token verified here but the API refused it, or that user isn't a member of the tenant", - 404: "the API has OIDC switched off: it needs OIDC_ISSUER set in its own environment"}.get(exc.code, "") + hint = { + 401: "the token verified here but the API refused it, or that user isn't a member of the tenant", + 404: "the API has OIDC switched off: it needs OIDC_ISSUER set in its own environment", + }.get(exc.code, "") return Result("sign-in", "fail", f"POST {url} gave {exc.code}. {hint}".rstrip()) except (urllib.error.URLError, OSError) as exc: return Result("sign-in", "fail", f"could not reach {url}: {exc}") - return Result("sign-in", "ok", f"200: signed in as {session.get('username')!r} to tenant {session.get('tenant')!r} " - f"with role {session.get('role')!r}; session expires {session.get('expiresAt')}") + return Result( + "sign-in", + "ok", + f"200: signed in as {session.get('username')!r} to tenant {session.get('tenant')!r} " + f"with role {session.get('role')!r}; session expires {session.get('expiresAt')}", + ) -def run_checks(token: str, api_url: str | None = None, tenant: str | None = None, discovery: bool = True) -> list[Result]: +def run_checks( + token: str, api_url: str | None = None, tenant: str | None = None, discovery: bool = True +) -> list[Result]: results = [check_config()] if results[0].status == "fail": return results @@ -170,7 +208,9 @@ def read_token(args) -> str: def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--token-env", default="ID_TOKEN", help="environment variable holding the ID token (default ID_TOKEN)") + ap.add_argument( + "--token-env", default="ID_TOKEN", help="environment variable holding the ID token (default ID_TOKEN)" + ) ap.add_argument("--token-file", help="a file holding the ID token") ap.add_argument("--token-stdin", action="store_true", help="read the ID token from standard input") ap.add_argument("--api", help="also sign in through a running API, e.g. http://localhost:8000") @@ -189,9 +229,16 @@ def main(argv: list[str] | None = None) -> int: print(f"{r.status.upper():<5} {r.step:<{width}} {r.detail}") failed = [r.step for r in results if r.status == "fail"] ran_api = any(r.step == "sign-in" for r in results) - print("\nFAILED: " + ", ".join(failed) if failed else - "\nOK: " + ("sign-in works end to end." if ran_api else - "the token verifies. Add --api and --tenant to check the sign-in itself.")) + print( + "\nFAILED: " + ", ".join(failed) + if failed + else "\nOK: " + + ( + "sign-in works end to end." + if ran_api + else "the token verifies. Add --api and --tenant to check the sign-in itself." + ) + ) return 1 if failed else 0 diff --git a/scripts/ci_changes.py b/scripts/ci_changes.py index fdb2bb3..a0a6425 100644 --- a/scripts/ci_changes.py +++ b/scripts/ci_changes.py @@ -15,6 +15,7 @@ When in doubt it runs everything: a push (to main), any event other than a pull request, a diff that cannot be read, an empty diff. Skipping is only ever the answer to "every changed file is a document that nothing reads". """ + from __future__ import annotations import argparse @@ -25,7 +26,17 @@ ROOT = Path(__file__).resolve().parents[1] DOC_PREFIXES = ("docs/", "DECISIONS/") -SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", "dist", "build/csv/logs"} +SKIP_DIRS = { + ".git", + "node_modules", + "__pycache__", + ".venv", + "venv", + ".mypy_cache", + ".pytest_cache", + "dist", + "build/csv/logs", +} MAX_BYTES = 2_000_000 @@ -86,8 +97,11 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) paths = changed_files(args.base, args.head) if args.event == "pull_request" and args.base and args.head else None answer = decide(args.event, paths) - why = "not a pull request" if args.event != "pull_request" else ( - "no readable diff, so everything runs" if not paths else f"{len(paths)} changed file(s)") + why = ( + "not a pull request" + if args.event != "pull_request" + else ("no readable diff, so everything runs" if not paths else f"{len(paths)} changed file(s)") + ) print(f"{why} -> database jobs {'run' if answer == 'true' else 'skipped (documentation only)'}", file=sys.stderr) line = f"code={answer}" print(line) diff --git a/scripts/ci_gate.py b/scripts/ci_gate.py index e09d7bd..bca1f09 100644 --- a/scripts/ci_gate.py +++ b/scripts/ci_gate.py @@ -14,6 +14,7 @@ Exit status 0 for pass, 1 for fail. The message names every job and what it did. """ + from __future__ import annotations import sys diff --git a/scripts/ci_shards.py b/scripts/ci_shards.py index 8d31929..d6e8fa3 100644 --- a/scripts/ci_shards.py +++ b/scripts/ci_shards.py @@ -22,6 +22,7 @@ Exit status: 0 on success; 2 for a shard that does not exist (a typo in the workflow must fail the job, not run nothing and pass). """ + from __future__ import annotations import argparse @@ -32,10 +33,10 @@ ROOT = Path(__file__).resolve().parents[1] WEIGHTS_PATH = ROOT / "ci" / "shard_weights.json" -EGRESS_SHARDS = 3 # the egress job splits tests/system/ this many ways (the `shard:` matrix of integration-egress) -SHARDS = 3 # keep in step with the `shard:` matrix in .github/workflows/quality-gate.yml (tested) -DEFAULT_WEIGHT = 20.0 # seconds, for a file with no recorded duration -MIN_WEIGHT = 1.0 # seconds: every file costs at least its import and collection +EGRESS_SHARDS = 3 # the egress job splits tests/system/ this many ways (the `shard:` matrix of integration-egress) +SHARDS = 3 # keep in step with the `shard:` matrix in .github/workflows/quality-gate.yml (tested) +DEFAULT_WEIGHT = 20.0 # seconds, for a file with no recorded duration +MIN_WEIGHT = 1.0 # seconds: every file costs at least its import and collection EXCLUDED_PREFIXES = ("tests/accessibility/",) @@ -98,7 +99,9 @@ def main(argv: list[str] | None = None) -> int: files = sub.add_parser("files", help="print one shard's files, one per line") files.add_argument("--shard", type=int, required=True) files.add_argument("--of", type=int, default=SHARDS, dest="of") - files.add_argument("--only", default="", help="split only the files under this prefix, e.g. tests/system/ (egress job)") + files.add_argument( + "--only", default="", help="split only the files under this prefix, e.g. tests/system/ (egress job)" + ) plan = sub.add_parser("plan", help="print every shard with an estimate") plan.add_argument("--of", type=int, default=SHARDS, dest="of") update = sub.add_parser("update-weights", help="regenerate durations from a JUnit report of a full run") @@ -123,7 +126,10 @@ def main(argv: list[str] | None = None) -> int: return 2 chosen = test_files(only=args.only) if not chosen: - print(f"no test files under {args.only!r}: a typo in the workflow must fail the job, not run nothing", file=sys.stderr) + print( + f"no test files under {args.only!r}: a typo in the workflow must fail the job, not run nothing", + file=sys.stderr, + ) return 2 print("\n".join(assign(chosen, load_weights(), args.of)[args.shard - 1])) return 0 diff --git a/scripts/create_app_role.py b/scripts/create_app_role.py index 57e0a2e..2186111 100644 --- a/scripts/create_app_role.py +++ b/scripts/create_app_role.py @@ -76,16 +76,23 @@ def retire_legacy_credentials(env: str) -> str | None: def main() -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--env", required=True, choices=ENVIRONMENTS, - help="which environment this role serves. Mandatory: it names both the role " - "(te_app_) and the credential file (~/.te-migration/app-db-.env), " - "so two environments on one PostgreSQL cluster never share either (RV-S3, #173).") - ap.add_argument("--role", default=None, - help="override the role name. Defaults to te_app_.") - ap.add_argument("--env-file", type=Path, default=None, - help="override where the credentials are written. Defaults to " - "~/.te-migration/app-db-.env. Given explicitly, the legacy " - "credential file is left alone.") + ap.add_argument( + "--env", + required=True, + choices=ENVIRONMENTS, + help="which environment this role serves. Mandatory: it names both the role " + "(te_app_) and the credential file (~/.te-migration/app-db-.env), " + "so two environments on one PostgreSQL cluster never share either (RV-S3, #173).", + ) + ap.add_argument("--role", default=None, help="override the role name. Defaults to te_app_.") + ap.add_argument( + "--env-file", + type=Path, + default=None, + help="override where the credentials are written. Defaults to " + "~/.te-migration/app-db-.env. Given explicitly, the legacy " + "credential file is left alone.", + ) args = ap.parse_args() role_name = args.role or role_for(args.env) @@ -99,36 +106,40 @@ def main() -> int: role, pw = sql.Identifier(role_name), sql.Literal(password) cur.execute("SELECT 1 FROM pg_roles WHERE rolname = %s", (role_name,)) verb = "ALTER" if cur.fetchone() else "CREATE" - cur.execute(sql.SQL(verb + " ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD {}") - .format(role, pw)) + cur.execute(sql.SQL(verb + " ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD {}").format(role, pw)) cur.execute(sql.SQL("GRANT {} TO {}").format(role, sql.Identifier(settings.PG_USER))) - cur.execute(sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format( - sql.Identifier(settings.PG_DATABASE), role)) + cur.execute(sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(sql.Identifier(settings.PG_DATABASE), role)) conn.commit() cur.execute("SELECT 1 FROM pg_roles WHERE rolname = %s", (LEGACY_ROLE,)) legacy_role_present = cur.fetchone() is not None and role_name != LEGACY_ROLE settings.APP_DB_USER, settings.APP_DB_PASSWORD = role_name, SecretStr(password) - db.bootstrap() # migrations, then grants on every schema, tenants included + db.bootstrap() # migrations, then grants on every schema, tenants included env_file.parent.mkdir(parents=True, exist_ok=True) fd = os.open(env_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(f"APP_DB_USER={role_name}\nAPP_DB_PASSWORD={password}\n") - print(f"Role '{role_name}' is ready ({'created' if verb == 'CREATE' else 'new password set'}) " - f"for the {args.env} environment. Its settings are in {env_file}; " - "start-api.ps1 loads them. Restart the API.") + print( + f"Role '{role_name}' is ready ({'created' if verb == 'CREATE' else 'new password set'}) " + f"for the {args.env} environment. Its settings are in {env_file}; " + "start-api.ps1 loads them. Restart the API." + ) if args.env_file is None: superseded = retire_legacy_credentials(args.env) if superseded: - print(f"Moved the pre-#173 credential file aside: {superseded}. start-api.ps1 now reads " - f"{env_file} instead, so the API no longer starts on the old cluster-wide role.") + print( + f"Moved the pre-#173 credential file aside: {superseded}. start-api.ps1 now reads " + f"{env_file} instead, so the API no longer starts on the old cluster-wide role." + ) if legacy_role_present: - print(f"The pre-#173 cluster-wide role '{LEGACY_ROLE}' still exists on this server. Each " - "environment now has its own role, so it is unused once every environment has been " - "re-provisioned with --env. Drop it then, as the owner: " - f'DROP OWNED BY {LEGACY_ROLE}; DROP ROLE {LEGACY_ROLE};') + print( + f"The pre-#173 cluster-wide role '{LEGACY_ROLE}' still exists on this server. Each " + "environment now has its own role, so it is unused once every environment has been " + "re-provisioned with --env. Drop it then, as the owner: " + f"DROP OWNED BY {LEGACY_ROLE}; DROP ROLE {LEGACY_ROLE};" + ) return 0 diff --git a/scripts/create_tenant_admin.py b/scripts/create_tenant_admin.py index 5f389ac..cbc23ed 100644 --- a/scripts/create_tenant_admin.py +++ b/scripts/create_tenant_admin.py @@ -61,19 +61,25 @@ def confirm(question: str) -> bool: def refusal(username: str, found: accounts.Existing) -> str | None: """Why this admin can never be created here, even by using an existing tenant.""" if found.user and not found.member: - return (f"The username '{username}' is already in use (usernames are unique across all tenants), " - "so it was not created again. Nothing was changed.\n" - "Choose a different --username.") + return ( + f"The username '{username}' is already in use (usernames are unique across all tenants), " + "so it was not created again. Nothing was changed.\n" + "Choose a different --username." + ) return None def describe_existing(tenant: str, username: str, found: accounts.Existing) -> tuple[str, str]: """(what already exists, the question to ask) when the tenant is already there.""" if found.member: - return (f"Tenant '{tenant}' already exists, and '{username}' is already a member of it.", - f"Use the existing tenant '{tenant}' as it is? (nothing will be created)") - return (f"Tenant '{tenant}' already exists, and '{username}' is not in it yet.", - f"Use the existing tenant '{tenant}' and add '{username}' as a tenant admin?") + return ( + f"Tenant '{tenant}' already exists, and '{username}' is already a member of it.", + f"Use the existing tenant '{tenant}' as it is? (nothing will be created)", + ) + return ( + f"Tenant '{tenant}' already exists, and '{username}' is not in it yet.", + f"Use the existing tenant '{tenant}' and add '{username}' as a tenant admin?", + ) def main(argv: list[str] | None = None) -> int: @@ -81,10 +87,12 @@ def main(argv: list[str] | None = None) -> int: ap.add_argument("--tenant", required=True, help="tenant slug: lowercase letters, digits, underscore") ap.add_argument("--name", required=True, help="tenant display name (ignored if the tenant already exists)") ap.add_argument("--username", required=True) - ap.add_argument("--allow-self-approval", action="store_true", - help="let members approve data they uploaded or submitted (for a tenant with a single user)") - ap.add_argument("--use-existing", action="store_true", - help="if the tenant already exists, use it without asking") + ap.add_argument( + "--allow-self-approval", + action="store_true", + help="let members approve data they uploaded or submitted (for a tenant with a single user)", + ) + ap.add_argument("--use-existing", action="store_true", help="if the tenant already exists, use it without asking") args = ap.parse_args(argv) too_short = f"Password must be at least {accounts.MIN_PASSWORD} characters." env_password = os.environ.get("TE_ADMIN_PASSWORD") @@ -107,8 +115,11 @@ def main(argv: list[str] | None = None) -> int: print(what, file=sys.stderr) if not args.use_existing: if not interactive(): - print("Nothing was changed. To use the existing tenant without being asked, " - "run again with --use-existing.", file=sys.stderr) + print( + "Nothing was changed. To use the existing tenant without being asked, " + "run again with --use-existing.", + file=sys.stderr, + ) return 1 if not confirm(question): print("Nothing was changed.", file=sys.stderr) @@ -136,8 +147,11 @@ def main(argv: list[str] | None = None) -> int: except psycopg2.errors.UniqueViolation: # The checks above passed, then someone else created the same tenant or user. conn.rollback() - print(f"Tenant '{args.tenant}' or username '{args.username}' was created by someone else " - "while this ran. Nothing was changed.", file=sys.stderr) + print( + f"Tenant '{args.tenant}' or username '{args.username}' was created by someone else " + "while this ran. Nothing was changed.", + file=sys.stderr, + ) return 1 migrate_tenant(args.tenant) finally: @@ -146,10 +160,12 @@ def main(argv: list[str] | None = None) -> int: if not found.tenant: print(f"Created tenant '{args.tenant}' (schema {schema}) with tenant admin '{args.username}'.") elif found.member: - print(f"Using the existing tenant '{args.tenant}' (schema {schema}). Nothing was created: " - f"'{args.username}' is already a member.\n" - f"To set a new password for '{args.username}': " - f"python scripts/reset_password.py --username {args.username}") + print( + f"Using the existing tenant '{args.tenant}' (schema {schema}). Nothing was created: " + f"'{args.username}' is already a member.\n" + f"To set a new password for '{args.username}': " + f"python scripts/reset_password.py --username {args.username}" + ) else: print(f"Added tenant admin '{args.username}' to the existing tenant '{args.tenant}' (schema {schema}).") return 0 diff --git a/scripts/eval_compare.py b/scripts/eval_compare.py index 1cfe96b..90c3037 100644 --- a/scripts/eval_compare.py +++ b/scripts/eval_compare.py @@ -7,6 +7,7 @@ python3 scripts/eval_compare.py # auto last 2 python3 scripts/eval_compare.py # explicit """ + from __future__ import annotations import json @@ -33,27 +34,25 @@ def _load(run_id: str) -> dict: def _scenario_map(summary: dict) -> dict[str, dict]: - return { - f"{s['tier']}/{s['name']}": s - for s in summary.get("scenarios", []) - } + return {f"{s['tier']}/{s['name']}": s for s in summary.get("scenarios", [])} def main() -> None: - runs = sorted( - (p for p in REPORTS_DIR.iterdir() if p.is_dir()), - key=lambda p: p.name, - ) if REPORTS_DIR.exists() else [] + runs = ( + sorted( + (p for p in REPORTS_DIR.iterdir() if p.is_dir()), + key=lambda p: p.name, + ) + if REPORTS_DIR.exists() + else [] + ) if len(sys.argv) == 3: id_a, id_b = sys.argv[1], sys.argv[2] elif len(runs) >= 2: id_a, id_b = runs[-2].name, runs[-1].name else: - print( - f"{YELLOW}Need at least 2 eval runs. " - f"Pass run IDs as arguments or run evals first.{NC}" - ) + print(f"{YELLOW}Need at least 2 eval runs. Pass run IDs as arguments or run evals first.{NC}") sys.exit(0) a = _load(id_a) @@ -68,7 +67,7 @@ def main() -> None: print(f" B: {id_b}") print("=" * 65) print(f" {'Scenario':<40} {'A':>6} {'B':>6} Delta") - print(f" {'-'*40} {'-'*6} {'-'*6} -----") + print(f" {'-' * 40} {'-' * 6} {'-' * 6} -----") regressions = improvements = 0 @@ -106,14 +105,8 @@ def _status(s: dict | None) -> str: print() ta = a.get("totals", {}) tb = b.get("totals", {}) - print( - f" Totals A: {ta.get('passed', 0)}P/" - f"{ta.get('failed', 0)}F/{ta.get('skipped', 0)}S" - ) - print( - f" B: {tb.get('passed', 0)}P/" - f"{tb.get('failed', 0)}F/{tb.get('skipped', 0)}S" - ) + print(f" Totals A: {ta.get('passed', 0)}P/{ta.get('failed', 0)}F/{ta.get('skipped', 0)}S") + print(f" B: {tb.get('passed', 0)}P/{tb.get('failed', 0)}F/{tb.get('skipped', 0)}S") print() if regressions: print(f" {RED}{regressions} regression(s) detected{NC}") diff --git a/scripts/eval_list.py b/scripts/eval_list.py index b360273..6c8a1ac 100644 --- a/scripts/eval_list.py +++ b/scripts/eval_list.py @@ -3,21 +3,22 @@ Mirrors `bun run eval:list` in gstack. """ + from __future__ import annotations import json import sys from pathlib import Path -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[1] REPORTS_DIR = ROOT / "evals" / "reports" -GREEN = "\033[0;32m" -RED = "\033[0;31m" +GREEN = "\033[0;32m" +RED = "\033[0;31m" YELLOW = "\033[1;33m" -CYAN = "\033[0;36m" -DIM = "\033[2m" -NC = "\033[0m" +CYAN = "\033[0;36m" +DIM = "\033[2m" +NC = "\033[0m" def main() -> None: @@ -38,7 +39,7 @@ def main() -> None: print(f"\n{CYAN}Eval runs ({len(runs)} total) — most recent first{NC}") print("=" * 70) print(f" {'Run ID':<30} {'Total':>5} {'Pass':>5} {'Fail':>5} {'Skip':>5}") - print(f" {'-'*30} {'-'*5} {'-'*5} {'-'*5} {'-'*5}") + print(f" {'-' * 30} {'-' * 5} {'-' * 5} {'-' * 5} {'-' * 5}") for run_dir in runs: summary_path = run_dir / "summary.json" @@ -48,9 +49,9 @@ def main() -> None: try: summary = json.loads(summary_path.read_text(encoding="utf-8")) t = summary.get("totals", {}) - total = t.get("total", 0) - passed = t.get("passed", 0) - failed = t.get("failed", 0) + total = t.get("total", 0) + passed = t.get("passed", 0) + failed = t.get("failed", 0) skipped = t.get("skipped", 0) fail_col = RED if failed else NC print( diff --git a/scripts/eval_summary.py b/scripts/eval_summary.py index 35ffc9b..2bb07b9 100644 --- a/scripts/eval_summary.py +++ b/scripts/eval_summary.py @@ -3,21 +3,22 @@ Mirrors `bun run eval:summary` in gstack. """ + from __future__ import annotations import json import sys from pathlib import Path -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[1] REPORTS_DIR = ROOT / "evals" / "reports" -GREEN = "\033[0;32m" -RED = "\033[0;31m" +GREEN = "\033[0;32m" +RED = "\033[0;31m" YELLOW = "\033[1;33m" -CYAN = "\033[0;36m" -DIM = "\033[2m" -NC = "\033[0m" +CYAN = "\033[0;36m" +DIM = "\033[2m" +NC = "\033[0m" def main() -> None: @@ -45,9 +46,9 @@ def main() -> None: total_runs += 1 t = summary.get("totals", {}) - grand_total += t.get("total", 0) - grand_passed += t.get("passed", 0) - grand_failed += t.get("failed", 0) + grand_total += t.get("total", 0) + grand_passed += t.get("passed", 0) + grand_failed += t.get("failed", 0) grand_skipped += t.get("skipped", 0) for s in summary.get("scenarios", []): @@ -80,7 +81,7 @@ def main() -> None: print(f"\n {CYAN}Per-scenario pass rate{NC}") print(f" {'Scenario':<40} {'Pass%':>6} {'Runs':>5} {'Fail':>5}") - print(f" {'-'*40} {'-'*6} {'-'*5} {'-'*5}") + print(f" {'-' * 40} {'-' * 6} {'-' * 5} {'-' * 5}") for key in sorted(scenario_stats): st = scenario_stats[key] @@ -88,8 +89,7 @@ def main() -> None: col = GREEN if pct >= 90 else (YELLOW if pct >= 50 else RED) fail_count = st["fail"] print( - f" {key:<40} {col}{pct:>5.0f}%{NC} {st['total']:>5} " - f"{(RED if fail_count else DIM)}{fail_count:>5}{NC}" + f" {key:<40} {col}{pct:>5.0f}%{NC} {st['total']:>5} {(RED if fail_count else DIM)}{fail_count:>5}{NC}" ) print() diff --git a/scripts/fix_api_imports.py b/scripts/fix_api_imports.py index 493d0ef..34e00a9 100644 --- a/scripts/fix_api_imports.py +++ b/scripts/fix_api_imports.py @@ -37,6 +37,7 @@ python -c "from api.main import app; print('ok')" python -m pytest tests/test_api.py -m unit """ + from __future__ import annotations import argparse @@ -54,20 +55,21 @@ PATTERNS = [ # from config import settings -> from api.config import settings # from services.csv_parse import x -> from api.services.csv_parse import x - (re.compile(rf"^(\s*)from\s+({'|'.join(LOCAL)})(\.[\w.]+)?\s+import\s", - re.MULTILINE), - lambda m: f"{m.group(1)}from api.{m.group(2)}{m.group(3) or ''} import "), + ( + re.compile(rf"^(\s*)from\s+({'|'.join(LOCAL)})(\.[\w.]+)?\s+import\s", re.MULTILINE), + lambda m: f"{m.group(1)}from api.{m.group(2)}{m.group(3) or ''} import ", + ), # import db -> from api import db - (re.compile(rf"^(\s*)import\s+({'|'.join(LOCAL)})\s*$", re.MULTILINE), - lambda m: f"{m.group(1)}from api import {m.group(2)}"), + ( + re.compile(rf"^(\s*)import\s+({'|'.join(LOCAL)})\s*$", re.MULTILINE), + lambda m: f"{m.group(1)}from api import {m.group(2)}", + ), ] def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--dry-run", action="store_true", - help="show what would change without writing") + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--dry-run", action="store_true", help="show what would change without writing") args = ap.parse_args() if not API.is_dir(): @@ -80,8 +82,7 @@ def main() -> int: elif args.dry_run: print(" would create api/__init__.py") else: - init.write_text('"""FastAPI backend for the CSV Table Hub frontend."""\n', - encoding="utf-8") + init.write_text('"""FastAPI backend for the CSV Table Hub frontend."""\n', encoding="utf-8") print(" created api/__init__.py") changed = 0 @@ -108,7 +109,7 @@ def main() -> int: print(f"\n{changed} file(s) {'would be ' if args.dry_run else ''}changed") if not args.dry_run and changed: print("\nNow verify:") - print(' python -c "from api.main import app; print(\'ok\')"') + print(" python -c \"from api.main import app; print('ok')\"") print(" python -m pytest tests/test_api.py -m unit") print("\nAnd update scripts/start-api.ps1 to run from the repo root:") print(" Set-Location $PSScriptRoot\\..") diff --git a/scripts/fix_inserted_rows_count.py b/scripts/fix_inserted_rows_count.py index 1b3363c..696e1f8 100644 --- a/scripts/fix_inserted_rows_count.py +++ b/scripts/fix_inserted_rows_count.py @@ -26,6 +26,7 @@ python -m pytest tests/test_issue_04_multi_file_upload.py """ + from __future__ import annotations import argparse @@ -35,36 +36,34 @@ ROOT = Path(__file__).resolve().parents[1] TARGET = ROOT / "api" / "services" / "dynamic_loader.py" -OLD_STMT = ''' stmt = sql.SQL( +OLD_STMT = """ stmt = sql.SQL( "INSERT INTO {}.{} ({}) VALUES %s ON CONFLICT (_row_hash) DO NOTHING" - ).format(sql.Identifier(schema), sql.Identifier(table_name), insert_cols)''' + ).format(sql.Identifier(schema), sql.Identifier(table_name), insert_cols)""" -NEW_STMT = ''' # RETURNING + fetch=True is deliberate: execute_values pages at 100 +NEW_STMT = """ # RETURNING + fetch=True is deliberate: execute_values pages at 100 # by default and cur.rowcount reflects only the last page, which # under-counted every file over 100 rows. Counting returned rows is # page-size independent. See docs/DEFECT_INSERTED_ROWS.md. stmt = sql.SQL( "INSERT INTO {}.{} ({}) VALUES %s " "ON CONFLICT (_row_hash) DO NOTHING RETURNING 1" - ).format(sql.Identifier(schema), sql.Identifier(table_name), insert_cols)''' + ).format(sql.Identifier(schema), sql.Identifier(table_name), insert_cols)""" -OLD_LOOP = ''' for i in range(0, len(to_insert), 500): +OLD_LOOP = """ for i in range(0, len(to_insert), 500): chunk = to_insert[i : i + 500] execute_values(cur, stmt.as_string(cur), chunk) - inserted += cur.rowcount if cur.rowcount >= 0 else len(chunk)''' + inserted += cur.rowcount if cur.rowcount >= 0 else len(chunk)""" -NEW_LOOP = ''' for i in range(0, len(to_insert), 500): +NEW_LOOP = """ for i in range(0, len(to_insert), 500): chunk = to_insert[i : i + 500] returned = execute_values( cur, stmt.as_string(cur), chunk, fetch=True) - inserted += len(returned)''' + inserted += len(returned)""" def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--dry-run", action="store_true", - help="show what would change without writing") + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--dry-run", action="store_true", help="show what would change without writing") args = ap.parse_args() if not TARGET.exists(): @@ -77,9 +76,9 @@ def main() -> int: print(" already fixed — nothing to do") return 0 - missing = [name for name, snippet in - (("INSERT statement", OLD_STMT), ("insert loop", OLD_LOOP)) - if snippet not in text] + missing = [ + name for name, snippet in (("INSERT statement", OLD_STMT), ("insert loop", OLD_LOOP)) if snippet not in text + ] if missing: print("error: could not locate the expected code:") for name in missing: diff --git a/scripts/health_check.py b/scripts/health_check.py index 2a4eede..7a746da 100644 --- a/scripts/health_check.py +++ b/scripts/health_check.py @@ -8,6 +8,7 @@ Exit code 0 when all checks pass; 1 if any check fails. """ + from __future__ import annotations import ast @@ -17,11 +18,11 @@ ROOT = Path(__file__).resolve().parents[1] -GREEN = "\033[0;32m" +GREEN = "\033[0;32m" YELLOW = "\033[1;33m" -RED = "\033[0;31m" -CYAN = "\033[0;36m" -NC = "\033[0m" +RED = "\033[0;31m" +CYAN = "\033[0;36m" +NC = "\033[0m" _results: list[tuple[str, str, str]] = [] # (status, label, detail) @@ -59,10 +60,11 @@ def _check_py_syntax(label: str, path: Path) -> None: # ── Core Python source ──────────────────────────────────────────────────────── + def check_core_python() -> None: files = { - "validator.py syntax": ROOT / "build" / "csv" / "validator.py", - "runner.py syntax": ROOT / "evals" / "runner.py", + "validator.py syntax": ROOT / "build" / "csv" / "validator.py", + "runner.py syntax": ROOT / "evals" / "runner.py", "gap_report.py syntax": ROOT / "evals" / "gap_report.py", } for label, path in files.items(): @@ -71,6 +73,7 @@ def check_core_python() -> None: # ── Shell scripts ───────────────────────────────────────────────────────────── + def check_shell_scripts() -> None: scripts = [ ROOT / "build" / "deploy_all.sh", @@ -79,7 +82,7 @@ def check_shell_scripts() -> None: ROOT / "preflight.sh", ] adapters = (ROOT / "build" / "adapters").glob("adapter_*.sh") - loaders = (ROOT / "build" / "csv").glob("loader_*.sh") + loaders = (ROOT / "build" / "csv").glob("loader_*.sh") for path in [*scripts, *adapters, *loaders]: rel = path.relative_to(ROOT) _check_file(str(rel), path) @@ -87,6 +90,7 @@ def check_shell_scripts() -> None: # ── SQL schema & environment files ─────────────────────────────────────────── + def check_sql_files() -> None: pg_schema = ROOT / "build" / "schema" / "postgresql" / "te_core_schema.sql" _check_file("postgresql schema", pg_schema) @@ -115,6 +119,7 @@ def check_sql_files() -> None: # ── Eval datasets & expected files ──────────────────────────────────────────── + def check_eval_coverage() -> None: datasets_root = ROOT / "evals" / "datasets" expected_root = ROOT / "evals" / "expected" @@ -149,6 +154,7 @@ def check_eval_coverage() -> None: exp_action = "" if exp_file.exists(): import json + try: d = json.loads(exp_file.read_text(encoding="utf-8")) exp_action = d.get("runner_action", "default") @@ -162,13 +168,14 @@ def check_eval_coverage() -> None: # ── Test infrastructure ─────────────────────────────────────────────────────── + def check_test_infra() -> None: files = { - "pytest.ini": ROOT / "pytest.ini", - "conftest.py": ROOT / "tests" / "conftest.py", - "requirements-dev": ROOT / "requirements-dev.txt", - "Makefile": ROOT / "Makefile", - "run_qa.ps1": ROOT / "scripts" / "run_qa.ps1", + "pytest.ini": ROOT / "pytest.ini", + "conftest.py": ROOT / "tests" / "conftest.py", + "requirements-dev": ROOT / "requirements-dev.txt", + "Makefile": ROOT / "Makefile", + "run_qa.ps1": ROOT / "scripts" / "run_qa.ps1", } for label, path in files.items(): _check_file(label, path) @@ -183,6 +190,7 @@ def check_test_infra() -> None: # ── Config template ─────────────────────────────────────────────────────────── + def check_config() -> None: example = ROOT / "build" / "config.env.example" if not example.exists(): @@ -207,6 +215,7 @@ def check_config() -> None: # ── Main ────────────────────────────────────────────────────────────────────── + def main() -> int: print(f"\n{CYAN}PostgreDataMigrationApp — Health Dashboard{NC}") print("=" * 60) diff --git a/scripts/perf_import.py b/scripts/perf_import.py index 8fc7559..1e77466 100644 --- a/scripts/perf_import.py +++ b/scripts/perf_import.py @@ -28,7 +28,10 @@ try: from fastapi.testclient import TestClient # noqa: E402 -except (ImportError, RuntimeError) as exc: # starlette's TestClient needs httpx2, which api/requirements.txt doesn't list +except ( + ImportError, + RuntimeError, +) as exc: # starlette's TestClient needs httpx2, which api/requirements.txt doesn't list sys.exit(f"{exc}\nInstall it with: pip install httpx2") from psycopg2 import sql # noqa: E402 @@ -48,8 +51,10 @@ def make_csv(rows: int) -> str: """A realistic file: eight typed columns, unique rows, no row that fails validation.""" lines = ["id,name,email,amount,created,active,notes,score"] for i in range(1, rows + 1): - lines.append(f"{i},Person {i},person{i}@example.org,{i % 1000}.{i % 100:02d},2026-{i % 12 + 1:02d}-{i % 28 + 1:02d}," - f"{'true' if i % 2 else 'false'},note for row {i} with some text,{i % 97}") + lines.append( + f"{i},Person {i},person{i}@example.org,{i % 1000}.{i % 100:02d},2026-{i % 12 + 1:02d}-{i % 28 + 1:02d}," + f"{'true' if i % 2 else 'false'},note for row {i} with some text,{i % 97}" + ) return "\n".join(lines) + "\n" @@ -59,10 +64,17 @@ def _windows_total_memory() -> int: from ctypes import wintypes class MemoryStatus(ctypes.Structure): - _fields_ = [("dwLength", wintypes.DWORD), ("dwMemoryLoad", wintypes.DWORD), ("ullTotalPhys", ctypes.c_ulonglong), - ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), - ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), - ("ullAvailVirtual", ctypes.c_ulonglong), ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] + _fields_ = [ + ("dwLength", wintypes.DWORD), + ("dwMemoryLoad", wintypes.DWORD), + ("ullTotalPhys", ctypes.c_ulonglong), + ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), + ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), + ("ullAvailVirtual", ctypes.c_ulonglong), + ("ullAvailExtendedVirtual", ctypes.c_ulonglong), + ] kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) kernel32.GlobalMemoryStatusEx.argtypes = [ctypes.POINTER(MemoryStatus)] @@ -84,11 +96,18 @@ def _windows_peak_memory() -> int: from ctypes import wintypes class ProcessCounters(ctypes.Structure): - _fields_ = [("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD), ("PeakWorkingSetSize", ctypes.c_size_t), - ("WorkingSetSize", ctypes.c_size_t), ("QuotaPeakPagedPoolUsage", ctypes.c_size_t), - ("QuotaPagedPoolUsage", ctypes.c_size_t), ("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t), - ("QuotaNonPagedPoolUsage", ctypes.c_size_t), ("PagefileUsage", ctypes.c_size_t), - ("PeakPagefileUsage", ctypes.c_size_t)] + _fields_ = [ + ("cb", wintypes.DWORD), + ("PageFaultCount", wintypes.DWORD), + ("PeakWorkingSetSize", ctypes.c_size_t), + ("WorkingSetSize", ctypes.c_size_t), + ("QuotaPeakPagedPoolUsage", ctypes.c_size_t), + ("QuotaPagedPoolUsage", ctypes.c_size_t), + ("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t), + ("QuotaNonPagedPoolUsage", ctypes.c_size_t), + ("PagefileUsage", ctypes.c_size_t), + ("PeakPagefileUsage", ctypes.c_size_t), + ] kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) psapi = ctypes.WinDLL("psapi", use_last_error=True) @@ -107,9 +126,9 @@ def peak_memory_mb() -> int | None: try: try: import resource - except ImportError: # Windows has no resource module + except ImportError: # Windows has no resource module return round(_windows_peak_memory() / 1024 / 1024) - peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # KiB on Linux, bytes on macOS + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # KiB on Linux, bytes on macOS return round(peak / (1024 * 1024 if sys.platform == "darwin" else 1024)) except Exception: # noqa: BLE001 return None @@ -118,17 +137,24 @@ def peak_memory_mb() -> int | None: def hardware() -> dict: mem_gb = None try: - mem_gb = round(int(next(line for line in Path("/proc/meminfo").read_text().splitlines() - if line.startswith("MemTotal")).split()[1]) / 1024 / 1024, 1) + mem_gb = round( + int( + next( + line for line in Path("/proc/meminfo").read_text().splitlines() if line.startswith("MemTotal") + ).split()[1] + ) + / 1024 + / 1024, + 1, + ) except (OSError, StopIteration): try: - mem_gb = round(_windows_total_memory() / 1024 ** 3, 1) + mem_gb = round(_windows_total_memory() / 1024**3, 1) except Exception: # noqa: BLE001 — a readout, not a requirement pass # CPUs this process may use (taskset or a container limit lowers it), not the machine's total. cpus = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count() - return {"cpus": cpus, "memoryGB": mem_gb, "python": platform.python_version(), - "os": platform.platform()} + return {"cpus": cpus, "memoryGB": mem_gb, "python": platform.python_version(), "os": platform.platform()} def run(rows: int) -> dict: @@ -142,7 +168,7 @@ def run(rows: int) -> dict: with Conn() as conn, conn.cursor() as cur: tenant_id = accounts.create_tenant(cur, slug, "Performance run") accounts.add_membership(cur, accounts.create_user(cur, f"{slug}_u", password), tenant_id, "tenant_admin") - accounts.set_self_approval(cur, slug, True) # one person does every step + accounts.set_self_approval(cur, slug, True) # one person does every step conn.commit() try: migrate_tenant(slug) @@ -158,27 +184,41 @@ def step(name, call): body = {"fileName": "perf.csv", "content": content} step("preview", lambda: client.post("/api/csv/preview", headers=headers, json=body)) - staged = step("stage", lambda: client.post("/api/csv/uploads", headers=headers, json={**body, "types": TYPES})) + staged = step( + "stage", lambda: client.post("/api/csv/uploads", headers=headers, json={**body, "types": TYPES}) + ) upload = staged["uploadId"] - step("reviewPage", lambda: client.get(f"/api/csv/uploads/{upload}/rows", headers=headers, params={"limit": 100})) + step( + "reviewPage", + lambda: client.get(f"/api/csv/uploads/{upload}/rows", headers=headers, params={"limit": 100}), + ) step("submit", lambda: client.post(f"/api/csv/uploads/{upload}/submit", headers=headers)) - step("approve", lambda: client.post(f"/api/csv/uploads/{upload}/approval", headers=headers, - json={"decision": "approve"})) + step( + "approve", + lambda: client.post( + f"/api/csv/uploads/{upload}/approval", headers=headers, json={"decision": "approve"} + ), + ) import_headers = {**headers, "Idempotency-Key": "perf"} result = step("import", lambda: client.post(f"/api/csv/uploads/{upload}/import", headers=import_headers)) finally: - with Conn() as conn, conn.cursor() as cur: # uploads are insert-only; dropping the tenant clears them + with Conn() as conn, conn.cursor() as cur: # uploads are insert-only; dropping the tenant clears them cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(slug)))) control = sql.Identifier(settings.CONTROL_SCHEMA) cur.execute(sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format(control), (slug,)) cur.execute(sql.SQL("DELETE FROM {}.users WHERE username = %s").format(control), (f"{slug}_u",)) - drop_tenant_role(cur, slug) # #297: each tenant has its own database role + drop_tenant_role(cur, slug) # #297: each tenant has its own database role conn.commit() timings["upToImported"] = round(sum(timings[k] for k in ("stage", "submit", "approve", "import")), 3) # This process only (the API and the CSV in memory), not PostgreSQL's. - return {"rows": rows, "timings": timings, "reconciliation": result["reconciliation"], - "csvMB": round(len(content.encode()) / 1024 / 1024, 1), "hardware": hardware(), - "peakPythonMB": peak_memory_mb()} + return { + "rows": rows, + "timings": timings, + "reconciliation": result["reconciliation"], + "csvMB": round(len(content.encode()) / 1024 / 1024, 1), + "hardware": hardware(), + "peakPythonMB": peak_memory_mb(), + } def preflight() -> None: @@ -187,19 +227,29 @@ def preflight() -> None: import psycopg2 try: - psycopg2.connect(host=settings.PG_HOST, port=settings.PG_PORT, user=settings.PG_USER, - password=settings.PG_PASSWORD.get_secret_value(), dbname=settings.PG_DATABASE, connect_timeout=5).close() + psycopg2.connect( + host=settings.PG_HOST, + port=settings.PG_PORT, + user=settings.PG_USER, + password=settings.PG_PASSWORD.get_secret_value(), + dbname=settings.PG_DATABASE, + connect_timeout=5, + ).close() except psycopg2.OperationalError as exc: - sys.exit(f"Cannot connect to PostgreSQL as '{settings.PG_USER}' at {settings.PG_HOST}:{settings.PG_PORT}, " - f"database '{settings.PG_DATABASE}':\n {str(exc).strip()}\n" - "Check PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE. In PowerShell they are set with, for example, " - '$env:PGPORT="5433" (a variable set in an earlier command stays set for the whole session).') + sys.exit( + f"Cannot connect to PostgreSQL as '{settings.PG_USER}' at {settings.PG_HOST}:{settings.PG_PORT}, " + f"database '{settings.PG_DATABASE}':\n {str(exc).strip()}\n" + "Check PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE. In PowerShell they are set with, for example, " + '$env:PGPORT="5433" (a variable set in an earlier command stays set for the whole session).' + ) def verdict(report: dict, max_import: float = MAX_IMPORT_SECONDS, max_page: float = MAX_FIRST_PAGE_SECONDS) -> dict: t = report["timings"] - return {"importUnderTarget": t["upToImported"] <= max_import, - "firstPageUnderTarget": max(t["preview"], t["reviewPage"]) <= max_page} + return { + "importUnderTarget": t["upToImported"] <= max_import, + "firstPageUnderTarget": max(t["preview"], t["reviewPage"]) <= max_page, + } def main() -> int: @@ -210,8 +260,11 @@ def main() -> int: args = ap.parse_args() preflight() report = run(args.rows) - report["targets"] = {"maxImportSeconds": MAX_IMPORT_SECONDS, "maxFirstPageSeconds": MAX_FIRST_PAGE_SECONDS, - **verdict(report)} + report["targets"] = { + "maxImportSeconds": MAX_IMPORT_SECONDS, + "maxFirstPageSeconds": MAX_FIRST_PAGE_SECONDS, + **verdict(report), + } if args.json: print(json.dumps(report, indent=2)) else: @@ -221,13 +274,21 @@ def main() -> int: for name in ("preview", "stage", "reviewPage", "submit", "approve", "import", "upToImported"): print(f" {name:<13}{t[name]:>8.2f} s") peak = report["peakPythonMB"] - print(f" peak memory of this process: {'unknown' if peak is None else f'{peak} MB'} (PostgreSQL's is separate)") + print( + f" peak memory of this process: {'unknown' if peak is None else f'{peak} MB'} (PostgreSQL's is separate)" + ) print(f" reconciliation {report['reconciliation']}") ok = report["targets"] - print(f" import (stage to imported) <= {MAX_IMPORT_SECONDS:.0f} s: {'yes' if ok['importUnderTarget'] else 'NO'}; " - f"first preview page <= {MAX_FIRST_PAGE_SECONDS:.0f} s: {'yes' if ok['firstPageUnderTarget'] else 'NO'}") + print( + f" import (stage to imported) <= {MAX_IMPORT_SECONDS:.0f} s: {'yes' if ok['importUnderTarget'] else 'NO'}; " + f"first preview page <= {MAX_FIRST_PAGE_SECONDS:.0f} s: {'yes' if ok['firstPageUnderTarget'] else 'NO'}" + ) print(" (targets are for a 2 vCPU / 4 GB instance; this machine is above)" if (hw["cpus"] or 0) > 2 else "") - return 1 if args.enforce and not all(report["targets"][k] for k in ("importUnderTarget", "firstPageUnderTarget")) else 0 + return ( + 1 + if args.enforce and not all(report["targets"][k] for k in ("importUnderTarget", "firstPageUnderTarget")) + else 0 + ) if __name__ == "__main__": diff --git a/scripts/pg_login.py b/scripts/pg_login.py index 86ae60b..2135385 100644 --- a/scripts/pg_login.py +++ b/scripts/pg_login.py @@ -90,8 +90,9 @@ def try_login(host: str, port: str, user: str, password: str, timeout: int = 5) """(OK | REFUSED | UNREACHABLE, a one-line reason). Connects to the always-present `postgres` database, so only the credentials are tested, not whether a particular database exists.""" try: - psycopg2.connect(host=host, port=port, user=user, password=password, - dbname="postgres", connect_timeout=timeout).close() + psycopg2.connect( + host=host, port=port, user=user, password=password, dbname="postgres", connect_timeout=timeout + ).close() except psycopg2.OperationalError as exc: reason = str(exc).strip().splitlines()[0] if str(exc).strip() else "connection failed" return (REFUSED if db._is_permanent(exc) else UNREACHABLE), reason @@ -99,19 +100,26 @@ def try_login(host: str, port: str, user: str, password: str, timeout: int = 5) def _login_from_env() -> tuple[str, str, str, str]: - return (os.environ.get("PGHOST") or DEFAULT_HOST, os.environ.get("PGPORT") or DEFAULT_PORT, - os.environ.get("PGUSER") or DEFAULT_USER, os.environ.get("PGPASSWORD", "")) + return ( + os.environ.get("PGHOST") or DEFAULT_HOST, + os.environ.get("PGPORT") or DEFAULT_PORT, + os.environ.get("PGUSER") or DEFAULT_USER, + os.environ.get("PGPASSWORD", ""), + ) def _not_reachable(host: str, port: str, reason: str) -> int: - print(f"Could not reach PostgreSQL at {host}:{port}.\n {reason}\n" - "Check that the server is running on that host and port.", file=sys.stderr) + print( + f"Could not reach PostgreSQL at {host}:{port}.\n {reason}\n" + "Check that the server is running on that host and port.", + file=sys.stderr, + ) return 3 def cmd_check(args) -> int: host, port, user, password = _login_from_env() - up, why = server_available(host, port) # first: is anything there to log in to? + up, why = server_available(host, port) # first: is anything there to log in to? if not up: return _not_reachable(host, port, why) if args.server_only: @@ -125,7 +133,7 @@ def cmd_check(args) -> int: if status == REFUSED: print(f"PostgreSQL refused the login for {who}.\n {reason}", file=sys.stderr) return 2 - return _not_reachable(host, port, reason) # it went away, or is still starting up + return _not_reachable(host, port, reason) # it went away, or is still starting up def cmd_save(args) -> int: @@ -136,16 +144,19 @@ def cmd_save(args) -> int: # Before asking for a password: with no server there is nothing to test it against. up, why = server_available(host, port) if not up: - print(f"PostgreSQL could not be reached at {host}:{port}, so nothing was saved and no " - f"password was asked for.\n {why}\n" - "Check that the server is running on that host and port, then run this again.", - file=sys.stderr) + print( + f"PostgreSQL could not be reached at {host}:{port}, so nothing was saved and no " + f"password was asked for.\n {why}\n" + "Check that the server is running on that host and port, then run this again.", + file=sys.stderr, + ) return 1 if args.from_env: password = os.environ.get("PGPASSWORD", "") else: password = os.environ.get("TE_PG_PASSWORD") or getpass.getpass( - f"Password for {user}@{host}:{port} (input hidden): ") + f"Password for {user}@{host}:{port} (input hidden): " + ) if not password: print("No password given; nothing was saved.", file=sys.stderr) return 2 @@ -156,14 +167,15 @@ def cmd_save(args) -> int: status, reason = try_login(host, port, user, password) if status != OK: what = "refused the login" if status == REFUSED else "could not be reached" - print(f"PostgreSQL {what} for {user}@{host}:{port}, so nothing was saved.\n {reason}", - file=sys.stderr) + print(f"PostgreSQL {what} for {user}@{host}:{port}, so nothing was saved.\n {reason}", file=sys.stderr) return 1 path = env_file_for(args.env) write_env_file(path, {"PGHOST": host, "PGPORT": port, "PGUSER": user, "PGPASSWORD": password}) - print(f"Saved the {args.env} login for {user}@{host}:{port} to {path}.\n" - "start-api.ps1 will use it. For the other scripts, in a PowerShell window run: " - ". .\\scripts\\dev-env.ps1") + print( + f"Saved the {args.env} login for {user}@{host}:{port} to {path}.\n" + "start-api.ps1 will use it. For the other scripts, in a PowerShell window run: " + ". .\\scripts\\dev-env.ps1" + ) return 0 @@ -174,8 +186,11 @@ def cmd_where(args) -> int: return 0 held = read_env_file(path) shown = {k: v for k, v in held.items() if k != "PGPASSWORD"} - print(f"{path}\n holds: " + ", ".join(f"{k}={v}" for k, v in shown.items()) - + (", PGPASSWORD=(saved, not shown)" if "PGPASSWORD" in held else "")) + print( + f"{path}\n holds: " + + ", ".join(f"{k}={v}" for k, v in shown.items()) + + (", PGPASSWORD=(saved, not shown)" if "PGPASSWORD" in held else "") + ) return 0 @@ -188,14 +203,20 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("--host") p.add_argument("--port") p.add_argument("--user") - p.add_argument("--from-env", action="store_true", - help="take the login from PGHOST / PGPORT / PGUSER / PGPASSWORD instead of asking") + p.add_argument( + "--from-env", + action="store_true", + help="take the login from PGHOST / PGPORT / PGUSER / PGPASSWORD instead of asking", + ) p.add_argument("--no-check", action="store_true", help="save without testing the login first") p.set_defaults(func=cmd_save) p = sub.add_parser("check", help="test the login in the current PG* variables") - p.add_argument("--server-only", action="store_true", - help="only check that PostgreSQL is accepting connections; use no password") + p.add_argument( + "--server-only", + action="store_true", + help="only check that PostgreSQL is accepting connections; use no password", + ) p.set_defaults(func=cmd_check) p = sub.add_parser("where", help="say where the saved login is") diff --git a/scripts/sample_verification_run.py b/scripts/sample_verification_run.py index 370fd21..45289e4 100644 --- a/scripts/sample_verification_run.py +++ b/scripts/sample_verification_run.py @@ -62,7 +62,9 @@ def call(self, method: str, path: str, body: dict | None = None) -> tuple[int, o if self.token: headers["Authorization"] = "Bearer " + self.token req = urllib.request.Request( - self.base + path, method=method, headers=headers, + self.base + path, + method=method, + headers=headers, data=json.dumps(body).encode() if body is not None else None, ) try: @@ -84,7 +86,11 @@ def upload(api: Api, name: str, content: str, mode: str, target: str | None = No body["targetTable"] = target status, resp = api.call("POST", "/api/csv/upload", body) resp.pop("logs", None) # per-step timestamps are noise in a report - return {"http": status, "preview": {k: prev.get(k) for k in ("status", "inferredTypes", "teTableMatch")}, "response": resp} + return { + "http": status, + "preview": {k: prev.get(k) for k in ("status", "inferredTypes", "teTableMatch")}, + "response": resp, + } def loaded_table(result: dict, what: str) -> str: @@ -97,7 +103,8 @@ def loaded_table(result: dict, what: str) -> str: raise NotFresh( f"The {what} upload was refused (HTTP {result['http']}, status {resp.get('status')!r}: {why}).\n" "This run needs a FRESH database, where nothing has been loaded, so that every count starts at zero " - "(see the prerequisites at the top of this file). Nothing was written.") + "(see the prerequisites at the top of this file). Nothing was written." + ) def collect(api: Api, conn) -> dict: @@ -121,15 +128,29 @@ def collect(api: Api, conn) -> dict: schema, table = loaded_table(a, "orgs_sample.csv (Test and Evaluation)").split(".") cur.execute(f'SELECT name, org_type, country FROM "{schema}"."{table}" ORDER BY name') # nosec B608 # schema and table are double-quoted names from this deployment's own API response (operator tool) db_rows = [list(r) for r in cur.fetchall()] - cur.execute(f'SELECT file_hash, row_count, total_rows, failed_rows, id FROM "{schema}".csv_files WHERE file_name=%s', # nosec B608 # schema and table are double-quoted names from this deployment's own API response (operator tool) - ("orgs_sample.csv",)) + cur.execute( + f'SELECT file_hash, row_count, total_rows, failed_rows, id FROM "{schema}".csv_files WHERE file_name=%s', # nosec B608 # schema and table are double-quoted names from this deployment's own API response (operator tool) + ("orgs_sample.csv",), + ) reg = cur.fetchone() expected_loaded = sorted(r for i, r in enumerate(src_rows, 1) if i not in EXPECTED_REJECTS) ev["te"] = { - "file": "orgs_sample.csv", "bytes": len(orgs_bytes), "sha256": hashlib.sha256(orgs_bytes).hexdigest(), - "source_rows": len(src_rows), "source_lines": {i: ",".join(r) for i, r in enumerate(src_rows, 1)}, - "api": a, "target": resp["tableName"], "db_row_count": len(db_rows), "db_rows": db_rows, - "registry": {"file_hash": reg[0], "row_count": reg[1], "total_rows": reg[2], "failed_rows": reg[3], "id": reg[4]}, + "file": "orgs_sample.csv", + "bytes": len(orgs_bytes), + "sha256": hashlib.sha256(orgs_bytes).hexdigest(), + "source_rows": len(src_rows), + "source_lines": {i: ",".join(r) for i, r in enumerate(src_rows, 1)}, + "api": a, + "target": resp["tableName"], + "db_row_count": len(db_rows), + "db_rows": db_rows, + "registry": { + "file_hash": reg[0], + "row_count": reg[1], + "total_rows": reg[2], + "failed_rows": reg[3], + "id": reg[4], + }, "expected_rejects": EXPECTED_REJECTS, "rejected_row_numbers": sorted(e["rowNumber"] for e in resp.get("rowErrors", [])), "loaded_matches_source": sorted(db_rows) == expected_loaded, @@ -143,14 +164,23 @@ def collect(api: Api, conn) -> dict: bs = ev["te"]["target"].split(".")[0] # dynamic tables live in the same tenant schema cur.execute(f'SELECT count(*) FROM "{bs}"."{bt}"') # nosec B608 # schema and table are double-quoted names from this deployment's own API response (operator tool) b_count = cur.fetchone()[0] - cur.execute("SELECT column_name, data_type FROM information_schema.columns " - "WHERE table_schema=%s AND table_name=%s ORDER BY ordinal_position", (bs, bt)) + cur.execute( + "SELECT column_name, data_type FROM information_schema.columns " + "WHERE table_schema=%s AND table_name=%s ORDER BY ordinal_position", + (bs, bt), + ) cols = [list(r) for r in cur.fetchall() if not r[0].startswith("_")] cur.execute(f'SELECT file_hash FROM "{bs}".csv_files WHERE file_name=%s', ("equipment_register.csv",)) # nosec B608 # schema and table are double-quoted names from this deployment's own API response (operator tool) ev["dynamic"] = { - "file": "equipment_register.csv", "bytes": len(eq_bytes), "sha256": hashlib.sha256(eq_bytes).hexdigest(), - "source_rows": len(eq.splitlines()) - 1, "api": b, "table": bt, "db_row_count": b_count, - "db_columns": cols, "registry_file_hash": cur.fetchone()[0], + "file": "equipment_register.csv", + "bytes": len(eq_bytes), + "sha256": hashlib.sha256(eq_bytes).hexdigest(), + "source_rows": len(eq.splitlines()) - 1, + "api": b, + "table": bt, + "db_row_count": b_count, + "db_columns": cols, + "registry_file_hash": cur.fetchone()[0], "duplicate_same_name": upload(api, "equipment_register.csv", eq, "dynamic")["response"], "duplicate_renamed": upload(api, "equipment_register_copy.csv", eq, "dynamic")["response"], } @@ -160,8 +190,12 @@ def collect(api: Api, conn) -> dict: cur.execute(f'SELECT id, row_count, failed_rows FROM "{schema}".csv_files WHERE file_name=%s', ("orgs_sample.csv",)) # nosec B608 # schema and table are double-quoted names from this deployment's own API response (operator tool) after = cur.fetchall() cur.execute(f'SELECT count(*) FROM "{schema}"."{table}"') # nosec B608 # schema and table are double-quoted names from this deployment's own API response (operator tool) - ev["te_reupload"] = {"status": again.get("status"), "inserted": again.get("insertedRows"), - "registry_after": [list(r) for r in after], "db_row_count_after": cur.fetchone()[0]} + ev["te_reupload"] = { + "status": again.get("status"), + "inserted": again.get("insertedRows"), + "registry_after": [list(r) for r in after], + "db_row_count_after": cur.fetchone()[0], + } # --- Observed deployment posture (read from the running system, not from our env) -- unauth = urllib.request.Request(api.base + "/api/csv/files") @@ -170,12 +204,17 @@ def collect(api: Api, conn) -> dict: unauth_status = r.status except urllib.error.HTTPError as e: unauth_status = e.code - cur.execute("SELECT DISTINCT usename FROM pg_stat_activity WHERE datname=current_database() " - "AND pid<>pg_backend_pid() AND usename IS NOT NULL") + cur.execute( + "SELECT DISTINCT usename FROM pg_stat_activity WHERE datname=current_database() " + "AND pid<>pg_backend_pid() AND usename IS NOT NULL" + ) api_roles = sorted(r[0] for r in cur.fetchall()) cur.execute("SELECT tableowner FROM pg_tables WHERE schemaname=%s AND tablename='audit_log'", (bs,)) - ev["posture"] = {"unauthenticated_request_status": unauth_status, "database_roles_connected": api_roles, - "audit_log_owner": cur.fetchone()[0]} + ev["posture"] = { + "unauthenticated_request_status": unauth_status, + "database_roles_connected": api_roles, + "audit_log_owner": cur.fetchone()[0], + } # --- Audit trail ---------------------------------------------------------------- ev["audit"] = { @@ -192,42 +231,77 @@ def checks(ev: dict) -> list[tuple[str, str, bool]]: r = te["api"]["response"] entries = au["log"]["entries"] return [ - ("T&E: every source row is accounted for (loaded + rejected = source)", - f"{r['insertedRows']} + {r['failedRows']} + {r['duplicateRowsSkipped']} = {r['insertedRows'] + r['failedRows'] + r['duplicateRowsSkipped']} of {te['source_rows']}", - r["insertedRows"] + r["failedRows"] + r["duplicateRowsSkipped"] == te["source_rows"]), - ("T&E: rows in the database equal the rows the API reported loaded", - f"database {te['db_row_count']}, API {r['insertedRows']}", te["db_row_count"] == r["insertedRows"]), - ("T&E: the rows rejected are exactly the rows the fixture was designed to produce", - f"rejected {te['rejected_row_numbers']}, expected {sorted(te['expected_rejects'])}", - te["rejected_row_numbers"] == sorted(int(k) for k in te["expected_rejects"])), - ("T&E: every loaded row matches its source row, field for field", - f"{te['db_row_count']} of {te['db_row_count']} match" if te["loaded_matches_source"] else "mismatch", - te["loaded_matches_source"]), - ("T&E: file hash recorded by the system equals an independently computed SHA-256", - te["registry"]["file_hash"][:16] + "…", te["registry"]["file_hash"] == te["sha256"]), - ("T&E: registry counts equal the API response", - f"registry loaded {te['registry']['row_count']} / failed {te['registry']['failed_rows']}", - te["registry"]["row_count"] == r["insertedRows"] and te["registry"]["failed_rows"] == r["failedRows"]), - ("Dynamic: rows in the new table equal source rows", - f"database {dy['db_row_count']}, source {dy['source_rows']}", dy["db_row_count"] == dy["source_rows"]), - ("Dynamic: file hash recorded by the system equals an independently computed SHA-256", - dy["registry_file_hash"][:16] + "…", dy["registry_file_hash"] == dy["sha256"]), - ("Dynamic: re-upload of the same file is refused", - dy["duplicate_same_name"].get("status"), dy["duplicate_same_name"].get("status") == "duplicate_file"), - ("Dynamic: the same content under a new filename is refused", - f"{dy['duplicate_renamed'].get('status')} (reason: {dy['duplicate_renamed'].get('reason')})", - dy["duplicate_renamed"].get("status") == "duplicate_file" and dy["duplicate_renamed"].get("reason") == "content"), - ("Audit: one entry per successful load; refused or fully failed uploads leave none", - f"{au['log']['total']} entries for 2 loads", au["log"]["total"] == 2 and len(entries) == 2), - ("Audit: hash chain recomputed and intact", - f"intact={au['verify'].get('intact')}, rows checked={au['verify'].get('rows')}", au["verify"].get("intact") is True), - ("T&E: re-uploading the same file, where every row now fails, is refused and changes nothing", - f"status {ev['te_reupload']['status']}; registry (id, loaded, failed) {ev['te_reupload']['registry_after']} " - f"vs before {[[te['registry']['id'], te['registry']['row_count'], te['registry']['failed_rows']]]}; " - f"database rows {ev['te_reupload']['db_row_count_after']}", - ev["te_reupload"]["status"] == "error" - and ev["te_reupload"]["registry_after"] == [[te["registry"]["id"], te["registry"]["row_count"], te["registry"]["failed_rows"]]] - and ev["te_reupload"]["db_row_count_after"] == te["db_row_count"]), + ( + "T&E: every source row is accounted for (loaded + rejected = source)", + f"{r['insertedRows']} + {r['failedRows']} + {r['duplicateRowsSkipped']} = {r['insertedRows'] + r['failedRows'] + r['duplicateRowsSkipped']} of {te['source_rows']}", + r["insertedRows"] + r["failedRows"] + r["duplicateRowsSkipped"] == te["source_rows"], + ), + ( + "T&E: rows in the database equal the rows the API reported loaded", + f"database {te['db_row_count']}, API {r['insertedRows']}", + te["db_row_count"] == r["insertedRows"], + ), + ( + "T&E: the rows rejected are exactly the rows the fixture was designed to produce", + f"rejected {te['rejected_row_numbers']}, expected {sorted(te['expected_rejects'])}", + te["rejected_row_numbers"] == sorted(int(k) for k in te["expected_rejects"]), + ), + ( + "T&E: every loaded row matches its source row, field for field", + f"{te['db_row_count']} of {te['db_row_count']} match" if te["loaded_matches_source"] else "mismatch", + te["loaded_matches_source"], + ), + ( + "T&E: file hash recorded by the system equals an independently computed SHA-256", + te["registry"]["file_hash"][:16] + "…", + te["registry"]["file_hash"] == te["sha256"], + ), + ( + "T&E: registry counts equal the API response", + f"registry loaded {te['registry']['row_count']} / failed {te['registry']['failed_rows']}", + te["registry"]["row_count"] == r["insertedRows"] and te["registry"]["failed_rows"] == r["failedRows"], + ), + ( + "Dynamic: rows in the new table equal source rows", + f"database {dy['db_row_count']}, source {dy['source_rows']}", + dy["db_row_count"] == dy["source_rows"], + ), + ( + "Dynamic: file hash recorded by the system equals an independently computed SHA-256", + dy["registry_file_hash"][:16] + "…", + dy["registry_file_hash"] == dy["sha256"], + ), + ( + "Dynamic: re-upload of the same file is refused", + dy["duplicate_same_name"].get("status"), + dy["duplicate_same_name"].get("status") == "duplicate_file", + ), + ( + "Dynamic: the same content under a new filename is refused", + f"{dy['duplicate_renamed'].get('status')} (reason: {dy['duplicate_renamed'].get('reason')})", + dy["duplicate_renamed"].get("status") == "duplicate_file" + and dy["duplicate_renamed"].get("reason") == "content", + ), + ( + "Audit: one entry per successful load; refused or fully failed uploads leave none", + f"{au['log']['total']} entries for 2 loads", + au["log"]["total"] == 2 and len(entries) == 2, + ), + ( + "Audit: hash chain recomputed and intact", + f"intact={au['verify'].get('intact')}, rows checked={au['verify'].get('rows')}", + au["verify"].get("intact") is True, + ), + ( + "T&E: re-uploading the same file, where every row now fails, is refused and changes nothing", + f"status {ev['te_reupload']['status']}; registry (id, loaded, failed) {ev['te_reupload']['registry_after']} " + f"vs before {[[te['registry']['id'], te['registry']['row_count'], te['registry']['failed_rows']]]}; " + f"database rows {ev['te_reupload']['db_row_count_after']}", + ev["te_reupload"]["status"] == "error" + and ev["te_reupload"]["registry_after"] + == [[te["registry"]["id"], te["registry"]["row_count"], te["registry"]["failed_rows"]]] + and ev["te_reupload"]["db_row_count_after"] == te["db_row_count"], + ), ] @@ -274,9 +348,11 @@ def render(ev: dict, rows: list[tuple[str, str, bool]]) -> str: "`scripts/sample_verification_run.py` before the run. The reason column is the database's own message.", "", "| Data row | Source line | Designed defect | Database message |\n|---|---|---|---|", - *[f"| {e['rowNumber']} | `{te['source_lines'][e['rowNumber']]}` " - f"| {te['expected_rejects'].get(e['rowNumber'], 'not expected')} | {e['reason']} |" - for e in r.get("rowErrors", [])], + *[ + f"| {e['rowNumber']} | `{te['source_lines'][e['rowNumber']]}` " + f"| {te['expected_rejects'].get(e['rowNumber'], 'not expected')} | {e['reason']} |" + for e in r.get("rowErrors", []) + ], "", "## 5. Rows loaded (T&E file)", "", @@ -303,8 +379,10 @@ def render(ev: dict, rows: list[tuple[str, str, bool]]) -> str: f"**intact = {au['verify'].get('intact')}** over {au['verify'].get('rows')} rows.", "", "| Action | File | Target | Mode | Actor | Time (UTC) |\n|---|---|---|---|---|---|", - *[f"| {e['action']} | {e['fileName']} | {e['tableName']} | {e['mode']} | {e['actor']} | {e['performedAt']} |" - for e in au["log"]["entries"]], + *[ + f"| {e['action']} | {e['fileName']} | {e['tableName']} | {e['mode']} | {e['actor']} | {e['performedAt']} |" + for e in au["log"]["entries"] + ], "", "## 8. What this report does and does not show", "", @@ -344,16 +422,21 @@ def main() -> int: return 2 api = Api(args.api) - status, login = api.call("POST", "/api/auth/login", - {"tenant": args.tenant, "username": args.username, "password": password}) + status, login = api.call( + "POST", "/api/auth/login", {"tenant": args.tenant, "username": args.username, "password": password} + ) if status != 200: print(f"Sign-in failed ({status}): {login}", file=sys.stderr) return 2 api.token = login["token"] - conn = psycopg2.connect(host=os.environ.get("PGHOST", "localhost"), port=os.environ.get("PGPORT", "5432"), - user=os.environ.get("PGUSER", "postgres"), password=os.environ.get("PGPASSWORD", ""), - dbname=os.environ.get("PGDATABASE", "te_mgmt_dev")) + conn = psycopg2.connect( + host=os.environ.get("PGHOST", "localhost"), + port=os.environ.get("PGPORT", "5432"), + user=os.environ.get("PGUSER", "postgres"), + password=os.environ.get("PGPASSWORD", ""), + dbname=os.environ.get("PGDATABASE", "te_mgmt_dev"), + ) conn.autocommit = True try: ev = collect(api, conn) @@ -362,7 +445,9 @@ def main() -> int: return 2 rows = checks(ev) - (SAMPLES / "verification-run-evidence.json").write_text(json.dumps(ev, indent=2, default=str) + "\n", encoding="utf-8") + (SAMPLES / "verification-run-evidence.json").write_text( + json.dumps(ev, indent=2, default=str) + "\n", encoding="utf-8" + ) (SAMPLES / "MIGRATION_VERIFICATION_REPORT_SAMPLE.md").write_text(render(ev, rows), encoding="utf-8") for c, o, p in rows: print(("PASS" if p else "FAIL"), "-", c, "->", o) diff --git a/scripts/security_audit.py b/scripts/security_audit.py index fe7adff..5e1a1a0 100644 --- a/scripts/security_audit.py +++ b/scripts/security_audit.py @@ -16,6 +16,7 @@ Exit status: 0 clean, 1 a blocking finding or an expired allow-list entry, 2 could not audit. """ + from __future__ import annotations import argparse @@ -74,8 +75,14 @@ def parse_pip_audit(text: str, source: str) -> list[Finding]: findings: dict[tuple, Finding] = {} # pip-audit can list the same advisory twice for one package for dep in audited: for vuln in dep["vulns"]: - finding = Finding(source=source, package=dep["name"], version=dep["version"], advisory=vuln["id"], - aliases=tuple(vuln.get("aliases", ())), fix=", ".join(vuln.get("fix_versions") or ())) + finding = Finding( + source=source, + package=dep["name"], + version=dep["version"], + advisory=vuln["id"], + aliases=tuple(vuln.get("aliases", ())), + fix=", ".join(vuln.get("fix_versions") or ()), + ) findings.setdefault((finding.package, finding.version, finding.advisory), finding) return list(findings.values()) @@ -102,9 +109,16 @@ def parse_npm_audit(text: str, source: str) -> list[Finding]: if severity not in NPM_BLOCKING: continue advisory = (via.get("url") or "").rstrip("/").rsplit("/", 1)[-1] or str(via.get("source", name)) - findings.append(Finding(source=source, package=name, version=entry.get("range", ""), - advisory=advisory, fix=str(entry.get("fixAvailable", "")), - severity=severity)) + findings.append( + Finding( + source=source, + package=name, + version=entry.get("range", ""), + advisory=advisory, + fix=str(entry.get("fixAvailable", "")), + severity=severity, + ) + ) return findings @@ -152,8 +166,11 @@ def _run(cmd: list[str], cwd: Path, what: str) -> str: def run_pip_audit(requirements: str) -> str: - return _run([sys.executable, "-m", "pip_audit", "-r", requirements, "--progress-spinner", "off", - "--format", "json"], ROOT, f"pip-audit on {requirements}") + return _run( + [sys.executable, "-m", "pip_audit", "-r", requirements, "--progress-spinner", "off", "--format", "json"], + ROOT, + f"pip-audit on {requirements}", + ) def run_npm_audit(directory: str) -> str: @@ -163,8 +180,16 @@ def run_npm_audit(directory: str) -> str: return _run([npm, "audit", "--omit=dev", "--json"], ROOT / directory, f"npm audit in {directory}") -def main(argv=None, *, pip_runner=run_pip_audit, npm_runner=run_npm_audit, today=None, requirements=None, - allowlist_text=None, npm_dir=NPM_DIR) -> int: +def main( + argv=None, + *, + pip_runner=run_pip_audit, + npm_runner=run_npm_audit, + today=None, + requirements=None, + allowlist_text=None, + npm_dir=NPM_DIR, +) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) parser.add_argument("--allowlist", type=Path, default=ALLOWLIST) args = parser.parse_args(argv) @@ -172,8 +197,9 @@ def main(argv=None, *, pip_runner=run_pip_audit, npm_runner=run_npm_audit, today problems: list[str] = [] findings: list[Finding] = [] try: - entries = parse_allowlist(allowlist_text if allowlist_text is not None - else args.allowlist.read_text(encoding="utf-8")) + entries = parse_allowlist( + allowlist_text if allowlist_text is not None else args.allowlist.read_text(encoding="utf-8") + ) files = requirements if requirements is not None else discover_requirements() except (AuditError, OSError) as exc: print(f"could not audit: {exc}") @@ -198,16 +224,22 @@ def main(argv=None, *, pip_runner=run_pip_audit, npm_runner=run_npm_audit, today for f in result.allowed: print(f"allowed {f.package} {f.version} {f.advisory} ({f.source})") for e in result.expired: - print(f"expired allow-list entry: {e.advisory} was valid through {e.expires}; renew it with a new reason, " - "or remove it") + print( + f"expired allow-list entry: {e.advisory} was valid through {e.expires}; renew it with a new reason, " + "or remove it" + ) for f in result.blocking: print(f"BLOCKING {f.package} {f.version} {f.advisory} fix: {f.fix or 'none known'} ({f.source})") if result.blocking or result.expired: - print(f"\n{len(result.blocking)} blocking, {len(result.expired)} expired exception(s). Upgrade the package, " - "or add an entry to security/audit-allowlist.txt with a reason and an expiry date.") + print( + f"\n{len(result.blocking)} blocking, {len(result.expired)} expired exception(s). Upgrade the package, " + "or add an entry to security/audit-allowlist.txt with a reason and an expiry date." + ) return 1 - print(f"no known vulnerabilities in {len(files)} requirements file(s) or in {npm_dir}'s production dependencies" - + (f" ({len(result.allowed)} allowed)" if result.allowed else "")) + print( + f"no known vulnerabilities in {len(files)} requirements file(s) or in {npm_dir}'s production dependencies" + + (f" ({len(result.allowed)} allowed)" if result.allowed else "") + ) return 0 diff --git a/scripts/select_tests.py b/scripts/select_tests.py index 1897218..0e3dc69 100644 --- a/scripts/select_tests.py +++ b/scripts/select_tests.py @@ -7,6 +7,7 @@ python3 scripts/select_tests.py # compare vs origin/main python3 scripts/select_tests.py HEAD~1 # compare vs previous commit """ + from __future__ import annotations import subprocess @@ -15,31 +16,35 @@ ROOT = Path(__file__).resolve().parents[1] -GREEN = "\033[0;32m" +GREEN = "\033[0;32m" YELLOW = "\033[1;33m" -CYAN = "\033[0;36m" -DIM = "\033[2m" -NC = "\033[0m" +CYAN = "\033[0;36m" +DIM = "\033[2m" +NC = "\033[0m" # Map of changed path patterns → pytest marks / files to run _RULES: list[tuple[str, str, str]] = [ # (path_fragment, mark_expression, human_label) - ("build/csv/validator", "unit or snapshot or regression", "validator changed → unit + snapshot + regression"), - ("evals/runner", "unit", "runner changed → unit"), - ("evals/gap_report", "unit", "gap_report changed → unit"), - ("evals/datasets/", "unit", "eval dataset changed → unit (tier_p)"), - ("evals/expected/", "unit", "expected file changed → unit (tier_p)"), - ("build/environments/", "integration or e2e or parity", "env SQL changed → integration + parity"), - ("build/schema/", "integration or e2e or parity", "schema changed → integration + parity"), - ("tests/suites/", "integration", "SQL test suite changed → integration"), - ("tests/unit/", "unit or regression or security or snapshot", "unit test changed → free tier"), - ("tests/system/", "integration", "system test changed → integration"), - ("tests/system_integration/", "e2e or integration or parity", "system-integration test changed → e2e + integration + parity"), - ("tests/accessibility/", "accessibility", "accessibility test changed → accessibility"), - ("csv-table-hub-main/src/", "accessibility", "frontend changed → accessibility scans (CI job only)"), - ("scripts/", "security", "scripts changed → security scan"), - ("build/adapters/", "security", "adapter changed → security scan"), - ("build/csv/loader_", "e2e", "loader changed → e2e"), + ("build/csv/validator", "unit or snapshot or regression", "validator changed → unit + snapshot + regression"), + ("evals/runner", "unit", "runner changed → unit"), + ("evals/gap_report", "unit", "gap_report changed → unit"), + ("evals/datasets/", "unit", "eval dataset changed → unit (tier_p)"), + ("evals/expected/", "unit", "expected file changed → unit (tier_p)"), + ("build/environments/", "integration or e2e or parity", "env SQL changed → integration + parity"), + ("build/schema/", "integration or e2e or parity", "schema changed → integration + parity"), + ("tests/suites/", "integration", "SQL test suite changed → integration"), + ("tests/unit/", "unit or regression or security or snapshot", "unit test changed → free tier"), + ("tests/system/", "integration", "system test changed → integration"), + ( + "tests/system_integration/", + "e2e or integration or parity", + "system-integration test changed → e2e + integration + parity", + ), + ("tests/accessibility/", "accessibility", "accessibility test changed → accessibility"), + ("csv-table-hub-main/src/", "accessibility", "frontend changed → accessibility scans (CI job only)"), + ("scripts/", "security", "scripts changed → security scan"), + ("build/adapters/", "security", "adapter changed → security scan"), + ("build/csv/loader_", "e2e", "loader changed → e2e"), ] _DEFAULT_MARKS = "unit" # always run at minimum when diff is unclear @@ -68,7 +73,7 @@ def main() -> None: if not changed: print(f" {YELLOW}No changed files detected — running default tier: {_DEFAULT_MARKS}{NC}") - print(f"\n pytest -m \"{_DEFAULT_MARKS}\" tests/\n") + print(f'\n pytest -m "{_DEFAULT_MARKS}" tests/\n') return print(f" {DIM}Changed files:{NC}") @@ -99,7 +104,7 @@ def main() -> None: print(f" • {label}") print(f"\n {GREEN}Recommended command:{NC}") - print(f" pytest -m \"{mark_expr}\" tests/\n") + print(f' pytest -m "{mark_expr}" tests/\n') if __name__ == "__main__": diff --git a/scripts/test_catalogue.py b/scripts/test_catalogue.py index 2b165f6..4c56619 100755 --- a/scripts/test_catalogue.py +++ b/scripts/test_catalogue.py @@ -12,6 +12,7 @@ CI generates it on every run and attaches it as the `test-catalogue` artifact; run this script to get a local copy. """ + from __future__ import annotations import ast @@ -22,9 +23,20 @@ TESTS_DIR = ROOT / "tests" OUTPUT = ROOT / "docs" / "TEST_CASES.md" -MARKER_NAMES = {"unit", "integration", "e2e", "regression", "security", - "snapshot", "parity", "system", "sit", "performance", - "accessibility", "uat"} +MARKER_NAMES = { + "unit", + "integration", + "e2e", + "regression", + "security", + "snapshot", + "parity", + "system", + "sit", + "performance", + "accessibility", + "uat", +} def _extract_markers(decorators: list[ast.expr]) -> list[str]: @@ -32,16 +44,16 @@ def _extract_markers(decorators: list[ast.expr]) -> list[str]: markers: list[str] = [] for dec in decorators: if isinstance(dec, ast.Attribute) and isinstance(dec.value, ast.Attribute): - if (isinstance(dec.value.value, ast.Name) - and dec.value.value.id == "pytest" - and dec.value.attr == "mark"): + if isinstance(dec.value.value, ast.Name) and dec.value.value.id == "pytest" and dec.value.attr == "mark": markers.append(dec.attr) elif isinstance(dec, ast.Call) and isinstance(dec.func, ast.Attribute): attr = dec.func if isinstance(attr.value, ast.Attribute): - if (isinstance(attr.value.value, ast.Name) - and attr.value.value.id == "pytest" - and attr.value.attr == "mark"): + if ( + isinstance(attr.value.value, ast.Name) + and attr.value.value.id == "pytest" + and attr.value.attr == "mark" + ): markers.append(attr.attr) return markers @@ -74,24 +86,28 @@ def _collect_tests(filepath: Path) -> list[dict]: for item in node.body: if isinstance(item, ast.FunctionDef) and item.name.startswith("test"): markers = class_markers + _extract_markers(item.decorator_list) - tests.append({ - "file": rel.as_posix(), - "class": node.name, - "name": item.name, - "line": item.lineno, - "markers": sorted(set(m for m in markers if m in MARKER_NAMES)), - "objective": _first_line_of_docstring(item), - }) + tests.append( + { + "file": rel.as_posix(), + "class": node.name, + "name": item.name, + "line": item.lineno, + "markers": sorted(set(m for m in markers if m in MARKER_NAMES)), + "objective": _first_line_of_docstring(item), + } + ) elif isinstance(item := node, ast.FunctionDef) and item.name.startswith("test"): markers = _extract_markers(item.decorator_list) - tests.append({ - "file": rel.as_posix(), - "class": "", - "name": item.name, - "line": item.lineno, - "markers": sorted(set(m for m in markers if m in MARKER_NAMES)), - "objective": _first_line_of_docstring(item), - }) + tests.append( + { + "file": rel.as_posix(), + "class": "", + "name": item.name, + "line": item.lineno, + "markers": sorted(set(m for m in markers if m in MARKER_NAMES)), + "objective": _first_line_of_docstring(item), + } + ) return tests diff --git a/scripts/test_report.py b/scripts/test_report.py index 7591364..4090f9b 100644 --- a/scripts/test_report.py +++ b/scripts/test_report.py @@ -28,6 +28,7 @@ Exit codes: 0 all executed tests passed; 1 otherwise (or any skip under --strict). """ + from __future__ import annotations import argparse @@ -52,9 +53,10 @@ def _collect_all_ids(paths: list[str] | None = None) -> set[str]: r = subprocess.run( # -o addopts="" neutralises pytest.ini's -q, which would otherwise collapse # the listing to per-file counts instead of individual test ids. - [sys.executable, "-m", "pytest", "--collect-only", "-q", "--no-header", - "-o", "addopts=", *(paths or [])], - cwd=ROOT, capture_output=True, text=True, + [sys.executable, "-m", "pytest", "--collect-only", "-q", "--no-header", "-o", "addopts=", *(paths or [])], + cwd=ROOT, + capture_output=True, + text=True, ) ids = set() for line in r.stdout.splitlines(): @@ -90,11 +92,9 @@ def _parse(xml_path: Path): if (n := case.find("skipped")) is not None: skipped.append((tid, (n.get("message") or "").strip() or "no reason given")) elif (n := case.find("failure")) is not None: - failed.append((tid, (n.get("message") or "").strip().splitlines()[0] - if n.get("message") else "")) + failed.append((tid, (n.get("message") or "").strip().splitlines()[0] if n.get("message") else "")) elif (n := case.find("error")) is not None: - errored.append((tid, (n.get("message") or "").strip().splitlines()[0] - if n.get("message") else "")) + errored.append((tid, (n.get("message") or "").strip().splitlines()[0] if n.get("message") else "")) else: passed.append(tid) return passed, failed, errored, skipped @@ -106,14 +106,15 @@ def _norm(tid: str) -> str: def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--markers", default=None, - help='pytest -m expression, e.g. "unit or security"') - ap.add_argument("--strict", action="store_true", - help="exit non-zero if any test was skipped") - ap.add_argument("--paths", nargs="+", default=None, - help="test paths to run instead of pytest.ini's testpaths (tests/), e.g. e2e for the browser tests") + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--markers", default=None, help='pytest -m expression, e.g. "unit or security"') + ap.add_argument("--strict", action="store_true", help="exit non-zero if any test was skipped") + ap.add_argument( + "--paths", + nargs="+", + default=None, + help="test paths to run instead of pytest.ini's testpaths (tests/), e.g. e2e for the browser tests", + ) args = ap.parse_args() with tempfile.TemporaryDirectory() as td: @@ -125,21 +126,27 @@ def main() -> int: # pytest's exit codes: 0 all passed, 1 some failed, 2 interrupted (e.g. a collection error), 3 internal error, # 4 usage error (a conftest that cannot be imported lands here), 5 nothing collected. Only 0 and 1 mean tests # ran; any other code means they did not, whatever the results hold (#273: 4 and 5 used to read as a pass). - meanings = {2: "interrupted, e.g. a collection error", 3: "internal error", - 4: "usage error, e.g. a conftest that cannot be imported", 5: "no tests were collected"} + meanings = { + 2: "interrupted, e.g. a collection error", + 3: "internal error", + 4: "usage error, e.g. a conftest that cannot be imported", + 5: "no tests were collected", + } interrupted = exit_code not in (0, 1) - executed = {_norm(t) for t in passed} \ - | {_norm(t) for t, _ in failed} \ - | {_norm(t) for t, _ in errored} \ + executed = ( + {_norm(t) for t in passed} + | {_norm(t) for t, _ in failed} + | {_norm(t) for t, _ in errored} | {_norm(t) for t, _ in skipped} + ) not_run = sorted(i for i in all_ids if _norm(i) not in executed) total = len(passed) + len(failed) + len(errored) + len(skipped) bar = "=" * 66 print(f"\n{CYAN}{bar}\n FINAL RESULT — every test accounted for\n{bar}{NC}") if args.markers: - print(f" marker filter : -m \"{args.markers}\"") + print(f' marker filter : -m "{args.markers}"') if args.paths: print(f" paths : {' '.join(args.paths)}") print(f" pytest exit : {exit_code}" + (f" ({meanings.get(exit_code, 'unexpected')})" if interrupted else "")) @@ -149,8 +156,7 @@ def main() -> int: print(f" {RED}FAILED{NC} : {len(failed)}") print(f" {RED}ERROR{NC} : {len(errored)}") print(f" {YELLOW}SKIPPED{NC} : {len(skipped)}") - not_run_reason = ("run INTERRUPTED before they could execute" - if interrupted else "deselected by the marker filter") + not_run_reason = "run INTERRUPTED before they could execute" if interrupted else "deselected by the marker filter" print(f" {DIM}NOT RUN{NC} : {len(not_run)} {DIM}({not_run_reason}){NC}") for label, colour, items in (("FAILED", RED, failed), ("ERROR", RED, errored)): @@ -175,21 +181,23 @@ def main() -> int: for tid in not_run: print(f" {DIM}- {tid}{NC}") if interrupted: - print(f" {RED}The run was interrupted (exit code 2) — most often a" - f" collection error above. These tests never executed.{NC}") + print( + f" {RED}The run was interrupted (exit code 2) — most often a" + f" collection error above. These tests never executed.{NC}" + ) else: - print(f" {DIM}Deselected by the marker filter, not skipped. They must" - f" run in another job.{NC}") + print(f" {DIM}Deselected by the marker filter, not skipped. They must run in another job.{NC}") else: print(f" {GREEN}none — every collected test was executed{NC}") # A run that executed nothing proves nothing, so it cannot pass. - ok = (not failed and not errored and not interrupted and total > 0 - and not (args.strict and skipped)) + ok = not failed and not errored and not interrupted and total > 0 and not (args.strict and skipped) if not ok: if interrupted: - print(f"\n {RED}pytest exited with code {exit_code} " - f"({meanings.get(exit_code, 'unexpected')}): the tests did not run.{NC}") + print( + f"\n {RED}pytest exited with code {exit_code} " + f"({meanings.get(exit_code, 'unexpected')}): the tests did not run.{NC}" + ) elif total == 0: print(f"\n {RED}No test was executed, so there is nothing to pass.{NC}") print(f"\n{bar}") diff --git a/streamlit_app/api_client.py b/streamlit_app/api_client.py index 32dd345..296e853 100644 --- a/streamlit_app/api_client.py +++ b/streamlit_app/api_client.py @@ -38,8 +38,11 @@ class TimedOut(ApiError): saying "can't reach the API" here would be untrue, and would invite a second import of the same file.""" def __init__(self, seconds: float): - super().__init__(0, f"The server did not answer within {seconds:g} seconds. It may still be working on " - "this, and it can't be stopped from here. Look in Import history before trying again.") + super().__init__( + 0, + f"The server did not answer within {seconds:g} seconds. It may still be working on " + "this, and it can't be stopped from here. Look in Import history before trying again.", + ) def _detail(response: requests.Response) -> str: diff --git a/streamlit_app/auth.py b/streamlit_app/auth.py index 1cb5202..89a71f6 100644 --- a/streamlit_app/auth.py +++ b/streamlit_app/auth.py @@ -23,18 +23,18 @@ # A copy of api/auth.py PERMISSIONS, so the app does not import the API's packages. A test fails if the # two drift apart (tests/unit/test_streamlit_shell.py::test_the_permission_table_matches_the_api). PERMISSIONS: dict[str, frozenset[str]] = { - "preview": frozenset({"uploader", "tenant_admin"}), - "upload": frozenset({"uploader", "tenant_admin"}), - "list_files": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), - "read_rows": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), - "list_te": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), - "delete_file": frozenset({"tenant_admin"}), - "read_audit": frozenset({"tenant_admin", "auditor"}), + "preview": frozenset({"uploader", "tenant_admin"}), + "upload": frozenset({"uploader", "tenant_admin"}), + "list_files": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), + "read_rows": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), + "list_te": frozenset({"uploader", "reviewer", "tenant_admin", "auditor"}), + "delete_file": frozenset({"tenant_admin"}), + "read_audit": frozenset({"tenant_admin", "auditor"}), "reset_password": frozenset({"tenant_admin"}), - "review_rows": frozenset({"reviewer", "tenant_admin"}), - "submit_import": frozenset({"uploader", "tenant_admin"}), + "review_rows": frozenset({"reviewer", "tenant_admin"}), + "submit_import": frozenset({"uploader", "tenant_admin"}), "approve_import": frozenset({"reviewer", "tenant_admin"}), - "run_import": frozenset({"uploader", "reviewer", "tenant_admin"}), + "run_import": frozenset({"uploader", "reviewer", "tenant_admin"}), } @@ -94,8 +94,9 @@ def take_notice() -> str | None: def sign_in(tenant: str, username: str, password: str) -> str | None: """Sign in. Returns None on success, or the message to show. Same wording as the React app.""" try: - new = api_client.request("POST", "/api/auth/login", - json={"tenant": tenant, "username": username, "password": password}) + new = api_client.request( + "POST", "/api/auth/login", json={"tenant": tenant, "username": username, "password": password} + ) except api_client.Unauthorized: return "Invalid tenant, username or password" except api_client.ApiError as e: diff --git a/streamlit_app/exports.py b/streamlit_app/exports.py index 8d6d88c..d092152 100644 --- a/streamlit_app/exports.py +++ b/streamlit_app/exports.py @@ -29,8 +29,19 @@ XLSX_SHEET_LIMIT = 31 ERROR_HEADERS = ["file", "row_number", "column", "value", "reason", "plain_english", "header_mapping"] -HISTORY_HEADERS = ["file", "status", "uploaded_at", "uploader", "mode", "state", "total_rows", "imported_rows", - "failed_rows", "reason", "upload_id"] +HISTORY_HEADERS = [ + "file", + "status", + "uploaded_at", + "uploader", + "mode", + "state", + "total_rows", + "imported_rows", + "failed_rows", + "reason", + "upload_id", +] CSV_TYPE = "text/csv" XLSX_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" @@ -52,6 +63,7 @@ def _cell(value: object) -> object: # ── files ─────────────────────────────────────────────────────────────────────────────────── + def to_csv(headers: list[str], rows: list[dict]) -> bytes: """The rows as CSV, UTF-8, a line feed after each line (as the React export does). Quoted only where needed.""" out = io.StringIO() @@ -64,7 +76,7 @@ def to_csv(headers: list[str], rows: list[dict]) -> bytes: def _xlsx_text(text: str) -> str: text = ILLEGAL_CHARACTERS_RE.sub("\ufffd", text) - return text if len(text) <= XLSX_CELL_LIMIT else text[:XLSX_CELL_LIMIT - 1] + "\u2026" + return text if len(text) <= XLSX_CELL_LIMIT else text[: XLSX_CELL_LIMIT - 1] + "\u2026" def to_xlsx(sheet: str, headers: list[str], rows: list[dict]) -> bytes: @@ -94,6 +106,7 @@ def report_name(kind: str, ext: str, file_name: str | None = None, now: datetime # ── what goes in them ─────────────────────────────────────────────────────────────────────── + def mapping_summary(mapping: list[dict] | None) -> str: """'a→b, c→d' for the renamed columns, '(no renames)' if none was renamed, '' if there was no mapping.""" if not mapping: @@ -102,25 +115,54 @@ def mapping_summary(mapping: list[dict] | None) -> str: return ", ".join(renames) if renames else "(no renames)" -def error_rows(file_name: str, row_errors: list[dict], message: str | None = None, - mapping: list[dict] | None = None) -> list[dict]: +def error_rows( + file_name: str, row_errors: list[dict], message: str | None = None, mapping: list[dict] | None = None +) -> list[dict]: """One report row per row error. An import that failed as a whole, with no row errors, gets one row for its message.""" summary = mapping_summary(mapping) rows = [] if message and not row_errors: - rows.append({"file": file_name, "row_number": 0, "column": "", "value": "", "reason": message, - "plain_english": message, "header_mapping": summary}) + rows.append( + { + "file": file_name, + "row_number": 0, + "column": "", + "value": "", + "reason": message, + "plain_english": message, + "header_mapping": summary, + } + ) for e in row_errors: - rows.append({"file": file_name, "row_number": e.get("rowNumber"), "column": e.get("column") or "", - "value": e.get("value") or "", "reason": e["reason"], "plain_english": e["reason"], - "header_mapping": summary}) + rows.append( + { + "file": file_name, + "row_number": e.get("rowNumber"), + "column": e.get("column") or "", + "value": e.get("value") or "", + "reason": e["reason"], + "plain_english": e["reason"], + "header_mapping": summary, + } + ) return rows def history_rows(uploads: list[dict]) -> list[dict]: """The import history as report rows: one per upload attempt, from `GET /api/csv/uploads`.""" - return [{"file": u["file_name"], "status": u["status"], "uploaded_at": u["uploaded_at"], - "uploader": u.get("uploader") or "", "mode": u.get("mode") or "", "state": u.get("state") or "", - "total_rows": u.get("total_rows"), "imported_rows": u.get("imported_rows"), - "failed_rows": u.get("failed_rows"), "reason": u.get("failure_reason") or "", "upload_id": u["id"]} - for u in uploads] + return [ + { + "file": u["file_name"], + "status": u["status"], + "uploaded_at": u["uploaded_at"], + "uploader": u.get("uploader") or "", + "mode": u.get("mode") or "", + "state": u.get("state") or "", + "total_rows": u.get("total_rows"), + "imported_rows": u.get("imported_rows"), + "failed_rows": u.get("failed_rows"), + "reason": u.get("failure_reason") or "", + "upload_id": u["id"], + } + for u in uploads + ] diff --git a/streamlit_app/files_model.py b/streamlit_app/files_model.py index 796dcd5..4d5d16b 100644 --- a/streamlit_app/files_model.py +++ b/streamlit_app/files_model.py @@ -22,14 +22,22 @@ def page_count(total: int) -> int: def files_frame(files: list[dict], first: int = 1) -> pd.DataFrame: """A page of the list of imported files, numbered from `first`.""" - return pd.DataFrame([{ - "#": first + i, "File": m.literal(f["file_name"]), "Table": m.literal(f["table_name"]), - "Columns": str(len(f.get("column_names") or [])), "Rows": str(f["row_count"]), - "Failed": "" if not f.get("failed_rows") else str(f["failed_rows"]), - "Uploaded (UTC)": m.when(f["created_at"]), - "Uploaded by": m.literal(f["uploader"]) if f.get("uploader") else "", - } for i, f in enumerate(files)], columns=["#", "File", "Table", "Columns", "Rows", "Failed", "Uploaded (UTC)", - "Uploaded by"]).set_index("#") + return pd.DataFrame( + [ + { + "#": first + i, + "File": m.literal(f["file_name"]), + "Table": m.literal(f["table_name"]), + "Columns": str(len(f.get("column_names") or [])), + "Rows": str(f["row_count"]), + "Failed": "" if not f.get("failed_rows") else str(f["failed_rows"]), + "Uploaded (UTC)": m.when(f["created_at"]), + "Uploaded by": m.literal(f["uploader"]) if f.get("uploader") else "", + } + for i, f in enumerate(files) + ], + columns=["#", "File", "Table", "Columns", "Rows", "Failed", "Uploaded (UTC)", "Uploaded by"], + ).set_index("#") def file_label(f: dict) -> str: diff --git a/streamlit_app/history_model.py b/streamlit_app/history_model.py index 58a9268..03a7122 100644 --- a/streamlit_app/history_model.py +++ b/streamlit_app/history_model.py @@ -20,16 +20,33 @@ EVENTS_PAGE = 100 # audit events a page shows (the API's default) ERROR_ROWS_SHOWN = 200 # failed rows shown at once; the report has all the server kept -STATUSES = [("", "All statuses"), ("imported", "Imported"), ("partly_imported", "Partly imported"), - ("failed", "Failed"), ("rejected", "Rejected"), ("duplicate", "Duplicate"), ("staged", "Staged")] +STATUSES = [ + ("", "All statuses"), + ("imported", "Imported"), + ("partly_imported", "Partly imported"), + ("failed", "Failed"), + ("rejected", "Rejected"), + ("duplicate", "Duplicate"), + ("staged", "Staged"), +] # The actions the API records (api/services/audit.py VALID_ACTIONS). A test fails if the two drift apart. -AUDIT_ACTIONS = ("upload", "delete", "password_reset", "row_decision", "cell_edit", "submit", "approve", "reject", - "import") +AUDIT_ACTIONS = ( + "upload", + "delete", + "password_reset", + "row_decision", + "cell_edit", + "submit", + "approve", + "reject", + "import", +) # ── what is asked ─────────────────────────────────────────────────────────────────────────── + def day_start(day: date) -> str: """Midnight UTC at the start of `day`, as the API takes a time.""" return datetime(day.year, day.month, day.day, tzinfo=timezone.utc).isoformat() @@ -42,8 +59,15 @@ def _range(params: dict, date_from: date | None, date_to: date | None) -> None: params["to"] = day_start(date_to + timedelta(days=1)) -def uploads_params(file: str = "", status: str = "", uploader: str = "", date_from: date | None = None, - date_to: date | None = None, limit: int = PAGE_SIZE + 1, offset: int = 0) -> dict: +def uploads_params( + file: str = "", + status: str = "", + uploader: str = "", + date_from: date | None = None, + date_to: date | None = None, + limit: int = PAGE_SIZE + 1, + offset: int = 0, +) -> dict: """The query for the list of imports. Blank filters are left out. One more than a page is asked for, so the screen knows whether there is a next page without a count (the API gives none).""" params: dict = {"limit": limit, "offset": offset} @@ -54,8 +78,16 @@ def uploads_params(file: str = "", status: str = "", uploader: str = "", date_fr return params -def events_params(actor: str = "", action: str = "", file: str = "", date_from: date | None = None, - date_to: date | None = None, limit: int = EVENTS_PAGE, offset: int = 0, fmt: str = "json") -> dict: +def events_params( + actor: str = "", + action: str = "", + file: str = "", + date_from: date | None = None, + date_to: date | None = None, + limit: int = EVENTS_PAGE, + offset: int = 0, + fmt: str = "json", +) -> dict: params: dict = {"limit": limit, "offset": offset} for key, value in (("actor", actor), ("action", action), ("file", file)): if value and value.strip(): @@ -88,6 +120,7 @@ def page_of(rows: list, size: int = PAGE_SIZE) -> tuple[list, bool]: # ── what is shown ─────────────────────────────────────────────────────────────────────────── + def status_label(status: str) -> str: return m.ATTEMPT_LABEL.get(status, status) @@ -105,13 +138,23 @@ def _number(value: int | None) -> str: def uploads_frame(uploads: list[dict]) -> pd.DataFrame: """The list of imports as a table, indexed by the upload's number.""" - return pd.DataFrame([{ - "#": int(u["id"]), "File": _text(u["file_name"]), "Status": status_label(u["status"]), - "Rows": _number(u.get("total_rows")), "Imported": _number(u.get("imported_rows")), - "Failed": _number(u.get("failed_rows")), "Uploaded (UTC)": m.when(u["uploaded_at"]), - "Uploaded by": _text(u.get("uploader")), "Mode": u.get("mode") or "", - } for u in uploads], columns=["#", "File", "Status", "Rows", "Imported", "Failed", "Uploaded (UTC)", - "Uploaded by", "Mode"]).set_index("#") + return pd.DataFrame( + [ + { + "#": int(u["id"]), + "File": _text(u["file_name"]), + "Status": status_label(u["status"]), + "Rows": _number(u.get("total_rows")), + "Imported": _number(u.get("imported_rows")), + "Failed": _number(u.get("failed_rows")), + "Uploaded (UTC)": m.when(u["uploaded_at"]), + "Uploaded by": _text(u.get("uploader")), + "Mode": u.get("mode") or "", + } + for u in uploads + ], + columns=["#", "File", "Status", "Rows", "Imported", "Failed", "Uploaded (UTC)", "Uploaded by", "Mode"], + ).set_index("#") def import_label(upload: dict) -> str: @@ -133,9 +176,18 @@ def outcome_line(upload: dict, detail: dict) -> str: def errors_frame(row_errors: list[dict]) -> pd.DataFrame: - return pd.DataFrame([{"Row": e.get("rowNumber"), "Column": _text(e.get("column")), "Value": _text(e.get("value")), - "Reason": _text(e["reason"])} for e in row_errors], - columns=["Row", "Column", "Value", "Reason"]).set_index("Row") + return pd.DataFrame( + [ + { + "Row": e.get("rowNumber"), + "Column": _text(e.get("column")), + "Value": _text(e.get("value")), + "Reason": _text(e["reason"]), + } + for e in row_errors + ], + columns=["Row", "Column", "Value", "Reason"], + ).set_index("Row") def errors_note(shown: int, failed: int | None) -> str | None: @@ -150,16 +202,32 @@ def log_frame(logs: list[dict]) -> pd.DataFrame: rows = [] for entry in logs: at = datetime.fromtimestamp(entry["ts"] / 1000, tz=timezone.utc).strftime("%H:%M:%S.%f")[:-3] - rows.append({"Time (UTC)": at, "Step": entry["step"], "Level": entry["level"], - "Message": _text(entry["message"]), "Count": _number(entry.get("count"))}) + rows.append( + { + "Time (UTC)": at, + "Step": entry["step"], + "Level": entry["level"], + "Message": _text(entry["message"]), + "Count": _number(entry.get("count")), + } + ) return pd.DataFrame(rows, columns=["Time (UTC)", "Step", "Level", "Message", "Count"]).set_index("Time (UTC)") def events_frame(entries: list[dict]) -> pd.DataFrame: - return pd.DataFrame([{ - "When (UTC)": m.when(e["performedAt"]), "Actor": _text(e.get("actor")), "Action": e["action"], - "File": _text(e.get("fileName")), "Table": _text(e.get("tableName")), - } for e in entries], columns=["When (UTC)", "Actor", "Action", "File", "Table"]).set_index("When (UTC)") + return pd.DataFrame( + [ + { + "When (UTC)": m.when(e["performedAt"]), + "Actor": _text(e.get("actor")), + "Action": e["action"], + "File": _text(e.get("fileName")), + "Table": _text(e.get("tableName")), + } + for e in entries + ], + columns=["When (UTC)", "Actor", "Action", "File", "Table"], + ).set_index("When (UTC)") def events_summary(page: dict) -> str: diff --git a/streamlit_app/outcomes.py b/streamlit_app/outcomes.py index a18b44a..229b696 100644 --- a/streamlit_app/outcomes.py +++ b/streamlit_app/outcomes.py @@ -37,20 +37,30 @@ def classify(name: str, res: dict) -> Outcome: status = res.get("status") if status == "ok": failed = res.get("failedRows") or 0 - line = (f"{file}: {'overwrote · ' if res.get('overwritten') else ''}{res.get('insertedRows', 0)} of " - f"{res.get('totalRows', 0)} rows imported" + (f" · {failed} failed" if failed else "")) + line = ( + f"{file}: {'overwrote · ' if res.get('overwritten') else ''}{res.get('insertedRows', 0)} of " + f"{res.get('totalRows', 0)} rows imported" + (f" · {failed} failed" if failed else "") + ) return Outcome("done", "warning" if failed else "success", line) if status == "duplicate_file": if res.get("reason") == "name": - return Outcome("duplicate", "warning", f"{file}: a file with this name is already imported with different contents.") + return Outcome( + "duplicate", "warning", f"{file}: a file with this name is already imported with different contents." + ) existing = res.get("existingFileName") as_ = f" as {m.literal(existing)}" if existing else " earlier" return Outcome("duplicate", "warning", f"{file}: already imported{as_}. Nothing was changed.") if status == "invalid_structure": said = res.get("message") - text = m.literal(said) if said else STRUCTURE_REASONS.get(str(res.get("reason")), "The file has no usable structure.") + text = ( + m.literal(said) + if said + else STRUCTURE_REASONS.get(str(res.get("reason")), "The file has no usable structure.") + ) return Outcome("error", "error", f"{file}: {text}") - return Outcome("error", "error", f"{file}: {m.literal(res['message']) if res.get('message') else 'The import failed.'}") + return Outcome( + "error", "error", f"{file}: {m.literal(res['message']) if res.get('message') else 'The import failed.'}" + ) def classify_error(name: str, err: Exception) -> Outcome: @@ -74,15 +84,20 @@ def result_notes(res: dict) -> list[str]: prev = f" (version {earlier['version']})" if earlier.get("version") else "" if check.get("compatible"): added = check.get("added") or [] - notes.append("Columns match the previous version" + prev + ( - f", with {len(added)} new: {', '.join(m.literal(c) for c in added)}." if added else ".")) + notes.append( + "Columns match the previous version" + + prev + + (f", with {len(added)} new: {', '.join(m.literal(c) for c in added)}." if added else ".") + ) else: parts = [] if check.get("removed"): parts.append("removed " + ", ".join(m.literal(c) for c in check["removed"])) if check.get("changed"): - parts.append("retyped " + ", ".join( - f"{m.literal(c['column'])} ({c['was']} → {c['now']})" for c in check["changed"])) + parts.append( + "retyped " + + ", ".join(f"{m.literal(c['column'])} ({c['was']} → {c['now']})" for c in check["changed"]) + ) if check.get("added"): parts.append("new " + ", ".join(m.literal(c) for c in check["added"])) notes.append("Columns differ from the previous version" + prev + ": " + "; ".join(parts) + ".") @@ -91,7 +106,9 @@ def result_notes(res: dict) -> list[str]: notes.append(f"{dupes} row{'' if dupes == 1 else 's'} already appear in an earlier version of this dataset.") skipped = res.get("duplicateRowsSkipped") if skipped: - notes.append(f"{skipped} duplicate row{'' if skipped == 1 else 's'} in the file {'was' if skipped == 1 else 'were'} skipped.") + notes.append( + f"{skipped} duplicate row{'' if skipped == 1 else 's'} in the file {'was' if skipped == 1 else 'were'} skipped." + ) return notes diff --git a/streamlit_app/review_model.py b/streamlit_app/review_model.py index 21782d4..22cc105 100644 --- a/streamlit_app/review_model.py +++ b/streamlit_app/review_model.py @@ -47,6 +47,7 @@ def literal(text: object) -> str: # ── which uploads ─────────────────────────────────────────────────────────────────────────── + def needs_attention(status: str) -> bool: return status in NEEDS_ATTENTION @@ -73,6 +74,7 @@ def page_count(total: int) -> int: # ── one page of rows ──────────────────────────────────────────────────────────────────────── + def row_status(row: dict) -> str: return "Excluded" if row["decision"] == "exclude" else "Invalid" if row["errors"] else "Included" @@ -111,12 +113,15 @@ def tint(rows: list[dict], frame: pd.DataFrame, columns: list[str]) -> pd.DataFr def summary(data: dict) -> str: """The line under the file name (the React screen's wording).""" rows = f"{data['total']} row{'' if data['total'] == 1 else 's'}" - return (f"{rows} · {data['excludedRows']} excluded · {data['editedRows']} edited. Changes are saved with " - "the upload for review. They don't change the imported table.") + return ( + f"{rows} · {data['excludedRows']} excluded · {data['editedRows']} edited. Changes are saved with " + "the upload for review. They don't change the imported table." + ) # ── one row ───────────────────────────────────────────────────────────────────────────────── + def error_lines(row: dict) -> list[str]: """Every reason the row is invalid. One with no column of the file is the database's own (#190, column "(database)"), or a cell beyond the header: shown the same way, naming where it came from.""" @@ -130,8 +135,11 @@ def decision_line(row: dict) -> str | None: def edit_lines(row: dict, columns: list[str]) -> list[str]: - return [f"{literal(columns[i])}: original {literal(row['original'][i] or '(empty)')}, " - f"now {literal(row['current'][i] or '(empty)')}" for i in row["editedColumns"]] + return [ + f"{literal(columns[i])}: original {literal(row['original'][i] or '(empty)')}, " + f"now {literal(row['current'][i] or '(empty)')}" + for i in row["editedColumns"] + ] def when(at: str) -> str: @@ -149,6 +157,8 @@ def history_line(entry: dict) -> str: if entry["kind"] == "decision": what = f"**{'Excluded' if entry['decision'] == 'exclude' else 'Included'}**" else: - what = (f"{literal(entry['column'])}: {literal(entry['oldValue'] or '(empty)')} → " - f"{literal(entry['newValue'] or '(empty)')}") + what = ( + f"{literal(entry['column'])}: {literal(entry['oldValue'] or '(empty)')} → " + f"{literal(entry['newValue'] or '(empty)')}" + ) return f"{when(entry['at'])} · {literal(entry.get('actor') or 'unknown')} · {what} \n{literal(entry['reason'])}" diff --git a/streamlit_app/upload_model.py b/streamlit_app/upload_model.py index 4ed0964..f7ad93a 100644 --- a/streamlit_app/upload_model.py +++ b/streamlit_app/upload_model.py @@ -29,8 +29,14 @@ # api/services/csv_parse.py ALLOWED_TYPES (a test fails if they drift), with the React app's labels. ALLOWED_TYPES = ("int8", "numeric", "date", "timestamptz", "boolean", "text") -TYPE_LABELS = {"int8": "Whole number", "numeric": "Number", "date": "Date", "timestamptz": "Timestamp", - "boolean": "True/False", "text": "Text"} +TYPE_LABELS = { + "int8": "Whole number", + "numeric": "Number", + "date": "Date", + "timestamptz": "Timestamp", + "boolean": "True/False", + "text": "Text", +} DYNAMIC, TE = "dynamic", "te" MODE_LABELS = {DYNAMIC: "New table from this file", TE: "Test and Evaluation table"} @@ -77,12 +83,17 @@ def prepare(name: str, raw: bytes, limit: int | None = None) -> Prepared: raise Refused(name, "is empty.") size = len(raw) - (3 if raw.startswith(b"\xef\xbb\xbf") else 0) # what the API counts: the text, as UTF-8 if size > limit: - raise Refused(name, f"is {format_bytes(size)}, over the {format_bytes(limit)} limit. Split it into smaller files.") + raise Refused( + name, f"is {format_bytes(size)}, over the {format_bytes(limit)} limit. Split it into smaller files." + ) try: text = raw.decode("utf-8-sig") except UnicodeDecodeError as e: - raise Refused(name, f"is not UTF-8 text: the byte at position {e.start} cannot be read. Save the file as " - "UTF-8 and choose it again.") from None + raise Refused( + name, + f"is not UTF-8 text: the byte at position {e.start} cannot be read. Save the file as " + "UTF-8 and choose it again.", + ) from None return Prepared(name, raw, text, hashlib.sha256(raw).hexdigest()[:12]) @@ -94,7 +105,7 @@ def preview_text(prepared: Prepared, limit: int | None = None) -> tuple[str, boo return prepared.text, False cut = body[:limit] end = cut.rfind(b"\n") - cut = cut[:end + 1] if end > 0 else cut + cut = cut[: end + 1] if end > 0 else cut return cut.decode("utf-8", errors="ignore"), True @@ -120,12 +131,24 @@ def ready(mode: str, confirmed: bool, target: str | None) -> bool: return bool(target) if mode == TE else bool(confirmed) -def build_payload(prepared: Prepared, mode: str, *, types: list[str] | None = None, renames: list[str] | None = None, - headers: list[str] | None = None, confirmed: bool = False, target: str | None = None) -> dict: +def build_payload( + prepared: Prepared, + mode: str, + *, + types: list[str] | None = None, + renames: list[str] | None = None, + headers: list[str] | None = None, + confirmed: bool = False, + target: str | None = None, +) -> dict: """The body of POST /api/csv/upload. A T&E load sends no types, no renames and no confirmation: the API refuses a header mapping or `typesConfirmed` there (422), because a T&E table has fixed columns.""" - body: dict[str, object] = {"fileName": prepared.name, "content": prepared.text, - "contentBase64": base64.b64encode(prepared.raw).decode("ascii"), "mode": mode} + body: dict[str, object] = { + "fileName": prepared.name, + "content": prepared.text, + "contentBase64": base64.b64encode(prepared.raw).decode("ascii"), + "mode": mode, + } if mode == TE: body["targetTable"] = target return body @@ -159,8 +182,10 @@ def chosen_once(files: list[tuple[str, bytes]]) -> tuple[list[tuple[str, bytes]] def sample_frame(preview: dict) -> pd.DataFrame: """The server's sample rows as a table to show. `st.table` reads a cell, and a column heading, as Markdown, and this is a stranger's file: every text goes in a code span.""" - frame = pd.DataFrame([[m.literal(c) if c else "" for c in row] for row in preview["sampleRows"]], - columns=[m.literal(c) for c in preview["columns"]]) + frame = pd.DataFrame( + [[m.literal(c) if c else "" for c in row] for row in preview["sampleRows"]], + columns=[m.literal(c) for c in preview["columns"]], + ) frame.index = range(1, len(frame) + 1) return frame diff --git a/streamlit_app/views/files.py b/streamlit_app/views/files.py index 1a89155..6488f0f 100644 --- a/streamlit_app/views/files.py +++ b/streamlit_app/views/files.py @@ -38,7 +38,9 @@ def _read(method: str, path: str, **kwargs): def render() -> None: st.title("Imported files") - st.caption("Every file imported into this tenant, whoever uploaded it. The Review page shows the stored rows of one.") + st.caption( + "Every file imported into this tenant, whoever uploaded it. The Review page shows the stored rows of one." + ) try: files = _files(auth.current()["token"]) except api_client.Unauthorized: @@ -56,14 +58,19 @@ def render() -> None: pages = f.page_count(len(files)) page = st.number_input(f"Page (of {pages})", 1, pages, 1, key=PAGE) start = (page - 1) * f.PAGE_SIZE - shown = files[start:start + f.PAGE_SIZE] + shown = files[start : start + f.PAGE_SIZE] st.caption(f"Files {start + 1} to {start + len(shown)} of {len(files)}, newest first.") st.table(f.files_frame(shown, start + 1)) st.divider() labels = {x["id"]: f.file_label(x) for x in shown} - chosen = st.selectbox("Look inside a file", list(labels), index=None, format_func=labels.__getitem__, - placeholder="Choose a file to preview its table") + chosen = st.selectbox( + "Look inside a file", + list(labels), + index=None, + format_func=labels.__getitem__, + placeholder="Choose a file to preview its table", + ) if chosen is not None: _inside(next(x for x in shown if x["id"] == chosen)) @@ -91,11 +98,15 @@ def _failed(file: dict) -> None: st.caption("No failure reasons were stored for this upload.") return st.markdown("**Rows that failed**") - st.table(h.errors_frame(errors[:h.ERROR_ROWS_SHOWN])) + st.table(h.errors_frame(errors[: h.ERROR_ROWS_SHOWN])) note = h.errors_note(min(len(errors), h.ERROR_ROWS_SHOWN), detail.get("failedRows")) if note: st.caption(note) rows = exports.error_rows(file["file_name"], errors) - st.download_button("Error report (CSV)", exports.to_csv(exports.ERROR_HEADERS, rows), - exports.report_name("errors", "csv", file["file_name"]), exports.CSV_TYPE, - key=f"files_errors_{file['id']}") + st.download_button( + "Error report (CSV)", + exports.to_csv(exports.ERROR_HEADERS, rows), + exports.report_name("errors", "csv", file["file_name"]), + exports.CSV_TYPE, + key=f"files_errors_{file['id']}", + ) diff --git a/streamlit_app/views/history.py b/streamlit_app/views/history.py index c943a27..a6c85fb 100644 --- a/streamlit_app/views/history.py +++ b/streamlit_app/views/history.py @@ -65,8 +65,11 @@ def render() -> None: st.title("Import history") st.caption("Every upload in this tenant, from the server, whoever made it and from whichever browser.") views = VIEWS if auth.can("read_audit") else VIEWS[:1] - view = st.radio("Show", views, horizontal=True, label_visibility="collapsed", key="history_view") \ - if len(views) > 1 else views[0] + view = ( + st.radio("Show", views, horizontal=True, label_visibility="collapsed", key="history_view") + if len(views) > 1 + else views[0] + ) if view == VIEWS[0]: _imports(auth.current()["token"]) else: @@ -75,6 +78,7 @@ def render() -> None: # ── the imports ───────────────────────────────────────────────────────────────────────────── + def _move(key: str, step: int) -> None: st.session_state[key] = max(0, st.session_state.get(key, 0) + step) @@ -89,8 +93,13 @@ def _imports(token: str) -> None: date_to = right.date_input("To", value=None) applied = st.form_submit_button("Apply") if applied: - st.session_state[FILTERS] = {"file": file, "status": status, "uploader": uploader, - "date_from": date_from, "date_to": date_to} + st.session_state[FILTERS] = { + "file": file, + "status": status, + "uploader": uploader, + "date_from": date_from, + "date_to": date_to, + } st.session_state[PAGE] = 0 filters = st.session_state.get(FILTERS, {}) page = st.session_state.get(PAGE, 0) @@ -116,8 +125,13 @@ def _imports(token: str) -> None: st.divider() labels = {u["id"]: h.import_label(u) for u in uploads} - chosen = st.selectbox("Details of an import", list(labels), index=None, format_func=labels.__getitem__, - placeholder="Choose an import to see why rows failed") + chosen = st.selectbox( + "Details of an import", + list(labels), + index=None, + format_func=labels.__getitem__, + placeholder="Choose an import to see why rows failed", + ) if chosen is not None: _detail(next(u for u in uploads if u["id"] == chosen)) @@ -127,12 +141,19 @@ def _history_report(filters: dict) -> None: key = repr(sorted((k, str(v)) for k, v in filters.items())) prepared = st.session_state.get(PREPARED) if st.button("Prepare a report of all matching imports"): - rows, capped = h.collect(lambda limit, offset: _read( - "GET", "/api/csv/uploads", params=h.uploads_params(**filters, limit=limit, offset=offset))) + rows, capped = h.collect( + lambda limit, offset: _read( + "GET", "/api/csv/uploads", params=h.uploads_params(**filters, limit=limit, offset=offset) + ) + ) report = exports.history_rows(rows) - prepared = {"key": key, "count": len(rows), "capped": capped, - "csv": exports.to_csv(exports.HISTORY_HEADERS, report), - "xlsx": exports.to_xlsx("History", exports.HISTORY_HEADERS, report)} + prepared = { + "key": key, + "count": len(rows), + "capped": capped, + "csv": exports.to_csv(exports.HISTORY_HEADERS, report), + "xlsx": exports.to_xlsx("History", exports.HISTORY_HEADERS, report), + } st.session_state[PREPARED] = prepared if prepared and prepared["key"] == key: n = prepared["count"] @@ -140,7 +161,9 @@ def _history_report(filters: dict) -> None: st.caption(f"Report of {n} import{'' if n == 1 else 's'}" + cut_short) one, two, _ = st.columns([1, 1, 4]) one.download_button("Download CSV", prepared["csv"], exports.report_name("history", "csv"), exports.CSV_TYPE) - two.download_button("Download XLSX", prepared["xlsx"], exports.report_name("history", "xlsx"), exports.XLSX_TYPE) + two.download_button( + "Download XLSX", prepared["xlsx"], exports.report_name("history", "xlsx"), exports.XLSX_TYPE + ) def _detail(upload: dict) -> None: @@ -154,7 +177,7 @@ def _detail(upload: dict) -> None: errors = detail.get("rowErrors") or [] if errors: st.markdown("**Rows that failed**") - st.table(h.errors_frame(errors[:h.ERROR_ROWS_SHOWN])) + st.table(h.errors_frame(errors[: h.ERROR_ROWS_SHOWN])) note = h.errors_note(min(len(errors), h.ERROR_ROWS_SHOWN), detail.get("failedRows")) if note: st.caption(note) @@ -163,12 +186,20 @@ def _detail(upload: dict) -> None: report = exports.error_rows(detail["fileName"], errors, reason if not errors else None) if report: one, two, _ = st.columns([1, 1, 4]) - one.download_button("Error report (CSV)", exports.to_csv(exports.ERROR_HEADERS, report), - exports.report_name("errors", "csv", detail["fileName"]), exports.CSV_TYPE, - key=f"history_errors_csv_{uid}") - two.download_button("Error report (XLSX)", exports.to_xlsx("Errors", exports.ERROR_HEADERS, report), - exports.report_name("errors", "xlsx", detail["fileName"]), exports.XLSX_TYPE, - key=f"history_errors_xlsx_{uid}") + one.download_button( + "Error report (CSV)", + exports.to_csv(exports.ERROR_HEADERS, report), + exports.report_name("errors", "csv", detail["fileName"]), + exports.CSV_TYPE, + key=f"history_errors_csv_{uid}", + ) + two.download_button( + "Error report (XLSX)", + exports.to_xlsx("Errors", exports.ERROR_HEADERS, report), + exports.report_name("errors", "xlsx", detail["fileName"]), + exports.XLSX_TYPE, + key=f"history_errors_xlsx_{uid}", + ) with st.expander("What the server did, step by step"): logs = detail.get("logs") or [] if logs: @@ -180,6 +211,7 @@ def _detail(upload: dict) -> None: # ── the server's audit events ─────────────────────────────────────────────────────────────── + def _events() -> None: with st.form("history_events"): left, right = st.columns(2) @@ -190,8 +222,13 @@ def _events() -> None: date_to = right.date_input("To", value=None) applied = st.form_submit_button("Apply") if applied: - st.session_state[EVENT_FILTERS] = {"actor": actor, "action": action, "file": file, "date_from": date_from, - "date_to": date_to} + st.session_state[EVENT_FILTERS] = { + "actor": actor, + "action": action, + "file": file, + "date_from": date_from, + "date_to": date_to, + } st.session_state[EVENT_PAGE] = 0 filters = st.session_state.get(EVENT_FILTERS, {}) page = st.session_state.get(EVENT_PAGE, 0) @@ -204,8 +241,9 @@ def _events() -> None: st.info("No events match the filters.") before, after, _ = st.columns([1, 1, 4]) before.button("Previous events", on_click=_move, args=(EVENT_PAGE, -1), disabled=page == 0) - after.button("Next events", on_click=_move, args=(EVENT_PAGE, 1), - disabled=(page + 1) * data["limit"] >= data["total"]) + after.button( + "Next events", on_click=_move, args=(EVENT_PAGE, 1), disabled=(page + 1) * data["limit"] >= data["total"] + ) key = repr(sorted((k, str(v)) for k, v in filters.items())) prepared = st.session_state.get(EVENT_PREPARED) @@ -214,8 +252,9 @@ def _events() -> None: prepared = {"key": key, "csv": body} st.session_state[EVENT_PREPARED] = prepared if prepared and prepared["key"] == key: - st.download_button("Download CSV", prepared["csv"], "audit-events.csv", exports.CSV_TYPE, - key="history_events_csv") + st.download_button( + "Download CSV", prepared["csv"], "audit-events.csv", exports.CSV_TYPE, key="history_events_csv" + ) st.caption("The server has already neutralised spreadsheet formulas in this file.") diff --git a/streamlit_app/views/review.py b/streamlit_app/views/review.py index 64cf3c8..e7a4bdb 100644 --- a/streamlit_app/views/review.py +++ b/streamlit_app/views/review.py @@ -86,8 +86,9 @@ def render() -> None: pages = m.page_count(upload["total_rows"] or 0) page_no = st.number_input(f"Page (of {pages})", 1, pages, 1, key=f"review_page_{uid}") - data = _read("GET", f"/api/csv/uploads/{uid}/rows", - params={"offset": (page_no - 1) * m.PAGE_SIZE, "limit": m.PAGE_SIZE}) + data = _read( + "GET", f"/api/csv/uploads/{uid}/rows", params={"offset": (page_no - 1) * m.PAGE_SIZE, "limit": m.PAGE_SIZE} + ) columns, types, rows = data["columns"], data["types"], data["rows"] can_review = auth.can("review_rows") @@ -105,8 +106,12 @@ def render() -> None: picked = st.dataframe( frame.style.apply(lambda _: m.tint(rows, frame, columns), axis=None), column_config={c: st.column_config.Column(f"{c} ({t})") for c, t in zip(columns, types)}, - on_select="rerun", selection_mode="single-row", key=f"review_grid_{uid}_{page_no}", - width="stretch", height=min(560, 38 + 35 * len(rows))) + on_select="rerun", + selection_mode="single-row", + key=f"review_grid_{uid}_{page_no}", + width="stretch", + height=min(560, 38 + 35 * len(rows)), + ) # A click on the table moves the Row number box to that row. Anything else (typing a number) leaves the # table alone. A number left from another page needs no handling: the box's range changes with the page, @@ -118,9 +123,16 @@ def render() -> None: if clicked is not None: st.session_state[row_key] = clicked with chooser: - number = st.number_input("Row number", first, last, value=None, step=1, key=row_key, - placeholder=f"{first} to {last}", - help="Select a row in the table, or type its number.") + number = st.number_input( + "Row number", + first, + last, + value=None, + step=1, + key=row_key, + placeholder=f"{first} to {last}", + help="Select a row in the table, or type its number.", + ) if number is None: st.caption("Select a row in the table, or type its number, to see its problems, original values and history.") return @@ -129,6 +141,7 @@ def render() -> None: # ── one row ───────────────────────────────────────────────────────────────────────────────── + def _detail(uid: str, row: dict, columns: list[str], types: list[str], can_review: bool) -> None: st.subheader(f"Row {row['rowNumber']}") for line in m.error_lines(row): @@ -169,10 +182,13 @@ def _history(uid: str, row_number: int) -> None: def _edit(uid: str, row: dict, columns: list[str], types: list[str], ver: int) -> None: n = row["rowNumber"] # Outside the form, so choosing a column shows that column's original value straight away. - i = st.selectbox("Column", range(len(columns)), format_func=lambda k: f"{columns[k]} ({types[k]})", - key=f"review_col_{uid}") - st.caption(f"Original value: {m.literal(row['original'][i] or '(empty)')} · " - f"Current value: {m.literal(row['current'][i] or '(empty)')}") + i = st.selectbox( + "Column", range(len(columns)), format_func=lambda k: f"{columns[k]} ({types[k]})", key=f"review_col_{uid}" + ) + st.caption( + f"Original value: {m.literal(row['original'][i] or '(empty)')} · " + f"Current value: {m.literal(row['current'][i] or '(empty)')}" + ) with st.form(f"review_edit_{uid}_{ver}"): value = st.text_input("New value", value=row["current"][i], key=f"review_value_{uid}_{n}_{i}_{ver}") reason = st.text_input("Reason for the change (required)", key=f"review_why_{uid}_{n}_{i}_{ver}") @@ -183,8 +199,14 @@ def _edit(uid: str, row: dict, columns: list[str], types: list[str], ver: int) - st.error("A reason is required") return # By position, not name: a column may be called "2024", which the API would read as a position, or hold a "/". - _save(uid, ver, "PUT", f"/api/csv/uploads/{uid}/rows/{n}/cells/{i}", {"value": value, "reason": reason}, - f"Saved: row {n}, {m.literal(columns[i])}.") + _save( + uid, + ver, + "PUT", + f"/api/csv/uploads/{uid}/rows/{n}/cells/{i}", + {"value": value, "reason": reason}, + f"Saved: row {n}, {m.literal(columns[i])}.", + ) def _decide(uid: str, row: dict, flip: str, ver: int) -> None: @@ -197,8 +219,14 @@ def _decide(uid: str, row: dict, flip: str, ver: int) -> None: if not reason.strip(): st.error("A reason is required") return - _save(uid, ver, "PUT", f"/api/csv/uploads/{uid}/rows/{n}/decision", {"decision": flip, "reason": reason}, - f"Saved: row {n} {'excluded' if flip == 'exclude' else 'included'}.") + _save( + uid, + ver, + "PUT", + f"/api/csv/uploads/{uid}/rows/{n}/decision", + {"decision": flip, "reason": reason}, + f"Saved: row {n} {'excluded' if flip == 'exclude' else 'included'}.", + ) def _save(uid: str, ver: int, method: str, path: str, body: dict, done: str) -> None: diff --git a/streamlit_app/views/upload.py b/streamlit_app/views/upload.py index 6285ab0..9ec7c57 100644 --- a/streamlit_app/views/upload.py +++ b/streamlit_app/views/upload.py @@ -48,8 +48,10 @@ def render() -> None: if not auth.can("upload"): st.info(f"The role {auth.current()['role']} can't upload files.") return - st.write("Choose CSV files, check the columns and types, then import. Each file becomes its own table. " - f"The most a file may hold is {u.format_bytes(u.max_bytes())}.") + st.write( + "Choose CSV files, check the columns and types, then import. Each file becomes its own table. " + f"The most a file may hold is {u.format_bytes(u.max_bytes())}." + ) generation = st.session_state.get(GENERATION, 0) chosen = st.file_uploader("CSV files", type=["csv"], accept_multiple_files=True, key=f"upload_files_{generation}") show([(f.name, f.getvalue()) for f in chosen]) @@ -58,6 +60,7 @@ def render() -> None: # ── the files chosen ──────────────────────────────────────────────────────────────────────── + def show(files: list[tuple[str, bytes]]) -> None: """One section per chosen file, and what to send. (Separate from the chooser so it can be tested with bytes.)""" ready = [] @@ -114,33 +117,47 @@ def _one(prepared: u.Prepared) -> dict | None: return None if pv.get("status") != "ok": said = pv.get("message") - st.error(m.literal(said) if said else outcomes.STRUCTURE_REASONS.get(str(pv.get("reason")), "No usable structure.")) + st.error( + m.literal(said) + if said + else outcomes.STRUCTURE_REASONS.get(str(pv.get("reason")), "No usable structure.") + ) return None rows = u.approx_rows(pv["totalRowsApprox"], pv["previewBytes"], len(prepared.raw), pv["truncated"]) st.caption(f"{len(pv['headers'])} columns · {'about ' if pv['truncated'] else ''}{rows} data rows") st.table(u.sample_frame(pv)) tables = _te_tables() - mode = st.radio("Load as", [u.DYNAMIC, u.TE], format_func=u.MODE_LABELS.__getitem__, horizontal=True, - index=[u.DYNAMIC, u.TE].index(u.default_mode(pv, tables)), key=f"mode_{key}") + mode = st.radio( + "Load as", + [u.DYNAMIC, u.TE], + format_func=u.MODE_LABELS.__getitem__, + horizontal=True, + index=[u.DYNAMIC, u.TE].index(u.default_mode(pv, tables)), + key=f"mode_{key}", + ) types, renames, confirmed, target = None, None, False, None if mode == u.TE: if not tables: st.warning("There are no Test and Evaluation tables to load into.") else: match = pv.get("teTableMatch") - target = st.selectbox("Into table", tables, index=tables.index(match) if match in tables else 0, - key=f"table_{key}") - st.caption("The columns of a Test and Evaluation table are fixed, so the file's headers are matched to them " - "as they are: nothing here can be renamed or retyped.") + target = st.selectbox( + "Into table", tables, index=tables.index(match) if match in tables else 0, key=f"table_{key}" + ) + st.caption( + "The columns of a Test and Evaluation table are fixed, so the file's headers are matched to them " + "as they are: nothing here can be renamed or retyped." + ) else: types, renames = _mapping(key, pv) confirmed = st.checkbox(u.CONFIRM, key=f"confirm_{key}") ok = u.ready(mode, confirmed, target) def build() -> dict: # at the click only: encoding a big file for every re-run would be slow - return u.build_payload(prepared, mode, types=types, renames=renames, headers=pv["headers"], - confirmed=confirmed, target=target) + return u.build_payload( + prepared, mode, types=types, renames=renames, headers=pv["headers"], confirmed=confirmed, target=target + ) st.caption(outcomes.NO_CANCEL + " (once you click Upload).") item = {"name": prepared.name, "build": build, "ready": ok} @@ -160,16 +177,31 @@ def _mapping(key: str, pv: dict) -> tuple[list[str], list[str]]: name.caption(f"becomes {m.literal(column)}") # A label is Markdown even when hidden, and also the box's aria-label as written: see column_label. label = u.column_label(header, i) - renames.append(rename.text_input(f"Rename {label}", key=f"rename_{key}_{i}", - label_visibility="collapsed", placeholder="keep", max_chars=128)) - types.append(kind.selectbox(f"Type of {label}", u.ALLOWED_TYPES, index=u.ALLOWED_TYPES.index(inferred), - format_func=u.TYPE_LABELS.__getitem__, key=f"type_{key}_{i}", - label_visibility="collapsed")) + renames.append( + rename.text_input( + f"Rename {label}", + key=f"rename_{key}_{i}", + label_visibility="collapsed", + placeholder="keep", + max_chars=128, + ) + ) + types.append( + kind.selectbox( + f"Type of {label}", + u.ALLOWED_TYPES, + index=u.ALLOWED_TYPES.index(inferred), + format_func=u.TYPE_LABELS.__getitem__, + key=f"type_{key}_{i}", + label_visibility="collapsed", + ) + ) return types, renames # ── sending ───────────────────────────────────────────────────────────────────────────────── + def _send(items: list[dict]) -> None: """Send each file in turn. The server cannot be asked to stop, so say so, and say what happened to every file.""" bar = st.progress(0.0) if len(items) > 1 else None @@ -183,9 +215,16 @@ def _send(items: list[dict]) -> None: outcome = outcomes.classify(item["name"], res) except api_client.ApiError as e: outcome = outcomes.classify_error(item["name"], e) - results.insert(0, {"name": item["name"], "outcome": outcome, "res": res, - "mapping": payload.get("headerMapping"), - "at": datetime.now(timezone.utc).strftime("%H:%M UTC")}) + results.insert( + 0, + { + "name": item["name"], + "outcome": outcome, + "res": res, + "mapping": payload.get("headerMapping"), + "at": datetime.now(timezone.utc).strftime("%H:%M UTC"), + }, + ) if bar: bar.progress(n / len(items)) st.cache_data.clear() # the history, the review picker and the files list now have something new @@ -196,6 +235,7 @@ def _send(items: list[dict]) -> None: # ── what happened ─────────────────────────────────────────────────────────────────────────── + def report() -> None: """This session's outcomes, newest first. The server's record, for everyone, is Import history.""" results = st.session_state.get(RESULTS) or [] @@ -204,8 +244,10 @@ def report() -> None: st.divider() st.subheader("Upload report") done = sum(r["outcome"].kind == "done" for r in results) - st.caption(f"{len(results)} upload{'' if len(results) == 1 else 's'} in this session, {done} imported. " - "Import history keeps the server's record.") + st.caption( + f"{len(results)} upload{'' if len(results) == 1 else 's'} in this session, {done} imported. " + "Import history keeps the server's record." + ) for i, r in enumerate(results): _result(i, r) if st.button("Clear this report"): @@ -229,13 +271,36 @@ def _result(i: int, r: dict) -> None: rows = exports.error_rows(r["name"], errors, None, r["mapping"]) if rows: one, two, three, _ = st.columns([1, 1, 1, 3]) - one.download_button("Error report (CSV)", exports.to_csv(exports.ERROR_HEADERS, rows), - exports.report_name("errors", "csv", r["name"]), exports.CSV_TYPE, key=f"up_csv_{i}") - two.download_button("Error report (XLSX)", exports.to_xlsx("Errors", exports.ERROR_HEADERS, rows), - exports.report_name("errors", "xlsx", r["name"]), exports.XLSX_TYPE, key=f"up_xlsx_{i}") + one.download_button( + "Error report (CSV)", + exports.to_csv(exports.ERROR_HEADERS, rows), + exports.report_name("errors", "csv", r["name"]), + exports.CSV_TYPE, + key=f"up_csv_{i}", + ) + two.download_button( + "Error report (XLSX)", + exports.to_xlsx("Errors", exports.ERROR_HEADERS, rows), + exports.report_name("errors", "xlsx", r["name"]), + exports.XLSX_TYPE, + key=f"up_xlsx_{i}", + ) if res.get("logs"): - body = json.dumps({"file": r["name"], "status": res.get("status"), "tableName": res.get("tableName"), - "generatedAt": datetime.now(timezone.utc).isoformat(), "logs": res.get("logs"), - "rowErrors": errors}, indent=2) - three.download_button("Processing logs (JSON)", body, exports.report_name("logs", "json", r["name"]), - "application/json", key=f"up_log_{i}") + body = json.dumps( + { + "file": r["name"], + "status": res.get("status"), + "tableName": res.get("tableName"), + "generatedAt": datetime.now(timezone.utc).isoformat(), + "logs": res.get("logs"), + "rowErrors": errors, + }, + indent=2, + ) + three.download_button( + "Processing logs (JSON)", + body, + exports.report_name("logs", "json", r["name"]), + "application/json", + key=f"up_log_{i}", + ) diff --git a/tests/accessibility/axe_baseline.py b/tests/accessibility/axe_baseline.py index 1bfadbc..eeb91ed 100644 --- a/tests/accessibility/axe_baseline.py +++ b/tests/accessibility/axe_baseline.py @@ -15,6 +15,7 @@ Pure functions, no browser and no Playwright import: tests/unit/test_a11y_baseline.py covers them in the free tier. """ + from __future__ import annotations import json @@ -31,10 +32,10 @@ @dataclass class Outcome: - new: list[str] = field(default_factory=list) # regressions: fail - fixed: list[str] = field(default_factory=list) # stale baseline entries: fail - shrunk: list[str] = field(default_factory=list) # fewer elements than recorded: notice - known: list[str] = field(default_factory=list) # as recorded: notice + new: list[str] = field(default_factory=list) # regressions: fail + fixed: list[str] = field(default_factory=list) # stale baseline entries: fail + shrunk: list[str] = field(default_factory=list) # fewer elements than recorded: notice + known: list[str] = field(default_factory=list) # as recorded: notice @property def ok(self) -> bool: @@ -60,8 +61,7 @@ def load_baseline(path: Path = BASELINE_PATH) -> Baseline: def describe(violation: dict, limit: int = 3) -> str: """One violation as a few readable lines: rule, impact, count, and where.""" nodes = violation["nodes"] - lines = [f"{violation['id']} ({violation.get('impact') or 'n/a'}) on {len(nodes)} element(s): " - f"{violation['help']}"] + lines = [f"{violation['id']} ({violation.get('impact') or 'n/a'}) on {len(nodes)} element(s): {violation['help']}"] for node in nodes[:limit]: target = " ".join(str(t) for t in node["target"]) html = " ".join(node.get("html", "").split()) @@ -91,6 +91,8 @@ def compare(scenario: str, violations: list[dict], baseline: Baseline) -> Outcom for (scen, rule), entry in sorted(baseline.items()): if scen == scenario and rule not in found: - out.fixed.append(f"{rule} no longer fails here: delete its entry from known_violations.json " - f"(it recorded: {entry['note']})") + out.fixed.append( + f"{rule} no longer fails here: delete its entry from known_violations.json " + f"(it recorded: {entry['note']})" + ) return out diff --git a/tests/accessibility/conftest.py b/tests/accessibility/conftest.py index e4e9f27..55909ec 100644 --- a/tests/accessibility/conftest.py +++ b/tests/accessibility/conftest.py @@ -16,21 +16,22 @@ A11Y_CHROMIUM_PATH use this Chromium instead of the one ``playwright install`` fetched A11Y_REPORT_DIR write one JSON file per scenario with every violation axe found """ + from __future__ import annotations import json import os -import sys -import threading -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import shutil import signal import socket import subprocess +import sys import tempfile +import threading import time import urllib.error import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path import pytest @@ -39,7 +40,7 @@ ROOT = Path(__file__).resolve().parents[2] FRONTEND = ROOT / "csv-table-hub-main" -STARTUP_TIMEOUT_S = 180 # first start also pre-bundles dependencies +STARTUP_TIMEOUT_S = 180 # first start also pre-bundles dependencies def _fail(message: str): @@ -56,8 +57,10 @@ def _wait_until_serving(url: str, proc: subprocess.Popen | None, log: Path) -> N deadline = time.monotonic() + STARTUP_TIMEOUT_S while time.monotonic() < deadline: if proc is not None and proc.poll() is not None: - _fail(f"The frontend dev server exited with code {proc.returncode} before serving.\n" - f"{log.read_text(errors='replace')[-2000:]}") + _fail( + f"The frontend dev server exited with code {proc.returncode} before serving.\n" + f"{log.read_text(errors='replace')[-2000:]}" + ) try: with urllib.request.urlopen(f"{url}/auth", timeout=5) as res: if res.status == 200: @@ -65,8 +68,10 @@ def _wait_until_serving(url: str, proc: subprocess.Popen | None, log: Path) -> N except (urllib.error.URLError, OSError): pass time.sleep(1) - _fail(f"The frontend did not serve {url}/auth within {STARTUP_TIMEOUT_S}s.\n" - f"{log.read_text(errors='replace')[-2000:] if log.exists() else ''}") + _fail( + f"The frontend did not serve {url}/auth within {STARTUP_TIMEOUT_S}s.\n" + f"{log.read_text(errors='replace')[-2000:] if log.exists() else ''}" + ) @pytest.fixture(scope="session") @@ -90,7 +95,9 @@ def app_url(): with log.open("wb") as out: proc = subprocess.Popen( [npm, "run", "dev", "--", "--host", "127.0.0.1", "--port", str(port), "--strictPort"], - cwd=FRONTEND, stdout=out, stderr=subprocess.STDOUT, + cwd=FRONTEND, + stdout=out, + stderr=subprocess.STDOUT, # An empty API base makes the app call /api on its own origin, where the # stub answers. A new session lets teardown stop npm, vite and their children. env={**os.environ, "VITE_API_BASE": "", "BROWSER": "none"}, @@ -119,8 +126,10 @@ def chromium(): try: from playwright.sync_api import sync_playwright except ImportError: - _fail("Playwright is not installed. Run: pip install -r requirements-a11y.txt " - "&& python -m playwright install chromium") + _fail( + "Playwright is not installed. Run: pip install -r requirements-a11y.txt " + "&& python -m playwright install chromium" + ) pw = sync_playwright().start() try: launch = {} @@ -165,10 +174,17 @@ def open_page(a11y_browser, app_url, request): contexts = [] unstubbed: list[str] = [] - def _open(path: str, *, signed_in: bool = True, jobs: list[dict] | None = None, - responses: stub_api.Responses | None = None): + def _open( + path: str, + *, + signed_in: bool = True, + jobs: list[dict] | None = None, + responses: stub_api.Responses | None = None, + ): context = a11y_browser.new_context( - viewport={"width": 1280, "height": 900}, locale="en-AU", timezone_id="UTC", + viewport={"width": 1280, "height": 900}, + locale="en-AU", + timezone_id="UTC", color_scheme="light", # Animations change what is on screen mid-scan (and what contrast is measured on). reduced_motion="reduce", @@ -177,8 +193,7 @@ def _open(path: str, *, signed_in: bool = True, jobs: list[dict] | None = None, script = stub_api.seed_script(stub_api.SESSION if signed_in else None, jobs) if script: context.add_init_script(script) - context.route("**/api/**", stub_api.handler({**stub_api.default_responses(), **(responses or {})}, - unstubbed)) + context.route("**/api/**", stub_api.handler({**stub_api.default_responses(), **(responses or {})}, unstubbed)) page = context.new_page() page.goto(app_url + path, wait_until="networkidle", timeout=60_000) return page @@ -214,9 +229,18 @@ def _scan(page, scenario: str) -> axe_baseline.Outcome: if report_dir: Path(report_dir).mkdir(parents=True, exist_ok=True) (Path(report_dir) / f"{scenario}.json").write_text( - json.dumps({"scenario": scenario, "url": page.url, "violations": violations, - "known": outcome.known, "shrunk": outcome.shrunk}, indent=2), - encoding="utf-8") + json.dumps( + { + "scenario": scenario, + "url": page.url, + "violations": violations, + "known": outcome.known, + "shrunk": outcome.shrunk, + }, + indent=2, + ), + encoding="utf-8", + ) for line in outcome.known + outcome.shrunk: print(f"[a11y {scenario}] {line}") @@ -243,8 +267,11 @@ class Handler(BaseHTTPRequestHandler): def _answer(self): body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) path = self.path.split("?")[0] - if self.command == "POST" and path == "/api/auth/login" \ - and json.loads(body or b"{}").get("password") == stub_api.STREAMLIT_PASSWORD: + if ( + self.command == "POST" + and path == "/api/auth/login" + and json.loads(body or b"{}").get("password") == stub_api.STREAMLIT_PASSWORD + ): status, payload = 200, stub_api.STREAMLIT_SESSION else: status, payload = stub_api.respond(path, responses) @@ -277,18 +304,34 @@ def streamlit_url(stub_api_url): log = Path(tempfile.mkdtemp(prefix="a11y-streamlit-")) / "streamlit.log" with log.open("wb") as out: proc = subprocess.Popen( - [sys.executable, "-m", "streamlit", "run", "app.py", "--server.port", str(port), - "--server.address", "127.0.0.1", "--server.headless", "true"], - cwd=STREAMLIT_APP, stdout=out, stderr=subprocess.STDOUT, - env={**os.environ, "API_URL": stub_api_url}, start_new_session=(os.name == "posix"), + [ + sys.executable, + "-m", + "streamlit", + "run", + "app.py", + "--server.port", + str(port), + "--server.address", + "127.0.0.1", + "--server.headless", + "true", + ], + cwd=STREAMLIT_APP, + stdout=out, + stderr=subprocess.STDOUT, + env={**os.environ, "API_URL": stub_api_url}, + start_new_session=(os.name == "posix"), ) url = f"http://127.0.0.1:{port}" try: deadline = time.monotonic() + 60 while True: if proc.poll() is not None: - _fail(f"Streamlit exited with code {proc.returncode} before serving.\n" - f"{log.read_text(errors='replace')[-2000:]}") + _fail( + f"Streamlit exited with code {proc.returncode} before serving.\n" + f"{log.read_text(errors='replace')[-2000:]}" + ) try: with urllib.request.urlopen(f"{url}/_stcore/health", timeout=5) as res: if res.read().strip() == b"ok": @@ -296,7 +339,9 @@ def streamlit_url(stub_api_url): except (urllib.error.URLError, OSError): pass if time.monotonic() > deadline: - _fail(f"Streamlit did not report healthy at {url} within 60s.\n{log.read_text(errors='replace')[-2000:]}") + _fail( + f"Streamlit did not report healthy at {url} within 60s.\n{log.read_text(errors='replace')[-2000:]}" + ) time.sleep(0.5) yield url finally: @@ -311,8 +356,13 @@ def streamlit_url(stub_api_url): @pytest.fixture def streamlit_page(streamlit_url, chromium): """``streamlit_page(sign_in=True)`` -> a Page on the Streamlit app, signed in through the real form unless told not to.""" - context = chromium.new_context(viewport={"width": 1280, "height": 900}, locale="en-AU", - timezone_id="UTC", color_scheme="light", reduced_motion="reduce") + context = chromium.new_context( + viewport={"width": 1280, "height": 900}, + locale="en-AU", + timezone_id="UTC", + color_scheme="light", + reduced_motion="reduce", + ) def _open(*, sign_in: bool = True): page = context.new_page() diff --git a/tests/accessibility/stub_api.py b/tests/accessibility/stub_api.py index 730d985..1419b4a 100644 --- a/tests/accessibility/stub_api.py +++ b/tests/accessibility/stub_api.py @@ -11,20 +11,35 @@ No Playwright import here: this module only describes data and a request handler. """ + from __future__ import annotations import json -from urllib.parse import quote from typing import Any, Callable +from urllib.parse import quote -SESSION = {"token": "a11y-scan-token", "expiresAt": "2099-01-01T00:00:00Z", - "username": "ada", "tenant": "acme", "role": "admin"} +SESSION = { + "token": "a11y-scan-token", + "expiresAt": "2099-01-01T00:00:00Z", + "username": "ada", + "tenant": "acme", + "role": "admin", +} -FILES = [{ - "id": "1", "file_name": "customers.csv", "table_name": "csv_customers", "row_count": 120, - "total_rows": 125, "failed_rows": 5, "uploader": "ada", "upload_id": "101", - "column_names": ["id", "name", "email"], "created_at": "2026-11-01T01:02:03Z", -}] +FILES = [ + { + "id": "1", + "file_name": "customers.csv", + "table_name": "csv_customers", + "row_count": 120, + "total_rows": 125, + "failed_rows": 5, + "uploader": "ada", + "upload_id": "101", + "column_names": ["id", "name", "email"], + "created_at": "2026-11-01T01:02:03Z", + } +] # What the Streamlit app signs in with (its roles are the API's: tenant_admin, not the React app's "admin"). STREAMLIT_SESSION = {**SESSION, "role": "tenant_admin"} @@ -33,50 +48,132 @@ # One upload's detail (GET /api/csv/uploads/{id}): the row errors the history screen lists. UPLOAD_DETAIL = {"rowErrors": [{"rowNumber": 1, "column": "date", "value": "27 Oct 26", "reason": "not a timestamp"}]} -TE_TABLES = [{"table": "organisations", "exists": True, "rowCount": 3}, - {"table": "programs", "exists": True, "rowCount": 2}] +TE_TABLES = [ + {"table": "organisations", "exists": True, "rowCount": 3}, + {"table": "programs", "exists": True, "rowCount": 2}, +] # Import history, kept by the browser (localStorage), one job per kind of outcome. _LOG = [{"step": "done", "level": "info", "message": "Imported 120 rows"}] JOBS = [ - {"id": "j1", "batchId": "b1", "name": "customers.csv", "size": 2048, "status": "done", "progress": 100, - "createdAt": 1793500000000, "insertedRows": 120, "totalRows": 125, "failedRows": 5, - "tableName": "csv_customers", "columns": ["id", "name", "email"], "types": ["int8", "text", "text"], - "logs": _LOG}, - {"id": "j2", "batchId": "b1", "name": "orders.csv", "size": 100, "status": "error", "progress": 100, - "createdAt": 1793500100000, "errorMessage": "None of the 2 rows could be imported", - "rowErrors": [{"row": 1, "column": "date", "value": "27 Oct 26", "reason": "not a timestamp"}]}, - {"id": "j3", "batchId": "b1", "name": "dup.csv", "size": 100, "status": "duplicate", "progress": 100, - "createdAt": 1793500200000, "existingFileName": "customers.csv", "duplicateReason": "content", - "tableName": "csv_customers"}, + { + "id": "j1", + "batchId": "b1", + "name": "customers.csv", + "size": 2048, + "status": "done", + "progress": 100, + "createdAt": 1793500000000, + "insertedRows": 120, + "totalRows": 125, + "failedRows": 5, + "tableName": "csv_customers", + "columns": ["id", "name", "email"], + "types": ["int8", "text", "text"], + "logs": _LOG, + }, + { + "id": "j2", + "batchId": "b1", + "name": "orders.csv", + "size": 100, + "status": "error", + "progress": 100, + "createdAt": 1793500100000, + "errorMessage": "None of the 2 rows could be imported", + "rowErrors": [{"row": 1, "column": "date", "value": "27 Oct 26", "reason": "not a timestamp"}], + }, + { + "id": "j3", + "batchId": "b1", + "name": "dup.csv", + "size": 100, + "status": "duplicate", + "progress": 100, + "createdAt": 1793500200000, + "existingFileName": "customers.csv", + "duplicateReason": "content", + "tableName": "csv_customers", + }, ] # Every upload attempt, failed ones included (the "Upload attempts" card on the upload page). UPLOADS = [ - {"id": "101", "file_name": "orders.csv", "mode": "dynamic", "status": "failed", "total_rows": 2, - "imported_rows": 0, "failed_rows": 2, "uploader": "ada", "uploaded_at": "2026-11-02T03:04:05Z"}, - {"id": "102", "file_name": "customers.csv", "mode": "dynamic", "status": "partly_imported", - "total_rows": 125, "imported_rows": 120, "failed_rows": 5, "uploader": "ada", - "uploaded_at": "2026-11-01T01:02:03Z"}, - {"id": "103", "file_name": "empty.csv", "mode": "dynamic", "status": "rejected", "total_rows": None, - "imported_rows": None, "failed_rows": None, "uploader": "ada", "uploaded_at": "2026-11-01T00:00:00Z"}, + { + "id": "101", + "file_name": "orders.csv", + "mode": "dynamic", + "status": "failed", + "total_rows": 2, + "imported_rows": 0, + "failed_rows": 2, + "uploader": "ada", + "uploaded_at": "2026-11-02T03:04:05Z", + }, + { + "id": "102", + "file_name": "customers.csv", + "mode": "dynamic", + "status": "partly_imported", + "total_rows": 125, + "imported_rows": 120, + "failed_rows": 5, + "uploader": "ada", + "uploaded_at": "2026-11-01T01:02:03Z", + }, + { + "id": "103", + "file_name": "empty.csv", + "mode": "dynamic", + "status": "rejected", + "total_rows": None, + "imported_rows": None, + "failed_rows": None, + "uploader": "ada", + "uploaded_at": "2026-11-01T00:00:00Z", + }, ] REVIEW_PAGE = { - "fileName": "customers.csv", "columns": ["id", "name"], "types": ["int8", "text"], "total": 2, - "offset": 0, "limit": 50, "excludedRows": 0, "editedRows": 0, + "fileName": "customers.csv", + "columns": ["id", "name"], + "types": ["int8", "text"], + "total": 2, + "offset": 0, + "limit": 50, + "excludedRows": 0, + "editedRows": 0, "rows": [ - {"rowNumber": 1, "original": ["1", "Ada"], "current": ["1", "Ada"], "editedColumns": [], - "decision": "include", "decisionReason": None, "errors": []}, - {"rowNumber": 2, "original": ["x", "Bob"], "current": ["x", "Bob"], "editedColumns": [], - "decision": "include", "decisionReason": None, - "errors": [{"column": "id", "value": "x", "reason": '"x" is not a whole number'}]}, + { + "rowNumber": 1, + "original": ["1", "Ada"], + "current": ["1", "Ada"], + "editedColumns": [], + "decision": "include", + "decisionReason": None, + "errors": [], + }, + { + "rowNumber": 2, + "original": ["x", "Bob"], + "current": ["x", "Bob"], + "editedColumns": [], + "decision": "include", + "decisionReason": None, + "errors": [{"column": "id", "value": "x", "reason": '"x" is not a whole number'}], + }, ], } -PREVIEW = {"status": "ok", "headers": ["id", "name"], "columns": ["id", "name"], - "inferredTypes": ["int8", "text"], "sampleRows": [["1", "a"], ["2", "b"]], - "totalRowsApprox": 2, "teTableMatch": None} +PREVIEW = { + "status": "ok", + "headers": ["id", "name"], + "columns": ["id", "name"], + "inferredTypes": ["int8", "text"], + "sampleRows": [["1", "a"], ["2", "b"]], + "totalRowsApprox": 2, + "teTableMatch": None, +} # route -> JSON body. A callable receives the request path and returns the body. Responses = dict[str, Any] @@ -112,13 +209,15 @@ def _is_session(body: Any) -> bool: def handler(responses: Responses, unstubbed: list[str]) -> Callable: """A Playwright route handler. Paths with no stub are recorded in ``unstubbed``.""" + def handle(route, request): path = request.url.split("?")[0] - path = path[path.index("/api/"):] if "/api/" in path else path + path = path[path.index("/api/") :] if "/api/" in path else path status, body = respond(path, responses) if status == 404: unstubbed.append(f"{request.method} {path}") route.fulfill(status=status, content_type="application/json", body=json.dumps(body)) + return handle @@ -139,7 +238,9 @@ def seed_script(session: dict | None, jobs: list[dict] | None) -> str: parts.append(f"sessionStorage.setItem('te.session', {json.dumps(json.dumps(session))});") if jobs is not None and session is not None: # The app keeps history per signed-in tenant and user (#176), so plant it under that user's key. - key = "csv-migrator:jobs:v1:{}:{}".format(quote(session["tenant"], safe=""), quote(session["username"], safe="")) + key = "csv-migrator:jobs:v1:{}:{}".format( + quote(session["tenant"], safe=""), quote(session["username"], safe="") + ) parts.append( f"(() => {{ const KEY = {json.dumps(key)}, set = Storage.prototype.setItem;" " Storage.prototype.setItem = function (k, v) { if (k === KEY && v === '[]') return;" diff --git a/tests/accessibility/test_accessibility.py b/tests/accessibility/test_accessibility.py index 52c80c5..bd721df 100644 --- a/tests/accessibility/test_accessibility.py +++ b/tests/accessibility/test_accessibility.py @@ -11,6 +11,7 @@ and then scans. Results are judged against known_violations.json; see README.md in this folder for what that means, and why scans of an unfixed frontend still pass today. """ + from __future__ import annotations import pytest @@ -123,6 +124,7 @@ def test_signed_out_visitors_are_sent_to_sign_in(open_page, path): # The stub is served over HTTP (conftest.stub_api_url); pages are reached through the sidebar. # st.dataframe draws on a canvas, so axe cannot see inside grids (README.md). + def test_streamlit_sign_in_page(streamlit_page, scan): page = streamlit_page(sign_in=False) _shows(page, "Sign in") @@ -132,6 +134,7 @@ def test_streamlit_sign_in_page(streamlit_page, scan): def test_streamlit_sign_in_after_a_failed_attempt(streamlit_page, scan): from tests.accessibility.conftest import sign_in_as + page = streamlit_page(sign_in=False) sign_in_as(page, "not-the-password") _shows(page, "Invalid tenant, username or password") diff --git a/tests/conftest.py b/tests/conftest.py index 50cb209..a75ecbb 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,9 +5,11 @@ where one test sets CSV_FILE / PGPASSWORD / PATH and leaks that value into an unrelated downstream test. """ + import os import sys from pathlib import Path + import pytest sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) @@ -30,7 +32,6 @@ # and let tests that specifically exercise limiting set their own budgets. from api.ratelimit import limiter as _limiter # noqa: E402 - _settings.RATE_LIMIT_READS_PER_MINUTE = 0 _settings.RATE_LIMIT_WRITES_PER_MINUTE = 0 @@ -53,8 +54,10 @@ def _reset_rate_limiter(): from api.db import Conn # noqa: E402 -_START_HELP = ("Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/PGPASSWORD/" - "PGDATABASE). See scripts/start-api.ps1.") +_START_HELP = ( + "Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/PGPASSWORD/" + "PGDATABASE). See scripts/start-api.ps1." +) @pytest.fixture(scope="class") @@ -107,16 +110,24 @@ def te_org_cleanup(request): yield names if names: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("DELETE FROM {}.organisations WHERE name = ANY(%s)").format( - sql.Identifier(_settings.TE_SCHEMA)), (names,)) + cur.execute( + sql.SQL("DELETE FROM {}.organisations WHERE name = ANY(%s)").format( + sql.Identifier(_settings.TE_SCHEMA) + ), + (names,), + ) conn.commit() # M7 (#111, BR-37): `pytest --block-egress` (or BLOCK_EGRESS=1) refuses any in-process connection that isn't # to this machine, so a test run proves the application makes no outbound calls. See tests/egress_guard.py. def pytest_addoption(parser): - parser.addoption("--block-egress", action="store_true", default=False, - help="refuse network connections to anything but this machine, and fail if one is attempted") + parser.addoption( + "--block-egress", + action="store_true", + default=False, + help="refuse network connections to anything but this machine, and fail if one is attempted", + ) def _egress_blocked(config) -> bool: @@ -126,6 +137,7 @@ def _egress_blocked(config) -> bool: def pytest_configure(config): if _egress_blocked(config): from tests import egress_guard + egress_guard.check_local_database(_settings.PG_HOST) egress_guard.install() @@ -138,10 +150,11 @@ def pytest_report_header(config): def pytest_sessionfinish(session, exitstatus): if _egress_blocked(session.config): from tests import egress_guard + egress_guard.uninstall() if egress_guard.attempts: print("\nEGRESS ATTEMPTED (blocked): " + "; ".join(sorted(set(egress_guard.attempts)))) - session.exitstatus = 1 # a swallowed EgressBlocked must still fail the run + session.exitstatus = 1 # a swallowed EgressBlocked must still fail the run # Folder -> marker (#167). The folder a test lives in is its category, so `-m system`, diff --git a/tests/egress_guard.py b/tests/egress_guard.py index 7a5235d..f6638db 100644 --- a/tests/egress_guard.py +++ b/tests/egress_guard.py @@ -29,7 +29,7 @@ def is_local(host) -> bool: if isinstance(host, bytes): host = host.decode("ascii", "replace") host = host.strip("[]") - if host == "localhost" or host.startswith("/"): # a Unix socket directory, as libpq takes it + if host == "localhost" or host.startswith("/"): # a Unix socket directory, as libpq takes it return True try: return ipaddress.ip_address(host).is_loopback @@ -40,7 +40,9 @@ def is_local(host) -> bool: def check_local_database(host: str) -> None: """libpq's connection can't be intercepted from Python, so refuse a remote database host outright.""" if not is_local(host): - raise EgressBlocked(f"The database host {host!r} is not on this machine; an egress-blocked run needs a local one.") + raise EgressBlocked( + f"The database host {host!r} is not on this machine; an egress-blocked run needs a local one." + ) def _blocked(what: str) -> EgressBlocked: @@ -51,10 +53,11 @@ def _blocked(what: str) -> EgressBlocked: def install() -> None: if _originals: return - _originals.update(connect=socket.socket.connect, connect_ex=socket.socket.connect_ex, - getaddrinfo=socket.getaddrinfo) + _originals.update( + connect=socket.socket.connect, connect_ex=socket.socket.connect_ex, getaddrinfo=socket.getaddrinfo + ) - unix = getattr(socket, "AF_UNIX", None) # Windows' Python has none + unix = getattr(socket, "AF_UNIX", None) # Windows' Python has none def check_address(sock, address, what): if (unix is not None and sock.family == unix) or not isinstance(address, tuple) or is_local(address[0]): @@ -80,5 +83,8 @@ def getaddrinfo(host, *args, **kwargs): def uninstall() -> None: if _originals: socket.socket.connect, socket.socket.connect_ex, socket.getaddrinfo = ( - _originals["connect"], _originals["connect_ex"], _originals["getaddrinfo"]) + _originals["connect"], + _originals["connect_ex"], + _originals["getaddrinfo"], + ) _originals.clear() diff --git a/tests/oidc_stub.py b/tests/oidc_stub.py index 13fccd2..3a6b6e1 100644 --- a/tests/oidc_stub.py +++ b/tests/oidc_stub.py @@ -44,23 +44,34 @@ def _self_signed(directory: Path) -> tuple[Path, Path]: key = new_key() name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")]) now = datetime.datetime.now(datetime.timezone.utc) - cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key()) - .serial_number(x509.random_serial_number()) - .not_valid_before(now - datetime.timedelta(days=1)).not_valid_after(now + datetime.timedelta(days=1)) - .add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost"), - x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), critical=False) - .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) - .sign(key, hashes.SHA256())) + cert = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(days=1)) + .not_valid_after(now + datetime.timedelta(days=1)) + .add_extension( + x509.SubjectAlternativeName([x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), + critical=False, + ) + .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) + .sign(key, hashes.SHA256()) + ) cert_path, key_path = directory / "idp.pem", directory / "idp.key" cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM)) - key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, - serialization.NoEncryption())) + key_path.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption() + ) + ) return cert_path, key_path class LocalIdp: def __init__(self, keys: dict[str, object] | None = None): - self.keys = dict(keys or {}) # kid -> private key; what /jwks publishes + self.keys = dict(keys or {}) # kid -> private key; what /jwks publishes self.requests: list[str] = [] self._dir = tempfile.TemporaryDirectory() self.cert_path, key_path = _self_signed(Path(self._dir.name)) @@ -91,7 +102,7 @@ def log_message(self, *args): self._server.socket = context.wrap_socket(self._server.socket, server_side=True) self.port = self._server.server_address[1] self.jwks_url = f"https://localhost:{self.port}/jwks" - self.issuer = f"https://localhost:{self.port}" # discovery is at /.well-known/openid-configuration + self.issuer = f"https://localhost:{self.port}" # discovery is at /.well-known/openid-configuration threading.Thread(target=self._server.serve_forever, daemon=True).start() def trust(self): diff --git a/tests/performance/test_import_scale.py b/tests/performance/test_import_scale.py index 3f7af96..65e87dd 100644 --- a/tests/performance/test_import_scale.py +++ b/tests/performance/test_import_scale.py @@ -29,10 +29,12 @@ def test_every_row_is_imported_and_the_targets_hold_when_enforced(self): harness = _harness() rows = int(os.environ.get("PERF_ROWS", "10000")) report = harness.run(rows) - self.assertEqual(report["reconciliation"], - {"rowsIn": rows, "excluded": 0, "edited": 0, "duplicate": 0, "imported": rows}) - self.assertEqual(set(report["timings"]), - {"preview", "stage", "reviewPage", "submit", "approve", "import", "upToImported"}) + self.assertEqual( + report["reconciliation"], {"rowsIn": rows, "excluded": 0, "edited": 0, "duplicate": 0, "imported": rows} + ) + self.assertEqual( + set(report["timings"]), {"preview", "stage", "reviewPage", "submit", "approve", "import", "upToImported"} + ) if os.environ.get("PERF_ENFORCE") == "1": verdict = harness.verdict(report) self.assertTrue(verdict["importUnderTarget"], report["timings"]) diff --git a/tests/system/test_accounts.py b/tests/system/test_accounts.py index c0ab119..cde424d 100644 --- a/tests/system/test_accounts.py +++ b/tests/system/test_accounts.py @@ -19,8 +19,10 @@ from api.main import app from api.services import accounts -_HELP = ("Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" - "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" + "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1." +) _PW = "correct horse battery staple" @@ -73,8 +75,10 @@ def _exec(self, query: str, *params) -> None: conn.commit() def _login(self, tenant=None, username=None, password=_PW): - return self.client.post("/api/auth/login", json={ - "tenant": tenant or self.tenant, "username": username or self.user, "password": password}) + return self.client.post( + "/api/auth/login", + json={"tenant": tenant or self.tenant, "username": username or self.user, "password": password}, + ) def _me(self, token: str): return self.client.get("/api/auth/me", headers={"Authorization": f"Bearer {token}"}) @@ -98,8 +102,9 @@ def test_every_login_failure_is_the_same_401(self): "unknown tenant": self._login(tenant="no_such_tenant"), } for name, res in cases.items(): - self.assertEqual((res.status_code, res.json()["detail"]), - (401, "Invalid tenant, username or password"), name) + self.assertEqual( + (res.status_code, res.json()["detail"]), (401, "Invalid tenant, username or password"), name + ) def test_inactive_user_cannot_sign_in_and_loses_live_sessions(self): token = self._login().json()["token"] @@ -115,8 +120,7 @@ def test_logout_revokes_the_session(self): def test_expired_session_is_rejected(self): token = self._login().json()["token"] - self._exec("UPDATE {c}.sessions SET expires_at = now() - interval '1 second' WHERE user_id = %s", - self.user_id) + self._exec("UPDATE {c}.sessions SET expires_at = now() - interval '1 second' WHERE user_id = %s", self.user_id) self.assertEqual(self._me(token).status_code, 401) def test_removing_the_membership_ends_the_session(self): @@ -125,15 +129,23 @@ def test_removing_the_membership_ends_the_session(self): self.assertEqual(self._me(token).status_code, 401) def test_missing_or_malformed_token_is_401(self): - for headers in ({}, {"Authorization": "Bearer "}, {"Authorization": "Basic abc"}, - {"Authorization": "Bearer not-a-real-token"}): + for headers in ( + {}, + {"Authorization": "Bearer "}, + {"Authorization": "Basic abc"}, + {"Authorization": "Bearer not-a-real-token"}, + ): self.assertEqual(self.client.get("/api/auth/me", headers=headers).status_code, 401, headers) def test_tokens_are_stored_only_as_hashes(self): token = self._login().json()["token"] with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT token_hash FROM {c}.sessions WHERE user_id = %s").format( - c=sql.Identifier(settings.CONTROL_SCHEMA)), (self.user_id,)) + cur.execute( + sql.SQL("SELECT token_hash FROM {c}.sessions WHERE user_id = %s").format( + c=sql.Identifier(settings.CONTROL_SCHEMA) + ), + (self.user_id,), + ) stored = [r[0] for r in cur.fetchall()] self.assertEqual(len(stored), 1) self.assertNotIn(token, stored) @@ -150,8 +162,7 @@ def _fail(self, n: int) -> None: def test_eleventh_attempt_is_refused_even_with_the_right_password(self): self._fail(settings.LOGIN_MAX_FAILURES) res = self._login() - self.assertEqual((res.status_code, res.json()["detail"]), - (401, "Invalid tenant, username or password")) + self.assertEqual((res.status_code, res.json()["detail"]), (401, "Invalid tenant, username or password")) def test_one_short_of_the_limit_still_signs_in_and_resets_the_count(self): self._fail(settings.LOGIN_MAX_FAILURES - 1) @@ -161,13 +172,15 @@ def test_one_short_of_the_limit_still_signs_in_and_resets_the_count(self): def test_sign_in_works_again_after_the_lock_expires(self): self._fail(settings.LOGIN_MAX_FAILURES) - self._exec("UPDATE {c}.users SET locked_until = now() - interval '1 second' WHERE id = %s", - self.user_id) + self._exec("UPDATE {c}.users SET locked_until = now() - interval '1 second' WHERE id = %s", self.user_id) self.assertEqual(self._login().status_code, 200) def test_failures_outside_the_window_start_a_new_count(self): self._fail(settings.LOGIN_MAX_FAILURES - 1) - self._exec("UPDATE {c}.users SET first_failed_at = now() - make_interval(mins => %s) " - "WHERE id = %s", settings.LOGIN_LOCKOUT_MINUTES + 1, self.user_id) + self._exec( + "UPDATE {c}.users SET first_failed_at = now() - make_interval(mins => %s) WHERE id = %s", + settings.LOGIN_LOCKOUT_MINUTES + 1, + self.user_id, + ) self._fail(1) self.assertEqual(self._login().status_code, 200) diff --git a/tests/system/test_api_coverage.py b/tests/system/test_api_coverage.py index b601667..4cdf963 100644 --- a/tests/system/test_api_coverage.py +++ b/tests/system/test_api_coverage.py @@ -10,6 +10,7 @@ Convention: same unittest.TestCase + pytest markers as test_api.py. """ + from __future__ import annotations import os @@ -23,11 +24,13 @@ client = TestClient(app) -_HELP = ("Start PostgreSQL and ensure api/ can reach it. Most often this means " - "PGPASSWORD is not set in this shell:\n" - " PowerShell: $env:PGPASSWORD = ''\n" - " bash: export PGPASSWORD=''\n" - "Defaults come from api/config.py; see scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it. Most often this means " + "PGPASSWORD is not set in this shell:\n" + " PowerShell: $env:PGPASSWORD = ''\n" + " bash: export PGPASSWORD=''\n" + "Defaults come from api/config.py; see scripts/start-api.ps1." +) class _IntegrationBase(unittest.TestCase): @@ -71,22 +74,33 @@ def _upload_dynamic(self, content=None, overwrite=False): name = f"{self.tag}.csv" if content is None: content = f"col_a,col_b\n{os.getpid()},{self._testMethodName}\n" - return self.client.post("/api/csv/upload", json={ - "fileName": name, "content": content, "overwrite": overwrite, - }) + return self.client.post( + "/api/csv/upload", + json={ + "fileName": name, + "content": content, + "overwrite": overwrite, + }, + ) def _upload_te(self, content, target_table="organisations"): name = f"{self.tag}.csv" - return self.client.post("/api/csv/upload", json={ - "fileName": name, "content": content, - "mode": "te", "targetTable": target_table, - }) + return self.client.post( + "/api/csv/upload", + json={ + "fileName": name, + "content": content, + "mode": "te", + "targetTable": target_table, + }, + ) # --------------------------------------------------------------------------- # Gap 1a: TE_TABLES whitelist (unit — no DB) # --------------------------------------------------------------------------- + @pytest.mark.unit class TeTablesConfig(unittest.TestCase): """The TE_TABLES whitelist in api/config.py must stay consistent.""" @@ -106,48 +120,53 @@ def test_te_tables_has_no_duplicates(self): # Gap 6: CORS middleware (unit — no DB) # --------------------------------------------------------------------------- + @pytest.mark.unit class CorsHeaders(unittest.TestCase): """CORS middleware must be active with the configured origins.""" def test_preflight_returns_cors_headers(self): - r = client.options("/api/health", headers={ - "Origin": "http://localhost:5173", - "Access-Control-Request-Method": "GET", - }) + r = client.options( + "/api/health", + headers={ + "Origin": "http://localhost:5173", + "Access-Control-Request-Method": "GET", + }, + ) self.assertIn("access-control-allow-origin", r.headers) def test_preflight_allows_put_for_review_changes(self): """#108: the browser's review screen sends PUT; without it the preflight fails.""" - r = client.options("/api/csv/uploads/1/rows/1/decision", headers={ - "Origin": "http://localhost:8080", - "Access-Control-Request-Method": "PUT", - "Access-Control-Request-Headers": "authorization,content-type", - }) + r = client.options( + "/api/csv/uploads/1/rows/1/decision", + headers={ + "Origin": "http://localhost:8080", + "Access-Control-Request-Method": "PUT", + "Access-Control-Request-Headers": "authorization,content-type", + }, + ) self.assertEqual(r.status_code, 200, r.text) self.assertIn("PUT", r.headers.get("access-control-allow-methods", "")) def test_cors_allows_configured_origin(self): r = client.get("/api/health", headers={"Origin": "http://localhost:5173"}) - self.assertEqual( - r.headers.get("access-control-allow-origin"), "http://localhost:5173") + self.assertEqual(r.headers.get("access-control-allow-origin"), "http://localhost:5173") def test_default_origins_include_vite_dev_port(self): """Issue #43: the Vite dev server runs on :8080 and must be allowed by default.""" r = client.get("/api/health", headers={"Origin": "http://localhost:8080"}) - self.assertEqual( - r.headers.get("access-control-allow-origin"), "http://localhost:8080") + self.assertEqual(r.headers.get("access-control-allow-origin"), "http://localhost:8080") def test_cors_rejects_unconfigured_origin(self): r = client.get("/api/health", headers={"Origin": "http://evil.example.com"}) - self.assertNotEqual( - r.headers.get("access-control-allow-origin"), "http://evil.example.com") + self.assertNotEqual(r.headers.get("access-control-allow-origin"), "http://evil.example.com") # --------------------------------------------------------------------------- # Gap 1b: GET /api/te/tables (integration — needs deployed T&E schema) # --------------------------------------------------------------------------- + @pytest.mark.integration class TeTablesEndpoint(_IntegrationBase): """GET /api/te/tables must return the 12 fixed T&E tables.""" @@ -176,9 +195,7 @@ def test_table_names_match_whitelist(self): def test_all_tables_exist_after_deploy(self): for entry in self.data: - self.assertTrue( - entry["exists"], - f"T&E table '{entry['table']}' does not exist — run deploy_all.sh dev") + self.assertTrue(entry["exists"], f"T&E table '{entry['table']}' does not exist — run deploy_all.sh dev") def test_row_count_is_non_negative_integer(self): for entry in self.data: @@ -190,14 +207,14 @@ def test_row_count_is_non_negative_integer(self): # Gap 3: preview teTableMatch (integration — match_te_table queries the DB) # --------------------------------------------------------------------------- + @pytest.mark.integration class PreviewTeTableMatch(_IntegrationBase): """POST /api/csv/preview must populate teTableMatch when columns fit.""" def test_preview_returns_te_match_for_matching_columns(self): csv = f"name,org_type,country\n{self.tag},government,AU\n" - r = self.client.post("/api/csv/preview", - json={"fileName": f"{self.tag}.csv", "content": csv}) + r = self.client.post("/api/csv/preview", json={"fileName": f"{self.tag}.csv", "content": csv}) self.assertEqual(r.status_code, 200) body = r.json() self.assertEqual(body.get("status"), "ok", body) @@ -205,16 +222,14 @@ def test_preview_returns_te_match_for_matching_columns(self): def test_preview_returns_null_for_non_matching_columns(self): csv = "col_x,col_y\n1,2\n" - r = self.client.post("/api/csv/preview", - json={"fileName": f"{self.tag}.csv", "content": csv}) + r = self.client.post("/api/csv/preview", json={"fileName": f"{self.tag}.csv", "content": csv}) body = r.json() self.assertEqual(body.get("status"), "ok", body) self.assertIsNone(body.get("teTableMatch")) def test_te_table_match_key_present_in_ok_response(self): csv = "a,b\n1,2\n" - r = self.client.post("/api/csv/preview", - json={"fileName": f"{self.tag}.csv", "content": csv}) + r = self.client.post("/api/csv/preview", json={"fileName": f"{self.tag}.csv", "content": csv}) body = r.json() if body.get("status") == "ok": self.assertIn("teTableMatch", body) @@ -224,6 +239,7 @@ def test_te_table_match_key_present_in_ok_response(self): # Gap 4: DELETE /api/csv/files/{file_id} (integration) # --------------------------------------------------------------------------- + @pytest.mark.integration class DeleteEndpoint(_IntegrationBase): """DELETE must return the right shape, 404 on missing, and handle modes.""" @@ -251,8 +267,7 @@ def test_delete_dynamic_drops_backing_table(self): self.client.delete(f"/api/csv/files/{file_id}") rows = self.client.get(f"/api/csv/tables/{table}/rows") - self.assertEqual(rows.status_code, 404, - "table should be unregistered after delete") + self.assertEqual(rows.status_code, 404, "table should be unregistered after delete") def test_delete_te_only_removes_registry(self): csv = f"name,org_type,country\n{self.tag}_del,government,AU\n" @@ -264,8 +279,7 @@ def test_delete_te_only_removes_registry(self): self.client.delete(f"/api/csv/files/{file_id}") file_names = [f["file_name"] for f in self.client.get("/api/csv/files").json()] - self.assertNotIn(f"{self.tag}.csv", file_names, - "registry entry should be gone") + self.assertNotIn(f"{self.tag}.csv", file_names, "registry entry should be gone") te = self.client.get("/api/te/tables").json() org = next(t for t in te if t["table"] == "organisations") @@ -284,6 +298,7 @@ def test_deleted_file_no_longer_listed(self): # BUG-041: GET /api/audit/log (integration) # --------------------------------------------------------------------------- + @pytest.mark.integration class AuditLogEndpoint(_IntegrationBase): """audit_log used to be write-only; verify deletions are readable back.""" @@ -302,9 +317,7 @@ def test_delete_appears_in_audit_log(self): page = r.json() for field in ("total", "limit", "offset", "entries"): self.assertIn(field, page) - entry = next( - (e for e in page["entries"] if e["fileId"] == file_id), None - ) + entry = next((e for e in page["entries"] if e["fileId"] == file_id), None) self.assertIsNotNone(entry, "delete should be recorded in the audit log") self.assertEqual(entry["action"], "delete") self.assertEqual(entry["fileName"], file_name) @@ -315,6 +328,7 @@ def test_delete_appears_in_audit_log(self): # Gap 5: overwrite=true (integration) # --------------------------------------------------------------------------- + @pytest.mark.integration class OverwriteUpload(_IntegrationBase): """A repeated filename becomes the next version; nothing is overwritten (M5, decision 2).""" @@ -359,6 +373,7 @@ def test_each_version_has_its_own_table(self): # Gap 2: T&E mode upload (integration) # --------------------------------------------------------------------------- + @pytest.mark.integration class TeUploadPipeline(_IntegrationBase): """POST /api/csv/upload with mode=te against a deployed T&E schema.""" @@ -372,9 +387,8 @@ def test_successful_upload_to_organisations(self): body = r.json() self.assertEqual(body["status"], "ok", body) self.assertGreaterEqual( - body["insertedRows"], 1, - f"failedRows={body.get('failedRows')}, " - f"rowErrors={body.get('rowErrors')}") + body["insertedRows"], 1, f"failedRows={body.get('failedRows')}, rowErrors={body.get('rowErrors')}" + ) self.assertIn("organisations", body["tableName"]) def test_response_shape_matches_contract(self): @@ -382,9 +396,7 @@ def test_response_shape_matches_contract(self): r = self._upload_te(csv) body = r.json() self.assertEqual(body["status"], "ok", body) - for key in ("totalRows", "insertedRows", - "duplicateRowsSkipped", "failedRows", - "columns", "rowErrors"): + for key in ("totalRows", "insertedRows", "duplicateRowsSkipped", "failedRows", "columns", "rowErrors"): self.assertIn(key, body, f"missing key '{key}'") self.assertEqual(body["duplicateRowsSkipped"], 0) # #190: one reviewable type per column (organisations' columns are all text). @@ -423,8 +435,9 @@ def test_enum_constraint_violation_reported_per_row(self): r = self._upload_te(csv) body = r.json() self.assertEqual(body["status"], "error", body) - self.assertGreaterEqual(body["failedRows"], 1, - "Invalid enum value should fail at row level, not crash the endpoint") + self.assertGreaterEqual( + body["failedRows"], 1, "Invalid enum value should fail at row level, not crash the endpoint" + ) self.assertIn("rowNumber", body["rowErrors"][0]) def test_null_in_not_null_column_reported_per_row(self): @@ -433,18 +446,20 @@ def test_null_in_not_null_column_reported_per_row(self): r = self._upload_te(csv) body = r.json() self.assertEqual(body["status"], "error", body) - self.assertGreaterEqual(body["failedRows"], 1, - "NULL in a NOT NULL column should fail at row level") + self.assertGreaterEqual(body["failedRows"], 1, "NULL in a NOT NULL column should fail at row level") self.assertIn("rowNumber", body["rowErrors"][0]) def test_unknown_target_table_returns_error(self): """Uploading to a table not in TE_TABLES must return status=error.""" - r = self.client.post("/api/csv/upload", json={ - "fileName": f"{self.tag}.csv", - "content": "col_a\nval\n", - "mode": "te", - "targetTable": "non_existent_table", - }) + r = self.client.post( + "/api/csv/upload", + json={ + "fileName": f"{self.tag}.csv", + "content": "col_a\nval\n", + "mode": "te", + "targetTable": "non_existent_table", + }, + ) body = r.json() self.assertEqual(body["status"], "error", body) self.assertIn("non_existent_table", body.get("message", "")) @@ -461,8 +476,7 @@ def test_te_reupload_same_file_replaces_registry(self): self.assertEqual(r2.json()["status"], "ok", r2.json()) files = self.client.get("/api/csv/files").json() matches = [f for f in files if f["file_name"] == f"{self.tag}.csv"] - self.assertEqual(len(matches), 1, - "Re-upload should replace the registry entry, not create a duplicate") + self.assertEqual(len(matches), 1, "Re-upload should replace the registry entry, not create a duplicate") def test_te_client_side_type_validation_reports_column_and_value(self): """BUG-028: a bad value on a client-validatable column (BOOLEAN here) @@ -482,15 +496,12 @@ def test_te_client_side_type_validation_reports_column_and_value(self): # #289: a T&E load is all or nothing, so the valid row does not land either. self.assertEqual(body["status"], "error", body) self.assertEqual(body["failedRows"], 1) - self.assertEqual(body["insertedRows"], 0, - "A file with a failing row imports nothing (#289).") + self.assertEqual(body["insertedRows"], 0, "A file with a failing row imports nothing (#289).") self.assertTrue(body["rowErrors"], "rowErrors must be populated") err = body["rowErrors"][0] # These two fields are the fingerprint of the client-side path. - self.assertEqual(err.get("column"), "is_active", - f"Client-side validator must set column; got {err!r}") - self.assertEqual(err.get("value"), "NOT_A_BOOL", - f"Client-side validator must set value; got {err!r}") + self.assertEqual(err.get("column"), "is_active", f"Client-side validator must set column; got {err!r}") + self.assertEqual(err.get("value"), "NOT_A_BOOL", f"Client-side validator must set value; got {err!r}") self.assertIn("true/false", err["reason"].lower()) def test_te_upload_rejects_over_row_cap(self): @@ -498,12 +509,11 @@ def test_te_upload_rejects_over_row_cap(self): rows must be rejected up-front with status=error and never reach the DB. """ from api import config as cfg + original = cfg.settings.MAX_ROWS cfg.settings.MAX_ROWS = 2 # keep the test small try: - csv = "name,org_type,country\n" + "".join( - f"{self.tag}_row{i},government,AU\n" for i in range(5) - ) + csv = "name,org_type,country\n" + "".join(f"{self.tag}_row{i},government,AU\n" for i in range(5)) r = self._upload_te(csv, target_table="organisations") body = r.json() self.assertEqual(body["status"], "error", body) @@ -513,8 +523,7 @@ def test_te_upload_rejects_over_row_cap(self): # Sanity check: no rows leaked to the DB. files = self.client.get("/api/csv/files").json() matches = [f for f in files if f["file_name"] == f"{self.tag}.csv"] - self.assertFalse(matches, - "An over-cap upload must not create a registry entry.") + self.assertFalse(matches, "An over-cap upload must not create a registry entry.") finally: cfg.settings.MAX_ROWS = original @@ -525,11 +534,11 @@ class DeleteGateUnit(unittest.TestCase): def test_delete_blocked_returns_403(self): from api import config as cfg + original = cfg.settings.allow_destructive cfg.settings.allow_destructive = False try: r = client.delete("/api/csv/files/1") - self.assertEqual(r.status_code, 403, - "DELETE must return 403 when API_ALLOW_DESTRUCTIVE=false") + self.assertEqual(r.status_code, 403, "DELETE must return 403 when API_ALLOW_DESTRUCTIVE=false") finally: cfg.settings.allow_destructive = original diff --git a/tests/system/test_api_integration.py b/tests/system/test_api_integration.py index 2d3463b..229b8f6 100644 --- a/tests/system/test_api_integration.py +++ b/tests/system/test_api_integration.py @@ -1,6 +1,7 @@ """API integration tests — require a live PostgreSQL database. Database-free tests live in test_api_unit.py. """ + from __future__ import annotations import os @@ -13,11 +14,13 @@ client = TestClient(app) -_HELP = ("Start PostgreSQL and ensure api/ can reach it. Most often this means " - "PGPASSWORD is not set in this shell:\n" - " PowerShell: $env:PGPASSWORD = ''\n" - " bash: export PGPASSWORD=''\n" - "Defaults come from api/config.py; see scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it. Most often this means " + "PGPASSWORD is not set in this shell:\n" + " PowerShell: $env:PGPASSWORD = ''\n" + " bash: export PGPASSWORD=''\n" + "Defaults come from api/config.py; see scripts/start-api.ps1." +) SMALL_CSV = "col_a,col_b\n1,2\n3,4\n" @@ -116,15 +119,13 @@ def tearDown(self): self.client.delete(f"/api/csv/files/{f['id']}") def test_preview_reports_columns(self): - r = self.client.post("/api/csv/preview", - json={"fileName": self.name, "content": self.content}) + r = self.client.post("/api/csv/preview", json={"fileName": self.name, "content": self.content}) self.assertEqual(r.status_code, 200) self.assertEqual(r.json().get("status"), "ok", r.text[:300]) self.assertEqual(r.json()["columns"], ["col_a", "col_b"]) def test_upload_then_list_then_read_rows(self): - up = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + up = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) self.assertEqual(up.status_code, 200) body = up.json() self.assertEqual(body["status"], "ok", body) @@ -140,19 +141,15 @@ def test_upload_then_list_then_read_rows(self): self.assertEqual(len(rows.json()["rows"]), 1) def test_reupload_of_identical_content_is_refused(self): - first = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + first = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) self.assertEqual(first.json()["status"], "ok") - again = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) - self.assertEqual(again.json()["status"], "duplicate_file", - "re-uploading identical content should be refused") + again = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) + self.assertEqual(again.json()["status"], "duplicate_file", "re-uploading identical content should be refused") def test_in_file_duplicate_rows_are_skipped(self): dupes = f"col_a,col_b\n{os.getpid()},x\n{os.getpid()},x\n" - r = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": dupes}) + r = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": dupes}) body = r.json() self.assertEqual(body["status"], "ok", body) self.assertEqual(body["insertedRows"], 1) @@ -165,11 +162,7 @@ def test_row_hash_does_not_collide_on_split_boundaries(self): rows and both land in the table. """ pid = os.getpid() - content = ( - "col_a,col_b\n" - f"{pid}ab,cd\n" - f"{pid}a,bcd\n" - ) + content = f"col_a,col_b\n{pid}ab,cd\n{pid}a,bcd\n" r = self.client.post( "/api/csv/upload", json={"fileName": self.name, "content": content}, @@ -177,7 +170,8 @@ def test_row_hash_does_not_collide_on_split_boundaries(self): body = r.json() self.assertEqual(body["status"], "ok", body) self.assertEqual( - body["insertedRows"], 2, + body["insertedRows"], + 2, "BUG-022 regression: split-boundary rows were deduplicated", ) self.assertEqual(body["duplicateRowsSkipped"], 0) @@ -200,11 +194,7 @@ def test_row_hash_still_dedupes_identical_rows(self): intended dedup — two byte-identical rows still count as one insert. """ pid = os.getpid() - content = ( - "col_a,col_b\n" - f"{pid}xy,{pid}z\n" - f"{pid}xy,{pid}z\n" - ) + content = f"col_a,col_b\n{pid}xy,{pid}z\n{pid}xy,{pid}z\n" r = self.client.post( "/api/csv/upload", json={"fileName": self.name, "content": content}, @@ -223,8 +213,7 @@ def test_injection_shaped_names_are_not_served(self): for name in ("csv_a; DROP TABLE personnel", "csv_a'--"): with self.subTest(table=name): r = self.client.get(f"/api/csv/tables/{name}/rows") - self.assertEqual(r.status_code, 404, - f"unregistered name was served: {name}") + self.assertEqual(r.status_code, 404, f"unregistered name was served: {name}") def test_core_te_tables_are_intact(self): """A CSV upload must never disturb the 12 tables the SQL suite asserts.""" @@ -239,8 +228,7 @@ def test_core_te_tables_are_intact(self): def test_audit_record_contains_required_fields(self): """BR-15: GET /api/csv/files must return all required audit fields.""" - up = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + up = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) self.assertEqual(up.json()["status"], "ok") files = self.client.get("/api/csv/files").json() @@ -254,34 +242,33 @@ def test_audit_record_row_count_matches_inserted_rows(self): """BR-15: persisted row_count must match what the upload response reported.""" content = f"col_a,col_b\n{os.getpid()}_audit,1\n{os.getpid()}_audit,2\n" name = f"br15_rowcount_{os.getpid()}.csv" - up = self.client.post("/api/csv/upload", - json={"fileName": name, "content": content}) + up = self.client.post("/api/csv/upload", json={"fileName": name, "content": content}) body = up.json() self.assertEqual(body["status"], "ok") files = self.client.get("/api/csv/files").json() record = next((f for f in files if f["file_name"] == name), None) self.assertIsNotNone(record) - self.assertEqual(record["row_count"], body["insertedRows"], - "Persisted row_count must match insertedRows in upload response") + self.assertEqual( + record["row_count"], body["insertedRows"], "Persisted row_count must match insertedRows in upload response" + ) def test_audit_record_table_name_matches_upload_response(self): """BR-15: persisted table_name must match what the upload response reported.""" - up = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + up = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) body = up.json() self.assertEqual(body["status"], "ok") files = self.client.get("/api/csv/files").json() record = next((f for f in files if f["file_name"] == self.name), None) self.assertIsNotNone(record) - self.assertEqual(record["table_name"], body["tableName"], - "Persisted table_name must match tableName in upload response") + self.assertEqual( + record["table_name"], body["tableName"], "Persisted table_name must match tableName in upload response" + ) def test_audit_record_has_iso_timestamp(self): """BR-15: created_at must be a non-empty ISO timestamp.""" - up = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + up = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) self.assertEqual(up.json()["status"], "ok") files = self.client.get("/api/csv/files").json() @@ -289,6 +276,7 @@ def test_audit_record_has_iso_timestamp(self): self.assertIsNotNone(record) self.assertTrue(record.get("created_at", ""), "created_at must not be empty") from datetime import datetime + try: datetime.fromisoformat(record["created_at"].replace("Z", "+00:00")) except ValueError: @@ -297,8 +285,7 @@ def test_audit_record_has_iso_timestamp(self): def test_failed_upload_leaves_no_audit_record(self): """BR-15: a structurally invalid file must not create a registry entry.""" bad_name = f"br15_fail_{os.getpid()}.csv" - up = self.client.post("/api/csv/upload", - json={"fileName": bad_name, "content": "col_a\n"}) + up = self.client.post("/api/csv/upload", json={"fileName": bad_name, "content": "col_a\n"}) self.assertIn(up.json()["status"], ("invalid_structure", "error")) files = self.client.get("/api/csv/files").json() @@ -331,6 +318,7 @@ def setUpClass(cls): # trail could not be tested, and tearDown's cleanup would silently 403 # and leave rows behind for the next run to trip over. from api.config import settings as _settings + cls._settings = _settings cls._orig_allow_destructive = _settings.allow_destructive _settings.allow_destructive = True @@ -380,13 +368,13 @@ def _entries_for(self, file_name: str) -> list[dict]: def test_successful_upload_writes_an_audit_row(self): """O-04: the gap this closes — a load used to leave no audit trace.""" - up = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + up = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) self.assertEqual(up.json()["status"], "ok", up.text) uploads = [e for e in self._entries_for(self.name) if e["action"] == "upload"] self.assertEqual( - len(uploads), 1, + len(uploads), + 1, f"expected exactly one 'upload' audit row for {self.name}, got {len(uploads)}", ) @@ -394,8 +382,7 @@ def test_audit_row_fields_match_the_upload_response(self): """The row must identify what was loaded and where, not merely that something happened — an audit trail that cannot be tied back to the artefact it describes is not evidence.""" - up = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + up = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) body = up.json() self.assertEqual(body["status"], "ok", up.text) @@ -408,8 +395,7 @@ def test_audit_row_fields_match_the_upload_response(self): def test_audit_row_names_the_actor_and_the_chain_verifies(self): """M3a (#107): who acted is recorded, and the hash chain checks out.""" - up = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + up = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) self.assertEqual(up.json()["status"], "ok", up.text) row = next(e for e in self._entries_for(self.name) if e["action"] == "upload") self.assertEqual(row["actor"], "anonymous") @@ -420,17 +406,16 @@ def test_audit_row_names_the_actor_and_the_chain_verifies(self): def test_upload_then_delete_leaves_both_rows(self): """The full lifecycle. Before O-04 only the second half was recorded, so a table could be seen to vanish with no record of its arrival.""" - up = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + up = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) self.assertEqual(up.json()["status"], "ok", up.text) - file_id = next(f["id"] for f in self.client.get("/api/csv/files").json() - if f["file_name"] == self.name) + file_id = next(f["id"] for f in self.client.get("/api/csv/files").json() if f["file_name"] == self.name) delete = self.client.delete(f"/api/csv/files/{file_id}") # setUpClass enables API_ALLOW_DESTRUCTIVE for this class, so a 403 here # means the gate itself changed, not that the environment is misconfigured. self.assertEqual( - delete.status_code, 200, + delete.status_code, + 200, f"delete was refused despite the class enabling it: {delete.text}", ) @@ -441,17 +426,16 @@ def test_upload_then_delete_leaves_both_rows(self): def test_duplicate_upload_writes_no_second_audit_row(self): """Only a genuine load is audited. A refused duplicate changed nothing, so logging it would make the trail read as if data had landed twice.""" - first = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + first = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) self.assertEqual(first.json()["status"], "ok", first.text) - second = self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + second = self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) self.assertEqual(second.json()["status"], "duplicate_file", second.text) uploads = [e for e in self._entries_for(self.name) if e["action"] == "upload"] self.assertEqual( - len(uploads), 1, + len(uploads), + 1, "a refused duplicate must not add a second 'upload' row", ) @@ -459,18 +443,17 @@ def test_failed_upload_writes_no_audit_row(self): """A header-only file is rejected before any rows land, so there is nothing to audit.""" bad = f"audit_fail_{os.getpid()}.csv" - resp = self.client.post("/api/csv/upload", - json={"fileName": bad, "content": "col_a\n"}) + resp = self.client.post("/api/csv/upload", json={"fileName": bad, "content": "col_a\n"}) self.assertIn(resp.json()["status"], ("invalid_structure", "error")) self.assertEqual( - self._entries_for(bad), [], + self._entries_for(bad), + [], "a failed upload must not leave an audit row", ) def test_audit_endpoint_reports_a_total_and_respects_limit(self): """Pagination contract, so a grower table stays consultable.""" - self.client.post("/api/csv/upload", - json={"fileName": self.name, "content": self.content}) + self.client.post("/api/csv/upload", json={"fileName": self.name, "content": self.content}) body = self.client.get("/api/audit/log", params={"limit": 1}).json() self.assertGreaterEqual(body["total"], 1) self.assertEqual(body["limit"], 1) @@ -491,18 +474,24 @@ class PoolTimeout(unittest.TestCase): def setUpClass(cls): # Save the original pool so we can restore it after the test. from api import db + cls.db = db cls.orig_pool = db._pool cls.orig_executor = db._getconn_executor cls.orig_timeout = db.settings.POOL_GETCONN_TIMEOUT - import psycopg2.pool from concurrent.futures import ThreadPoolExecutor + + import psycopg2.pool + try: db._pool = psycopg2.pool.ThreadedConnectionPool( - minconn=1, maxconn=2, - host=db.settings.PG_HOST, port=db.settings.PG_PORT, - user=db.settings.PG_USER, password=db.settings.PG_PASSWORD.get_secret_value(), + minconn=1, + maxconn=2, + host=db.settings.PG_HOST, + port=db.settings.PG_PORT, + user=db.settings.PG_USER, + password=db.settings.PG_PASSWORD.get_secret_value(), dbname=db.settings.PG_DATABASE, ) except Exception as exc: # noqa: BLE001 @@ -511,9 +500,7 @@ def setUpClass(cls): f" {type(exc).__name__}: {str(exc).strip().splitlines()[0]}\n" f"{_HELP}" ) from None - db._getconn_executor = ThreadPoolExecutor( - max_workers=4, thread_name_prefix="test-pool-getconn" - ) + db._getconn_executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="test-pool-getconn") db.settings.POOL_GETCONN_TIMEOUT = 0.5 # keep the test fast @classmethod @@ -533,7 +520,9 @@ def test_exhausted_pool_raises_within_timeout(self): behaviour, not a regression. """ import time + import psycopg2.pool + # Borrow both slots and hold them. c1 = self.db._pool.getconn() c2 = self.db._pool.getconn() @@ -546,9 +535,10 @@ def test_exhausted_pool_raises_within_timeout(self): # started blocking (a bug or a future psycopg2 change) and our # timeout wrapper failed to fire — exactly what BUG-030 guards. self.assertLess( - elapsed, 3.0, - f"BUG-030 regression: getconn blocked {elapsed:.2f}s " - f"instead of raising within POOL_GETCONN_TIMEOUT") + elapsed, + 3.0, + f"BUG-030 regression: getconn blocked {elapsed:.2f}s instead of raising within POOL_GETCONN_TIMEOUT", + ) self.assertIn("pool", str(ctx.exception).lower()) finally: self.db._pool.putconn(c1) diff --git a/tests/system/test_audit_append_only.py b/tests/system/test_audit_append_only.py index bd6d808..67c1ecb 100644 --- a/tests/system/test_audit_append_only.py +++ b/tests/system/test_audit_append_only.py @@ -13,9 +13,9 @@ import psycopg2 import pytest -from alembic import command from alembic.config import Config +from alembic import command from api.config import settings from api.services.audit import acting_as, verify_chain, write_audit @@ -24,8 +24,13 @@ def _connect(): try: - return psycopg2.connect(host=settings.PG_HOST, port=settings.PG_PORT, user=settings.PG_USER, - password=settings.PG_PASSWORD.get_secret_value(), dbname=settings.PG_DATABASE) + return psycopg2.connect( + host=settings.PG_HOST, + port=settings.PG_PORT, + user=settings.PG_USER, + password=settings.PG_PASSWORD.get_secret_value(), + dbname=settings.PG_DATABASE, + ) except psycopg2.OperationalError as exc: raise AssertionError(f"Database unreachable: {exc}") from None @@ -36,13 +41,13 @@ def setUp(self): self.original = settings.UPLOADS_SCHEMA settings.UPLOADS_SCHEMA = self.schema = f"audit_test_{uuid.uuid4().hex[:10]}" self.cfg = Config(_ALEMBIC_INI) - self.cfg.attributes["scope"] = "tenant" # per-tenant tables only; leave the control schema alone + self.cfg.attributes["scope"] = "tenant" # per-tenant tables only; leave the control schema alone self.conn = _connect() def tearDown(self): self.conn.rollback() with self.conn.cursor() as cur: - cur.execute(f'DROP SCHEMA IF EXISTS "{self.schema}" CASCADE') # DROP isn't blocked + cur.execute(f'DROP SCHEMA IF EXISTS "{self.schema}" CASCADE') # DROP isn't blocked self.conn.commit() self.conn.close() settings.UPLOADS_SCHEMA = self.original @@ -140,7 +145,9 @@ def test_downgrade_removes_the_triggers_and_columns(self): command.downgrade(self.cfg, "0005") self._sql("UPDATE {t} SET file_name = 'allowed again'") with self.conn.cursor() as cur: - cur.execute("SELECT count(*) FROM information_schema.columns " - "WHERE table_schema = %s AND table_name = 'audit_log' AND column_name = 'row_hash'", - (self.schema,)) + cur.execute( + "SELECT count(*) FROM information_schema.columns " + "WHERE table_schema = %s AND table_name = 'audit_log' AND column_name = 'row_hash'", + (self.schema,), + ) self.assertEqual(cur.fetchone()[0], 0) diff --git a/tests/system/test_check_oidc.py b/tests/system/test_check_oidc.py index 95ed1c7..eacc092 100644 --- a/tests/system/test_check_oidc.py +++ b/tests/system/test_check_oidc.py @@ -31,7 +31,7 @@ def _script(): spec = importlib.util.spec_from_file_location("check_oidc", _SCRIPT) module = importlib.util.module_from_spec(spec) - sys.modules[spec.name] = module # @dataclass looks its module up here + sys.modules[spec.name] = module # @dataclass looks its module up here spec.loader.exec_module(module) return module @@ -53,8 +53,17 @@ def __init__(self, status: int = 200): class Handler(BaseHTTPRequestHandler): def do_POST(self): # noqa: N802 outer.seen.append(json.loads(self.rfile.read(int(self.headers["Content-Length"])))) - body = json.dumps({"token": "SESSION-SECRET-TOKEN", "username": "alice", "tenant": "acme", "role": "reviewer", - "expiresAt": "2026-11-10T00:00:00+00:00"} if status == 200 else {"detail": "no"}).encode() + body = json.dumps( + { + "token": "SESSION-SECRET-TOKEN", + "username": "alice", + "tenant": "acme", + "role": "reviewer", + "expiresAt": "2026-11-10T00:00:00+00:00", + } + if status == 200 + else {"detail": "no"} + ).encode() self.send_response(status) self.send_header("Content-Length", str(len(body))) self.end_headers() @@ -75,7 +84,12 @@ def close(self): class _Base(unittest.TestCase): def setUp(self): self.script = _script() - self._orig = (settings.OIDC_ISSUER, settings.OIDC_AUDIENCE, settings.OIDC_JWKS_URL, settings.OIDC_USERNAME_CLAIM) + self._orig = ( + settings.OIDC_ISSUER, + settings.OIDC_AUDIENCE, + settings.OIDC_JWKS_URL, + settings.OIDC_USERNAME_CLAIM, + ) oidc._jwks.cache_clear() self.key = new_key() self.idp = LocalIdp({"k1": self.key}) @@ -101,8 +115,11 @@ def by_step(self, results): class EveryStageCanPass(_Base): def test_a_good_token_passes_every_stage(self): results = self.script.run_checks(self.token()) - self.assertEqual([(r.step, r.status) for r in results], - [("config", "ok"), ("discovery", "ok"), ("keys", "ok"), ("token", "ok")], results) + self.assertEqual( + [(r.step, r.status) for r in results], + [("config", "ok"), ("discovery", "ok"), ("keys", "ok"), ("token", "ok")], + results, + ) self.assertIn("1 signing key(s): k1", results[2].detail) self.assertIn("preferred_username = 'alice'", results[3].detail) @@ -126,22 +143,25 @@ def test_plain_http_key_url(self): self.assertIn("https:// or file://", self.script.run_checks("x")[0].detail) def test_an_issuer_that_differs_from_the_idps_own_is_a_warning_naming_both(self): - settings.OIDC_ISSUER = self.idp.issuer + "/" # the classic trailing slash; discovery lives at the same base + settings.OIDC_ISSUER = self.idp.issuer + "/" # the classic trailing slash; discovery lives at the same base discovery = self.by_step(self.script.run_checks(self.token()))["discovery"] self.assertEqual(discovery.status, "warn") self.assertIn("trailing slash", discovery.detail) def test_a_certificate_the_host_does_not_trust_says_what_to_set(self): - with patch.dict(os.environ): # restored on exit - os.environ.pop("SSL_CERT_FILE", None) # the host doesn't know this IdP's CA + with patch.dict(os.environ): # restored on exit + os.environ.pop("SSL_CERT_FILE", None) # the host doesn't know this IdP's CA keys = self.by_step(self.script.run_checks(self.token(), discovery=False))["keys"] self.assertEqual(keys.status, "fail") self.assertIn("SSL_CERT_FILE", keys.detail) def test_wrong_audience_expired_and_wrong_issuer_each_say_why(self): now = int(time.time()) - cases = {"OIDC_AUDIENCE": self.token(aud="another-app"), "expired": self.token(exp=now - 5, iat=now - 400), - "`iss` must equal": self.token(iss="https://evil.example/realms/te")} + cases = { + "OIDC_AUDIENCE": self.token(aud="another-app"), + "expired": self.token(exp=now - 5, iat=now - 400), + "`iss` must equal": self.token(iss="https://evil.example/realms/te"), + } for expected, token in cases.items(): result = self.by_step(self.script.run_checks(token, discovery=False))["token"] self.assertEqual(result.status, "fail", expected) @@ -206,7 +226,7 @@ def test_no_token_is_exit_two_and_the_token_is_not_a_command_line_argument(self) self.assertEqual(code, 2) self.assertIn("ID_TOKEN", err) with self.assertRaises(SystemExit): - self.run_main("--token", "abc") # no such option: a token on the command line is refused + self.run_main("--token", "abc") # no such option: a token on the command line is refused def test_token_from_a_file(self): path = Path(os.environ.get("TMPDIR", "/tmp")) / f"idtoken_{os.getpid()}.txt" diff --git a/tests/system/test_concurrent_migrations.py b/tests/system/test_concurrent_migrations.py index 7787601..58519c4 100644 --- a/tests/system/test_concurrent_migrations.py +++ b/tests/system/test_concurrent_migrations.py @@ -9,6 +9,7 @@ scratch schemas. Asserted: both exit 0 and ``alembic_version`` is head, 10 of 10 trials, on a fresh schema and on one a revision behind. Needs a live PostgreSQL, as in CI. """ + from __future__ import annotations import os @@ -53,18 +54,27 @@ def _error_line(result: subprocess.CompletedProcess) -> str: def _connect(): - return psycopg2.connect(host=settings.PG_HOST, port=settings.PG_PORT, user=settings.PG_USER, - password=settings.PG_PASSWORD.get_secret_value(), dbname=settings.PG_DATABASE) + return psycopg2.connect( + host=settings.PG_HOST, + port=settings.PG_PORT, + user=settings.PG_USER, + password=settings.PG_PASSWORD.get_secret_value(), + dbname=settings.PG_DATABASE, + ) @pytest.mark.integration class ConcurrentStartupMigrations(unittest.TestCase): - def setUp(self): tag = uuid.uuid4().hex[:10] self.uploads, self.control = f"mig_cc_{tag}", f"mig_ccc_{tag}" - self.env = {**os.environ, "CSV_UPLOADS_SCHEMA": self.uploads, "CONTROL_SCHEMA": self.control, - "ALEMBIC_INI": INI, "PYTHONPATH": str(ROOT)} + self.env = { + **os.environ, + "CSV_UPLOADS_SCHEMA": self.uploads, + "CONTROL_SCHEMA": self.control, + "ALEMBIC_INI": INI, + "PYTHONPATH": str(ROOT), + } self.conn = _connect() self.conn.autocommit = True @@ -79,8 +89,17 @@ def _drop(self): def _run(self, target: str, n: int) -> list[subprocess.CompletedProcess]: start_at = f"{time.time() + 2.0:.3f}" - procs = [subprocess.Popen([sys.executable, "-c", _WORKER, target, start_at], cwd=ROOT, env=self.env, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for _ in range(n)] + procs = [ + subprocess.Popen( + [sys.executable, "-c", _WORKER, target, start_at], + cwd=ROOT, + env=self.env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + for _ in range(n) + ] out = [] for p in procs: stdout, stderr = p.communicate(timeout=120) diff --git a/tests/system/test_create_tenant_admin.py b/tests/system/test_create_tenant_admin.py index 8b38167..e5eccf9 100644 --- a/tests/system/test_create_tenant_admin.py +++ b/tests/system/test_create_tenant_admin.py @@ -41,8 +41,13 @@ def _connect(): - return psycopg2.connect(host=settings.PG_HOST, port=settings.PG_PORT, user=settings.PG_USER, - password=settings.PG_PASSWORD.get_secret_value(), dbname=settings.PG_DATABASE) + return psycopg2.connect( + host=settings.PG_HOST, + port=settings.PG_PORT, + user=settings.PG_USER, + password=settings.PG_PASSWORD.get_secret_value(), + dbname=settings.PG_DATABASE, + ) @pytest.mark.integration @@ -62,14 +67,28 @@ def _env(self, password: str | None = PASSWORD) -> dict: def run_script(self, *args: str, password: str | None = PASSWORD) -> subprocess.CompletedProcess: """No terminal: stdin is closed, and stderr is captured so it is not one either.""" - return subprocess.run([sys.executable, str(SCRIPT), *args], cwd=ROOT, env=self._env(password), - capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) + return subprocess.run( + [sys.executable, str(SCRIPT), *args], + cwd=ROOT, + env=self._env(password), + capture_output=True, + text=True, + timeout=120, + stdin=subprocess.DEVNULL, + ) def run_interactive(self, *args: str, answer: str, password: str | None = PASSWORD) -> tuple[int, str]: """Run the script with a pseudo-terminal and type ``answer`` at it.""" master, slave = pty.openpty() - proc = subprocess.Popen([sys.executable, str(SCRIPT), *args], cwd=ROOT, env=self._env(password), - stdin=slave, stdout=slave, stderr=slave, close_fds=True) + proc = subprocess.Popen( + [sys.executable, str(SCRIPT), *args], + cwd=ROOT, + env=self._env(password), + stdin=slave, + stdout=slave, + stderr=slave, + close_fds=True, + ) os.close(slave) out = b"" try: @@ -94,10 +113,19 @@ def run_interactive(self, *args: str, answer: str, password: str | None = PASSWO os.close(master) return proc.returncode, out.decode("utf-8", errors="replace") - def create(self, *extra: str, user: str | None = None, tenant: str | None = None, - password: str = PASSWORD) -> subprocess.CompletedProcess: - res = self.run_script("--tenant", tenant or self.tenant, "--name", "Original name", - "--username", user or self.user, *extra, password=password) + def create( + self, *extra: str, user: str | None = None, tenant: str | None = None, password: str = PASSWORD + ) -> subprocess.CompletedProcess: + res = self.run_script( + "--tenant", + tenant or self.tenant, + "--name", + "Original name", + "--username", + user or self.user, + *extra, + password=password, + ) return res def _q(self, query: str, *params): @@ -114,9 +142,12 @@ def password_hash(self, user: str) -> str | None: return rows[0][0] if rows else None def role(self, tenant: str, user: str) -> str | None: - rows = self._q("SELECT m.role FROM {c}.memberships m JOIN {c}.users u ON u.id = m.user_id " - "JOIN {c}.tenants t ON t.id = m.tenant_id WHERE t.slug = %s AND u.username = %s", - tenant, user) + rows = self._q( + "SELECT m.role FROM {c}.memberships m JOIN {c}.users u ON u.id = m.user_id " + "JOIN {c}.tenants t ON t.id = m.tenant_id WHERE t.slug = %s AND u.username = %s", + tenant, + user, + ) return rows[0][0] if rows else None def tenant_name(self, tenant: str) -> str | None: @@ -133,16 +164,31 @@ def _cleanup(self): try: with _connect() as conn, conn.cursor() as cur: names = [self.user, self.new_user] - cur.execute(sql.SQL("DELETE FROM {c}.sessions WHERE user_id IN " - "(SELECT id FROM {c}.users WHERE username = ANY(%s))") - .format(c=sql.Identifier(settings.CONTROL_SCHEMA)), (names,)) - cur.execute(sql.SQL("DELETE FROM {c}.memberships WHERE user_id IN " - "(SELECT id FROM {c}.users WHERE username = ANY(%s))") - .format(c=sql.Identifier(settings.CONTROL_SCHEMA)), (names,)) - cur.execute(sql.SQL("DELETE FROM {c}.users WHERE username = ANY(%s)") - .format(c=sql.Identifier(settings.CONTROL_SCHEMA)), (names,)) - cur.execute(sql.SQL("DELETE FROM {c}.tenants WHERE slug = %s") - .format(c=sql.Identifier(settings.CONTROL_SCHEMA)), (self.tenant,)) + cur.execute( + sql.SQL( + "DELETE FROM {c}.sessions WHERE user_id IN (SELECT id FROM {c}.users WHERE username = ANY(%s))" + ).format(c=sql.Identifier(settings.CONTROL_SCHEMA)), + (names,), + ) + cur.execute( + sql.SQL( + "DELETE FROM {c}.memberships WHERE user_id IN " + "(SELECT id FROM {c}.users WHERE username = ANY(%s))" + ).format(c=sql.Identifier(settings.CONTROL_SCHEMA)), + (names,), + ) + cur.execute( + sql.SQL("DELETE FROM {c}.users WHERE username = ANY(%s)").format( + c=sql.Identifier(settings.CONTROL_SCHEMA) + ), + (names,), + ) + cur.execute( + sql.SQL("DELETE FROM {c}.tenants WHERE slug = %s").format( + c=sql.Identifier(settings.CONTROL_SCHEMA) + ), + (self.tenant,), + ) cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(self.tenant)))) except psycopg2.Error: pass # best effort: a leftover test tenant is harmless, and a failed cleanup must not mask a result @@ -205,8 +251,9 @@ def test_a_new_admin_for_an_existing_tenant_is_not_added_unless_accepted(self): res = self.create(user=self.new_user, password=OTHER_PASSWORD) self.assertEqual(res.returncode, 1, res.stderr) self.assertIn("--use-existing", res.stderr) - self.assertEqual(self.existing(user=self.new_user), accounts.Existing(True, False, False), - "no account was created") + self.assertEqual( + self.existing(user=self.new_user), accounts.Existing(True, False, False), "no account was created" + ) def test_use_existing_does_not_apply_to_a_tenant_that_does_not_exist(self): res = self.create("--use-existing") @@ -242,14 +289,24 @@ def _drop_tenant(self, slug: str): try: with _connect() as conn, conn.cursor() as cur: names = [self.user, self.new_user] - for stmt in ("DELETE FROM {c}.sessions WHERE tenant_id IN (SELECT id FROM {c}.tenants WHERE slug = %s)", - "DELETE FROM {c}.memberships WHERE tenant_id IN (SELECT id FROM {c}.tenants WHERE slug = %s)"): + for stmt in ( + "DELETE FROM {c}.sessions WHERE tenant_id IN (SELECT id FROM {c}.tenants WHERE slug = %s)", + "DELETE FROM {c}.memberships WHERE tenant_id IN (SELECT id FROM {c}.tenants WHERE slug = %s)", + ): cur.execute(sql.SQL(stmt).format(c=sql.Identifier(settings.CONTROL_SCHEMA)), (slug,)) - cur.execute(sql.SQL("DELETE FROM {c}.users WHERE username = ANY(%s) AND NOT EXISTS " - "(SELECT 1 FROM {c}.memberships m WHERE m.user_id = {c}.users.id)") - .format(c=sql.Identifier(settings.CONTROL_SCHEMA)), (names,)) - cur.execute(sql.SQL("DELETE FROM {c}.tenants WHERE slug = %s") - .format(c=sql.Identifier(settings.CONTROL_SCHEMA)), (slug,)) + cur.execute( + sql.SQL( + "DELETE FROM {c}.users WHERE username = ANY(%s) AND NOT EXISTS " + "(SELECT 1 FROM {c}.memberships m WHERE m.user_id = {c}.users.id)" + ).format(c=sql.Identifier(settings.CONTROL_SCHEMA)), + (names,), + ) + cur.execute( + sql.SQL("DELETE FROM {c}.tenants WHERE slug = %s").format( + c=sql.Identifier(settings.CONTROL_SCHEMA) + ), + (slug,), + ) cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(slug)))) except psycopg2.Error: pass @@ -259,8 +316,9 @@ def _drop_tenant(self, slug: str): @unittest.skipIf(pty is None, "needs a pseudo-terminal") def test_a_person_is_asked_and_y_uses_the_existing_tenant(self): before = self.seed() - code, out = self.run_interactive("--tenant", self.tenant, "--name", "Original name", - "--username", self.user, answer="y\n", password=None) + code, out = self.run_interactive( + "--tenant", self.tenant, "--name", "Original name", "--username", self.user, answer="y\n", password=None + ) self.assertEqual(code, 0, out) self.assertIn("already exists", out) self.assertIn("[y/N]", out, "the question was asked") @@ -271,8 +329,16 @@ def test_a_person_is_asked_and_y_uses_the_existing_tenant(self): @unittest.skipIf(pty is None, "needs a pseudo-terminal") def test_n_changes_nothing(self): before = self.seed() - code, out = self.run_interactive("--tenant", self.tenant, "--name", "Original name", - "--username", self.new_user, answer="n\n", password=OTHER_PASSWORD) + code, out = self.run_interactive( + "--tenant", + self.tenant, + "--name", + "Original name", + "--username", + self.new_user, + answer="n\n", + password=OTHER_PASSWORD, + ) self.assertEqual(code, 1, out) self.assertIn("[y/N]", out) self.assertIn("Nothing was changed", out) @@ -282,16 +348,32 @@ def test_n_changes_nothing(self): @unittest.skipIf(pty is None, "needs a pseudo-terminal") def test_pressing_enter_alone_means_no(self): self.seed() - code, out = self.run_interactive("--tenant", self.tenant, "--name", "Original name", - "--username", self.new_user, answer="\n", password=OTHER_PASSWORD) + code, out = self.run_interactive( + "--tenant", + self.tenant, + "--name", + "Original name", + "--username", + self.new_user, + answer="\n", + password=OTHER_PASSWORD, + ) self.assertEqual(code, 1, out) self.assertEqual(self.existing(user=self.new_user), accounts.Existing(True, False, False)) @unittest.skipIf(pty is None, "needs a pseudo-terminal") def test_y_adds_a_new_admin_to_the_existing_tenant(self): self.seed() - code, out = self.run_interactive("--tenant", self.tenant, "--name", "Original name", - "--username", self.new_user, answer="yes\n", password=OTHER_PASSWORD) + code, out = self.run_interactive( + "--tenant", + self.tenant, + "--name", + "Original name", + "--username", + self.new_user, + answer="yes\n", + password=OTHER_PASSWORD, + ) self.assertEqual(code, 0, out) self.assertIn("add", out.lower()) self.assertEqual(self.role(self.tenant, self.new_user), "tenant_admin") @@ -299,8 +381,9 @@ def test_y_adds_a_new_admin_to_the_existing_tenant(self): @unittest.skipIf(pty is None, "needs a pseudo-terminal") def test_a_new_tenant_is_created_without_a_question(self): - code, out = self.run_interactive("--tenant", self.tenant, "--name", "Original name", - "--username", self.user, answer="") + code, out = self.run_interactive( + "--tenant", self.tenant, "--name", "Original name", "--username", self.user, answer="" + ) self.assertEqual(code, 0, out) self.assertNotIn("[y/N]", out) self.assertIn(f"Created tenant '{self.tenant}'", out) diff --git a/tests/system/test_egress_network_blocked.py b/tests/system/test_egress_network_blocked.py index 0f6a976..603e835 100644 --- a/tests/system/test_egress_network_blocked.py +++ b/tests/system/test_egress_network_blocked.py @@ -9,6 +9,7 @@ They only make sense behind that firewall, so ``tests/conftest.py`` leaves them out of every other run (marker ``egress_network``, set ``EGRESS_NETWORK_BLOCKED=1`` to include them). On an open network they would connect. """ + from __future__ import annotations import errno @@ -22,7 +23,7 @@ pytestmark = pytest.mark.egress_network -OUTSIDE = "93.184.216.34" # a public address; the firewall must refuse before anything is sent +OUTSIDE = "93.184.216.34" # a public address; the firewall must refuse before anything is sent REFUSED = {errno.ECONNREFUSED, errno.ENETUNREACH, errno.EHOSTUNREACH, errno.EPERM, errno.EACCES} SOCKET_CHILD = f""" diff --git a/tests/system/test_failed_uploads.py b/tests/system/test_failed_uploads.py index cffc221..61cf72a 100644 --- a/tests/system/test_failed_uploads.py +++ b/tests/system/test_failed_uploads.py @@ -26,8 +26,9 @@ def setUp(self): self.registry_cleanup.append(self.name) def _upload(self, content: str, types: list[str], overwrite: bool = False) -> dict: - return self.client.post("/api/csv/upload", json={ - "fileName": self.name, "content": content, "types": types, "overwrite": overwrite}).json() + return self.client.post( + "/api/csv/upload", json={"fileName": self.name, "content": content, "types": types, "overwrite": overwrite} + ).json() def _registered(self) -> list[dict]: return [f for f in self.client.get("/api/csv/files").json() if f["file_name"] == self.name] diff --git a/tests/system/test_header_mapping.py b/tests/system/test_header_mapping.py index 2b541a0..e05aa51 100644 --- a/tests/system/test_header_mapping.py +++ b/tests/system/test_header_mapping.py @@ -12,8 +12,10 @@ from api.main import app from api.services.csv_parse import apply_header_mapping -_HELP = ("Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" - "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" + "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1." +) @pytest.mark.unit @@ -40,7 +42,8 @@ def test_unknown_original_is_rejected(self): def test_original_listed_twice_is_rejected(self): _, err = apply_header_mapping( - ["foo"], [{"original": "foo", "renamed": "a"}, {"original": "foo", "renamed": "b"}]) + ["foo"], [{"original": "foo", "renamed": "a"}, {"original": "foo", "renamed": "b"}] + ) self.assertIn("more than once", err) def test_rename_colliding_with_an_untouched_column_is_rejected(self): @@ -54,7 +57,8 @@ def test_collision_is_judged_after_sanitising(self): def test_swapping_two_names_is_allowed(self): out, err = apply_header_mapping( - ["a", "b"], [{"original": "a", "renamed": "b"}, {"original": "b", "renamed": "a"}]) + ["a", "b"], [{"original": "a", "renamed": "b"}, {"original": "b", "renamed": "a"}] + ) self.assertEqual((out, err), (["b", "a"], None)) @@ -118,12 +122,15 @@ def test_rename_that_collides_with_another_column_is_an_error(self): self.assertEqual((res["status"], res["reason"]), ("error", "invalid_header_mapping")) def test_te_mode_rejects_a_header_mapping_instead_of_ignoring_it(self): - resp = self.client.post("/api/csv/upload", json={ - "fileName": f"hdrmap_te_{self.tag}.csv", - "content": "a,b\n1,2\n", - "mode": "te", - "targetTable": "organisations", - "headerMapping": [{"original": "a", "renamed": "b"}], - }) + resp = self.client.post( + "/api/csv/upload", + json={ + "fileName": f"hdrmap_te_{self.tag}.csv", + "content": "a,b\n1,2\n", + "mode": "te", + "targetTable": "organisations", + "headerMapping": [{"original": "a", "renamed": "b"}], + }, + ) self.assertEqual(resp.status_code, 422) self.assertIn("dynamic", resp.json()["detail"]) diff --git a/tests/system/test_import_counts.py b/tests/system/test_import_counts.py index ed12fd1..d995ed1 100644 --- a/tests/system/test_import_counts.py +++ b/tests/system/test_import_counts.py @@ -14,8 +14,10 @@ from api.main import app -_HELP = ("Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" - "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" + "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1." +) @pytest.mark.integration @@ -50,21 +52,32 @@ def _assert_persisted_matches_response(self, res: dict) -> dict: def test_dynamic_import_persists_all_four_counts(self): # 5 data rows: 2 valid distinct, 1 in-file duplicate, 2 that fail the int8 cast. content = f"n,t\n1,{self.tag}\n2,{self.tag}\n1,{self.tag}\nx,{self.tag}\ny,{self.tag}\n" - res = self.client.post("/api/csv/upload", json={ - "fileName": f"counts_{self.tag}.csv", "content": content, "types": ["int8", "text"], - }).json() + res = self.client.post( + "/api/csv/upload", + json={ + "fileName": f"counts_{self.tag}.csv", + "content": content, + "types": ["int8", "text"], + }, + ).json() self.assertEqual(res["status"], "ok", res) entry = self._assert_persisted_matches_response(res) - self.assertEqual((entry["total_rows"], entry["row_count"], entry["duplicate_rows_skipped"], - entry["failed_rows"]), (5, 2, 1, 2)) + self.assertEqual( + (entry["total_rows"], entry["row_count"], entry["duplicate_rows_skipped"], entry["failed_rows"]), + (5, 2, 1, 2), + ) def test_te_import_persists_counts(self): - content = (f"name,org_type,country\nCNT_{self.tag}_1,government,AU\n" - f"CNT_{self.tag}_2,government,AU\n") - res = self.client.post("/api/csv/upload", json={ - "fileName": f"counts_te_{self.tag}.csv", "content": content, - "mode": "te", "targetTable": "organisations", - }).json() + content = f"name,org_type,country\nCNT_{self.tag}_1,government,AU\nCNT_{self.tag}_2,government,AU\n" + res = self.client.post( + "/api/csv/upload", + json={ + "fileName": f"counts_te_{self.tag}.csv", + "content": content, + "mode": "te", + "targetTable": "organisations", + }, + ).json() self.assertEqual(res["status"], "ok", res) entry = self._assert_persisted_matches_response(res) self.assertEqual((entry["total_rows"], entry["row_count"], entry["failed_rows"]), (2, 2, 0)) diff --git a/tests/system/test_issue_04_multi_file_upload.py b/tests/system/test_issue_04_multi_file_upload.py index 4982e9c..10062d9 100644 --- a/tests/system/test_issue_04_multi_file_upload.py +++ b/tests/system/test_issue_04_multi_file_upload.py @@ -22,6 +22,7 @@ Requires a reachable database; per the repository's no-skip policy a missing prerequisite FAILS with remediation text rather than skipping. """ + from __future__ import annotations import os @@ -32,10 +33,12 @@ from api.main import app -_HELP = ("Start PostgreSQL and ensure api/ can reach it. Most often this means " - "PGPASSWORD is not set in this shell:\n" - " PowerShell: $env:PGPASSWORD = ''\n" - " bash: export PGPASSWORD=''") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it. Most often this means " + "PGPASSWORD is not set in this shell:\n" + " PowerShell: $env:PGPASSWORD = ''\n" + " bash: export PGPASSWORD=''" +) # How many files to push through in the "any number" test. Kept modest so the # suite stays fast; the point is that the API imposes no limit, not throughput. @@ -77,8 +80,7 @@ def tearDown(self): def _upload(self, name: str, content: str) -> dict: self.uploaded.append(name) - r = self.client.post("/api/csv/upload", - json={"fileName": name, "content": content}) + r = self.client.post("/api/csv/upload", json={"fileName": name, "content": content}) self.assertEqual(r.status_code, 200, r.text[:300]) return r.json() @@ -88,13 +90,11 @@ def test_many_files_upload_in_one_session(self): """Uploading several files in sequence must all succeed.""" tables = [] for i in range(BATCH_SIZE): - body = self._upload(f"{self.tag}_{i}.csv", - f"col_a,col_b\n{self.tag},{i}\n") + body = self._upload(f"{self.tag}_{i}.csv", f"col_a,col_b\n{self.tag},{i}\n") self.assertEqual(body["status"], "ok", body) tables.append(body["tableName"]) - self.assertEqual(len(set(tables)), BATCH_SIZE, - f"each file needs its own table, got {tables}") + self.assertEqual(len(set(tables)), BATCH_SIZE, f"each file needs its own table, got {tables}") def test_every_uploaded_file_is_listed(self): """All uploads appear in /api/csv/files — this drives 'Migrated files'.""" @@ -108,8 +108,7 @@ def test_every_uploaded_file_is_listed(self): def test_each_file_is_independently_readable(self): """Rows from one upload must not leak into another's table.""" first = self._upload(f"{self.tag}_first.csv", f"col_a\n{self.tag}-first\n") - second = self._upload(f"{self.tag}_second.csv", - f"col_a\n{self.tag}-s1\n{self.tag}-s2\n") + second = self._upload(f"{self.tag}_second.csv", f"col_a\n{self.tag}-s1\n{self.tag}-s2\n") self.assertNotEqual(first["tableName"], second["tableName"]) @@ -134,10 +133,8 @@ def test_narrow_and_wide_files_both_load(self): def test_files_with_different_schemas_coexist(self): """Unrelated column sets must not collide — no shared fixed schema.""" - a = self._upload(f"{self.tag}_shape_a.csv", - f"name,email\n{self.tag},a@example.com\n") - b = self._upload(f"{self.tag}_shape_b.csv", - f"sku,qty,price\n{self.tag},3,9.99\n") + a = self._upload(f"{self.tag}_shape_a.csv", f"name,email\n{self.tag},a@example.com\n") + b = self._upload(f"{self.tag}_shape_b.csv", f"sku,qty,price\n{self.tag},3,9.99\n") self.assertEqual(a["columns"], ["name", "email"]) self.assertEqual(b["columns"], ["sku", "qty", "price"]) @@ -149,5 +146,4 @@ def test_a_larger_file_loads_completely(self): body = self._upload(f"{self.tag}_bulk.csv", f"col_a,col_b\n{rows}\n") self.assertEqual(body["status"], "ok", body) self.assertEqual(body["totalRows"], 250) - self.assertEqual(body["insertedRows"], 250, - "all distinct rows should load") + self.assertEqual(body["insertedRows"], 250, "all distinct rows should load") diff --git a/tests/system/test_issue_05_import_summary.py b/tests/system/test_issue_05_import_summary.py index 1e52a4c..8d8f38c 100644 --- a/tests/system/test_issue_05_import_summary.py +++ b/tests/system/test_issue_05_import_summary.py @@ -28,6 +28,7 @@ Requires a reachable database; per the repository's no-skip policy a missing prerequisite FAILS with remediation text rather than skipping. """ + from __future__ import annotations import os @@ -39,10 +40,12 @@ from api.config import settings from api.main import app -_HELP = ("Start PostgreSQL and ensure api/ can reach it. Most often this means " - "PGPASSWORD is not set in this shell:\n" - " PowerShell: $env:PGPASSWORD = ''\n" - " bash: export PGPASSWORD=''") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it. Most often this means " + "PGPASSWORD is not set in this shell:\n" + " PowerShell: $env:PGPASSWORD = ''\n" + " bash: export PGPASSWORD=''" +) SUMMARY_FIELDS = ("totalRows", "insertedRows", "duplicateRowsSkipped", "failedRows") @@ -107,17 +110,14 @@ def test_all_four_counts_are_returned(self): def test_total_rows_counts_data_rows_not_the_header(self): body = self._upload(f"col_a\n{self.tag}-1\n{self.tag}-2\n{self.tag}-3\n") - self.assertEqual(body["totalRows"], 3, - "header row must not be counted as data") + self.assertEqual(body["totalRows"], 3, "header row must not be counted as data") def test_created_count_matches_rows_actually_inserted(self): body = self._upload(f"col_a\n{self.tag}-1\n{self.tag}-2\n") self.assertEqual(body["insertedRows"], 2) - rows = self.client.get( - f"/api/csv/tables/{body['tableName']}/rows").json()["rows"] - self.assertEqual(len(rows), body["insertedRows"], - "insertedRows must match what is actually in the table") + rows = self.client.get(f"/api/csv/tables/{body['tableName']}/rows").json()["rows"] + self.assertEqual(len(rows), body["insertedRows"], "insertedRows must match what is actually in the table") def test_duplicate_count_reflects_repeated_rows_in_the_file(self): """Two identical rows plus one distinct: 1 duplicate skipped.""" @@ -138,8 +138,7 @@ def test_failed_count_reflects_rows_that_could_not_be_cast(self): types=["int8"], ) self.assertEqual(body["status"], "ok", body) - self.assertEqual(body["failedRows"], 1, - f"expected 1 uncastable row, got {body['failedRows']}") + self.assertEqual(body["failedRows"], 1, f"expected 1 uncastable row, got {body['failedRows']}") self.assertEqual(body["insertedRows"], 2) def test_failed_rows_are_reported_with_detail(self): @@ -180,7 +179,5 @@ def test_counts_are_per_batch_not_cumulative(self): first = self._upload(f"col_a\n{self.tag}-a\n", suffix="_first") self.assertEqual(first["totalRows"], 1) - second = self._upload( - f"col_a\n{self.tag}-b\n{self.tag}-c\n{self.tag}-d\n", suffix="_second") - self.assertEqual(second["totalRows"], 3, - "the summary must describe the current batch only") + second = self._upload(f"col_a\n{self.tag}-b\n{self.tag}-c\n{self.tag}-d\n", suffix="_second") + self.assertEqual(second["totalRows"], 3, "the summary must describe the current batch only") diff --git a/tests/system/test_issue_regressions.py b/tests/system/test_issue_regressions.py index 0df1069..7410429 100644 --- a/tests/system/test_issue_regressions.py +++ b/tests/system/test_issue_regressions.py @@ -42,6 +42,7 @@ def _csv(rows: list[list[str]]) -> str: # ── #183 ───────────────────────────────────────────────────────────────────── + def _request(api_key: str, host: str = "203.0.113.9") -> Request: return Request({"type": "http", "headers": [(b"x-api-key", api_key.encode())], "client": (host, 4321)}) @@ -80,6 +81,7 @@ def test_rotating_invalid_keys_from_one_client_share_one_budget(self): # ── #178 ───────────────────────────────────────────────────────────────────── + @pytest.mark.integration class RowDedupKeepsDistinctRows(unittest.TestCase): """#178: two different rows must not be skipped as duplicates because they serialise alike.""" @@ -97,8 +99,9 @@ def setUp(self): self.tag = f"{os.getpid()}_{uuid.uuid4().hex[:8]}" def _upload(self, rows: list[list[str]], name: str = "dedup") -> dict: - body = self.client.post("/api/csv/upload", json={ - "fileName": f"{name}_{self.tag}.csv", "content": _csv([["a", "b", "c"]] + rows)}).json() + body = self.client.post( + "/api/csv/upload", json={"fileName": f"{name}_{self.tag}.csv", "content": _csv([["a", "b", "c"]] + rows)} + ).json() self.assertEqual(body["status"], "ok", body) return body @@ -137,14 +140,18 @@ def test_stored_hashes_carry_the_version_marker(self): body = self._upload([["v", "2", self.tag]], "hashver") table = body["tableName"].split(".")[-1] with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT _row_hash FROM {}.{}").format( - sql.Identifier(settings.UPLOADS_SCHEMA), sql.Identifier(table))) + cur.execute( + sql.SQL("SELECT _row_hash FROM {}.{}").format( + sql.Identifier(settings.UPLOADS_SCHEMA), sql.Identifier(table) + ) + ) hashes = [r[0] for r in cur.fetchall()] self.assertTrue(hashes and all(h.startswith("v2:") for h in hashes), hashes) # ── #175 / #189 need a signed-in tenant ────────────────────────────────────── + @pytest.mark.integration class UploadPaths(unittest.TestCase): @classmethod @@ -161,8 +168,9 @@ def setUpClass(cls): conn.commit() migrate_tenant(cls.slug) for role in ROLES: - res = cls.client.post("/api/auth/login", json={ - "tenant": cls.slug, "username": f"{cls.slug}_{role}", "password": _PW}) + res = cls.client.post( + "/api/auth/login", json={"tenant": cls.slug, "username": f"{cls.slug}_{role}", "password": _PW} + ) assert res.status_code == 200, res.text cls.headers[role] = {"Authorization": f"Bearer {res.json()['token']}"} @@ -170,10 +178,14 @@ def setUpClass(cls): def tearDownClass(cls): with Conn() as conn, conn.cursor() as cur: cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(cls.slug)))) - cur.execute(sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (cls.slug,)) - cur.execute(sql.SQL("DELETE FROM {}.users WHERE username LIKE %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (f"{cls.slug}_%",)) + cur.execute( + sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format(sql.Identifier(settings.CONTROL_SCHEMA)), + (cls.slug,), + ) + cur.execute( + sql.SQL("DELETE FROM {}.users WHERE username LIKE %s").format(sql.Identifier(settings.CONTROL_SCHEMA)), + (f"{cls.slug}_%",), + ) conn.commit() cls.ctx.__exit__(None, None, None) @@ -207,8 +219,9 @@ def _registered_tables(self) -> set[str]: return {f["table_name"] for f in files} def _rows(self, table: str) -> list[str]: - res = self.client.get(f"/api/csv/tables/{table}/rows", headers=self.headers["tenant_admin"], - params={"limit": 50}) + res = self.client.get( + f"/api/csv/tables/{table}/rows", headers=self.headers["tenant_admin"], params={"limit": 50} + ) self.assertEqual(res.status_code, 200, res.text) return [r["k"] for r in res.json()["rows"]] @@ -223,19 +236,34 @@ def test_an_uploader_overwrite_leaves_the_existing_dataset_intact(self): def test_an_uploader_mode_switch_leaves_the_existing_dataset_intact(self): name = f"switch_{self.tag}.csv" original = self._dynamic(name)["tableName"] - res = self._post("uploader", fileName=name, mode="te", targetTable="organisations", - content=f"name,org_type,country\nORG_{self.tag},government,AU\n") + res = self._post( + "uploader", + fileName=name, + mode="te", + targetTable="organisations", + content=f"name,org_type,country\nORG_{self.tag},government,AU\n", + ) self.assertIn(res.status_code, (200, 403), res.text) self.assertIn(original, self._registered_tables(), "the existing dataset must still be registered") self.assertEqual(self._rows(original), [self.tag], "and its rows must be untouched") def test_an_uploader_cannot_replace_a_prior_te_load(self): name = f"te_{self.tag}.csv" - first = self._post("tenant_admin", fileName=name, mode="te", targetTable="organisations", - content=f"name,org_type,country\nORG_A_{self.tag},government,AU\n") + first = self._post( + "tenant_admin", + fileName=name, + mode="te", + targetTable="organisations", + content=f"name,org_type,country\nORG_A_{self.tag},government,AU\n", + ) self.assertEqual(first.json()["status"], "ok", first.text) - again = self._post("uploader", fileName=name, mode="te", targetTable="organisations", - content=f"name,org_type,country\nORG_B_{self.tag},government,AU\n") + again = self._post( + "uploader", + fileName=name, + mode="te", + targetTable="organisations", + content=f"name,org_type,country\nORG_B_{self.tag},government,AU\n", + ) self.assertEqual(again.status_code, 403, again.text) def test_a_tenant_admin_may_upload_the_same_name_again(self): @@ -254,13 +282,16 @@ class TeDatabaseErrorsNameTheSourceRow(UploadPaths): """#189: a row that fails in the database is reported by its CSV row, not its place among survivors.""" def test_type_failure_then_foreign_key_failure_report_rows_1_and_2(self): - content = _csv([ - ["org_id", "program_code", "program_name", "start_date"], - [str(uuid.uuid4()), f"P1_{self.tag}", "bad date", "not-a-date"], # row 1: fails the type check - [str(uuid.uuid4()), f"P2_{self.tag}", "no such org", "2026-01-01"], # row 2: fails the foreign key - ]) - res = self._post("tenant_admin", fileName=f"prog_{self.tag}.csv", mode="te", - targetTable="test_programs", content=content).json() + content = _csv( + [ + ["org_id", "program_code", "program_name", "start_date"], + [str(uuid.uuid4()), f"P1_{self.tag}", "bad date", "not-a-date"], # row 1: fails the type check + [str(uuid.uuid4()), f"P2_{self.tag}", "no such org", "2026-01-01"], # row 2: fails the foreign key + ] + ) + res = self._post( + "tenant_admin", fileName=f"prog_{self.tag}.csv", mode="te", targetTable="test_programs", content=content + ).json() by_row = {e["rowNumber"]: e for e in res["rowErrors"]} self.assertEqual(sorted(by_row), [1, 2], res) self.assertEqual(by_row[1].get("column"), "start_date") diff --git a/tests/system/test_loader_responses_golden.py b/tests/system/test_loader_responses_golden.py index c1abdfd..fb60e81 100644 --- a/tests/system/test_loader_responses_golden.py +++ b/tests/system/test_loader_responses_golden.py @@ -50,19 +50,37 @@ def corpus(t: str) -> list[tuple[str, dict]]: return [ ("good", _dyn(f"people_{t}.csv", f"id,name,qty\n1,a{t},5\n2,b,6\n")), ("same bytes again", _dyn(f"other_{t}.csv", f"id,name,qty\n1,a{t},5\n2,b,6\n")), - ("version 2, new column, one row repeated", _dyn(f"people_{t}.csv", f"id,name,qty,extra\n1,a{t},5,\n3,c,7,z\n")), - ("version 3, typed, one bad row", _dyn(f"people_{t}.csv", f"id,name,qty\n4,d{t},8\nx,e,9\n5,f,1.5\n", - types=["int8", "text", "numeric"], typesConfirmed=True)), + ( + "version 2, new column, one row repeated", + _dyn(f"people_{t}.csv", f"id,name,qty,extra\n1,a{t},5,\n3,c,7,z\n"), + ), + ( + "version 3, typed, one bad row", + _dyn( + f"people_{t}.csv", + f"id,name,qty\n4,d{t},8\nx,e,9\n5,f,1.5\n", + types=["int8", "text", "numeric"], + typesConfirmed=True, + ), + ), ("every row bad", _dyn(f"allbad_{t}.csv", f"n,tag\nx,{t}\ny,{t}\n", types=["int8", "text"])), ("ragged and short rows", _dyn(f"ragged_{t}.csv", f"a,b\n1,2,3\n4\n5,{t}\n")), ("in-file duplicates", _dyn(f"dupes_{t}.csv", f"a\n{t}\n{t}\n2\n")), ("empty", _dyn(f"empty_{t}.csv", "")), ("header only", _dyn(f"header_{t}.csv", "a,b\n")), ("blank header", _dyn(f"blank_{t}.csv", f",\n1,{t}\n")), - ("header rename", _dyn(f"rename_{t}.csv", f"Old Name,b\n1,{t}\n", - headerMapping=[{"original": "Old Name", "renamed": "new_name"}])), - ("bad header mapping", _dyn(f"rename2_{t}.csv", f"a\n{t}\n", - headerMapping=[{"original": "nope", "renamed": "x"}])), + ( + "header rename", + _dyn( + f"rename_{t}.csv", + f"Old Name,b\n1,{t}\n", + headerMapping=[{"original": "Old Name", "renamed": "new_name"}], + ), + ), + ( + "bad header mapping", + _dyn(f"rename2_{t}.csv", f"a\n{t}\n", headerMapping=[{"original": "nope", "renamed": "x"}]), + ), ("type count mismatch", _dyn(f"types_{t}.csv", f"a,b\n1,{t}\n", types=["int8"])), ("unsupported type", _dyn(f"types2_{t}.csv", f"a\n{t}\n", types=["money"])), ("over the row cap", _dyn(f"big_{t}.csv", "a\n" + "".join(f"{i}\n" for i in range(60)))), @@ -72,12 +90,17 @@ def corpus(t: str) -> list[tuple[str, dict]]: ("te: empty", _te(f"t1_{t}.csv", "name\n")), ("te: unknown column", _te(f"t2_{t}.csv", f"name,bogus\n{t},1\n")), ("te: good", _te(f"orgs_{t}.csv", f"name,org_type,country\nAlpha {t},prime,AU\nBeta {t},test_unit,NZ\n")), - ("te: CHECK violation on one row (database fallback)", - _te(f"orgs2_{t}.csv", f"name,org_type,country\nGamma {t},prime,AU\nDelta {t},not_a_type,AU\n")), + ( + "te: CHECK violation on one row (database fallback)", + _te(f"orgs2_{t}.csv", f"name,org_type,country\nGamma {t},prime,AU\nDelta {t},not_a_type,AU\n"), + ), ("te: client-side type error", _te(f"ev_{t}.csv", f"is_active,name,org_type\nmaybe,E {t},prime\n")), ("te: ragged", _te(f"orgs3_{t}.csv", f"name,org_type\nZeta {t},prime,extra\n")), ("te: re-upload by the same name", _te(f"orgs_{t}.csv", f"name,org_type,country\nEta {t},academic,AU\n")), - ("dynamic: an organisation-shaped dataset", _dyn(f"orgset_{t}.csv", f"name,org_type,country\nTheta {t},prime,AU\n")), + ( + "dynamic: an organisation-shaped dataset", + _dyn(f"orgset_{t}.csv", f"name,org_type,country\nTheta {t},prime,AU\n"), + ), ("te: content already a dataset", _te(f"orgs-te_{t}.csv", f"name,org_type,country\nTheta {t},prime,AU\n")), ("te: over the row cap", _te(f"bigte_{t}.csv", "name\n" + "".join(f"n{i}\n" for i in range(60)))), ] @@ -129,9 +152,11 @@ def test_upload_responses_match_the_recorded_ones(caps): got, want = json.loads(actual), json.loads(expected) first = next((i for i, (a, b) in enumerate(zip(got, want)) if a != b), min(len(got), len(want))) case = (want[first] if first < len(want) else got[first])["case"] - pytest.fail(f"the upload endpoint answers differently from the recorded responses, first at case " - f"{first + 1} ({case!r}):\n expected {json.dumps(want[first] if first < len(want) else None)[:600]}" - f"\n actual {json.dumps(got[first] if first < len(got) else None)[:600]}") + pytest.fail( + f"the upload endpoint answers differently from the recorded responses, first at case " + f"{first + 1} ({case!r}):\n expected {json.dumps(want[first] if first < len(want) else None)[:600]}" + f"\n actual {json.dumps(got[first] if first < len(got) else None)[:600]}" + ) def test_the_corpus_reaches_every_branch_it_names(): diff --git a/tests/system/test_migrations.py b/tests/system/test_migrations.py index 24f2efe..d2bb278 100644 --- a/tests/system/test_migrations.py +++ b/tests/system/test_migrations.py @@ -16,26 +16,33 @@ import psycopg2 import psycopg2.errors import pytest -from alembic import command from alembic.config import Config from alembic.script import ScriptDirectory from fastapi.testclient import TestClient +from alembic import command from api.config import settings from api.db import Conn from api.main import app from api.services.dynamic_loader import upload_dynamic from api.services.te_loader import upload_te -_HELP = ("Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" - "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" + "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1." +) _ALEMBIC_INI = str(Path(__file__).resolve().parents[2] / "alembic.ini") def _connect(): try: - return psycopg2.connect(host=settings.PG_HOST, port=settings.PG_PORT, user=settings.PG_USER, - password=settings.PG_PASSWORD.get_secret_value(), dbname=settings.PG_DATABASE) + return psycopg2.connect( + host=settings.PG_HOST, + port=settings.PG_PORT, + user=settings.PG_USER, + password=settings.PG_PASSWORD.get_secret_value(), + dbname=settings.PG_DATABASE, + ) except psycopg2.OperationalError as exc: raise AssertionError(f"Database unreachable: {exc}\n{_HELP}") from None @@ -54,7 +61,7 @@ def setUp(self): self.original = (settings.UPLOADS_SCHEMA, settings.CONTROL_SCHEMA) tag = uuid.uuid4().hex[:10] settings.UPLOADS_SCHEMA = f"mig_test_{tag}" - settings.CONTROL_SCHEMA = f"mig_ctl_{tag}" # never touch the live control schema + settings.CONTROL_SCHEMA = f"mig_ctl_{tag}" # never touch the live control schema self.cfg = Config(_ALEMBIC_INI) self.conn = _connect() self.conn.autocommit = True @@ -70,27 +77,38 @@ def _constraints(self) -> set[str]: with self.conn.cursor() as cur: cur.execute( "SELECT conname FROM pg_constraint c JOIN pg_namespace n ON n.oid = c.connamespace " - "WHERE n.nspname = %s AND c.contype = 'u'", (settings.UPLOADS_SCHEMA,)) + "WHERE n.nspname = %s AND c.contype = 'u'", + (settings.UPLOADS_SCHEMA,), + ) return {r[0] for r in cur.fetchall()} def _tables(self) -> set[str]: with self.conn.cursor() as cur: - cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = %s", - (settings.UPLOADS_SCHEMA,)) + cur.execute( + "SELECT table_name FROM information_schema.tables WHERE table_schema = %s", (settings.UPLOADS_SCHEMA,) + ) return {r[0] for r in cur.fetchall()} def test_upgrade_head_creates_tables_and_unique_constraints(self): command.upgrade(self.cfg, "head") self.assertTrue({"csv_files", "audit_log", "alembic_version"} <= self._tables()) - self.assertEqual(self._constraints(), { - "csv_files_file_hash_key", "csv_files_dataset_version_key", - "approvals_submission_id_key", "imports_upload_id_key", "imports_approval_id_key"}) + self.assertEqual( + self._constraints(), + { + "csv_files_file_hash_key", + "csv_files_dataset_version_key", + "approvals_submission_id_key", + "imports_upload_id_key", + "imports_approval_id_key", + }, + ) def test_control_schema_is_created_and_removed(self): command.upgrade(self.cfg, "head") with self.conn.cursor() as cur: - cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = %s", - (settings.CONTROL_SCHEMA,)) + cur.execute( + "SELECT table_name FROM information_schema.tables WHERE table_schema = %s", (settings.CONTROL_SCHEMA,) + ) self.assertEqual({r[0] for r in cur.fetchall()}, {"tenants", "users", "memberships", "sessions"}) command.downgrade(self.cfg, "0003") with self.conn.cursor() as cur: @@ -110,32 +128,48 @@ def test_baseline_adopts_a_fallback_created_schema(self): # the tables. Upgrading must adopt them, not fail on CREATE TABLE. with self.conn.cursor() as cur: cur.execute(f'CREATE SCHEMA "{settings.UPLOADS_SCHEMA}"') - cur.execute(f'CREATE TABLE "{settings.UPLOADS_SCHEMA}".csv_files (id BIGSERIAL PRIMARY KEY, ' - "file_name TEXT NOT NULL, file_hash TEXT NOT NULL, table_name TEXT NOT NULL, " - "mode TEXT NOT NULL, row_count INTEGER NOT NULL DEFAULT 0, " - "column_names TEXT[] NOT NULL DEFAULT '{}', created_at TIMESTAMPTZ NOT NULL DEFAULT now())") + cur.execute( + f'CREATE TABLE "{settings.UPLOADS_SCHEMA}".csv_files (id BIGSERIAL PRIMARY KEY, ' + "file_name TEXT NOT NULL, file_hash TEXT NOT NULL, table_name TEXT NOT NULL, " + "mode TEXT NOT NULL, row_count INTEGER NOT NULL DEFAULT 0, " + "column_names TEXT[] NOT NULL DEFAULT '{}', created_at TIMESTAMPTZ NOT NULL DEFAULT now())" + ) command.upgrade(self.cfg, "head") self.assertIn("csv_files_file_hash_key", self._constraints()) def _seed_registry(self, rows): with self.conn.cursor() as cur: for i, (name, mode) in enumerate(rows): - cur.execute(f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files ' - "(file_name, file_hash, table_name, mode) VALUES (%s, %s, %s, %s)", - (name, f"hash{i}", f"csv_legacy{i}", mode)) + cur.execute( + f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files ' + "(file_name, file_hash, table_name, mode) VALUES (%s, %s, %s, %s)", + (name, f"hash{i}", f"csv_legacy{i}", mode), + ) def test_0010_backfills_dataset_and_version_oldest_first_and_leaves_te_rows_alone(self): command.upgrade(self.cfg, "0009") - self._seed_registry([("Sales Report.csv", "dynamic"), ("other.csv", "dynamic"), - ("sales_report.csv", "dynamic"), ("loaded.csv", "te")]) + self._seed_registry( + [ + ("Sales Report.csv", "dynamic"), + ("other.csv", "dynamic"), + ("sales_report.csv", "dynamic"), + ("loaded.csv", "te"), + ] + ) command.upgrade(self.cfg, "0010") with self.conn.cursor() as cur: - cur.execute(f'SELECT file_name, dataset, version, table_name FROM "{settings.UPLOADS_SCHEMA}".csv_files ORDER BY id') - self.assertEqual(cur.fetchall(), [ - ("Sales Report.csv", "sales_report", 1, "csv_legacy0"), # tables are kept as they were - ("other.csv", "other", 1, "csv_legacy1"), - ("sales_report.csv", "sales_report", 2, "csv_legacy2"), - ("loaded.csv", None, None, "csv_legacy3")]) + cur.execute( + f'SELECT file_name, dataset, version, table_name FROM "{settings.UPLOADS_SCHEMA}".csv_files ORDER BY id' + ) + self.assertEqual( + cur.fetchall(), + [ + ("Sales Report.csv", "sales_report", 1, "csv_legacy0"), # tables are kept as they were + ("other.csv", "other", 1, "csv_legacy1"), + ("sales_report.csv", "sales_report", 2, "csv_legacy2"), + ("loaded.csv", None, None, "csv_legacy3"), + ], + ) def test_0010_sql_slug_agrees_with_the_loaders_slug(self): from api.services.dynamic_loader import dataset_slug @@ -150,41 +184,48 @@ def test_0010_sql_slug_agrees_with_the_loaders_slug(self): def test_0010_keeps_one_te_row_per_file_name_but_allows_dataset_versions(self): command.upgrade(self.cfg, "head") - insert = (f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files (file_name, file_hash, table_name, mode, dataset, version) ' - "VALUES (%s, %s, 't', %s, %s, %s)") + insert = ( + f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files (file_name, file_hash, table_name, mode, dataset, version) ' + "VALUES (%s, %s, 't', %s, %s, %s)" + ) with self.conn.cursor() as cur: cur.execute(insert, ("same.csv", "h1", "dynamic", "same", 1)) - cur.execute(insert, ("same.csv", "h2", "dynamic", "same", 2)) # versions share a name + cur.execute(insert, ("same.csv", "h2", "dynamic", "same", 2)) # versions share a name cur.execute(insert, ("same.csv", "h3", "te", None, None)) - with self.assertRaises(psycopg2.errors.UniqueViolation): # T&E race guard is intact + with self.assertRaises(psycopg2.errors.UniqueViolation): # T&E race guard is intact cur.execute(insert, ("same.csv", "h4", "te", None, None)) with self.conn.cursor() as cur: - with self.assertRaises(psycopg2.errors.UniqueViolation): # a version number is used once + with self.assertRaises(psycopg2.errors.UniqueViolation): # a version number is used once cur.execute(insert, ("same.csv", "h5", "dynamic", "same", 2)) def test_0010_downgrade_refuses_while_versions_share_a_name_then_restores_the_constraint(self): command.upgrade(self.cfg, "head") self._seed_registry([("same.csv", "te")]) with self.conn.cursor() as cur: - cur.execute(f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files (file_name, file_hash, table_name, mode, dataset, version) ' - "VALUES ('same.csv', 'hx', 't', 'dynamic', 'same', 1)") + cur.execute( + f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files (file_name, file_hash, table_name, mode, dataset, version) ' + "VALUES ('same.csv', 'hx', 't', 'dynamic', 'same', 1)" + ) with self.assertRaisesRegex(RuntimeError, "versioned datasets share a file name.*same.csv"): command.downgrade(self.cfg, "0009") with self.conn.cursor() as cur: - cur.execute(f'DELETE FROM "{settings.UPLOADS_SCHEMA}".csv_files WHERE mode = \'dynamic\'') + cur.execute(f"DELETE FROM \"{settings.UPLOADS_SCHEMA}\".csv_files WHERE mode = 'dynamic'") command.downgrade(self.cfg, "0009") self.assertIn("csv_files_file_name_key", self._constraints()) def _provenance_by_file(self) -> list[tuple]: with self.conn.cursor() as cur: - cur.execute(f'SELECT file_name, types_provenance FROM "{settings.UPLOADS_SCHEMA}".csv_files ' - "ORDER BY file_name") + cur.execute( + f'SELECT file_name, types_provenance FROM "{settings.UPLOADS_SCHEMA}".csv_files ORDER BY file_name' + ) return cur.fetchall() def test_type_provenance_marks_old_dynamic_rows_unconfirmed_and_leaves_te_null(self): command.upgrade(self.cfg, "0008") - insert = (f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files (file_name, file_hash, table_name, mode) ' - "VALUES (%s, %s, 't', %s)") + insert = ( + f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files (file_name, file_hash, table_name, mode) ' + "VALUES (%s, %s, 't', %s)" + ) with self.conn.cursor() as cur: cur.execute(insert, ("d.csv", "h_dyn", "dynamic")) cur.execute(insert, ("t.csv", "h_te", "te")) @@ -195,32 +236,42 @@ def test_type_provenance_only_accepts_the_two_known_values(self): command.upgrade(self.cfg, "head") with self.conn.cursor() as cur: with self.assertRaises(psycopg2.errors.CheckViolation): - cur.execute(f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files ' - "(file_name, file_hash, table_name, mode, types_provenance) " - "VALUES ('x.csv', 'hx', 't', 'dynamic', 'bogus')") + cur.execute( + f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files ' + "(file_name, file_hash, table_name, mode, types_provenance) " + "VALUES ('x.csv', 'hx', 't', 'dynamic', 'bogus')" + ) def test_type_provenance_downgrade_drops_the_column(self): command.upgrade(self.cfg, "head") command.downgrade(self.cfg, "0008") with self.conn.cursor() as cur: - cur.execute("SELECT 1 FROM information_schema.columns WHERE table_schema = %s " - "AND table_name = 'csv_files' AND column_name = 'types_provenance'", - (settings.UPLOADS_SCHEMA,)) + cur.execute( + "SELECT 1 FROM information_schema.columns WHERE table_schema = %s " + "AND table_name = 'csv_files' AND column_name = 'types_provenance'", + (settings.UPLOADS_SCHEMA,), + ) self.assertIsNone(cur.fetchone()) def _insert_upload(self, cur, status: str) -> int: - cur.execute(f'INSERT INTO "{settings.UPLOADS_SCHEMA}".uploads (file_name, sha256, byte_size, mode, status) ' - "VALUES ('u.csv', 'sha', 1, 'dynamic', %s) RETURNING id", (status,)) + cur.execute( + f'INSERT INTO "{settings.UPLOADS_SCHEMA}".uploads (file_name, sha256, byte_size, mode, status) ' + "VALUES ('u.csv', 'sha', 1, 'dynamic', %s) RETURNING id", + (status,), + ) return cur.fetchone()[0] def test_0011_adds_the_workflow_tables_and_the_tenant_setting(self): command.upgrade(self.cfg, "head") self.assertTrue({"submissions", "approvals", "imports"} <= self._tables()) with self.conn.cursor() as cur: - cur.execute("SELECT column_default FROM information_schema.columns WHERE table_schema = %s " - "AND table_name = 'tenants' AND column_name = 'allow_self_approval'", (settings.CONTROL_SCHEMA,)) + cur.execute( + "SELECT column_default FROM information_schema.columns WHERE table_schema = %s " + "AND table_name = 'tenants' AND column_name = 'allow_self_approval'", + (settings.CONTROL_SCHEMA,), + ) self.assertEqual(cur.fetchone()[0], "false", "self-approval is off unless a tenant turns it on") - self._insert_upload(cur, "staged") # the new status is accepted + self._insert_upload(cur, "staged") # the new status is accepted def test_0011_the_database_checks_that_import_counts_reconcile(self): command.upgrade(self.cfg, "head") @@ -229,15 +280,20 @@ def test_0011_the_database_checks_that_import_counts_reconcile(self): up = self._insert_upload(cur, "staged") cur.execute(f'INSERT INTO "{schema}".submissions (upload_id) VALUES (%s) RETURNING id', (up,)) sub = cur.fetchone()[0] - cur.execute(f'INSERT INTO "{schema}".approvals (submission_id, upload_id, decision, decisions_upto, edits_upto) ' - "VALUES (%s, %s, 'approve', 0, 0) RETURNING id", (sub, up)) + cur.execute( + f'INSERT INTO "{schema}".approvals (submission_id, upload_id, decision, decisions_upto, edits_upto) ' + "VALUES (%s, %s, 'approve', 0, 0) RETURNING id", + (sub, up), + ) appr = cur.fetchone()[0] - insert = (f'INSERT INTO "{schema}".imports (upload_id, approval_id, idempotency_key, rows_in, rows_excluded, ' - "rows_edited, rows_duplicate, rows_imported, csv_file_id, table_name) " - "VALUES (%s, %s, 'k', %s, 1, 0, 1, %s, 1, 't')") + insert = ( + f'INSERT INTO "{schema}".imports (upload_id, approval_id, idempotency_key, rows_in, rows_excluded, ' + "rows_edited, rows_duplicate, rows_imported, csv_file_id, table_name) " + "VALUES (%s, %s, 'k', %s, 1, 0, 1, %s, 1, 't')" + ) with self.assertRaises(psycopg2.errors.CheckViolation): - cur.execute(insert, (up, appr, 10, 7)) # 10 != 1 + 1 + 7 - cur.execute(insert, (up, appr, 10, 8)) # 10 == 1 + 1 + 8 + cur.execute(insert, (up, appr, 10, 7)) # 10 != 1 + 1 + 7 + cur.execute(insert, (up, appr, 10, 8)) # 10 == 1 + 1 + 8 def test_0011_a_rejection_needs_a_reason_but_an_approval_does_not(self): command.upgrade(self.cfg, "head") @@ -248,8 +304,10 @@ def test_0011_a_rejection_needs_a_reason_but_an_approval_does_not(self): for _ in range(3): cur.execute(f'INSERT INTO "{schema}".submissions (upload_id) VALUES (%s) RETURNING id', (up,)) ids.append(cur.fetchone()[0]) - insert = (f'INSERT INTO "{schema}".approvals (submission_id, upload_id, decision, reason, decisions_upto, ' - "edits_upto) VALUES (%s, %s, %s, %s, 0, 0)") + insert = ( + f'INSERT INTO "{schema}".approvals (submission_id, upload_id, decision, reason, decisions_upto, ' + "edits_upto) VALUES (%s, %s, %s, %s, 0, 0)" + ) cur.execute(insert, (ids[0], up, "approve", None)) with self.assertRaises(psycopg2.errors.CheckViolation): cur.execute(insert, (ids[1], up, "reject", " ")) @@ -270,26 +328,33 @@ def test_0011_downgrade_removes_the_workflow_and_the_staged_status(self): with self.conn.cursor() as cur: with self.assertRaises(psycopg2.errors.CheckViolation): self._insert_upload(cur, "staged") - cur.execute("SELECT 1 FROM information_schema.columns WHERE table_schema = %s " - "AND table_name = 'tenants' AND column_name = 'allow_self_approval'", (settings.CONTROL_SCHEMA,)) + cur.execute( + "SELECT 1 FROM information_schema.columns WHERE table_schema = %s " + "AND table_name = 'tenants' AND column_name = 'allow_self_approval'", + (settings.CONTROL_SCHEMA,), + ) self.assertIsNone(cur.fetchone()) def _session_columns(self) -> dict[str, tuple[str, str, str | None]]: with self.conn.cursor() as cur: - cur.execute("SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns " - "WHERE table_schema = %s AND table_name = 'sessions'", (settings.CONTROL_SCHEMA,)) + cur.execute( + "SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns " + "WHERE table_schema = %s AND table_name = 'sessions'", + (settings.CONTROL_SCHEMA,), + ) return {r[0]: (r[1], r[2], r[3]) for r in cur.fetchall()} def _session_indexes(self) -> set[str]: with self.conn.cursor() as cur: - cur.execute("SELECT indexname FROM pg_indexes WHERE schemaname = %s AND tablename = 'sessions'", - (settings.CONTROL_SCHEMA,)) + cur.execute( + "SELECT indexname FROM pg_indexes WHERE schemaname = %s AND tablename = 'sessions'", + (settings.CONTROL_SCHEMA,), + ) return {r[0] for r in cur.fetchall()} def test_0012_adds_last_seen_and_the_purge_indexes(self): command.upgrade(self.cfg, "head") - self.assertEqual(self._session_columns()["last_seen_at"], - ("timestamp with time zone", "NO", "now()")) + self.assertEqual(self._session_columns()["last_seen_at"], ("timestamp with time zone", "NO", "now()")) self.assertTrue({"sessions_expires_at_idx", "sessions_revoked_at_idx"} <= self._session_indexes()) def test_0012_existing_sessions_start_with_a_current_last_seen_so_nobody_is_signed_out(self): @@ -300,12 +365,16 @@ def test_0012_existing_sessions_start_with_a_current_last_seen_so_nobody_is_sign tid = cur.fetchone()[0] cur.execute(f'INSERT INTO "{ctl}".users (username, password_hash) VALUES (%s, %s) RETURNING id', ("u", "x")) uid = cur.fetchone()[0] - cur.execute(f'INSERT INTO "{ctl}".sessions (token_hash, user_id, tenant_id, expires_at) ' - "VALUES ('h', %s, %s, now() + interval '1 hour')", (uid, tid)) + cur.execute( + f'INSERT INTO "{ctl}".sessions (token_hash, user_id, tenant_id, expires_at) ' + "VALUES ('h', %s, %s, now() + interval '1 hour')", + (uid, tid), + ) command.upgrade(self.cfg, "head") with self.conn.cursor() as cur: - cur.execute(f'SELECT extract(epoch FROM now() - last_seen_at) FROM "{ctl}".sessions WHERE token_hash = %s', - ("h",)) + cur.execute( + f'SELECT extract(epoch FROM now() - last_seen_at) FROM "{ctl}".sessions WHERE token_hash = %s', ("h",) + ) self.assertLess(cur.fetchone()[0], 120, "an existing session must not look idle after the upgrade") def test_0012_downgrade_removes_the_column_and_the_indexes(self): @@ -319,9 +388,11 @@ def test_existing_duplicates_stop_the_upgrade_with_remediation(self): command.upgrade(self.cfg, "0001") with self.conn.cursor() as cur: for name in ("a.csv", "b.csv"): - cur.execute(f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files ' - "(file_name, file_hash, table_name, mode) VALUES (%s, 'samehash', 't', 'dynamic')", - (name,)) + cur.execute( + f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files ' + "(file_name, file_hash, table_name, mode) VALUES (%s, 'samehash', 't', 'dynamic')", + (name,), + ) with self.assertRaisesRegex(RuntimeError, "duplicated value.*samehash"): command.upgrade(self.cfg, "head") self.assertEqual(self._constraints(), set()) @@ -352,8 +423,10 @@ def test_bootstrap_brings_the_schema_to_head(self): self.assertEqual(cur.fetchone()[0], ScriptDirectory.from_config(Config(_ALEMBIC_INI)).get_current_head()) def test_duplicate_hash_is_rejected_by_the_database(self): - insert = (f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files (file_name, file_hash, table_name, mode) ' - "VALUES (%s, %s, 't', 'dynamic')") + insert = ( + f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files (file_name, file_hash, table_name, mode) ' + "VALUES (%s, %s, 't', 'dynamic')" + ) with Conn() as conn, conn.cursor() as cur: cur.execute(insert, (f"a_{self.tag}.csv", f"h_{self.tag}")) with self.assertRaises(psycopg2.errors.UniqueViolation): @@ -370,9 +443,11 @@ def _against_uncommitted_competitor(self, fn, name: str, content: str, table: st result: dict = {} try: with competitor.cursor() as cur: - cur.execute(f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files ' - "(file_name, file_hash, table_name, mode) VALUES (%s, %s, %s, %s)", - (name, file_hash, table, mode)) + cur.execute( + f'INSERT INTO "{settings.UPLOADS_SCHEMA}".csv_files ' + "(file_name, file_hash, table_name, mode) VALUES (%s, %s, %s, %s)", + (name, file_hash, table, mode), + ) worker = threading.Thread(target=lambda: result.update(fn())) worker.start() watcher = _connect() @@ -402,7 +477,8 @@ def test_dynamic_upload_losing_the_race_reports_duplicate_and_commits_nothing(se content = f"a,b\n1,{self.tag}\n2,{self.tag}\n" table = f"csv_{hashlib.sha256(content.encode()).hexdigest()[:16]}" result = self._against_uncommitted_competitor( - lambda: upload_dynamic(name, content, None, False), name, content, table, "dynamic") + lambda: upload_dynamic(name, content, None, False), name, content, table, "dynamic" + ) self.assertEqual(result["status"], "duplicate_file") with Conn() as conn, conn.cursor() as cur: cur.execute("SELECT to_regclass(%s)", (f'"{settings.UPLOADS_SCHEMA}".{table}',)) @@ -410,13 +486,17 @@ def test_dynamic_upload_losing_the_race_reports_duplicate_and_commits_nothing(se def test_te_load_losing_the_race_reports_error_and_rolls_back_rows(self): name = f"race_te_{self.tag}.csv" - content = "name,org_type,country\n" + "\n".join( - f"RACE_{self.tag}_{i},government,AU" for i in range(20)) + "\n" + content = "name,org_type,country\n" + "\n".join(f"RACE_{self.tag}_{i},government,AU" for i in range(20)) + "\n" result = self._against_uncommitted_competitor( - lambda: upload_te(name, content, "organisations"), name, content, - f"{settings.TE_SCHEMA}.organisations", "te") + lambda: upload_te(name, content, "organisations"), + name, + content, + f"{settings.TE_SCHEMA}.organisations", + "te", + ) self.assertEqual(result["status"], "error") with Conn() as conn, conn.cursor() as cur: - cur.execute(f'SELECT count(*) FROM "{settings.TE_SCHEMA}".organisations WHERE name LIKE %s', - (f"RACE_{self.tag}_%",)) + cur.execute( + f'SELECT count(*) FROM "{settings.TE_SCHEMA}".organisations WHERE name LIKE %s', (f"RACE_{self.tag}_%",) + ) self.assertEqual(cur.fetchone()[0], 0, "the losing load must roll back its rows") diff --git a/tests/system/test_oidc.py b/tests/system/test_oidc.py index addd108..6cc666d 100644 --- a/tests/system/test_oidc.py +++ b/tests/system/test_oidc.py @@ -57,8 +57,7 @@ def tearDownClass(cls): @staticmethod def token(username="alice", key=None, kid=_KID, alg="RS256", **overrides) -> str: now = int(time.time()) - claims = {"iss": _ISS, "aud": _AUD, "iat": now, "exp": now + 300, - "sub": "abc", "preferred_username": username} + claims = {"iss": _ISS, "aud": _AUD, "iat": now, "exp": now + 300, "sub": "abc", "preferred_username": username} claims.update(overrides) claims = {k: v for k, v in claims.items() if v is not None} return jwt.encode(claims, key or _SIGNER, algorithm=alg, headers={"kid": kid}) @@ -81,7 +80,10 @@ def test_rejected_tokens(self): "no username claim": self.token(username=None), "unsigned (alg none)": jwt.encode( {"iss": _ISS, "aud": _AUD, "exp": now + 300, "iat": now, "preferred_username": "alice"}, - None, algorithm="none", headers={"kid": _KID}), + None, + algorithm="none", + headers={"kid": _KID}, + ), "garbage": "not.a.token", } for name, tok in cases.items(): @@ -131,8 +133,9 @@ def test_invalid_token_is_401(self): def test_inactive_user_is_401(self): with Conn() as conn: with conn.cursor() as cur: - cur.execute(f'UPDATE "{settings.CONTROL_SCHEMA}".users SET is_active = false WHERE id = %s', - (self.user_id,)) + cur.execute( + f'UPDATE "{settings.CONTROL_SCHEMA}".users SET is_active = false WHERE id = %s', (self.user_id,) + ) conn.commit() self.assertEqual(self._post(self.tenant, self.token(self.user)).status_code, 401) diff --git a/tests/system/test_oidc_https.py b/tests/system/test_oidc_https.py index a464438..e1e4cbd 100644 --- a/tests/system/test_oidc_https.py +++ b/tests/system/test_oidc_https.py @@ -72,9 +72,11 @@ def test_claims_are_still_checked_after_the_signature(self): key = new_key() with LocalIdp({"k1": key}) as idp, idp.trust(): settings.OIDC_JWKS_URL = idp.jwks_url - for name, token in {"audience": _token(key, "k1", aud="another-app"), - "issuer": _token(key, "k1", iss="https://evil.example/realms/te"), - "expiry": _token(key, "k1", exp=int(time.time()) - 5, iat=int(time.time()) - 400)}.items(): + for name, token in { + "audience": _token(key, "k1", aud="another-app"), + "issuer": _token(key, "k1", iss="https://evil.example/realms/te"), + "expiry": _token(key, "k1", exp=int(time.time()) - 5, iat=int(time.time()) - 400), + }.items(): self.assertIsNone(oidc.username_from(token), name) def test_a_rotated_signing_key_is_picked_up_without_a_restart_after_the_cooldown(self): @@ -83,13 +85,19 @@ def test_a_rotated_signing_key_is_picked_up_without_a_restart_after_the_cooldown settings.OIDC_JWKS_URL = idp.jwks_url self.assertEqual(oidc.username_from(_token(old, "old")), "alice") client = oidc._jwks(idp.jwks_url) - client.cooldown_duration = 0.5 # PyJWT's default is 30 s; shortened to keep the test quick - idp.keys = {"old": old, "new": new} # the IdP rotates - self.assertIsNone(oidc.username_from(_token(new, "new")), "refused inside the cooldown after the last fetch") + client.cooldown_duration = 0.5 # PyJWT's default is 30 s; shortened to keep the test quick + idp.keys = {"old": old, "new": new} # the IdP rotates + self.assertIsNone( + oidc.username_from(_token(new, "new")), "refused inside the cooldown after the last fetch" + ) self.assertEqual(len(idp.requests), 1, "...and that didn't cost the IdP a request") time.sleep(0.6) - self.assertEqual(oidc.username_from(_token(new, "new")), "alice", "after the cooldown the key set is re-fetched") - self.assertEqual(oidc.username_from(_token(old, "old")), "alice", "the old key still works during the overlap") + self.assertEqual( + oidc.username_from(_token(new, "new")), "alice", "after the cooldown the key set is re-fetched" + ) + self.assertEqual( + oidc.username_from(_token(old, "old")), "alice", "the old key still works during the overlap" + ) self.assertEqual(len(idp.requests), 2) def test_random_key_ids_cannot_make_the_api_hammer_the_idp(self): @@ -105,7 +113,7 @@ def test_random_key_ids_cannot_make_the_api_hammer_the_idp(self): class WhenTheIdpCannotBeTrustedOrReached(_Https): def test_a_certificate_the_host_does_not_trust_fails_closed(self): key = new_key() - with LocalIdp({"k1": key}) as idp: # no idp.trust(): self-signed and unknown + with LocalIdp({"k1": key}) as idp: # no idp.trust(): self-signed and unknown settings.OIDC_JWKS_URL = idp.jwks_url self.assertIsNone(oidc.username_from(_token(key, "k1"))) self.assertEqual(idp.requests, [], "the TLS handshake failed, so no request was made") @@ -158,16 +166,26 @@ def test_the_idp_token_becomes_a_session_with_the_members_role(self): key = new_key() with LocalIdp({"k1": key}) as idp, idp.trust(): settings.OIDC_JWKS_URL = idp.jwks_url - res = self.client.post("/api/auth/oidc", json={"tenant": tenant, "idToken": _token(key, "k1", username=user)}) + res = self.client.post( + "/api/auth/oidc", json={"tenant": tenant, "idToken": _token(key, "k1", username=user)} + ) self.assertEqual(res.status_code, 200, res.text) - self.assertEqual((res.json()["username"], res.json()["role"], res.json()["tenant"]), (user, "reviewer", tenant)) - stranger = self.client.post("/api/auth/oidc", json={"tenant": tenant, "idToken": _token(key, "k1", username="nobody")}) + self.assertEqual( + (res.json()["username"], res.json()["role"], res.json()["tenant"]), (user, "reviewer", tenant) + ) + stranger = self.client.post( + "/api/auth/oidc", json={"tenant": tenant, "idToken": _token(key, "k1", username="nobody")} + ) self.assertEqual(stranger.status_code, 401, "a valid token for someone who isn't a member gets nothing") - forged = self.client.post("/api/auth/oidc", json={"tenant": tenant, "idToken": _token(new_key(), "k1", username=user)}) + forged = self.client.post( + "/api/auth/oidc", json={"tenant": tenant, "idToken": _token(new_key(), "k1", username=user)} + ) self.assertEqual(forged.status_code, 401) with Conn() as conn, conn.cursor() as cur: from psycopg2 import sql + from api.tenancy import schema_for + control = sql.Identifier(settings.CONTROL_SCHEMA) cur.execute(sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format(control), (tenant,)) cur.execute(sql.SQL("DELETE FROM {}.users WHERE username = %s").format(control), (user,)) diff --git a/tests/system/test_original_bytes.py b/tests/system/test_original_bytes.py index 9447ea0..c075ea8 100644 --- a/tests/system/test_original_bytes.py +++ b/tests/system/test_original_bytes.py @@ -20,8 +20,10 @@ from api.main import app -_HELP = ("Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" - "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" + "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1." +) def _browser_decode(raw: bytes) -> str: @@ -90,12 +92,15 @@ def test_a_failed_upload_keeps_the_raw_original_too(self): def test_without_contentbase64_the_utf8_encoding_of_content_is_kept_as_before(self): content = f"a,b\n1,{self.tag}\n" - res = self.client.post("/api/csv/upload", json={ - "fileName": f"bytes_plain_{self.tag}.csv", "content": content}).json() + res = self.client.post( + "/api/csv/upload", json={"fileName": f"bytes_plain_{self.tag}.csv", "content": content} + ).json() self._assert_round_trips(content.encode(), res) def test_invalid_base64_is_rejected_before_anything_loads(self): - resp = self.client.post("/api/csv/upload", json={ - "fileName": f"bytes_bad_{self.tag}.csv", "content": "a\n1\n", "contentBase64": "not base64!!"}) + resp = self.client.post( + "/api/csv/upload", + json={"fileName": f"bytes_bad_{self.tag}.csv", "content": "a\n1\n", "contentBase64": "not base64!!"}, + ) self.assertEqual(resp.status_code, 422) self.assertIn("base64", resp.json()["detail"]) diff --git a/tests/system/test_password_rehash.py b/tests/system/test_password_rehash.py index ae337fd..6aa55d0 100644 --- a/tests/system/test_password_rehash.py +++ b/tests/system/test_password_rehash.py @@ -8,6 +8,7 @@ * a wrong password leaves the old hash alone; * the upgrade is conditional on the hash that was checked, so a password changed in between is not undone. """ + from __future__ import annotations import hashlib @@ -31,8 +32,12 @@ def old_hash(password: str, n: int = 2**14) -> str: class HashUpgradeAtSignIn(_Accounts): def _stored(self) -> str: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT password_hash FROM {c}.users WHERE id = %s") - .format(c=sql.Identifier(settings.CONTROL_SCHEMA)), (self.user_id,)) + cur.execute( + sql.SQL("SELECT password_hash FROM {c}.users WHERE id = %s").format( + c=sql.Identifier(settings.CONTROL_SCHEMA) + ), + (self.user_id,), + ) return cur.fetchone()[0] def _store(self, value: str) -> None: @@ -65,7 +70,7 @@ def test_a_wrong_password_leaves_the_old_hash_alone(self): def test_a_password_changed_meanwhile_is_not_undone_by_the_upgrade(self): legacy = old_hash(_PW) changed = accounts.hash_password("a different passphrase") - self._store(changed) # changed after the sign-in read `legacy` + self._store(changed) # changed after the sign-in read `legacy` with Conn() as conn: with conn.cursor() as cur: self.assertFalse(accounts._upgrade_hash(cur, self.user_id, legacy, _PW)) diff --git a/tests/system/test_password_reset.py b/tests/system/test_password_reset.py index 15c0ef3..5392ca3 100644 --- a/tests/system/test_password_reset.py +++ b/tests/system/test_password_reset.py @@ -31,8 +31,9 @@ def _bearer(token: str) -> dict: @pytest.mark.integration class ChangeOwnPassword(_Accounts): def _change(self, token: str, current=_PW, new=_NEW): - return self.client.post("/api/auth/password", headers=_bearer(token), - json={"currentPassword": current, "newPassword": new}) + return self.client.post( + "/api/auth/password", headers=_bearer(token), json={"currentPassword": current, "newPassword": new} + ) def test_new_password_works_old_does_not_and_other_sessions_end(self): mine, other = self._login().json()["token"], self._login().json()["token"] @@ -48,8 +49,12 @@ def test_wrong_current_password_is_400_changes_nothing_and_counts_as_a_failure(s self.assertEqual((res.status_code, res.json()["detail"]), (400, "Current password is incorrect")) self.assertEqual(self._me(token).status_code, 200) with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT failed_logins FROM {}.users WHERE id = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (self.user_id,)) + cur.execute( + sql.SQL("SELECT failed_logins FROM {}.users WHERE id = %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (self.user_id,), + ) self.assertEqual(cur.fetchone()[0], 1) self.assertEqual(self._login().status_code, 200, "password unchanged") @@ -70,11 +75,14 @@ def setUp(self): self.admin = f"admin_{uuid.uuid4().hex[:8]}" with Conn() as conn: with conn.cursor() as cur: - cur.execute(sql.SQL("SELECT id FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (self.tenant,)) + cur.execute( + sql.SQL("SELECT id FROM {}.tenants WHERE slug = %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (self.tenant,), + ) self.tenant_id = cur.fetchone()[0] - accounts.add_membership(cur, accounts.create_user(cur, self.admin, _PW), - self.tenant_id, "tenant_admin") + accounts.add_membership(cur, accounts.create_user(cur, self.admin, _PW), self.tenant_id, "tenant_admin") conn.commit() migrate_tenant(self.tenant) # real tenants always have their schema (audit_log lives there) self.admin_token = self._login(username=self.admin).json()["token"] @@ -82,13 +90,15 @@ def setUp(self): def tearDown(self): with Conn() as conn: with conn.cursor() as cur: - cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format( - sql.Identifier(schema_for(self.tenant)))) + cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(self.tenant)))) conn.commit() def _reset(self, username: str, token: str | None = None): - return self.client.post(f"/api/auth/users/{username}/password", - headers=_bearer(token or self.admin_token), json={"newPassword": _NEW}) + return self.client.post( + f"/api/auth/users/{username}/password", + headers=_bearer(token or self.admin_token), + json={"newPassword": _NEW}, + ) def test_admin_reset_sets_password_unlocks_and_ends_the_users_sessions(self): user_token = self._login().json()["token"] @@ -101,8 +111,11 @@ def test_admin_reset_sets_password_unlocks_and_ends_the_users_sessions(self): def test_reset_is_written_to_the_tenants_audit_log(self): self.assertEqual(self._reset(self.user).status_code, 200) with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT action, file_name, mode, actor FROM {}.audit_log").format( - sql.Identifier(schema_for(self.tenant)))) + cur.execute( + sql.SQL("SELECT action, file_name, mode, actor FROM {}.audit_log").format( + sql.Identifier(schema_for(self.tenant)) + ) + ) self.assertEqual(cur.fetchall(), [("password_reset", self.user, None, self.admin)]) def test_non_admin_cannot_reset(self): @@ -114,8 +127,12 @@ def test_admin_cannot_reset_a_user_in_another_tenant(self): outsider = f"out_{uuid.uuid4().hex[:8]}" with Conn() as conn: with conn.cursor() as cur: - cur.execute(sql.SQL("SELECT id FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (self.other,)) + cur.execute( + sql.SQL("SELECT id FROM {}.tenants WHERE slug = %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (self.other,), + ) tid = cur.fetchone()[0] accounts.add_membership(cur, accounts.create_user(cur, outsider, _PW), tid, "uploader") conn.commit() @@ -125,8 +142,12 @@ def test_admin_cannot_reset_a_user_in_another_tenant(self): def test_user_who_is_also_in_another_tenant_is_refused(self): with Conn() as conn: with conn.cursor() as cur: - cur.execute(sql.SQL("SELECT id FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (self.other,)) + cur.execute( + sql.SQL("SELECT id FROM {}.tenants WHERE slug = %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (self.other,), + ) accounts.add_membership(cur, self.user_id, cur.fetchone()[0], "uploader") conn.commit() self.assertEqual(self._reset(self.user).status_code, 409) @@ -136,9 +157,14 @@ def test_user_who_is_also_in_another_tenant_is_refused(self): @pytest.mark.integration class BreakGlassReset(_Accounts): def _run(self, username: str, password: str = _NEW) -> subprocess.CompletedProcess: - return subprocess.run([sys.executable, "scripts/reset_password.py", "--username", username], - cwd=_ROOT, env={**os.environ, "TE_NEW_PASSWORD": password}, - capture_output=True, text=True, timeout=60) + return subprocess.run( + [sys.executable, "scripts/reset_password.py", "--username", username], + cwd=_ROOT, + env={**os.environ, "TE_NEW_PASSWORD": password}, + capture_output=True, + text=True, + timeout=60, + ) def test_resets_password_clears_lockout_and_ends_sessions(self): token = self._login().json()["token"] diff --git a/tests/system/test_preserved_uploads.py b/tests/system/test_preserved_uploads.py index b6bf4ad..6b0a34f 100644 --- a/tests/system/test_preserved_uploads.py +++ b/tests/system/test_preserved_uploads.py @@ -54,8 +54,12 @@ def _upload_row(self, upload_id: str) -> dict: def _source_rows(self, upload_id: str) -> list[list[str]]: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT cells FROM {}.source_rows WHERE upload_id = %s ORDER BY row_number") - .format(sql.Identifier(settings.UPLOADS_SCHEMA)), (int(upload_id),)) + cur.execute( + sql.SQL("SELECT cells FROM {}.source_rows WHERE upload_id = %s ORDER BY row_number").format( + sql.Identifier(settings.UPLOADS_SCHEMA) + ), + (int(upload_id),), + ) return [r[0] for r in cur.fetchall()] def test_original_bytes_and_rows_are_kept_with_the_outcome(self): @@ -63,14 +67,16 @@ def test_original_bytes_and_rows_are_kept_with_the_outcome(self): res = self._upload(content) self.assertEqual(res["status"], "ok", res) row = self._upload_row(res["uploadId"]) - self.assertEqual((row["status"], row["uploader"], row["total_rows"], row["imported_rows"]), - ("imported", "anonymous", 2, 2)) + self.assertEqual( + (row["status"], row["uploader"], row["total_rows"], row["imported_rows"]), ("imported", "anonymous", 2, 2) + ) self.assertEqual(row["csv_file_id"], res["fileId"]) original = self.client.get(f"/api/csv/uploads/{res['uploadId']}/original") self.assertEqual(original.content, content.encode("utf-8")) self.assertEqual(original.headers["x-content-sha256"], hashlib.sha256(content.encode()).hexdigest()) - self.assertEqual(self._source_rows(res["uploadId"]), - [["name", "note"], [self.tag, "a, b"], ["second", "line\nbreak"]]) + self.assertEqual( + self._source_rows(res["uploadId"]), [["name", "note"], [self.tag, "a, b"], ["second", "line\nbreak"]] + ) [listed] = [f for f in self.client.get("/api/csv/files").json() if f["file_name"] == self.name] self.assertEqual((listed["uploader"], listed["upload_id"]), ("anonymous", res["uploadId"])) @@ -85,8 +91,8 @@ def test_a_failed_upload_still_keeps_its_original(self): def test_failure_reasons_and_log_are_readable_from_another_session(self): """M3c (#107): the reasons rows failed live on the server, not only in the uploading browser.""" res = self._upload(f"n,t\n1,{self.tag}\nx,{self.tag}\n", ["int8", "text"]) - other = TestClient(app) # a separate client with no state shared with the uploader; no - detail = other.get(f"/api/csv/uploads/{res['uploadId']}").json() # lifespan, so the pool stays up + other = TestClient(app) # a separate client with no state shared with the uploader; no + detail = other.get(f"/api/csv/uploads/{res['uploadId']}").json() # lifespan, so the pool stays up self.assertEqual((detail["status"], detail["failedRows"]), ("partly_imported", 1)) self.assertEqual(detail["rowErrors"], res["rowErrors"]) self.assertEqual(detail["rowErrors"][0]["rowNumber"], 2) @@ -103,16 +109,19 @@ def test_overwrite_keeps_the_replaced_original(self): first = self._upload(f"v\nold_{self.tag}\n") second = self._upload(f"v\nnew_{self.tag}\n", overwrite=True) self.assertEqual(second["status"], "ok", second) - self.assertEqual(self.client.get(f"/api/csv/uploads/{first['uploadId']}/original").content, - f"v\nold_{self.tag}\n".encode()) + self.assertEqual( + self.client.get(f"/api/csv/uploads/{first['uploadId']}/original").content, f"v\nold_{self.tag}\n".encode() + ) self.assertEqual(self._source_rows(first["uploadId"]), [["v"], [f"old_{self.tag}"]]) def test_preserved_tables_reject_update_and_delete(self): res = self._upload(f"v\n{self.tag}\n") uid = int(res["uploadId"]) for table, column in (("uploads", "file_name"), ("upload_blobs", "content"), ("source_rows", "cells")): - for statement in (f"UPDATE {{}}.{table} SET {column} = {column} WHERE {'id' if table == 'uploads' else 'upload_id'} = %s", - f"DELETE FROM {{}}.{table} WHERE {'id' if table == 'uploads' else 'upload_id'} = %s"): + for statement in ( + f"UPDATE {{}}.{table} SET {column} = {column} WHERE {'id' if table == 'uploads' else 'upload_id'} = %s", + f"DELETE FROM {{}}.{table} WHERE {'id' if table == 'uploads' else 'upload_id'} = %s", + ): with self.subTest(statement=statement), Conn() as conn, conn.cursor() as cur: with self.assertRaises(psycopg2.errors.InsufficientPrivilege): cur.execute(sql.SQL(statement).format(sql.Identifier(settings.UPLOADS_SCHEMA)), (uid,)) diff --git a/tests/system/test_ragged_rows.py b/tests/system/test_ragged_rows.py index c63bdb9..5becf60 100644 --- a/tests/system/test_ragged_rows.py +++ b/tests/system/test_ragged_rows.py @@ -12,8 +12,10 @@ from api.main import app from api.services.csv_parse import extra_cells -_HELP = ("Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" - "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" + "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1." +) @pytest.mark.unit @@ -68,8 +70,7 @@ def test_dynamic_mode_accepts_a_trailing_empty_cell(self): self.assertEqual((res["status"], res["insertedRows"], res["failedRows"]), ("ok", 1, 0)) def test_te_mode_reports_a_row_wider_than_the_header(self): - content = (f"name,org_type,country\nRAG_{self.tag}_1,government,AU\n" - f"RAG_{self.tag}_2,government,AU,LOST\n") + content = f"name,org_type,country\nRAG_{self.tag}_1,government,AU\nRAG_{self.tag}_2,government,AU,LOST\n" res = self._upload(content, mode="te", targetTable="organisations") # #289: a T&E file with a bad row is rejected as a whole. The wide row is still reported, never # silently truncated (#82), and the good row does not land either. @@ -80,10 +81,7 @@ def test_te_mode_reports_a_row_wider_than_the_header(self): def test_multiple_ragged_rows_each_get_a_reason(self): """Every ragged row gets its own entry in rowErrors with a reason.""" - content = (f"a,b\n" - f"1,{self.tag}\n" - f"2,{self.tag},X1,X2\n" - f"3,{self.tag},X3\n") + content = f"a,b\n1,{self.tag}\n2,{self.tag},X1,X2\n3,{self.tag},X3\n" res = self._upload(content) self.assertEqual(res["status"], "ok") self.assertEqual(res["failedRows"], 2) @@ -109,7 +107,8 @@ def _assert_accounted(self, res: dict, ragged_rows: dict[int, str], *, rejected: self.assertEqual( res["totalRows"], res["insertedRows"] + res["duplicateRowsSkipped"] + res["failedRows"], - f"rows went missing: {res}") + f"rows went missing: {res}", + ) self.assertEqual(res["failedRows"], len(ragged_rows)) def by_row(errors): @@ -127,8 +126,7 @@ def by_row(errors): def test_dynamic_mode_accounts_for_every_row_with_a_stored_reason(self): t = self.tag - res = self._upload( - f"a,b\n1,{t}\n1,{t}\n2,{t},LOST1\n3,{t}\n4,{t},LOST2,MORE\n") + res = self._upload(f"a,b\n1,{t}\n1,{t}\n2,{t},LOST1\n3,{t}\n4,{t},LOST2,MORE\n") self.assertEqual((res["insertedRows"], res["duplicateRowsSkipped"], res["failedRows"]), (2, 1, 2)) self._assert_accounted(res, {3: "LOST1", 5: "LOST2"}) @@ -137,9 +135,11 @@ def test_te_mode_accounts_for_every_row_with_a_stored_reason(self): head = "name,org_type,country\n" res = self._upload( head + f"RAG_{t}_1,government,AU\n" - f"RAG_{t}_2,government,AU,LOST1\n" - f"RAG_{t}_3,government,AU\n" - f"RAG_{t}_4,government,AU,LOST2,MORE\n", - mode="te", targetTable="organisations") + f"RAG_{t}_2,government,AU,LOST1\n" + f"RAG_{t}_3,government,AU\n" + f"RAG_{t}_4,government,AU,LOST2,MORE\n", + mode="te", + targetTable="organisations", + ) self.assertEqual((res["insertedRows"], res["failedRows"]), (0, 2)) # #289: all or nothing self._assert_accounted(res, {2: "LOST1", 4: "LOST2"}, rejected=True) diff --git a/tests/system/test_registry_race.py b/tests/system/test_registry_race.py index 15bc805..391b634 100644 --- a/tests/system/test_registry_race.py +++ b/tests/system/test_registry_race.py @@ -62,17 +62,21 @@ def go(item): def _registry(names: list[str], hashes: list[str]) -> list[tuple]: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL( - "SELECT file_name, file_hash, table_name FROM {}.csv_files " - "WHERE file_name = ANY(%s) OR file_hash = ANY(%s)").format(sql.Identifier(uploads_schema())), - (names, hashes)) + cur.execute( + sql.SQL( + "SELECT file_name, file_hash, table_name FROM {}.csv_files " + "WHERE file_name = ANY(%s) OR file_hash = ANY(%s)" + ).format(sql.Identifier(uploads_schema())), + (names, hashes), + ) return cur.fetchall() def _table_rows(table: str) -> int: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT count(*) FROM {}.{}").format( - sql.Identifier(uploads_schema()), sql.Identifier(table))) + cur.execute( + sql.SQL("SELECT count(*) FROM {}.{}").format(sql.Identifier(uploads_schema()), sql.Identifier(table)) + ) return cur.fetchone()[0] @@ -84,8 +88,9 @@ def setUp(self): def _assert_one_winner(self, results: list[dict], round_no: int) -> tuple[int, dict]: ok = [(i, r) for i, r in enumerate(results) if r["status"] == "ok"] - self.assertEqual(len(ok), 1, f"round {round_no}: expected exactly one winner, " - f"got {[r['status'] for r in results]}") + self.assertEqual( + len(ok), 1, f"round {round_no}: expected exactly one winner, got {[r['status'] for r in results]}" + ) return ok[0] def _assert_attributable(self, res: dict, winner_name: str, round_no: int): @@ -139,10 +144,16 @@ def test_same_name_different_content_gets_distinct_versions(self): results = _race(uploads) - self.assertEqual([r["status"] for r in results], ["ok"] * RACERS, - f"round {n}: every version must be stored, got {results}") - self.assertEqual(sorted(r["version"] for r in results), list(range(1, RACERS + 1)), - f"round {n}: versions must be distinct and gapless") + self.assertEqual( + [r["status"] for r in results], + ["ok"] * RACERS, + f"round {n}: every version must be stored, got {results}", + ) + self.assertEqual( + sorted(r["version"] for r in results), + list(range(1, RACERS + 1)), + f"round {n}: versions must be distinct and gapless", + ) self.assertEqual(len({r["dataset"] for r in results}), 1) digests = [hashlib.sha256(c.encode()).hexdigest() for _, c in uploads] self.assertEqual(len(_registry([name], digests)), RACERS, f"round {n}: registry rows") diff --git a/tests/system/test_reports_and_policy.py b/tests/system/test_reports_and_policy.py index db02da9..1f01679 100644 --- a/tests/system/test_reports_and_policy.py +++ b/tests/system/test_reports_and_policy.py @@ -97,8 +97,9 @@ def setUpClass(cls): migrate_tenant(cls.slug) cls.auth = {} for who in roles: - res = cls.client.post("/api/auth/login", json={ - "tenant": cls.slug, "username": f"{cls.slug}_{who}", "password": _PW}) + res = cls.client.post( + "/api/auth/login", json={"tenant": cls.slug, "username": f"{cls.slug}_{who}", "password": _PW} + ) assert res.status_code == 200, res.text cls.auth[who] = {"Authorization": f"Bearer {res.json()['token']}"} @@ -117,8 +118,11 @@ def setUp(self): self.tag = uuid.uuid4().hex[:8] def upload(self, who, name, content, **extra): - res = self.client.post("/api/csv/upload", headers=self.auth[who], - json={"fileName": f"{self.tag}_{name}", "content": content, **extra}) + res = self.client.post( + "/api/csv/upload", + headers=self.auth[who], + json={"fileName": f"{self.tag}_{name}", "content": content, **extra}, + ) self.assertEqual(res.status_code, 200, res.text) return res.json() @@ -153,8 +157,9 @@ def test_time_window_is_from_inclusive_to_exclusive_and_accepts_a_date(self): now = datetime.now(timezone.utc) self.assertEqual(self.events(**{"from": (now + timedelta(hours=1)).isoformat()})["total"], 0) self.assertEqual(self.events(**{"to": (now - timedelta(hours=1)).isoformat()})["total"], 0) - everything = self.events(**{"from": (now - timedelta(hours=1)).isoformat(), - "to": (now + timedelta(hours=1)).isoformat()})["total"] + everything = self.events( + **{"from": (now - timedelta(hours=1)).isoformat(), "to": (now + timedelta(hours=1)).isoformat()} + )["total"] self.assertEqual(everything, 3) self.assertEqual(self.events(**{"from": "2020-01-01"})["total"], 3) @@ -179,23 +184,39 @@ def test_a_tenant_sees_only_its_own_events(self): self.assertEqual(no_session["total"], 0) def test_csv_export_matches_the_filter_and_carries_the_marking(self): - res = self.client.get("/api/audit/events", headers=self.auth["au"], - params={"file": self.tag, "action": "upload", "format": "csv"}) + res = self.client.get( + "/api/audit/events", headers=self.auth["au"], params={"file": self.tag, "action": "upload", "format": "csv"} + ) self.assertEqual((res.status_code, res.headers["content-type"].split(";")[0]), (200, "text/csv")) self.assertEqual(res.headers["x-data-classification"], settings.DATA_CLASSIFICATION) self.assertEqual(res.headers["x-total-count"], "2") rows = list(csv.DictReader(io.StringIO(res.text))) self.assertEqual([r["action"] for r in rows], ["upload", "upload"]) - self.assertEqual(list(rows[0]), ["id", "performed_at", "actor", "action", "file_id", "file_name", "table_name", - "mode", "before_value", "after_value"]) + self.assertEqual( + list(rows[0]), + [ + "id", + "performed_at", + "actor", + "action", + "file_id", + "file_name", + "table_name", + "mode", + "before_value", + "after_value", + ], + ) def test_csv_export_neutralises_formulas_in_user_supplied_names(self): name = f'={self.tag}_HYPERLINK("http://example.invalid")' - res = self.client.post("/api/csv/upload", headers=self.auth["ad"], json={ - "fileName": name, "content": f"k\n{self.tag}3\n"}) + res = self.client.post( + "/api/csv/upload", headers=self.auth["ad"], json={"fileName": name, "content": f"k\n{self.tag}3\n"} + ) self.assertEqual(res.json()["status"], "ok", res.text) - report = self.client.get("/api/audit/events", headers=self.auth["au"], - params={"file": f"{self.tag}_HYPERLINK", "format": "csv"}) + report = self.client.get( + "/api/audit/events", headers=self.auth["au"], params={"file": f"{self.tag}_HYPERLINK", "format": "csv"} + ) [row] = list(csv.DictReader(io.StringIO(report.text))) self.assertEqual(row["file_name"], "'" + name) @@ -204,9 +225,9 @@ def test_csv_export_neutralises_formulas_in_user_supplied_names(self): class UploadFailureReasons(_Base): def test_every_outcome_can_be_filtered_and_failures_say_why(self): self.upload("up", "good.csv", f"k\n{self.tag}\n") - self.upload("up", "dup.csv", f"k\n{self.tag}\n") # duplicate - self.upload("up", "bad.csv", f"n\nx{self.tag}\n", types=["int8"]) # every row fails - self.upload("ad", "empty.csv", "only,a,header\n") # rejected + self.upload("up", "dup.csv", f"k\n{self.tag}\n") # duplicate + self.upload("up", "bad.csv", f"n\nx{self.tag}\n", types=["int8"]) # every row fails + self.upload("ad", "empty.csv", "only,a,header\n") # rejected res = self.client.get("/api/csv/uploads", headers=self.auth["au"], params={"file": self.tag}) self.assertEqual(res.status_code, 200, res.text) by_status = {u["status"]: u for u in res.json()} @@ -219,6 +240,7 @@ def test_every_outcome_can_be_filtered_and_failures_say_why(self): def test_filters_combine(self): self.upload("up", "a.csv", f"k\n{self.tag}a\n") self.upload("ad", "b.csv", f"k\n{self.tag}b\n") + def listing(**p): return self.client.get("/api/csv/uploads", headers=self.auth["au"], params={"file": self.tag, **p}).json() @@ -229,8 +251,9 @@ def listing(**p): future = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat() self.assertEqual(listing(**{"from": future}), []) self.assertEqual(len(listing(**{"to": future})), 2) - self.assertEqual(self.client.get("/api/csv/uploads", headers=self.auth["au"], - params={"status": "bogus"}).status_code, 422) + self.assertEqual( + self.client.get("/api/csv/uploads", headers=self.auth["au"], params={"status": "bogus"}).status_code, 422 + ) @pytest.mark.integration @@ -260,11 +283,15 @@ def test_every_api_area_marks_its_responses(self): self.assertEqual(res.headers[policy.HEADER], "OFFICIAL: Sensitive") def test_the_marking_follows_the_deployment_setting(self): - with patch.object(settings, "DATA_CLASSIFICATION", "OFFICIAL"), patch.object(settings, "AUDIT_RETENTION_YEARS", 10): + with ( + patch.object(settings, "DATA_CLASSIFICATION", "OFFICIAL"), + patch.object(settings, "AUDIT_RETENTION_YEARS", 10), + ): res = self.client.get("/api/policy", headers=self.auth["up"]) self.assertEqual((res.headers[policy.HEADER], res.json()["auditRetentionYears"]), ("OFFICIAL", 10)) - self.assertEqual(self.client.get("/api/audit/events", headers=self.auth["au"]).json()["classification"], - "OFFICIAL") + self.assertEqual( + self.client.get("/api/audit/events", headers=self.auth["au"]).json()["classification"], "OFFICIAL" + ) def test_a_browser_can_read_the_marking(self): res = self.client.get("/api/policy", headers={"Origin": "http://localhost:5173"}) diff --git a/tests/system/test_require_type_confirmation.py b/tests/system/test_require_type_confirmation.py index c18501e..2b72db5 100644 --- a/tests/system/test_require_type_confirmation.py +++ b/tests/system/test_require_type_confirmation.py @@ -105,9 +105,15 @@ def test_on_accepts_confirmed_types_on_both_endpoints(self): def test_on_does_not_touch_te_mode(self): settings.REQUIRE_TYPE_CONFIRMATION = True - res = self.client.post("/api/csv/upload", json={ - "fileName": f"req_te_{self.tag}.csv", "mode": "te", "targetTable": "organisations", - "content": f"name,org_type,country\nREQ_{self.tag},government,AU\n"}) + res = self.client.post( + "/api/csv/upload", + json={ + "fileName": f"req_te_{self.tag}.csv", + "mode": "te", + "targetTable": "organisations", + "content": f"name,org_type,country\nREQ_{self.tag},government,AU\n", + }, + ) self.assertEqual(res.status_code, 200, res.text) self.assertEqual(res.json()["status"], "ok", res.text) diff --git a/tests/system/test_review.py b/tests/system/test_review.py index db5c826..f62d7c1 100644 --- a/tests/system/test_review.py +++ b/tests/system/test_review.py @@ -34,8 +34,9 @@ def setUp(self): self.tag = f"{os.getpid()}_{uuid.uuid4().hex[:8]}" def _upload(self, content: str, types: list[str]) -> dict: - return self.client.post("/api/csv/upload", json={ - "fileName": f"rev_{self.tag}.csv", "content": content, "types": types}).json() + return self.client.post( + "/api/csv/upload", json={"fileName": f"rev_{self.tag}.csv", "content": content, "types": types} + ).json() def _three_rows(self) -> str: res = self._upload(f"n,t\n1,{self.tag}\nx,b\n3,c\n", ["int8", "text"]) @@ -48,12 +49,14 @@ def _rows(self, uid: str, **params) -> dict: return res.json() def _decide(self, uid: str, row: int, decision: str, reason: str = "checked with the owner"): - return self.client.put(f"/api/csv/uploads/{uid}/rows/{row}/decision", - json={"decision": decision, "reason": reason}) + return self.client.put( + f"/api/csv/uploads/{uid}/rows/{row}/decision", json={"decision": decision, "reason": reason} + ) def _edit(self, uid: str, row: int, column: str, value: str, reason: str = "typo in source"): - return self.client.put(f"/api/csv/uploads/{uid}/rows/{row}/cells/{column}", - json={"value": value, "reason": reason}) + return self.client.put( + f"/api/csv/uploads/{uid}/rows/{row}/cells/{column}", json={"value": value, "reason": reason} + ) def test_pages_through_every_row_with_validation(self): uid = self._three_rows() @@ -80,31 +83,45 @@ def test_row_decisions_record_actor_and_reason_and_the_latest_wins(self): self.assertEqual(self._decide(uid, 2, "include", "fixed upstream").json()["decision"], "include") self.assertEqual(self._rows(uid)["excludedRows"], 0) history = self.client.get(f"/api/csv/uploads/{uid}/rows/2/history").json() - self.assertEqual([(h["decision"], h["actor"], h["reason"]) for h in history], - [("exclude", "anonymous", "checked with the owner"), ("include", "anonymous", "fixed upstream")]) + self.assertEqual( + [(h["decision"], h["actor"], h["reason"]) for h in history], + [("exclude", "anonymous", "checked with the owner"), ("include", "anonymous", "fixed upstream")], + ) def test_cell_edits_are_versions_over_the_unchanged_original(self): uid = self._three_rows() row = self._edit(uid, 2, "n", "2").json() - self.assertEqual((row["original"], row["current"], row["editedColumns"], row["errors"]), - (["x", "b"], ["2", "b"], [0], [])) + self.assertEqual( + (row["original"], row["current"], row["editedColumns"], row["errors"]), (["x", "b"], ["2", "b"], [0], []) + ) self.assertEqual(self._edit(uid, 2, "0", "20", "second look").json()["current"], ["20", "b"]) edits = [h for h in self.client.get(f"/api/csv/uploads/{uid}/rows/2/history").json() if h["kind"] == "edit"] - self.assertEqual([(e["column"], e["oldValue"], e["newValue"], e["reason"]) for e in edits], - [("n", "x", "2", "typo in source"), ("n", "2", "20", "second look")]) - with Conn() as conn, conn.cursor() as cur: # M3's original is untouched - cur.execute(sql.SQL("SELECT cells FROM {}.source_rows WHERE upload_id = %s AND row_number = 2") - .format(sql.Identifier(settings.UPLOADS_SCHEMA)), (int(uid),)) + self.assertEqual( + [(e["column"], e["oldValue"], e["newValue"], e["reason"]) for e in edits], + [("n", "x", "2", "typo in source"), ("n", "2", "20", "second look")], + ) + with Conn() as conn, conn.cursor() as cur: # M3's original is untouched + cur.execute( + sql.SQL("SELECT cells FROM {}.source_rows WHERE upload_id = %s AND row_number = 2").format( + sql.Identifier(settings.UPLOADS_SCHEMA) + ), + (int(uid),), + ) self.assertEqual(cur.fetchone()[0], ["x", "b"]) listed = [f for f in self.client.get("/api/csv/files").json() if f["upload_id"] == uid] self.assertEqual(listed[0]["row_count"], 2, "decision 1: the imported table doesn't change until M6") def test_refusals(self): uid = self._three_rows() - for res, code in ((self._decide(uid, 2, "exclude", " "), 422), (self._edit(uid, 2, "n", "5", ""), 422), - (self._decide(uid, 2, "maybe"), 422), (self._edit(uid, 2, "n", "x"), 422), - (self._decide(uid, 4, "exclude"), 404), (self._edit(uid, 1, "nope", "1"), 404), - (self.client.get("/api/csv/uploads/999999999/rows"), 404)): + for res, code in ( + (self._decide(uid, 2, "exclude", " "), 422), + (self._edit(uid, 2, "n", "5", ""), 422), + (self._decide(uid, 2, "maybe"), 422), + (self._edit(uid, 2, "n", "x"), 422), + (self._decide(uid, 4, "exclude"), 404), + (self._edit(uid, 1, "nope", "1"), 404), + (self.client.get("/api/csv/uploads/999999999/rows"), 404), + ): with self.subTest(body=res.text): self.assertEqual(res.status_code, code) self.assertEqual(self.client.get(f"/api/csv/uploads/{uid}/rows/2/history").json(), []) @@ -114,9 +131,15 @@ def test_te_review_shows_the_database_reason_a_row_was_rejected(self): # #190: T&E uploads stored no types, so review said errors: [] for a row the CHECK rejected. good, bad = f"TE_REV_{self.tag}_ok", f"TE_REV_{self.tag}_bad" self.te_org_cleanup.extend([good, bad]) - res = self.client.post("/api/csv/upload", json={ - "fileName": f"te_rev_{self.tag}.csv", "mode": "te", "targetTable": "organisations", - "content": f"name,org_type,country\n{good},government,AU\n{bad},not_a_type,AU\n"}).json() + res = self.client.post( + "/api/csv/upload", + json={ + "fileName": f"te_rev_{self.tag}.csv", + "mode": "te", + "targetTable": "organisations", + "content": f"name,org_type,country\n{good},government,AU\n{bad},not_a_type,AU\n", + }, + ).json() self.assertEqual(res["failedRows"], 1, res) page = self._rows(res["uploadId"]) self.assertEqual(len(page["types"]), 3) @@ -135,14 +158,20 @@ def test_changes_are_audited_and_insert_only(self): self._edit(uid, 2, "n", "2") with Conn() as conn, conn.cursor() as cur: s = sql.Identifier(settings.UPLOADS_SCHEMA) - cur.execute(sql.SQL("SELECT action, before_value, after_value FROM {}.audit_log " - "WHERE after_value->>'upload' = %s ORDER BY id").format(s), (uid,)) + cur.execute( + sql.SQL( + "SELECT action, before_value, after_value FROM {}.audit_log " + "WHERE after_value->>'upload' = %s ORDER BY id" + ).format(s), + (uid,), + ) [(a1, b1, f1), (a2, b2, f2)] = cur.fetchall() self.assertEqual((a1, b1["decision"], f1["decision"]), ("row_decision", "include", "exclude")) self.assertEqual((a2, b2["value"], f2["value"], f2["column"]), ("cell_edit", "x", "2", "n")) for table in ("row_decisions", "cell_edits"): with self.subTest(table=table), self.assertRaises(psycopg2.errors.InsufficientPrivilege): - cur.execute(sql.SQL("DELETE FROM {}.{} WHERE upload_id = %s").format(s, sql.Identifier(table)), - (int(uid),)) + cur.execute( + sql.SQL("DELETE FROM {}.{} WHERE upload_id = %s").format(s, sql.Identifier(table)), (int(uid),) + ) conn.rollback() self.assertTrue(self.client.get("/api/audit/verify").json()["intact"]) diff --git a/tests/system/test_review_cases.py b/tests/system/test_review_cases.py index c173c96..e21e31b 100644 --- a/tests/system/test_review_cases.py +++ b/tests/system/test_review_cases.py @@ -50,8 +50,9 @@ def setUpClass(cls): for key, slug in cls.tenants.items(): migrate_tenant(slug) for role in ROLES: - res = cls.client.post("/api/auth/login", json={ - "tenant": slug, "username": cls.users[(key, role)], "password": _PW}) + res = cls.client.post( + "/api/auth/login", json={"tenant": slug, "username": cls.users[(key, role)], "password": _PW} + ) assert res.status_code == 200, res.text cls.headers[(key, role)] = {"Authorization": f"Bearer {res.json()['token']}"} @@ -61,10 +62,18 @@ def tearDownClass(cls): with conn.cursor() as cur: for slug in cls.tenants.values(): cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(slug)))) - cur.execute(sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (slug,)) - cur.execute(sql.SQL("DELETE FROM {}.users WHERE username LIKE %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (f"{slug}_%",)) + cur.execute( + sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (slug,), + ) + cur.execute( + sql.SQL("DELETE FROM {}.users WHERE username LIKE %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (f"{slug}_%",), + ) conn.commit() cls.ctx.__exit__(None, None, None) @@ -74,8 +83,11 @@ def _h(self, role: str = "tenant_admin", tenant: str = "a") -> dict: def _upload(self, content: str, types: list[str], tenant: str = "a") -> dict: tag = uuid.uuid4().hex[:10] - return self.client.post("/api/csv/upload", headers=self._h(tenant=tenant), json={ - "fileName": f"case_{tag}.csv", "content": content.replace("{tag}", tag), "types": types}).json() + return self.client.post( + "/api/csv/upload", + headers=self._h(tenant=tenant), + json={"fileName": f"case_{tag}.csv", "content": content.replace("{tag}", tag), "types": types}, + ).json() def _three(self, tenant: str = "a") -> str: res = self._upload("n,t\n1,{tag}\nx,b\n3,c\n", ["int8", "text"], tenant) @@ -89,12 +101,14 @@ def _put(self, path: str, body: dict, role: str = "tenant_admin", tenant: str = return self.client.put(path, headers=self._h(role, tenant), json=body) def _decide(self, uid, row, decision="exclude", reason="case reason", role="tenant_admin", tenant="a"): - return self._put(f"/api/csv/uploads/{uid}/rows/{row}/decision", - {"decision": decision, "reason": reason}, role, tenant) + return self._put( + f"/api/csv/uploads/{uid}/rows/{row}/decision", {"decision": decision, "reason": reason}, role, tenant + ) def _edit(self, uid, row, column, value, reason="case reason", role="tenant_admin", tenant="a"): - return self._put(f"/api/csv/uploads/{uid}/rows/{row}/cells/{column}", - {"value": value, "reason": reason}, role, tenant) + return self._put( + f"/api/csv/uploads/{uid}/rows/{row}/cells/{column}", {"value": value, "reason": reason}, role, tenant + ) # positive ------------------------------------------------------------ def test_P02_paging_bounds(self): @@ -140,10 +154,10 @@ def test_P11_actor_is_the_signed_in_user(self): uid = self._three() self._decide(uid, 1, role="reviewer") self._edit(uid, 2, "n", "2", role="tenant_admin") - actors = {h["kind"]: h["actor"] for r in (1, 2) - for h in self._get(f"/api/csv/uploads/{uid}/rows/{r}/history").json()} - self.assertEqual(actors, {"decision": self.users[("a", "reviewer")], - "edit": self.users[("a", "tenant_admin")]}) + actors = { + h["kind"]: h["actor"] for r in (1, 2) for h in self._get(f"/api/csv/uploads/{uid}/rows/{r}/history").json() + } + self.assertEqual(actors, {"decision": self.users[("a", "reviewer")], "edit": self.users[("a", "tenant_admin")]}) def test_P12_every_role_can_view_rows_and_history(self): uid = self._three() @@ -166,8 +180,11 @@ def test_N06_column_index_out_of_range(self): self.assertEqual(self._edit(uid, 1, "2", "x").status_code, 404) def test_N07_unknown_upload_on_every_route(self): - for res in (self._decide(999_999_999, 1), self._edit(999_999_999, 1, "n", "1"), - self._get("/api/csv/uploads/999999999/rows/1/history")): + for res in ( + self._decide(999_999_999, 1), + self._edit(999_999_999, 1, "n", "1"), + self._get("/api/csv/uploads/999999999/rows/1/history"), + ): with self.subTest(url=str(res.url)): self.assertEqual(res.status_code, 404) @@ -183,8 +200,12 @@ def test_N10_an_invalid_session_is_refused(self): uid = self._three() bad = {"Authorization": "Bearer not-a-real-token"} self.assertEqual(self.client.get(f"/api/csv/uploads/{uid}/rows", headers=bad).status_code, 401) - self.assertEqual(self.client.put(f"/api/csv/uploads/{uid}/rows/1/decision", headers=bad, - json={"decision": "exclude", "reason": "x"}).status_code, 401) + self.assertEqual( + self.client.put( + f"/api/csv/uploads/{uid}/rows/1/decision", headers=bad, json={"decision": "exclude", "reason": "x"} + ).status_code, + 401, + ) def test_N11_another_tenant_cannot_see_or_change_the_upload(self): uid = self._three(tenant="a") @@ -196,10 +217,12 @@ def test_N11_another_tenant_cannot_see_or_change_the_upload(self): def test_N12_missing_or_wrong_body_fields(self): uid = self._three() - for path, body in ((f"/api/csv/uploads/{uid}/rows/1/decision", {"decision": "exclude"}), - (f"/api/csv/uploads/{uid}/rows/1/decision", {"reason": "r"}), - (f"/api/csv/uploads/{uid}/rows/1/cells/n", {"reason": "r"}), - (f"/api/csv/uploads/{uid}/rows/1/cells/n", {"value": 5, "reason": "r"})): + for path, body in ( + (f"/api/csv/uploads/{uid}/rows/1/decision", {"decision": "exclude"}), + (f"/api/csv/uploads/{uid}/rows/1/decision", {"reason": "r"}), + (f"/api/csv/uploads/{uid}/rows/1/cells/n", {"reason": "r"}), + (f"/api/csv/uploads/{uid}/rows/1/cells/n", {"value": 5, "reason": "r"}), + ): with self.subTest(body=body): self.assertEqual(self._put(path, body).status_code, 422) @@ -208,9 +231,14 @@ def test_N13_review_tables_reject_update_delete_and_truncate(self): self._decide(uid, 1) self._edit(uid, 2, "n", "2") s = sql.Identifier(schema_for(self.tenants["a"])) - for statement in ("UPDATE {}.row_decisions SET reason = 'x'", "DELETE FROM {}.row_decisions", - "TRUNCATE {}.row_decisions", "UPDATE {}.cell_edits SET new_value = 'x'", - "DELETE FROM {}.cell_edits", "TRUNCATE {}.cell_edits"): + for statement in ( + "UPDATE {}.row_decisions SET reason = 'x'", + "DELETE FROM {}.row_decisions", + "TRUNCATE {}.row_decisions", + "UPDATE {}.cell_edits SET new_value = 'x'", + "DELETE FROM {}.cell_edits", + "TRUNCATE {}.cell_edits", + ): with self.subTest(statement=statement), Conn() as conn, conn.cursor() as cur: with self.assertRaises(psycopg2.errors.InsufficientPrivilege): cur.execute(sql.SQL(statement).format(s)) @@ -220,10 +248,16 @@ def test_N14_database_rejects_a_blank_reason(self): uid = self._three() s = sql.Identifier(schema_for(self.tenants["a"])) for statement, args in ( - ("INSERT INTO {}.row_decisions (upload_id, row_number, decision, reason) VALUES (%s, 1, 'exclude', ' ')", - (int(uid),)), - ("INSERT INTO {}.cell_edits (upload_id, row_number, column_index, old_value, new_value, reason) " - "VALUES (%s, 1, 0, '1', '2', '')", (int(uid),))): + ( + "INSERT INTO {}.row_decisions (upload_id, row_number, decision, reason) VALUES (%s, 1, 'exclude', ' ')", + (int(uid),), + ), + ( + "INSERT INTO {}.cell_edits (upload_id, row_number, column_index, old_value, new_value, reason) " + "VALUES (%s, 1, 0, '1', '2', '')", + (int(uid),), + ), + ): with self.subTest(statement=statement[:40]), Conn() as conn, conn.cursor() as cur: with self.assertRaises(psycopg2.errors.CheckViolation): cur.execute(sql.SQL(statement).format(s), args) diff --git a/tests/system/test_roles.py b/tests/system/test_roles.py index ac53e88..8040714 100644 --- a/tests/system/test_roles.py +++ b/tests/system/test_roles.py @@ -46,7 +46,7 @@ def _doc_matrix() -> dict[str, frozenset[str]]: rows = [ln for ln in _DOC.read_text(encoding="utf-8").splitlines() if ln.startswith("| ")] header = [c.strip() for c in rows[0].strip("|").split("|")] out = {} - for ln in rows[1:]: # the |---| separator does not start with "| " + for ln in rows[1:]: # the |---| separator does not start with "| " cells = [c.strip() for c in ln.strip("|").split("|")] out[cells[0]] = frozenset(r for r, c in zip(header[2:], cells[2:]) if c == "✓") return out @@ -82,8 +82,9 @@ def setUpClass(cls): conn.commit() migrate_tenant(cls.slug) for role in ROLES: - res = cls.client.post("/api/auth/login", json={ - "tenant": cls.slug, "username": f"{cls.slug}_{role}", "password": _PW}) + res = cls.client.post( + "/api/auth/login", json={"tenant": cls.slug, "username": f"{cls.slug}_{role}", "password": _PW} + ) assert res.status_code == 200, res.text cls.headers[role] = {"Authorization": f"Bearer {res.json()['token']}"} @@ -93,17 +94,26 @@ def tearDownClass(cls): with Conn() as conn: with conn.cursor() as cur: cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(cls.slug)))) - cur.execute(sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (cls.slug,)) - cur.execute(sql.SQL("DELETE FROM {}.users WHERE username LIKE %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (f"{cls.slug}_%",)) + cur.execute( + sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format(sql.Identifier(settings.CONTROL_SCHEMA)), + (cls.slug,), + ) + cur.execute( + sql.SQL("DELETE FROM {}.users WHERE username LIKE %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (f"{cls.slug}_%",), + ) conn.commit() cls.ctx.__exit__(None, None, None) def _file(self) -> tuple[str, str, str]: tag = uuid.uuid4().hex[:10] - res = self.client.post("/api/csv/upload", headers=self.headers["tenant_admin"], - json={"fileName": f"r_{tag}.csv", "content": f"k\n{tag}\n"}).json() + res = self.client.post( + "/api/csv/upload", + headers=self.headers["tenant_admin"], + json={"fileName": f"r_{tag}.csv", "content": f"k\n{tag}\n"}, + ).json() assert res["status"] == "ok", res return res["tableName"], res["fileId"], res["uploadId"] @@ -119,8 +129,12 @@ def _call(self, role: str, action: str) -> int: user = f"{self.slug}_t{uuid.uuid4().hex[:6]}" with Conn() as conn: with conn.cursor() as cur: - cur.execute(sql.SQL("SELECT id FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (self.slug,)) + cur.execute( + sql.SQL("SELECT id FROM {}.tenants WHERE slug = %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (self.slug,), + ) tid = cur.fetchone()[0] accounts.add_membership(cur, accounts.create_user(cur, user, _PW), tid, "uploader") conn.commit() @@ -129,8 +143,12 @@ def _call(self, role: str, action: str) -> int: body = {"decision": "exclude", "reason": "role matrix test"} if action == "approve_import": body = {"decision": "reject", "reason": "role matrix test"} - res = self.client.request(method, path.format(table=table, id=file_id, user=user, upload=upload_id), - headers=self.headers[role], json=body) + res = self.client.request( + method, + path.format(table=table, id=file_id, user=user, upload=upload_id), + headers=self.headers[role], + json=body, + ) return res.status_code def test_every_role_against_every_route(self): diff --git a/tests/system/test_runtime_role.py b/tests/system/test_runtime_role.py index 3efc206..d899832 100644 --- a/tests/system/test_runtime_role.py +++ b/tests/system/test_runtime_role.py @@ -35,8 +35,13 @@ def _owner(): - return psycopg2.connect(host=settings.PG_HOST, port=settings.PG_PORT, user=settings.PG_USER, - password=settings.PG_PASSWORD.get_secret_value(), dbname=settings.PG_DATABASE) + return psycopg2.connect( + host=settings.PG_HOST, + port=settings.PG_PORT, + user=settings.PG_USER, + password=settings.PG_PASSWORD.get_secret_value(), + dbname=settings.PG_DATABASE, + ) @pytest.mark.integration @@ -48,9 +53,21 @@ def setUpClass(cls): env_file = Path(cls.tmp.name) / "app-db.env" # RV-S3 (#173): --env is mandatory. The role and credential file are # still overridden here so each run gets a unique, disposable role. - run = subprocess.run([sys.executable, "scripts/create_app_role.py", "--env", "test", - "--role", cls.role, "--env-file", str(env_file)], - cwd=_ROOT, capture_output=True, text=True) + run = subprocess.run( + [ + sys.executable, + "scripts/create_app_role.py", + "--env", + "test", + "--role", + cls.role, + "--env-file", + str(env_file), + ], + cwd=_ROOT, + capture_output=True, + text=True, + ) assert run.returncode == 0, run.stderr cls.script_stdout = run.stdout values = dict(line.split("=", 1) for line in env_file.read_text().splitlines()) @@ -70,8 +87,13 @@ def tearDownClass(cls): cls.tmp.cleanup() def _as_runtime(self): - return psycopg2.connect(host=settings.PG_HOST, port=settings.PG_PORT, user=settings.APP_DB_USER, - password=settings.APP_DB_PASSWORD.get_secret_value(), dbname=settings.PG_DATABASE) + return psycopg2.connect( + host=settings.PG_HOST, + port=settings.PG_PORT, + user=settings.APP_DB_USER, + password=settings.APP_DB_PASSWORD.get_secret_value(), + dbname=settings.PG_DATABASE, + ) def test_script_keeps_the_password_out_of_its_output(self): self.assertIn(self.role, self.script_stdout) @@ -84,19 +106,24 @@ def test_the_api_works_as_the_runtime_role(self): up = self.client.post("/api/csv/upload", json={"fileName": name, "content": f"v\n{name}\n"}).json() self.assertEqual(up["status"], "ok", up) self.assertIsNotNone(up["uploadId"], "the original must be stored by the runtime role") - over = self.client.post("/api/csv/upload", json={ - "fileName": name, "content": f"v\nnew_{name}\n", "overwrite": True}).json() + over = self.client.post( + "/api/csv/upload", json={"fileName": name, "content": f"v\nnew_{name}\n", "overwrite": True} + ).json() self.assertEqual(over["status"], "ok", over) # P15 (docs/test-cases/M4-review.md): review changes work through the runtime role. - decided = self.client.put(f"/api/csv/uploads/{up['uploadId']}/rows/1/decision", - json={"decision": "exclude", "reason": "runtime role case"}) + decided = self.client.put( + f"/api/csv/uploads/{up['uploadId']}/rows/1/decision", + json={"decision": "exclude", "reason": "runtime role case"}, + ) self.assertEqual(decided.status_code, 200, decided.text) - edited = self.client.put(f"/api/csv/uploads/{up['uploadId']}/rows/1/cells/v", - json={"value": "changed", "reason": "runtime role case"}) + edited = self.client.put( + f"/api/csv/uploads/{up['uploadId']}/rows/1/cells/v", + json={"value": "changed", "reason": "runtime role case"}, + ) self.assertEqual(edited.status_code, 200, edited.text) self.assertEqual(self.client.delete(f"/api/csv/files/{over['fileId']}").status_code, 200) self.assertTrue(self.client.get("/api/audit/verify").json()["intact"]) - with Conn() as conn, conn.cursor() as cur: # the API's own request pool + with Conn() as conn, conn.cursor() as cur: # the API's own request pool cur.execute("SELECT current_user") self.assertEqual(cur.fetchone()[0], self.role) @@ -114,12 +141,26 @@ def test_the_staged_import_works_as_the_runtime_role(self): def test_runtime_role_cannot_change_or_unprotect_append_only_tables(self): schema = settings.UPLOADS_SCHEMA - tables = ("audit_log", "uploads", "upload_blobs", "source_rows", "row_decisions", "cell_edits", "row_flags", - "submissions", "approvals", "imports") + tables = ( + "audit_log", + "uploads", + "upload_blobs", + "source_rows", + "row_decisions", + "cell_edits", + "row_flags", + "submissions", + "approvals", + "imports", + ) statements = [f"{verb} {{}}.{table}" for table in tables for verb in ("DELETE FROM", "TRUNCATE")] - statements += ["UPDATE {}.audit_log SET actor = 'x'", "UPDATE {}.uploads SET status = 'failed'", - "UPDATE {}.row_decisions SET reason = 'x'", "UPDATE {}.cell_edits SET new_value = 'x'", # N15 - "ALTER TABLE {}.audit_log DISABLE TRIGGER audit_no_change"] + statements += [ + "UPDATE {}.audit_log SET actor = 'x'", + "UPDATE {}.uploads SET status = 'failed'", + "UPDATE {}.row_decisions SET reason = 'x'", + "UPDATE {}.cell_edits SET new_value = 'x'", # N15 + "ALTER TABLE {}.audit_log DISABLE TRIGGER audit_no_change", + ] conn = self._as_runtime() try: for statement in statements: @@ -129,9 +170,12 @@ def test_runtime_role_cannot_change_or_unprotect_append_only_tables(self): # Refused by privilege, not by the trigger: the owner's triggers are a second layer. self.assertNotIn("append-only", str(caught.exception)) conn.rollback() - with conn.cursor() as cur: # inserting into the audit log still works - cur.execute(sql.SQL("INSERT INTO {}.audit_log (action, actor) VALUES ('upload', 'role-test')") - .format(sql.Identifier(schema))) + with conn.cursor() as cur: # inserting into the audit log still works + cur.execute( + sql.SQL("INSERT INTO {}.audit_log (action, actor) VALUES ('upload', 'role-test')").format( + sql.Identifier(schema) + ) + ) conn.rollback() finally: conn.close() @@ -142,7 +186,7 @@ def test_a_signed_in_tenant_works_through_its_own_role(self): with Conn() as conn, conn.cursor() as cur: tid = accounts.create_tenant(cur, slug, "Runtime role tenant") accounts.add_membership(cur, accounts.create_user(cur, f"{slug}_u", pw), tid, "tenant_admin") - accounts.set_self_approval(cur, slug, True) # one user here; also checks the session carries the flag + accounts.set_self_approval(cur, slug, True) # one user here; also checks the session carries the flag conn.commit() try: migrate_tenant(slug) @@ -154,8 +198,11 @@ def test_a_signed_in_tenant_works_through_its_own_role(self): self.assertEqual(up.json()["status"], "ok", up.text) uid = up.json()["uploadId"] for res in ( - self.client.put(f"/api/csv/uploads/{uid}/rows/1/decision", headers=h, - json={"decision": "exclude", "reason": "runtime role case"}), + self.client.put( + f"/api/csv/uploads/{uid}/rows/1/decision", + headers=h, + json={"decision": "exclude", "reason": "runtime role case"}, + ), self.client.get(f"/api/csv/uploads/{uid}/rows/1/history", headers=h), self.client.get(f"/api/csv/tables/{up.json()['tableName']}/rows", headers=h), self.client.get("/api/csv/uploads", headers=h), @@ -165,8 +212,9 @@ def test_a_signed_in_tenant_works_through_its_own_role(self): log = self.client.get("/api/audit/log?limit=50", headers=h).json()["entries"] self.assertIn(name, [e["fileName"] for e in log]) self.assertTrue(self.client.get("/api/audit/verify", headers=h).json()["intact"]) - staged = self.client.post("/api/csv/uploads", headers=h, - json={"fileName": "s_" + name, "content": "v\nstaged\n"}).json()["uploadId"] + staged = self.client.post( + "/api/csv/uploads", headers=h, json={"fileName": "s_" + name, "content": "v\nstaged\n"} + ).json()["uploadId"] for action, body in (("submit", None), ("approval", {"decision": "approve"})): res = self.client.post(f"/api/csv/uploads/{staged}/{action}", headers=h, json=body) self.assertEqual(res.status_code, 200, res.text) @@ -177,12 +225,14 @@ def test_a_signed_in_tenant_works_through_its_own_role(self): conn = self._as_runtime() try: with conn.cursor() as cur: - with self.assertRaises(psycopg2.errors.InsufficientPrivilege): # no rights without SET ROLE + with self.assertRaises(psycopg2.errors.InsufficientPrivilege): # no rights without SET ROLE cur.execute(sql.SQL("SELECT * FROM {}.csv_files").format(sql.Identifier(schema_for(slug)))) conn.rollback() - cur.execute("SELECT m.inherit_option, m.set_option FROM pg_auth_members m " - "WHERE m.roleid = to_regrole(%s) AND m.member = to_regrole(%s)", - (role_for(slug), self.role)) + cur.execute( + "SELECT m.inherit_option, m.set_option FROM pg_auth_members m " + "WHERE m.roleid = to_regrole(%s) AND m.member = to_regrole(%s)", + (role_for(slug), self.role), + ) self.assertEqual(cur.fetchone(), (False, True), "member WITH INHERIT FALSE, SET TRUE") cur.execute(sql.SQL("SET ROLE {}").format(sql.Identifier(role_for(slug)))) cur.execute(sql.SQL("SELECT count(*) FROM {}.csv_files").format(sql.Identifier(schema_for(slug)))) @@ -192,8 +242,12 @@ def test_a_signed_in_tenant_works_through_its_own_role(self): finally: with _owner() as conn, conn.cursor() as cur: cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(slug)))) - cur.execute(sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (slug,)) - cur.execute(sql.SQL("DELETE FROM {}.users WHERE username = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (f"{slug}_u",)) + cur.execute( + sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format(sql.Identifier(settings.CONTROL_SCHEMA)), + (slug,), + ) + cur.execute( + sql.SQL("DELETE FROM {}.users WHERE username = %s").format(sql.Identifier(settings.CONTROL_SCHEMA)), + (f"{slug}_u",), + ) drop_tenant_role(cur, slug) diff --git a/tests/system/test_runtime_role_per_env.py b/tests/system/test_runtime_role_per_env.py index 29c5d8a..f3b8260 100644 --- a/tests/system/test_runtime_role_per_env.py +++ b/tests/system/test_runtime_role_per_env.py @@ -68,21 +68,26 @@ def test_every_environment_gets_a_distinct_credential_file(self): def test_no_environment_reuses_the_pre_fix_names(self): """The cluster-wide names are what made provisioning cross-contaminate.""" for env in ENVIRONMENTS: - self.assertNotEqual(role_for(env), LEGACY_ROLE, - f"--env {env} still resolves to the shared role {LEGACY_ROLE}") - self.assertNotEqual(env_file_for(env), LEGACY_ENV_FILE, - f"--env {env} still resolves to the shared file {LEGACY_ENV_FILE}") + self.assertNotEqual( + role_for(env), LEGACY_ROLE, f"--env {env} still resolves to the shared role {LEGACY_ROLE}" + ) + self.assertNotEqual( + env_file_for(env), LEGACY_ENV_FILE, f"--env {env} still resolves to the shared file {LEGACY_ENV_FILE}" + ) def test_env_is_mandatory(self): """Without --env the script must refuse, not fall back to a shared default.""" - run = subprocess.run([sys.executable, "scripts/create_app_role.py"], - cwd=_ROOT, capture_output=True, text=True) + run = subprocess.run([sys.executable, "scripts/create_app_role.py"], cwd=_ROOT, capture_output=True, text=True) self.assertNotEqual(run.returncode, 0, "the script ran without --env") self.assertIn("--env", run.stderr, run.stderr) def test_an_unknown_environment_is_refused(self): - run = subprocess.run([sys.executable, "scripts/create_app_role.py", "--env", "producton"], - cwd=_ROOT, capture_output=True, text=True) + run = subprocess.run( + [sys.executable, "scripts/create_app_role.py", "--env", "producton"], + cwd=_ROOT, + capture_output=True, + text=True, + ) self.assertNotEqual(run.returncode, 0, "a misspelled environment was accepted") @@ -105,6 +110,7 @@ def setUp(self): def _retire(self, env: str): with unittest.mock.patch("scripts.create_app_role.LEGACY_ENV_FILE", self.legacy): from scripts.create_app_role import retire_legacy_credentials + return retire_legacy_credentials(env) def test_a_legacy_file_is_moved_aside_and_kept(self): @@ -113,8 +119,9 @@ def test_a_legacy_file_is_moved_aside_and_kept(self): self.assertIsNotNone(moved, "the legacy credential file was left in place") self.assertFalse(self.legacy.exists(), "start-api.ps1 would still read the legacy file") self.assertTrue(Path(moved).exists(), "the legacy file was deleted rather than moved aside") - self.assertIn("te_app", Path(moved).read_text(), - "the move must preserve the file, so it can be put back with one mv") + self.assertIn( + "te_app", Path(moved).read_text(), "the move must preserve the file, so it can be put back with one mv" + ) def test_a_clean_dev_pc_is_untouched(self): self.assertIsNone(self._retire("dev"), "reported a migration where there was no legacy file") @@ -162,8 +169,13 @@ def tearDownClass(cls): @staticmethod def _owner(): - return psycopg2.connect(host=settings.PG_HOST, port=settings.PG_PORT, user=settings.PG_USER, - password=settings.PG_PASSWORD.get_secret_value(), dbname=settings.PG_DATABASE) + return psycopg2.connect( + host=settings.PG_HOST, + port=settings.PG_PORT, + user=settings.PG_USER, + password=settings.PG_PASSWORD.get_secret_value(), + dbname=settings.PG_DATABASE, + ) @classmethod def _role_exists(cls, role: str) -> bool: @@ -178,20 +190,29 @@ def credentials(cls, env: str) -> dict[str, str]: if not path.exists(): run = subprocess.run( [sys.executable, "scripts/create_app_role.py", "--env", env, "--env-file", str(path)], - cwd=_ROOT, capture_output=True, text=True) + cwd=_ROOT, + capture_output=True, + text=True, + ) assert run.returncode == 0, run.stderr return dict(line.split("=", 1) for line in path.read_text().splitlines()) def _connect_as(self, creds: dict[str, str]): - return psycopg2.connect(host=settings.PG_HOST, port=settings.PG_PORT, - user=creds["APP_DB_USER"], password=creds["APP_DB_PASSWORD"], - dbname=settings.PG_DATABASE) + return psycopg2.connect( + host=settings.PG_HOST, + port=settings.PG_PORT, + user=creds["APP_DB_USER"], + password=creds["APP_DB_PASSWORD"], + dbname=settings.PG_DATABASE, + ) def test_the_two_environments_got_different_roles(self): - self.assertNotEqual(self.credentials(self.FIRST)["APP_DB_USER"], - self.credentials(self.SECOND)["APP_DB_USER"], - "both environments were given the same role, so provisioning one " - "rotates the other's password (RV-S3, #173)") + self.assertNotEqual( + self.credentials(self.FIRST)["APP_DB_USER"], + self.credentials(self.SECOND)["APP_DB_USER"], + "both environments were given the same role, so provisioning one " + "rotates the other's password (RV-S3, #173)", + ) def test_the_first_environments_credentials_still_work(self): """The regression: this failed once the second environment was provisioned.""" @@ -215,6 +236,7 @@ def test_the_second_environments_credentials_work_too(self): def test_the_credential_files_are_owner_readable_only(self): """Unchanged from M3d, re-asserted because the write path moved.""" import os + if os.name != "posix": self.skipTest("file modes are a POSIX concern") for env in (self.FIRST, self.SECOND): diff --git a/tests/system/test_session_idle_and_purge.py b/tests/system/test_session_idle_and_purge.py index 6cde47d..e548ffd 100644 --- a/tests/system/test_session_idle_and_purge.py +++ b/tests/system/test_session_idle_and_purge.py @@ -13,6 +13,7 @@ * ``scripts/purge_sessions.py`` does the same from the command line, and the API purges once at start-up without a purge failure ever stopping it from starting. """ + from __future__ import annotations import logging @@ -52,8 +53,11 @@ def _token(self) -> str: def _set(self, token: str, **ages) -> None: """Move columns of one session into the past: ``last_seen_at=timedelta`` style, given as SQL intervals.""" for column, interval in ages.items(): - self._exec(f"UPDATE {{c}}.sessions SET {column} = now() - %s::interval WHERE token_hash = %s", - interval, accounts._token_hash(token)) + self._exec( + f"UPDATE {{c}}.sessions SET {column} = now() - %s::interval WHERE token_hash = %s", + interval, + accounts._token_hash(token), + ) def _gone(self, token: str) -> bool: return not self._fetch("SELECT 1 FROM {c}.sessions WHERE token_hash = %s", accounts._token_hash(token)) @@ -75,7 +79,7 @@ def test_a_session_idle_past_the_limit_is_refused(self): self.assertEqual((res.status_code, res.json()["detail"]), (401, UNAUTHORISED)) def test_a_session_idle_past_the_limit_is_refused_on_a_data_route_too(self): - migrate_tenant(self.tenant) # real tenants always have their schema; the data route reads from it + migrate_tenant(self.tenant) # real tenants always have their schema; the data route reads from it token = self._token() self.assertEqual(self._files(token).status_code, 200, "an active session reaches the route") self._set(token, last_seen_at="31 minutes") @@ -102,16 +106,20 @@ def test_zero_turns_the_idle_check_off(self): def test_the_absolute_expiry_still_applies_to_an_active_session(self): token = self._token() - self._exec("UPDATE {c}.sessions SET expires_at = now() - interval '1 second' WHERE token_hash = %s", - accounts._token_hash(token)) + self._exec( + "UPDATE {c}.sessions SET expires_at = now() - interval '1 second' WHERE token_hash = %s", + accounts._token_hash(token), + ) self.assertEqual(self._me(token).status_code, 401) def test_activity_refreshes_last_seen_and_it_is_committed(self): token = self._token() self._set(token, last_seen_at="10 minutes") self.assertEqual(self._me(token).status_code, 200) - (age,), = self._fetch("SELECT extract(epoch FROM now() - last_seen_at) FROM {c}.sessions WHERE token_hash = %s", - accounts._token_hash(token)) # a different connection: only a commit shows + ((age,),) = self._fetch( + "SELECT extract(epoch FROM now() - last_seen_at) FROM {c}.sessions WHERE token_hash = %s", + accounts._token_hash(token), + ) # a different connection: only a commit shows self.assertLess(age, 60, f"last_seen_at was not refreshed (still {age:.0f} s old)") def test_a_request_inside_the_throttle_does_not_write(self): @@ -140,9 +148,18 @@ def _purge(self) -> int: def _kinds(self) -> dict[str, str]: """One session of each kind, for the same user: name -> token.""" - kinds = {name: self._token() for name in ( - "live", "expired_long_ago", "expired_recently", "revoked_long_ago", "revoked_recently", - "idle_long_ago", "idle_recently")} + kinds = { + name: self._token() + for name in ( + "live", + "expired_long_ago", + "expired_recently", + "revoked_long_ago", + "revoked_recently", + "idle_long_ago", + "idle_recently", + ) + } self._set(kinds["expired_long_ago"], expires_at="2 days") self._set(kinds["expired_recently"], expires_at="1 hour") self._set(kinds["revoked_long_ago"], revoked_at="2 days") @@ -164,8 +181,14 @@ def test_the_grace_period_follows_the_setting(self): kinds = self._kinds() with mock.patch.object(settings, "SESSION_PURGE_GRACE_DAYS", 0): self._purge() - for name in ("expired_long_ago", "expired_recently", "revoked_long_ago", "revoked_recently", - "idle_long_ago", "idle_recently"): + for name in ( + "expired_long_ago", + "expired_recently", + "revoked_long_ago", + "revoked_recently", + "idle_long_ago", + "idle_recently", + ): self.assertTrue(self._gone(kinds[name]), f"{name} should have been purged with no grace") self.assertFalse(self._gone(kinds["live"])) @@ -196,8 +219,14 @@ class PurgeScript(_Sessions): def test_the_script_purges_and_reports(self): old, live = self._token(), self._token() self._set(old, expires_at="3 days") - done = subprocess.run([sys.executable, "scripts/purge_sessions.py"], cwd=ROOT, env={**os.environ}, - capture_output=True, text=True, timeout=120) + done = subprocess.run( + [sys.executable, "scripts/purge_sessions.py"], + cwd=ROOT, + env={**os.environ}, + capture_output=True, + text=True, + timeout=120, + ) self.assertEqual(done.returncode, 0, done.stderr) self.assertRegex(done.stdout, r"Purged \d+ session") self.assertTrue(self._gone(old)) @@ -215,23 +244,31 @@ def _make_expired_session(self) -> str: tid = accounts.create_tenant(cur, f"su_{tag}", "Startup tenant") uid = accounts.create_user(cur, f"su_user_{tag}", _PW) accounts.add_membership(cur, uid, tid, "uploader") - cur.execute(sql.SQL("INSERT INTO {c}.sessions (token_hash, user_id, tenant_id, expires_at) " - "VALUES (%s, %s, %s, now() - interval '5 days')") - .format(c=sql.Identifier(settings.CONTROL_SCHEMA)), (f"th_{tag}", uid, tid)) + cur.execute( + sql.SQL( + "INSERT INTO {c}.sessions (token_hash, user_id, tenant_id, expires_at) " + "VALUES (%s, %s, %s, now() - interval '5 days')" + ).format(c=sql.Identifier(settings.CONTROL_SCHEMA)), + (f"th_{tag}", uid, tid), + ) conn.commit() return f"th_{tag}" def _exists(self, token_hash: str) -> bool: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT 1 FROM {c}.sessions WHERE token_hash = %s") - .format(c=sql.Identifier(settings.CONTROL_SCHEMA)), (token_hash,)) + cur.execute( + sql.SQL("SELECT 1 FROM {c}.sessions WHERE token_hash = %s").format( + c=sql.Identifier(settings.CONTROL_SCHEMA) + ), + (token_hash,), + ) return cur.fetchone() is not None def test_start_up_removes_old_sessions(self): - with TestClient(app): # the pool is open only while a client is; leaving it closes the pool + with TestClient(app): # the pool is open only while a client is; leaving it closes the pool token_hash = self._make_expired_session() self.assertTrue(self._exists(token_hash)) - with TestClient(app): # starting again purges + with TestClient(app): # starting again purges self.assertFalse(self._exists(token_hash), "the API did not purge on start-up") def test_a_purge_failure_does_not_stop_start_up(self): diff --git a/tests/system/test_sessions_required.py b/tests/system/test_sessions_required.py index 10c162d..06ccd5a 100644 --- a/tests/system/test_sessions_required.py +++ b/tests/system/test_sessions_required.py @@ -14,6 +14,7 @@ The suite runs with the anonymous opt-in on (tests/conftest.py); every test here switches it off. The 401 tests need no database. The session tests need PostgreSQL and fail, never skip, without it. """ + from __future__ import annotations import os @@ -71,8 +72,11 @@ def test_the_route_list_is_not_empty(self): self.assertGreater(len(_data_routes()), 20, _data_routes()) def test_every_data_route_needs_a_session(self): - wrong = [(method, path, res.status_code) for method, path in _data_routes() - if (res := self.client.request(method, path, json={})).status_code != 401] + wrong = [ + (method, path, res.status_code) + for method, path in _data_routes() + if (res := self.client.request(method, path, json={})).status_code != 401 + ] self.assertEqual(wrong, [], "these answered without a session") def test_api_env_dev_alone_is_not_anonymous(self): @@ -106,9 +110,14 @@ def test_the_shared_key_setting_is_gone(self): self.assertFalse(hasattr(settings, "API_KEY")) def test_cors_no_longer_offers_the_key_header(self): - res = self.client.options("/api/csv/files", headers={ - "Origin": settings.CORS_ORIGINS[0], "Access-Control-Request-Method": "GET", - "Access-Control-Request-Headers": "x-api-key"}) + res = self.client.options( + "/api/csv/files", + headers={ + "Origin": settings.CORS_ORIGINS[0], + "Access-Control-Request-Method": "GET", + "Access-Control-Request-Headers": "x-api-key", + }, + ) self.assertNotIn("x-api-key", res.headers.get("access-control-allow-headers", "").lower()) @@ -136,8 +145,9 @@ def setUpClass(cls): conn.commit() migrate_tenant(cls.slug) for role in ("uploader", "tenant_admin"): - res = cls.client.post("/api/auth/login", json={ - "tenant": cls.slug, "username": f"{cls.slug}_{role}", "password": _PW}) + res = cls.client.post( + "/api/auth/login", json={"tenant": cls.slug, "username": f"{cls.slug}_{role}", "password": _PW} + ) assert res.status_code == 200, res.text cls.headers[role] = {"Authorization": f"Bearer {res.json()['token']}"} @@ -147,10 +157,16 @@ def tearDownClass(cls): with Conn() as conn: with conn.cursor() as cur: cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(cls.slug)))) - cur.execute(sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (cls.slug,)) - cur.execute(sql.SQL("DELETE FROM {}.users WHERE username LIKE %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (f"{cls.slug}_%",)) + cur.execute( + sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format(sql.Identifier(settings.CONTROL_SCHEMA)), + (cls.slug,), + ) + cur.execute( + sql.SQL("DELETE FROM {}.users WHERE username LIKE %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (f"{cls.slug}_%",), + ) conn.commit() cls.ctx.__exit__(None, None, None) @@ -176,11 +192,23 @@ def test_an_uploader_may_not_delete(self): def test_an_uploader_may_not_replace_a_prior_load(self): tag = uuid.uuid4().hex[:10] name = f"te_{tag}.csv" - self._upload("tenant_admin", fileName=name, mode="te", targetTable="organisations", - content=f"name,org_type,country\nORG_A_{tag},government,AU\n") - again = self.client.post("/api/csv/upload", headers=self.headers["uploader"], json={ - "fileName": name, "mode": "te", "targetTable": "organisations", - "content": f"name,org_type,country\nORG_B_{tag},government,AU\n"}) + self._upload( + "tenant_admin", + fileName=name, + mode="te", + targetTable="organisations", + content=f"name,org_type,country\nORG_A_{tag},government,AU\n", + ) + again = self.client.post( + "/api/csv/upload", + headers=self.headers["uploader"], + json={ + "fileName": name, + "mode": "te", + "targetTable": "organisations", + "content": f"name,org_type,country\nORG_B_{tag},government,AU\n", + }, + ) self.assertEqual(again.status_code, 403, again.text) def test_the_audit_log_names_the_signed_in_user(self): diff --git a/tests/system/test_staged_import.py b/tests/system/test_staged_import.py index 6773601..f919c55 100644 --- a/tests/system/test_staged_import.py +++ b/tests/system/test_staged_import.py @@ -67,8 +67,9 @@ def setUpClass(cls): cls.auth: dict[str, dict] = {} for key, slug in cls.slugs.items(): for who in roles[key]: - res = cls.client.post("/api/auth/login", json={ - "tenant": slug, "username": f"{slug}_{who}", "password": _PW}) + res = cls.client.post( + "/api/auth/login", json={"tenant": slug, "username": f"{slug}_{who}", "password": _PW} + ) assert res.status_code == 200, res.text cls.auth[f"{key}_{who}"] = {"Authorization": f"Bearer {res.json()['token']}"} @@ -86,7 +87,7 @@ def tearDownClass(cls): def setUp(self): self.tag = uuid.uuid4().hex[:10] - self.one = f"k\n{self.tag}\n" # content no other test stages: the same bytes twice in a tenant are a duplicate + self.one = f"k\n{self.tag}\n" # content no other test stages: the same bytes twice in a tenant are a duplicate # -- API helpers; ``who`` is a key of cls.auth, or None for no session -------------------- @@ -94,8 +95,11 @@ def _h(self, who): return self.auth[who] if who else {} def stage(self, who, name, content, expect=200, **extra): - res = self.client.post("/api/csv/uploads", headers=self._h(who), - json={"fileName": f"{self.tag}_{name}", "content": content, **extra}) + res = self.client.post( + "/api/csv/uploads", + headers=self._h(who), + json={"fileName": f"{self.tag}_{name}", "content": content, **extra}, + ) self.assertEqual(res.status_code, expect, res.text) return res.json() if expect == 200 else res.json()["detail"] @@ -113,13 +117,19 @@ def state(self, who, upload) -> str: return self.client.get(f"/api/csv/uploads/{upload}/workflow", headers=self._h(who)).json()["state"] def decide(self, who, upload, row, decision="exclude", expect=200): - res = self.client.put(f"/api/csv/uploads/{upload}/rows/{row}/decision", headers=self._h(who), - json={"decision": decision, "reason": "test"}) + res = self.client.put( + f"/api/csv/uploads/{upload}/rows/{row}/decision", + headers=self._h(who), + json={"decision": decision, "reason": "test"}, + ) self.assertEqual(res.status_code, expect, res.text) def edit(self, who, upload, row, column, value, expect=200): - res = self.client.put(f"/api/csv/uploads/{upload}/rows/{row}/cells/{column}", headers=self._h(who), - json={"value": value, "reason": "test"}) + res = self.client.put( + f"/api/csv/uploads/{upload}/rows/{row}/cells/{column}", + headers=self._h(who), + json={"value": value, "reason": "test"}, + ) self.assertEqual(res.status_code, expect, res.text) def approved(self, content, name="a.csv", **extra) -> str: @@ -149,28 +159,33 @@ def test_stage_imports_nothing_and_the_whole_flow_reconciles(self): up = staged["uploadId"] self.assertEqual((staged["status"], staged["state"], staged["totalRows"]), ("staged", "staged", 6)) self.assertEqual(self.registry("team_up"), [], "staging must not import anything") - self.assertEqual(self.team_sql("SELECT count(*) FROM {s}.csv_files WHERE file_name LIKE %s", - (f"{self.tag}%",))[0][0], 0) + self.assertEqual( + self.team_sql("SELECT count(*) FROM {s}.csv_files WHERE file_name LIKE %s", (f"{self.tag}%",))[0][0], 0 + ) self.post("team_up", up, "submit", note="please review") self.assertEqual(self.state("team_up", up), "submitted") # Row 2 is invalid, so approval is refused until the reviewer deals with it. refused = self.post("team_rv", up, "approval", expect=422, decision="approve") self.assertEqual((refused["invalidRows"], refused["rowErrors"][0]["rowNumber"]), (1, 2)) - self.edit("team_rv", up, 2, "k", "2") # fix an invalid cell - self.decide("team_rv", up, 3) # exclude a row - self.edit("team_rv", up, 6, "v", "E") # change a valid one + self.edit("team_rv", up, 2, "k", "2") # fix an invalid cell + self.decide("team_rv", up, 3) # exclude a row + self.edit("team_rv", up, 6, "v", "E") # change a valid one approved = self.post("team_rv", up, "approval", decision="approve") self.assertEqual(approved["state"], "approved") self.assertEqual(self.registry("team_up"), [], "approving doesn't import either") result = self.imp("team_up", up) - self.assertEqual(result["reconciliation"], {"rowsIn": 6, "excluded": 1, "edited": 2, "duplicate": 1, "imported": 4}) + self.assertEqual( + result["reconciliation"], {"rowsIn": 6, "excluded": 1, "edited": 2, "duplicate": 1, "imported": 4} + ) self.assertEqual(self.state("team_up", up), "imported") self.assertEqual((result["dataset"], result["version"]), (staged["dataset"], 1)) # The data: edits applied, exclusion dropped, duplicate skipped; lineage points back to source rows. - rows = self.team_sql('SELECT k, v, _source_row_id, _import_id FROM {s}."' + result["tableName"] + '" ORDER BY _id') + rows = self.team_sql( + 'SELECT k, v, _source_row_id, _import_id FROM {s}."' + result["tableName"] + '" ORDER BY _id' + ) self.assertEqual([r[:3] for r in rows], [(1, "a", 1), (2, "b", 2), (4, "d", 4), (6, "E", 6)]) self.assertEqual({r[3] for r in rows}, {int(result["importId"])}) # The original is untouched, and the review page still shows both. @@ -178,25 +193,36 @@ def test_stage_imports_nothing_and_the_whole_flow_reconciles(self): self.assertEqual((page[5]["original"], page[5]["current"]), (["6", "e"], ["6", "E"])) # It is registered like any other file, with the uploader known. [entry] = self.registry("team_up") - self.assertEqual((entry["uploader"], entry["row_count"], entry["total_rows"], entry["duplicate_rows_skipped"]), - (f"{self.slugs['team']}_up", 4, 6, 1)) + self.assertEqual( + (entry["uploader"], entry["row_count"], entry["total_rows"], entry["duplicate_rows_skipped"]), + (f"{self.slugs['team']}_up", 4, 6, 1), + ) # Every step is in the audit log, in the same chain. - actions = self.team_sql("SELECT action, actor FROM {s}.audit_log WHERE file_name = %s " - "AND action IN ('submit','approve','import') ORDER BY id", (staged_name,)) - self.assertEqual(actions, [("submit", f"{self.slugs['team']}_up"), ("approve", f"{self.slugs['team']}_rv"), - ("import", f"{self.slugs['team']}_up")]) + actions = self.team_sql( + "SELECT action, actor FROM {s}.audit_log WHERE file_name = %s " + "AND action IN ('submit','approve','import') ORDER BY id", + (staged_name,), + ) + self.assertEqual( + actions, + [ + ("submit", f"{self.slugs['team']}_up"), + ("approve", f"{self.slugs['team']}_rv"), + ("import", f"{self.slugs['team']}_up"), + ], + ) self.assertTrue(self.client.get("/api/audit/verify", headers=self._h("team_ad")).json()["intact"]) def test_reject_then_resubmit(self): up = self.stage("team_up", "rr.csv", "k\n1\nnot a number\n3\n", types=["int8"])["uploadId"] - self.post("team_rv", up, "approval", expect=409, decision="approve") # nothing submitted yet + self.post("team_rv", up, "approval", expect=409, decision="approve") # nothing submitted yet self.post("team_up", up, "submit") - self.post("team_up", up, "submit", expect=409) # already submitted - self.post("team_rv", up, "approval", expect=422, decision="reject") # a reason is required + self.post("team_up", up, "submit", expect=409) # already submitted + self.post("team_rv", up, "approval", expect=422, decision="reject") # a reason is required rejected = self.post("team_rv", up, "approval", decision="reject", reason="row 2 is not a number") self.assertEqual(rejected["state"], "rejected") - self.imp("team_up", up, expect=409) # a rejected upload can't import - self.decide("team_rv", up, 2) # review reopens + self.imp("team_up", up, expect=409) # a rejected upload can't import + self.decide("team_rv", up, 2) # review reopens self.post("team_up", up, "submit", note="row 2 excluded") self.assertEqual(self.state("team_up", up), "submitted") self.post("team_rv", up, "approval", decision="approve") @@ -223,8 +249,11 @@ def test_import_needs_an_approval_and_a_key(self): self.assertEqual(self.registry("team_up"), []) def test_a_direct_upload_has_no_workflow(self): - res = self.client.post("/api/csv/upload", headers=self._h("team_up"), - json={"fileName": f"{self.tag}_legacy.csv", "content": self.one}).json() + res = self.client.post( + "/api/csv/upload", + headers=self._h("team_up"), + json={"fileName": f"{self.tag}_legacy.csv", "content": self.one}, + ).json() self.assertEqual(self.state("team_up", res["uploadId"]), "legacy") self.post("team_up", res["uploadId"], "submit", expect=409) # ...and review of it still works as before M6. @@ -234,12 +263,16 @@ def test_uploads_list_shows_the_workflow_state(self): up = self.stage("team_up", "list.csv", self.one)["uploadId"] listing = {u["id"]: u["state"] for u in self.client.get("/api/csv/uploads", headers=self._h("team_up")).json()} self.assertEqual(listing[up], "staged") - self.assertEqual(self.client.get(f"/api/csv/uploads/{up}", headers=self._h("team_up")).json()["state"], "staged") + self.assertEqual( + self.client.get(f"/api/csv/uploads/{up}", headers=self._h("team_up")).json()["state"], "staged" + ) def test_bad_files_are_recorded_and_refused(self): bad = self.stage("team_up", "bad.csv", "only,a,header\n", expect=422) self.assertEqual((bad["status"], bad["reason"]), ("invalid_structure", "header_only")) - recorded = {u["id"]: u["status"] for u in self.client.get("/api/csv/uploads", headers=self._h("team_up")).json()} + recorded = { + u["id"]: u["status"] for u in self.client.get("/api/csv/uploads", headers=self._h("team_up")).json() + } self.assertEqual(recorded[bad["uploadId"]], "rejected", "every attempt gets an uploads row (BR-23)") self.stage("team_up", "types.csv", self.one, expect=422, types=["int8", "text"]) @@ -257,7 +290,7 @@ def test_a_member_cannot_approve_what_they_uploaded_or_submitted(self): self.post("team_ad", up, "submit") refused = self.post("team_ad", up, "approval", expect=403, decision="approve") self.assertIn("another member must approve", refused["message"]) - self.post("team_rv", up, "approval", decision="approve") # someone else can + self.post("team_rv", up, "approval", decision="approve") # someone else can self.assertEqual(self.state("team_ad", up), "approved") def test_the_submitter_cannot_approve_even_if_someone_else_uploaded(self): @@ -303,9 +336,13 @@ def _leftovers(self, table_like: str) -> dict: "files": self.registry("team_up"), "imports": self.team_sql("SELECT count(*) FROM {s}.imports")[0][0], "imported_audit": self.team_sql("SELECT count(*) FROM {s}.audit_log WHERE action = 'import'")[0][0], - "tables": [r[0] for r in self.team_sql( - "SELECT table_name FROM information_schema.tables WHERE table_schema = %s AND table_name LIKE %s", - (schema_for(self.slugs["team"]), table_like))], + "tables": [ + r[0] + for r in self.team_sql( + "SELECT table_name FROM information_schema.tables WHERE table_schema = %s AND table_name LIKE %s", + (schema_for(self.slugs["team"]), table_like), + ) + ], } def test_failure_at_every_step_changes_nothing_and_a_retry_then_succeeds(self): @@ -321,15 +358,17 @@ def boom(at, step=step): with patch.object(staged_import, "_checkpoint", boom): with self.assertRaises(RuntimeError): - self.client.post(f"/api/csv/uploads/{up}/import", - headers={**self._h("team_up"), "Idempotency-Key": "retry-me"}) + self.client.post( + f"/api/csv/uploads/{up}/import", + headers={**self._h("team_up"), "Idempotency-Key": "retry-me"}, + ) left = self._leftovers(like) self.assertEqual(([f for f in left["files"] if step in f["file_name"]], left["tables"]), ([], [])) self.assertEqual(self.state("team_up", up), "approved", "still approved and importable") imports_before = left["imports"] audit_before = left["imported_audit"] - result = self.imp("team_up", up, key="retry-me") # the retry, same key + result = self.imp("team_up", up, key="retry-me") # the retry, same key self.assertEqual((result["replayed"], result["reconciliation"]["imported"]), (False, 3)) after = self._leftovers(like) self.assertEqual((after["imports"], after["imported_audit"]), (imports_before + 1, audit_before + 1)) @@ -339,8 +378,9 @@ def test_a_retry_after_success_returns_the_original_and_adds_nothing(self): up = self.approved("k\n1\n2\n") first = self.imp("team_up", up, key="same") again = self.imp("team_up", up, key="same") - self.assertEqual((again["replayed"], again["importId"], again["tableName"]), - (True, first["importId"], first["tableName"])) + self.assertEqual( + (again["replayed"], again["importId"], again["tableName"]), (True, first["importId"], first["tableName"]) + ) self.assertEqual(self.team_sql('SELECT count(*) FROM {s}."' + first["tableName"] + '"')[0][0], 2) other = self.imp("team_up", up, key="different", expect=409) self.assertEqual(other["importId"], first["importId"]) @@ -350,8 +390,9 @@ def test_concurrent_imports_of_one_upload_import_it_once(self): up = self.approved("k\n1\n2\n3\n") def run(key): - return self.client.post(f"/api/csv/uploads/{up}/import", - headers={**self._h("team_up"), "Idempotency-Key": key}) + return self.client.post( + f"/api/csv/uploads/{up}/import", headers={**self._h("team_up"), "Idempotency-Key": key} + ) with ThreadPoolExecutor(max_workers=2) as pool: different = sorted(r.status_code for r in pool.map(run, ["a", "b"])) @@ -361,15 +402,21 @@ def run(key): up2 = self.approved("k\n7\n8\n", name="same_key.csv") with ThreadPoolExecutor(max_workers=2) as pool: - results = list(pool.map(lambda _: self.client.post( - f"/api/csv/uploads/{up2}/import", headers={**self._h("team_up"), "Idempotency-Key": "z"}), range(2))) + results = list( + pool.map( + lambda _: self.client.post( + f"/api/csv/uploads/{up2}/import", headers={**self._h("team_up"), "Idempotency-Key": "z"} + ), + range(2), + ) + ) self.assertEqual([r.status_code for r in results], [200, 200]) self.assertEqual(sorted(r.json()["replayed"] for r in results), [False, True]) self.assertEqual(self.team_sql("SELECT count(*) FROM {s}.imports WHERE upload_id = %s", (int(up2),))[0][0], 1) def test_the_same_bytes_staged_twice_import_once(self): first = self.stage("team_up", "twice.csv", "k\nsame\n")["uploadId"] - second = self.stage("team_up", "twice_copy.csv", "k\nsame\n")["uploadId"] # not in the registry yet + second = self.stage("team_up", "twice_copy.csv", "k\nsame\n")["uploadId"] # not in the registry yet for up in (first, second): self.post("team_up", up, "submit") self.post("team_rv", up, "approval", decision="approve") @@ -406,8 +453,9 @@ def test_the_registry_records_whether_the_types_were_confirmed(self): for up in (confirmed, guessed, unsent): self.imp("team_up", up, key=f"k{up}") found = {f["file_name"].split("_", 1)[1]: f["types_provenance"] for f in self.registry("team_up")} - self.assertEqual(found, {"c.csv": "user_confirmed", "g.csv": "inferred_unconfirmed", - "u.csv": "inferred_unconfirmed"}) + self.assertEqual( + found, {"c.csv": "user_confirmed", "g.csv": "inferred_unconfirmed", "u.csv": "inferred_unconfirmed"} + ) self.stage("team_up", "bad.csv", f"n\n{self.tag}4\n", expect=422, typesConfirmed=True) # no types sent def test_a_second_file_with_the_same_name_is_version_two_and_flags_are_known_before_approval(self): @@ -419,7 +467,7 @@ def test_a_second_file_with_the_same_name_is_version_two_and_flags_are_known_bef self.assertEqual(page[0]["duplicateOfEarlierVersion"]["version"], 1) up = staged["uploadId"] self.post("team_up", up, "submit") - self.decide("team_rv", up, 1) # the reviewer drops the repeated row + self.decide("team_rv", up, 1) # the reviewer drops the repeated row self.post("team_rv", up, "approval", decision="approve") result = self.imp("team_up", up) self.assertEqual((result["version"], result["reconciliation"]["imported"]), (2, 1)) @@ -437,9 +485,14 @@ def test_staged_uploads_keep_every_attempt_even_when_never_imported(self): @pytest.mark.integration class BrowserAccess(_Base): def test_a_browser_may_send_the_idempotency_key(self): - res = self.client.options("/api/csv/uploads/1/import", headers={ - "Origin": "http://localhost:5173", "Access-Control-Request-Method": "POST", - "Access-Control-Request-Headers": "idempotency-key,authorization,content-type"}) + res = self.client.options( + "/api/csv/uploads/1/import", + headers={ + "Origin": "http://localhost:5173", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "idempotency-key,authorization,content-type", + }, + ) self.assertEqual(res.status_code, 200, res.text) self.assertIn("idempotency-key", res.headers["access-control-allow-headers"].lower()) @@ -453,16 +506,23 @@ def test_no_update_or_delete_on_submissions_approvals_imports(self): self.imp("team_up", up) schema = sql.Identifier(schema_for(self.slugs["team"])) with Conn() as conn, conn.cursor() as cur: - for table, update in (("submissions", "note = 'x'"), ("approvals", "reason = 'x'"), - ("imports", "rows_in = 0")): - for statement in (f"UPDATE {{}}.{table} SET {update}", f"DELETE FROM {{}}.{table}", - f"TRUNCATE {{}}.{table}"): + for table, update in ( + ("submissions", "note = 'x'"), + ("approvals", "reason = 'x'"), + ("imports", "rows_in = 0"), + ): + for statement in ( + f"UPDATE {{}}.{table} SET {update}", + f"DELETE FROM {{}}.{table}", + f"TRUNCATE {{}}.{table}", + ): with self.subTest(statement=statement): # The trigger refuses it; for a table other tables reference, PostgreSQL's own # foreign-key check refuses TRUNCATE first. Either way nothing changes. try: - with self.assertRaises((psycopg2.errors.InsufficientPrivilege, - psycopg2.errors.FeatureNotSupported)): + with self.assertRaises( + (psycopg2.errors.InsufficientPrivilege, psycopg2.errors.FeatureNotSupported) + ): cur.execute(sql.SQL(statement).format(schema)) finally: conn.rollback() diff --git a/tests/system/test_te_cannot_drop_dataset.py b/tests/system/test_te_cannot_drop_dataset.py index d5c64f1..3c79b34 100644 --- a/tests/system/test_te_cannot_drop_dataset.py +++ b/tests/system/test_te_cannot_drop_dataset.py @@ -9,6 +9,7 @@ and the T&E upload changes nothing (no T&E rows land, no T&E registry row). Needs a live PostgreSQL with the dev schema deployed, as in CI. """ + from __future__ import annotations import unittest @@ -47,14 +48,17 @@ def _table_exists(self, table: str) -> bool: def _te_rows(self, org: str) -> int: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT count(*) FROM {}.organisations WHERE name = %s").format( - sql.Identifier(self.te_schema)), (org,)) + cur.execute( + sql.SQL("SELECT count(*) FROM {}.organisations WHERE name = %s").format(sql.Identifier(self.te_schema)), + (org,), + ) return cur.fetchone()[0] def _drop_org(self, org: str) -> None: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("DELETE FROM {}.organisations WHERE name = %s").format( - sql.Identifier(self.te_schema)), (org,)) + cur.execute( + sql.SQL("DELETE FROM {}.organisations WHERE name = %s").format(sql.Identifier(self.te_schema)), (org,) + ) conn.commit() def check_te_upload_of_a_datasets_bytes_leaves_the_dataset_alone(self): @@ -72,8 +76,9 @@ def check_te_upload_of_a_datasets_bytes_leaves_the_dataset_alone(self): self.assertTrue(self._table_exists(table), f"the dataset's table was dropped: {res.status_code} {res.text}") registered = [(f["mode"], f["table_name"]) for f in self._files() if tag in f["file_name"]] - self.assertEqual(registered, [("dynamic", table)], - "the dataset's registry row must survive and no T&E row may replace it") + self.assertEqual( + registered, [("dynamic", table)], "the dataset's registry row must survive and no T&E row may replace it" + ) self.assertEqual(self._te_rows(org), 0, "a refused T&E upload must not leave rows behind") self.assertIn(res.status_code, (200, 403, 409), res.text) if res.status_code == 200: @@ -117,6 +122,7 @@ def setUpClass(cls): cls.role_headers = cls.headers cls.headers = cls.role_headers["tenant_admin"] from api.tenancy import schema_for + cls.schema = cls.te_schema = schema_for(cls.slug) @classmethod diff --git a/tests/system/test_te_import_all_or_nothing.py b/tests/system/test_te_import_all_or_nothing.py index 83d1bda..3ca2d7e 100644 --- a/tests/system/test_te_import_all_or_nothing.py +++ b/tests/system/test_te_import_all_or_nothing.py @@ -12,6 +12,7 @@ Needs a live PostgreSQL with the dev schema deployed, as in CI. """ + from __future__ import annotations import unittest @@ -53,16 +54,26 @@ def _csv(self, *rows: str) -> str: return "\n".join([HEADER, *rows]) + "\n" def _upload(self, content: str, file_name: str | None = None) -> dict: - res = self.client.post("/api/csv/upload", json={ - "fileName": file_name or self.file_name, "content": content, - "mode": "te", "targetTable": "organisations"}) + res = self.client.post( + "/api/csv/upload", + json={ + "fileName": file_name or self.file_name, + "content": content, + "mode": "te", + "targetTable": "organisations", + }, + ) self.assertEqual(res.status_code, 200, res.text) return res.json() def _org_names(self) -> list[str]: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT name FROM {}.organisations WHERE name LIKE %s ORDER BY name").format( - sql.Identifier(settings.TE_SCHEMA)), (f"{self.tag}\\_%",)) + cur.execute( + sql.SQL("SELECT name FROM {}.organisations WHERE name LIKE %s ORDER BY name").format( + sql.Identifier(settings.TE_SCHEMA) + ), + (f"{self.tag}\\_%",), + ) return [r[0] for r in cur.fetchall()] def _registered(self) -> list[dict]: @@ -72,10 +83,16 @@ def _registered(self) -> list[dict]: def _cleanup(self) -> None: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("DELETE FROM {}.organisations WHERE name LIKE %s").format( - sql.Identifier(settings.TE_SCHEMA)), (f"{self.tag}\\_%",)) - cur.execute(sql.SQL("DELETE FROM {}.csv_files WHERE file_name = %s AND mode = 'te'").format( - sql.Identifier(settings.UPLOADS_SCHEMA)), (self.file_name,)) + cur.execute( + sql.SQL("DELETE FROM {}.organisations WHERE name LIKE %s").format(sql.Identifier(settings.TE_SCHEMA)), + (f"{self.tag}\\_%",), + ) + cur.execute( + sql.SQL("DELETE FROM {}.csv_files WHERE file_name = %s AND mode = 'te'").format( + sql.Identifier(settings.UPLOADS_SCHEMA) + ), + (self.file_name,), + ) conn.commit() def _assert_nothing_imported(self, body: dict) -> None: @@ -101,10 +118,13 @@ def test_one_row_failing_in_the_database_imports_nothing(self): self.assertEqual([e["rowNumber"] for e in body["rowErrors"]], [2], body) def test_both_kinds_of_failure_are_all_reported_and_nothing_is_imported(self): - body = self._upload(self._csv( - self._org("a", is_active="NOT_A_BOOL"), # row 1: type check - self._org("b", org_type="INVALID_ENUM"), # row 2: database - self._org("c"))) # row 3: fine, but it must not land either + body = self._upload( + self._csv( + self._org("a", is_active="NOT_A_BOOL"), # row 1: type check + self._org("b", org_type="INVALID_ENUM"), # row 2: database + self._org("c"), + ) + ) # row 3: fine, but it must not land either self._assert_nothing_imported(body) self.assertEqual((body["totalRows"], body["failedRows"]), (3, 2), body) self.assertEqual(sorted(e["rowNumber"] for e in body["rowErrors"]), [1, 2], body) @@ -121,8 +141,11 @@ def test_a_failed_reupload_keeps_the_earlier_load(self): again = self._upload(self._csv(self._org("second"), self._org("bad", is_active="NOT_A_BOOL"))) self.assertEqual(again["status"], "error", again) self.assertEqual(self._org_names(), [f"{self.tag}_first"], "the second file's good row must not land") - self.assertEqual([f["id"] for f in self._registered()], [registered["id"]], - "the earlier load's registry row must be untouched") + self.assertEqual( + [f["id"] for f in self._registered()], + [registered["id"]], + "the earlier load's registry row must be untouched", + ) def test_a_clean_file_still_imports_every_row(self): body = self._upload(self._csv(self._org("a"), self._org("b"), self._org("c"))) diff --git a/tests/system/test_te_loader_integration.py b/tests/system/test_te_loader_integration.py index 02bb499..8c204f9 100644 --- a/tests/system/test_te_loader_integration.py +++ b/tests/system/test_te_loader_integration.py @@ -18,6 +18,7 @@ Requires a provisioned dev environment: bash scripts/provision_full_test_env.sh """ + from __future__ import annotations import os @@ -72,16 +73,18 @@ def tearDownClass(cls): # so the suite does not pollute the dev seed data if cls._inserted: try: - from api.db import Conn from psycopg2 import sql + from api.config import settings + from api.db import Conn + with Conn() as conn: with conn.cursor() as cur: for name in cls._inserted: cur.execute( - sql.SQL( - "DELETE FROM {}.organisations WHERE name = %s" - ).format(sql.Identifier(settings.TE_SCHEMA)), + sql.SQL("DELETE FROM {}.organisations WHERE name = %s").format( + sql.Identifier(settings.TE_SCHEMA) + ), (name,), ) conn.commit() @@ -91,19 +94,16 @@ def tearDownClass(cls): def _make_csv(self, n_rows: int = 1) -> tuple[str, list[str]]: """Return (csv_content, list_of_inserted_names).""" - names = [f"TE_TEST_{os.getpid()}_{i}_{self._testMethodName[:20]}" - for i in range(n_rows)] + names = [f"TE_TEST_{os.getpid()}_{i}_{self._testMethodName[:20]}" for i in range(n_rows)] rows = "\n".join(f"{n},government,AU" for n in names) content = f"{ORG_HEADER}\n{rows}\n" return content, names - def _upload_te(self, content: str, target: str = TARGET, - file_name: str | None = None) -> dict: + def _upload_te(self, content: str, target: str = TARGET, file_name: str | None = None) -> dict: name = file_name or f"te_{os.getpid()}_{self._testMethodName[:30]}.csv" r = self.client.post( "/api/csv/upload", - json={"fileName": name, "content": content, - "mode": "te", "targetTable": target}, + json={"fileName": name, "content": content, "mode": "te", "targetTable": target}, ) self.assertEqual(r.status_code, 200, r.text[:300]) return r.json() @@ -132,10 +132,10 @@ def test_table_name_in_response_is_schema_qualified(self): self.__class__._inserted.extend(names) body = self._upload_te(content) self.assertEqual(body["status"], "ok", body) - self.assertIn(".", body.get("tableName", ""), - "tableName must be schema-qualified") - self.assertTrue(body["tableName"].endswith(f".{TARGET}"), - f"tableName should end with .{TARGET}, got {body['tableName']}") + self.assertIn(".", body.get("tableName", ""), "tableName must be schema-qualified") + self.assertTrue( + body["tableName"].endswith(f".{TARGET}"), f"tableName should end with .{TARGET}, got {body['tableName']}" + ) def test_rows_are_queryable_after_upload(self): """Inserted rows must appear in the T&E table row count.""" @@ -146,10 +146,8 @@ def test_rows_are_queryable_after_upload(self): te_r = self.client.get("/api/te/tables") self.assertEqual(te_r.status_code, 200, te_r.text[:200]) tables = {row["table"]: row for row in te_r.json()} - self.assertIn(TARGET, tables, - f"'{TARGET}' not in /api/te/tables response") - self.assertGreater(tables[TARGET]["rowCount"], 0, - f"T&E table '{TARGET}' has 0 rows after upload") + self.assertIn(TARGET, tables, f"'{TARGET}' not in /api/te/tables response") + self.assertGreater(tables[TARGET]["rowCount"], 0, f"T&E table '{TARGET}' has 0 rows after upload") def test_core_te_tables_undisturbed_after_upload(self): """A T&E upload must not drop or alter the other 11 core tables.""" @@ -162,8 +160,7 @@ def test_core_te_tables_undisturbed_after_upload(self): tables = {t["table"]: t for t in te_r.json()} for tbl in ["requirements", "test_cases", "defect_reports"]: self.assertIn(tbl, tables, f"Core table '{tbl}' missing after T&E upload") - self.assertTrue(tables[tbl]["exists"], - f"Core table '{tbl}' no longer exists after T&E upload") + self.assertTrue(tables[tbl]["exists"], f"Core table '{tbl}' no longer exists after T&E upload") # ── cleanup on re-upload ────────────────────────────────────────────── @@ -178,18 +175,15 @@ def test_reupload_cleans_prior_registry_entry(self): content_v2 = content.replace(names[0], names[0] + "_v2") self.__class__._inserted.append(names[0] + "_v2") - first = self._upload_te(content, file_name=fname) + first = self._upload_te(content, file_name=fname) second = self._upload_te(content_v2, file_name=fname) - self.assertEqual(first["status"], "ok", first) + self.assertEqual(first["status"], "ok", first) self.assertEqual(second["status"], "ok", second) files = self.client.get("/api/csv/files").json() matches = [f for f in files if f["file_name"] == fname] - self.assertLessEqual( - len(matches), 1, - f"Re-upload left {len(matches)} registry entries for the same file" - ) + self.assertLessEqual(len(matches), 1, f"Re-upload left {len(matches)} registry entries for the same file") # ── guard rails ─────────────────────────────────────────────────────── @@ -202,9 +196,10 @@ def test_invalid_target_table_is_rejected(self): def test_empty_file_is_rejected(self): """Empty CSV is rejected — 422 from Pydantic min_length or status=error.""" - r = self.client.post("/api/csv/upload", json={ - "fileName": f"te_{os.getpid()}_empty.csv", - "content": "", "mode": "te", "targetTable": TARGET}) + r = self.client.post( + "/api/csv/upload", + json={"fileName": f"te_{os.getpid()}_empty.csv", "content": "", "mode": "te", "targetTable": TARGET}, + ) if r.status_code == 422: pass # Pydantic min_length=1 guard — valid rejection else: @@ -226,9 +221,11 @@ def test_missing_target_table_param_is_rejected(self): """mode=te with no targetTable must return 422 from the API layer.""" r = self.client.post( "/api/csv/upload", - json={"fileName": f"te_{os.getpid()}.csv", - "content": f"{ORG_HEADER}\n{ORG_ROW_TPL.format(pid=os.getpid(), n=0)}\n", - "mode": "te"}, + json={ + "fileName": f"te_{os.getpid()}.csv", + "content": f"{ORG_HEADER}\n{ORG_ROW_TPL.format(pid=os.getpid(), n=0)}\n", + "mode": "te", + }, ) self.assertEqual(r.status_code, 422, r.text[:200]) @@ -264,15 +261,17 @@ def setUpClass(cls): def tearDownClass(cls): if cls._inserted: try: - from api.db import Conn from psycopg2 import sql + + from api.db import Conn + with Conn() as conn: with conn.cursor() as cur: for name in cls._inserted: cur.execute( - sql.SQL( - "DELETE FROM {}.organisations WHERE name = %s" - ).format(sql.Identifier(settings.TE_SCHEMA)), + sql.SQL("DELETE FROM {}.organisations WHERE name = %s").format( + sql.Identifier(settings.TE_SCHEMA) + ), (name,), ) conn.commit() @@ -309,7 +308,8 @@ def test_dynamic_upload_with_a_te_files_name_leaves_the_te_entry_alone(self): }, ).json() self.assertEqual( - dynamic_body["status"], "ok", + dynamic_body["status"], + "ok", f"dynamic-mode overwrite of a TE-origin file must succeed: {dynamic_body}", ) self.assertTrue(dynamic_body["tableName"].startswith("csv_"), dynamic_body) @@ -317,7 +317,8 @@ def test_dynamic_upload_with_a_te_files_name_leaves_the_te_entry_alone(self): files = self.client.get("/api/csv/files").json() matches = [f for f in files if f["file_name"] == fname] self.assertEqual( - sorted(m["mode"] for m in matches), ["dynamic", "te"], + sorted(m["mode"] for m in matches), + ["dynamic", "te"], f"expected the T&E entry and the new dynamic dataset for {fname!r}, found {matches}", ) diff --git a/tests/system/test_te_reupload_registry.py b/tests/system/test_te_reupload_registry.py index c1e2e1a..87595e7 100644 --- a/tests/system/test_te_reupload_registry.py +++ b/tests/system/test_te_reupload_registry.py @@ -7,6 +7,7 @@ Needs a live PostgreSQL with the dev schema deployed (see tests/test_api_integration.py). """ + from __future__ import annotations import os @@ -55,9 +56,15 @@ def tearDown(self): # -- helpers ------------------------------------------------------------- def _upload_te(self, content: str): - return self.client.post("/api/csv/upload", json={ - "fileName": self.file_name, "content": content, "mode": "te", "targetTable": "organisations", - }).json() + return self.client.post( + "/api/csv/upload", + json={ + "fileName": self.file_name, + "content": content, + "mode": "te", + "targetTable": "organisations", + }, + ).json() def _registry(self) -> list[dict]: return [f for f in self.client.get("/api/csv/files").json() if f["file_name"] == self.file_name] @@ -65,8 +72,9 @@ def _registry(self) -> list[dict]: def _loaded_orgs(self) -> int: with Conn() as conn: with conn.cursor() as cur: - cur.execute(f"SELECT count(*) FROM {settings.TE_SCHEMA}.organisations WHERE name LIKE %s", - (self.tag + "%",)) + cur.execute( + f"SELECT count(*) FROM {settings.TE_SCHEMA}.organisations WHERE name LIKE %s", (self.tag + "%",) + ) return cur.fetchone()[0] # -- the bug ------------------------------------------------------------- @@ -86,9 +94,11 @@ def test_all_failed_reupload_keeps_the_earlier_registry_record(self): self.assertEqual(second["insertedRows"], 0, second) after = self._registry() - self.assertEqual([(r["id"], r["row_count"], r["failed_rows"]) for r in after], - [(before[0]["id"], 2, 0)], - "the earlier load's registry record must survive an all-failed re-upload") + self.assertEqual( + [(r["id"], r["row_count"], r["failed_rows"]) for r in after], + [(before[0]["id"], 2, 0)], + "the earlier load's registry record must survive an all-failed re-upload", + ) self.assertEqual(self._loaded_orgs(), 2, "registry and table must still agree") # -- guard against over-correcting --------------------------------------- @@ -111,9 +121,14 @@ def test_reupload_that_inserts_rows_still_replaces_the_registry_record(self): def test_all_failed_te_upload_keeps_a_prior_dynamic_table_of_the_same_name(self): """An all-failed T&E upload does not drop a dynamic table registered under the same filename (#170).""" - dyn = self.client.post("/api/csv/upload", json={ - "fileName": self.file_name, "content": "col_a,col_b\n1,2\n", "mode": "dynamic", - }).json() + dyn = self.client.post( + "/api/csv/upload", + json={ + "fileName": self.file_name, + "content": "col_a,col_b\n1,2\n", + "mode": "dynamic", + }, + ).json() self.assertEqual(dyn["status"], "ok", dyn) table = dyn["tableName"] @@ -122,5 +137,8 @@ def test_all_failed_te_upload_keeps_a_prior_dynamic_table_of_the_same_name(self) reg = self._registry() self.assertEqual([(r["mode"], r["table_name"]) for r in reg], [("dynamic", table)]) - self.assertEqual(self.client.get(f"/api/csv/tables/{table}/rows").status_code, 200, - "the prior dynamic table must not have been dropped") + self.assertEqual( + self.client.get(f"/api/csv/tables/{table}/rows").status_code, + 200, + "the prior dynamic table must not have been dropped", + ) diff --git a/tests/system/test_tenant_isolation.py b/tests/system/test_tenant_isolation.py index 7fc69e6..10db5b0 100644 --- a/tests/system/test_tenant_isolation.py +++ b/tests/system/test_tenant_isolation.py @@ -23,15 +23,17 @@ from fastapi.testclient import TestClient from psycopg2 import sql -from api.config import TE_TABLES, settings from api import db +from api.config import TE_TABLES, settings from api.db import Conn from api.main import app from api.services import accounts from api.tenancy import drop_tenant_role, migrate_tenant, role_for, schema_for, tenant -_HELP = ("Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" - "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" + "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1." +) _PW = "correct horse battery staple" _ALEMBIC_INI = str(Path(__file__).resolve().parents[2] / "alembic.ini") @@ -62,8 +64,7 @@ def setUpClass(cls): migrate_tenant(slug) cls.headers = {} for key, slug in cls.slugs.items(): - res = cls.client.post("/api/auth/login", json={ - "tenant": slug, "username": f"{slug}_user", "password": _PW}) + res = cls.client.post("/api/auth/login", json={"tenant": slug, "username": f"{slug}_user", "password": _PW}) assert res.status_code == 200, res.text cls.headers[key] = {"Authorization": f"Bearer {res.json()['token']}"} @@ -74,17 +75,26 @@ def tearDownClass(cls): with conn.cursor() as cur: for slug in cls.slugs.values(): cur.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(schema_for(slug)))) - cur.execute(sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (slug,)) - cur.execute(sql.SQL("DELETE FROM {}.users WHERE username = %s").format( - sql.Identifier(settings.CONTROL_SCHEMA)), (f"{slug}_user",)) + cur.execute( + sql.SQL("DELETE FROM {}.tenants WHERE slug = %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (slug,), + ) + cur.execute( + sql.SQL("DELETE FROM {}.users WHERE username = %s").format( + sql.Identifier(settings.CONTROL_SCHEMA) + ), + (f"{slug}_user",), + ) drop_tenant_role(cur, slug) conn.commit() cls.ctx.__exit__(None, None, None) def _upload(self, who: str, name: str, content: str) -> dict: - res = self.client.post("/api/csv/upload", headers=self.headers[who], - json={"fileName": name, "content": content}) + res = self.client.post( + "/api/csv/upload", headers=self.headers[who], json={"fileName": name, "content": content} + ) self.assertEqual(res.status_code, 200, res.text) return res.json() @@ -102,8 +112,7 @@ def test_upload_lands_in_the_tenants_own_schema(self): res = self._upload("a", name, content) self.assertEqual(res["status"], "ok", res) with Conn() as conn, conn.cursor() as cur: - cur.execute("SELECT table_schema FROM information_schema.tables WHERE table_name = %s", - (res["tableName"],)) + cur.execute("SELECT table_schema FROM information_schema.tables WHERE table_name = %s", (res["tableName"],)) self.assertEqual([r[0] for r in cur.fetchall()], [schema_for(self.slugs["a"])]) def test_other_tenant_cannot_list_read_or_delete(self): @@ -131,8 +140,9 @@ def test_duplicate_detection_is_per_tenant(self): name, content = self._fresh() self.assertEqual(self._upload("a", name, content)["status"], "ok") self.assertEqual(self._upload("a", "again_" + name, content)["status"], "duplicate_file") - self.assertEqual(self._upload("b", name, content)["status"], "ok", - "the same file in another tenant is not a duplicate") + self.assertEqual( + self._upload("b", name, content)["status"], "ok", "the same file in another tenant is not a duplicate" + ) def test_audit_log_is_per_tenant(self): name, content = self._fresh() @@ -148,9 +158,16 @@ def names(who): self.assertNotIn(name, names(None)) def _te_upload(self, who: str, org: str) -> dict: - res = self.client.post("/api/csv/upload", headers=self.headers[who], json={ - "fileName": f"{org}.csv", "content": f"name,org_type,country\n{org},government,AU\n", - "mode": "te", "targetTable": "organisations"}) + res = self.client.post( + "/api/csv/upload", + headers=self.headers[who], + json={ + "fileName": f"{org}.csv", + "content": f"name,org_type,country\n{org},government,AU\n", + "mode": "te", + "targetTable": "organisations", + }, + ) self.assertEqual(res.status_code, 200, res.text) return res.json() @@ -181,24 +198,35 @@ def count(who): def test_tenant_te_tables_keep_their_foreign_keys_and_triggers(self): schema = schema_for(self.slugs["b"]) with Conn() as conn, conn.cursor() as cur: - cur.execute("SELECT count(*) FROM information_schema.table_constraints " - "WHERE table_schema = %s AND constraint_type = 'FOREIGN KEY' AND table_name = ANY(%s)", - (schema, TE_TABLES)) # the T&E tables only; 0007's upload tables have their own + cur.execute( + "SELECT count(*) FROM information_schema.table_constraints " + "WHERE table_schema = %s AND constraint_type = 'FOREIGN KEY' AND table_name = ANY(%s)", + (schema, TE_TABLES), + ) # the T&E tables only; 0007's upload tables have their own tenant_fks = cur.fetchone()[0] - cur.execute("SELECT count(*) FROM information_schema.table_constraints " - "WHERE table_schema = %s AND constraint_type = 'FOREIGN KEY'", (settings.TE_SCHEMA,)) + cur.execute( + "SELECT count(*) FROM information_schema.table_constraints " + "WHERE table_schema = %s AND constraint_type = 'FOREIGN KEY'", + (settings.TE_SCHEMA,), + ) self.assertEqual(tenant_fks, cur.fetchone()[0]) - cur.execute("SELECT count(*) FROM information_schema.referential_constraints rc " - "JOIN information_schema.table_constraints tc USING (constraint_schema, constraint_name) " - "WHERE rc.constraint_schema = %s AND rc.unique_constraint_schema <> %s", (schema, schema)) + cur.execute( + "SELECT count(*) FROM information_schema.referential_constraints rc " + "JOIN information_schema.table_constraints tc USING (constraint_schema, constraint_name) " + "WHERE rc.constraint_schema = %s AND rc.unique_constraint_schema <> %s", + (schema, schema), + ) self.assertEqual(cur.fetchone()[0], 0, "foreign keys must point inside the tenant schema") cur.execute("SELECT count(*) FROM information_schema.triggers WHERE trigger_schema = %s", (schema,)) self.assertGreater(cur.fetchone()[0], 0) with self.assertRaises(psycopg2.errors.ForeignKeyViolation): - cur.execute(sql.SQL( - "INSERT INTO {}.personnel (org_id, full_name, email, te_role, password_hash) " - "VALUES (gen_random_uuid(), 'x', %s, 'observer', 'x')").format(sql.Identifier(schema)), - (f"{uuid.uuid4().hex}@example.com",)) + cur.execute( + sql.SQL( + "INSERT INTO {}.personnel (org_id, full_name, email, te_role, password_hash) " + "VALUES (gen_random_uuid(), 'x', %s, 'observer', 'x')" + ).format(sql.Identifier(schema)), + (f"{uuid.uuid4().hex}@example.com",), + ) conn.rollback() def test_invalid_session_is_401_not_a_fallback_to_default(self): @@ -207,11 +235,16 @@ def test_invalid_session_is_401_not_a_fallback_to_default(self): def test_tenant_schema_is_at_head_with_its_own_registry(self): with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("SELECT version_num FROM {}.alembic_version").format( - sql.Identifier(schema_for(self.slugs["b"])))) + cur.execute( + sql.SQL("SELECT version_num FROM {}.alembic_version").format( + sql.Identifier(schema_for(self.slugs["b"])) + ) + ) self.assertEqual(cur.fetchone()[0], ScriptDirectory.from_config(Config(_ALEMBIC_INI)).get_current_head()) - cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = %s", - (schema_for(self.slugs["b"]),)) + cur.execute( + "SELECT table_name FROM information_schema.tables WHERE table_schema = %s", + (schema_for(self.slugs["b"]),), + ) self.assertTrue({"csv_files", "audit_log"} <= {r[0] for r in cur.fetchall()}) def test_concurrent_requests_never_see_another_tenants_schema(self): @@ -257,10 +290,11 @@ def test_a_query_as_tenant_a_on_tenant_bs_schema_fails_at_the_database(self): for schema, table in targets: with self.subTest(schema=schema, table=table): with self.assertRaises(psycopg2.errors.InsufficientPrivilege): - cur.execute(sql.SQL("SELECT * FROM {}.{} LIMIT 1").format( - sql.Identifier(schema), sql.Identifier(table))) + cur.execute( + sql.SQL("SELECT * FROM {}.{} LIMIT 1").format(sql.Identifier(schema), sql.Identifier(table)) + ) conn.rollback() - cur.execute("SELECT current_user") # a rollback must not undo the switch + cur.execute("SELECT current_user") # a rollback must not undo the switch self.assertEqual(cur.fetchone()[0], role_for(a)) cur.execute(sql.SQL("SELECT count(*) FROM {}.csv_files").format(sql.Identifier(schema_for(a)))) self.assertIsNotNone(cur.fetchone(), "the tenant's own schema stays readable") @@ -268,10 +302,13 @@ def test_a_query_as_tenant_a_on_tenant_bs_schema_fails_at_the_database(self): def test_tenant_role_has_rights_only_on_its_own_schema(self): a, b = self.slugs["a"], self.slugs["b"] with Conn() as conn, conn.cursor() as cur: - for role, schema, expected in ((role_for(a), schema_for(a), True), (role_for(a), schema_for(b), False), - (role_for(b), schema_for(a), False), - (role_for(a), settings.CONTROL_SCHEMA, False), - (role_for(a), settings.UPLOADS_SCHEMA, False)): + for role, schema, expected in ( + (role_for(a), schema_for(a), True), + (role_for(a), schema_for(b), False), + (role_for(b), schema_for(a), False), + (role_for(a), settings.CONTROL_SCHEMA, False), + (role_for(a), settings.UPLOADS_SCHEMA, False), + ): with self.subTest(role=role, schema=schema): cur.execute("SELECT has_schema_privilege(%s, %s, 'USAGE')", (role, schema)) self.assertIs(cur.fetchone()[0], expected) @@ -282,8 +319,10 @@ def test_a_signed_in_request_runs_as_the_tenants_role(self): """The csv_* table an upload creates is owned by the tenant's role: the request ran as it.""" res = self._upload("a", *self._fresh()) with Conn() as conn, conn.cursor() as cur: - cur.execute("SELECT pg_get_userbyid(relowner) FROM pg_class WHERE oid = to_regclass(%s)", - (f'"{schema_for(self.slugs["a"])}"."{res["tableName"]}"',)) + cur.execute( + "SELECT pg_get_userbyid(relowner) FROM pg_class WHERE oid = to_regclass(%s)", + (f'"{schema_for(self.slugs["a"])}"."{res["tableName"]}"',), + ) self.assertEqual(cur.fetchone()[0], role_for(self.slugs["a"])) def test_a_connection_goes_back_to_the_pool_as_the_login_role(self): @@ -302,12 +341,12 @@ def test_a_connection_goes_back_to_the_pool_as_the_login_role(self): self.assertTrue(fail) self.assertFalse(raw.closed, "the connection should have been reset and pooled, not closed") self.assertIn(raw, db._pool._pool, "the connection is back in the pool") - with raw.cursor() as cur: # the pooled connection itself, as the next borrower would get it + with raw.cursor() as cur: # the pooled connection itself, as the next borrower would get it cur.execute("SELECT current_user = session_user, current_user") same, who = cur.fetchone() raw.rollback() self.assertTrue(same, f"pooled connection still runs as {who}") - with Conn() as conn, conn.cursor() as cur: # and an unscoped borrow is the login role + with Conn() as conn, conn.cursor() as cur: # and an unscoped borrow is the login role cur.execute("SELECT current_user = session_user") self.assertTrue(cur.fetchone()[0]) diff --git a/tests/system/test_tenant_te_migrations.py b/tests/system/test_tenant_te_migrations.py index 0997c4a..460a865 100644 --- a/tests/system/test_tenant_te_migrations.py +++ b/tests/system/test_tenant_te_migrations.py @@ -26,14 +26,23 @@ from unittest import mock import pytest -from alembic import command from alembic.script import ScriptDirectory from psycopg2 import sql +from alembic import command from api.config import TE_TABLES, settings from api.db import APPEND_ONLY, owner_connect -from api.tenancy import (TE_BASELINE, TE_VERSION_TABLE, _te_config, migrate_te_schema, migrate_tenant, - provision_te_tables, schema_for, te_head, template_te_version) +from api.tenancy import ( + TE_BASELINE, + TE_VERSION_TABLE, + _te_config, + migrate_te_schema, + migrate_tenant, + provision_te_tables, + schema_for, + te_head, + template_te_version, +) ROOT = Path(__file__).resolve().parents[2] _PROGRAM_TABLES = ("test_cases", "test_events", "vcrm_entries", "test_results") @@ -49,8 +58,11 @@ def test_it_is_linear_and_starts_at_the_baseline(self): def test_both_copies_of_the_schema_file_stamp_the_head(self): for path in ("build/te_core_schema.sql", "build/schema/postgresql/te_core_schema.sql"): text = (ROOT / path).read_text(encoding="utf-8") - self.assertIn(f"IS 'te_schema_version={te_head()}'", text, - f"{path} must stamp the newest migration; bump it with the migration") + self.assertIn( + f"IS 'te_schema_version={te_head()}'", + text, + f"{path} must stamp the newest migration; bump it with the migration", + ) def test_the_runtime_role_cannot_rewrite_the_version_table(self): self.assertIn(TE_VERSION_TABLE, APPEND_ONLY) @@ -58,28 +70,41 @@ def test_the_runtime_role_cannot_rewrite_the_version_table(self): def signature(cur, schema: str) -> dict[str, list]: """Everything about a schema's T&E tables that a migration could change, with its own name removed.""" + def norm(text): return None if text is None else re.sub(rf'(?.", text) sig: dict[str, list] = {} - cur.execute("SELECT table_name, column_name, data_type, is_nullable, column_default " - "FROM information_schema.columns WHERE table_schema = %s AND table_name = ANY(%s)", - (schema, TE_TABLES)) + cur.execute( + "SELECT table_name, column_name, data_type, is_nullable, column_default " + "FROM information_schema.columns WHERE table_schema = %s AND table_name = ANY(%s)", + (schema, TE_TABLES), + ) sig["columns"] = sorted((t, c, d, n, norm(df)) for t, c, d, n, df in cur.fetchall()) - cur.execute("SELECT r.relname, c.conname, c.contype, pg_get_constraintdef(c.oid) FROM pg_constraint c " - "JOIN pg_class r ON r.oid = c.conrelid WHERE r.relnamespace = %s::regnamespace " - "AND r.relname = ANY(%s)", (schema, TE_TABLES)) + cur.execute( + "SELECT r.relname, c.conname, c.contype, pg_get_constraintdef(c.oid) FROM pg_constraint c " + "JOIN pg_class r ON r.oid = c.conrelid WHERE r.relnamespace = %s::regnamespace " + "AND r.relname = ANY(%s)", + (schema, TE_TABLES), + ) sig["constraints"] = sorted((t, n, k, norm(d)) for t, n, k, d in cur.fetchall()) - cur.execute("SELECT tablename, indexname, indexdef FROM pg_indexes WHERE schemaname = %s " - "AND tablename = ANY(%s)", (schema, TE_TABLES)) + cur.execute( + "SELECT tablename, indexname, indexdef FROM pg_indexes WHERE schemaname = %s AND tablename = ANY(%s)", + (schema, TE_TABLES), + ) sig["indexes"] = sorted((t, n, norm(d)) for t, n, d in cur.fetchall()) - cur.execute("SELECT r.relname, t.tgname, pg_get_triggerdef(t.oid) FROM pg_trigger t " - "JOIN pg_class r ON r.oid = t.tgrelid WHERE r.relnamespace = %s::regnamespace " - "AND r.relname = ANY(%s) AND NOT t.tgisinternal", (schema, TE_TABLES)) + cur.execute( + "SELECT r.relname, t.tgname, pg_get_triggerdef(t.oid) FROM pg_trigger t " + "JOIN pg_class r ON r.oid = t.tgrelid WHERE r.relnamespace = %s::regnamespace " + "AND r.relname = ANY(%s) AND NOT t.tgisinternal", + (schema, TE_TABLES), + ) sig["triggers"] = sorted((t, n, norm(d)) for t, n, d in cur.fetchall()) - cur.execute("SELECT p.proname, pg_get_functiondef(p.oid) FROM pg_proc p WHERE " - "p.pronamespace = %s::regnamespace AND p.proname IN ('set_updated_at', 'te_fill_program_id')", - (schema,)) + cur.execute( + "SELECT p.proname, pg_get_functiondef(p.oid) FROM pg_proc p WHERE " + "p.pronamespace = %s::regnamespace AND p.proname IN ('set_updated_at', 'te_fill_program_id')", + (schema,), + ) sig["functions"] = sorted((n, norm(d)) for n, d in cur.fetchall()) return sig @@ -118,16 +143,22 @@ def _signature(self, schema=None): return signature(cur, schema or self.schema) def _version(self) -> str | None: - rows = self._q(sql.SQL("SELECT version_num FROM {}.{}").format( - sql.Identifier(self.schema), sql.Identifier(TE_VERSION_TABLE))) + rows = self._q( + sql.SQL("SELECT version_num FROM {}.{}").format( + sql.Identifier(self.schema), sql.Identifier(TE_VERSION_TABLE) + ) + ) return rows[0][0] if rows else None def _assert_matches_template(self, schema=None): actual = self._signature(schema) for part, expected in self.template_sig.items(): missing, extra = sorted(set(expected) - set(actual[part])), sorted(set(actual[part]) - set(expected)) - self.assertEqual((missing, extra), ([], []), - f"{part}: the tenant lacks the first list and has the second beyond the template") + self.assertEqual( + (missing, extra), + ([], []), + f"{part}: the tenant lacks the first list and has the second beyond the template", + ) def _migrate(self) -> str: with owner_connect() as conn, conn.cursor() as cur: @@ -138,23 +169,38 @@ def _make_old_shape_tenant(self): migrate_tenant(self.slug) command.downgrade(_te_config(self.schema), TE_BASELINE) with owner_connect() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("DROP TABLE {}.{}").format(sql.Identifier(self.schema), - sql.Identifier(TE_VERSION_TABLE))) + cur.execute( + sql.SQL("DROP TABLE {}.{}").format(sql.Identifier(self.schema), sql.Identifier(TE_VERSION_TABLE)) + ) for table in TE_TABLES: - cur.execute("SELECT column_name FROM information_schema.columns WHERE table_schema = %s " - "AND table_name = %s", (self.schema, table)) + cur.execute( + "SELECT column_name FROM information_schema.columns WHERE table_schema = %s AND table_name = %s", + (self.schema, table), + ) mine = {r[0] for r in cur.fetchall()} - cur.execute("SELECT column_name FROM information_schema.columns WHERE table_schema = %s " - "AND table_name = %s", (self._template, table)) + cur.execute( + "SELECT column_name FROM information_schema.columns WHERE table_schema = %s AND table_name = %s", + (self._template, table), + ) cols = sql.SQL(", ").join(sql.Identifier(c) for c in sorted(mine & {r[0] for r in cur.fetchall()})) - cur.execute(sql.SQL("INSERT INTO {s}.{t} ({c}) SELECT {c} FROM {tpl}.{t}").format( - s=sql.Identifier(self.schema), t=sql.Identifier(table), c=cols, - tpl=sql.Identifier(self._template))) + cur.execute( + sql.SQL("INSERT INTO {s}.{t} ({c}) SELECT {c} FROM {tpl}.{t}").format( + s=sql.Identifier(self.schema), + t=sql.Identifier(table), + c=cols, + tpl=sql.Identifier(self._template), + ) + ) conn.commit() - seeded = self._q(sql.SQL("SELECT (SELECT count(*) FROM {t}.test_programs), (SELECT count(*) FROM {t}.vcrm_entries)") - .format(t=sql.Identifier(self._template)))[0] - self.assertTrue(seeded[0] >= 2 and seeded[1] >= 1, - f"the template needs seed rows for two programs and a VCRM entry (SEED_DEV=true); has {seeded}") + seeded = self._q( + sql.SQL("SELECT (SELECT count(*) FROM {t}.test_programs), (SELECT count(*) FROM {t}.vcrm_entries)").format( + t=sql.Identifier(self._template) + ) + )[0] + self.assertTrue( + seeded[0] >= 2 and seeded[1] >= 1, + f"the template needs seed rows for two programs and a VCRM entry (SEED_DEV=true); has {seeded}", + ) # -- paths to the template's shape ----------------------------------------------------- @@ -189,35 +235,61 @@ def test_downgrade_restores_the_shape_from_before_177_and_upgrade_restores_the_t def test_a_tenant_from_before_versioning_is_adopted_and_keeps_its_data(self): self._make_old_shape_tenant() - updated_before = self._q(sql.SQL("SELECT tc_id, updated_at FROM {}.test_cases ORDER BY tc_id").format( - sql.Identifier(self.schema))) + updated_before = self._q( + sql.SQL("SELECT tc_id, updated_at FROM {}.test_cases ORDER BY tc_id").format(sql.Identifier(self.schema)) + ) self.assertTrue(updated_before) self.assertEqual(self._migrate(), "adopted") self.assertEqual(self._version(), te_head()) self._assert_matches_template() # program_id came from each row's parent, so it equals the template's value for the same row - for table, key in (("test_cases", "tc_id"), ("test_events", "event_id"), - ("vcrm_entries", "vcrm_id"), ("test_results", "result_id")): - mine = self._q(sql.SQL("SELECT {k}, program_id FROM {}.{} ORDER BY {k}").format( - sql.Identifier(self.schema), sql.Identifier(table), k=sql.Identifier(key))) - theirs = self._q(sql.SQL("SELECT {k}, program_id FROM {}.{} WHERE {k} = ANY(%s::uuid[]) ORDER BY {k}").format( - sql.Identifier(self._template), sql.Identifier(table), k=sql.Identifier(key)), - ([r[0] for r in mine],)) + for table, key in ( + ("test_cases", "tc_id"), + ("test_events", "event_id"), + ("vcrm_entries", "vcrm_id"), + ("test_results", "result_id"), + ): + mine = self._q( + sql.SQL("SELECT {k}, program_id FROM {}.{} ORDER BY {k}").format( + sql.Identifier(self.schema), sql.Identifier(table), k=sql.Identifier(key) + ) + ) + theirs = self._q( + sql.SQL("SELECT {k}, program_id FROM {}.{} WHERE {k} = ANY(%s::uuid[]) ORDER BY {k}").format( + sql.Identifier(self._template), sql.Identifier(table), k=sql.Identifier(key) + ), + ([r[0] for r in mine],), + ) self.assertEqual(mine, theirs, table) - self.assertEqual(self._q(sql.SQL("SELECT tc_id, updated_at FROM {}.test_cases ORDER BY tc_id").format( - sql.Identifier(self.schema))), updated_before, "the backfill must not look like an edit") + self.assertEqual( + self._q( + sql.SQL("SELECT tc_id, updated_at FROM {}.test_cases ORDER BY tc_id").format( + sql.Identifier(self.schema) + ) + ), + updated_before, + "the backfill must not look like an edit", + ) def test_a_tenant_cloned_after_177_with_default_constraint_names_is_adopted_without_duplicates(self): migrate_tenant(self.slug) s = sql.Identifier(self.schema) - self._q(sql.SQL("ALTER TABLE {}.test_phases RENAME CONSTRAINT uq_phases_id_program " - "TO test_phases_phase_id_program_id_key").format(s)) + self._q( + sql.SQL( + "ALTER TABLE {}.test_phases RENAME CONSTRAINT uq_phases_id_program " + "TO test_phases_phase_id_program_id_key" + ).format(s) + ) self._q(sql.SQL("DROP TABLE {}.{}").format(s, sql.Identifier(TE_VERSION_TABLE))) self.assertEqual(self._migrate(), "adopted") self._assert_matches_template() - unique_on_phases = self._q(sql.SQL( - "SELECT count(*) FROM pg_constraint WHERE conrelid = %s::regclass AND contype = 'u' " - "AND pg_get_constraintdef(oid) = 'UNIQUE (phase_id, program_id)'"), (f'"{self.schema}".test_phases',)) + unique_on_phases = self._q( + sql.SQL( + "SELECT count(*) FROM pg_constraint WHERE conrelid = %s::regclass AND contype = 'u' " + "AND pg_get_constraintdef(oid) = 'UNIQUE (phase_id, program_id)'" + ), + (f'"{self.schema}".test_phases',), + ) self.assertEqual(unique_on_phases[0][0], 1, "an equivalent constraint must be renamed, not duplicated") def test_a_clone_carries_the_templates_index_and_constraint_names(self): @@ -225,17 +297,21 @@ def test_a_clone_carries_the_templates_index_and_constraint_names(self): names = {n for _, n, *_ in self._signature()["indexes"]} self.assertLessEqual({"idx_testcases_phase", "uq_phases_id_program", "idx_personnel_email_trgm"}, names) # what LIKE ... INCLUDING ALL would have called the same objects - self.assertTrue(names.isdisjoint({"test_cases_phase_id_idx", "test_phases_phase_id_program_id_key", - "personnel_email_idx"})) + self.assertTrue( + names.isdisjoint({"test_cases_phase_id_idx", "test_phases_phase_id_program_id_key", "personnel_email_idx"}) + ) def test_cross_program_rows_stop_the_upgrade_name_the_rows_and_change_nothing(self): self._make_old_shape_tenant() s = sql.Identifier(self.schema) # old shape: a VCRM entry may name a requirement from one program and a test case from another - (vcrm_id, other_req), = self._q(sql.SQL( - "SELECT v.vcrm_id, r.req_id FROM {s}.vcrm_entries v " - "JOIN {s}.test_cases c ON c.tc_id = v.tc_id JOIN {s}.test_phases ph ON ph.phase_id = c.phase_id " - "JOIN {s}.requirements r ON r.program_id <> ph.program_id LIMIT 1").format(s=s)) + ((vcrm_id, other_req),) = self._q( + sql.SQL( + "SELECT v.vcrm_id, r.req_id FROM {s}.vcrm_entries v " + "JOIN {s}.test_cases c ON c.tc_id = v.tc_id JOIN {s}.test_phases ph ON ph.phase_id = c.phase_id " + "JOIN {s}.requirements r ON r.program_id <> ph.program_id LIMIT 1" + ).format(s=s) + ) self._q(sql.SQL("UPDATE {}.vcrm_entries SET req_id = %s WHERE vcrm_id = %s").format(s), (other_req, vcrm_id)) before = self._signature() with self.assertRaises(RuntimeError) as ctx: @@ -255,8 +331,9 @@ def test_a_template_at_an_older_version_is_cloned_then_brought_forward(self): conn.commit() command.stamp(_te_config(scratch), te_head()) command.downgrade(_te_config(scratch), TE_BASELINE) - self._q(sql.SQL("COMMENT ON SCHEMA {} IS %s").format(sql.Identifier(scratch)), - (f"te_schema_version={TE_BASELINE}",)) + self._q( + sql.SQL("COMMENT ON SCHEMA {} IS %s").format(sql.Identifier(scratch)), (f"te_schema_version={TE_BASELINE}",) + ) settings.TE_SCHEMA = scratch try: self.assertEqual(self._migrate_new(), "provisioned") @@ -280,14 +357,17 @@ def test_the_next_schema_change_reaches_existing_and_new_tenants(self): migrate_tenant(existing) chain = Path(tempfile.mkdtemp(prefix="alembic_te_next_")) try: - shutil.copytree(ROOT / "alembic_te", chain, dirs_exist_ok=True, - ignore=shutil.ignore_patterns("__pycache__")) + shutil.copytree( + ROOT / "alembic_te", chain, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__") + ) (chain / "versions" / "te9001_demo.py").write_text( 'from alembic import op\nrevision = "te9001"\ndown_revision = "te0002"\n' "branch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n" ' schema = op.get_context().opts["version_table_schema"]\n' - ' op.execute(f\'ALTER TABLE "{schema}".organisations ADD COLUMN demo_note TEXT\')\n\n\n' - "def downgrade():\n pass\n", encoding="utf-8") + " op.execute(f'ALTER TABLE \"{schema}\".organisations ADD COLUMN demo_note TEXT')\n\n\n" + "def downgrade():\n pass\n", + encoding="utf-8", + ) def config_with_next_change(schema): cfg = _te_config(schema) @@ -295,8 +375,13 @@ def config_with_next_change(schema): return cfg def has_demo_note(schema): - return bool(self._q("SELECT 1 FROM information_schema.columns WHERE table_schema = %s " - "AND table_name = 'organisations' AND column_name = 'demo_note'", (schema,))) + return bool( + self._q( + "SELECT 1 FROM information_schema.columns WHERE table_schema = %s " + "AND table_name = 'organisations' AND column_name = 'demo_note'", + (schema,), + ) + ) with mock.patch("api.tenancy._te_config", side_effect=config_with_next_change): self.assertFalse(has_demo_note(self.schema)) @@ -338,7 +423,9 @@ def test_a_template_stamped_with_an_unknown_version_is_refused(self): self._migrate_new() def test_two_workers_starting_together_leave_one_correct_tenant(self): - self._q(sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(self.schema))) # the T&E tables are what both race to build + self._q( + sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(self.schema)) + ) # the T&E tables are what both race to build with ThreadPoolExecutor(max_workers=2) as pool: results = [f.result() for f in [pool.submit(self._migrate_new) for _ in range(2)]] self.assertEqual(sorted(results), ["provisioned", "upgraded"]) diff --git a/tests/system/test_type_provenance.py b/tests/system/test_type_provenance.py index 554e9b1..88c8e31 100644 --- a/tests/system/test_type_provenance.py +++ b/tests/system/test_type_provenance.py @@ -21,14 +21,18 @@ from api.db import Conn from api.main import app -_HELP = ("Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" - "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it (PGHOST/PGPORT/PGUSER/" + "PGPASSWORD/PGDATABASE). See scripts/start-api.ps1." +) def _column_types(table: str) -> dict[str, str]: with Conn() as conn, conn.cursor() as cur: - cur.execute("SELECT column_name, data_type FROM information_schema.columns " - "WHERE table_schema = %s AND table_name = %s", (settings.UPLOADS_SCHEMA, table)) + cur.execute( + "SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = %s AND table_name = %s", + (settings.UPLOADS_SCHEMA, table), + ) return dict(cur.fetchall()) @@ -89,24 +93,38 @@ def test_no_types_at_all_is_unconfirmed(self): self.assertEqual(self._registered()["types_provenance"], "inferred_unconfirmed") def test_confirmation_without_the_confirmed_types_is_rejected_and_loads_nothing(self): - resp = self.client.post("/api/csv/upload", json={ - "fileName": self.name, "content": self.content, "typesConfirmed": True}) + resp = self.client.post( + "/api/csv/upload", json={"fileName": self.name, "content": self.content, "typesConfirmed": True} + ) self.assertEqual(resp.status_code, 422) self.assertIsNone(self._registered()) def test_te_mode_rejects_types_confirmed(self): - resp = self.client.post("/api/csv/upload", json={ - "fileName": self.name, "content": self.content, "mode": "te", - "targetTable": "organisations", "typesConfirmed": True}) + resp = self.client.post( + "/api/csv/upload", + json={ + "fileName": self.name, + "content": self.content, + "mode": "te", + "targetTable": "organisations", + "typesConfirmed": True, + }, + ) self.assertEqual(resp.status_code, 422) self.assertIn("dynamic", resp.json()["detail"]) def test_te_import_rejects_a_dynamic_table_as_its_target(self): dynamic = self._upload(types=["int8", "text"], typesConfirmed=True) self.assertEqual(dynamic["status"], "ok", dynamic) - res = self.client.post("/api/csv/upload", json={ - "fileName": f"te_{self.name}", "content": self.content, "mode": "te", - "targetTable": dynamic["tableName"]}).json() + res = self.client.post( + "/api/csv/upload", + json={ + "fileName": f"te_{self.name}", + "content": self.content, + "mode": "te", + "targetTable": dynamic["tableName"], + }, + ).json() self.assertEqual(res["status"], "error", res) self.assertIn(dynamic["tableName"], res["message"].lower()) self.assertFalse([f for f in self.client.get("/api/csv/files").json() if f["file_name"] == f"te_{self.name}"]) diff --git a/tests/system/test_upload_atomic_records.py b/tests/system/test_upload_atomic_records.py index 2435781..3efadd7 100644 --- a/tests/system/test_upload_atomic_records.py +++ b/tests/system/test_upload_atomic_records.py @@ -12,6 +12,7 @@ Integration: needs a live PostgreSQL with the dev schema deployed, as in CI. """ + from __future__ import annotations import contextlib @@ -66,8 +67,7 @@ def setUp(self): def _q(self, query: str, *params): with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL(query).format(s=sql.Identifier(self.schema), t=sql.Identifier(self.te_schema)), - params) + cur.execute(sql.SQL(query).format(s=sql.Identifier(self.schema), t=sql.Identifier(self.te_schema)), params) return cur.fetchall() def _registry(self): @@ -77,12 +77,14 @@ def _uploads(self): return self._q("SELECT status, csv_file_id FROM {s}.uploads WHERE file_name = %s ORDER BY id", self.name) def _upload_audit(self): - return self._q("SELECT file_id, table_name FROM {s}.audit_log WHERE action = 'upload' AND file_name = %s", - self.name) + return self._q( + "SELECT file_id, table_name FROM {s}.audit_log WHERE action = 'upload' AND file_name = %s", self.name + ) def _dataset_tables(self) -> int: - return self._q("SELECT count(*) FROM pg_tables WHERE schemaname = %s AND tablename LIKE 'csv\\_%%'", - self.schema)[0][0] + return self._q( + "SELECT count(*) FROM pg_tables WHERE schemaname = %s AND tablename LIKE 'csv\\_%%'", self.schema + )[0][0] def _te_rows(self, org: str) -> int: return self._q("SELECT count(*) FROM {t}.organisations WHERE name = %s", org)[0][0] @@ -94,32 +96,52 @@ def _cleanup(self, org: str | None = None): self.client.delete(f"/api/csv/files/{f['id']}") with Conn() as conn, conn.cursor() as cur: if org: - cur.execute(sql.SQL("DELETE FROM {}.organisations WHERE name = %s").format( - sql.Identifier(self.te_schema)), (org,)) - cur.execute(sql.SQL("DELETE FROM {}.csv_files WHERE file_name = %s AND mode = 'te'").format( - sql.Identifier(self.schema)), (self.name,)) + cur.execute( + sql.SQL("DELETE FROM {}.organisations WHERE name = %s").format(sql.Identifier(self.te_schema)), + (org,), + ) + cur.execute( + sql.SQL("DELETE FROM {}.csv_files WHERE file_name = %s AND mode = 'te'").format( + sql.Identifier(self.schema) + ), + (self.name,), + ) conn.commit() def _dynamic(self): - return self.client.post("/api/csv/upload", json={ - "fileName": self.name, "content": f"k,v\n{self.tag},1\nsecond,2\n", "mode": "dynamic"}) + return self.client.post( + "/api/csv/upload", + json={"fileName": self.name, "content": f"k,v\n{self.tag},1\nsecond,2\n", "mode": "dynamic"}, + ) def _te(self, org: str): - return self.client.post("/api/csv/upload", json={ - "fileName": self.name, "content": f"name,org_type,country\n{org},government,AU\n", - "mode": "te", "targetTable": "organisations"}) + return self.client.post( + "/api/csv/upload", + json={ + "fileName": self.name, + "content": f"name,org_type,country\n{org},government,AU\n", + "mode": "te", + "targetTable": "organisations", + }, + ) def _assert_nothing_committed(self, res, tables_before: int, org: str | None = None): body = res.json() if res.headers.get("content-type", "").startswith("application/json") else {} - self.assertFalse(res.status_code == 200 and body.get("status") == "ok", - f"a load whose records could not be written must not report success: {res.status_code} {res.text}") + self.assertFalse( + res.status_code == 200 and body.get("status") == "ok", + f"a load whose records could not be written must not report success: {res.status_code} {res.text}", + ) self.assertEqual(self._registry(), [], "the load's registry row committed without its records") - self.assertEqual(self._dataset_tables(), tables_before, "the load's dataset table committed without its records") + self.assertEqual( + self._dataset_tables(), tables_before, "the load's dataset table committed without its records" + ) if org: self.assertEqual(self._te_rows(org), 0, "the load's T&E rows committed without its records") self.assertEqual(self._upload_audit(), [], "no upload audit row may exist for a load that did not commit") - self.assertTrue(all(status == "failed" and file_id is None for status, file_id in self._uploads()), - f"only a failed attempt may be recorded: {self._uploads()}") + self.assertTrue( + all(status == "failed" and file_id is None for status, file_id in self._uploads()), + f"only a failed attempt may be recorded: {self._uploads()}", + ) # -- faults ---------------------------------------------------------------------------------- diff --git a/tests/system/test_versioned_datasets.py b/tests/system/test_versioned_datasets.py index 9a1ff2f..34b628d 100644 --- a/tests/system/test_versioned_datasets.py +++ b/tests/system/test_versioned_datasets.py @@ -80,8 +80,11 @@ def tearDown(self): self.client.delete(f"/api/csv/files/{f['id']}", headers=self.headers) def up(self, name: str, content: str, **extra) -> dict: - res = self.client.post("/api/csv/upload", headers=self.headers, - json={"fileName": f"{self.tag}_{name}", "content": content, **extra}) + res = self.client.post( + "/api/csv/upload", + headers=self.headers, + json={"fileName": f"{self.tag}_{name}", "content": content, **extra}, + ) self.assertEqual(res.status_code, 200, res.text) return res.json() @@ -115,8 +118,11 @@ def test_same_name_different_content_becomes_versions_and_keeps_every_table(self self.assertEqual([r["status"] for r in (v1, v2, v3)], ["ok"] * 3) self.assertEqual([r["version"] for r in (v1, v2, v3)], [1, 2, 3]) self.assertEqual(v2["tableName"], f"csv_{dataset_slug(self.tag + '_sales.csv')}_v2") - self.assertEqual([self.rows(r["tableName"])[0]["v"] for r in (v1, v2, v3)], ["a", "b", "c"], - "an earlier version's rows must be exactly what was uploaded") + self.assertEqual( + [self.rows(r["tableName"])[0]["v"] for r in (v1, v2, v3)], + ["a", "b", "c"], + "an earlier version's rows must be exactly what was uploaded", + ) self.assertEqual(len(self.files()), 3) def test_overwrite_is_never_honoured(self): @@ -134,8 +140,9 @@ def test_filenames_with_one_slug_are_one_dataset(self): def test_a_filename_cannot_name_a_registry_table(self): # A bare slug would collide with the uploads registry; the csv_ prefix and _v suffix prevent it. - res = self.client.post("/api/csv/upload", headers=self.headers, - json={"fileName": "uploads.csv", "content": f"k\n{self.tag}\n"}) + res = self.client.post( + "/api/csv/upload", headers=self.headers, json={"fileName": "uploads.csv", "content": f"k\n{self.tag}\n"} + ) body = res.json() self.assertEqual(body["status"], "ok", body) self.addCleanup(self.client.delete, f"/api/csv/files/{body['fileId']}", headers=self.headers) @@ -203,8 +210,11 @@ def test_the_user_decides_per_row_through_review(self): self.assertEqual(before[0]["duplicateOfEarlierVersion"]["version"], 1) self.assertIsNone(before[1]["duplicateOfEarlierVersion"]) self.assertEqual(before[0]["decision"], "include", "a flag does not decide anything by itself") - res = self.client.put(f"{review[:-5]}/rows/1/decision", headers=self.headers, - json={"decision": "exclude", "reason": "already loaded in v1"}) + res = self.client.put( + f"{review[:-5]}/rows/1/decision", + headers=self.headers, + json={"decision": "exclude", "reason": "already loaded in v1"}, + ) self.assertEqual(res.status_code, 200, res.text) after = self.client.get(review, headers=self.headers).json()["rows"][0] self.assertEqual(after["decision"], "exclude") @@ -214,10 +224,14 @@ def test_flags_are_insert_only(self): self.up("io.csv", "k\n1\n") v2 = self.up("io.csv", "k\n1\n2\n") with Conn() as conn, conn.cursor() as cur: - for statement in ("UPDATE {}.row_flags SET matched_version = 9 WHERE upload_id = %s", - "DELETE FROM {}.row_flags WHERE upload_id = %s"): + for statement in ( + "UPDATE {}.row_flags SET matched_version = 9 WHERE upload_id = %s", + "DELETE FROM {}.row_flags WHERE upload_id = %s", + ): with self.assertRaises(psycopg2.errors.InsufficientPrivilege): - cur.execute(sql.SQL(statement).format(sql.Identifier(settings.UPLOADS_SCHEMA)), (int(v2["uploadId"]),)) + cur.execute( + sql.SQL(statement).format(sql.Identifier(settings.UPLOADS_SCHEMA)), (int(v2["uploadId"]),) + ) conn.rollback() # -- T&E loads share the registry ------------------------------------------ @@ -226,9 +240,16 @@ def test_a_te_load_with_a_datasets_name_does_not_touch_its_versions(self): v1 = self.up("t.csv", "k\n1\n") v2 = self.up("t.csv", "k\n2\n") org = f"{self.tag}_org" - te = self.client.post("/api/csv/upload", headers=self.headers, json={ - "fileName": f"{self.tag}_t.csv", "mode": "te", "targetTable": "organisations", - "content": f"name,org_type,country\n{org},government,AU\n"}).json() + te = self.client.post( + "/api/csv/upload", + headers=self.headers, + json={ + "fileName": f"{self.tag}_t.csv", + "mode": "te", + "targetTable": "organisations", + "content": f"name,org_type,country\n{org},government,AU\n", + }, + ).json() self.assertEqual(te["status"], "ok", te) self.addCleanup(self._drop_org, org) self.assertEqual(sorted(f["mode"] for f in self.files()), ["dynamic", "dynamic", "te"]) @@ -237,8 +258,10 @@ def test_a_te_load_with_a_datasets_name_does_not_touch_its_versions(self): def _drop_org(self, name: str) -> None: with Conn() as conn, conn.cursor() as cur: - cur.execute(sql.SQL("DELETE FROM {}.organisations WHERE name = %s").format( - sql.Identifier(settings.TE_SCHEMA)), (name,)) + cur.execute( + sql.SQL("DELETE FROM {}.organisations WHERE name = %s").format(sql.Identifier(settings.TE_SCHEMA)), + (name,), + ) conn.commit() @@ -263,7 +286,9 @@ def setUpClass(cls): accounts.add_membership(cur, uid, tid, "tenant_admin") conn.commit() migrate_tenant(cls.slug) - res = cls.client.post("/api/auth/login", json={"tenant": cls.slug, "username": f"{cls.slug}_user", "password": pw}) + res = cls.client.post( + "/api/auth/login", json={"tenant": cls.slug, "username": f"{cls.slug}_user", "password": pw} + ) assert res.status_code == 200, res.text cls.auth = {"Authorization": f"Bearer {res.json()['token']}"} @@ -279,8 +304,9 @@ def tearDownClass(cls): cls.ctx.__exit__(None, None, None) def up(self, name: str, content: str, auth: bool) -> dict: - res = self.client.post("/api/csv/upload", headers=self.auth if auth else {}, - json={"fileName": name, "content": content}) + res = self.client.post( + "/api/csv/upload", headers=self.auth if auth else {}, json={"fileName": name, "content": content} + ) self.assertEqual(res.status_code, 200, res.text) return res.json() diff --git a/tests/system_integration/environments/_contract.py b/tests/system_integration/environments/_contract.py index 1a77418..fda79ac 100644 --- a/tests/system_integration/environments/_contract.py +++ b/tests/system_integration/environments/_contract.py @@ -1,16 +1,26 @@ """Shared contract every deployed environment must satisfy.""" + from __future__ import annotations + import shutil import subprocess # nosec B404 CORE_TABLES = { - "organisations", "personnel", "test_programs", "temp_documents", - "test_phases", "requirements", "test_cases", "vcrm_entries", - "test_events", "test_results", "defect_reports", "evidence_artifacts", + "organisations", + "personnel", + "test_programs", + "temp_documents", + "test_phases", + "requirements", + "test_cases", + "vcrm_entries", + "test_events", + "test_results", + "defect_reports", + "evidence_artifacts", } SEEDED_TABLES = ("organisations", "personnel", "requirements") -HELP = ("Deploy environments first:\n" - " bash scripts/provision_full_test_env.sh") +HELP = "Deploy environments first:\n bash scripts/provision_full_test_env.sh" def _psql(db, sql): @@ -19,7 +29,10 @@ def _psql(db, sql): try: proc = subprocess.run( # nosec B603 B607 ["psql", "-d", db, "-tA", "--no-psqlrc", "-v", "ON_ERROR_STOP=1", "-c", sql], - capture_output=True, text=True, timeout=20) + capture_output=True, + text=True, + timeout=20, + ) except (subprocess.TimeoutExpired, FileNotFoundError) as exc: return False, str(exc) return proc.returncode == 0, proc.stdout.strip() @@ -45,7 +58,9 @@ def test_database_exists(self): self.assertEqual(out, "1") def test_schema_has_all_core_tables(self): - ok, out = _psql(self.DB, f"SELECT table_name FROM information_schema.tables WHERE table_schema = '{self.SCHEMA}'") + ok, out = _psql( + self.DB, f"SELECT table_name FROM information_schema.tables WHERE table_schema = '{self.SCHEMA}'" + ) self.assertTrue(ok, out) missing = sorted(CORE_TABLES - set(out.splitlines())) self.assertEqual(missing, [], f"{self.ENV}: missing tables {missing}") diff --git a/tests/system_integration/environments/test_env_dev.py b/tests/system_integration/environments/test_env_dev.py index 23d64a2..bf8c6f7 100644 --- a/tests/system_integration/environments/test_env_dev.py +++ b/tests/system_integration/environments/test_env_dev.py @@ -1,6 +1,9 @@ """Contract tests for the dev environment.""" + import unittest + import pytest + from tests.system_integration.environments._contract import EnvironmentContract pytestmark = [pytest.mark.integration, pytest.mark.parity] diff --git a/tests/system_integration/environments/test_env_prod.py b/tests/system_integration/environments/test_env_prod.py index 71412dd..78baffe 100644 --- a/tests/system_integration/environments/test_env_prod.py +++ b/tests/system_integration/environments/test_env_prod.py @@ -1,6 +1,9 @@ """Contract tests for the prod environment.""" + import unittest + import pytest + from tests.system_integration.environments._contract import EnvironmentContract pytestmark = [pytest.mark.integration, pytest.mark.parity] diff --git a/tests/system_integration/environments/test_env_staging.py b/tests/system_integration/environments/test_env_staging.py index 0d8b57d..7ef58cb 100644 --- a/tests/system_integration/environments/test_env_staging.py +++ b/tests/system_integration/environments/test_env_staging.py @@ -1,6 +1,9 @@ """Contract tests for the staging environment.""" + import unittest + import pytest + from tests.system_integration.environments._contract import EnvironmentContract pytestmark = [pytest.mark.integration, pytest.mark.parity] diff --git a/tests/system_integration/environments/test_env_test.py b/tests/system_integration/environments/test_env_test.py index 6e909b1..217a3f1 100644 --- a/tests/system_integration/environments/test_env_test.py +++ b/tests/system_integration/environments/test_env_test.py @@ -1,6 +1,9 @@ """Contract tests for the test environment.""" + import unittest + import pytest + from tests.system_integration.environments._contract import EnvironmentContract pytestmark = [pytest.mark.integration, pytest.mark.parity] diff --git a/tests/system_integration/test_csv_loader_arbitrary_shapes.py b/tests/system_integration/test_csv_loader_arbitrary_shapes.py index e3e6c0b..dc8b629 100644 --- a/tests/system_integration/test_csv_loader_arbitrary_shapes.py +++ b/tests/system_integration/test_csv_loader_arbitrary_shapes.py @@ -8,6 +8,7 @@ Skipped automatically when PostgreSQL is not reachable. """ + import csv import os import shutil @@ -21,17 +22,16 @@ pytestmark = pytest.mark.integration -ROOT = Path(__file__).resolve().parents[2] -LOADER = ROOT / "build" / "csv_loader.sh" -UTILISE = ROOT / "build" / "csv_utilise.sh" -BUILD_DIR = ROOT / "build" +ROOT = Path(__file__).resolve().parents[2] +LOADER = ROOT / "build" / "csv_loader.sh" +UTILISE = ROOT / "build" / "csv_utilise.sh" +BUILD_DIR = ROOT / "build" def _find_bash(): """Locate a real bash; on Windows prefer Git Bash over the WSL shim.""" if sys.platform == "win32": - for c in (r"C:\Program Files\Git\bin\bash.exe", - r"C:\Program Files (x86)\Git\bin\bash.exe"): + for c in (r"C:\Program Files\Git\bin\bash.exe", r"C:\Program Files (x86)\Git\bin\bash.exe"): if Path(c).exists(): return c which = shutil.which("bash") @@ -50,7 +50,9 @@ def _can_connect_pg() -> bool: try: r = subprocess.run( ["psql", "-tA", "-c", "SELECT 1"], - capture_output=True, text=True, timeout=5, + capture_output=True, + text=True, + timeout=5, env={**os.environ, "PGUSER": os.environ.get("PGUSER", "postgres")}, ) return r.returncode == 0 @@ -61,8 +63,7 @@ def _can_connect_pg() -> bool: _PG_AVAILABLE = _can_connect_pg() _CONFIG_PRESENT = (BUILD_DIR / "config.local.env").exists() _SKIP_REASON = ( - "PostgreSQL not reachable" if not _PG_AVAILABLE - else "build/config.local.env not present — run ./build/setup.sh" + "PostgreSQL not reachable" if not _PG_AVAILABLE else "build/config.local.env not present — run ./build/setup.sh" ) @@ -79,15 +80,14 @@ class CsvLoaderArbitraryShapes(unittest.TestCase): @classmethod def setUpClass(cls): if not (_PG_AVAILABLE and _CONFIG_PRESENT): - raise AssertionError( - f"{_SKIP_REASON}. Run 'bash scripts/provision_full_test_env.sh'.") + raise AssertionError(f"{_SKIP_REASON}. Run 'bash scripts/provision_full_test_env.sh'.") """Loads CSVs of varying shape into Postgres and verifies row counts.""" SHAPES = [ - ("tiny", 2, 3), + ("tiny", 2, 3), ("medium", 10, 50), - ("skinny", 1, 100), + ("skinny", 1, 100), ] def _run_loader_and_count(self, n_cols: int, n_rows: int, label: str) -> None: @@ -99,10 +99,13 @@ def _run_loader_and_count(self, n_cols: int, n_rows: int, label: str) -> None: load = subprocess.run( [_BASH, str(LOADER), str(csv_path), "--env", "dev"], - capture_output=True, text=True, cwd=ROOT, + capture_output=True, + text=True, + cwd=ROOT, ) self.assertEqual( - load.returncode, 0, + load.returncode, + 0, f"Loader failed for {label}: stdout={load.stdout[-500:]} stderr={load.stderr[-500:]}", ) @@ -110,7 +113,9 @@ def _run_loader_and_count(self, n_cols: int, n_rows: int, label: str) -> None: # Verify via csv_utilise.sh describe (also asserts marker columns present). describe = subprocess.run( [_BASH, str(UTILISE), "describe", table, "--env", "dev"], - capture_output=True, text=True, cwd=ROOT, + capture_output=True, + text=True, + cwd=ROOT, ) self.assertEqual(describe.returncode, 0, describe.stderr) self.assertIn(f"Row count: {n_rows}", describe.stdout) @@ -118,7 +123,9 @@ def _run_loader_and_count(self, n_cols: int, n_rows: int, label: str) -> None: # Always drop the table — keep dev clean. subprocess.run( [_BASH, str(UTILISE), "drop", table, "--yes", "--env", "dev"], - capture_output=True, text=True, cwd=ROOT, + capture_output=True, + text=True, + cwd=ROOT, ) def test_shape_tiny(self): diff --git a/tests/system_integration/test_e2e_pipeline.py b/tests/system_integration/test_e2e_pipeline.py index d6fd899..d58c006 100644 --- a/tests/system_integration/test_e2e_pipeline.py +++ b/tests/system_integration/test_e2e_pipeline.py @@ -7,6 +7,7 @@ Mirrors gstack's skill-e2e-*.test.ts pattern: tests exercise the full user-facing workflow, not just individual functions. """ + import os import shutil import subprocess @@ -19,9 +20,9 @@ pytestmark = pytest.mark.e2e -ROOT = Path(__file__).resolve().parents[2] +ROOT = Path(__file__).resolve().parents[2] VALIDATOR = ROOT / "build" / "csv" / "validator.py" -RUNNER = ROOT / "evals" / "runner.py" +RUNNER = ROOT / "evals" / "runner.py" def _can_connect_pg() -> bool: @@ -30,7 +31,9 @@ def _can_connect_pg() -> bool: try: r = subprocess.run( ["psql", "-tA", "-c", "SELECT 1"], - capture_output=True, text=True, timeout=5, + capture_output=True, + text=True, + timeout=5, env={**os.environ, "PGUSER": os.environ.get("PGUSER", "postgres")}, ) return r.returncode == 0 @@ -43,15 +46,14 @@ def _can_connect_pg() -> bool: # The concrete env launchers are gitignored (only env_dev.example.sql is # committed), so a fresh clone has no env_dev.sql. Tier I/S deploys require it, # so treat its absence the same way we treat an unreachable database: skip. -_ENV_DEV_SQL = ROOT / "build" / "environments" / "env_dev.sql" -_DB_E2E_READY = _PG_AVAILABLE and _ENV_DEV_SQL.exists() -HELP = ("Run 'bash scripts/provision_full_test_env.sh' (needs a reachable " - "PostgreSQL and PGUSER/PGHOST/PGPORT set).") -_SKIP_REASON = ( +_ENV_DEV_SQL = ROOT / "build" / "environments" / "env_dev.sql" +_DB_E2E_READY = _PG_AVAILABLE and _ENV_DEV_SQL.exists() +HELP = "Run 'bash scripts/provision_full_test_env.sh' (needs a reachable PostgreSQL and PGUSER/PGHOST/PGPORT set)." +_SKIP_REASON = ( "PostgreSQL not reachable — skipping DB-dependent E2E tests" if not _PG_AVAILABLE else "build/environments/env_dev.sql not present (create it from " - "env_dev.example.sql) — skipping DB-dependent E2E tests" + "env_dev.example.sql) — skipping DB-dependent E2E tests" ) @@ -62,25 +64,30 @@ def test_happy_path_two_valid_rows(self): """Standard 2-column CSV with 2 valid rows produces correct outputs.""" with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) - csv_file = tmp_path / "input.csv" + csv_file = tmp_path / "input.csv" valid_csv = tmp_path / "valid.csv" - skip_csv = tmp_path / "skip.csv" + skip_csv = tmp_path / "skip.csv" csv_file.write_text("id,name\n1,Alice\n2,Bob\n", encoding="utf-8") - env = {**os.environ, - "CSV_FILE": str(csv_file), - "VALID_CSV": str(valid_csv), - "SKIP_FILE": str(skip_csv), - "TABLE_NAME": "people"} + env = { + **os.environ, + "CSV_FILE": str(csv_file), + "VALID_CSV": str(valid_csv), + "SKIP_FILE": str(skip_csv), + "TABLE_NAME": "people", + } r = subprocess.run( [sys.executable, str(VALIDATOR)], - env=env, capture_output=True, text=True, - encoding="utf-8", errors="replace", + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", ) self.assertEqual(r.returncode, 0, r.stderr) valid_lines = valid_csv.read_text(encoding="utf-8").strip().splitlines() self.assertEqual(valid_lines[0], "id,name") self.assertIn("1,Alice", valid_lines) - self.assertIn("2,Bob", valid_lines) + self.assertIn("2,Bob", valid_lines) # skip.csv should contain only the header (no skips) if skip_csv.exists(): skip_lines = [ln for ln in skip_csv.read_text(encoding="utf-8").splitlines() if ln.strip()] @@ -90,24 +97,29 @@ def test_mixed_rows_splits_correctly(self): """Mixed CSV produces separate valid and skip outputs.""" with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) - csv_file = tmp_path / "input.csv" + csv_file = tmp_path / "input.csv" valid_csv = tmp_path / "valid.csv" - skip_csv = tmp_path / "skip.csv" + skip_csv = tmp_path / "skip.csv" csv_file.write_text("id,name\n1,Alice\n\n2\n3,Bob\n", encoding="utf-8") - env = {**os.environ, - "CSV_FILE": str(csv_file), - "VALID_CSV": str(valid_csv), - "SKIP_FILE": str(skip_csv), - "TABLE_NAME": "people"} + env = { + **os.environ, + "CSV_FILE": str(csv_file), + "VALID_CSV": str(valid_csv), + "SKIP_FILE": str(skip_csv), + "TABLE_NAME": "people", + } r = subprocess.run( [sys.executable, str(VALIDATOR)], - env=env, capture_output=True, text=True, - encoding="utf-8", errors="replace", + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", ) self.assertEqual(r.returncode, 0, r.stderr) valid_lines = valid_csv.read_text(encoding="utf-8").strip().splitlines() self.assertIn("1,Alice", valid_lines) - self.assertIn("3,Bob", valid_lines) + self.assertIn("3,Bob", valid_lines) skip_lines = skip_csv.read_text(encoding="utf-8").strip().splitlines() # header + 2 bad rows self.assertEqual(len(skip_lines), 3) @@ -116,19 +128,24 @@ def test_all_invalid_rows_exit_nonzero(self): """A CSV where every data row fails validation must exit 1.""" with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) - csv_file = tmp_path / "input.csv" + csv_file = tmp_path / "input.csv" valid_csv = tmp_path / "valid.csv" - skip_csv = tmp_path / "skip.csv" + skip_csv = tmp_path / "skip.csv" csv_file.write_text("id,name\n\n2\n", encoding="utf-8") - env = {**os.environ, - "CSV_FILE": str(csv_file), - "VALID_CSV": str(valid_csv), - "SKIP_FILE": str(skip_csv), - "TABLE_NAME": "people"} + env = { + **os.environ, + "CSV_FILE": str(csv_file), + "VALID_CSV": str(valid_csv), + "SKIP_FILE": str(skip_csv), + "TABLE_NAME": "people", + } r = subprocess.run( [sys.executable, str(VALIDATOR)], - env=env, capture_output=True, text=True, - encoding="utf-8", errors="replace", + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", ) self.assertEqual(r.returncode, 1) self.assertIn("No valid rows", r.stderr) @@ -137,20 +154,25 @@ def test_output_directory_is_created_automatically(self): """Validator must create the output directory if it does not exist.""" with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) - csv_file = tmp_path / "input.csv" - out_dir = tmp_path / "nested" / "out" + csv_file = tmp_path / "input.csv" + out_dir = tmp_path / "nested" / "out" valid_csv = out_dir / "valid.csv" - skip_csv = out_dir / "skip.csv" + skip_csv = out_dir / "skip.csv" csv_file.write_text("id,name\n1,Alice\n", encoding="utf-8") - env = {**os.environ, - "CSV_FILE": str(csv_file), - "VALID_CSV": str(valid_csv), - "SKIP_FILE": str(skip_csv), - "TABLE_NAME": "people"} + env = { + **os.environ, + "CSV_FILE": str(csv_file), + "VALID_CSV": str(valid_csv), + "SKIP_FILE": str(skip_csv), + "TABLE_NAME": "people", + } r = subprocess.run( [sys.executable, str(VALIDATOR)], - env=env, capture_output=True, text=True, - encoding="utf-8", errors="replace", + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", ) # Either succeeds and created the dir, or fails with a clear message if r.returncode == 0: @@ -173,19 +195,21 @@ def test_tier_p_scenarios_all_pass(self): """All Tier P eval scenarios must pass when the runner is executed end-to-end.""" r = subprocess.run( [sys.executable, str(RUNNER), "--tiers", "p"], - capture_output=True, text=True, cwd=ROOT, + capture_output=True, + text=True, + cwd=ROOT, ) - self.assertEqual(r.returncode, 0, - f"Tier P eval run failed:\n{r.stdout[-2000:]}\n{r.stderr[-500:]}") + self.assertEqual(r.returncode, 0, f"Tier P eval run failed:\n{r.stdout[-2000:]}\n{r.stderr[-500:]}") def test_tier_i_idempotency(self): """Tier I (idempotency) scenarios must pass against the running PostgreSQL.""" r = subprocess.run( [sys.executable, str(RUNNER), "--tiers", "i"], - capture_output=True, text=True, cwd=ROOT, + capture_output=True, + text=True, + cwd=ROOT, ) - self.assertEqual(r.returncode, 0, - f"Tier I eval run failed:\n{r.stdout[-2000:]}\n{r.stderr[-500:]}") + self.assertEqual(r.returncode, 0, f"Tier I eval run failed:\n{r.stdout[-2000:]}\n{r.stderr[-500:]}") if __name__ == "__main__": diff --git a/tests/system_integration/test_parity.py b/tests/system_integration/test_parity.py index 55d7349..9a21f36 100644 --- a/tests/system_integration/test_parity.py +++ b/tests/system_integration/test_parity.py @@ -7,6 +7,7 @@ All tests skip automatically when PostgreSQL is not reachable. """ + import os import shutil import subprocess @@ -23,29 +24,38 @@ # Adjust these values if the seed SQL is intentionally changed. _DEV_MIN_COUNTS: dict[str, int] = { "organisations": 1, - "personnel": 1, + "personnel": 1, "test_programs": 1, - "test_phases": 1, - "requirements": 1, - "test_cases": 1, - "vcrm_entries": 1, - "test_events": 1, - "test_results": 1, + "test_phases": 1, + "requirements": 1, + "test_cases": 1, + "vcrm_entries": 1, + "test_events": 1, + "test_results": 1, "defect_reports": 1, } # Tables that must exist in every environment (not just dev) _REQUIRED_TABLES = [ - "organisations", "personnel", "test_programs", "temp_documents", - "test_phases", "requirements", "test_cases", "vcrm_entries", - "test_events", "test_results", "defect_reports", "evidence_artifacts", + "organisations", + "personnel", + "test_programs", + "temp_documents", + "test_phases", + "requirements", + "test_cases", + "vcrm_entries", + "test_events", + "test_results", + "defect_reports", + "evidence_artifacts", ] _ENV_CONFIG = { - "dev": ("te_mgmt_dev", "te_dev"), - "test": ("te_mgmt_test", "te_test"), + "dev": ("te_mgmt_dev", "te_dev"), + "test": ("te_mgmt_test", "te_test"), "staging": ("te_mgmt_staging", "te_staging"), - "prod": ("te_mgmt_prod", "te_prod"), + "prod": ("te_mgmt_prod", "te_prod"), } @@ -65,7 +75,10 @@ def _can_connect() -> bool: try: r = subprocess.run( ["psql", "-tA", "-c", "SELECT 1"], - env=_pg_env(), capture_output=True, text=True, timeout=5, + env=_pg_env(), + capture_output=True, + text=True, + timeout=5, ) return r.returncode == 0 except (subprocess.TimeoutExpired, FileNotFoundError): @@ -76,7 +89,10 @@ def _count_rows(db: str, schema: str, table: str) -> int | None: query = f'SELECT count(*) FROM {schema}."{table}";' r = subprocess.run( ["psql", "-tA", "-d", db, "-c", query], - env=_pg_env(), capture_output=True, text=True, timeout=10, + env=_pg_env(), + capture_output=True, + text=True, + timeout=10, ) if r.returncode == 0 and r.stdout.strip().isdigit(): return int(r.stdout.strip()) @@ -84,13 +100,13 @@ def _count_rows(db: str, schema: str, table: str) -> int | None: def _table_exists(db: str, schema: str, table: str) -> bool: - query = ( - f"SELECT 1 FROM information_schema.tables " - f"WHERE table_schema='{schema}' AND table_name='{table}';" - ) + query = f"SELECT 1 FROM information_schema.tables WHERE table_schema='{schema}' AND table_name='{table}';" r = subprocess.run( ["psql", "-tA", "-d", db, "-c", query], - env=_pg_env(), capture_output=True, text=True, timeout=10, + env=_pg_env(), + capture_output=True, + text=True, + timeout=10, ) return r.returncode == 0 and r.stdout.strip() == "1" @@ -101,9 +117,11 @@ def _db_deployed(db: str) -> bool: return False try: r = subprocess.run( - ["psql", "-tA", "-c", - f"SELECT 1 FROM pg_database WHERE datname = '{db}'"], - env=_pg_env(), capture_output=True, text=True, timeout=5, + ["psql", "-tA", "-c", f"SELECT 1 FROM pg_database WHERE datname = '{db}'"], + env=_pg_env(), + capture_output=True, + text=True, + timeout=5, ) return r.returncode == 0 and r.stdout.strip() == "1" except (subprocess.TimeoutExpired, FileNotFoundError): @@ -115,8 +133,7 @@ def _db_deployed(db: str) -> bool: # environment must also have been deployed (deploy_all.sh). A fresh clone has # a running server but no te_mgmt_* databases; skip rather than fail. _DEV_DEPLOYED = _db_deployed(_ENV_CONFIG["dev"][0]) -_HELP = ("Run 'bash scripts/provision_full_test_env.sh' (needs a reachable " - "PostgreSQL and PGUSER/PGHOST/PGPORT set).") +_HELP = "Run 'bash scripts/provision_full_test_env.sh' (needs a reachable PostgreSQL and PGUSER/PGHOST/PGPORT set)." def _require_pg(): @@ -143,9 +160,7 @@ def test_dev_seed_row_counts(self): if count is None: failures.append(f" {schema}.{table}: could not query (table may not exist)") elif count < min_count: - failures.append( - f" {schema}.{table}: expected >= {min_count} rows, got {count}" - ) + failures.append(f" {schema}.{table}: expected >= {min_count} rows, got {count}") if failures: self.fail("Dev seed row count failures:\n" + "\n".join(failures)) @@ -159,19 +174,18 @@ def _check_env(self, env_name: str) -> None: # Skip if this database doesn't exist at all r = subprocess.run( ["psql", "-tA", "-d", db, "-c", "SELECT 1"], - env=_pg_env(), capture_output=True, text=True, timeout=5, + env=_pg_env(), + capture_output=True, + text=True, + timeout=5, ) if r.returncode != 0: self.fail(f"Database {db!r} not deployed. {_HELP}") - missing = [ - t for t in _REQUIRED_TABLES - if not _table_exists(db, schema, t) - ] + missing = [t for t in _REQUIRED_TABLES if not _table_exists(db, schema, t)] if missing: self.fail( - f"Environment {env_name!r} ({db}/{schema}) is missing tables:\n" - + "\n".join(f" {t}" for t in missing) + f"Environment {env_name!r} ({db}/{schema}) is missing tables:\n" + "\n".join(f" {t}" for t in missing) ) def test_dev_has_required_tables(self): @@ -194,6 +208,7 @@ class TestNoSeedInStagingAndProd(unittest.TestCase): include_seed_data flipped to true, which would silently push test data into production. See GitHub Issue #23. """ + setUpClass = classmethod(lambda cls: _require_pg()) _SEEDED_TABLES = list(_DEV_MIN_COUNTS.keys()) @@ -243,7 +258,10 @@ def _snapshot() -> dict[str, int | None]: r = subprocess.run( ["psql", "-f", str(env_sql)], - env=_pg_env(), capture_output=True, text=True, timeout=180, + env=_pg_env(), + capture_output=True, + text=True, + timeout=180, ) if r.returncode != 0: self.fail(f"Second deploy failed:\n{r.stderr[-500:]}") diff --git a/tests/unit/streamlit_harness.py b/tests/unit/streamlit_harness.py index 6401c03..2669d21 100644 --- a/tests/unit/streamlit_harness.py +++ b/tests/unit/streamlit_harness.py @@ -3,6 +3,7 @@ AppTest cannot switch to a page registered with st.navigation, so a screen is run by itself, as app.py runs it: only for someone signed in, so a 401 that ends the session ends the run cleanly instead of failing. """ + import sys from datetime import datetime, timedelta, timezone from pathlib import Path @@ -33,8 +34,13 @@ def later(hours: float = 8) -> str: def screen(view: str, who: str = "rita", token: str = "tok-1", tenant: str = "acme", timeout: int = 30) -> AppTest: """One screen (the module name in streamlit_app/views) with a session already in place, run once.""" at = AppTest.from_string(HARNESS.format(app_dir=str(APP_DIR), view=view), default_timeout=timeout) - at.session_state["session"] = {"token": token, "expiresAt": later(), "username": who, "tenant": tenant, - "role": ROLES[who]} + at.session_state["session"] = { + "token": token, + "expiresAt": later(), + "username": who, + "tenant": tenant, + "role": ROLES[who], + } at.run() assert not at.exception, at.exception return at diff --git a/tests/unit/test_a11y_baseline.py b/tests/unit/test_a11y_baseline.py index a3be4a5..d5242c1 100644 --- a/tests/unit/test_a11y_baseline.py +++ b/tests/unit/test_a11y_baseline.py @@ -3,6 +3,7 @@ No browser: tests/accessibility/axe_baseline.py is pure. The scans themselves are in tests/accessibility/test_accessibility.py and run only in the accessibility CI job. """ + from __future__ import annotations import json @@ -18,8 +19,13 @@ def _violation(rule: str, count: int, impact: str = "serious") -> dict: - return {"id": rule, "impact": impact, "help": f"help for {rule}", "helpUrl": f"https://axe/{rule}", - "nodes": [{"target": [f".n{i}"], "html": f"x"} for i in range(count)]} + return { + "id": rule, + "impact": impact, + "help": f"help for {rule}", + "helpUrl": f"https://axe/{rule}", + "nodes": [{"target": [f".n{i}"], "html": f"x"} for i in range(count)], + } def _entry(scenario: str, rule: str, nodes: int, note: str = "known") -> dict: diff --git a/tests/unit/test_api_hardening.py b/tests/unit/test_api_hardening.py index a1fb80b..7bb106f 100644 --- a/tests/unit/test_api_hardening.py +++ b/tests/unit/test_api_hardening.py @@ -110,6 +110,7 @@ def test_clients_are_independent(self): def test_bucket_table_is_bounded(self): # A spray of spoofed identities must not grow memory without limit. from api.ratelimit import _MAX_TRACKED_CLIENTS + for i in range(_MAX_TRACKED_CLIENTS + 250): self.lim.check(f"client-{i}", "read", 5, 60.0, now=100.0) self.assertLessEqual(len(self.lim._buckets), _MAX_TRACKED_CLIENTS) @@ -135,8 +136,7 @@ def setUp(self): ) def tearDown(self): - (settings.RATE_LIMIT_READS_PER_MINUTE, - settings.RATE_LIMIT_WRITES_PER_MINUTE) = self._saved + (settings.RATE_LIMIT_READS_PER_MINUTE, settings.RATE_LIMIT_WRITES_PER_MINUTE) = self._saved limiter.reset() def test_exceeding_the_write_budget_returns_429_with_retry_after(self): @@ -167,19 +167,15 @@ def test_disabled_budget_allows_everything(self): settings.RATE_LIMIT_WRITES_PER_MINUTE = 0 payload = {"fileName": "x.csv", "content": "a,b\n1,2\n"} for _ in range(25): - self.assertNotEqual( - client.post("/api/csv/preview", json=payload).status_code, 429 - ) + self.assertNotEqual(client.post("/api/csv/preview", json=payload).status_code, 429) def test_forwarded_for_cannot_be_used_to_evade_the_limit(self): settings.RATE_LIMIT_WRITES_PER_MINUTE = 2 payload = {"fileName": "x.csv", "content": "a,b\n1,2\n"} for i in range(2): - client.post("/api/csv/preview", json=payload, - headers={"X-Forwarded-For": f"10.0.0.{i}"}) + client.post("/api/csv/preview", json=payload, headers={"X-Forwarded-For": f"10.0.0.{i}"}) # A client-supplied header must not mint a fresh bucket on demand. - resp = client.post("/api/csv/preview", json=payload, - headers={"X-Forwarded-For": "10.0.0.99"}) + resp = client.post("/api/csv/preview", json=payload, headers={"X-Forwarded-For": "10.0.0.99"}) self.assertEqual(resp.status_code, 429) @@ -188,8 +184,20 @@ class AuditWriterContract(unittest.TestCase): """O-04: the shared audit writer's guardrails, without touching a database.""" def test_only_known_actions_are_accepted(self): - self.assertEqual(VALID_ACTIONS, {"upload", "delete", "password_reset", "row_decision", "cell_edit", - "submit", "approve", "reject", "import"}) + self.assertEqual( + VALID_ACTIONS, + { + "upload", + "delete", + "password_reset", + "row_decision", + "cell_edit", + "submit", + "approve", + "reject", + "import", + }, + ) def test_unknown_action_raises_before_any_sql_runs(self): class ExplodingCursor: @@ -207,8 +215,7 @@ def execute(self, statement, params=None): captured["params"] = params write_audit(RecordingCursor(), "upload", 7, "f.csv", "csv_abc", "dynamic") - self.assertEqual(captured["params"], - ("upload", 7, "f.csv", "csv_abc", "dynamic", None, None, None)) + self.assertEqual(captured["params"], ("upload", 7, "f.csv", "csv_abc", "dynamic", None, None, None)) def test_file_id_is_coerced_from_the_loaders_string_form(self): self.assertEqual(coerce_file_id("42"), 42) diff --git a/tests/unit/test_api_key_not_logged.py b/tests/unit/test_api_key_not_logged.py index c4b4214..9f3df8f 100644 --- a/tests/unit/test_api_key_not_logged.py +++ b/tests/unit/test_api_key_not_logged.py @@ -8,6 +8,7 @@ Asserted by running the real ``lifespan``. No database is needed: the pool and bootstrap are replaced. """ + from __future__ import annotations import asyncio @@ -52,8 +53,9 @@ def test_a_leftover_key_is_reported_as_unused(monkeypatch, caplog): def test_no_part_of_a_leftover_key_is_in_the_startup_log(monkeypatch, caplog): logged = run_startup(monkeypatch, caplog, key=KEY) - leaked = [KEY[i:i + n] for n in range(4, len(KEY) + 1) for i in range(len(KEY) - n + 1) - if KEY[i:i + n] in logged] + leaked = [ + KEY[i : i + n] for n in range(4, len(KEY) + 1) for i in range(len(KEY) - n + 1) if KEY[i : i + n] in logged + ] assert leaked == [], f"parts of the key are in the log: {leaked[:5]}" @@ -63,7 +65,9 @@ def test_no_key_no_key_message(monkeypatch, caplog): def test_anonymous_access_is_announced_loudly(monkeypatch, caplog): run_startup(monkeypatch, caplog, anonymous=True) - warnings = [r for r in caplog.records if r.levelno >= logging.WARNING and "ANONYMOUS ACCESS IS ON" in r.getMessage()] + warnings = [ + r for r in caplog.records if r.levelno >= logging.WARNING and "ANONYMOUS ACCESS IS ON" in r.getMessage() + ] assert warnings, "the opt-in must produce a WARNING at start-up" diff --git a/tests/unit/test_api_unit.py b/tests/unit/test_api_unit.py index ca33159..ad850d5 100644 --- a/tests/unit/test_api_unit.py +++ b/tests/unit/test_api_unit.py @@ -1,6 +1,7 @@ """API unit tests — no database required. Database-backed tests live in test_api_integration.py. """ + from __future__ import annotations import unittest @@ -12,11 +13,13 @@ client = TestClient(app) -_HELP = ("Start PostgreSQL and ensure api/ can reach it. Most often this means " - "PGPASSWORD is not set in this shell:\n" - " PowerShell: $env:PGPASSWORD = ''\n" - " bash: export PGPASSWORD=''\n" - "Defaults come from api/config.py; see scripts/start-api.ps1.") +_HELP = ( + "Start PostgreSQL and ensure api/ can reach it. Most often this means " + "PGPASSWORD is not set in this shell:\n" + " PowerShell: $env:PGPASSWORD = ''\n" + " bash: export PGPASSWORD=''\n" + "Defaults come from api/config.py; see scripts/start-api.ps1." +) SMALL_CSV = "col_a,col_b\n1,2\n3,4\n" @@ -44,8 +47,7 @@ def test_sanitize_columns_no_collision_on_stem_conflict(self): from api.services.csv_parse import sanitize_columns out = sanitize_columns(["foo", "foo", "foo_2"]) - self.assertEqual(len(out), len(set(out)), - f"BUG-036 regression: collision in {out}") + self.assertEqual(len(out), len(set(out)), f"BUG-036 regression: collision in {out}") # First occurrence keeps its name; later ones get bumped past # anything already assigned. self.assertEqual(out[0], "foo") @@ -98,26 +100,23 @@ def test_preview_rejects_empty_content(self): self.assertEqual(r.status_code, 422) def test_preview_rejects_overlong_filename(self): - r = client.post("/api/csv/preview", - json={"fileName": "x" * 256, "content": SMALL_CSV}) + r = client.post("/api/csv/preview", json={"fileName": "x" * 256, "content": SMALL_CSV}) self.assertEqual(r.status_code, 422) def test_upload_rejects_unknown_mode(self): - r = client.post("/api/csv/upload", json={ - "fileName": "a.csv", "content": SMALL_CSV, "mode": "sideways"}) + r = client.post("/api/csv/upload", json={"fileName": "a.csv", "content": SMALL_CSV, "mode": "sideways"}) self.assertEqual(r.status_code, 422) def test_upload_te_mode_requires_target_table(self): - r = client.post("/api/csv/upload", json={ - "fileName": "a.csv", "content": SMALL_CSV, "mode": "te"}) + r = client.post("/api/csv/upload", json={"fileName": "a.csv", "content": SMALL_CSV, "mode": "te"}) self.assertEqual(r.status_code, 422) self.assertIn("targetTable", r.text) def test_oversized_upload_is_rejected(self): from api.config import settings + oversized = "x" * (settings.MAX_UPLOAD_BYTES + 1) - r = client.post("/api/csv/preview", - json={"fileName": "big.csv", "content": oversized}) + r = client.post("/api/csv/preview", json={"fileName": "big.csv", "content": oversized}) self.assertEqual(r.status_code, 413) @@ -130,8 +129,7 @@ def test_non_upload_tables_are_rejected(self): for name in ("organisations", "personnel", "pg_catalog", "users"): with self.subTest(table=name): r = client.get(f"/api/csv/tables/{name}/rows") - self.assertEqual(r.status_code, 422, - f"non-upload table accepted: {name}") + self.assertEqual(r.status_code, 422, f"non-upload table accepted: {name}") def test_overlong_names_are_rejected(self): r = client.get(f"/api/csv/tables/csv_{'x' * 70}/rows") @@ -165,5 +163,4 @@ def test_identifiers_are_never_string_formatted(self): is_execute = isinstance(func, ast.Attribute) and func.attr == "execute" if is_execute and node.args and isinstance(node.args[0], ast.JoinedStr): offenders.append(f"{path.name}:{node.lineno}") - self.assertEqual(offenders, [], - f"execute() called with an f-string at {offenders}") + self.assertEqual(offenders, [], f"execute() called with an f-string at {offenders}") diff --git a/tests/unit/test_body_limit.py b/tests/unit/test_body_limit.py index ecd7216..3c6d4e7 100644 --- a/tests/unit/test_body_limit.py +++ b/tests/unit/test_body_limit.py @@ -14,6 +14,7 @@ The middleware is driven directly at the ASGI level, so what it read and what the handler saw can be asserted, and then through the real app, where the CORS headers and the route's own answer matter. No database is needed. """ + from __future__ import annotations import asyncio @@ -28,8 +29,8 @@ pytestmark = [pytest.mark.unit, pytest.mark.regression, pytest.mark.security] -MAX_UPLOAD = 1000 # patched in, so the tests send kilobytes, not hundreds of megabytes -CAP = 2 * MAX_UPLOAD - 1 # the largest body let through +MAX_UPLOAD = 1000 # patched in, so the tests send kilobytes, not hundreds of megabytes +CAP = 2 * MAX_UPLOAD - 1 # the largest body let through @pytest.fixture(autouse=True) @@ -41,9 +42,9 @@ class Run: """The outcome of one request driven through the middleware.""" def __init__(self): - self.entered = False # the handler behind the middleware was called - self.handler_read = 0 # bytes the handler got to read - self.chunks_taken = 0 # chunks pulled from the client + self.entered = False # the handler behind the middleware was called + self.handler_read = 0 # bytes the handler got to read + self.chunks_taken = 0 # chunks pulled from the client self.sent: list[dict] = [] # everything the middleware sent to the client @property @@ -61,8 +62,13 @@ def body(self) -> dict: return json.loads(data) if data else {} -def drive(chunks: list[bytes], *, content_length: int | None = None, scope_type: str = "http", - raw_content_length: bytes | None = None) -> Run: +def drive( + chunks: list[bytes], + *, + content_length: int | None = None, + scope_type: str = "http", + raw_content_length: bytes | None = None, +) -> Run: run = Run() queue = list(chunks) @@ -71,7 +77,7 @@ async def inner(scope, receive, send): while True: message = await receive() if message["type"] == "http.disconnect": - raise RuntimeError("client went away") # what a real handler does when told the client left + raise RuntimeError("client went away") # what a real handler does when told the client left run.handler_read += len(message.get("body", b"")) if not message.get("more_body"): break @@ -102,14 +108,17 @@ def chunks_of(total: int, size: int = 400) -> list[bytes]: # -- the cap --------------------------------------------------------------------------------------------------------- + def test_the_cap_is_just_under_twice_the_file_limit(): assert max_body_bytes() == CAP - assert 2 * MAX_UPLOAD > max_body_bytes() >= MAX_UPLOAD * 4 // 3, \ + assert 2 * MAX_UPLOAD > max_body_bytes() >= MAX_UPLOAD * 4 // 3, ( "a body of 2 x the limit is refused, but base64 of a full-size file must fit" + ) # -- Content-Length -------------------------------------------------------------------------------------------------- + def test_a_declared_length_over_the_cap_is_refused_without_reading_the_body(): run = drive(chunks_of(2 * MAX_UPLOAD), content_length=2 * MAX_UPLOAD) assert run.status == 413 and run.body == {"detail": "Request body too large"}, run.sent @@ -124,8 +133,9 @@ def test_a_declared_length_at_the_cap_is_let_through(): # -- no Content-Length, or a wrong one ------------------------------------------------------------------------------ + def test_a_chunked_body_over_the_cap_is_refused_and_reading_stops(): - chunks = chunks_of(10 * MAX_UPLOAD) # 25 chunks, no Content-Length + chunks = chunks_of(10 * MAX_UPLOAD) # 25 chunks, no Content-Length run = drive(chunks) assert run.status == 413 and run.body == {"detail": "Request body too large"}, run.sent assert run.chunks_taken < len(chunks), "the whole body must not be pulled in" @@ -153,6 +163,7 @@ def test_an_unusable_content_length_is_ignored_and_the_body_is_counted(raw): # -- what it leaves alone -------------------------------------------------------------------------------------------- + def test_a_request_without_a_body_passes_through(): run = drive([]) assert run.status == 200 and run.handler_read == 0 @@ -172,16 +183,21 @@ async def inner(scope, receive, send): # -- through the real app -------------------------------------------------------------------------------------------- + def test_the_real_app_refuses_an_oversize_body_with_the_cors_headers_a_browser_needs(): client = TestClient(app) - res = client.post("/api/csv/upload", content=b"x" * (2 * MAX_UPLOAD), - headers={"Content-Type": "application/json", "Origin": "http://localhost:5173"}) + res = client.post( + "/api/csv/upload", + content=b"x" * (2 * MAX_UPLOAD), + headers={"Content-Type": "application/json", "Origin": "http://localhost:5173"}, + ) assert res.status_code == 413 and res.json() == {"detail": "Request body too large"}, res.text - assert res.headers.get("access-control-allow-origin") == "http://localhost:5173", \ + assert res.headers.get("access-control-allow-origin") == "http://localhost:5173", ( "without CORS headers the browser cannot read the 413" + ) def test_the_real_app_hands_a_body_within_the_cap_to_the_route(): client = TestClient(app) res = client.post("/api/csv/upload", content=b"{}", headers={"Content-Type": "application/json"}) - assert res.status_code != 413, res.text # it reached the route, which rejects the empty request itself + assert res.status_code != 413, res.text # it reached the route, which rejects the empty request itself diff --git a/tests/unit/test_bootstrap_requires_migrations.py b/tests/unit/test_bootstrap_requires_migrations.py index 6ceae62..c3c2a7e 100644 --- a/tests/unit/test_bootstrap_requires_migrations.py +++ b/tests/unit/test_bootstrap_requires_migrations.py @@ -11,6 +11,7 @@ No database is needed: the fallback and the pool are replaced. """ + from __future__ import annotations import asyncio diff --git a/tests/unit/test_ci_parallel_jobs.py b/tests/unit/test_ci_parallel_jobs.py index 2c11232..38b6723 100644 --- a/tests/unit/test_ci_parallel_jobs.py +++ b/tests/unit/test_ci_parallel_jobs.py @@ -17,6 +17,7 @@ the egress steps are intact, the check keeps its name, a push to ``main`` always runs everything, and a newer push to a pull request cancels the older run. """ + from __future__ import annotations import subprocess @@ -42,6 +43,7 @@ # -- scripts/ci_changes.py: when may the database jobs be skipped? ----------------------------------------------------- + @pytest.fixture def tree(tmp_path): """A small repository: docs nothing reads, a doc a test reads, a doc a workflow names, code.""" @@ -65,12 +67,24 @@ def tree(tmp_path): def test_a_change_to_documents_nothing_reads_skips_the_database_jobs(tree): assert ci_changes.is_docs_only(["docs/audit/example_report.md"], tree) is True - assert ci_changes.is_docs_only(["docs/audit/example_report.md", "DECISIONS/2026-11-23-x.md", "docs/NOTES_EXAMPLE.md"], tree) is True + assert ( + ci_changes.is_docs_only( + ["docs/audit/example_report.md", "DECISIONS/2026-11-23-x.md", "docs/NOTES_EXAMPLE.md"], tree + ) + is True + ) def test_code_always_runs_everything(tree): - for path in ("api/main.py", "scripts/x.sh", "requirements-dev.txt", ".github/workflows/quality-gate.yml", - "tests/unit/test_x.py", "csv-table-hub-main/src/a.ts", "Makefile"): + for path in ( + "api/main.py", + "scripts/x.sh", + "requirements-dev.txt", + ".github/workflows/quality-gate.yml", + "tests/unit/test_x.py", + "csv-table-hub-main/src/a.ts", + "Makefile", + ): assert ci_changes.is_docs_only([path], tree) is False, path @@ -124,8 +138,13 @@ def test_any_other_event_or_no_files_runs_everything(tree): def test_the_real_repository_runs_everything_for_its_own_ci_files(): - for path in ("scripts/ci_changes.py", "scripts/ci_gate.py", "scripts/ci_shards.py", "ci/shard_weights.json", - ".github/workflows/quality-gate.yml"): + for path in ( + "scripts/ci_changes.py", + "scripts/ci_gate.py", + "scripts/ci_shards.py", + "ci/shard_weights.json", + ".github/workflows/quality-gate.yml", + ): assert ci_changes.is_docs_only([path], ROOT) is False, path @@ -137,6 +156,7 @@ def test_the_real_documents_the_tests_read_are_not_skippable(): # -- scripts/ci_gate.py: one verdict from the jobs' results ------------------------------------------------------------- + def gate(changed: str, **results: str) -> int: return ci_gate.verdict(changed, results)[0] @@ -183,15 +203,22 @@ def test_the_message_names_every_job_and_what_happened(): def test_the_cli_exits_with_the_verdict(): - ok = subprocess.run([sys.executable, str(ROOT / "scripts" / "ci_gate.py"), "true", "shards=success", "coverage=success"], - capture_output=True, text=True) - bad = subprocess.run([sys.executable, str(ROOT / "scripts" / "ci_gate.py"), "true", "shards=success", "coverage=failure"], - capture_output=True, text=True) + ok = subprocess.run( + [sys.executable, str(ROOT / "scripts" / "ci_gate.py"), "true", "shards=success", "coverage=success"], + capture_output=True, + text=True, + ) + bad = subprocess.run( + [sys.executable, str(ROOT / "scripts" / "ci_gate.py"), "true", "shards=success", "coverage=failure"], + capture_output=True, + text=True, + ) assert (ok.returncode, bad.returncode) == (0, 1), (ok.stdout, bad.stdout) # -- the workflow -------------------------------------------------------------------------------------------------------- + def load() -> dict: return yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) @@ -212,7 +239,8 @@ def test_the_parallel_jobs_exist_and_the_check_keeps_its_name(): for job_id in ("changes", "free-tier", *HEAVY, "integration-postgres", "accessibility", "browser"): assert job_id in j, job_id assert j["integration-postgres"]["name"] == "integration (postgres service)", ( - "the aggregate check keeps the name the owner's branch protection would require") + "the aggregate check keeps the name the owner's branch protection would require" + ) def test_the_heavy_jobs_wait_for_the_changes_job_and_skip_for_documentation_only(): @@ -279,9 +307,14 @@ def test_each_shard_measures_coverage_and_hands_its_data_to_the_coverage_job(): assert f"--cov={scope}" in opts, scope assert "--cov-branch" in opts and "--cov-report=" in opts assert "coverage-shard-${{ matrix.shard }}.dat" in step["run"] or any( - "coverage-shard-${{ matrix.shard }}.dat" in (s.get("run") or "") for s in job["steps"]) - uploads = [s for s in job["steps"] if "upload-artifact" in (s.get("uses") or "") and - "coverage-shard-${{ matrix.shard }}" in str((s.get("with") or {}).get("name", ""))] + "coverage-shard-${{ matrix.shard }}.dat" in (s.get("run") or "") for s in job["steps"] + ) + uploads = [ + s + for s in job["steps"] + if "upload-artifact" in (s.get("uses") or "") + and "coverage-shard-${{ matrix.shard }}" in str((s.get("with") or {}).get("name", "")) + ] assert len(uploads) == 1, "each shard uploads its own coverage data under a name that is unique per shard" assert "coverage-shard-${{ matrix.shard }}.dat" in str(uploads[0]["with"]["path"]) @@ -293,7 +326,8 @@ def test_the_coverage_job_combines_the_shards_and_applies_the_floors_and_needs_n assert {"changes", "integration-shards"} <= set(needs) assert "needs.changes.outputs.code == 'true'" in str(job.get("if")) assert "needs.integration-shards.result == 'success'" in str(job.get("if")), ( - "no coverage verdict from a run in which a shard failed") + "no coverage verdict from a run in which a shard failed" + ) download = next(s for s in job["steps"] if "download-artifact" in (s.get("uses") or "")) assert "coverage-shard-*" in str(download["with"].get("pattern")) assert download["with"].get("merge-multiple") in (True, "true") @@ -309,15 +343,20 @@ def test_the_egress_pass_is_sharded_and_keeps_its_firewall_steps(): assert job["strategy"]["matrix"]["shard"] == list(range(1, ci_shards.EGRESS_SHARDS + 1)) assert job["strategy"].get("fail-fast") is False text = run_text(job) - for needed in ("egress_firewall.sh install egresstest", "egress_firewall.sh check", "--block-egress", - "egress_firewall.sh remove"): + for needed in ( + "egress_firewall.sh install egresstest", + "egress_firewall.sh check", + "--block-egress", + "egress_firewall.sh remove", + ): assert needed in text, needed assert "test_report.py" not in text, "the egress job does not re-run the whole suite on the open network" assert "ci_shards.py files --shard ${{ matrix.shard }}" in text assert f"--of {ci_shards.EGRESS_SHARDS}" in text and "--only tests/system/" in text uploads = [s for s in job["steps"] if "upload-artifact" in (s.get("uses") or "")] assert uploads and all("${{ matrix.shard }}" in str(s["with"]["name"]) for s in uploads), ( - "artifact names must be unique per shard or the uploads collide") + "artifact names must be unique per shard or the uploads collide" + ) def test_the_egress_shards_hold_every_system_test_file_once(): @@ -353,12 +392,14 @@ def test_the_triggers_are_unchanged_and_nothing_is_skipped_by_path_at_the_workfl on = wf.get("on") if "on" in wf else wf[True] assert set(on) == {"push", "pull_request"} assert "paths-ignore" not in str(on) and "paths" not in (on.get("pull_request") or {}), ( - "a workflow-level path filter would leave the required check pending forever; the changes job decides instead") + "a workflow-level path filter would leave the required check pending forever; the changes job decides instead" + ) assert on["push"]["branches"] == ["main", "master"] # -- the sample documents must not be real ones ------------------------------------------------------------------------- + def test_the_sample_documents_in_the_fixture_are_not_real_documents_of_this_repository(tree): """A test file naming a real document makes that document count as 'read by a test', so a change to it could never skip the database jobs (found the first time the real audit report was changed on its own). The fixture's documents @@ -371,4 +412,6 @@ def test_the_sample_documents_in_the_fixture_are_not_real_documents_of_this_repo real_report = "2026" + "1123.md" assert not (tree / "docs" / "audit" / real_report).exists(), "the fixture must not use the real report's name" assert not (tree / "docs" / ("NOTES" + ".md")).exists() - assert (real_root / "docs" / "audit" / real_report).is_file(), "the real report this guard protects was renamed: update it" + assert (real_root / "docs" / "audit" / real_report).is_file(), ( + "the real report this guard protects was renamed: update it" + ) diff --git a/tests/unit/test_ci_quality_gate.py b/tests/unit/test_ci_quality_gate.py index 1538c7e..44a1302 100644 --- a/tests/unit/test_ci_quality_gate.py +++ b/tests/unit/test_ci_quality_gate.py @@ -4,6 +4,7 @@ configuration. Catches accidental removals or misconfigurations before they reach CI. No database or network required. """ + import re import sys import unittest @@ -120,7 +121,7 @@ def _run_text(self, job_id: str) -> str: def test_has_accessibility_job_that_runs_only_the_accessibility_marker(self): self.assertIn("accessibility", self.jobs) - self.assertIn('--markers accessibility', self._run_text("accessibility")) + self.assertIn("--markers accessibility", self._run_text("accessibility")) def test_accessibility_job_installs_a_browser_and_the_frontend(self): text = self._run_text("accessibility") @@ -142,6 +143,7 @@ class TestGapAnalysisG2Accepted(unittest.TestCase): """G2 is accepted as out-of-scope, not closed. Checks the decision is recorded in docs/GAP_ANALYSIS.md. """ + @classmethod def setUpClass(cls): if not GAP_ANALYSIS.exists(): @@ -157,8 +159,7 @@ def test_g2_is_accepted_or_deferred(self): if "| G2 |" in line: lower = line.lower() self.assertTrue( - "accept" in lower or "defer" in lower, - f"G2 row should be accepted/deferred, got: {line.strip()}" + "accept" in lower or "defer" in lower, f"G2 row should be accepted/deferred, got: {line.strip()}" ) return self.fail("G2 row not found in docs/GAP_ANALYSIS.md") @@ -168,9 +169,7 @@ def test_g2_section_exists(self): def test_g2_is_not_marked_closed(self): self.assertNotIn( - "G2 — Windows CI cannot host PostgreSQL (Closed)", - self.content, - "G2 should not say Closed — it is Accepted" + "G2 — Windows CI cannot host PostgreSQL (Closed)", self.content, "G2 should not say Closed — it is Accepted" ) @@ -195,7 +194,7 @@ def keeps_status(run: str, step: dict, job: dict) -> bool: return "pipefail" in run or shell == "bash" def test_the_detector_reads_continuations_and_ignores_or(self): - piped = 'python -m pytest tests/ \\\n --cov=x \\\n -q 2>&1 | tail -20\npython3 check.py' + piped = "python -m pytest tests/ \\\n --cov=x \\\n -q 2>&1 | tail -20\npython3 check.py" self.assertTrue(self.pipes_pytest(piped)) self.assertFalse(self.pipes_pytest("python -m pytest tests/ -q || true")) self.assertFalse(self.pipes_pytest("python3 scripts/test_report.py --markers x --strict")) @@ -320,8 +319,11 @@ def test_it_has_what_the_tests_need(self): def test_no_other_job_runs_the_browser_tests(self): for job_id in self.jobs: if job_id != "browser": - self.assertNotIn("e2e", self._run_text(job_id).replace("e2e/", "").replace("Tier E", ""), - f"job {job_id!r} runs the browser tests") + self.assertNotIn( + "e2e", + self._run_text(job_id).replace("e2e/", "").replace("Tier E", ""), + f"job {job_id!r} runs the browser tests", + ) def test_a_failure_leaves_screenshots_to_look_at(self): uploads = [s for s in self.jobs["browser"]["steps"] if "upload-artifact" in s.get("uses", "")] diff --git a/tests/unit/test_ci_shards.py b/tests/unit/test_ci_shards.py index 280f17b..cbf704d 100644 --- a/tests/unit/test_ci_shards.py +++ b/tests/unit/test_ci_shards.py @@ -12,6 +12,7 @@ * the recorded durations name files that exist, so the table cannot rot; * the durations can be regenerated from a JUnit report. """ + from __future__ import annotations import json @@ -40,6 +41,7 @@ def cli(*args: str) -> subprocess.CompletedProcess: # -- every test file is in exactly one shard -------------------------------------------------------------------------- + @pytest.mark.parametrize("n", [1, 2, 3, 5, 8]) def test_the_shards_are_disjoint_and_together_hold_every_file(n): files = ci_shards.test_files() @@ -53,16 +55,36 @@ def test_the_shards_are_disjoint_and_together_hold_every_file(n): def test_the_files_the_script_lists_are_the_files_pytest_collects(): """The strongest guard: the script's idea of 'a test file' is checked against pytest's own collection.""" # `-o addopts=` because pytest.ini already adds -q, and a second one switches the output to per-file counts. - done = subprocess.run([sys.executable, "-m", "pytest", "tests", "-m", "not accessibility", "--collect-only", "-q", - "-o", "addopts=", "-p", "no:cacheprovider"], cwd=ROOT, capture_output=True, text=True, - timeout=300) + done = subprocess.run( + [ + sys.executable, + "-m", + "pytest", + "tests", + "-m", + "not accessibility", + "--collect-only", + "-q", + "-o", + "addopts=", + "-p", + "no:cacheprovider", + ], + cwd=ROOT, + capture_output=True, + text=True, + timeout=300, + ) assert done.returncode == 0, done.stdout[-800:] + done.stderr[-800:] collected = {line.split("::")[0] for line in done.stdout.splitlines() if "::" in line} - assert len(collected) > 50, f"the collection output was not parsed (got {len(collected)} files): {done.stdout[:300]}" + assert len(collected) > 50, ( + f"the collection output was not parsed (got {len(collected)} files): {done.stdout[:300]}" + ) listed = set(ci_shards.test_files()) assert collected <= listed, f"collected by pytest but in no shard: {sorted(collected - listed)}" assert listed - collected <= {f for f in listed if _nothing_to_collect_here(f)}, ( - f"listed but pytest collects nothing from them: {sorted(listed - collected)}") + f"listed but pytest collects nothing from them: {sorted(listed - collected)}" + ) def _nothing_to_collect_here(rel: str) -> bool: @@ -83,6 +105,7 @@ def test_helpers_and_caches_are_not_test_files(): # -- the split --------------------------------------------------------------------------------------------------------- + def test_the_split_is_deterministic(): files, weights = ci_shards.test_files(), ci_shards.load_weights() assert ci_shards.assign(files, weights, 3) == ci_shards.assign(list(reversed(files)), weights, 3) @@ -95,15 +118,24 @@ def test_the_split_is_balanced_by_recorded_duration(): average = sum(totals) / len(totals) biggest_file = max(weights.get(f, ci_shards.DEFAULT_WEIGHT) for f in files) assert max(totals) <= max(average * 1.25, average + biggest_file), ( - f"unbalanced: {totals} (average {average:.0f}s, biggest file {biggest_file:.0f}s)") + f"unbalanced: {totals} (average {average:.0f}s, biggest file {biggest_file:.0f}s)" + ) assert all(shard for shard in shards), "no shard may be empty" def test_the_heaviest_files_are_spread_not_piled_into_one_shard(): - weights = {"tests/a.py": 100, "tests/b.py": 100, "tests/c.py": 100, "tests/d.py": 1, "tests/e.py": 1, "tests/f.py": 1} + weights = { + "tests/a.py": 100, + "tests/b.py": 100, + "tests/c.py": 100, + "tests/d.py": 1, + "tests/e.py": 1, + "tests/f.py": 1, + } shards = ci_shards.assign(sorted(weights), weights, 3) assert sorted(sum(weights[f] for f in shard) for shard in shards) == [2, 101, 101] or all( - sum(weights[f] for f in shard) >= 100 for shard in shards) + sum(weights[f] for f in shard) >= 100 for shard in shards + ) assert all(any(weights[f] == 100 for f in shard) for shard in shards), shards @@ -123,6 +155,7 @@ def test_one_shard_is_the_whole_suite(): # -- the recorded durations -------------------------------------------------------------------------------------------- + def test_the_recorded_durations_name_files_that_exist(): weights = ci_shards.load_weights() assert weights, "ci/shard_weights.json must not be empty" @@ -142,13 +175,15 @@ def test_durations_are_regenerated_from_a_junit_report(tmp_path): (tmp_path / "tests" / "unit" / "test_one.py").write_text("def test_a(): pass\n") (tmp_path / "tests" / "unit" / "test_two.py").write_text("def test_b(): pass\n") xml = tmp_path / "junit.xml" - xml.write_text(textwrap.dedent("""\ + xml.write_text( + textwrap.dedent("""\ - """)) + """) + ) weights = ci_shards.weights_from_junit(xml, root=tmp_path) assert weights == {"tests/unit/test_one.py": 3.75, "tests/unit/test_two.py": 10.0} @@ -158,14 +193,17 @@ def test_a_file_that_took_no_time_still_costs_its_import_and_collection(tmp_path (tmp_path / "tests").mkdir() (tmp_path / "tests" / "test_quick.py").write_text("def test_a(): pass\n") xml = tmp_path / "junit.xml" - xml.write_text('' - '') + xml.write_text( + '' + "" + ) weights = ci_shards.weights_from_junit(xml, root=tmp_path) assert weights == {"tests/test_quick.py": ci_shards.MIN_WEIGHT} and ci_shards.MIN_WEIGHT >= 1.0 # -- the command line the workflow uses -------------------------------------------------------------------------------- + def test_the_cli_prints_one_shards_files_one_per_line(): files, weights = ci_shards.test_files(), ci_shards.load_weights() expected = ci_shards.assign(files, weights, 3)[1] @@ -198,8 +236,10 @@ def test_the_cli_plan_prints_every_shard_with_an_estimate(): def test_the_cli_writes_regenerated_durations(tmp_path): xml = tmp_path / "junit.xml" - xml.write_text('' - '') + xml.write_text( + '' + "" + ) out = tmp_path / "weights.json" done = cli("update-weights", str(xml), "--output", str(out)) assert done.returncode == 0, done.stderr @@ -208,6 +248,7 @@ def test_the_cli_writes_regenerated_durations(tmp_path): # -- the egress job's shards: only the system tests, split on their own ------------------------------------------------ + def test_only_limits_the_files_to_a_prefix(): files = ci_shards.test_files(only="tests/system/") assert files and all(f.startswith("tests/system/") for f in files) diff --git a/tests/unit/test_cloudshell_setup.py b/tests/unit/test_cloudshell_setup.py index 0589387..27bfc45 100644 --- a/tests/unit/test_cloudshell_setup.py +++ b/tests/unit/test_cloudshell_setup.py @@ -61,8 +61,13 @@ # Calls that change something in Azure. A dry run must make none of them. MUTATING = ( - "group create", "storage account create", "storage container create", "ad app create", - "ad sp create", "role assignment create", "federated-credential create", + "group create", + "storage account create", + "storage container create", + "ad app create", + "ad sp create", + "role assignment create", + "federated-credential create", ) @@ -80,10 +85,8 @@ def setUp(self): path.chmod(0o755) def run_script(self, *args: str, **env: str) -> subprocess.CompletedProcess: - full = {**os.environ, "PATH": f"{self.bin}{os.pathsep}{os.environ['PATH']}", - "STUB_LOG": str(self.log), **env} - return subprocess.run(["bash", str(SCRIPT), *args], capture_output=True, text=True, - env=full, timeout=60) + full = {**os.environ, "PATH": f"{self.bin}{os.pathsep}{os.environ['PATH']}", "STUB_LOG": str(self.log), **env} + return subprocess.run(["bash", str(SCRIPT), *args], capture_output=True, text=True, env=full, timeout=60) @property def calls(self) -> list[str]: @@ -148,13 +151,15 @@ def test_the_region_is_used(self): self.assertTrue(any("--location australiasoutheast" in c for c in self.mutating()), self.mutating()) def test_the_account_name_is_valid_stable_and_per_environment_and_subscription(self): - names = {key: self.account_name(self.run_script(*args, **env)) - for key, args, env in ( - ("test", ("test",), {}), - ("test again", ("test",), {}), - ("staging", ("staging",), {}), - ("other sub", ("test",), {"STUB_SUB_ID": "99999999-9999-9999-9999-999999999999"}), - )} + names = { + key: self.account_name(self.run_script(*args, **env)) + for key, args, env in ( + ("test", ("test",), {}), + ("test again", ("test",), {}), + ("staging", ("staging",), {}), + ("other sub", ("test",), {"STUB_SUB_ID": "99999999-9999-9999-9999-999999999999"}), + ) + } self.assertEqual(names["test"], names["test again"], "a re-run must find the same account") self.assertEqual(len({names["test"], names["staging"], names["other sub"]}), 3) for name in names.values(): @@ -181,9 +186,15 @@ def test_dry_run_prints_the_changes_and_makes_none(self): self.assertEqual(res.returncode, 0, res.stderr) self.assertEqual(self.mutating(), [], "a dry run must not change anything") self.assertIn("DRY RUN", res.stdout) - for expected in ("+ az group create", "+ az storage account create", "+ az storage container create", - "+ az ad app create", "+ az ad sp create", "+ az role assignment create", - "+ az ad app federated-credential create"): + for expected in ( + "+ az group create", + "+ az storage account create", + "+ az storage container create", + "+ az ad app create", + "+ az ad sp create", + "+ az role assignment create", + "+ az ad app federated-credential create", + ): self.assertIn(expected, res.stdout + res.stderr) # -- the backend hand-off ---------------------------------------------------- @@ -220,8 +231,16 @@ def test_oidc_creates_app_principal_roles_and_a_credential_bound_to_the_environm self.assertRegex(res.stdout, r"AZURE_TENANT_ID\s+= 22222222-2222-2222-2222-222222222222") def test_oidc_reuses_what_exists(self): - res = self.run_script("test", "--with-oidc", "octo/app", STUB_APP_EXISTS="1", STUB_SP_EXISTS="1", - STUB_ROLE_EXISTS="1", STUB_CRED_EXISTS="1", STUB_ENV="test") + res = self.run_script( + "test", + "--with-oidc", + "octo/app", + STUB_APP_EXISTS="1", + STUB_SP_EXISTS="1", + STUB_ROLE_EXISTS="1", + STUB_CRED_EXISTS="1", + STUB_ENV="test", + ) self.assertEqual(res.returncode, 0, res.stderr) made = self.mutating() for call in ("ad app create", "ad sp create", "role assignment create", "federated-credential create"): diff --git a/tests/unit/test_concurrent_import_limit.py b/tests/unit/test_concurrent_import_limit.py index be9ee36..56fd6b5 100644 --- a/tests/unit/test_concurrent_import_limit.py +++ b/tests/unit/test_concurrent_import_limit.py @@ -14,6 +14,7 @@ its load to anyone without a key; the slot comes after the permission check on each route; * a preview (no database) is not limited. """ + from __future__ import annotations import os @@ -39,6 +40,7 @@ # -- the helper ------------------------------------------------------------------------------------------------------- + def take(n: int): """Hold ``n`` slots, as ``n`` requests in flight would; returns the open dependency generators.""" held = [] @@ -84,7 +86,7 @@ def test_it_admits_the_limit_and_refuses_the_next_with_503_and_retry_after(): def test_a_slot_frees_when_its_request_ends(): held = take(4) held.pop().close() - again = take(1) # does not raise + again = take(1) # does not raise release(held + again) @@ -116,13 +118,14 @@ def test_the_limit_is_read_when_a_request_arrives(monkeypatch): def test_lowering_the_limit_while_requests_run_does_not_leak_slots(monkeypatch): held = take(3) - monkeypatch.setattr(settings, "MAX_CONCURRENT_IMPORTS", 0) # the 3 were counted; they must still be released + monkeypatch.setattr(settings, "MAX_CONCURRENT_IMPORTS", 0) # the 3 were counted; they must still be released release(held) assert concurrency.active_imports() == 0 # -- the real routes ------------------------------------------------------------------------------------------------- + class Loader: """Stands in for a loader: counts the callers inside it and holds them until released.""" @@ -156,9 +159,9 @@ def wait_for(self, n: int) -> None: def loader(monkeypatch): """One stand-in behind all three routes (so each test names the route and nothing else).""" stand_in = Loader({"status": "staged"}) - monkeypatch.setattr(staged_import, "import_upload", stand_in) # POST .../uploads/{id}/import - monkeypatch.setattr(import_routes, "_run", stand_in) # POST .../uploads (stage) - monkeypatch.setattr(csv_routes, "upload_dynamic", stand_in) # POST .../upload + monkeypatch.setattr(staged_import, "import_upload", stand_in) # POST .../uploads/{id}/import + monkeypatch.setattr(import_routes, "_run", stand_in) # POST .../uploads (stage) + monkeypatch.setattr(csv_routes, "upload_dynamic", stand_in) # POST .../upload monkeypatch.setattr(csv_routes, "record_upload", lambda *a, **k: None) return stand_in @@ -231,13 +234,14 @@ def test_the_slot_is_taken_after_authentication_and_the_permission_check(path): route = next(r for r in routes if "POST" in r.methods and r.path_format == path.replace("/1/", "/{upload_id}/")) calls = [d.call for d in route.dependant.dependencies] assert concurrency.import_slot in calls, f"{path} is not limited" - before = calls[:calls.index(concurrency.import_slot)] + before = calls[: calls.index(concurrency.import_slot)] assert any(getattr(c, "__name__", "") == "check" for c in before), "the permission check must come first" def test_the_limit_and_the_pool_behaviour_are_documented(): """BR-58 asks for the pool-exhaustion behaviour to be documented, and an operator must find the setting.""" from pathlib import Path + text = (Path(__file__).resolve().parents[2] / "docs" / "ENV_VARIABLES.md").read_text(encoding="utf-8") row = next((line for line in text.splitlines() if line.startswith("| `API_MAX_CONCURRENT_IMPORTS`")), "") assert row, "docs/ENV_VARIABLES.md must document API_MAX_CONCURRENT_IMPORTS" diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index c229b31..d441697 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -1,9 +1,9 @@ """#331: the API's settings are validated when it starts, and the reference doc matches them. - - A bad value stops start-up with a message that names the variable, what it holds and what was expected, and lists - every bad variable at once. The message never holds a password. - - Ranges and allowed values are checked; values the API read before #331 still read the same way. - - docs/ENV_VARIABLES.md lists every setting with the default the code uses. +- A bad value stops start-up with a message that names the variable, what it holds and what was expected, and lists + every bad variable at once. The message never holds a password. +- Ranges and allowed values are checked; values the API read before #331 still read the same way. +- docs/ENV_VARIABLES.md lists every setting with the default the code uses. """ from __future__ import annotations @@ -34,30 +34,50 @@ def _error(env: dict[str, str]) -> str: # ── Defaults and the values that worked before #331 ───────────────────────────────────────────────────────────── + def test_an_empty_environment_gives_the_documented_defaults(): s = Settings.from_env({}) assert (s.PG_HOST, s.PG_PORT, s.PG_USER, s.PG_DATABASE) == ("localhost", 5432, "postgres", "te_mgmt_dev") assert s.PG_PASSWORD.get_secret_value() == "" and s.APP_DB_PASSWORD.get_secret_value() == "" - assert (s.API_ENV, s.API_ALLOW_ANONYMOUS, s.allow_destructive, s.REQUIRE_TYPE_CONFIRMATION) == ("dev", False, False, False) + assert (s.API_ENV, s.API_ALLOW_ANONYMOUS, s.allow_destructive, s.REQUIRE_TYPE_CONFIRMATION) == ( + "dev", + False, + False, + False, + ) assert s.CORS_ORIGINS == ["http://localhost:8080", "http://localhost:5173", "http://localhost:3000"] assert (s.MAX_ROWS, s.MAX_UPLOAD_BYTES, s.POOL_GETCONN_TIMEOUT) == (100000, 50 * 1024 * 1024, 5.0) def test_values_are_read_from_their_environment_variables(): - s = Settings.from_env({"PGPORT": "6543", "CSV_UPLOADS_SCHEMA": "up", "API_MAX_ROWS": "10", - "API_POOL_GETCONN_TIMEOUT": "0.5", "CORS_ORIGINS": "https://a.example,https://b.example", - "API_ENV": " Prod ", "DATA_CLASSIFICATION": " OFFICIAL ", "PGPASSWORD": SECRET}) + s = Settings.from_env( + { + "PGPORT": "6543", + "CSV_UPLOADS_SCHEMA": "up", + "API_MAX_ROWS": "10", + "API_POOL_GETCONN_TIMEOUT": "0.5", + "CORS_ORIGINS": "https://a.example,https://b.example", + "API_ENV": " Prod ", + "DATA_CLASSIFICATION": " OFFICIAL ", + "PGPASSWORD": SECRET, + } + ) assert (s.PG_PORT, s.UPLOADS_SCHEMA, s.MAX_ROWS, s.POOL_GETCONN_TIMEOUT) == (6543, "up", 10, 0.5) assert s.CORS_ORIGINS == ["https://a.example", "https://b.example"] assert (s.API_ENV, s.DATA_CLASSIFICATION) == ("prod", "OFFICIAL") # stripped (and lower-cased) as before assert s.PG_PASSWORD.get_secret_value() == SECRET -@pytest.mark.parametrize("value, expected", [("1", True), ("true", True), ("YES", True), - ("", False), ("0", False), ("false", False), ("No", False)]) +@pytest.mark.parametrize( + "value, expected", + [("1", True), ("true", True), ("YES", True), ("", False), ("0", False), ("false", False), ("No", False)], +) def test_on_off_values_read_as_before(value, expected): - for name, attr in (("API_ALLOW_DESTRUCTIVE", "allow_destructive"), ("API_ALLOW_ANONYMOUS", "API_ALLOW_ANONYMOUS"), - ("API_REQUIRE_TYPE_CONFIRMATION", "REQUIRE_TYPE_CONFIRMATION")): + for name, attr in ( + ("API_ALLOW_DESTRUCTIVE", "allow_destructive"), + ("API_ALLOW_ANONYMOUS", "API_ALLOW_ANONYMOUS"), + ("API_REQUIRE_TYPE_CONFIRMATION", "REQUIRE_TYPE_CONFIRMATION"), + ): assert getattr(Settings.from_env({name: value}), attr) is expected, name @@ -67,36 +87,47 @@ def test_every_deployment_name_is_accepted(value): def test_zero_still_turns_off_the_limits_documented_as_off_at_zero(): - s = Settings.from_env({"SESSION_IDLE_MINUTES": "0", "API_RATE_LIMIT_READS": "0", "API_RATE_LIMIT_WRITES": "0", - "API_MAX_CONCURRENT_IMPORTS": "0", "SESSION_PURGE_GRACE_DAYS": "0"}) + s = Settings.from_env( + { + "SESSION_IDLE_MINUTES": "0", + "API_RATE_LIMIT_READS": "0", + "API_RATE_LIMIT_WRITES": "0", + "API_MAX_CONCURRENT_IMPORTS": "0", + "SESSION_PURGE_GRACE_DAYS": "0", + } + ) assert (s.SESSION_IDLE_MINUTES, s.RATE_LIMIT_READS_PER_MINUTE, s.MAX_CONCURRENT_IMPORTS) == (0, 0, 0) # ── Bad values ────────────────────────────────────────────────────────────────────────────────────────────────── + def test_a_bad_value_names_the_variable_its_value_and_the_expected_format(): msg = _error({"PGPORT": "abc"}) assert "PGPORT='abc'" in msg and "valid integer" in msg -@pytest.mark.parametrize("name, value, expected", [ - ("PGPORT", "0", "greater than or equal to 1"), - ("PGPORT", "70000", "less than or equal to 65535"), - ("SESSION_TTL_HOURS", "-1", "greater than or equal to 1"), - ("SESSION_IDLE_MINUTES", "-5", "greater than or equal to 0"), - ("LOGIN_MAX_FAILURES", "0", "greater than or equal to 1"), - ("LOGIN_LOCKOUT_MINUTES", "0", "greater than or equal to 1"), - ("API_MAX_ROWS", "0", "greater than or equal to 1"), - ("MAX_UPLOAD_BYTES", "0", "greater than or equal to 1"), - ("API_POOL_GETCONN_TIMEOUT", "0", "greater than 0"), - ("API_POOL_GETCONN_TIMEOUT", "soon", "valid number"), - ("API_RATE_LIMIT_WRITES", "-1", "greater than or equal to 0"), - ("API_ENV", "production", "dev, test, staging, prod"), - # Before #331 these silently meant "off"; now they are refused instead of guessed at. - ("API_ALLOW_DESTRUCTIVE", "on", "expected one of 1, true, yes"), - ("API_ALLOW_ANONYMOUS", "enabled", "expected one of 1, true, yes"), - ("API_REQUIRE_TYPE_CONFIRMATION", " true", "expected one of 1, true, yes"), -]) +@pytest.mark.parametrize( + "name, value, expected", + [ + ("PGPORT", "0", "greater than or equal to 1"), + ("PGPORT", "70000", "less than or equal to 65535"), + ("SESSION_TTL_HOURS", "-1", "greater than or equal to 1"), + ("SESSION_IDLE_MINUTES", "-5", "greater than or equal to 0"), + ("LOGIN_MAX_FAILURES", "0", "greater than or equal to 1"), + ("LOGIN_LOCKOUT_MINUTES", "0", "greater than or equal to 1"), + ("API_MAX_ROWS", "0", "greater than or equal to 1"), + ("MAX_UPLOAD_BYTES", "0", "greater than or equal to 1"), + ("API_POOL_GETCONN_TIMEOUT", "0", "greater than 0"), + ("API_POOL_GETCONN_TIMEOUT", "soon", "valid number"), + ("API_RATE_LIMIT_WRITES", "-1", "greater than or equal to 0"), + ("API_ENV", "production", "dev, test, staging, prod"), + # Before #331 these silently meant "off"; now they are refused instead of guessed at. + ("API_ALLOW_DESTRUCTIVE", "on", "expected one of 1, true, yes"), + ("API_ALLOW_ANONYMOUS", "enabled", "expected one of 1, true, yes"), + ("API_REQUIRE_TYPE_CONFIRMATION", " true", "expected one of 1, true, yes"), + ], +) def test_out_of_range_and_unknown_values_are_refused(name, value, expected): msg = _error({name: value}) assert f"{name}={value!r}" in msg and expected in msg, msg @@ -124,8 +155,9 @@ def test_a_password_is_never_printed(): def test_the_api_refuses_to_start_with_a_named_error(): """The real start-up path: importing the app with a bad value fails with ConfigError, not a bare ValueError.""" env = {**os.environ, "PGPORT": "abc", "PGPASSWORD": SECRET} - res = subprocess.run([sys.executable, "-c", "import api.main"], cwd=ROOT, env=env, - capture_output=True, text=True, timeout=120) + res = subprocess.run( + [sys.executable, "-c", "import api.main"], cwd=ROOT, env=env, capture_output=True, text=True, timeout=120 + ) assert res.returncode != 0 assert "api.config.ConfigError: Invalid configuration" in res.stderr and "PGPORT='abc'" in res.stderr assert SECRET not in res.stderr + res.stdout @@ -142,6 +174,7 @@ def test_settings_still_accept_assignment(): # ── docs/ENV_VARIABLES.md ─────────────────────────────────────────────────────────────────────────────────────── + def _documented_defaults() -> dict[str, str]: """``{VARIABLE: first cell after the name}`` for every table row that starts with a `VARIABLE`.""" rows = {} diff --git a/tests/unit/test_container_bundle.py b/tests/unit/test_container_bundle.py index 3fa8f5b..b7d82d1 100644 --- a/tests/unit/test_container_bundle.py +++ b/tests/unit/test_container_bundle.py @@ -69,7 +69,9 @@ def test_every_service_is_a_te_image_that_is_never_pulled_or_built(self): self.assertEqual(sorted(services), sorted(IMAGES)) for name, svc in services.items(): with self.subTest(service=name): - self.assertNotIn("build", svc, "the installer has no build tools or internet; images come from the bundle") + self.assertNotIn( + "build", svc, "the installer has no build tools or internet; images come from the bundle" + ) self.assertRegex(svc["image"], rf"^te-{name}:\$\{{TE_VERSION") self.assertEqual(svc.get("pull_policy"), "never", "a missing image must be an error, not a download") @@ -81,11 +83,19 @@ def test_the_web_app_and_api_ports_are_published(self): def test_secrets_come_from_variables_not_literals(self): services = compose()["services"] - for svc, var in (("db", "POSTGRES_PASSWORD"), ("db", "TE_DB_PASSWORD"), ("db", "TE_RUNTIME_PASSWORD"), - ("api", "PGPASSWORD"), ("api", "APP_DB_PASSWORD")): + for svc, var in ( + ("db", "POSTGRES_PASSWORD"), + ("db", "TE_DB_PASSWORD"), + ("db", "TE_RUNTIME_PASSWORD"), + ("api", "PGPASSWORD"), + ("api", "APP_DB_PASSWORD"), + ): with self.subTest(service=svc, variable=var): - self.assertRegex(str(services[svc]["environment"][var]), r"^\$\{[A-Z_]+:\?", - "a secret must be required from .env, never written in the file") + self.assertRegex( + str(services[svc]["environment"][var]), + r"^\$\{[A-Z_]+:\?", + "a secret must be required from .env, never written in the file", + ) def test_the_installers_look_for_the_volume_compose_creates(self): """Compose names the volume _. The installers refuse to reuse an old database volume @@ -123,8 +133,10 @@ def test_no_healthcheck_passes_arguments_with_spaces_in_the_exec_form(self): test = svc.get("healthcheck", {}).get("test", []) if test and test[0] == "CMD": with self.subTest(service=name): - self.assertFalse([a for a in test[1:] if re.search(r"\s", a)], - "use CMD-SHELL with one string, or put the command in a script") + self.assertFalse( + [a for a in test[1:] if re.search(r"\s", a)], + "use CMD-SHELL with one string, or put the command in a script", + ) def test_the_api_waits_for_a_healthy_database_and_the_web_app_for_the_api(self): services = compose()["services"] @@ -145,22 +157,34 @@ def test_every_copied_file_exists_and_none_holds_credentials(self): for img in IMAGES: for src in copy_sources(CONTAINER / f"{img}.Dockerfile"): with self.subTest(image=img, source=src): - self.assertTrue((ROOT / src).exists(), f"{src} does not exist; a rename would break the image build") + self.assertTrue( + (ROOT / src).exists(), f"{src} does not exist; a rename would break the image build" + ) self.assertNotIn(src.rstrip("/"), SENSITIVE) - self.assertNotEqual(src.rstrip("/"), "build", "copy named files, not the whole build/ tree: it can hold config.local.env") + self.assertNotEqual( + src.rstrip("/"), + "build", + "copy named files, not the whole build/ tree: it can hold config.local.env", + ) def test_no_secret_is_baked_into_an_image(self): for img in IMAGES: text = (CONTAINER / f"{img}.Dockerfile").read_text(encoding="utf-8") with self.subTest(image=img): - self.assertNotRegex(text, r"(?im)^\s*(ENV|ARG)\s+\w*(PASSWORD|API_KEY|SECRET)\w*[= ]", - "credentials arrive as run-time environment variables, never in a layer") + self.assertNotRegex( + text, + r"(?im)^\s*(ENV|ARG)\s+\w*(PASSWORD|API_KEY|SECRET)\w*[= ]", + "credentials arrive as run-time environment variables, never in a layer", + ) @pytest.mark.unit class PowerShellInstallerAvoidsWindowsTraps(unittest.TestCase): - code = "\n".join(line for line in (CONTAINER / "install.ps1").read_text(encoding="utf-8").splitlines() - if not line.lstrip().startswith("#")) + code = "\n".join( + line + for line in (CONTAINER / "install.ps1").read_text(encoding="utf-8").splitlines() + if not line.lstrip().startswith("#") + ) def test_the_env_file_is_written_without_a_byte_order_mark(self): """-Encoding UTF8 adds a BOM in Windows PowerShell 5.1; a .env parser then reads it as part of the first key.""" @@ -185,8 +209,11 @@ def test_shell_scripts_have_no_syntax_errors(self): def test_the_installer_uses_nothing_newer_than_bash_3_2(self): """macOS ships bash 3.2: no associative arrays, mapfile, or ${var,,} / ${var^^}.""" - code = "\n".join(line for line in (CONTAINER / "install.sh").read_text(encoding="utf-8").splitlines() - if not line.lstrip().startswith("#")) + code = "\n".join( + line + for line in (CONTAINER / "install.sh").read_text(encoding="utf-8").splitlines() + if not line.lstrip().startswith("#") + ) for pattern in (r"declare\s+-A", r"\bmapfile\b", r"\breadarray\b", r"\$\{[A-Za-z_]+(,,|\^\^)\}", r"&>>"): with self.subTest(pattern=pattern): self.assertNotRegex(code, pattern) @@ -258,8 +285,9 @@ def run_smoke(self, *, broken: set[str] = frozenset(), with_login: bool = True): env.update(API_URL=self.url, FRONTEND_URL=self.url) if with_login: env.update(SMOKE_TENANT="main", SMOKE_USER="admin", SMOKE_PASSWORD="long-enough-password") - return subprocess.run([sys.executable, str(CONTAINER / "smoke_test.py")], env=env, - capture_output=True, text=True, timeout=60) + return subprocess.run( + [sys.executable, str(CONTAINER / "smoke_test.py")], env=env, capture_output=True, text=True, timeout=60 + ) def test_a_healthy_stack_passes_all_seven(self): res = self.run_smoke() @@ -272,13 +300,17 @@ def test_without_admin_credentials_it_fails_and_says_what_to_set(self): res = self.run_smoke(with_login=False) self.assertNotEqual(res.returncode, 0, res.stdout + res.stderr) self.assertIn("3 of 7 passed", res.stdout) - self.assertIn("FAIL sign-in, upload and listing checks: set SMOKE_TENANT, SMOKE_USER and SMOKE_PASSWORD", - res.stdout) + self.assertIn( + "FAIL sign-in, upload and listing checks: set SMOKE_TENANT, SMOKE_USER and SMOKE_PASSWORD", res.stdout + ) self.assertNotIn("SKIP", res.stdout) def test_each_failure_is_reported_and_fails_the_run(self): - for breakage, label in (("no401", "API rejects a request without a session"), ("upload", "upload a CSV"), - ("role", "session is tenant_admin")): + for breakage, label in ( + ("no401", "API rejects a request without a session"), + ("upload", "upload a CSV"), + ("role", "session is tenant_admin"), + ): with self.subTest(breakage=breakage): res = self.run_smoke(broken={breakage}) self.assertNotEqual(res.returncode, 0, res.stdout) @@ -293,8 +325,11 @@ def test_it_needs_no_api_key(self): def test_the_script_parses_and_defines_seven_checks(self): tree = ast.parse((CONTAINER / "smoke_test.py").read_text(encoding="utf-8")) - consts = {n.targets[0].id: n.value.value for n in tree.body - if isinstance(n, ast.Assign) and isinstance(n.targets[0], ast.Name) and isinstance(n.value, ast.Constant)} + consts = { + n.targets[0].id: n.value.value + for n in tree.body + if isinstance(n, ast.Assign) and isinstance(n.targets[0], ast.Name) and isinstance(n.value, ast.Constant) + } self.assertEqual(consts.get("TOTAL"), 7) diff --git a/tests/unit/test_container_bundle_sbom.py b/tests/unit/test_container_bundle_sbom.py index 66c5d8f..c76758f 100644 --- a/tests/unit/test_container_bundle_sbom.py +++ b/tests/unit/test_container_bundle_sbom.py @@ -9,6 +9,7 @@ repository's dist/. `tooling` only: they need bash, and the Windows job selects unit/regression (on its runner `bash` is WSL's, with no distribution installed). """ + from __future__ import annotations import hashlib @@ -59,8 +60,14 @@ def assemble(repo: Path, *tars: str, require: bool = False) -> subprocess.Comple env.pop("TE_REQUIRE_SBOM", None) if require: env["TE_REQUIRE_SBOM"] = "1" - return subprocess.run(["bash", str(repo / "container" / "build_bundle.sh"), "assemble", *tars], cwd=repo, env=env, - capture_output=True, text=True, timeout=120) + return subprocess.run( + ["bash", str(repo / "container" / "build_bundle.sh"), "assemble", *tars], + cwd=repo, + env=env, + capture_output=True, + text=True, + timeout=120, + ) def bundle(repo: Path) -> Path: @@ -86,8 +93,10 @@ def checksums_verify(folder: Path) -> list[str]: def listed(repo: Path) -> list[str]: - return [line.split(None, 1)[1].lstrip("*").strip() - for line in (bundle(repo) / "SHA256SUMS").read_text(encoding="utf-8").splitlines()] + return [ + line.split(None, 1)[1].lstrip("*").strip() + for line in (bundle(repo) / "SHA256SUMS").read_text(encoding="utf-8").splitlines() + ] def test_a_bundle_with_no_sbom_builds_as_it_always_did(repo): diff --git a/tests/unit/test_container_image_hardening.py b/tests/unit/test_container_image_hardening.py index 9c1a90d..770a959 100644 --- a/tests/unit/test_container_image_hardening.py +++ b/tests/unit/test_container_image_hardening.py @@ -15,6 +15,7 @@ These read the Dockerfiles as text: the scan itself, in CI, is what proves the findings are gone. """ + from __future__ import annotations import re @@ -70,8 +71,9 @@ def test_the_frontend_image_that_ships_has_no_npm(): removal = index_of(runtime, "/usr/local/lib/node_modules/npm") assert removal != -1, "the runtime stage must remove npm: its bundled packages carry the scan findings" assert runtime[removal].upper().startswith("RUN ") and "rm " in runtime[removal] - assert "/usr/local/bin/npm" in runtime[removal] and "/usr/local/bin/npx" in runtime[removal], \ + assert "/usr/local/bin/npm" in runtime[removal] and "/usr/local/bin/npx" in runtime[removal], ( "remove the npm and npx commands too, not just the library folder" + ) user = index_of(runtime, "USER node") assert user != -1 and removal < user, "removing files needs root: it must come before USER node" @@ -89,10 +91,13 @@ def test_nothing_in_the_container_start_up_needs_npm(): assert "exec node " in code -@pytest.mark.parametrize("image, packages", [ - ("api.Dockerfile", ["zlib1g"]), - ("db.Dockerfile", ["zlib1g", "libgssapi-krb5-2", "libkrb5-3", "libk5crypto3", "libkrb5support0"]), -]) +@pytest.mark.parametrize( + "image, packages", + [ + ("api.Dockerfile", ["zlib1g"]), + ("db.Dockerfile", ["zlib1g", "libgssapi-krb5-2", "libkrb5-3", "libk5crypto3", "libkrb5support0"]), + ], +) def test_the_debian_packages_the_scan_flagged_are_upgraded(image, packages): items = joined(dockerfile(image)) upgrade = [ins for ins in items if ins.upper().startswith("RUN ") and "--only-upgrade" in ins] @@ -102,8 +107,9 @@ def test_the_debian_packages_the_scan_flagged_are_upgraded(image, packages): assert re.search(rf"(? Path: if with_psql: stub = path / "psql" # An absolute shebang: the restricted PATH has no `bash` for `env` to find. - stub.write_text(PSQL_STUB.replace("#!/usr/bin/env bash", f"#!{BASH}", 1), - encoding="utf-8", newline="\n") + stub.write_text(PSQL_STUB.replace("#!/usr/bin/env bash", f"#!{BASH}", 1), encoding="utf-8", newline="\n") stub.chmod(0o755) return path def run_script(self, *args: str, with_psql: bool = True, **env: str) -> subprocess.CompletedProcess: - full = {"PATH": str(self._bin(with_psql)), "STUB_LOG": str(self.log), - "HOME": str(self.dir), **env} + full = {"PATH": str(self._bin(with_psql)), "STUB_LOG": str(self.log), "HOME": str(self.dir), **env} # stdin is closed: with no terminal the script must never wait for an answer, even # when the person running pytest has one (stderr is captured, so it is not a terminal). - return subprocess.run([BASH, str(self.dir / "build" / "deploy_all.sh"), *args], - capture_output=True, text=True, env=full, timeout=60, - stdin=subprocess.DEVNULL) + return subprocess.run( + [BASH, str(self.dir / "build" / "deploy_all.sh"), *args], + capture_output=True, + text=True, + env=full, + timeout=60, + stdin=subprocess.DEVNULL, + ) def run_interactive(self, *args: str, answer: str, **env: str) -> tuple[int, str]: """Run the script with a real terminal (a pseudo-terminal) and type ``answer`` at it. @@ -113,8 +117,14 @@ def run_interactive(self, *args: str, answer: str, **env: str) -> tuple[int, str """ full = {"PATH": str(self._bin(True)), "STUB_LOG": str(self.log), "HOME": str(self.dir), **env} master, slave = pty.openpty() - proc = subprocess.Popen([BASH, str(self.dir / "build" / "deploy_all.sh"), *args], - stdin=slave, stdout=slave, stderr=slave, env=full, close_fds=True) + proc = subprocess.Popen( + [BASH, str(self.dir / "build" / "deploy_all.sh"), *args], + stdin=slave, + stdout=slave, + stderr=slave, + env=full, + close_fds=True, + ) os.close(slave) out = b"" try: @@ -169,8 +179,9 @@ def test_a_missing_psql_with_an_install_names_the_newest_bin_folder(self): res = self.run_script("dev", with_psql=False, PROGRAMFILES=str(pf)) self.assertEqual(res.returncode, 1) self.assertIn("installed, but its bin folder is not on PATH", res.stderr) - self.assertIn(f'export PATH="{pf}/PostgreSQL/18/bin:$PATH"', res.stderr, - "version order, not text order: 18 beats 9.6") + self.assertIn( + f'export PATH="{pf}/PostgreSQL/18/bin:$PATH"', res.stderr, "version order, not text order: 18 beats 9.6" + ) def test_a_missing_psql_with_no_install_says_how_to_get_it(self): res = self.run_script("dev", with_psql=False, PROGRAMFILES=str(self.dir / "empty-pf")) @@ -182,16 +193,21 @@ def test_a_missing_psql_with_no_install_says_how_to_get_it(self): # -- bash from PowerShell is WSL: say so, instead of sending a Windows user to apt -------- def test_inside_wsl_a_missing_psql_points_at_git_bash_not_at_apt_alone(self): - res = self.run_script("dev", with_psql=False, WSL_DISTRO_NAME="Ubuntu-24.04", - PROGRAMFILES=str(self.dir / "empty-pf")) + res = self.run_script( + "dev", with_psql=False, WSL_DISTRO_NAME="Ubuntu-24.04", PROGRAMFILES=str(self.dir / "empty-pf") + ) self.assertEqual(res.returncode, 1) self.assertIn("psql was not found on PATH", res.stderr) self.assertIn("inside WSL", res.stderr) self.assertIn("Git Bash", res.stderr) - self.assertIn(r'"C:\Program Files\Git\bin\bash.exe" build/deploy_all.sh', res.stderr, - "the exact PowerShell command to use instead") - self.assertIn("sudo apt install postgresql-client", res.stderr, - "still offered, for a PostgreSQL that runs inside WSL") + self.assertIn( + r'"C:\Program Files\Git\bin\bash.exe" build/deploy_all.sh', + res.stderr, + "the exact PowerShell command to use instead", + ) + self.assertIn( + "sudo apt install postgresql-client", res.stderr, "still offered, for a PostgreSQL that runs inside WSL" + ) self.assertNotIn("Install it with: apt install", res.stderr, "the generic Linux hint is replaced") self.assertNotIn("Creating database", res.stdout) self.assertEqual(self.calls, []) @@ -228,8 +244,9 @@ def test_an_unreachable_server_is_reported_once_with_the_reason(self): def test_the_host_and_port_in_the_message_are_the_ones_used(self): res = self.run_script("dev", STUB_CONNECT="fail", PGHOST="db.example", PGPORT="5433", PGUSER="admin") self.assertIn("at db.example:5433 as admin", res.stderr) - self.assertTrue(any("-h db.example" in c and "-p 5433" in c and "-U admin" in c - for c in self.calls), self.calls) + self.assertTrue( + any("-h db.example" in c and "-p 5433" in c and "-U admin" in c for c in self.calls), self.calls + ) # -- the existence check ----------------------------------------------------- diff --git a/tests/unit/test_docker_image_secrets.py b/tests/unit/test_docker_image_secrets.py index 5ade09d..376581a 100644 --- a/tests/unit/test_docker_image_secrets.py +++ b/tests/unit/test_docker_image_secrets.py @@ -21,6 +21,7 @@ observe. On `main` at c7bebd1 the Dockerfile had a single `COPY build/ ./build/`, so TestExplicitCopyList fails there. """ + from __future__ import annotations import fnmatch @@ -89,16 +90,8 @@ def expand(source: str) -> set[str]: """ if source.endswith("/"): base = ROOT / source - return { - str(p.relative_to(ROOT)).replace("\\", "/") - for p in base.rglob("*") - if p.is_file() - } - return { - str(p.relative_to(ROOT)).replace("\\", "/") - for p in ROOT.glob(source) - if p.is_file() - } + return {str(p.relative_to(ROOT)).replace("\\", "/") for p in base.rglob("*") if p.is_file()} + return {str(p.relative_to(ROOT)).replace("\\", "/") for p in ROOT.glob(source) if p.is_file()} def ignore_patterns() -> list[str]: diff --git a/tests/unit/test_e2e_preflight.py b/tests/unit/test_e2e_preflight.py index 8fb3d6c..b46226d 100644 --- a/tests/unit/test_e2e_preflight.py +++ b/tests/unit/test_e2e_preflight.py @@ -4,6 +4,7 @@ cryptic "Executable doesn't exist" trace), PostgreSQL not running, and a package version read from an attribute the package does not have. No Playwright, browser or database is needed here. """ + import importlib.util import sys import types @@ -28,14 +29,14 @@ def _all_fine(tmp_path, monkeypatch, **overrides): monkeypatch.setattr(preflight.importlib.metadata, "version", lambda name: "1.0") monkeypatch.setattr(preflight.importlib.util, "find_spec", lambda name: object()) (tmp_path / "csv-table-hub-main" / "node_modules").mkdir(parents=True) - args = dict(root=tmp_path, env={}, pg_host="localhost", pg_port=5433, probe=UP, ports=(8000, 8080), - is_free=FREE) + args = dict(root=tmp_path, env={}, pg_host="localhost", pg_port=5433, probe=UP, ports=(8000, 8080), is_free=FREE) args.update(overrides) return preflight.problems(**args) # ── Playwright ──────────────────────────────────────────────────────────────────────────── + def test_a_missing_playwright_says_how_to_install_it(monkeypatch): def not_installed(name): raise preflight.importlib.metadata.PackageNotFoundError(name) @@ -59,6 +60,7 @@ def test_playwright_is_asked_of_the_package_metadata_not_of_a_version_attribute( # ── the browser ─────────────────────────────────────────────────────────────────────────── + def test_an_override_that_points_nowhere_is_reported_with_the_way_out(tmp_path): missing = tmp_path / "no" / "chrome" @@ -78,6 +80,7 @@ def test_an_override_that_exists_and_no_override_are_both_fine(tmp_path): # ── PostgreSQL ──────────────────────────────────────────────────────────────────────────── + def test_postgresql_not_there_names_where_it_looked_why_and_what_to_do(): msg = preflight.check_postgres("db.example.test", 6543, lambda h, p: (False, "refused")) @@ -97,6 +100,7 @@ def test_postgresql_there_is_fine(): # ── ports, Node, Streamlit ──────────────────────────────────────────────────────────────── + def test_every_busy_port_is_listed_with_the_remedy(): msgs = preflight.check_ports((8000, 8080, 8501), lambda p: p == 8080) @@ -117,6 +121,7 @@ def test_a_missing_streamlit_says_how_to_install_it(monkeypatch): # ── all together ────────────────────────────────────────────────────────────────────────── + def test_nothing_is_reported_when_everything_is_there(tmp_path, monkeypatch): assert _all_fine(tmp_path, monkeypatch) == [] @@ -127,16 +132,28 @@ def not_installed(name): monkeypatch.setattr(preflight.importlib.metadata, "version", not_installed) monkeypatch.setattr(preflight.importlib.util, "find_spec", lambda name: None) # Streamlit missing too - found = preflight.problems(root=tmp_path, env={"E2E_CHROMIUM": str(tmp_path / "gone")}, pg_host="h", - pg_port=1, probe=lambda h, p: (False, "refused"), ports=(8000, 8080), - is_free=lambda p: p != 8080) + found = preflight.problems( + root=tmp_path, + env={"E2E_CHROMIUM": str(tmp_path / "gone")}, + pg_host="h", + pg_port=1, + probe=lambda h, p: (False, "refused"), + ports=(8000, 8080), + is_free=lambda p: p != 8080, + ) assert len(found) == 6 assert [m.split(" ")[0] for m in found][:3] == ["Playwright", "E2E_CHROMIUM", "Streamlit"] assert "npm ci" in found[3] and "PostgreSQL" in found[4] and "port 8080" in found[5] - assert found == preflight.problems(root=tmp_path, env={"E2E_CHROMIUM": str(tmp_path / "gone")}, pg_host="h", - pg_port=1, probe=lambda h, p: (False, "refused"), ports=(8000, 8080), - is_free=lambda p: p != 8080) + assert found == preflight.problems( + root=tmp_path, + env={"E2E_CHROMIUM": str(tmp_path / "gone")}, + pg_host="h", + pg_port=1, + probe=lambda h, p: (False, "refused"), + ports=(8000, 8080), + is_free=lambda p: p != 8080, + ) def test_the_report_counts_and_lists_each_problem_on_its_own_line(): diff --git a/tests/unit/test_egress_firewall_script.py b/tests/unit/test_egress_firewall_script.py index bae9e6c..e697102 100644 --- a/tests/unit/test_egress_firewall_script.py +++ b/tests/unit/test_egress_firewall_script.py @@ -17,6 +17,7 @@ `tooling`: these run bash, and the Windows job's `bash` is WSL's, with no distribution installed. """ + from __future__ import annotations import json @@ -33,7 +34,7 @@ ROOT = Path(__file__).resolve().parents[2] SCRIPT = ROOT / "scripts" / "egress_firewall.sh" -USER = "nobody" # exists on every Linux and macOS; never root, and not the user running the tests (not under sudo) +USER = "nobody" # exists on every Linux and macOS; never root, and not the user running the tests (not under sudo) FAKE_IPTABLES = '''#!{python} """A stateful stand-in for iptables: just the commands egress_firewall.sh uses.""" @@ -100,14 +101,14 @@ def fail(message): save() ''' -FAKE_SETPRIV = '''#!/bin/sh +FAKE_SETPRIV = """#!/bin/sh # Records how it was called, then runs the command after the options (the real one would switch user first). echo "$@" >> "{calls}" while [ $# -gt 0 ]; do case "$1" in --*) shift ;; *) break ;; esac done exec "$@" -''' +""" @pytest.fixture @@ -153,8 +154,9 @@ def setpriv_calls(self) -> list[str]: def run(fakes, *args: str, env: dict | None = None) -> subprocess.CompletedProcess: full_env = {"PATH": fakes.path + os.pathsep + "/usr/bin:/bin", "HOME": str(Path.home()), **(env or {})} - return subprocess.run([shutil.which("bash"), str(SCRIPT), *args], cwd=ROOT, env=full_env, - capture_output=True, text=True, timeout=60) + return subprocess.run( + [shutil.which("bash"), str(SCRIPT), *args], cwd=ROOT, env=full_env, capture_output=True, text=True, timeout=60 + ) def uid_of(user: str) -> str: @@ -162,8 +164,12 @@ def uid_of(user: str) -> str: # Loopback (the local database) and the Docker bridges (containers only) return to the normal rules; the rest is refused. -CHAIN_RULES = [["-o", "lo", "-j", "RETURN"], ["-o", "docker0", "-j", "RETURN"], ["-o", "br+", "-j", "RETURN"], - ["-j", "REJECT"]] +CHAIN_RULES = [ + ["-o", "lo", "-j", "RETURN"], + ["-o", "docker0", "-j", "RETURN"], + ["-o", "br+", "-j", "RETURN"], + ["-j", "REJECT"], +] def jumps(fakes) -> list[list[str]]: @@ -172,6 +178,7 @@ def jumps(fakes) -> list[list[str]]: # -- install --------------------------------------------------------------------------------------------------------- + def test_install_rejects_the_users_traffic_except_to_this_machine(fakes): done = run(fakes, "install", USER) assert done.returncode == 0, done.stderr @@ -212,6 +219,7 @@ def test_install_needs_a_user_argument(fakes): # -- count, check, reset ----------------------------------------------------------------------------------------------- + def test_count_prints_the_refused_packets(fakes): run(fakes, "install", USER) fakes.set_packets(7) @@ -247,6 +255,7 @@ def test_check_cannot_pass_when_the_block_was_never_installed(fakes): # -- remove ---------------------------------------------------------------------------------------------------------- + def test_remove_takes_the_rule_and_the_chain_away_and_leaves_other_rules(fakes): fakes.add_other_rule("-m", "owner", "--uid-owner", "999", "-j", "ACCEPT") run(fakes, "install", USER) @@ -264,6 +273,7 @@ def test_remove_is_safe_when_nothing_is_installed(fakes): # -- run ------------------------------------------------------------------------------------------------------------- + def test_run_executes_the_command_as_that_user_with_the_callers_environment(fakes): done = run(fakes, "run", USER, "--", "printenv", "EGRESS_TEST_MARKER", env={"EGRESS_TEST_MARKER": "kept"}) assert done.returncode == 0, done.stderr diff --git a/tests/unit/test_egress_guard.py b/tests/unit/test_egress_guard.py index a98747c..008ee9d 100644 --- a/tests/unit/test_egress_guard.py +++ b/tests/unit/test_egress_guard.py @@ -21,7 +21,15 @@ def test_loopback_names_addresses_and_socket_directories_are_local(self): self.assertTrue(is_local(host), host) def test_everything_else_is_not(self): - for host in ("example.com", "93.184.216.34", "10.0.0.5", "192.168.1.1", "0.0.0.0", "db.internal", "2001:db8::1"): + for host in ( + "example.com", + "93.184.216.34", + "10.0.0.5", + "192.168.1.1", + "0.0.0.0", + "db.internal", + "2001:db8::1", + ): self.assertFalse(is_local(host), host) def test_a_remote_database_host_is_refused_up_front(self): @@ -34,7 +42,7 @@ def test_a_remote_database_host_is_refused_up_front(self): @pytest.mark.unit class GuardBehaviour(unittest.TestCase): def setUp(self): - self._active = bool(egress_guard._originals) # already installed by `pytest --block-egress` + self._active = bool(egress_guard._originals) # already installed by `pytest --block-egress` egress_guard.uninstall() egress_guard.attempts.clear() egress_guard.install() @@ -48,7 +56,7 @@ def tearDown(self): def test_connecting_to_a_public_address_is_blocked_before_any_packet_is_sent(self): with self.assertRaises(EgressBlocked): - socket.create_connection(("93.184.216.34", 80), timeout=1) # resolves first, and is stopped there + socket.create_connection(("93.184.216.34", 80), timeout=1) # resolves first, and is stopped there self.assertEqual(egress_guard.attempts, ["resolve 93.184.216.34"]) def test_a_direct_connect_is_blocked_too(self): diff --git a/tests/unit/test_egress_network_control.py b/tests/unit/test_egress_network_control.py index bd97436..1b6dccc 100644 --- a/tests/unit/test_egress_network_control.py +++ b/tests/unit/test_egress_network_control.py @@ -14,6 +14,7 @@ suite on the open network runs in the shards, never in this job; * the docs say the child-process and libpq gap is closed in CI, and how. """ + from __future__ import annotations import os @@ -34,10 +35,17 @@ # -- collection ------------------------------------------------------------------------------------------------------ + def collected(extra_env: dict[str, str]) -> subprocess.CompletedProcess: env = {k: v for k, v in os.environ.items() if k != "EGRESS_NETWORK_BLOCKED"} | extra_env - return subprocess.run([sys.executable, "-m", "pytest", CONTROL, "--collect-only", "-q", "-p", "no:cacheprovider"], - cwd=ROOT, env=env, capture_output=True, text=True, timeout=120) + return subprocess.run( + [sys.executable, "-m", "pytest", CONTROL, "--collect-only", "-q", "-p", "no:cacheprovider"], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + timeout=120, + ) def test_the_control_is_left_out_of_every_run_without_the_firewall(): @@ -60,10 +68,14 @@ def test_the_marker_is_registered(): # -- the workflow ---------------------------------------------------------------------------------------------------- + def job_steps() -> list[dict]: jobs = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"] - return next(job["steps"] for job in jobs.values() - if any("API tests with network egress blocked" in (s.get("name") or "") for s in job["steps"])) + return next( + job["steps"] + for job in jobs.values() + if any("API tests with network egress blocked" in (s.get("name") or "") for s in job["steps"]) + ) def index_of(steps: list[dict], needle: str) -> int: @@ -78,8 +90,9 @@ def test_the_block_is_installed_for_a_dedicated_user_never_the_runners(): text = "\n".join(s.get("run") or "" for s in steps) assert re.search(r"useradd[^\n]*\begresstest\b", text), "a dedicated user must be created" assert re.search(r"egress_firewall\.sh install egresstest\b", text) - assert not re.search(r"egress_firewall\.sh install\s+(runner|\$USER|\"\$USER\"|root|\$\(whoami\))", text), \ + assert not re.search(r"egress_firewall\.sh install\s+(runner|\$USER|\"\$USER\"|root|\$\(whoami\))", text), ( "blocking the runner's user would cut off the agent that reports the job" + ) def test_the_steps_run_in_an_order_that_makes_the_check_mean_something(): @@ -91,7 +104,13 @@ def test_the_steps_run_in_an_order_that_makes_the_check_mean_something(): check = index_of(steps, "egress_firewall.sh check") remove = index_of(steps, "egress_firewall.sh remove") assert create < install < control < blocked_tests < check < remove, ( - create, install, control, blocked_tests, check, remove) + create, + install, + control, + blocked_tests, + check, + remove, + ) def test_the_suite_on_the_open_network_runs_in_the_shards_never_with_the_control_enabled(): @@ -101,7 +120,8 @@ def test_the_suite_on_the_open_network_runs_in_the_shards_never_with_the_control assert "EGRESS_NETWORK_BLOCKED" not in text, "on an open network the control would connect" assert "test_report.py" in text, "the suite on the open network runs in the shards" assert "test_report.py" not in "\n".join(s.get("run") or "" for s in job_steps()), ( - "the egress job does not run the whole suite a second time") + "the egress job does not run the whole suite a second time" + ) def test_the_control_runs_as_the_blocked_user_and_must_have_been_counted_then_the_count_is_zeroed(): @@ -110,8 +130,9 @@ def test_the_control_runs_as_the_blocked_user_and_must_have_been_counted_then_th run = step["run"] assert "egress_firewall.sh run egresstest" in run, "the control must run as the blocked user" assert str((step.get("env") or {}).get("EGRESS_NETWORK_BLOCKED")) == "1" - assert re.search(r"egress_firewall\.sh count", run) and re.search(r"-ge 1|-gt 0", run), \ + assert re.search(r"egress_firewall\.sh count", run) and re.search(r"-ge 1|-gt 0", run), ( "the step must fail if the control's deliberate attempts were not counted (the counter would then prove nothing)" + ) assert run.index("count") < run.index("egress_firewall.sh reset"), "zero the count after reading it" @@ -120,14 +141,17 @@ def test_the_egress_blocked_tests_run_as_the_blocked_user_without_the_control(): step = steps[index_of(steps, "--block-egress")] assert "egress_firewall.sh run egresstest" in step["run"] assert "EGRESS_NETWORK_BLOCKED" not in str(step.get("env") or {}), ( - "the deliberate attempts of the control must not run in the step whose count must stay zero") + "the deliberate attempts of the control must not run in the step whose count must stay zero" + ) def test_no_step_relies_on_sudo_preserving_the_environment(): """sudo-rs (the default sudo on newer Ubuntu) ignores -E, so the variables never reached the blocked user (first CI run).""" for step in job_steps(): run = step.get("run") or "" - assert not re.search(r"sudo\s+(-\w*E\b|--preserve-env)", run), f"{step.get('name')}: pass the variables with `sudo env VAR=...`" + assert not re.search(r"sudo\s+(-\w*E\b|--preserve-env)", run), ( + f"{step.get('name')}: pass the variables with `sudo env VAR=...`" + ) def test_the_variables_the_tests_need_are_passed_to_the_blocked_user_by_name(): @@ -135,11 +159,18 @@ def test_the_variables_the_tests_need_are_passed_to_the_blocked_user_by_name(): control = steps[index_of(steps, CONTROL)]["run"] blocked = steps[index_of(steps, "--block-egress")]["run"] for name, run in (("control", control), ("egress tests", blocked)): - for needed in ('"PATH=$PATH"', '"PGHOST=$PGHOST"', '"PGPORT=$PGPORT"', '"PGUSER=$PGUSER"', '"PGPASSWORD=$PGPASSWORD"', - '"PGDATABASE=$PGDATABASE"'): + for needed in ( + '"PATH=$PATH"', + '"PGHOST=$PGHOST"', + '"PGPORT=$PGPORT"', + '"PGUSER=$PGUSER"', + '"PGPASSWORD=$PGPASSWORD"', + '"PGDATABASE=$PGDATABASE"', + ): assert needed in run, f"the {name} step must pass {needed} to the blocked user" assert '"EGRESS_NETWORK_BLOCKED=$EGRESS_NETWORK_BLOCKED"' in control, ( - "without it the control is deselected and pytest exits 5 (the first CI run)") + "without it the control is deselected and pytest exits 5 (the first CI run)" + ) assert '"EGRESS_NETWORK_BLOCKED=' not in blocked, "the control's variable must not reach the counted step" @@ -151,6 +182,7 @@ def test_the_block_is_removed_even_when_an_earlier_step_failed(): # -- the docs -------------------------------------------------------------------------------------------------------- + def test_the_docs_say_the_child_process_gap_is_closed_in_ci_and_how(): sovereignty = (ROOT / "docs" / "SOVEREIGNTY.md").read_text(encoding="utf-8") assert "scripts/egress_firewall.sh" in sovereignty diff --git a/tests/unit/test_evals_runner.py b/tests/unit/test_evals_runner.py index d27e143..51d5eea 100644 --- a/tests/unit/test_evals_runner.py +++ b/tests/unit/test_evals_runner.py @@ -6,6 +6,7 @@ tier_i fail-on-unreachable behaviour is verified by mocking _can_connect_pg. """ + import importlib.util import shutil import tempfile @@ -91,6 +92,7 @@ def test_count_dev_rows_records_none_for_failed_count_query(self): def _run_main_with_result(self, *, passed, skipped): """Run runner.main() over one tier_p scenario whose result is faked.""" + def fake_runner(scenario): result = runner.ScenarioResult("p", scenario.name) result.passed = passed @@ -102,10 +104,11 @@ def fake_runner(scenario): reports = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, reports, True) scenario = sorted((PROJECT_ROOT / "evals" / "datasets" / "tier_p").iterdir())[0] - with mock.patch.object(runner, "REPORTS_DIR", reports), \ - mock.patch.dict(runner.TIER_RUNNERS, {"p": fake_runner}), \ - mock.patch.object(runner.sys, "argv", - ["runner.py", "--tiers", "p", "--only", scenario.name]): + with ( + mock.patch.object(runner, "REPORTS_DIR", reports), + mock.patch.dict(runner.TIER_RUNNERS, {"p": fake_runner}), + mock.patch.object(runner.sys, "argv", ["runner.py", "--tiers", "p", "--only", scenario.name]), + ): return runner.main() def test_main_exits_nonzero_when_a_scenario_is_skipped(self): diff --git a/tests/unit/test_evals_tier_e_x.py b/tests/unit/test_evals_tier_e_x.py index de1e908..880ebc4 100644 --- a/tests/unit/test_evals_tier_e_x.py +++ b/tests/unit/test_evals_tier_e_x.py @@ -12,8 +12,8 @@ import subprocess import sys import unittest -from unittest.mock import patch from pathlib import Path +from unittest.mock import patch import pytest @@ -94,12 +94,12 @@ class TierEColumnSignatureQuery(unittest.TestCase): """ def _scenario(self, completed): - expected = {"expected": {"min_tables_per_env": 12}, - "envs_under_test": ["dev"]} + expected = {"expected": {"min_tables_per_env": 12}, "envs_under_test": ["dev"]} result = runner.ScenarioResult(tier="e", name="t") - with patch.object(runner, "_deploy_env", - return_value={"env": "dev", "exit_code": 0}), \ - patch.object(runner.subprocess, "run", return_value=completed) as run: + with ( + patch.object(runner, "_deploy_env", return_value={"env": "dev", "exit_code": 0}), + patch.object(runner.subprocess, "run", return_value=completed) as run, + ): runner._run_envs_have_identical_structure(result, expected) return result, run @@ -111,19 +111,18 @@ def test_query_is_sent_on_stdin_not_via_dash_c(self): self.assertIn(":'sch'", kwargs["input"]) def test_query_failure_is_reported_as_a_query_error(self): - bad = subprocess.CompletedProcess([], 1, stdout="", - stderr='ERROR: syntax error at or near ":"') + bad = subprocess.CompletedProcess([], 1, stdout="", stderr='ERROR: syntax error at or near ":"') result, _ = self._scenario(bad) self.assertFalse(result.passed) - self.assertTrue(any("schema query" in e and "syntax error" in e - for e in result.errors), result.errors) + self.assertTrue(any("schema query" in e and "syntax error" in e for e in result.errors), result.errors) def test_genuinely_empty_schema_still_fails(self): empty = subprocess.CompletedProcess([], 0, stdout="", stderr="") result, _ = self._scenario(empty) self.assertFalse(result.passed) - self.assertIn("env dev has 0 tables in its schema, expected >= 12 " - "(deploy may have partially failed)", result.errors) + self.assertIn( + "env dev has 0 tables in its schema, expected >= 12 (deploy may have partially failed)", result.errors + ) @pytest.mark.unit @@ -139,17 +138,17 @@ class TierEEmptySchemaControl(unittest.TestCase): REF = {"t%d" % i: ["id:uuid:NO"] for i in range(12)} EXPECTED = { "reference_env": "dev", - "expected": {"min_reference_tables": 12, "empty_schema_tables": 0, - "diff_reports_missing_tables": True}, + "expected": {"min_reference_tables": 12, "empty_schema_tables": 0, "diff_reports_missing_tables": True}, } def _run(self, signatures, psql=None, diff=None, expected=None): """Run the control; returns (result, psql mock, signature mock).""" ok = subprocess.CompletedProcess([], 0, stdout="", stderr="") result = runner.ScenarioResult(tier="e", name="02_empty_schema_is_detected") - with patch.object(runner, "_column_signature", side_effect=signatures) as sig, \ - patch.object(runner, "_psql_run", - **({"side_effect": psql} if psql else {"return_value": ok})) as run: + with ( + patch.object(runner, "_column_signature", side_effect=signatures) as sig, + patch.object(runner, "_psql_run", **({"side_effect": psql} if psql else {"return_value": ok})) as run, + ): if diff is None: runner._run_empty_schema_negative_control(result, expected or self.EXPECTED) else: @@ -172,8 +171,7 @@ def test_fails_when_the_comparison_no_longer_reports_the_missing_tables(self): # The point of a control: neutralise the thing it guards and it must go red. result, _, _ = self._run([self.REF, {}], diff=[]) self.assertFalse(result.passed) - self.assertTrue(any("would pass a deploy that wrote nothing" in e - for e in result.errors), result.errors) + self.assertTrue(any("would pass a deploy that wrote nothing" in e for e in result.errors), result.errors) def test_fails_when_an_empty_schema_reports_tables(self): result, _, _ = self._run([self.REF, {"x": ["id:uuid:NO"]}]) @@ -183,8 +181,10 @@ def test_fails_when_an_empty_schema_reports_tables(self): def test_a_failed_query_on_the_empty_schema_is_not_read_as_no_tables(self): result, _, _ = self._run([self.REF, RuntimeError("connection lost")]) self.assertFalse(result.passed) - self.assertTrue(any("must not be reported as 'no tables'" in e - and "connection lost" in e for e in result.errors), result.errors) + self.assertTrue( + any("must not be reported as 'no tables'" in e and "connection lost" in e for e in result.errors), + result.errors, + ) def test_refuses_to_run_against_an_empty_reference_and_creates_nothing(self): result, run, _ = self._run([{}]) @@ -219,15 +219,15 @@ def test_a_failed_drop_is_reported(self): bad = subprocess.CompletedProcess([], 1, stdout="", stderr="ERROR: cannot drop") result, _, _ = self._run([self.REF, {}], psql=[ok, bad]) self.assertFalse(result.passed) - self.assertTrue(any("could not drop the throwaway schema" in e - and "cannot drop" in e for e in result.errors), result.errors) + self.assertTrue( + any("could not drop the throwaway schema" in e and "cannot drop" in e for e in result.errors), result.errors + ) def test_a_failed_create_is_reported_and_no_schema_query_is_run_on_it(self): bad = subprocess.CompletedProcess([], 1, stdout="", stderr="ERROR: permission denied") result, _, sig = self._run([self.REF], psql=[bad]) self.assertFalse(result.passed) - self.assertTrue(any("could not create the throwaway schema" in e - for e in result.errors), result.errors) + self.assertTrue(any("could not create the throwaway schema" in e for e in result.errors), result.errors) self.assertEqual(sig.call_count, 1, "only the reference was queried") def test_an_unknown_reference_env_is_reported(self): @@ -238,15 +238,19 @@ def test_an_unknown_reference_env_is_reported(self): def test_the_scenario_is_dispatched_by_name(self): scenario = Path("evals/datasets/tier_e/02_empty_schema_is_detected") - with patch.object(runner, "_load_expected", return_value={"expected": {}}), \ - patch.object(runner, "_can_connect_pg", return_value=True), \ - patch.object(runner, "_run_empty_schema_negative_control") as control: + with ( + patch.object(runner, "_load_expected", return_value={"expected": {}}), + patch.object(runner, "_can_connect_pg", return_value=True), + patch.object(runner, "_run_empty_schema_negative_control") as control, + ): runner.run_tier_e_scenario(scenario) control.assert_called_once() def test_an_unknown_tier_e_scenario_is_still_an_error(self): - with patch.object(runner, "_load_expected", return_value={"expected": {}}), \ - patch.object(runner, "_can_connect_pg", return_value=True): + with ( + patch.object(runner, "_load_expected", return_value={"expected": {}}), + patch.object(runner, "_can_connect_pg", return_value=True), + ): result = runner.run_tier_e_scenario(Path("evals/datasets/tier_e/99_unknown")) self.assertIn("Unknown tier-E scenario: 99_unknown", result.errors) @@ -264,15 +268,12 @@ class TierXSqliteStructure(unittest.TestCase): """O-08: SQLite DDL execution and structural readback.""" def test_placeholders_are_substituted(self): - out = runner._substitute_placeholders( - "CREATE TABLE {{TBL_ORGANISATIONS}} (x TEXT);" - ) + out = runner._substitute_placeholders("CREATE TABLE {{TBL_ORGANISATIONS}} (x TEXT);") self.assertIn("organisations", out) self.assertNotIn("{{", out) def test_every_known_table_has_a_substitution(self): - ddl = " ".join("{{TBL_" + t.upper() + "}}" - for t in runner._ENGINE_PLACEHOLDER_TABLES) + ddl = " ".join("{{TBL_" + t.upper() + "}}" for t in runner._ENGINE_PLACEHOLDER_TABLES) self.assertNotIn("{{", runner._substitute_placeholders(ddl)) def test_unknown_placeholder_survives_so_the_scenario_can_flag_it(self): @@ -281,8 +282,7 @@ def test_unknown_placeholder_survives_so_the_scenario_can_flag_it(self): def test_structure_is_read_back_from_executed_ddl(self): got = runner._sqlite_structure( - "CREATE TABLE alpha (id TEXT PRIMARY KEY, name TEXT NOT NULL);" - "CREATE TABLE beta (ref TEXT);" + "CREATE TABLE alpha (id TEXT PRIMARY KEY, name TEXT NOT NULL);CREATE TABLE beta (ref TEXT);" ) self.assertNotIn("error", got) self.assertEqual(sorted(got["tables"]), ["alpha", "beta"]) @@ -293,20 +293,17 @@ def test_invalid_ddl_is_reported_rather_than_raised(self): self.assertIn("error", got) def test_sqlite_internal_tables_are_excluded(self): - got = runner._sqlite_structure( - "CREATE TABLE t (id INTEGER PRIMARY KEY AUTOINCREMENT);" - ) + got = runner._sqlite_structure("CREATE TABLE t (id INTEGER PRIMARY KEY AUTOINCREMENT);") # AUTOINCREMENT creates sqlite_sequence; it is not part of the schema. self.assertEqual(sorted(got["tables"]), ["t"]) def test_the_real_sqlite_ddl_executes_and_matches_the_expectation_file(self): import json + root = Path(__file__).resolve().parents[2] - ddl = (root / "build" / "schema" / "sqlite" - / "te_core_schema.sql").read_text(encoding="utf-8") + ddl = (root / "build" / "schema" / "sqlite" / "te_core_schema.sql").read_text(encoding="utf-8") exp = json.loads( - (root / "evals" / "expected" / "tier_x" - / "01_sqlite_schema_structure.json").read_text(encoding="utf-8") + (root / "evals" / "expected" / "tier_x" / "01_sqlite_schema_structure.json").read_text(encoding="utf-8") )["expected"] got = runner._sqlite_structure(runner._substitute_placeholders(ddl)) @@ -318,33 +315,32 @@ def test_known_missing_tables_are_genuinely_absent(self): # these tables to the DDL but forgets to move it out of # known_missing_tables, the file would misreport the shortfall. import json + root = Path(__file__).resolve().parents[2] - ddl = (root / "build" / "schema" / "sqlite" - / "te_core_schema.sql").read_text(encoding="utf-8") + ddl = (root / "build" / "schema" / "sqlite" / "te_core_schema.sql").read_text(encoding="utf-8") exp = json.loads( - (root / "evals" / "expected" / "tier_x" - / "01_sqlite_schema_structure.json").read_text(encoding="utf-8") + (root / "evals" / "expected" / "tier_x" / "01_sqlite_schema_structure.json").read_text(encoding="utf-8") )["expected"] got = runner._sqlite_structure(runner._substitute_placeholders(ddl)) for table in exp["known_missing_tables"]: self.assertNotIn( - table, got["tables"], - f"{table} is listed as missing but the DDL now defines it — " - "move it into expected_tables", + table, + got["tables"], + f"{table} is listed as missing but the DDL now defines it — move it into expected_tables", ) def test_missing_plus_present_accounts_for_all_twelve_tables(self): import json + root = Path(__file__).resolve().parents[2] exp = json.loads( - (root / "evals" / "expected" / "tier_x" - / "01_sqlite_schema_structure.json").read_text(encoding="utf-8") + (root / "evals" / "expected" / "tier_x" / "01_sqlite_schema_structure.json").read_text(encoding="utf-8") )["expected"] total = set(exp["expected_tables"]) | set(exp["known_missing_tables"]) self.assertEqual( - total, set(runner._ENGINE_PLACEHOLDER_TABLES), - "the expectation file must account for every T&E table, so the " - "shortfall cannot be understated by omission", + total, + set(runner._ENGINE_PLACEHOLDER_TABLES), + "the expectation file must account for every T&E table, so the shortfall cannot be understated by omission", ) diff --git a/tests/unit/test_gap_registers_agree.py b/tests/unit/test_gap_registers_agree.py index da62178..4b8c361 100644 --- a/tests/unit/test_gap_registers_agree.py +++ b/tests/unit/test_gap_registers_agree.py @@ -17,6 +17,7 @@ All read the Markdown or the DDL as text; no database or network. """ + from __future__ import annotations import re @@ -58,8 +59,11 @@ def statuses() -> dict[str, str]: continue cells = [c.strip() for c in line.strip().strip("|").split("|")] # The first rows put the status after the test-coverage columns; the later (ART) rows put it second. - symbol = cells[1] if len(cells) > 1 and _SYMBOLS.match(cells[1]) else next( - (c for c in cells[3:] if _SYMBOLS.match(c)), "") + symbol = ( + cells[1] + if len(cells) > 1 and _SYMBOLS.match(cells[1]) + else next((c for c in cells[3:] if _SYMBOLS.match(c)), "") + ) text = " ".join(cells[1:]) if symbol.startswith("✅"): found[m.group(1)] = "verified" @@ -77,8 +81,11 @@ def statuses() -> dict[str, str]: def latest_headline() -> tuple[int, int, int, int]: """(total, verified, deferred, open) from the newest '**Headline (date):**' paragraph.""" text = VCRM.read_text(encoding="utf-8") - m = re.search(r"\*\*Headline \(\d{4}-\d{2}-\d{2}\):\*\*.*?\*\*(\d+) of (\d+) \(\d+ %\)\*\* are verified, " - r"(\d+) are deferred by decision, and the other (\d+) are partial or not started", text) + m = re.search( + r"\*\*Headline \(\d{4}-\d{2}-\d{2}\):\*\*.*?\*\*(\d+) of (\d+) \(\d+ %\)\*\* are verified, " + r"(\d+) are deferred by decision, and the other (\d+) are partial or not started", + text, + ) assert m, "VCRM.md has no headline in the expected shape" verified, total, deferred, still_open = (int(g) for g in m.groups()) return total, verified, deferred, still_open @@ -93,9 +100,14 @@ def test_vcrm_agrees_with_its_own_headline(): counts = Counter(statuses().values()) total, verified, deferred, still_open = latest_headline() assert (len(statuses()), counts["verified"], counts["deferred"], counts["partial"] + counts["not started"]) == ( - total, verified, deferred, still_open), ( + total, + verified, + deferred, + still_open, + ), ( f"VCRM.md's table says {dict(counts)} but its latest headline says {verified} verified, {deferred} deferred, " - f"{still_open} open of {total}: update one of them") + f"{still_open} open of {total}: update one of them" + ) def test_vcrm_gaps_lists_what_vcrm_calls_not_verified_or_says_it_is_superseded(): @@ -107,11 +119,13 @@ def test_vcrm_gaps_lists_what_vcrm_calls_not_verified_or_says_it_is_superseded() assert listed == not_verified, ( "docs/VCRM_GAPS.md says it lists the requirements that are not fully verified, but VCRM.md disagrees. " f"Only in VCRM_GAPS.md (now verified): {sorted(listed - not_verified)}. " - f"Only in VCRM.md (not verified, missing from VCRM_GAPS.md): {sorted(not_verified - listed)}.") + f"Only in VCRM.md (not verified, missing from VCRM_GAPS.md): {sorted(not_verified - listed)}." + ) # --- the registers that are not a copy of VCRM.md --------------------------------------------------------------- + def banner(path: Path) -> str: return "\n".join(path.read_text(encoding="utf-8").splitlines()[:BANNER_LINES]) @@ -121,9 +135,11 @@ def test_register_opens_with_a_pointer_to_the_document_that_owns_the_status(regi head = banner(register) assert "VCRM.md" in head, ( f"{register.name} does not name docs/VCRM.md in its first {BANNER_LINES} lines. A reader cannot tell which " - "document to trust for requirement status: add a banner that says VCRM.md is the authority.") + "document to trust for requirement status: add a banner that says VCRM.md is the authority." + ) assert re.search(r"authoritative|superseded|point-in-time|snapshot", head, re.I), ( - f"{register.name} names VCRM.md but does not say how the two relate (authoritative / superseded / snapshot).") + f"{register.name} names VCRM.md but does not say how the two relate (authoritative / superseded / snapshot)." + ) @pytest.mark.parametrize("register", REGISTERS, ids=lambda p: p.name) @@ -167,7 +183,10 @@ def ddl_table_count(engine: str) -> int: def test_engine_table_counts_in_engine_parity_todo_match_the_ddl(): rows = dict(re.findall(r"^\| \*\*(\w+)\*\* \| (\d+) \|", ENGINE_PARITY.read_text(encoding="utf-8"), re.M)) assert {"postgresql", "sqlite", "mariadb", "teradata"} <= set(rows), ( - f"ENGINE_PARITY_TODO.md's 'Measured state' table lost an engine row: {sorted(rows)}") + f"ENGINE_PARITY_TODO.md's 'Measured state' table lost an engine row: {sorted(rows)}" + ) wrong = {e: (int(n), ddl_table_count(e)) for e, n in rows.items() if int(n) != ddl_table_count(e)} - assert wrong == {}, (f"engine: (count in ENGINE_PARITY_TODO.md, CREATE TABLE statements in the DDL) = {wrong}. " - "Count with 'CREATE SET TABLE' as well as 'CREATE TABLE', and skip comment lines.") + assert wrong == {}, ( + f"engine: (count in ENGINE_PARITY_TODO.md, CREATE TABLE statements in the DDL) = {wrong}. " + "Count with 'CREATE SET TABLE' as well as 'CREATE TABLE', and skip comment lines." + ) diff --git a/tests/unit/test_image_scan_workflow.py b/tests/unit/test_image_scan_workflow.py index e5ae25e..3fa7605 100644 --- a/tests/unit/test_image_scan_workflow.py +++ b/tests/unit/test_image_scan_workflow.py @@ -8,6 +8,7 @@ * an SBOM that is written but never reaches the bundle (the bundle job must require it); * an exception in .trivyignore.yaml with no reason or no expiry date, or one that has expired. """ + from __future__ import annotations import datetime as dt @@ -108,4 +109,6 @@ def test_the_trivy_exceptions_file_documents_and_limits_every_exception(): expires = entry.get("expired_at") assert expires, f"{entry.get('id')}: an exception needs an expiry date" expires = expires if isinstance(expires, dt.date) else dt.date.fromisoformat(str(expires)) - assert expires >= dt.date.today(), f"{entry['id']} expired on {expires}: renew it with a new reason, or remove it" + assert expires >= dt.date.today(), ( + f"{entry['id']} expired on {expires}: renew it with a new reason, or remove it" + ) diff --git a/tests/unit/test_infer_type_leading_zeros.py b/tests/unit/test_infer_type_leading_zeros.py index 814e560..3db2d03 100644 --- a/tests/unit/test_infer_type_leading_zeros.py +++ b/tests/unit/test_infer_type_leading_zeros.py @@ -11,6 +11,7 @@ * the preview a user confirms shows ``text`` for such a column, so the value loads as it was typed; * ``cast_value`` for a text column keeps the original characters. """ + from __future__ import annotations import sys @@ -25,28 +26,34 @@ from api.services import csv_parse as cp # noqa: E402 -@pytest.mark.parametrize("values", [ - ["007", "012", "100"], # the leading zero is on some values only - ["02134", "90210"], # US postcode - ["0412345678", "0498765432"], # AU mobile numbers - ["000123", "000124"], # padded account numbers - ["00", "01"], - ["-007", "5"], # a sign does not hide the padding - ["007.5", "1.5"], # padding before a decimal part is still padding -]) +@pytest.mark.parametrize( + "values", + [ + ["007", "012", "100"], # the leading zero is on some values only + ["02134", "90210"], # US postcode + ["0412345678", "0498765432"], # AU mobile numbers + ["000123", "000124"], # padded account numbers + ["00", "01"], + ["-007", "5"], # a sign does not hide the padding + ["007.5", "1.5"], # padding before a decimal part is still padding + ], +) def test_a_zero_padded_whole_number_makes_the_column_text(values): assert cp.infer_type(values) == "text", values -@pytest.mark.parametrize("values, expected", [ - (["0"], "int8"), # a single zero is a number - (["0", "10", "-5"], "int8"), - (["10", "100", "1000"], "int8"), # trailing zeros are not padding - (["0.5", "0.25"], "numeric"), # a zero before a decimal point is not padding - (["-0.25", "1.10"], "numeric"), - (["1", "2", ""], "int8"), # blanks are ignored as before - ([], "text"), -]) +@pytest.mark.parametrize( + "values, expected", + [ + (["0"], "int8"), # a single zero is a number + (["0", "10", "-5"], "int8"), + (["10", "100", "1000"], "int8"), # trailing zeros are not padding + (["0.5", "0.25"], "numeric"), # a zero before a decimal point is not padding + (["-0.25", "1.10"], "numeric"), + (["1", "2", ""], "int8"), # blanks are ignored as before + ([], "text"), + ], +) def test_ordinary_numbers_are_still_numbers(values, expected): assert cp.infer_type(values) == expected, values diff --git a/tests/unit/test_infra_private_access.py b/tests/unit/test_infra_private_access.py index be3ff80..ccc1afb 100644 --- a/tests/unit/test_infra_private_access.py +++ b/tests/unit/test_infra_private_access.py @@ -4,6 +4,7 @@ defaults to false in every environment. A literal `public_network_access_enabled = true` would leave the secrets store or registry internet-reachable if the manual flip were forgotten. """ + import re from pathlib import Path @@ -16,10 +17,12 @@ def test_no_terraform_file_hardcodes_public_network_access(): - offenders = [f"{p.relative_to(ROOT)}:{n}" - for p in (ROOT / "infra").rglob("*.tf") - for n, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1) - if re.search(r"public_network_access_enabled\s*=\s*true\b", line)] + offenders = [ + f"{p.relative_to(ROOT)}:{n}" + for p in (ROOT / "infra").rglob("*.tf") + for n, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1) + if re.search(r"public_network_access_enabled\s*=\s*true\b", line) + ] assert offenders == [] diff --git a/tests/unit/test_issue_322_security_findings.py b/tests/unit/test_issue_322_security_findings.py index 2f33713..e69f320 100644 --- a/tests/unit/test_issue_322_security_findings.py +++ b/tests/unit/test_issue_322_security_findings.py @@ -12,6 +12,7 @@ one JUnit XML parse of a file the script itself had pytest write, and the two string-built DO blocks in the migration, whose identifiers are quoted by the dialect. """ + from __future__ import annotations import importlib.util diff --git a/tests/unit/test_lint_scope.py b/tests/unit/test_lint_scope.py index ffeca11..fb6dde0 100644 --- a/tests/unit/test_lint_scope.py +++ b/tests/unit/test_lint_scope.py @@ -13,6 +13,7 @@ Policy pinned here: flake8 checks every tracked .py file; bandit checks every tracked .py file except test code (tests/ and e2e/), where its findings are about fixtures and asserts. """ + from __future__ import annotations import shutil @@ -60,7 +61,8 @@ def test_flake8_scope_is_every_tracked_python_file(): tracked, linted, excluded = tracked_python(), listed("--list-files"), listed("--list-excluded") assert tracked - linted - excluded == set(), ( f"tracked Python files that no lint run checks (and that are not in LINT_EXCLUDE): " - f"{short(tracked - linted - excluded)}") + f"{short(tracked - linted - excluded)}" + ) assert linted - tracked == set(), f"lint.sh lists files git does not track: {short(linted - tracked)}" @@ -112,8 +114,7 @@ def test_a_new_tracked_file_with_a_style_error_fails_the_lint(scratch_repo): def test_a_new_tracked_file_with_a_security_finding_fails_the_lint(scratch_repo): repo, add = scratch_repo - add("api/fetch.py", - "import urllib.request\n\n\ndef get(url):\n return urllib.request.urlopen(url)\n") # B310 + add("api/fetch.py", "import urllib.request\n\n\ndef get(url):\n return urllib.request.urlopen(url)\n") # B310 result = lint_in(repo) assert result.returncode != 0, "a source file nobody listed was not scanned by bandit" assert "B310" in result.stdout + result.stderr, result.stdout[-600:] @@ -133,8 +134,10 @@ def test_test_code_is_style_checked_but_not_security_scanned(scratch_repo): def test_test_code_in_a_package_folder_is_also_not_security_scanned(scratch_repo): """csv_loader/tests/ is test code like tests/: its fixtures build SQL and temp paths on purpose (bandit B608, B108).""" repo, add = scratch_repo - add("csv_loader/tests/test_fetch.py", - "import urllib.request\n\n\ndef test_x(url):\n return urllib.request.urlopen(url)\n") # B310 in a fixture + add( + "csv_loader/tests/test_fetch.py", + "import urllib.request\n\n\ndef test_x(url):\n return urllib.request.urlopen(url)\n", + ) # B310 in a fixture assert lint_in(repo).returncode == 0, "bandit should not scan a tests/ folder inside a package" add("csv_loader/tests/test_unused.py", "import os\n") # but flake8 does result = lint_in(repo) diff --git a/tests/unit/test_load_common.py b/tests/unit/test_load_common.py index ec3b20f..c13c20c 100644 --- a/tests/unit/test_load_common.py +++ b/tests/unit/test_load_common.py @@ -21,12 +21,15 @@ # ── load_common ───────────────────────────────────────────────────────────────────────────────────────────────── + def test_log_adds_a_count_only_when_given(): logs: list[dict] = [] lc.log(logs, "parse", "Parsed 3 rows", count=3) lc.log(logs, "error", "bad", "error") assert [(e["step"], e["level"], e["message"], e.get("count")) for e in logs] == [ - ("parse", "info", "Parsed 3 rows", 3), ("error", "error", "bad", None)] + ("parse", "info", "Parsed 3 rows", 3), + ("error", "error", "bad", None), + ] assert "count" not in logs[1] and all(isinstance(e["ts"], int) for e in logs) @@ -37,8 +40,10 @@ def test_row_errors_count_every_failure_but_keep_only_the_cap(monkeypatch): errors.add(n, "qty", "x", "not a number") errors.add_db_error(6, "violates foreign key") assert errors.failed == 6 - assert errors.items == [{"rowNumber": 1, "column": "qty", "value": "x", "reason": "not a number"}, - {"rowNumber": 2, "column": "qty", "value": "x", "reason": "not a number"}] + assert errors.items == [ + {"rowNumber": 1, "column": "qty", "value": "x", "reason": "not a number"}, + {"rowNumber": 2, "column": "qty", "value": "x", "reason": "not a number"}, + ] assert errors.first() == errors.items[0] @@ -80,8 +85,19 @@ def test_the_rows_failed_response_keeps_its_field_order(): def test_the_ok_result_keeps_its_field_order(): res = lc.ok_result(7, "t", 3, 2, 1, 0, ["a"], ["text"], rowErrors=[], logs=[]) assert res["fileId"] == "7" - assert list(res) == ["status", "fileId", "tableName", "totalRows", "insertedRows", "duplicateRowsSkipped", - "failedRows", "columns", "types", "rowErrors", "logs"] + assert list(res) == [ + "status", + "fileId", + "tableName", + "totalRows", + "insertedRows", + "duplicateRowsSkipped", + "failedRows", + "columns", + "types", + "rowErrors", + "logs", + ] def _stmt(text): @@ -129,6 +145,7 @@ def test_batches_are_chunked(): # ── dynamic loader ────────────────────────────────────────────────────────────────────────────────────────────── + def test_the_row_hash_is_unambiguous(): """#178: a join on U+001F made these two rows hash the same.""" assert dyn.row_hash(["a\x1fb", "c"]) != dyn.row_hash(["a", "b\x1fc"]) @@ -167,10 +184,13 @@ def test_header_renames_are_applied_or_refused(): # sanitize_columns names blank headers and de-duplicates (a, A -> a, a_2), so only the types can be refused here. -@pytest.mark.parametrize("header, types, message", [ - (["a", "b"], ["text"], "Provided 1 column types but the CSV has 2 columns."), - (["a"], ["money"], "Unsupported column type provided."), -]) +@pytest.mark.parametrize( + "header, types, message", + [ + (["a", "b"], ["text"], "Provided 1 column types but the CSV has 2 columns."), + (["a"], ["money"], "Unsupported column type provided."), + ], +) def test_unusable_columns_or_types_are_refused(header, types, message): res = dyn._columns_and_types(header, types, []) assert isinstance(res, dict) and res["status"] == "error" and message in res["message"] @@ -186,13 +206,15 @@ def test_the_every_row_failed_message_names_the_first_problem(): errors = lc.RowErrors() errors.add(2, "qty", "x", "not an integer") res = dyn._every_row_failed(errors, 2, ["qty"], ["int8"], []) - assert res["message"] == ('None of the 2 rows could be imported, so nothing was saved. ' - 'First problem: row 2, column "qty": not an integer') + assert res["message"] == ( + 'None of the 2 rows could be imported, so nothing was saved. First problem: row 2, column "qty": not an integer' + ) assert (res["columns"], res["types"]) == (["qty"], ["int8"]) # ── T&E loader ────────────────────────────────────────────────────────────────────────────────────────────────── + def test_te_rows_are_stripped_and_empty_cells_are_null(): errors = lc.RowErrors() rows = [[" 5 ", "", " x "], ["oops", "1", "y"], ["1", "2", "3", "4"]] diff --git a/tests/unit/test_makefile_categories.py b/tests/unit/test_makefile_categories.py index 8672985..52a6d7e 100644 --- a/tests/unit/test_makefile_categories.py +++ b/tests/unit/test_makefile_categories.py @@ -4,6 +4,7 @@ category, so a renamed folder, a wrong path or a changed marker made `make test-` pass without running a test. Now only the categories named in `EMPTY_CATEGORIES` may be empty. """ + from __future__ import annotations import os diff --git a/tests/unit/test_offline_streamlit_packaging.py b/tests/unit/test_offline_streamlit_packaging.py index 132fff6..bcb9e0a 100644 --- a/tests/unit/test_offline_streamlit_packaging.py +++ b/tests/unit/test_offline_streamlit_packaging.py @@ -10,6 +10,7 @@ * smoke_test.sh checks /_stcore/health, and a Streamlit that does not answer "ok" is a FAIL; * docs/offline-install.md lists exactly the PASS lines the smoke test prints. """ + from __future__ import annotations import os @@ -53,9 +54,14 @@ def test_both_wheel_sets_use_one_set_of_flags(self): def test_the_flags_pin_cpython_312_manylinux_x86_64_binary_only(self): flags = re.search(r"WHEEL_FLAGS=\((.*?)\)", BUILD, re.S).group(1) - for flag in ("--only-binary=:all:", "--python-version 3.12", "--implementation cp", - "--platform manylinux2014_x86_64", "--platform manylinux_2_17_x86_64", - "--platform manylinux_2_28_x86_64"): + for flag in ( + "--only-binary=:all:", + "--python-version 3.12", + "--implementation cp", + "--platform manylinux2014_x86_64", + "--platform manylinux_2_17_x86_64", + "--platform manylinux_2_28_x86_64", + ): with self.subTest(flag=flag): self.assertIn(flag, flags) @@ -72,9 +78,12 @@ class InstallAddsTheStreamlitService(unittest.TestCase): API_ENV = heredoc(INSTALL, '"$DEST/env"') def test_the_venv_is_built_offline_from_the_bundle(self): - self.assertRegex(INSTALL, r'streamlit-venv/bin/pip" install -q --no-index --find-links "\$BUNDLE/wheels" ' - r'--require-hashes --no-deps \\\n' - r'\s+-r "\$DEST/app/streamlit_app/requirements\.lock"') + self.assertRegex( + INSTALL, + r'streamlit-venv/bin/pip" install -q --no-index --find-links "\$BUNDLE/wheels" ' + r"--require-hashes --no-deps \\\n" + r'\s+-r "\$DEST/app/streamlit_app/requirements\.lock"', + ) def test_the_unit_runs_streamlit_from_streamlit_app(self): self.assertRegex(self.UNIT, r"(?m)^ExecStart=\$DEST/streamlit-venv/bin/python -m streamlit run app\.py ") @@ -139,10 +148,16 @@ def _fake_bin(d: Path, st_health: str) -> Path: class SmokeTestChecksStreamlit(unittest.TestCase): def _run(self, st_health: str) -> subprocess.CompletedProcess: with tempfile.TemporaryDirectory() as d: - env = {**os.environ, "PATH": f"{_fake_bin(Path(d), st_health)}:{os.environ['PATH']}", - "SMOKE_TENANT": "main", "SMOKE_USER": "admin", "SMOKE_PASSWORD": "pw"} - return subprocess.run(["bash", str(OFFLINE / "smoke_test.sh")], capture_output=True, text=True, - env=env, timeout=60) + env = { + **os.environ, + "PATH": f"{_fake_bin(Path(d), st_health)}:{os.environ['PATH']}", + "SMOKE_TENANT": "main", + "SMOKE_USER": "admin", + "SMOKE_PASSWORD": "pw", + } + return subprocess.run( + ["bash", str(OFFLINE / "smoke_test.sh")], capture_output=True, text=True, env=env, timeout=60 + ) def test_a_healthy_streamlit_passes(self): res = self._run("ok") @@ -166,7 +181,7 @@ class GuideMatchesTheSmokeTest(unittest.TestCase): def test_the_guide_lists_exactly_the_pass_lines_the_smoke_test_prints(self): printed = re.findall(r'pass "([^"]+)"', SMOKE) block = re.search(r"```\n(PASS .*?)\n```", GUIDE, re.S).group(1) - self.assertEqual([ln[len("PASS "):] for ln in block.splitlines()], printed) + self.assertEqual([ln[len("PASS ") :] for ln in block.splitlines()], printed) def test_the_guide_gives_the_number_of_pass_lines(self): n = len(re.findall(r'pass "([^"]+)"', SMOKE)) diff --git a/tests/unit/test_oidc_https_jwks.py b/tests/unit/test_oidc_https_jwks.py index 41c739b..a72c72a 100644 --- a/tests/unit/test_oidc_https_jwks.py +++ b/tests/unit/test_oidc_https_jwks.py @@ -49,16 +49,27 @@ def _self_signed(directory: Path) -> tuple[Path, Path]: key = _rsa() name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")]) now = datetime.datetime.now(datetime.timezone.utc) - cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key()) - .serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(minutes=5)) - .not_valid_after(now + datetime.timedelta(days=1)) - .add_extension(x509.SubjectAlternativeName( - [x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), critical=False) - .sign(key, hashes.SHA256())) + cert = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(minutes=5)) + .not_valid_after(now + datetime.timedelta(days=1)) + .add_extension( + x509.SubjectAlternativeName([x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), + critical=False, + ) + .sign(key, hashes.SHA256()) + ) cert_path, key_path = directory / "cert.pem", directory / "key.pem" cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM)) - key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, - serialization.NoEncryption())) + key_path.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption() + ) + ) return cert_path, key_path @@ -152,7 +163,9 @@ def test_a_certificate_that_is_not_trusted_is_refused(self): os.environ["SSL_CERT_FILE"] = str(stranger) try: oidc._jwks.cache_clear() - self.assertIsNone(oidc.username_from(self._token(self.keys["key-1"], "key-1")), - "a JWKS endpoint whose certificate isn't trusted must not yield a session") + self.assertIsNone( + oidc.username_from(self._token(self.keys["key-1"], "key-1")), + "a JWKS endpoint whose certificate isn't trusted must not yield a session", + ) finally: os.environ["SSL_CERT_FILE"] = trusted diff --git a/tests/unit/test_open_issues.py b/tests/unit/test_open_issues.py index 78a0ae5..aaa8727 100644 --- a/tests/unit/test_open_issues.py +++ b/tests/unit/test_open_issues.py @@ -68,8 +68,9 @@ def test_the_build_and_install_scripts_stop_on_the_first_error(self): # smoke_test.sh is excluded on purpose: it counts PASS/FAIL checks and exits non-zero at the end. for name in ("build_bundle.sh", "install.sh"): with self.subTest(script=name): - self.assertRegex((ROOT / "scripts/offline" / name).read_text(encoding="utf-8"), - r"(?m)^set -euo pipefail") + self.assertRegex( + (ROOT / "scripts/offline" / name).read_text(encoding="utf-8"), r"(?m)^set -euo pipefail" + ) def test_the_guide_names_the_scripts_it_relies_on(self): for name in ("build_bundle.sh", "install.sh"): diff --git a/tests/unit/test_password_hash_cost.py b/tests/unit/test_password_hash_cost.py index 55e74ac..82a4e63 100644 --- a/tests/unit/test_password_hash_cost.py +++ b/tests/unit/test_password_hash_cost.py @@ -16,6 +16,7 @@ failed sign-in having paid for one current-cost hash, and the dummy hash has the current cost; * at most ``MAX_CONCURRENT_HASHES`` hashes are computed at once, so a burst of sign-ins cannot hold 128 MiB each. """ + from __future__ import annotations import datetime as dt @@ -49,6 +50,7 @@ def params(stored: str) -> tuple[int, int, int]: # -- the cost, and what still verifies -------------------------------------------------------------------------------- + def test_new_hashes_use_the_current_cost(): stored = accounts.hash_password(PW) assert stored.startswith("scrypt$131072$8$1$"), stored @@ -80,6 +82,7 @@ def test_a_stored_hash_asking_for_too_much_memory_is_refused_at_once(): # -- needs_rehash ----------------------------------------------------------------------------------------------------- + def test_needs_rehash_is_true_for_a_weaker_hash(): assert accounts.needs_rehash(legacy_hash()) is True assert accounts.needs_rehash(legacy_hash(n=2**16)) is True @@ -95,6 +98,7 @@ def test_needs_rehash_is_false_for_a_current_or_stronger_hash_and_for_junk(): # -- login, with a fake cursor ---------------------------------------------------------------------------------------- + class FakeCursor: """Answers the queries ``accounts.login`` runs and records every statement and its parameters.""" @@ -155,7 +159,8 @@ def test_the_upgrade_only_applies_if_the_stored_hash_is_still_the_one_checked(sc accounts.login(cur, "acme", "alice", PW) sql, _ = cur.password_updates()[0] assert "password_hash = %s" in sql and sql.count("password_hash") >= 2, ( - "UPDATE ... WHERE id = %s AND password_hash = %s, so a password changed meanwhile is not undone: " + sql) + "UPDATE ... WHERE id = %s AND password_hash = %s, so a password changed meanwhile is not undone: " + sql + ) def test_signing_in_with_a_current_hash_stores_nothing(scrypt_costs): @@ -164,12 +169,15 @@ def test_signing_in_with_a_current_hash_stores_nothing(scrypt_costs): assert cur.password_updates() == [] -@pytest.mark.parametrize("case, row_kw, password", [ - ("wrong password", {}, "not the password"), - ("inactive user", {"active": False}, PW), - ("not a member", {"role": None}, PW), - ("locked account", {"locked": True}, PW), -]) +@pytest.mark.parametrize( + "case, row_kw, password", + [ + ("wrong password", {}, "not the password"), + ("inactive user", {"active": False}, PW), + ("not a member", {"role": None}, PW), + ("locked account", {"locked": True}, PW), + ], +) def test_a_refused_sign_in_never_upgrades_a_hash(scrypt_costs, case, row_kw, password): cur = FakeCursor(user_row(legacy_hash(), **row_kw)) assert accounts.login(cur, "acme", "alice", password) is None, case @@ -178,6 +186,7 @@ def test_a_refused_sign_in_never_upgrades_a_hash(scrypt_costs, case, row_kw, pas # -- no new timing oracle --------------------------------------------------------------------------------------------- + def failed_sign_in_costs(scrypt_costs, row) -> list[int]: scrypt_costs.clear() assert accounts.login(FakeCursor(row), "acme", "alice", "wrong password entirely") is None @@ -192,11 +201,13 @@ def test_a_failed_sign_in_pays_one_current_cost_hash_whoever_the_user_is(scrypt_ assert current_user == [CURRENT[0]], current_user assert CURRENT[0] in old_user, ( "a user whose hash is old must not fail faster than an unknown one (that tells an attacker the name exists): " - f"{old_user}") + f"{old_user}" + ) # -- bounded memory --------------------------------------------------------------------------------------------------- + def test_no_more_than_the_limit_of_hashes_run_at_once(monkeypatch): active = peak = 0 lock = threading.Lock() diff --git a/tests/unit/test_pg_login.py b/tests/unit/test_pg_login.py index f19f1e1..53aceec 100644 --- a/tests/unit/test_pg_login.py +++ b/tests/unit/test_pg_login.py @@ -14,6 +14,7 @@ No database needed: psycopg2.connect is monkeypatched, and so is the reachability probe except in the tests of the probe itself, which use a socket on the loopback interface. """ + import os import re import socket @@ -30,10 +31,14 @@ REAL_SERVER_AVAILABLE = pg_login.server_available # the autouse fixture below replaces it SECRET = "p4ss=w0rd with 'quotes' and =signs" # '=' and spaces: the awkward cases for KEY=VALUE -REFUSED_MSG = ('connection to server at "localhost" (::1), port 5433 failed: ' - 'FATAL: password authentication failed for user "postgres"') -UNREACHABLE_MSG = ('connection to server at "localhost" (::1), port 5433 failed: Connection refused\n' - '\tIs the server running on that host and accepting TCP/IP connections?') +REFUSED_MSG = ( + 'connection to server at "localhost" (::1), port 5433 failed: ' + 'FATAL: password authentication failed for user "postgres"' +) +UNREACHABLE_MSG = ( + 'connection to server at "localhost" (::1), port 5433 failed: Connection refused\n' + "\tIs the server running on that host and accepting TCP/IP connections?" +) class _Conn: @@ -84,15 +89,28 @@ def _saved(tmp_path, env="dev"): # ── save ────────────────────────────────────────────────────────────────────────────────── + def test_save_checks_the_login_then_writes_all_four_values(connects, monkeypatch, tmp_path, capsys): monkeypatch.setenv("TE_PG_PASSWORD", SECRET) assert pg_login.main(["save"]) == 0 - assert connects == [{"host": "localhost", "port": "5433", "user": "postgres", "password": SECRET, - "dbname": "postgres", "connect_timeout": 5}] + assert connects == [ + { + "host": "localhost", + "port": "5433", + "user": "postgres", + "password": SECRET, + "dbname": "postgres", + "connect_timeout": 5, + } + ] assert pg_login.read_env_file(_saved(tmp_path)) == { - "PGHOST": "localhost", "PGPORT": "5433", "PGUSER": "postgres", "PGPASSWORD": SECRET} + "PGHOST": "localhost", + "PGPORT": "5433", + "PGUSER": "postgres", + "PGPASSWORD": SECRET, + } out = capsys.readouterr() assert SECRET not in out.out + out.err, "the password is never printed" assert "dev-env.ps1" in out.out, "it says how to load the login into a window" @@ -160,7 +178,11 @@ def test_from_env_takes_the_whole_login_from_the_pg_variables_without_asking(con assert pg_login.main(["save", "--from-env"]) == 0 assert pg_login.read_env_file(_saved(tmp_path)) == { - "PGHOST": "db.example.test", "PGPORT": "6543", "PGUSER": "alice", "PGPASSWORD": SECRET} + "PGHOST": "db.example.test", + "PGPORT": "6543", + "PGUSER": "alice", + "PGPASSWORD": SECRET, + } def test_flags_override_the_variables_which_override_the_defaults(connects, monkeypatch): @@ -189,7 +211,8 @@ def getpass(prompt): @pytest.mark.parametrize("password", ["", "line\nbreak"]) def test_an_empty_password_or_one_with_a_line_break_is_refused_before_anything_is_tried( - connects, monkeypatch, tmp_path, password): + connects, monkeypatch, tmp_path, password +): monkeypatch.setattr(pg_login.getpass, "getpass", lambda *a, **k: password) assert pg_login.main(["save"]) == 2 @@ -211,6 +234,7 @@ def test_an_unknown_environment_is_rejected(): # ── check ───────────────────────────────────────────────────────────────────────────────── + def test_check_exits_0_when_the_login_works(connects, monkeypatch, capsys): monkeypatch.setenv("PGPASSWORD", SECRET) @@ -243,20 +267,26 @@ def test_check_exits_3_when_the_server_cannot_be_reached(monkeypatch, capsys): assert "Traceback" not in err -@pytest.mark.parametrize("message", [ - 'connection to server at "localhost" (::1), port 5433 failed: FATAL: role "ghost" does not exist', - 'connection to server at "localhost" (::1), port 5433 failed: FATAL: database "x" does not exist', - 'connection to server at "h", port 5432 failed: FATAL: no pg_hba.conf entry for host "1.2.3.4"', -]) +@pytest.mark.parametrize( + "message", + [ + 'connection to server at "localhost" (::1), port 5433 failed: FATAL: role "ghost" does not exist', + 'connection to server at "localhost" (::1), port 5433 failed: FATAL: database "x" does not exist', + 'connection to server at "h", port 5432 failed: FATAL: no pg_hba.conf entry for host "1.2.3.4"', + ], +) def test_other_rejections_are_refusals_too(monkeypatch, message): _fails(monkeypatch, message) assert pg_login.main(["check"]) == 2 -@pytest.mark.parametrize("message", [ - 'connection to server at "db", port 5432 failed: FATAL: the database system is starting up', - 'connection to server at "db", port 5432 failed: timeout expired', -]) +@pytest.mark.parametrize( + "message", + [ + 'connection to server at "db", port 5432 failed: FATAL: the database system is starting up', + 'connection to server at "db", port 5432 failed: timeout expired', + ], +) def test_a_server_that_is_still_starting_or_slow_is_not_a_refusal(monkeypatch, message): _fails(monkeypatch, message) assert pg_login.main(["check"]) == 3 @@ -269,6 +299,7 @@ def test_check_uses_the_login_defaults_when_nothing_is_set(connects): # ── the server is looked for first ──────────────────────────────────────────────────────── + def test_save_with_no_server_asks_for_no_password_tries_none_and_saves_nothing(monkeypatch, tmp_path, capsys): _server_down(monkeypatch) # getpass and psycopg2.connect both fail the test if reached @@ -333,7 +364,7 @@ def test_check_with_no_server_exits_3_without_trying_the_login(monkeypatch, caps def test_check_server_only_needs_no_password_and_tries_none(monkeypatch, capsys): monkeypatch.setattr(psycopg2, "connect", lambda **k: pytest.fail("tried a login")) - assert pg_login.main(["check", "--server-only"]) == 0 # no PGPASSWORD set at all + assert pg_login.main(["check", "--server-only"]) == 0 # no PGPASSWORD set at all assert "accepting connections at localhost:5433" in capsys.readouterr().out @@ -363,7 +394,7 @@ def test_the_probe_finds_a_listening_socket(): def test_the_probe_reports_a_port_nothing_listens_on(): with socket.socket() as s: s.bind(("127.0.0.1", 0)) - port = s.getsockname()[1] # free again once the socket is closed + port = s.getsockname()[1] # free again once the socket is closed up, why = REAL_SERVER_AVAILABLE("127.0.0.1", str(port), timeout=2) @@ -385,6 +416,7 @@ def test_a_unix_socket_directory_is_left_to_the_login_attempt(): # ── where ───────────────────────────────────────────────────────────────────────────────── + def test_where_says_when_nothing_is_saved(capsys): assert pg_login.main(["where"]) == 0 assert "No saved login for dev" in capsys.readouterr().out @@ -404,6 +436,7 @@ def test_where_shows_the_path_and_what_it_holds_but_never_the_password(connects, # ── the file format PowerShell reads ────────────────────────────────────────────────────── + def test_the_file_round_trips_a_password_with_equals_signs_spaces_and_quotes(tmp_path): path = tmp_path / "f.env" login = {"PGHOST": "h", "PGPORT": "5433", "PGUSER": "u", "PGPASSWORD": SECRET} @@ -459,8 +492,9 @@ def test_the_powershell_scripts_read_the_file_pg_login_writes(script): def test_dev_env_never_uses_exit_because_it_is_dot_sourced(): """`exit` in a dot-sourced script closes the window it was sourced into.""" - code = "\n".join(line for line in DEV_ENV.read_text(encoding="ascii").splitlines() - if not line.lstrip().startswith("#")) + code = "\n".join( + line for line in DEV_ENV.read_text(encoding="ascii").splitlines() if not line.lstrip().startswith("#") + ) assert not re.search(r"(?m)^\s*exit\b", code) assert re.search(r"(?m)^\s*return\b", code) @@ -478,7 +512,7 @@ def test_start_api_acts_on_the_exit_codes_pg_login_check_documents(): def test_start_api_looks_for_the_server_before_it_asks_for_a_password(): """With PostgreSQL down, no password can work: it must not ask for one first.""" code = START_API.read_text(encoding="ascii") - probe = code.index("python $pgLogin check --server-only") # the command, not the comment + probe = code.index("python $pgLogin check --server-only") # the command, not the comment prompt = code.index("PGPASSWORD not set - enter it now") login_check = code.index("python $pgLogin check\n") diff --git a/tests/unit/test_preflight_ps1.py b/tests/unit/test_preflight_ps1.py index e35d1bd..5b7c8d6 100644 --- a/tests/unit/test_preflight_ps1.py +++ b/tests/unit/test_preflight_ps1.py @@ -10,6 +10,7 @@ preventing CI 'unmet prerequisites must FAIL, not skip' gate failures). Verification method (ASDEFCON): Inspection (static), Test (Windows run). """ + import os import re import shutil @@ -33,7 +34,7 @@ def _code_only(text: str) -> str: while i < len(text): ch = text[i] if quote: - if quote == '"' and ch == "`": # backtick escape in "..." + if quote == '"' and ch == "`": # backtick escape in "..." i += 2 continue if ch == quote: @@ -44,7 +45,7 @@ def _code_only(text: str) -> str: elif ch in ("'", '"'): quote = ch out.append(ch) - elif ch == "#": # comment to end of line + elif ch == "#": # comment to end of line while i < len(text) and text[i] != "\n": i += 1 continue @@ -74,7 +75,11 @@ def _run(args, extra_env=None, drop_env=(), timeout=180): env.update(extra_env or {}) return subprocess.run( [WINDOWS_PS, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), *args], - cwd=ROOT, env=env, capture_output=True, text=True, timeout=timeout, + cwd=ROOT, + env=env, + capture_output=True, + text=True, + timeout=timeout, ) @@ -122,8 +127,7 @@ def test_port_label_is_not_hardcoded(raw): @pytest.mark.regression def test_connection_defaults_resolved_once_and_reused(code): """Defaults live in variables; connection commands must use them.""" - for var, env in [("pgHost", "PGHOST"), ("pgPort", "PGPORT"), - ("pgUser", "PGUSER"), ("pgDb", "PGDATABASE")]: + for var, env in [("pgHost", "PGHOST"), ("pgPort", "PGPORT"), ("pgUser", "PGUSER"), ("pgDb", "PGDATABASE")]: assert re.search(rf"\${var}\s*=\s*if\s*\(\$env:{env}\)", code), f"${var} default missing" assert re.search(r"Test-NetConnection\s+-ComputerName\s+\$pgHost\s+-Port\s+\$pgPort", code) assert re.search(r"psql\s+-h\s+\$pgHost\s+-p\s+\$pgPort\s+-U\s+\$pgUser\s+-d\s+\$pgDb", code) @@ -158,6 +162,7 @@ def test_exit_code_contract_documented_and_implemented(raw): # Conditioned at collection time so non-Windows runners never register or skip # these tests, avoiding failure against the zero-skip CI accounting policy. if WINDOWS_PS is not None: + @pytest.mark.regression def test_parses_under_windows_powershell(): """Parse with the real PowerShell parser (5.1 on stock Windows).""" @@ -168,7 +173,10 @@ def test_parses_under_windows_powershell(): ) r = subprocess.run( [WINDOWS_PS, "-NoProfile", "-Command", cmd], - env={**os.environ, "PF_PATH": str(SCRIPT)}, capture_output=True, text=True, timeout=60, + env={**os.environ, "PF_PATH": str(SCRIPT)}, + capture_output=True, + text=True, + timeout=60, ) assert r.returncode == 0, f"Parse errors:\n{r.stdout}{r.stderr}" @@ -179,8 +187,9 @@ def test_runs_with_skippg_and_reports_summary(): assert r.returncode in (0, 1, 2), out assert "Summary:" in r.stdout, out assert "ParserError" not in out, out - assert "PostgreSQL" not in r.stdout.split("Git state")[-1].split("Summary:")[0], \ + assert "PostgreSQL" not in r.stdout.split("Git state")[-1].split("Summary:")[0], ( "-SkipPg must skip the PostgreSQL section" + ) @pytest.mark.regression def test_default_port_label_when_pgport_unset(): diff --git a/tests/unit/test_preflight_sh_without_timeout.py b/tests/unit/test_preflight_sh_without_timeout.py index 878f4d0..f7563b2 100644 --- a/tests/unit/test_preflight_sh_without_timeout.py +++ b/tests/unit/test_preflight_sh_without_timeout.py @@ -12,6 +12,7 @@ `tooling` only: these run bash, and the Windows job's `bash` is WSL's, with no distribution installed. """ + from __future__ import annotations import re @@ -55,8 +56,9 @@ def path_dir(tmp_path: Path, *, gtimeout: bool = False, timeout: bool = False) - def run_preflight(path: str, host: str, port: int) -> str: env = {"PATH": path, "HOME": str(Path.home()), "PGHOST": host, "PGPORT": str(port)} - done = subprocess.run([shutil.which("bash"), str(SCRIPT)], cwd=ROOT, env=env, capture_output=True, text=True, - timeout=120) + done = subprocess.run( + [shutil.which("bash"), str(SCRIPT)], cwd=ROOT, env=env, capture_output=True, text=True, timeout=120 + ) return done.stdout @@ -78,11 +80,12 @@ def listening_port(): def closed_port(): with closing(socket.socket()) as probe: probe.bind(("127.0.0.1", 0)) - return probe.getsockname()[1] # closed again as soon as the block ends + return probe.getsockname()[1] # closed again as soon as the block ends # -- the real script, on a PATH like stock macOS --------------------------------------------------------------------- + def test_an_open_port_is_reachable_with_no_timeout_command(tmp_path, listening_port): assert port_line(run_preflight(path_dir(tmp_path), "127.0.0.1", listening_port), listening_port) == "PASS" @@ -105,6 +108,7 @@ def test_an_open_port_is_still_reachable_with_the_gnu_timeout(tmp_path, listenin # -- with_timeout itself --------------------------------------------------------------------------------------------- + def helper() -> str: text = SCRIPT.read_text(encoding="utf-8") match = re.search(r"^with_timeout\(\) \{.*?^\}\n", text, re.DOTALL | re.MULTILINE) @@ -114,8 +118,13 @@ def helper() -> str: def with_timeout(path: str, *args: str) -> tuple[int, float]: started = time.monotonic() - done = subprocess.run([shutil.which("bash"), "-c", helper() + '\nwith_timeout "$@"', "_", *args], - env={"PATH": path}, capture_output=True, text=True, timeout=60) + done = subprocess.run( + [shutil.which("bash"), "-c", helper() + '\nwith_timeout "$@"', "_", *args], + env={"PATH": path}, + capture_output=True, + text=True, + timeout=60, + ) return done.returncode, time.monotonic() - started diff --git a/tests/unit/test_preview_fast_path.py b/tests/unit/test_preview_fast_path.py index 8d15b69..4364c60 100644 --- a/tests/unit/test_preview_fast_path.py +++ b/tests/unit/test_preview_fast_path.py @@ -17,12 +17,14 @@ def reference_preview(text: str, sample_rows: int = 10, infer_rows: int = 200) -> dict: """The preview as it was before M7: parse everything, then slice.""" - with patch.object(csv_parse, "_FAST_PREVIEW_CHARS", 10 ** 12): + with patch.object(csv_parse, "_FAST_PREVIEW_CHARS", 10**12): return build_preview(text, sample_rows, infer_rows) def big(rows: int, tail: str = "") -> str: - return "id,name,amount,when\n" + "".join(f"{i},Name {i},{i}.5,2026-01-{i % 28 + 1:02d}\n" for i in range(rows)) + tail + return ( + "id,name,amount,when\n" + "".join(f"{i},Name {i},{i}.5,2026-01-{i % 28 + 1:02d}\n" for i in range(rows)) + tail + ) @pytest.mark.unit @@ -60,11 +62,14 @@ def test_a_file_that_ends_in_blank_lines_matches_the_full_parse(self): self.assertGreater(len(text), csv_parse._FAST_PREVIEW_CHARS) with patch.object(csv_parse, "parse_csv", wraps=parse_csv) as spy: self.assertEqual(self.assertSamePreview(text, exact_count=False)[0], 150) - self.assertIn(((text,), {}), [(c.args, c.kwargs) for c in spy.call_args_list], - "the head ended in blank lines, so the whole file is parsed") + self.assertIn( + ((text,), {}), + [(c.args, c.kwargs) for c in spy.call_args_list], + "the head ended in blank lines, so the whole file is parsed", + ) def test_a_head_that_ends_in_blank_lines_falls_back_to_the_full_parse(self): - text = big(5) + "\n" * 250_000 + big(10)[len("id,name,amount,when\n"):] + text = big(5) + "\n" * 250_000 + big(10)[len("id,name,amount,when\n") :] self.assertGreater(len(text), csv_parse._FAST_PREVIEW_CHARS) self.assertSamePreview(text, exact_count=False) diff --git a/tests/unit/test_prod_db_naming.py b/tests/unit/test_prod_db_naming.py index 1804c1d..cf6dee3 100644 --- a/tests/unit/test_prod_db_naming.py +++ b/tests/unit/test_prod_db_naming.py @@ -57,8 +57,9 @@ def _bash(args: list[str], env: dict[str, str | None]) -> subprocess.CompletedPr else: full_env[key] = value # The scripts print UTF-8 symbols; the Windows locale codec cannot decode them. - return subprocess.run([_BASH, *args], env=full_env, capture_output=True, encoding="utf-8", - errors="replace", timeout=60) + return subprocess.run( + [_BASH, *args], env=full_env, capture_output=True, encoding="utf-8", errors="replace", timeout=60 + ) def _require_bash() -> None: @@ -83,8 +84,10 @@ def setUp(self): shutil.copy(BUILD / "deploy_all.sh", self.tmp / "build" / "deploy_all.sh") shutil.copytree(BUILD / "environments", self.tmp / "build" / "environments") for env in ("dev", "test", "staging", "prod"): - shutil.copy(self.tmp / "build" / "environments" / f"env_{env}.example.sql", - self.tmp / "build" / "environments" / f"env_{env}.sql") + shutil.copy( + self.tmp / "build" / "environments" / f"env_{env}.example.sql", + self.tmp / "build" / "environments" / f"env_{env}.sql", + ) def tearDown(self): shutil.rmtree(self.tmp, ignore_errors=True) @@ -94,16 +97,21 @@ def _launcher(self, env: str) -> Path: def _dry_run(self, *envs: str) -> subprocess.CompletedProcess: # PGHOST is unreachable on purpose: a dry run must not touch PostgreSQL. - return _bash([_posix(self.tmp / "build" / "deploy_all.sh"), "--dry-run", *envs], - {"PGHOST": "/nonexistent-socket-dir"}) + return _bash( + [_posix(self.tmp / "build" / "deploy_all.sh"), "--dry-run", *envs], {"PGHOST": "/nonexistent-socket-dir"} + ) def _write_launcher(self, env: str, text: str) -> None: self._launcher(env).write_text(text, encoding="utf-8", newline="\n") def test_committed_templates_keep_the_on_prem_names(self): out = self._dry_run().stdout - for env, db in (("DEV", "te_mgmt_dev"), ("TEST", "te_mgmt_test"), - ("STAGING", "te_mgmt_staging"), ("PROD", "te_mgmt_prod")): + for env, db in ( + ("DEV", "te_mgmt_dev"), + ("TEST", "te_mgmt_test"), + ("STAGING", "te_mgmt_staging"), + ("PROD", "te_mgmt_prod"), + ): self.assertRegex(out, rf"{env}\s+\(database: {db}, owner: postgres\)") def test_the_launcher_decides_the_database_and_owner(self): @@ -116,14 +124,18 @@ def test_the_launcher_decides_the_database_and_owner(self): self.assertRegex(res.stdout, r"PROD\s+\(database: te_prod, owner: pgadmin\)") def test_a_launcher_that_sets_neither_falls_back_to_the_on_prem_names(self): - lines = [ln for ln in self._launcher("prod").read_text(encoding="utf-8").splitlines() - if not re.match(r"\\set (db_name|db_owner)\b", ln)] + lines = [ + ln + for ln in self._launcher("prod").read_text(encoding="utf-8").splitlines() + if not re.match(r"\\set (db_name|db_owner)\b", ln) + ] self._write_launcher("prod", "\n".join(lines)) self.assertRegex(self._dry_run("prod").stdout, r"database: te_mgmt_prod, owner: postgres") def test_an_unsafe_identifier_is_refused(self): - text = re.sub(r"(\\set db_name\s+).*", r'\1"x; DROP DATABASE y"', - self._launcher("prod").read_text(encoding="utf-8")) + text = re.sub( + r"(\\set db_name\s+).*", r'\1"x; DROP DATABASE y"', self._launcher("prod").read_text(encoding="utf-8") + ) self._write_launcher("prod", text) res = self._dry_run("prod") self.assertNotEqual(res.returncode, 0) @@ -142,9 +154,16 @@ def setUp(self): (self.home / "build" / "environments").mkdir(parents=True) for template in (BUILD / "environments").glob("env_*.example.sql"): shutil.copy(template, self.home / "build" / "environments" / template.name) - self.env = {"MIGRATION_HOME": _posix(self.home), "TARGET_ENV": "prod", "PGHOST": "unused", - "PGPORT": "5432", "PGUSER": "pgadmin", "PGDATABASE": "te_prod", - "WAIT_FOR_DB_SECONDS": "1", "APP_DB_PASSWORD": SECRET} + self.env = { + "MIGRATION_HOME": _posix(self.home), + "TARGET_ENV": "prod", + "PGHOST": "unused", + "PGPORT": "5432", + "PGUSER": "pgadmin", + "PGDATABASE": "te_prod", + "WAIT_FOR_DB_SECONDS": "1", + "APP_DB_PASSWORD": SECRET, + } def tearDown(self): shutil.rmtree(self.home, ignore_errors=True) @@ -154,8 +173,14 @@ def _render(self, **override) -> subprocess.CompletedProcess: return _bash([_posix(ENTRYPOINT), "render"], {**self.env, **override}) def test_the_image_has_no_concrete_launcher(self): - self.assertEqual([p.name for p in (self.home / "build" / "environments").glob("env_*.sql") - if not p.name.endswith(".example.sql")], []) + self.assertEqual( + [ + p.name + for p in (self.home / "build" / "environments").glob("env_*.sql") + if not p.name.endswith(".example.sql") + ], + [], + ) def test_the_launcher_is_made_from_the_containers_database_and_user(self): res = self._render() @@ -198,8 +223,10 @@ def test_an_environment_with_no_template_is_an_error(self): @pytest.mark.unit class TerraformAgreesWithTheDeployment(unittest.TestCase): def test_the_database_terraform_creates_is_te_prod(self): - m = re.search(r'resource "azurerm_postgresql_flexible_server_database" "te_prod"\s*\{[^}]*?name\s*=\s*"([^"]+)"', - TERRAFORM) + m = re.search( + r'resource "azurerm_postgresql_flexible_server_database" "te_prod"\s*\{[^}]*?name\s*=\s*"([^"]+)"', + TERRAFORM, + ) self.assertIsNotNone(m) self.assertEqual(m.group(1), "te_prod") @@ -210,7 +237,9 @@ def test_the_job_deploys_into_that_database_as_the_servers_admin(self): def test_the_job_receives_the_application_password_as_a_secret(self): self.assertEqual(_tf_env("APP_DB_PASSWORD"), "app-password") - self.assertRegex(TERRAFORM, r'secret\s*\{\s*name\s*=\s*"app-password"[^}]*azurerm_key_vault_secret\.app_password\.id') + self.assertRegex( + TERRAFORM, r'secret\s*\{\s*name\s*=\s*"app-password"[^}]*azurerm_key_vault_secret\.app_password\.id' + ) def test_every_extension_the_schema_creates_is_allow_listed_on_azure(self): needed = set(re.findall(r'CREATE EXTENSION IF NOT EXISTS "([^"]+)"', SCHEMA_SQL.read_text(encoding="utf-8"))) @@ -228,7 +257,7 @@ def test_the_two_schema_copies_are_identical(self): def test_the_password_row_is_captured_not_printed(self): text = SCHEMA_SQL.read_text(encoding="utf-8") start = text.index("set_config('te.env_label'") - stmt = text[start:text.index("\\echo", start)] + stmt = text[start : text.index("\\echo", start)] self.assertIn("te.app_password", stmt) self.assertIn("\\gset", stmt) self.assertNotIn(";", stmt, "a ';'-terminated SELECT prints the row, password included") diff --git a/tests/unit/test_prod_health_and_docs.py b/tests/unit/test_prod_health_and_docs.py index 8c70631..1151d8a 100644 --- a/tests/unit/test_prod_health_and_docs.py +++ b/tests/unit/test_prod_health_and_docs.py @@ -12,6 +12,7 @@ The health tests replace the database connection, so they need no PostgreSQL. The docs routes are fixed when the app is created, so they are checked in a fresh process per environment. """ + from __future__ import annotations import json @@ -69,6 +70,7 @@ def health(monkeypatch, api_env: str, *, database_up: bool = True) -> dict: # -- /api/health ------------------------------------------------------------------------------------------------ + def test_in_dev_the_health_body_keeps_its_details(monkeypatch): body = health(monkeypatch, "dev") assert set(body) == DEV_KEYS and body["status"] == "ok", body @@ -93,13 +95,19 @@ def test_in_dev_a_failing_database_still_says_why_in_general_terms(monkeypatch): def test_the_production_body_names_nothing_about_the_database(monkeypatch): text = json.dumps(health(monkeypatch, "prod")) - for secret in (settings.PG_DATABASE, settings.PG_HOST, str(settings.PG_PORT), settings.UPLOADS_SCHEMA, - "PostgreSQL"): + for secret in ( + settings.PG_DATABASE, + settings.PG_HOST, + str(settings.PG_PORT), + settings.UPLOADS_SCHEMA, + "PostgreSQL", + ): assert str(secret) not in text, f"{secret!r} is in {text}" # -- /docs, /redoc, /openapi.json -------------------------------------------------------------------------------- + def docs_statuses(api_env: str) -> dict[str, int]: """Status of each docs route in a fresh process that creates the app with this API_ENV.""" code = ( @@ -110,8 +118,7 @@ def docs_statuses(api_env: str) -> dict[str, int]: "print(json.dumps({p: c.get(p).status_code for p in ('/docs', '/redoc', '/openapi.json')}))\n" ) env = {**os.environ, "API_ENV": api_env} - done = subprocess.run([sys.executable, "-c", code], cwd=ROOT, env=env, capture_output=True, text=True, - timeout=180) + done = subprocess.run([sys.executable, "-c", code], cwd=ROOT, env=env, capture_output=True, text=True, timeout=180) assert done.returncode == 0, done.stderr[-600:] return json.loads(done.stdout.strip().splitlines()[-1]) diff --git a/tests/unit/test_prod_web_apps_terraform.py b/tests/unit/test_prod_web_apps_terraform.py index 37a059e..c0ac1bd 100644 --- a/tests/unit/test_prod_web_apps_terraform.py +++ b/tests/unit/test_prod_web_apps_terraform.py @@ -6,6 +6,7 @@ the existing ones. These read the Terraform and the Dockerfile as text. `terraform validate` was run by hand (it needs the providers, which CI does not download); nothing here is applied to Azure. """ + from __future__ import annotations import re @@ -91,7 +92,9 @@ def test_streamlit_scales_by_the_variable_and_has_sticky_sessions(): def test_streamlit_calls_the_api_at_its_internal_address(): assert env_value(ST, "API_URL") == "value=local.api_internal_url" - assert re.search(r'api_internal_url\s*=\s*.*"https://\$\{azurerm_container_app\.api\[0\]\.ingress\[0\]\.fqdn\}"', MAIN) + assert re.search( + r'api_internal_url\s*=\s*.*"https://\$\{azurerm_container_app\.api\[0\]\.ingress\[0\]\.fqdn\}"', MAIN + ) def test_both_apps_get_one_upload_limit(): @@ -138,7 +141,8 @@ def test_the_vnet_can_resolve_the_apps(): assert 'name = "*"' in record assert "records = [azurerm_container_app_environment.env.static_ip_address]" in record assert "virtual_network_id = azurerm_virtual_network.vnet.id" in resource( - "azurerm_private_dns_zone_virtual_network_link", "cae") + "azurerm_private_dns_zone_virtual_network_link", "cae" + ) def test_the_outputs_name_the_streamlit_address(): @@ -154,6 +158,7 @@ def test_the_apps_can_be_left_out_of_the_bootstrap_apply(): # --- container/streamlit.Dockerfile ------------------------------------- + def test_the_image_runs_streamlit_from_streamlit_app_as_a_non_root_user(): assert re.search(r"(?m)^FROM python:3\.12-slim@sha256:[0-9a-f]{64}$", DOCKERFILE) # pinned by digest (#327) assert re.search(r"(?m)^WORKDIR /app/streamlit_app$", DOCKERFILE) diff --git a/tests/unit/test_rate_limit_behind_a_proxy.py b/tests/unit/test_rate_limit_behind_a_proxy.py index ffee5ca..a63d014 100644 --- a/tests/unit/test_rate_limit_behind_a_proxy.py +++ b/tests/unit/test_rate_limit_behind_a_proxy.py @@ -18,6 +18,7 @@ * the setting, and the two rate-limit settings that were undocumented, are documented, and so is where a limit set in the proxy belongs; the limiter's docstring says how the client address is chosen. """ + from __future__ import annotations import re @@ -62,6 +63,7 @@ def preview(client: TestClient, forwarded: str) -> int: # -- behind a trusted proxy ------------------------------------------------------------------------------------------ + def test_two_clients_behind_a_trusted_proxy_have_separate_budgets(monkeypatch): client = served(monkeypatch, PROXY) assert [preview(client, "203.0.113.5") for _ in range(2)] == [200, 200] @@ -93,15 +95,16 @@ def test_forging_the_header_does_not_mint_a_budget_behind_a_trusted_proxy(monkey # -- not behind a trusted proxy -------------------------------------------------------------------------------------- + def test_a_header_from_an_untrusted_peer_is_ignored(monkeypatch): - client = served(monkeypatch, "10.0.0.2") # a different address is the trusted one + client = served(monkeypatch, "10.0.0.2") # a different address is the trusted one statuses = [preview(client, f"203.0.113.{i}") for i in range(3)] assert statuses == [200, 200, 429], "all three share the peer's budget, whatever the header says" def test_by_default_only_loopback_is_trusted(monkeypatch): assert uvicorn.Config("api.main:app", log_config=None).forwarded_allow_ips in ("127.0.0.1,::1", "127.0.0.1") - client = served(monkeypatch, None) # FORWARDED_ALLOW_IPS unset: the shipped default + client = served(monkeypatch, None) # FORWARDED_ALLOW_IPS unset: the shipped default assert [preview(client, f"203.0.113.{i}") for i in range(3)] == [200, 200, 429] @@ -115,19 +118,23 @@ def test_a_loopback_proxy_is_trusted_by_default(monkeypatch): def test_the_limiter_itself_keys_on_whatever_client_address_it_is_given(): """Without the wrapper (a different server, or a test), the peer is the identity and the header is not.""" from starlette.requests import Request + scope = {"type": "http", "headers": [(b"x-forwarded-for", b"203.0.113.5")], "client": (PROXY, 5000)} assert _client_id(Request(scope)) == f"ip:{PROXY}" # -- what the repo starts, and what it says -------------------------------------------------------------------------- + def _start_up_files() -> list[Path]: roots = [ROOT / "container", ROOT / "scripts" / "offline", ROOT / "infra", ROOT / ".github" / "workflows"] found = [] for base in roots: for path in base.rglob("*"): - scanned = path.suffix in {".sh", ".ps1", ".yml", ".yaml", ".tf", ".tfvars", ".json", ".md", ""} \ - or "dockerfile" in path.name.lower() # api.Dockerfile has the suffix ".Dockerfile" + scanned = ( + path.suffix in {".sh", ".ps1", ".yml", ".yaml", ".tf", ".tfvars", ".json", ".md", ""} + or "dockerfile" in path.name.lower() + ) # api.Dockerfile has the suffix ".Dockerfile" if path.is_file() and ".terraform" not in path.parts and scanned: found.append(path) assert any(p.name == "api.Dockerfile" for p in found), "the scan must include the API image" diff --git a/tests/unit/test_regression.py b/tests/unit/test_regression.py index 814a0c1..913d93b 100644 --- a/tests/unit/test_regression.py +++ b/tests/unit/test_regression.py @@ -4,6 +4,7 @@ Adding a test here prevents the same bug from silently re-appearing. No database required; all tests run offline. """ + import os import subprocess import sys @@ -40,15 +41,17 @@ class RegressionBomHandling(unittest.TestCase): def test_bom_csv_is_accepted(self): with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) - csv_file = tmp_path / "bom_input.csv" + csv_file = tmp_path / "bom_input.csv" valid_csv = tmp_path / "valid.csv" - skip_csv = tmp_path / "skip.csv" + skip_csv = tmp_path / "skip.csv" csv_file.write_bytes(b"\xef\xbb\xbfid,name\n1,Alice\n2,Bob\n") - env = {**os.environ, - "CSV_FILE": str(csv_file), - "VALID_CSV": str(valid_csv), - "SKIP_FILE": str(skip_csv), - "TABLE_NAME": "people"} + env = { + **os.environ, + "CSV_FILE": str(csv_file), + "VALID_CSV": str(valid_csv), + "SKIP_FILE": str(skip_csv), + "TABLE_NAME": "people", + } result = _run(env) self.assertEqual(result.returncode, 0, result.stderr) lines = valid_csv.read_text(encoding="utf-8").strip().splitlines() @@ -65,15 +68,17 @@ class RegressionCrlfLineEndings(unittest.TestCase): def test_crlf_csv_accepted(self): with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) - csv_file = tmp_path / "crlf.csv" + csv_file = tmp_path / "crlf.csv" valid_csv = tmp_path / "valid.csv" - skip_csv = tmp_path / "skip.csv" + skip_csv = tmp_path / "skip.csv" csv_file.write_bytes(b"id,name\r\n1,Alice\r\n2,Bob\r\n") - env = {**os.environ, - "CSV_FILE": str(csv_file), - "VALID_CSV": str(valid_csv), - "SKIP_FILE": str(skip_csv), - "TABLE_NAME": "people"} + env = { + **os.environ, + "CSV_FILE": str(csv_file), + "VALID_CSV": str(valid_csv), + "SKIP_FILE": str(skip_csv), + "TABLE_NAME": "people", + } result = _run(env) self.assertEqual(result.returncode, 0, result.stderr) lines = valid_csv.read_text(encoding="utf-8").strip().splitlines() @@ -93,19 +98,20 @@ class RegressionHeaderOnlyCsv(unittest.TestCase): def test_header_only_exits_cleanly(self): with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) - csv_file = tmp_path / "header_only.csv" + csv_file = tmp_path / "header_only.csv" valid_csv = tmp_path / "valid.csv" - skip_csv = tmp_path / "skip.csv" + skip_csv = tmp_path / "skip.csv" csv_file.write_text("id,name\n", encoding="utf-8") - env = {**os.environ, - "CSV_FILE": str(csv_file), - "VALID_CSV": str(valid_csv), - "SKIP_FILE": str(skip_csv), - "TABLE_NAME": "people"} + env = { + **os.environ, + "CSV_FILE": str(csv_file), + "VALID_CSV": str(valid_csv), + "SKIP_FILE": str(skip_csv), + "TABLE_NAME": "people", + } result = _run(env) self.assertEqual(result.returncode, 1) - self.assertNotIn("Traceback", result.stderr, - "Unhandled exception leaked — must exit cleanly") + self.assertNotIn("Traceback", result.stderr, "Unhandled exception leaked — must exit cleanly") self.assertIn("No valid rows", result.stderr) @@ -119,20 +125,22 @@ class RegressionSingleColumnCsv(unittest.TestCase): def test_single_column_valid_rows_pass(self): with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) - csv_file = tmp_path / "single_col.csv" + csv_file = tmp_path / "single_col.csv" valid_csv = tmp_path / "valid.csv" - skip_csv = tmp_path / "skip.csv" + skip_csv = tmp_path / "skip.csv" csv_file.write_text("name\nAlice\nBob\n", encoding="utf-8") - env = {**os.environ, - "CSV_FILE": str(csv_file), - "VALID_CSV": str(valid_csv), - "SKIP_FILE": str(skip_csv), - "TABLE_NAME": "names"} + env = { + **os.environ, + "CSV_FILE": str(csv_file), + "VALID_CSV": str(valid_csv), + "SKIP_FILE": str(skip_csv), + "TABLE_NAME": "names", + } result = _run(env) self.assertEqual(result.returncode, 0, result.stderr) lines = valid_csv.read_text(encoding="utf-8").strip().splitlines() self.assertIn("Alice", "\n".join(lines)) - self.assertIn("Bob", "\n".join(lines)) + self.assertIn("Bob", "\n".join(lines)) class RegressionNoTraceback(unittest.TestCase): @@ -151,18 +159,19 @@ def _assert_no_traceback(self, env: dict, label: str) -> None: ) def test_missing_env_vars_no_traceback(self): - env = {k: v for k, v in os.environ.items() - if k not in ("CSV_FILE", "VALID_CSV", "SKIP_FILE")} + env = {k: v for k, v in os.environ.items() if k not in ("CSV_FILE", "VALID_CSV", "SKIP_FILE")} self._assert_no_traceback(env, "missing env vars") def test_nonexistent_file_no_traceback(self): with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) - env = {**os.environ, - "CSV_FILE": str(tmp_path / "does_not_exist.csv"), - "VALID_CSV": str(tmp_path / "valid.csv"), - "SKIP_FILE": str(tmp_path / "skip.csv"), - "TABLE_NAME": "t"} + env = { + **os.environ, + "CSV_FILE": str(tmp_path / "does_not_exist.csv"), + "VALID_CSV": str(tmp_path / "valid.csv"), + "SKIP_FILE": str(tmp_path / "skip.csv"), + "TABLE_NAME": "t", + } self._assert_no_traceback(env, "nonexistent file") def test_invalid_utf8_no_traceback(self): @@ -170,11 +179,13 @@ def test_invalid_utf8_no_traceback(self): tmp_path = Path(tmp) csv_file = tmp_path / "bad.csv" csv_file.write_bytes(b"id,name\n1,\xe9\n") - env = {**os.environ, - "CSV_FILE": str(csv_file), - "VALID_CSV": str(tmp_path / "valid.csv"), - "SKIP_FILE": str(tmp_path / "skip.csv"), - "TABLE_NAME": "t"} + env = { + **os.environ, + "CSV_FILE": str(csv_file), + "VALID_CSV": str(tmp_path / "valid.csv"), + "SKIP_FILE": str(tmp_path / "skip.csv"), + "TABLE_NAME": "t", + } self._assert_no_traceback(env, "invalid UTF-8") diff --git a/tests/unit/test_reproducible_builds.py b/tests/unit/test_reproducible_builds.py index a5424b4..3acfb0f 100644 --- a/tests/unit/test_reproducible_builds.py +++ b/tests/unit/test_reproducible_builds.py @@ -10,6 +10,7 @@ No database or network needed: these read the files. """ + from __future__ import annotations import re @@ -32,8 +33,12 @@ "api/requirements.lock": ["api/requirements.txt"], "streamlit_app/requirements.lock": ["streamlit_app/requirements.txt"], "requirements-dev.lock": ["requirements-dev.txt", "api/requirements.txt"], - "requirements-a11y.lock": ["requirements-dev.txt", "api/requirements.txt", "requirements-a11y.txt", - "streamlit_app/requirements.txt"], + "requirements-a11y.lock": [ + "requirements-dev.txt", + "api/requirements.txt", + "requirements-a11y.txt", + "streamlit_app/requirements.txt", + ], } @@ -54,6 +59,7 @@ def _steps(): # ── #325 ────────────────────────────────────────────────────────────────────── + def test_every_action_is_pinned_to_a_commit_sha_with_its_version_in_a_comment(): offenders = [] for path in WORKFLOWS: @@ -62,7 +68,8 @@ def test_every_action_is_pinned_to_a_commit_sha_with_its_version_in_a_comment(): if not m or m.group(1).startswith("./"): continue ok = re.fullmatch(r"[\w.-]+/[\w./-]+@[0-9a-f]{40}", m.group(1)) and re.fullmatch( - r"\s+#\s*v\d+(\.\d+){0,2}\s*", m.group(2)) + r"\s+#\s*v\d+(\.\d+){0,2}\s*", m.group(2) + ) if not ok: offenders.append(f"{path.name}: {line.strip()}") assert not offenders, "pin actions as owner/repo@<40-hex sha> # vX.Y.Z: " + "; ".join(offenders) @@ -86,6 +93,7 @@ def test_dependabot_covers_pip_actions_npm_and_docker(): # ── #328 ────────────────────────────────────────────────────────────────────── + def test_python_version_file_names_the_supported_version(): assert _text(ROOT / ".python-version").strip() == SUPPORTED_PYTHON @@ -132,6 +140,7 @@ def test_the_locks_are_compiled_for_the_supported_version(): # ── #327: Python locks ──────────────────────────────────────────────────────── + def _lock_entries(path: str) -> dict[str, tuple[str, int]]: """name -> (version, number of hashes).""" entries: dict[str, tuple[str, int]] = {} @@ -176,7 +185,8 @@ def test_each_lock_satisfies_the_requirements_files_it_was_compiled_from(lock): version = entries[name][0] assert req.specifier.contains(version, prereleases=True), ( f"{lock} has {req.name}=={version}, which {source} ({req}) no longer allows: re-run " - "scripts/lock_requirements.sh") + "scripts/lock_requirements.sh" + ) def test_a_package_has_the_same_version_in_every_lock(): @@ -220,10 +230,12 @@ def test_the_offline_bundle_downloads_and_installs_only_hashed_locks(): # ── #327: JS lock, image digests, healthchecks ──────────────────────────────── + def test_the_frontend_has_one_lock_file(): fe = ROOT / "csv-table-hub-main" - present = [n for n in ("package-lock.json", "bun.lock", "bun.lockb", "yarn.lock", "pnpm-lock.yaml") - if (fe / n).exists()] + present = [ + n for n in ("package-lock.json", "bun.lock", "bun.lockb", "yarn.lock", "pnpm-lock.yaml") if (fe / n).exists() + ] assert present == ["package-lock.json"], present @@ -265,6 +277,7 @@ def test_the_api_and_frontend_images_have_the_compose_healthcheck(image): # ── #329 ────────────────────────────────────────────────────────────────────── + def test_a_ci_job_lints_type_checks_and_builds_the_frontend(): job = _workflow(ROOT / ".github/workflows/quality-gate.yml")["jobs"]["frontend"] assert job["defaults"]["run"]["working-directory"] == "csv-table-hub-main" diff --git a/tests/unit/test_sample_verification_run.py b/tests/unit/test_sample_verification_run.py index 026f8f7..9a724d6 100644 --- a/tests/unit/test_sample_verification_run.py +++ b/tests/unit/test_sample_verification_run.py @@ -5,6 +5,7 @@ 2 (cannot run, as for a missing password) and writes nothing, so the committed sample report is never overwritten by a half run. No server or database is needed: the API and the connection are stubs. """ + import shutil import sys from pathlib import Path @@ -33,16 +34,21 @@ def test_a_refused_upload_stops_with_the_reason_and_the_way_out(): def test_a_loaded_upload_gives_its_table(): - assert run.loaded_table(_result({"status": "ok", "tableName": "tenant_dev.organisations"}), "x") == \ - "tenant_dev.organisations" - - -@pytest.mark.parametrize("response, shown", [ - ({"status": "error", "message": "a plain message"}, "a plain message"), - ({"status": "invalid_structure", "reason": "empty"}, "empty"), - ({"detail": "File too large"}, "File too large"), - ({}, "no reason given"), -]) + assert ( + run.loaded_table(_result({"status": "ok", "tableName": "tenant_dev.organisations"}), "x") + == "tenant_dev.organisations" + ) + + +@pytest.mark.parametrize( + "response, shown", + [ + ({"status": "error", "message": "a plain message"}, "a plain message"), + ({"status": "invalid_structure", "reason": "empty"}, "empty"), + ({"detail": "File too large"}, "File too large"), + ({}, "no reason given"), + ], +) def test_whatever_the_refusal_looks_like_it_is_explained(response, shown): with pytest.raises(run.NotFresh, match=shown): run.loaded_table(_result(response, 413), "file") @@ -89,5 +95,6 @@ def test_main_on_a_populated_database_exits_2_says_why_and_writes_nothing(tmp_pa assert code == 2 err = capsys.readouterr().err assert "FRESH database" in err and "Traceback" not in err - assert sorted(p.name for p in Path(tmp_path).iterdir()) == ["equipment_register.csv", "orgs_sample.csv"], \ + assert sorted(p.name for p in Path(tmp_path).iterdir()) == ["equipment_register.csv", "orgs_sample.csv"], ( "no report or evidence file was written" + ) diff --git a/tests/unit/test_security.py b/tests/unit/test_security.py index 286c2bd..4c93378 100644 --- a/tests/unit/test_security.py +++ b/tests/unit/test_security.py @@ -6,6 +6,7 @@ No database required; all tests are purely static (file-read) checks. """ + import re import unittest from pathlib import Path @@ -24,18 +25,19 @@ ] # ── Shell scripts to scan ───────────────────────────────────────────────────── -SHELL_SCRIPTS = list((ROOT / "build" / "adapters").glob("adapter_*.sh")) + \ - list((ROOT / "build" / "csv").glob("loader_*.sh")) + [ - ROOT / "build" / "deploy_all.sh", - ROOT / "build" / "setup.sh", - ROOT / "build" / "csv_loader.sh", - ] +SHELL_SCRIPTS = ( + list((ROOT / "build" / "adapters").glob("adapter_*.sh")) + + list((ROOT / "build" / "csv").glob("loader_*.sh")) + + [ + ROOT / "build" / "deploy_all.sh", + ROOT / "build" / "setup.sh", + ROOT / "build" / "csv_loader.sh", + ] +) # ── Patterns that must NOT appear in source ─────────────────────────────────── # Matches a password-like variable assigned a non-empty literal value -_HARDCODED_PASSWORD = re.compile( - r'(?i)(password|passwd|secret|pg_password)\s*[=:]\s*["\'][^"\']{3,}["\']' -) +_HARDCODED_PASSWORD = re.compile(r'(?i)(password|passwd|secret|pg_password)\s*[=:]\s*["\'][^"\']{3,}["\']') # f-string containing what looks like a SQL keyword — SQL must never be built # with f-strings; use psycopg2.sql.Identifier / parameterised queries. @@ -106,8 +108,7 @@ def test_pg_password_is_empty(self): self.assertRegex( stripped, r'^PG_PASSWORD\s*=\s*(["\'][\s]*["\']|)(\s*#.*)?$', - "PG_PASSWORD in config.env.example must be empty — " - "do not commit real credentials.", + "PG_PASSWORD in config.env.example must be empty — do not commit real credentials.", ) return # If PG_PASSWORD line is absent entirely that is also fine @@ -122,7 +123,7 @@ class TestShellScriptsNoPrintedPasswords(unittest.TestCase): """ _ECHO_PASSWORD = re.compile( - r'\becho\b.*\$(PG_?PASSWORD|PGPASSWORD)', + r"\becho\b.*\$(PG_?PASSWORD|PGPASSWORD)", re.IGNORECASE, ) @@ -131,20 +132,14 @@ def test_no_echo_password_in_adapters(self): text = script.read_text(encoding="utf-8", errors="replace") for i, line in enumerate(text.splitlines(), 1): if self._ECHO_PASSWORD.search(line) and not line.strip().startswith("#"): - self.fail( - f"Password may be echoed to stdout in " - f"{script.relative_to(ROOT)}:{i}:\n {line.strip()}" - ) + self.fail(f"Password may be echoed to stdout in {script.relative_to(ROOT)}:{i}:\n {line.strip()}") def test_no_echo_password_in_loaders(self): for script in (ROOT / "build" / "csv").glob("loader_*.sh"): text = script.read_text(encoding="utf-8", errors="replace") for i, line in enumerate(text.splitlines(), 1): if self._ECHO_PASSWORD.search(line) and not line.strip().startswith("#"): - self.fail( - f"Password may be echoed to stdout in " - f"{script.relative_to(ROOT)}:{i}:\n {line.strip()}" - ) + self.fail(f"Password may be echoed to stdout in {script.relative_to(ROOT)}:{i}:\n {line.strip()}") class TestSqlFilesNoInlineCredentials(unittest.TestCase): @@ -168,8 +163,7 @@ def test_env_sql_files_no_hardcoded_passwords(self): continue if self._SQL_PASSWORD.search(line) and not line.strip().startswith("--"): self.fail( - f"Possible hardcoded password in SQL file " - f"{sql_file.relative_to(ROOT)}:{i}:\n {line.strip()}" + f"Possible hardcoded password in SQL file {sql_file.relative_to(ROOT)}:{i}:\n {line.strip()}" ) diff --git a/tests/unit/test_security_audit.py b/tests/unit/test_security_audit.py index 2fb84b9..60c0513 100644 --- a/tests/unit/test_security_audit.py +++ b/tests/unit/test_security_audit.py @@ -8,6 +8,7 @@ result is "could not audit" (exit 2), never a pass. (test_report.py once printed PASS with 0 tests run.) * the requirements files come from git, not from a list, so a new one is audited without anyone remembering. """ + from __future__ import annotations import datetime as dt @@ -32,9 +33,19 @@ def pip_json(*deps: dict) -> str: CLEAN = pip_json({"name": "fastapi", "version": "0.162.5", "vulns": []}) VULNERABLE = pip_json( {"name": "fastapi", "version": "0.162.5", "vulns": []}, - {"name": "requests", "version": "2.30.0", "vulns": [ - {"id": "PYSEC-2023-74", "aliases": ["CVE-2023-32681", "GHSA-j8r2-6x86-q33q"], "fix_versions": ["2.31.0"], - "description": "Unintended leak of Proxy-Authorization header"}]}) + { + "name": "requests", + "version": "2.30.0", + "vulns": [ + { + "id": "PYSEC-2023-74", + "aliases": ["CVE-2023-32681", "GHSA-j8r2-6x86-q33q"], + "fix_versions": ["2.31.0"], + "description": "Unintended leak of Proxy-Authorization header", + } + ], + }, +) def npm_json(**vulns) -> str: @@ -42,16 +53,40 @@ def npm_json(**vulns) -> str: NPM_HIGH = npm_json( - lodash={"name": "lodash", "severity": "high", "via": [ - {"source": 1, "name": "lodash", "title": "Prototype pollution", "severity": "high", - "url": "https://github.com/advisories/GHSA-p6mc-m468-83gw"}], "fixAvailable": True}, - left_pad={"name": "left-pad", "severity": "moderate", "via": [ - {"source": 2, "name": "left-pad", "title": "Meh", "severity": "moderate", - "url": "https://github.com/advisories/GHSA-aaaa-bbbb-cccc"}], "fixAvailable": False}) + lodash={ + "name": "lodash", + "severity": "high", + "via": [ + { + "source": 1, + "name": "lodash", + "title": "Prototype pollution", + "severity": "high", + "url": "https://github.com/advisories/GHSA-p6mc-m468-83gw", + } + ], + "fixAvailable": True, + }, + left_pad={ + "name": "left-pad", + "severity": "moderate", + "via": [ + { + "source": 2, + "name": "left-pad", + "title": "Meh", + "severity": "moderate", + "url": "https://github.com/advisories/GHSA-aaaa-bbbb-cccc", + } + ], + "fixAvailable": False, + }, +) # --- parsing ----------------------------------------------------------------------------------------------------- + def test_pip_audit_output_with_a_vulnerable_package_yields_one_finding_with_its_aliases(): findings = sa.parse_pip_audit(VULNERABLE, "api/requirements.txt") assert [(f.package, f.version, f.advisory) for f in findings] == [("requests", "2.30.0", "PYSEC-2023-74")] @@ -109,11 +144,15 @@ def test_npm_audit_with_no_vulnerabilities_key_is_an_error(): def test_the_allowlist_reads_id_expiry_and_reason(): entries = sa.parse_allowlist(ALLOW) assert [(e.advisory, e.expires.isoformat()) for e in entries] == [ - ("PYSEC-2023-74", "2026-12-31"), ("GHSA-old-old-old", "2026-01-01")] + ("PYSEC-2023-74", "2026-12-31"), + ("GHSA-old-old-old", "2026-01-01"), + ] assert "not reachable" in entries[0].reason -@pytest.mark.parametrize("line", ["PYSEC-1", "PYSEC-1 not-a-date because", "PYSEC-1 2026-12-31", "2026-12-31 PYSEC-1 why"]) +@pytest.mark.parametrize( + "line", ["PYSEC-1", "PYSEC-1 not-a-date because", "PYSEC-1 2026-12-31", "2026-12-31 PYSEC-1 why"] +) def test_a_malformed_allowlist_line_is_an_error(line): with pytest.raises(sa.AuditError, match="allow-list"): sa.parse_allowlist(line) @@ -140,6 +179,7 @@ def test_an_expired_allowlist_entry_is_reported_even_when_it_matches_nothing(): # --- the whole run, with the auditors stubbed --------------------------------------------------------------------- + def run(pip_out=CLEAN, npm_out=npm_json(), allow="", files=("api/requirements.txt",), pip_exc=None, npm_exc=None): def pip_runner(_path): if pip_exc: @@ -151,8 +191,15 @@ def npm_runner(_dir): raise npm_exc return npm_out - return sa.main([], pip_runner=pip_runner, npm_runner=npm_runner, today=TODAY, requirements=list(files), - allowlist_text=allow, npm_dir="csv-table-hub-main") + return sa.main( + [], + pip_runner=pip_runner, + npm_runner=npm_runner, + today=TODAY, + requirements=list(files), + allowlist_text=allow, + npm_dir="csv-table-hub-main", + ) def test_a_clean_run_exits_zero(capsys): @@ -172,7 +219,10 @@ def test_a_high_npm_vulnerability_exits_one(capsys): def test_an_allowlisted_finding_exits_zero_and_says_it_was_allowed(capsys): - assert run(pip_out=VULNERABLE, allow=ALLOW.replace("GHSA-old-old-old 2026-01-01 an exception that has expired", "")) == 0 + assert ( + run(pip_out=VULNERABLE, allow=ALLOW.replace("GHSA-old-old-old 2026-01-01 an exception that has expired", "")) + == 0 + ) assert "allowed" in capsys.readouterr().out.lower() @@ -193,8 +243,10 @@ def test_when_there_are_no_requirements_files_the_result_is_could_not_audit(caps # --- discovery --------------------------------------------------------------------------------------------------- + def test_every_tracked_requirements_file_is_audited(): - tracked = subprocess.run(["git", "ls-files", "*requirements*.txt"], cwd=ROOT, capture_output=True, text=True, - check=True).stdout.split() + tracked = subprocess.run( + ["git", "ls-files", "*requirements*.txt"], cwd=ROOT, capture_output=True, text=True, check=True + ).stdout.split() assert tracked, "expected at least one tracked requirements file" assert sorted(sa.discover_requirements(ROOT)) == sorted(tracked) diff --git a/tests/unit/test_security_scan_workflow.py b/tests/unit/test_security_scan_workflow.py index a67ffa7..d3f0fef 100644 --- a/tests/unit/test_security_scan_workflow.py +++ b/tests/unit/test_security_scan_workflow.py @@ -9,6 +9,7 @@ * the gitleaks config does not extend the default rules, which leaves only the custom ones (usually none); * the allow-list file is malformed or holds an expired entry, which would only show up on the weekly run. """ + from __future__ import annotations import datetime as dt @@ -70,7 +71,8 @@ def test_the_dependency_audit_installs_a_pinned_pip_audit_and_runs_the_script(wo def test_the_secret_scan_checks_out_the_whole_history(workflow): checkout = [s for s in steps(workflow, "secret-scan") if "checkout" in s.get("uses", "")] assert checkout and checkout[0].get("with", {}).get("fetch-depth") == 0, ( - "a shallow checkout makes the 'full history' scan look at one commit") + "a shallow checkout makes the 'full history' scan look at one commit" + ) def test_the_secret_scan_runs_a_pinned_gitleaks_that_fails_on_a_leak(workflow): @@ -102,7 +104,8 @@ def test_the_gitleaks_config_keeps_the_default_rules(): assert GITLEAKS.exists(), ".gitleaks.toml is missing" text = GITLEAKS.read_text(encoding="utf-8") assert re.search(r"(?m)^\[extend\]\s*\n\s*useDefault\s*=\s*true", text), ( - "a config without [extend] useDefault = true replaces gitleaks's rules with only the ones written here") + "a config without [extend] useDefault = true replaces gitleaks's rules with only the ones written here" + ) def test_every_allowlisted_secret_has_a_reason(): @@ -111,7 +114,8 @@ def test_every_allowlisted_secret_has_a_reason(): blocks = re.split(r"(?m)^\[\[?allowlists?\]\]?\s*$", text)[1:] for block in blocks: assert re.search(r"(?m)^\s*description\s*=\s*\"[^\"]{15,}\"", block), ( - "every gitleaks allow-list block needs a description of why it is safe") + "every gitleaks allow-list block needs a description of why it is safe" + ) def test_the_real_audit_allowlist_parses_and_holds_no_expired_entry(): diff --git a/tests/unit/test_session_settings_docs.py b/tests/unit/test_session_settings_docs.py index 3634fc6..a9fde2f 100644 --- a/tests/unit/test_session_settings_docs.py +++ b/tests/unit/test_session_settings_docs.py @@ -3,6 +3,7 @@ Without a database: a setting nobody can find is as good as none. Both are read from the environment with a default the table must state, and the purge script an operator schedules must be named in the operator guide. """ + from __future__ import annotations import re diff --git a/tests/unit/test_snapshot.py b/tests/unit/test_snapshot.py index cf1b087..192a75b 100644 --- a/tests/unit/test_snapshot.py +++ b/tests/unit/test_snapshot.py @@ -7,6 +7,7 @@ UPDATE_SNAPSHOTS=1 pytest -m snapshot tests/test_snapshot.py # regenerate pytest -m snapshot tests/test_snapshot.py # compare """ + import os import subprocess import sys @@ -18,24 +19,24 @@ pytestmark = [pytest.mark.unit, pytest.mark.snapshot] -VALIDATOR = Path(__file__).resolve().parents[2] / "build" / "csv" / "validator.py" +VALIDATOR = Path(__file__).resolve().parents[2] / "build" / "csv" / "validator.py" SNAPSHOTS_DIR = Path(__file__).resolve().parents[1] / "snapshots" -UPDATE = os.environ.get("UPDATE_SNAPSHOTS", "").lower() in ("1", "true", "yes") +UPDATE = os.environ.get("UPDATE_SNAPSHOTS", "").lower() in ("1", "true", "yes") def _run_validator(csv_content: bytes, table_name: str = "people") -> tuple[str, str, int]: """Run the validator on csv_content bytes; return (valid_text, skip_text, exit_code).""" with tempfile.TemporaryDirectory() as tmp: tmp_path = Path(tmp) - csv_file = tmp_path / "input.csv" + csv_file = tmp_path / "input.csv" valid_csv = tmp_path / "valid.csv" - skip_csv = tmp_path / "skip.csv" + skip_csv = tmp_path / "skip.csv" csv_file.write_bytes(csv_content) env = { **os.environ, - "CSV_FILE": str(csv_file), - "VALID_CSV": str(valid_csv), - "SKIP_FILE": str(skip_csv), + "CSV_FILE": str(csv_file), + "VALID_CSV": str(valid_csv), + "SKIP_FILE": str(skip_csv), "TABLE_NAME": table_name, } r = subprocess.run( @@ -47,7 +48,7 @@ def _run_validator(csv_content: bytes, table_name: str = "people") -> tuple[str, errors="replace", ) valid_text = valid_csv.read_text(encoding="utf-8") if valid_csv.exists() else "" - skip_text = skip_csv.read_text(encoding="utf-8") if skip_csv.exists() else "" + skip_text = skip_csv.read_text(encoding="utf-8") if skip_csv.exists() else "" return valid_text, skip_text, r.returncode @@ -96,8 +97,7 @@ def test_all_valid_no_skips(self): _assert_snapshot(valid_text, "all_valid_expected_valid.csv") # skip file should have only a header (or be empty) skip_lines = [ln for ln in skip_text.splitlines() if ln.strip()] - self.assertLessEqual(len(skip_lines), 1, - "Expected at most a header row in skip.csv when all rows are valid") + self.assertLessEqual(len(skip_lines), 1, "Expected at most a header row in skip.csv when all rows are valid") if __name__ == "__main__": diff --git a/tests/unit/test_sovereignty.py b/tests/unit/test_sovereignty.py index 273c149..675e277 100644 --- a/tests/unit/test_sovereignty.py +++ b/tests/unit/test_sovereignty.py @@ -23,13 +23,42 @@ _FRONTEND_ALLOWED = _LOCAL | {"www.w3.org"} # Modules that make outbound requests. The API imports none. Its one external call, the OIDC key fetch, # is made by PyJWT and only when OIDC_ISSUER is set, to an IdP the deployment controls (api/oidc.py). -_HTTP_MODULES = {"requests", "httpx", "aiohttp", "urllib3", "urllib.request", "http.client", "ftplib", "smtplib", - "telnetlib", "xmlrpc.client", "websockets", "boto3", "botocore"} +_HTTP_MODULES = { + "requests", + "httpx", + "aiohttp", + "urllib3", + "urllib.request", + "http.client", + "ftplib", + "smtplib", + "telnetlib", + "xmlrpc.client", + "websockets", + "boto3", + "botocore", +} # urllib.request names that only convert between paths and URLs. _URL_PATH_HELPERS = {"url2pathname", "pathname2url"} # npm packages that phone home to a third party. -_TELEMETRY = ("sentry", "posthog", "mixpanel", "segment", "amplitude", "datadog", "newrelic", "hotjar", "logrocket", - "fullstory", "bugsnag", "rollbar", "analytics", "gtag", "heap", "intercom") +_TELEMETRY = ( + "sentry", + "posthog", + "mixpanel", + "segment", + "amplitude", + "datadog", + "newrelic", + "hotjar", + "logrocket", + "fullstory", + "bugsnag", + "rollbar", + "analytics", + "gtag", + "heap", + "intercom", +) def _hosts(path: Path) -> set[str]: @@ -38,8 +67,11 @@ def _hosts(path: Path) -> set[str]: def _frontend_sources() -> list[Path]: src = _ROOT / "csv-table-hub-main" / "src" - files = [p for p in src.rglob("*") if p.suffix in {".ts", ".tsx", ".js", ".jsx", ".css", ".html", ".svg", ".json"} - and "__tests__" not in p.parts] + files = [ + p + for p in src.rglob("*") + if p.suffix in {".ts", ".tsx", ".js", ".jsx", ".css", ".html", ".svg", ".json"} and "__tests__" not in p.parts + ] public = _ROOT / "csv-table-hub-main" / "public" return files + (list(public.rglob("*")) if public.exists() else []) @@ -50,13 +82,24 @@ def test_the_api_imports_no_http_client(self): found = [] for path in (_ROOT / "api").rglob("*.py"): for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): - if isinstance(node, ast.ImportFrom) and node.module == "urllib.request" and \ - {a.name for a in node.names} <= _URL_PATH_HELPERS: - continue # url2pathname turns a file:// URL into a path; it opens nothing - names = ([a.name for a in node.names] if isinstance(node, ast.Import) - else [node.module or ""] if isinstance(node, ast.ImportFrom) else []) - found += [f"{path.relative_to(_ROOT)}: {n}" for n in names - if n in _HTTP_MODULES or n.split(".")[0] in _HTTP_MODULES] + if ( + isinstance(node, ast.ImportFrom) + and node.module == "urllib.request" + and {a.name for a in node.names} <= _URL_PATH_HELPERS + ): + continue # url2pathname turns a file:// URL into a path; it opens nothing + names = ( + [a.name for a in node.names] + if isinstance(node, ast.Import) + else [node.module or ""] + if isinstance(node, ast.ImportFrom) + else [] + ) + found += [ + f"{path.relative_to(_ROOT)}: {n}" + for n in names + if n in _HTTP_MODULES or n.split(".")[0] in _HTTP_MODULES + ] self.assertEqual(found, []) def test_the_scan_catches_a_network_capable_urllib_import(self): @@ -88,14 +131,18 @@ def test_no_html_entry_loads_a_remote_script_or_stylesheet(self): for page in (_ROOT / "csv-table-hub-main").rglob("*.html"): if "node_modules" in page.parts or "dist" in page.parts: continue - offenders += re.findall(r"""(?:src|href)\s*=\s*["']((?:https?:)?//[^"']+)""", page.read_text(errors="ignore")) + offenders += re.findall( + r"""(?:src|href)\s*=\s*["']((?:https?:)?//[^"']+)""", page.read_text(errors="ignore") + ) self.assertEqual(offenders, []) def test_the_scan_would_catch_a_cdn(self): # The check isn't vacuous: it flags the hosts a real violation would use. sample = 'import "https://cdn.jsdelivr.net/npm/x"; fetch("https://www.google-analytics.com/collect")' - self.assertEqual({h.lower() for h in _HOST.findall(sample)} - _FRONTEND_ALLOWED, - {"cdn.jsdelivr.net", "www.google-analytics.com"}) + self.assertEqual( + {h.lower() for h in _HOST.findall(sample)} - _FRONTEND_ALLOWED, + {"cdn.jsdelivr.net", "www.google-analytics.com"}, + ) def _checker(): @@ -116,28 +163,42 @@ def scan(self, files: dict[str, str]) -> dict: return _checker().scan(Path(tmp)) def test_namespaces_documentation_links_and_new_url_are_not_load_paths(self): - found = self.scan({"app.js": 'const ns = "http://www.w3.org/2000/svg"; new URL("https://exa\\nmple.com");' - ' // https://react.dev/errors/418', "a.css": "a { color: red }"}) + found = self.scan( + { + "app.js": 'const ns = "http://www.w3.org/2000/svg"; new URL("https://exa\\nmple.com");' + " // https://react.dev/errors/418", + "a.css": "a { color: red }", + } + ) self.assertEqual((found["loads"], found["banned"]), ([], [])) self.assertIn("www.w3.org", found["other"]) def test_external_markup_resources_are_load_paths(self): - for name, text in (("index.html", ''), - ("index.html", ''), - ("a.css", '@import url("https://fonts.example.org/f.css");'), - ("a.css", "a { background: url(https://img.example.org/b.png) }")): + for name, text in ( + ("index.html", ''), + ("index.html", ''), + ("a.css", '@import url("https://fonts.example.org/f.css");'), + ("a.css", "a { background: url(https://img.example.org/b.png) }"), + ): self.assertEqual(len(self.scan({name: text})["loads"]), 1, text) def test_literal_external_requests_in_scripts_are_load_paths(self): - for text in ('fetch("https://api.example.org/x")', 'x.open("GET", "https://api.example.org/x")', - 'navigator.sendBeacon("https://t.example.org/c")', 'new WebSocket("wss://ws.example.org")', - 'import("https://esm.example.org/m.js")'): + for text in ( + 'fetch("https://api.example.org/x")', + 'x.open("GET", "https://api.example.org/x")', + 'navigator.sendBeacon("https://t.example.org/c")', + 'new WebSocket("wss://ws.example.org")', + 'import("https://esm.example.org/m.js")', + ): self.assertEqual(len(self.scan({"app.js": text})["loads"]), 1, text) def test_requests_to_this_machine_are_fine(self): self.assertEqual(self.scan({"app.js": 'fetch("http://localhost:8000/api/x")'})["loads"], []) def test_analytics_and_cdn_hosts_fail_wherever_they_appear(self): - found = self.scan({"app.js": 'const a = "https://www.google-analytics.com/collect"; // https://cdn.jsdelivr.net/x'}) - self.assertEqual(sorted(h.split(": ")[1] for h in found["banned"]), - ["cdn.jsdelivr.net", "www.google-analytics.com"]) + found = self.scan( + {"app.js": 'const a = "https://www.google-analytics.com/collect"; // https://cdn.jsdelivr.net/x'} + ) + self.assertEqual( + sorted(h.split(": ")[1] for h in found["banned"]), ["cdn.jsdelivr.net", "www.google-analytics.com"] + ) diff --git a/tests/unit/test_sql_no_bom.py b/tests/unit/test_sql_no_bom.py index a6dbfed..20925f7 100644 --- a/tests/unit/test_sql_no_bom.py +++ b/tests/unit/test_sql_no_bom.py @@ -1,6 +1,7 @@ """psql on Windows (client encoding WIN1252) does not skip a UTF-8 BOM and fails the launcher with 'syntax error at or near ""'. Linux CI skips it, so guard the shipped SQL templates here.""" + from pathlib import Path import pytest diff --git a/tests/unit/test_streamlit_api_client.py b/tests/unit/test_streamlit_api_client.py index 43c03de..5bfe12d 100644 --- a/tests/unit/test_streamlit_api_client.py +++ b/tests/unit/test_streamlit_api_client.py @@ -4,10 +4,12 @@ not be reported as "can't reach the API". That wording would send a person to re-upload a file the server is still importing. """ + import pytest import requests from tests.unit import streamlit_harness # noqa: F401 (puts streamlit_app on the path) + # The imports below need the path the import above sets up, so the import sort must not move them up. # isort: split @@ -89,12 +91,15 @@ def test_a_401_is_unauthorized_in_both_ways_of_calling(sent): api_client.download("GET", "/x", token="t") -@pytest.mark.parametrize("reply, message", [ - (Reply(413, {"detail": "File too large"}, reason="Payload Too Large"), "File too large"), - (Reply(500, None, reason="Internal Server Error"), "Internal Server Error"), - (Reply(422, {"detail": ["not", "a", "string"]}, reason="Unprocessable"), "Unprocessable"), - (Reply(502, {"detail": ""}, reason=""), "HTTP 502"), -]) +@pytest.mark.parametrize( + "reply, message", + [ + (Reply(413, {"detail": "File too large"}, reason="Payload Too Large"), "File too large"), + (Reply(500, None, reason="Internal Server Error"), "Internal Server Error"), + (Reply(422, {"detail": ["not", "a", "string"]}, reason="Unprocessable"), "Unprocessable"), + (Reply(502, {"detail": ""}, reason=""), "HTTP 502"), + ], +) def test_an_error_says_what_the_api_said_or_a_plain_fallback(sent, reply, message): _, outcome = sent outcome["reply"] = reply diff --git a/tests/unit/test_streamlit_exports.py b/tests/unit/test_streamlit_exports.py index 6d655b0..948e068 100644 --- a/tests/unit/test_streamlit_exports.py +++ b/tests/unit/test_streamlit_exports.py @@ -4,6 +4,7 @@ and checked by reading the files back the way a spreadsheet program would. The guard is the point: every cell holds text from someone else's file, so a cell that would run as a formula must not. """ + import csv import io from datetime import datetime, timezone @@ -12,6 +13,7 @@ from openpyxl import load_workbook from tests.unit import streamlit_harness # noqa: F401 (puts streamlit_app on the path) + # The imports below need the path the import above sets up, so the import sort must not move them up. # isort: split @@ -38,12 +40,15 @@ def _errors(value, **extra): # ── the guard ───────────────────────────────────────────────────────────────────────────── + @pytest.mark.parametrize("value", PAYLOADS) def test_a_cell_that_would_run_as_a_formula_gets_a_leading_quote(value): assert x.guard(value) == "'" + value -@pytest.mark.parametrize("value", ["-5", "+3.2", "5", "1.5", "-0", "+0.25", "plain text", "a=b", "x-y", "", "email@x.test"]) +@pytest.mark.parametrize( + "value", ["-5", "+3.2", "5", "1.5", "-0", "+0.25", "plain text", "a=b", "x-y", "", "email@x.test"] +) def test_plain_numbers_and_ordinary_text_are_left_alone(value): assert x.guard(value) == value @@ -62,6 +67,7 @@ def test_the_guard_looks_past_characters_nobody_can_see(): # ── CSV ─────────────────────────────────────────────────────────────────────────────────── + def test_the_csv_has_the_header_row_and_a_line_feed_after_every_line(): data = x.to_csv(x.ERROR_HEADERS, _errors("v")) @@ -78,23 +84,32 @@ def test_commas_quotes_and_line_breaks_in_a_value_are_quoted(): assert _csv_rows(data)[1][3] == 'say "hello", world\nbye', "and read back as written" -@pytest.mark.parametrize("value, expected", [ - ('=HYPERLINK("http://x","y")', '\'=HYPERLINK(""http://x"",""y"")'), - ("+cmd|' /C calc'!A0", "'+cmd|' /C calc'!A0"), - ("-2+3", "'-2+3"), - ("@SUM(A1:A2)", "'@SUM(A1:A2)"), -]) +@pytest.mark.parametrize( + "value, expected", + [ + ('=HYPERLINK("http://x","y")', '\'=HYPERLINK(""http://x"",""y"")'), + ("+cmd|' /C calc'!A0", "'+cmd|' /C calc'!A0"), + ("-2+3", "'-2+3"), + ("@SUM(A1:A2)", "'@SUM(A1:A2)"), + ], +) def test_a_formula_payload_is_neutralised_in_the_csv(value, expected): data = x.to_csv(x.ERROR_HEADERS, _errors(value)) assert expected in data.decode() assert _csv_rows(data)[1][3] == "'" + value - assert not any(cell.lstrip("\x00-\x08\x0b\x0c\x0e-\x1f").startswith(("=", "+", "-", "@")) - for row in _csv_rows(data)[1:] for cell in row if cell not in ("-5",)), "no cell starts as a formula" + assert not any( + cell.lstrip("\x00-\x08\x0b\x0c\x0e-\x1f").startswith(("=", "+", "-", "@")) + for row in _csv_rows(data)[1:] + for cell in row + if cell not in ("-5",) + ), "no cell starts as a formula" def test_signed_numbers_stay_numbers_in_the_csv(): - data = x.to_csv(x.ERROR_HEADERS, x.error_rows("d.csv", [{"rowNumber": 1, "column": "n", "value": "-5", "reason": "+3.2"}])) + data = x.to_csv( + x.ERROR_HEADERS, x.error_rows("d.csv", [{"rowNumber": 1, "column": "n", "value": "-5", "reason": "+3.2"}]) + ) assert ",-5," in data.decode() and ",+3.2," in data.decode() @@ -117,6 +132,7 @@ def test_an_empty_report_is_just_the_header(): # ── XLSX ────────────────────────────────────────────────────────────────────────────────── + @pytest.mark.parametrize("value", PAYLOADS) def test_a_formula_payload_is_a_text_cell_with_no_formula_in_the_xlsx(value): ws = _sheet(x.to_xlsx("Errors", x.ERROR_HEADERS, _errors(value)), "Errors") @@ -136,13 +152,20 @@ def test_even_with_the_guard_gone_text_that_starts_with_an_equals_sign_is_stored cell = _sheet(data, "S")["A2"] assert (cell.data_type, cell.value) == ("s", "=1+1") import zipfile + sheet_xml = zipfile.ZipFile(io.BytesIO(data)).read("xl/worksheets/sheet1.xml").decode() assert "" not in sheet_xml and "= self._when(p["to"]): continue out.append(u) - return out[p.get("offset", 0):p.get("offset", 0) + min(p.get("limit", 100), 500)] + return out[p.get("offset", 0) : p.get("offset", 0) + min(p.get("limit", 100), 500)] def _events(self, p): - rows = [e for e in self.events - if ("actor" not in p or e["actor"] == p["actor"]) and ("action" not in p or e["action"] == p["action"]) - and ("file" not in p or p["file"].lower() in (e["fileName"] or "").lower()) - and ("from" not in p or self._when(e["performedAt"]) >= self._when(p["from"])) - and ("to" not in p or self._when(e["performedAt"]) < self._when(p["to"]))] + rows = [ + e + for e in self.events + if ("actor" not in p or e["actor"] == p["actor"]) + and ("action" not in p or e["action"] == p["action"]) + and ("file" not in p or p["file"].lower() in (e["fileName"] or "").lower()) + and ("from" not in p or self._when(e["performedAt"]) >= self._when(p["from"])) + and ("to" not in p or self._when(e["performedAt"]) < self._when(p["to"])) + ] limit, offset = p.get("limit", 100), p.get("offset", 0) - return {"classification": self.classification, "total": len(rows), "limit": limit, "offset": offset, - "entries": rows[offset:offset + limit]} + return { + "classification": self.classification, + "total": len(rows), + "limit": limit, + "offset": offset, + "entries": rows[offset : offset + limit], + } def list_calls(self): return [c for c in self.calls if c[1] == "/api/csv/uploads"] @@ -136,10 +169,21 @@ def _history(api, who="rita", **kw): def _apply(at, **fields): """Fill the filter form and press Apply.""" for label, value in fields.items(): - el = widget(at.text_input if label in ("File name contains", "Uploaded by", "Actor", "File") else - at.selectbox if label in ("Status", "Action") else at.date_input, label) - (el.input if label in ("File name contains", "Uploaded by", "Actor", "File") else - el.select if label in ("Status", "Action") else el.set_value)(value) + el = widget( + at.text_input + if label in ("File name contains", "Uploaded by", "Actor", "File") + else at.selectbox + if label in ("Status", "Action") + else at.date_input, + label, + ) + ( + el.input + if label in ("File name contains", "Uploaded by", "Actor", "File") + else el.select + if label in ("Status", "Action") + else el.set_value + )(value) widget(at.button, "Apply").click().run() assert not at.exception, at.exception return at @@ -160,10 +204,15 @@ def _last_list(api): # ── the list ────────────────────────────────────────────────────────────────────────────── + def test_the_list_shows_every_import_newest_first_with_how_each_ended(api): - api.uploads = [_upload(1, "a.csv", "imported", total=3), _upload(2, "b.csv", "partly_imported", total=10, failed=4), - _upload(3, "c.csv", "failed", total=5, failed=5), _upload(4, "d.csv", "rejected", total=None), - _upload(5, "e.csv", "duplicate")] + api.uploads = [ + _upload(1, "a.csv", "imported", total=3), + _upload(2, "b.csv", "partly_imported", total=10, failed=4), + _upload(3, "c.csv", "failed", total=5, failed=5), + _upload(4, "d.csv", "rejected", total=None), + _upload(5, "e.csv", "duplicate"), + ] at = _history(api) @@ -184,6 +233,7 @@ def test_a_tenant_with_no_imports_is_told_so(api): # ── filters (React: audit-filters.test.ts) ──────────────────────────────────────────────── + def test_the_file_name_filter_is_sent_trimmed_and_matches_ignoring_case(api): api.uploads = [_upload(1, "Sales_2026.csv"), _upload(2, "people.csv")] at = _history(api) @@ -195,7 +245,11 @@ def test_the_file_name_filter_is_sent_trimmed_and_matches_ignoring_case(api): def test_the_status_filter_asks_for_that_status_only(api): - api.uploads = [_upload(1, status="imported"), _upload(2, status="failed", failed=30), _upload(3, status="duplicate")] + api.uploads = [ + _upload(1, status="imported"), + _upload(2, status="failed", failed=30), + _upload(3, status="duplicate"), + ] at = _history(api) _apply(at, Status="failed") @@ -213,10 +267,12 @@ def test_the_uploader_filter(api): def test_the_date_range_includes_the_whole_of_the_last_day_and_nothing_after_it(api): day = date(2026, 11, 18) - api.uploads = [_upload(1, "late.csv", at=datetime(2026, 11, 18, 23, 59, tzinfo=timezone.utc)), - _upload(2, "next.csv", at=datetime(2026, 11, 19, 0, 0, tzinfo=timezone.utc)), - _upload(3, "early.csv", at=datetime(2026, 11, 17, 0, 0, tzinfo=timezone.utc)), - _upload(4, "before.csv", at=datetime(2026, 11, 16, 23, 59, tzinfo=timezone.utc))] + api.uploads = [ + _upload(1, "late.csv", at=datetime(2026, 11, 18, 23, 59, tzinfo=timezone.utc)), + _upload(2, "next.csv", at=datetime(2026, 11, 19, 0, 0, tzinfo=timezone.utc)), + _upload(3, "early.csv", at=datetime(2026, 11, 17, 0, 0, tzinfo=timezone.utc)), + _upload(4, "before.csv", at=datetime(2026, 11, 16, 23, 59, tzinfo=timezone.utc)), + ] at = _history(api) _apply(at, From=date(2026, 11, 17), To=day) @@ -232,12 +288,14 @@ def test_filters_that_match_nothing_say_so_and_blank_filters_are_not_sent(api): at = _apply(at, **{"File name contains": " "}) assert len(_frame(at)) == 3, "blank again: everything is back" - assert all(c[3].get("file") == "no such file" or "file" not in c[3] for c in api.list_calls()), \ + assert all(c[3].get("file") == "no such file" or "file" not in c[3] for c in api.list_calls()), ( "a blank filter is never sent" + ) # ── pages ───────────────────────────────────────────────────────────────────────────────── + def test_the_list_pages_by_twenty_five_and_knows_there_is_a_next_page_without_a_count(api): api.uploads = [_upload(i, f"f{i:02}.csv") for i in range(1, 31)] at = _history(api) @@ -267,14 +325,32 @@ def test_applying_a_filter_goes_back_to_the_first_page(api): # ── one import: why rows failed (React: stored-row-errors.test.tsx) ─────────────────────── + def _failed_import(api, errors, failed=None, **extra): - api.uploads = [_upload(1, "bad.csv", "partly_imported", total=300, failed=failed or len(errors), - reason="2 rows failed")] - api.details["1"] = {"id": "1", "fileName": "bad.csv", "status": "partly_imported", "totalRows": 300, - "importedRows": 298, "failedRows": failed or len(errors), "rowErrors": errors, - "logs": [{"ts": 1_795_000_000_123, "step": "cast_rows", "level": "warn", - "message": "2 rows failed validation", "count": 2}], - "uploader": "alice", "state": "imported", **extra} + api.uploads = [ + _upload(1, "bad.csv", "partly_imported", total=300, failed=failed or len(errors), reason="2 rows failed") + ] + api.details["1"] = { + "id": "1", + "fileName": "bad.csv", + "status": "partly_imported", + "totalRows": 300, + "importedRows": 298, + "failedRows": failed or len(errors), + "rowErrors": errors, + "logs": [ + { + "ts": 1_795_000_000_123, + "step": "cast_rows", + "level": "warn", + "message": "2 rows failed validation", + "count": 2, + } + ], + "uploader": "alice", + "state": "imported", + **extra, + } def _open(at, uid="1"): @@ -284,13 +360,20 @@ def _open(at, uid="1"): def test_choosing_an_import_lists_the_reasons_the_server_stored(api): - _failed_import(api, [{"rowNumber": 7, "column": "amount", "value": "x", "reason": '"x" is not a whole number'}, - {"rowNumber": 14, "column": "amount", "value": "y", "reason": '"y" is not a whole number'}]) + _failed_import( + api, + [ + {"rowNumber": 7, "column": "amount", "value": "x", "reason": '"x" is not a whole number'}, + {"rowNumber": 14, "column": "amount", "value": "y", "reason": '"y" is not a whole number'}, + ], + ) at = _open(_history(api)) assert at.subheader[0].value == "` bad.csv `" - assert "Partly imported · 2 of 300 rows failed · uploaded by alice · 2026-11-18 00:00 UTC" in [c.value for c in at.caption] + assert "Partly imported · 2 of 300 rows failed · uploaded by alice · 2026-11-18 00:00 UTC" in [ + c.value for c in at.caption + ] assert [i.value for i in at.info] == ["Why: ` 2 rows failed `"] frame = at.table[1].value assert frame.index.name == "Row" and list(frame.columns) == ["Column", "Value", "Reason"] @@ -300,13 +383,16 @@ def test_choosing_an_import_lists_the_reasons_the_server_stored(api): def test_it_says_so_when_the_server_kept_fewer_reasons_than_rows_failed(api): - _failed_import(api, [{"rowNumber": i, "column": "a", "value": "x", "reason": "bad"} for i in range(1, 201)], failed=351) + _failed_import( + api, [{"rowNumber": i, "column": "a", "value": "x", "reason": "bad"} for i in range(1, 201)], failed=351 + ) at = _open(_history(api)) assert len(at.table[1].value) == 200 assert "Showing the first 200 of 351 failed rows: the server keeps the reasons for the first 200 only." in [ - c.value for c in at.caption] + c.value for c in at.caption + ] def test_it_says_so_when_no_reasons_were_stored(api): @@ -321,6 +407,7 @@ def test_it_says_so_when_no_reasons_were_stored(api): def test_the_step_log_is_shown_in_utc_whatever_the_servers_own_zone(api, monkeypatch): import time + monkeypatch.setenv("TZ", "Australia/Sydney") # ten hours from UTC: local time would show if hasattr(time, "tzset"): # not on Windows, where the zone cannot be changed from inside the process time.tzset() @@ -348,8 +435,17 @@ def test_an_import_with_no_step_log_says_so(api): def test_a_rejected_import_offers_its_reason_as_a_report_even_with_no_row_errors(api): api.uploads = [_upload(1, "nope.csv", "rejected", total=None, reason="The file has no header row")] - api.details["1"] = {"id": "1", "fileName": "nope.csv", "status": "rejected", "totalRows": None, "failedRows": 0, - "rowErrors": [], "logs": [], "uploader": "alice", "state": "rejected"} + api.details["1"] = { + "id": "1", + "fileName": "nope.csv", + "status": "rejected", + "totalRows": None, + "failedRows": 0, + "rowErrors": [], + "logs": [], + "uploader": "alice", + "state": "rejected", + } at = _open(_history(api)) @@ -375,6 +471,7 @@ def test_the_error_report_downloads_are_named_for_the_file(api): # ── a report of the whole filtered list ─────────────────────────────────────────────────── + def test_a_report_collects_every_matching_import_not_only_the_page(api): api.uploads = [_upload(i, f"f{i:04}.csv") for i in range(1, 1201)] at = _history(api) @@ -422,6 +519,7 @@ def test_the_report_asks_for_what_the_filters_ask_for(api): # ── the list is cached and never shared ─────────────────────────────────────────────────── + def test_the_list_is_fetched_once_for_many_reruns_and_again_on_refresh(api): at = _history(api) _open(at) @@ -445,6 +543,7 @@ def test_one_sessions_list_is_never_shown_to_another(api): # ── a session the server ended, a server that is down ──────────────────────────────────── + def test_a_session_the_server_ended_signs_the_person_out_with_a_reason(api): api.dead.add("tok-1") @@ -472,11 +571,21 @@ def test_an_api_that_is_down_says_so_instead_of_failing(api): # ── text from a file is shown as written ───────────────────────────────────────────────── + def test_a_file_name_and_a_reason_that_look_like_links_show_as_written(api): evil = "[click](https://evil.example/login)" api.uploads = [_upload(1, f"{evil}.csv", "failed", failed=30, reason=f"see {evil}")] - api.details["1"] = {"id": "1", "fileName": f"{evil}.csv", "status": "failed", "totalRows": 30, "failedRows": 30, - "rowErrors": [], "logs": [], "uploader": "alice", "state": "rejected"} + api.details["1"] = { + "id": "1", + "fileName": f"{evil}.csv", + "status": "failed", + "totalRows": 30, + "failedRows": 30, + "rowErrors": [], + "logs": [], + "uploader": "alice", + "state": "rejected", + } at = _open(_history(api)) @@ -486,10 +595,23 @@ def test_a_file_name_and_a_reason_that_look_like_links_show_as_written(api): # ── the server's audit events ──────────────────────────────────────────────────────────── + def _events(n=3): - return [{"id": str(i), "performedAt": (T0 - timedelta(minutes=i)).isoformat(), "actor": "rita" if i % 2 else "ada", - "action": "upload" if i % 2 else "import", "fileId": None, "fileName": f"f{i}.csv", "tableName": f"t{i}", - "mode": "dynamic", "before": None, "after": None} for i in range(1, n + 1)] + return [ + { + "id": str(i), + "performedAt": (T0 - timedelta(minutes=i)).isoformat(), + "actor": "rita" if i % 2 else "ada", + "action": "upload" if i % 2 else "import", + "fileId": None, + "fileName": f"f{i}.csv", + "tableName": f"t{i}", + "mode": "dynamic", + "before": None, + "after": None, + } + for i in range(1, n + 1) + ] def _show_events(api, who="ada", n=3): @@ -523,8 +645,15 @@ def test_the_events_filters_are_sent_as_the_react_panel_sent_them(api): _apply(at, Actor=" rita ", Action="upload", File="f1", From=date(2026, 11, 18), To=date(2026, 11, 18)) - assert api.event_calls()[-1][3] == {"limit": 100, "offset": 0, "actor": "rita", "action": "upload", "file": "f1", - "from": "2026-11-18T00:00:00+00:00", "to": "2026-11-19T00:00:00+00:00"} + assert api.event_calls()[-1][3] == { + "limit": 100, + "offset": 0, + "actor": "rita", + "action": "upload", + "file": "f1", + "from": "2026-11-18T00:00:00+00:00", + "to": "2026-11-19T00:00:00+00:00", + } assert list(at.table[0].value["File"]) == ["` f1.csv `"] assert "1 event · OFFICIAL: Sensitive" in [c.value for c in at.caption] @@ -587,16 +716,29 @@ def test_a_session_that_ends_while_reading_events_signs_out(api): # ── what the model asks and says ───────────────────────────────────────────────────────── + def test_day_start_is_midnight_utc(): assert h.day_start(date(2026, 3, 1)) == "2026-03-01T00:00:00+00:00" def test_params_leave_out_blank_filters_and_the_to_day_runs_to_the_next_midnight(): assert h.uploads_params() == {"limit": 26, "offset": 0} - assert h.uploads_params(file=" a ", status="failed", uploader="", date_from=date(2026, 12, 31), - date_to=date(2026, 12, 31), limit=5, offset=10) == { - "limit": 5, "offset": 10, "file": "a", "status": "failed", "from": "2026-12-31T00:00:00+00:00", - "to": "2027-01-01T00:00:00+00:00"} + assert h.uploads_params( + file=" a ", + status="failed", + uploader="", + date_from=date(2026, 12, 31), + date_to=date(2026, 12, 31), + limit=5, + offset=10, + ) == { + "limit": 5, + "offset": 10, + "file": "a", + "status": "failed", + "from": "2026-12-31T00:00:00+00:00", + "to": "2027-01-01T00:00:00+00:00", + } def test_an_events_download_is_not_paged(): @@ -610,14 +752,19 @@ def test_page_of_keeps_a_page_and_says_whether_more_follow(): assert h.page_of([]) == ([], False) -@pytest.mark.parametrize("have, cap, page, expect_rows, expect_capped, expect_calls", [ - (0, 10, 4, 0, False, [(4, 0)]), - (7, 10, 4, 7, False, [(4, 0), (4, 4)]), - (10, 10, 4, 10, False, [(4, 0), (4, 4), (3, 8)]), # exactly the cap: nothing more, so not cut short - (11, 10, 4, 10, True, [(4, 0), (4, 4), (3, 8)]), # one more than the cap: cut short - (50, 10, 4, 10, True, [(4, 0), (4, 4), (3, 8)]), -]) -def test_collect_stops_at_the_cap_and_knows_if_there_was_more(have, cap, page, expect_rows, expect_capped, expect_calls): +@pytest.mark.parametrize( + "have, cap, page, expect_rows, expect_capped, expect_calls", + [ + (0, 10, 4, 0, False, [(4, 0)]), + (7, 10, 4, 7, False, [(4, 0), (4, 4)]), + (10, 10, 4, 10, False, [(4, 0), (4, 4), (3, 8)]), # exactly the cap: nothing more, so not cut short + (11, 10, 4, 10, True, [(4, 0), (4, 4), (3, 8)]), # one more than the cap: cut short + (50, 10, 4, 10, True, [(4, 0), (4, 4), (3, 8)]), + ], +) +def test_collect_stops_at_the_cap_and_knows_if_there_was_more( + have, cap, page, expect_rows, expect_capped, expect_calls +): calls = [] def fetch(limit, offset): @@ -631,11 +778,13 @@ def fetch(limit, offset): def test_the_statuses_offered_are_the_ones_the_api_knows(): from api.routers.csv_routes import _UPLOAD_STATUSES + assert {s for s, _ in h.STATUSES if s} == set(_UPLOAD_STATUSES) def test_the_actions_offered_are_the_ones_the_api_records(): from api.services.audit import VALID_ACTIONS + assert set(h.AUDIT_ACTIONS) == set(VALID_ACTIONS) @@ -643,8 +792,11 @@ def test_outcome_line_covers_a_clean_a_partial_and_a_rejected_import(): up = _upload(1) assert h.outcome_line(up, {"status": "imported", "totalRows": 1, "failedRows": 0}).startswith("Imported · 1 row · ") assert h.outcome_line(up, {"status": "partly_imported", "totalRows": None, "failedRows": 2}).startswith( - "Partly imported · 2 of ? rows failed") - assert h.outcome_line(_upload(1, status="rejected", uploader=None), {"status": "rejected"}).startswith("Rejected · ") + "Partly imported · 2 of ? rows failed" + ) + assert h.outcome_line(_upload(1, status="rejected", uploader=None), {"status": "rejected"}).startswith( + "Rejected · " + ) def test_errors_note_only_when_the_server_kept_fewer_than_failed(): diff --git a/tests/unit/test_streamlit_outcomes.py b/tests/unit/test_streamlit_outcomes.py index dc11eb1..2af97a1 100644 --- a/tests/unit/test_streamlit_outcomes.py +++ b/tests/unit/test_streamlit_outcomes.py @@ -4,9 +4,11 @@ (ok, duplicate_file, invalid_structure, error), the failed-rows and type-provenance notes, and what is new here: file text must not become Markdown, a timeout is not "can't reach the API", and the version and schema notes (M5). """ + import pytest from tests.unit import streamlit_harness # noqa: F401 (puts streamlit_app on the path) + # The imports below need the path the import above sets up, so the import sort must not move them up. # isort: split @@ -15,12 +17,24 @@ pytestmark = [pytest.mark.unit, pytest.mark.regression] -OK = {"status": "ok", "fileId": "1", "tableName": "csv_people_v1", "totalRows": 30, "insertedRows": 26, - "duplicateRowsSkipped": 0, "failedRows": 4, "columns": ["id"], "types": ["int8"], "rowErrors": [], "logs": []} +OK = { + "status": "ok", + "fileId": "1", + "tableName": "csv_people_v1", + "totalRows": 30, + "insertedRows": 26, + "duplicateRowsSkipped": 0, + "failedRows": 4, + "columns": ["id"], + "types": ["int8"], + "rowErrors": [], + "logs": [], +} # ── the four answers (React: classifyUploadResult) ───────────────────────────────────────── + def test_a_clean_import_is_a_success_that_says_how_many_rows_went_in(): out = o.classify("people.csv", {**OK, "failedRows": 0, "insertedRows": 30}) @@ -40,8 +54,16 @@ def test_an_overwrite_is_said_first_as_the_react_app_said_it(): def test_the_same_bytes_again_is_a_duplicate_and_says_nothing_changed(): - out = o.classify("again.csv", {"status": "duplicate_file", "reason": "content", "existingFileName": "people.csv", - "tableName": "csv_people_v1", "logs": []}) + out = o.classify( + "again.csv", + { + "status": "duplicate_file", + "reason": "content", + "existingFileName": "people.csv", + "tableName": "csv_people_v1", + "logs": [], + }, + ) assert (out.kind, out.level) == ("duplicate", "warning") assert out.message == "` again.csv `: already imported as ` people.csv `. Nothing was changed." @@ -59,13 +81,16 @@ def test_the_old_same_name_different_contents_duplicate_is_still_worded(): assert out.kind == "duplicate" and "different contents" in out.message -@pytest.mark.parametrize("reason, said", [ - ("empty", "The file is empty."), - ("header_only", "The file has a header row but no data rows."), - ("no_columns", "The header row has no column names."), - ("parse_failed", "The file could not be read as CSV."), - ("something_new", "The file has no usable structure."), -]) +@pytest.mark.parametrize( + "reason, said", + [ + ("empty", "The file is empty."), + ("header_only", "The file has a header row but no data rows."), + ("no_columns", "The header row has no column names."), + ("parse_failed", "The file could not be read as CSV."), + ("something_new", "The file has no usable structure."), + ], +) def test_a_file_with_no_usable_structure_says_why_in_plain_words(reason, said): out = o.classify("a.csv", {"status": "invalid_structure", "reason": reason, "logs": []}) @@ -73,13 +98,17 @@ def test_a_file_with_no_usable_structure_says_why_in_plain_words(reason, said): def test_the_apis_own_message_wins_over_the_plain_words(): - out = o.classify("a.csv", {"status": "invalid_structure", "reason": "empty", "message": "Nothing to import", "logs": []}) + out = o.classify( + "a.csv", {"status": "invalid_structure", "reason": "empty", "message": "Nothing to import", "logs": []} + ) assert out.message == "` a.csv `: ` Nothing to import `" def test_an_error_carries_the_apis_message(): - out = o.classify("a.csv", {"status": "error", "message": "Provided 2 column types but the CSV has 3 columns.", "logs": []}) + out = o.classify( + "a.csv", {"status": "error", "message": "Provided 2 column types but the CSV has 3 columns.", "logs": []} + ) assert (out.kind, out.level) == ("error", "error") assert out.message == "` a.csv `: ` Provided 2 column types but the CSV has 3 columns. `" @@ -91,6 +120,7 @@ def test_an_error_with_no_message_still_says_it_failed(): # ── the call itself failed (React: classifyThrownError) ─────────────────────────────────── + def test_a_refusal_from_the_api_is_an_error_in_its_words(): out = o.classify_error("a.csv", api_client.ApiError(413, "File too large")) @@ -107,45 +137,78 @@ def test_no_answer_in_time_is_not_a_failure_because_the_server_may_still_be_impo out = o.classify_error("big.csv", api_client.TimedOut(600)) assert (out.kind, out.level) == ("unknown", "warning") - assert "may still be working" in out.message and "Import history" in out.message and "Can't reach" not in out.message + assert ( + "may still be working" in out.message and "Import history" in out.message and "Can't reach" not in out.message + ) # ── text from a file is shown as written ────────────────────────────────────────────────── + def test_a_file_name_and_an_api_message_that_look_like_links_are_in_code_spans(): evil = "[click](https://evil.example/x)" - assert o.classify(f"{evil}.csv", {"status": "error", "message": f"bad {evil}"}).message == \ - f"` {evil}.csv `: ` bad {evil} `" - assert o.classify_error(f"{evil}.csv", api_client.ApiError(422, f"bad {evil}")).message == \ - f"` {evil}.csv `: ` bad {evil} `" + assert ( + o.classify(f"{evil}.csv", {"status": "error", "message": f"bad {evil}"}).message + == f"` {evil}.csv `: ` bad {evil} `" + ) + assert ( + o.classify_error(f"{evil}.csv", api_client.ApiError(422, f"bad {evil}")).message + == f"` {evil}.csv `: ` bad {evil} `" + ) # ── what else is worth saying (M5) ──────────────────────────────────────────────────────── -def test_a_new_version_says_which_dataset_and_how_the_columns_compare(): - notes = o.result_notes({**OK, "dataset": "people", "version": 2, "schemaCheck": { - "compatible": True, "added": ["email"], "removed": [], "changed": [], - "comparedTo": {"fileName": "people.csv", "version": 1, "tableName": "csv_people_v1"}}, - "duplicateRowsAcrossUploads": 3}) - assert notes == ["Version 2 of the dataset ` people `.", - "Columns match the previous version (version 1), with 1 new: ` email `.", - "3 rows already appear in an earlier version of this dataset."] +def test_a_new_version_says_which_dataset_and_how_the_columns_compare(): + notes = o.result_notes( + { + **OK, + "dataset": "people", + "version": 2, + "schemaCheck": { + "compatible": True, + "added": ["email"], + "removed": [], + "changed": [], + "comparedTo": {"fileName": "people.csv", "version": 1, "tableName": "csv_people_v1"}, + }, + "duplicateRowsAcrossUploads": 3, + } + ) + + assert notes == [ + "Version 2 of the dataset ` people `.", + "Columns match the previous version (version 1), with 1 new: ` email `.", + "3 rows already appear in an earlier version of this dataset.", + ] def test_columns_that_differ_say_what_was_removed_retyped_and_added(): - notes = o.result_notes({"version": 2, "dataset": "d", "schemaCheck": { - "compatible": False, "added": ["c"], "removed": ["a"], "changed": [{"column": "b", "was": "int8", "now": "text"}], - "comparedTo": {"version": 1}}}) - - assert notes[1] == ("Columns differ from the previous version (version 1): removed ` a `; " - "retyped ` b ` (int8 → text); new ` c `.") + notes = o.result_notes( + { + "version": 2, + "dataset": "d", + "schemaCheck": { + "compatible": False, + "added": ["c"], + "removed": ["a"], + "changed": [{"column": "b", "was": "int8", "now": "text"}], + "comparedTo": {"version": 1}, + }, + } + ) + + assert notes[1] == ( + "Columns differ from the previous version (version 1): removed ` a `; retyped ` b ` (int8 → text); new ` c `." + ) def test_a_first_version_with_nothing_to_compare_has_just_the_version(): assert o.result_notes({**OK, "dataset": "people", "version": 1, "schemaCheck": None}) == [ - "Version 1 of the dataset ` people `."] + "Version 1 of the dataset ` people `." + ] def test_rows_skipped_as_duplicates_within_the_file_are_counted(): @@ -155,14 +218,16 @@ def test_rows_skipped_as_duplicates_within_the_file_are_counted(): def test_a_column_name_that_looks_like_a_link_is_a_code_span_in_a_note(): - notes = o.result_notes({"schemaCheck": {"compatible": False, "added": [], "removed": ["[a](http://x.test)"], - "changed": []}}) + notes = o.result_notes( + {"schemaCheck": {"compatible": False, "added": [], "removed": ["[a](http://x.test)"], "changed": []}} + ) assert "` [a](http://x.test) `" in notes[0] # ── the notes under a file in the list (React: failedRowsNote, typesProvenanceNote) ─────── + def test_failed_rows_are_named_out_of_the_total(): assert o.failed_rows_note(51, 171) == "51 of 171 rows failed" assert o.failed_rows_note(51, None) == "51 rows failed" diff --git a/tests/unit/test_streamlit_review.py b/tests/unit/test_streamlit_review.py index a95c0ec..5690031 100644 --- a/tests/unit/test_streamlit_review.py +++ b/tests/unit/test_streamlit_review.py @@ -8,6 +8,7 @@ be read as Markdown, the cached list of uploads must not leak between sessions, and the row-number box must survive a change of page. AppTest cannot click a row in the grid; e2e/test_streamlit_review.py does. """ + import re import sys from datetime import datetime, timedelta, timezone @@ -44,8 +45,17 @@ def _later() -> str: def _row(n, cells, **extra): - return {"rowNumber": n, "original": list(cells), "current": list(cells), "editedColumns": [], - "decision": "include", "decisionReason": None, "duplicateOfEarlierVersion": None, "errors": [], **extra} + return { + "rowNumber": n, + "original": list(cells), + "current": list(cells), + "editedColumns": [], + "decision": "include", + "decisionReason": None, + "duplicateOfEarlierVersion": None, + "errors": [], + **extra, + } def _people() -> list[dict]: @@ -53,15 +63,30 @@ def _people() -> list[dict]: return [ _row(1, ["1", "a"], current=["10", "a"], editedColumns=[0]), _row(2, ["x", "b"], errors=[{"column": "n", "value": "x", "reason": '"x" is not a whole number'}]), - _row(3, ["3", "c"], decision="exclude", decisionReason="duplicate of row 1", - errors=[{"column": "(database)", "value": "", "reason": "violates check constraint"}]), + _row( + 3, + ["3", "c"], + decision="exclude", + decisionReason="duplicate of row 1", + errors=[{"column": "(database)", "value": "", "reason": "violates check constraint"}], + ), ] def _attempt(uid, name, status, total=3, failed=0, **extra): - return {"id": uid, "file_name": name, "mode": "dynamic", "status": status, "total_rows": total, - "imported_rows": (total or 0) - failed, "failed_rows": failed, "uploader": "alice", - "uploaded_at": "2026-11-18T01:00:00+00:00", "failure_reason": None, **extra} + return { + "id": uid, + "file_name": name, + "mode": "dynamic", + "status": status, + "total_rows": total, + "imported_rows": (total or 0) - failed, + "failed_rows": failed, + "uploader": "alice", + "uploaded_at": "2026-11-18T01:00:00+00:00", + "failure_reason": None, + **extra, + } UPLOADS = [ # newest first, as the API lists them; "7" is the one with rows to look at @@ -106,11 +131,18 @@ def __call__(self, method, path, token=None, **kwargs): def _page(self, uid, offset, limit): d = self.data[uid] - rows = d["rows"][offset:offset + limit] - return {"fileName": next(u["file_name"] for u in self.uploads if u["id"] == uid), "columns": d["columns"], - "types": d["types"], "total": len(d["rows"]), "offset": offset, "limit": limit, - "excludedRows": sum(r["decision"] == "exclude" for r in d["rows"]), - "editedRows": sum(bool(r["editedColumns"]) for r in d["rows"]), "rows": rows} + rows = d["rows"][offset : offset + limit] + return { + "fileName": next(u["file_name"] for u in self.uploads if u["id"] == uid), + "columns": d["columns"], + "types": d["types"], + "total": len(d["rows"]), + "offset": offset, + "limit": limit, + "excludedRows": sum(r["decision"] == "exclude" for r in d["rows"]), + "editedRows": sum(bool(r["editedColumns"]) for r in d["rows"]), + "rows": rows, + } def _change(self, uid, n, what, body): if uid in self.frozen: @@ -122,14 +154,23 @@ def _change(self, uid, n, what, body): if what == "decision": row["decision"], row["decisionReason"] = body["decision"], body["reason"] self.history.setdefault((uid, n), []).append( - {"kind": "decision", "at": at, "actor": "rita", "reason": body["reason"], "decision": body["decision"]}) + {"kind": "decision", "at": at, "actor": "rita", "reason": body["reason"], "decision": body["decision"]} + ) else: i = int(what.split("/")[1]) if body["value"] == row["current"][i]: raise api_client.ApiError(422, "The new value is the same as the current one") self.history.setdefault((uid, n), []).append( - {"kind": "edit", "at": at, "actor": "rita", "reason": body["reason"], - "column": self.data[uid]["columns"][i], "oldValue": row["current"][i], "newValue": body["value"]}) + { + "kind": "edit", + "at": at, + "actor": "rita", + "reason": body["reason"], + "column": self.data[uid]["columns"][i], + "oldValue": row["current"][i], + "newValue": body["value"], + } + ) row["current"][i] = body["value"] row["editedColumns"] = sorted({*row["editedColumns"], i}) return row @@ -161,8 +202,13 @@ def api(monkeypatch): def _screen(api, who="rita", token="tok-1") -> AppTest: """The review screen with a session already in place.""" at = AppTest.from_string(HARNESS.format(app_dir=str(APP_DIR)), default_timeout=30) - at.session_state["session"] = {"token": token, "expiresAt": _later(), "username": who, "tenant": "acme", - "role": ROLES[who]} + at.session_state["session"] = { + "token": token, + "expiresAt": _later(), + "username": who, + "tenant": "acme", + "role": ROLES[who], + } at.run() assert not at.exception, at.exception return at @@ -212,15 +258,18 @@ def _texts(at): # ── which upload: every attempt, #187 ───────────────────────────────────────────────────────── + def test_every_attempt_is_listed_failed_and_partial_ones_included(api): at = _screen(api) options = _upload_box(at).options - assert options == ["#7 people.csv · Imported · 3 rows", - "#8 bad.csv · Failed · 5 of 5 rows failed", - "#9 half.csv · Partly imported · 4 of 10 rows failed", - "#10 nope.csv · Rejected · 0 rows", - "#11 same.csv · Duplicate · 3 rows"] + assert options == [ + "#7 people.csv · Imported · 3 rows", + "#8 bad.csv · Failed · 5 of 5 rows failed", + "#9 half.csv · Partly imported · 4 of 10 rows failed", + "#10 nope.csv · Rejected · 0 rows", + "#11 same.csv · Duplicate · 3 rows", + ] def test_the_failed_or_partial_filter_leaves_the_ones_that_need_attention(api): @@ -264,6 +313,7 @@ def test_the_chosen_upload_stays_chosen_when_the_list_changes_under_it(api): # ── every row, with its validation, edits and decision ───────────────────────────────────────── + def test_the_page_shows_every_row_with_its_status_and_the_count_line(api): at = _pick_upload(_screen(api), "7") @@ -272,8 +322,10 @@ def test_the_page_shows_every_row_with_its_status_and_the_count_line(api): assert list(frame["Row status"]) == ["Included", "Invalid", "Excluded"] assert list(frame["n"]) == ["10", "x", "3"], "the current values, so the edit shows" assert at.subheader[0].value == "` people.csv `" - assert at.caption[0].value == ("3 rows · 1 excluded · 1 edited. Changes are saved with the upload for review. " - "They don't change the imported table.") + assert at.caption[0].value == ( + "3 rows · 1 excluded · 1 edited. Changes are saved with the upload for review. " + "They don't change the imported table." + ) def test_a_row_shows_why_it_is_invalid_what_was_edited_and_the_decision_and_the_database_reason(api): @@ -300,6 +352,7 @@ def test_no_row_is_shown_until_one_is_chosen(api): # ── a reviewer excludes a row with a required reason ─────────────────────────────────────────── + def test_excluding_needs_a_reason_and_sends_the_row_the_decision_and_the_reason(api): at = _review(_screen(api), row=2) assert [t.label for t in at.tabs] == ["Edit a cell", "Exclude row", "History"] @@ -312,7 +365,8 @@ def test_excluding_needs_a_reason_and_sends_the_row_the_decision_and_the_reason( assert not at.exception, at.exception assert [(c[0], c[1], c[3]) for c in api.writes()] == [ - ("PUT", "/api/csv/uploads/7/rows/2/decision", {"decision": "exclude", "reason": "bad row"})] + ("PUT", "/api/csv/uploads/7/rows/2/decision", {"decision": "exclude", "reason": "bad row"}) + ] assert [s.value for s in at.success] == ["Saved: row 2 excluded."] assert list(at.dataframe[0].value["Row status"]) == ["Included", "Excluded", "Excluded"] assert _widget(at.text_input, "Reason to include this row (required)").value == "", "the form starts empty again" @@ -330,6 +384,7 @@ def test_a_whitespace_only_reason_is_refused_too(api): # ── a reviewer edits a cell as a new value with a reason ─────────────────────────────────────── + def test_editing_shows_the_original_and_sends_the_new_value_and_reason_by_column_position(api): at = _review(_screen(api), row=2) @@ -341,7 +396,8 @@ def test_editing_shows_the_original_and_sends_the_new_value_and_reason_by_column assert not at.exception, at.exception assert [(c[1], c[3]) for c in api.writes()] == [ - ("/api/csv/uploads/7/rows/2/cells/0", {"value": "2", "reason": "typo"})] + ("/api/csv/uploads/7/rows/2/cells/0", {"value": "2", "reason": "typo"}) + ] assert [s.value for s in at.success] == ["Saved: row 2, ` n `."] assert list(at.dataframe[0].value["n"]) == ["10", "2", "3"] assert any(c.value == "` n `: original ` x `, now ` 2 `" for c in at.caption) @@ -383,6 +439,7 @@ def test_the_history_tab_lists_what_was_changed_by_whom_and_why(api): # ── other roles can view but not change ──────────────────────────────────────────────────────── + @pytest.mark.parametrize("who", ["alice", "audrey"]) def test_other_roles_can_look_but_not_change(api, who): at = _review(_screen(api, who), row=2) @@ -402,6 +459,7 @@ def test_a_tenant_admin_can_change_too(api): # ── a session the server has ended, or a server that is down ─────────────────────────────────── + def test_a_session_the_server_ended_during_a_save_signs_the_person_out_with_a_reason(api): at = _review(_screen(api), row=2) api.expire_on_write = True @@ -426,8 +484,13 @@ def test_an_api_that_is_down_says_so_instead_of_failing(api): api.down = True at = AppTest.from_string(HARNESS.format(app_dir=str(APP_DIR)), default_timeout=30) - at.session_state["session"] = {"token": "t", "expiresAt": _later(), "username": "rita", "tenant": "acme", - "role": "reviewer"} + at.session_state["session"] = { + "token": "t", + "expiresAt": _later(), + "username": "rita", + "tenant": "acme", + "role": "reviewer", + } at.run() assert not at.exception and "Can't reach the API" in _errors(at)[0] @@ -435,6 +498,7 @@ def test_an_api_that_is_down_says_so_instead_of_failing(api): # ── the list of uploads is cached, and never shared between sessions ─────────────────────────── + def test_the_list_is_fetched_once_for_many_reruns_and_again_on_refresh(api): at = _pick_upload(_screen(api), "7") _choose_row(at, 2) @@ -447,8 +511,10 @@ def test_the_list_is_fetched_once_for_many_reruns_and_again_on_refresh(api): def test_one_sessions_list_is_never_shown_to_another(api): - api.lists_by_token = {"tok-a": [_attempt("1", "acme-secret.csv", "imported")], - "tok-b": [_attempt("2", "zed-plans.csv", "imported")]} + api.lists_by_token = { + "tok-a": [_attempt("1", "acme-secret.csv", "imported")], + "tok-b": [_attempt("2", "zed-plans.csv", "imported")], + } api.uploads += api.lists_by_token["tok-a"] + api.lists_by_token["tok-b"] # so the fake can serve their rows api.data["1"] = api.data["2"] = api.data["7"] @@ -472,8 +538,9 @@ def test_the_rows_are_never_cached_because_they_change_as_people_review(api): # ── text from a file is shown as written ─────────────────────────────────────────────────────── + def test_a_cell_that_looks_like_a_link_or_bold_text_shows_as_written(api): - evil = '[click here](https://evil.example/login) **urgent** :warning: $x$ hi user@evil.example' + evil = "[click here](https://evil.example/login) **urgent** :warning: $x$ hi user@evil.example" api.data["7"]["rows"][1]["errors"] = [{"column": "n", "value": evil, "reason": f'"{evil}" is not a whole number'}] api.data["7"]["rows"][1]["original"][1] = evil api.data["7"]["rows"][1]["current"][1] = evil @@ -488,13 +555,21 @@ def test_a_cell_that_looks_like_a_link_or_bold_text_shows_as_written(api): def test_a_file_name_and_a_reason_in_the_history_show_as_written(api): api.uploads[0]["file_name"] = "[a](https://evil.example)**.csv" - api.history[("7", 2)] = [{"kind": "decision", "at": "2026-11-18T02:30:00+00:00", "actor": "r[x](y)", - "reason": "see https://evil.example now", "decision": "exclude"}] + api.history[("7", 2)] = [ + { + "kind": "decision", + "at": "2026-11-18T02:30:00+00:00", + "actor": "r[x](y)", + "reason": "see https://evil.example now", + "decision": "exclude", + } + ] at = _review(_screen(api), row=2) assert at.subheader[0].value == "` [a](https://evil.example)**.csv `" assert [w.value for w in at.markdown if "UTC" in w.value] == [ - "2026-11-18 02:30 UTC · ` r[x](y) ` · **Excluded** \n` see https://evil.example now `"] + "2026-11-18 02:30 UTC · ` r[x](y) ` · **Excluded** \n` see https://evil.example now `" + ] def test_a_file_with_a_column_called_status_does_not_clash_with_the_status_column(api): @@ -507,6 +582,7 @@ def test_a_file_with_a_column_called_status_does_not_clash_with_the_status_colum # ── pages ────────────────────────────────────────────────────────────────────────────────────── + def _big(api, total=250): api.data["7"]["rows"] = [_row(i, [str(i), f"p{i}"]) for i in range(1, total + 1)] api.uploads[0]["total_rows"] = total @@ -551,18 +627,25 @@ def test_a_row_chosen_on_a_later_page_is_shown_with_its_own_data(api): # ── what the model says ──────────────────────────────────────────────────────────────────────── -@pytest.mark.parametrize("text, shown", [ - ("[a](b)", "` [a](b) `"), - ("**x**_y_", "` **x**_y_ `"), - ("https://evil.example/x www.evil.example a@evil.example", "` https://evil.example/x www.evil.example a@evil.example `"), - ("a`b", "`` a`b ``"), - ("``", "``` `` ```"), - ("`", "`` ` ``"), - ("a\r\nb\tc", "` a b c `"), - ("", "` `"), - (None, "` None `"), - (5, "` 5 `"), -]) + +@pytest.mark.parametrize( + "text, shown", + [ + ("[a](b)", "` [a](b) `"), + ("**x**_y_", "` **x**_y_ `"), + ( + "https://evil.example/x www.evil.example a@evil.example", + "` https://evil.example/x www.evil.example a@evil.example `", + ), + ("a`b", "`` a`b ``"), + ("``", "``` `` ```"), + ("`", "`` ` ``"), + ("a\r\nb\tc", "` a b c `"), + ("", "` `"), + (None, "` None `"), + (5, "` 5 `"), + ], +) def test_literal_puts_text_in_a_code_span_that_nothing_inside_it_can_end(text, shown): assert m.literal(text) == shown @@ -572,9 +655,10 @@ def test_a_literal_is_one_code_span_holding_exactly_the_text(text): """The CommonMark rule for a code span: a fence of N backticks ends at the next run of exactly N, so the fence must be longer than any run inside, and a single space of padding at each end is not shown.""" import re + span = m.literal(text) fence = re.match(r"`+", span).group() - inner = span[len(fence):-len(fence)] + inner = span[len(fence) : -len(fence)] assert span.endswith(fence) and not span.endswith("`" * (len(fence) + 1)) assert all(len(run) != len(fence) for run in re.findall(r"`+", inner)), "nothing inside can close the span early" assert inner[1:-1] == text, "what is shown is what was in the file" @@ -588,7 +672,8 @@ def test_needs_attention_is_failed_partial_and_rejected_only(): def test_attempt_wording_matches_the_react_list(): assert m.attempt_label(_attempt("1", "a.csv", "imported", total=3)) == "#1 a.csv · Imported · 3 rows" assert m.attempt_label(_attempt("1", "a.csv", "partly_imported", total=10, failed=2)).endswith( - "Partly imported · 2 of 10 rows failed") + "Partly imported · 2 of 10 rows failed" + ) assert m.attempt_label(_attempt("1", "a.csv", "failed", total=None, failed=2)).endswith("2 of ? rows failed") assert m.attempt_label(_attempt("1", "a.csv", "mystery", total=0)).endswith("mystery · 0 rows") assert m.reviewable(_attempt("1", "a", "failed")) and not m.reviewable(_attempt("1", "a", "rejected")) @@ -631,6 +716,15 @@ def test_when_gives_utc_takes_a_zoneless_time_as_utc_and_survives_rubbish(): def test_a_history_edit_line_shows_both_values_and_an_unknown_actor(): - line = m.history_line({"kind": "edit", "at": "2026-11-18T02:30:00+00:00", "actor": None, "reason": "typo", - "column": "n", "oldValue": "x", "newValue": "2"}) + line = m.history_line( + { + "kind": "edit", + "at": "2026-11-18T02:30:00+00:00", + "actor": None, + "reason": "typo", + "column": "n", + "oldValue": "x", + "newValue": "2", + } + ) assert line == "2026-11-18 02:30 UTC · ` unknown ` · ` n `: ` x ` → ` 2 ` \n` typo `" diff --git a/tests/unit/test_streamlit_shell.py b/tests/unit/test_streamlit_shell.py index b0833bd..d21717e 100644 --- a/tests/unit/test_streamlit_shell.py +++ b/tests/unit/test_streamlit_shell.py @@ -8,6 +8,7 @@ session ends up signed out with a reason; sign-out leaves nothing for the next tenant (#176); what a role is shown matches what the API will allow; and the Streamlit version stays pinned with telemetry off. """ + import os import subprocess import sys @@ -66,8 +67,7 @@ def __call__(self, method, path, token=None, **kwargs): raise api_client.Unauthorized(401, "Invalid tenant, username or password") tok = f"tok-{len(self.tokens) + 1}" self.tokens[tok] = who - return {"token": tok, "expiresAt": _later(), "username": who[1], "tenant": who[0], - "role": USERS[who]} + return {"token": tok, "expiresAt": _later(), "username": who[1], "tenant": who[0], "role": USERS[who]} if token is None or token in self.dead or token not in self.tokens: raise api_client.Unauthorized(401, "Not signed in") if path == "/api/auth/logout": @@ -114,22 +114,29 @@ def _errors(at): # ── sign-in ─────────────────────────────────────────────────────────────────────────────── + def test_a_signed_out_visitor_sees_only_the_sign_in_page(api): at = _open() assert [t.value for t in at.title] == ["Sign in"] assert [t.label for t in at.text_input] == ["Tenant", "Username", "Password"] - assert [t.proto.type for t in at.text_input] == [TextInputProto.DEFAULT, TextInputProto.DEFAULT, - TextInputProto.PASSWORD], "the password is masked" + assert [t.proto.type for t in at.text_input] == [ + TextInputProto.DEFAULT, + TextInputProto.DEFAULT, + TextInputProto.PASSWORD, + ], "the password is masked" assert not at.exception and not at.sidebar.button, "no sign-out, no session menu" assert api.calls == [], "nothing is asked of the API until someone signs in" -@pytest.mark.parametrize("tenant, username, password", [ - ("acme", "alice", "wrong password entirely"), - ("acme", "nobody", PASSWORD), - ("nowhere", "alice", PASSWORD), -]) +@pytest.mark.parametrize( + "tenant, username, password", + [ + ("acme", "alice", "wrong password entirely"), + ("acme", "nobody", PASSWORD), + ("nowhere", "alice", PASSWORD), + ], +) def test_a_wrong_sign_in_says_what_the_react_app_says_and_gives_no_hint_which_part(api, tenant, username, password): at = _sign_in(_open(), tenant, username, password) @@ -173,10 +180,16 @@ def refuse(method, path, token=None, **kwargs): # ── expiry and a revoked session ────────────────────────────────────────────────────────── + def test_an_expired_session_is_signed_out_with_a_reason_and_nothing_left_over(api): at = _open() - at.session_state["session"] = {"token": "t", "expiresAt": _later(-1), "username": "alice", - "tenant": "acme", "role": "uploader"} + at.session_state["session"] = { + "token": "t", + "expiresAt": _later(-1), + "username": "alice", + "tenant": "acme", + "role": "uploader", + } at.session_state["leftover"] = "something acme's" at.run() @@ -187,8 +200,13 @@ def test_an_expired_session_is_signed_out_with_a_reason_and_nothing_left_over(ap def test_the_reason_is_shown_once(api): at = _open() - at.session_state["session"] = {"token": "t", "expiresAt": _later(-1), "username": "a", "tenant": "b", - "role": "uploader"} + at.session_state["session"] = { + "token": "t", + "expiresAt": _later(-1), + "username": "a", + "tenant": "b", + "role": "uploader", + } at.run() assert len(at.warning) == 1 @@ -235,8 +253,13 @@ def _view(name: str, who=("acme", "alice"), api: FakeApi | None = None) -> AppTe at = AppTest.from_string(HARNESS.format(app_dir=str(APP_DIR), view=name), default_timeout=30) if api is not None: api.tokens["tok-v"] = who - at.session_state["session"] = {"token": "tok-v", "expiresAt": _later(), "username": who[1], - "tenant": who[0], "role": USERS[who]} + at.session_state["session"] = { + "token": "tok-v", + "expiresAt": _later(), + "username": who[1], + "tenant": who[0], + "role": USERS[who], + } return at.run() @@ -260,6 +283,7 @@ def test_a_401_from_any_call_ends_the_session_and_says_why(api): # ── sign-out ────────────────────────────────────────────────────────────────────────────── + def test_sign_out_revokes_the_session_and_leaves_nothing_behind(api): at = _signed_in() token = at.session_state["session"]["token"] @@ -316,14 +340,20 @@ def test_signing_in_starts_from_a_clean_state_even_if_something_was_left(api): # ── roles ───────────────────────────────────────────────────────────────────────────────── + def _listed(at) -> list[str]: return [m.value.removeprefix("- ") for m in at.markdown if m.value.startswith("- ")] -@pytest.mark.parametrize("who, role", [ - (("acme", "alice"), "uploader"), (("acme", "rita"), "reviewer"), - (("acme", "ada"), "tenant_admin"), (("acme", "audrey"), "auditor"), -]) +@pytest.mark.parametrize( + "who, role", + [ + (("acme", "alice"), "uploader"), + (("acme", "rita"), "reviewer"), + (("acme", "ada"), "tenant_admin"), + (("acme", "audrey"), "auditor"), + ], +) def test_home_lists_exactly_what_the_api_will_allow_that_role(api, who, role): at = _signed_in(who) @@ -332,8 +362,9 @@ def test_home_lists_exactly_what_the_api_will_allow_that_role(api, who, role): def test_role_differences_are_visible_and_hold_the_other_way_round(api): - uploader, auditor, reviewer = (_listed(_signed_in(w)) for w in - [("acme", "alice"), ("acme", "audrey"), ("acme", "rita")]) + uploader, auditor, reviewer = ( + _listed(_signed_in(w)) for w in [("acme", "alice"), ("acme", "audrey"), ("acme", "rita")] + ) assert "Upload CSV files" in uploader and "Upload CSV files" not in auditor assert "Read the audit log" in auditor and "Read the audit log" not in uploader @@ -370,16 +401,20 @@ def test_every_permission_has_a_plain_label(): # ── change password ─────────────────────────────────────────────────────────────────────── + def test_change_password_success_keeps_this_session_and_says_so(api): at = _view("change_password", api=api) _change(at, PASSWORD, "a brand new passphrase", "a brand new passphrase") assert [s.value for s in at.success] == [ - "Password changed. You're still signed in here; any other sessions have been signed out."] + "Password changed. You're still signed in here; any other sessions have been signed out." + ] assert "session" in at.session_state - assert api.calls_to("/api/auth/password")[0][3] == {"currentPassword": PASSWORD, - "newPassword": "a brand new passphrase"} + assert api.calls_to("/api/auth/password")[0][3] == { + "currentPassword": PASSWORD, + "newPassword": "a brand new passphrase", + } # The browser empties the fields after the submit; AppTest does not emulate that, so check the form is set to. form = next(c for c in at.main.children.values() if c.type == "form") assert form.proto.form.clear_on_submit is True, "the passwords are not left in the form" @@ -432,6 +467,7 @@ def test_a_422_from_the_api_is_explained_in_the_same_words(api): # ── configuration ───────────────────────────────────────────────────────────────────────── + def test_usage_statistics_are_off(): """Streamlit sends them by default; this app is for on-premises and air-gapped installs.""" config = tomllib.loads((APP_DIR / ".streamlit" / "config.toml").read_text(encoding="utf-8")) @@ -439,8 +475,11 @@ def test_usage_statistics_are_off(): def test_streamlit_is_pinned_to_the_version_the_tests_run_against(): - pinned = [ln.strip() for ln in (APP_DIR / "requirements.txt").read_text().splitlines() - if ln.strip().startswith("streamlit")] + pinned = [ + ln.strip() + for ln in (APP_DIR / "requirements.txt").read_text().splitlines() + if ln.strip().startswith("streamlit") + ] assert pinned == [f"streamlit=={st.__version__}"], "bump the pin and the tests together" dev = (ROOT / "requirements-dev.txt").read_text() assert f"streamlit=={st.__version__}" in dev, "CI installs it for these tests" @@ -459,8 +498,9 @@ def run(api_url): env = {k: v for k, v in os.environ.items() if k != "API_URL"} if api_url is not None: env["API_URL"] = api_url - return subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env, - check=True).stdout.strip() + return subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, env=env, check=True + ).stdout.strip() assert run("http://api.internal:9000/") == "http://api.internal:9000", "no trailing slash" assert run(None) == "http://localhost:8000", "the default is the local API" diff --git a/tests/unit/test_streamlit_upload.py b/tests/unit/test_streamlit_upload.py index ad2ee54..6c05389 100644 --- a/tests/unit/test_streamlit_upload.py +++ b/tests/unit/test_streamlit_upload.py @@ -7,6 +7,7 @@ The preview and the files are the real server's: the fake calls api.services.csv_parse.build_preview. """ + import base64 import pytest @@ -14,6 +15,7 @@ from streamlit.testing.v1 import AppTest from tests.unit.streamlit_harness import APP_DIR, ROLES, errors, later, widget + # The imports below need the path the import above sets up, so the import sort must not move them up. # isort: split @@ -39,10 +41,24 @@ """ PEOPLE = b"id,name,amount\n1,ann,10\n2,bob,20\n3,cy,30\n" -OK = {"status": "ok", "fileId": "1", "tableName": "csv_people_v1", "totalRows": 3, "insertedRows": 3, - "duplicateRowsSkipped": 0, "failedRows": 0, "columns": ["id", "name", "amount"], - "types": ["int8", "text", "int8"], "rowErrors": [], "logs": [], "dataset": "people", "version": 1, - "schemaCheck": None, "duplicateRowsAcrossUploads": 0, "uploadId": "5"} +OK = { + "status": "ok", + "fileId": "1", + "tableName": "csv_people_v1", + "totalRows": 3, + "insertedRows": 3, + "duplicateRowsSkipped": 0, + "failedRows": 0, + "columns": ["id", "name", "amount"], + "types": ["int8", "text", "int8"], + "rowErrors": [], + "logs": [], + "dataset": "people", + "version": 1, + "schemaCheck": None, + "duplicateRowsAcrossUploads": 0, + "uploadId": "5", +} class FakeApi: @@ -54,8 +70,11 @@ def __init__(self): self.upload_timeouts: list = [] self.reply = dict(OK) # what the next upload answers: a dict, an Exception, or a callable of the payload self.te_match: str | None = None - self.te_tables = [{"table": "orgs", "exists": True, "rowCount": 0}, {"table": "people", "exists": True, "rowCount": 0}, - {"table": "unbuilt", "exists": False, "rowCount": 0}] + self.te_tables = [ + {"table": "orgs", "exists": True, "rowCount": 0}, + {"table": "people", "exists": True, "rowCount": 0}, + {"table": "unbuilt", "exists": False, "rowCount": 0}, + ] self.dead: set[str] = set() self.preview_raises: Exception | None = None @@ -100,8 +119,13 @@ def api(monkeypatch): def _screen(api, files, who="alice", token="tok-1") -> AppTest: at = AppTest.from_string(HARNESS.format(app_dir=str(APP_DIR)), default_timeout=30) - at.session_state["session"] = {"token": token, "expiresAt": later(), "username": who, "tenant": "acme", - "role": ROLES[who]} + at.session_state["session"] = { + "token": token, + "expiresAt": later(), + "username": who, + "tenant": "acme", + "role": ROLES[who], + } at.session_state["test_files"] = files at.run() assert not at.exception, at.exception @@ -125,15 +149,30 @@ def _texts(at): # ── the preview ───────────────────────────────────────────────────────────────────────────── + def test_a_chosen_file_is_previewed_by_the_server_and_its_columns_are_offered_for_checking(api): at = _screen(api, [("people.csv", PEOPLE)]) assert [c.value for c in at.caption][0] == "3 columns · 3 data rows" sample = at.table[0].value - assert list(sample.columns) == ["` id `", "` name `", "` amount `"] and list(sample["` name `"]) == ["` ann `", "` bob `", "` cy `"] - assert [t.label for t in at.text_input] == ["Rename column 1 (id)", "Rename column 2 (name)", "Rename column 3 (amount)"] - assert [s.label for s in at.selectbox] == ["Type of column 1 (id)", "Type of column 2 (name)", "Type of column 3 (amount)"] - assert [s.value for s in at.selectbox if s.label.startswith("Type")] == ["int8", "text", "int8"], "the server's inference" + assert list(sample.columns) == ["` id `", "` name `", "` amount `"] and list(sample["` name `"]) == [ + "` ann `", + "` bob `", + "` cy `", + ] + assert [t.label for t in at.text_input] == [ + "Rename column 1 (id)", + "Rename column 2 (name)", + "Rename column 3 (amount)", + ] + assert [s.label for s in at.selectbox] == [ + "Type of column 1 (id)", + "Type of column 2 (name)", + "Type of column 3 (amount)", + ] + assert [s.value for s in at.selectbox if s.label.startswith("Type")] == ["int8", "text", "int8"], ( + "the server's inference" + ) assert api.previews()[0][3] == {"fileName": "people.csv", "content": PEOPLE.decode()} @@ -179,6 +218,7 @@ def test_a_preview_the_api_refuses_says_why_and_the_other_files_still_show(api): # ── files the screen will not send ────────────────────────────────────────────────────────── + def test_a_file_that_is_not_utf8_is_refused_with_the_reason_and_nothing_is_sent_for_it(api): latin = "name\n\xe9t\xe9\n".encode("latin-1") @@ -200,7 +240,10 @@ def test_a_file_over_the_limit_is_refused_before_anything_is_sent(api, monkeypat def test_an_empty_file_and_a_wrong_extension_are_refused(api): at = _screen(api, [("empty.csv", b""), ("notes.txt", b"a,b\n")]) - assert errors(at) == ["` empty.csv ` is empty.", "` notes.txt ` is not a .csv file. Only CSV files can be imported."] + assert errors(at) == [ + "` empty.csv ` is empty.", + "` notes.txt ` is not a .csv file. Only CSV files can be imported.", + ] assert not api.calls @@ -212,6 +255,7 @@ def test_a_file_name_that_looks_like_a_link_is_quoted_in_the_refusal(api): # ── who may send, and when ────────────────────────────────────────────────────────────────── + def test_a_new_table_cannot_be_sent_until_the_columns_and_types_are_confirmed(api): at = _screen(api, [("people.csv", PEOPLE)]) @@ -230,6 +274,7 @@ def test_the_no_cancel_wording_is_shown_before_the_click(api): # ── what is sent ──────────────────────────────────────────────────────────────────────────── + def test_the_click_sends_the_file_the_original_bytes_the_confirmed_types_and_only_the_renames(api): at = _screen(api, [("people.csv", PEOPLE)]) widget(at.text_input, "Rename column 2 (name)").input("who") @@ -240,9 +285,15 @@ def test_the_click_sends_the_file_the_original_bytes_the_confirmed_types_and_onl assert not at.exception, at.exception [sent] = api.uploads - assert sent == {"fileName": "people.csv", "content": PEOPLE.decode(), "contentBase64": base64.b64encode(PEOPLE).decode(), - "mode": "dynamic", "types": ["int8", "text", "numeric"], "typesConfirmed": True, - "headerMapping": [{"original": "name", "renamed": "who"}]} + assert sent == { + "fileName": "people.csv", + "content": PEOPLE.decode(), + "contentBase64": base64.b64encode(PEOPLE).decode(), + "mode": "dynamic", + "types": ["int8", "text", "numeric"], + "typesConfirmed": True, + "headerMapping": [{"original": "name", "renamed": "who"}], + } assert api.upload_timeouts == [u.UPLOAD_TIMEOUT_SECONDS], "an import is given far longer than a read" @@ -262,6 +313,7 @@ def test_the_payload_is_built_only_at_the_click_because_encoding_a_big_file_on_e # ── what is said back ─────────────────────────────────────────────────────────────────────── + def test_a_successful_import_is_reported_and_the_chooser_is_emptied_so_it_cannot_be_sent_twice(api): at = _screen(api, [("people.csv", PEOPLE)]) _confirm(at) @@ -292,9 +344,13 @@ def test_the_same_file_chosen_again_after_an_import_is_previewed_again_because_t def test_a_partial_import_is_a_warning_with_its_row_errors_and_the_reports(api): - api.reply = {**OK, "insertedRows": 2, "failedRows": 1, "rowErrors": [ - {"rowNumber": 3, "column": "amount", "value": "=1+1", "reason": '"=1+1" is not a whole number'}], - "logs": [{"ts": 1_795_000_000_000, "step": "cast_rows", "level": "warn", "message": "1 row failed"}]} + api.reply = { + **OK, + "insertedRows": 2, + "failedRows": 1, + "rowErrors": [{"rowNumber": 3, "column": "amount", "value": "=1+1", "reason": '"=1+1" is not a whole number'}], + "logs": [{"ts": 1_795_000_000_000, "step": "cast_rows", "level": "warn", "message": "1 row failed"}], + } at = _screen(api, [("people.csv", PEOPLE)]) _confirm(at) @@ -303,11 +359,16 @@ def test_a_partial_import_is_a_warning_with_its_row_errors_and_the_reports(api): assert at.warning[0].value.startswith("` people.csv `: 2 of 3 rows imported · 1 failed") rows = at.table[-1].value assert list(rows.index) == [3] and list(rows["Value"]) == ["` =1+1 `"] - assert [b.label for b in at.get("download_button")] == ["Error report (CSV)", "Error report (XLSX)", "Processing logs (JSON)"] + assert [b.label for b in at.get("download_button")] == [ + "Error report (CSV)", + "Error report (XLSX)", + "Processing logs (JSON)", + ] def test_the_error_report_carries_the_renames_that_were_sent(api, monkeypatch): import exports + built = [] real = exports.to_csv monkeypatch.setattr(exports, "to_csv", lambda headers, rows: built.append(rows) or real(headers, rows)) @@ -322,8 +383,13 @@ def test_the_error_report_carries_the_renames_that_were_sent(api, monkeypatch): def test_the_same_bytes_again_is_reported_as_already_imported_and_nothing_pretends_it_was_loaded(api): - api.reply = {"status": "duplicate_file", "reason": "content", "existingFileName": "people.csv", - "tableName": "csv_people_v1", "logs": []} + api.reply = { + "status": "duplicate_file", + "reason": "content", + "existingFileName": "people.csv", + "tableName": "csv_people_v1", + "logs": [], + } at = _screen(api, [("again.csv", PEOPLE)]) _confirm(at) @@ -402,18 +468,27 @@ def test_the_report_can_be_cleared(api): widget(at.button, "Clear this report").click().run() - assert not at.success and not at.warning and "upload_results" in at.session_state and at.session_state["upload_results"] == [] + assert ( + not at.success + and not at.warning + and "upload_results" in at.session_state + and at.session_state["upload_results"] == [] + ) # ── Test and Evaluation mode ──────────────────────────────────────────────────────────────── + def test_a_te_shaped_file_starts_as_a_te_load_into_the_matching_table(api): api.te_match = "orgs" at = _screen(api, [("orgs.csv", b"name\nacme\n")]) assert at.radio[0].value == u.TE - assert widget(at.selectbox, "Into table").value == "orgs" and widget(at.selectbox, "Into table").options == ["orgs", "people"] + assert widget(at.selectbox, "Into table").value == "orgs" and widget(at.selectbox, "Into table").options == [ + "orgs", + "people", + ] assert not at.checkbox and not at.text_input, "no mapping and no confirmation in T&E mode" assert not _upload_button(at, "orgs.csv").disabled @@ -455,6 +530,7 @@ def test_a_te_load_with_no_te_tables_says_so_and_cannot_be_sent(api): # ── several files ─────────────────────────────────────────────────────────────────────────── + def test_upload_all_waits_for_every_file_to_be_confirmed_then_sends_them_in_turn(api): other = b"city,pop\nperth,2\n" at = _screen(api, [("people.csv", PEOPLE), ("cities.csv", other)]) @@ -469,11 +545,15 @@ def test_upload_all_waits_for_every_file_to_be_confirmed_then_sends_them_in_turn assert not at.exception, at.exception assert [x["fileName"] for x in api.uploads] == ["people.csv", "cities.csv"] assert [r.value.split(" \n")[0] for r in at.success] == [ - "` cities.csv `: 3 of 3 rows imported", "` people.csv `: 3 of 3 rows imported"], "newest first" + "` cities.csv `: 3 of 3 rows imported", + "` people.csv `: 3 of 3 rows imported", + ], "newest first" def test_one_file_failing_does_not_stop_the_rest(api): - api.reply = lambda payload: {"status": "error", "message": "boom", "logs": []} if payload["fileName"] == "bad.csv" else dict(OK) + api.reply = lambda payload: ( + {"status": "error", "message": "boom", "logs": []} if payload["fileName"] == "bad.csv" else dict(OK) + ) at = _screen(api, [("bad.csv", PEOPLE), ("good.csv", b"city,pop\nperth,2\n")]) for box in [c for c in at.checkbox if c.label == u.CONFIRM]: box.check().run() @@ -488,8 +568,13 @@ def test_two_copies_of_the_same_bytes_under_two_names_are_two_files_with_their_o """Found by this test: widget keys were made from the content alone, so two copies crashed the page.""" at = _screen(api, [("orig.csv", PEOPLE), ("copy.csv", PEOPLE)]) - assert len(at.expander) == 2 and len(at.checkbox) == 2 and len(api.previews()) == 1, "one preview, two sets of boxes" - assert [b.label for b in at.button if b.label.startswith("Upload `")] == ["Upload ` orig.csv `", "Upload ` copy.csv `"] + assert len(at.expander) == 2 and len(at.checkbox) == 2 and len(api.previews()) == 1, ( + "one preview, two sets of boxes" + ) + assert [b.label for b in at.button if b.label.startswith("Upload `")] == [ + "Upload ` orig.csv `", + "Upload ` copy.csv `", + ] def test_the_same_file_chosen_twice_is_shown_once_and_says_so(api): @@ -500,21 +585,32 @@ def test_the_same_file_chosen_twice_is_shown_once_and_says_so(api): # ── who may use the page ──────────────────────────────────────────────────────────────────── + def test_the_page_itself_is_only_for_roles_that_may_upload(): from api.auth import PERMISSIONS + assert {r for r, role in ROLES.items() if role in PERMISSIONS["upload"]} == {"alice", "ada"} def test_a_role_that_may_not_upload_is_told_so_instead_of_being_shown_a_chooser(api): - at = AppTest.from_string(f""" + at = AppTest.from_string( + f""" import sys sys.path.insert(0, {str(APP_DIR)!r}) import auth from views import upload if auth.signed_in(): upload.render() -""", default_timeout=30) - at.session_state["session"] = {"token": "t", "expiresAt": later(), "username": "audrey", "tenant": "acme", "role": "auditor"} +""", + default_timeout=30, + ) + at.session_state["session"] = { + "token": "t", + "expiresAt": later(), + "username": "audrey", + "tenant": "acme", + "role": "auditor", + } at.run() @@ -523,6 +619,7 @@ def test_a_role_that_may_not_upload_is_told_so_instead_of_being_shown_a_chooser( # ── text from a file is shown as written ─────────────────────────────────────────────────── + def test_headers_cells_and_the_file_name_that_look_like_links_are_code_spans_everywhere(api): evil = "[click](https://evil.example/x)" raw = f"{evil},b\n{evil},2\n".encode() @@ -538,7 +635,11 @@ def test_headers_cells_and_the_file_name_that_look_like_links_are_code_spans_eve def test_a_row_error_with_a_link_in_it_is_a_code_span(api): evil = "[click](https://evil.example/x)" - api.reply = {**OK, "failedRows": 1, "rowErrors": [{"rowNumber": 1, "column": "a", "value": evil, "reason": f'"{evil}" bad'}]} + api.reply = { + **OK, + "failedRows": 1, + "rowErrors": [{"rowNumber": 1, "column": "a", "value": evil, "reason": f'"{evil}" bad'}], + } at = _screen(api, [("people.csv", PEOPLE)]) _confirm(at) diff --git a/tests/unit/test_streamlit_upload_model.py b/tests/unit/test_streamlit_upload_model.py index dabaaef..79d41cc 100644 --- a/tests/unit/test_streamlit_upload_model.py +++ b/tests/unit/test_streamlit_upload_model.py @@ -5,12 +5,14 @@ and the request bodies: a new table sends the confirmed types and only the renames, a Test and Evaluation load sends neither (the API answers 422 to either there). """ + import base64 import tomllib import pytest from tests.unit.streamlit_harness import APP_DIR + # The imports below need the path the import above sets up, so the import sort must not move them up. # isort: split @@ -27,6 +29,7 @@ def _prep(name="a.csv", raw=b"id,name\n1,x\n", limit=LIMIT): # ── prepare ─────────────────────────────────────────────────────────────────────────────── + def test_a_good_file_is_decoded_and_keeps_its_original_bytes(): p = _prep(raw="id,name\n1,café\n".encode("utf-8")) @@ -69,7 +72,9 @@ def test_a_file_that_is_not_utf8_is_refused_not_quietly_changed(): with pytest.raises(u.Refused) as e: _prep("latin.csv", "name\n\xe9t\xe9\n".encode("latin-1")) - assert "not UTF-8" in e.value.reason and "position 5" in e.value.reason and "Save the file as UTF-8" in e.value.reason + assert ( + "not UTF-8" in e.value.reason and "position 5" in e.value.reason and "Save the file as UTF-8" in e.value.reason + ) def test_an_empty_file_and_a_wrong_extension_are_refused(): @@ -90,14 +95,24 @@ def test_a_refusal_keeps_the_name_apart_from_the_reason_so_the_name_can_be_quote assert e.value.name == "[x](http://y.test).txt" and not e.value.reason.startswith("[x]") -@pytest.mark.parametrize("n, text", [(0, "0 B"), (1023, "1023 B"), (1024, "1.0 KB"), (1536, "1.5 KB"), - (1_048_576, "1.00 MB"), (52_428_800, "50.00 MB")]) +@pytest.mark.parametrize( + "n, text", + [ + (0, "0 B"), + (1023, "1023 B"), + (1024, "1.0 KB"), + (1536, "1.5 KB"), + (1_048_576, "1.00 MB"), + (52_428_800, "50.00 MB"), + ], +) def test_sizes_are_worded_as_the_react_app_words_them(n, text): assert u.format_bytes(n) == text # ── the preview reads only the start of a big file ──────────────────────────────────────── + def test_a_small_file_is_previewed_whole(): p = _prep() @@ -135,6 +150,7 @@ def test_rows_are_estimated_from_the_part_that_was_read_only_when_it_was_cut(): # ── mode and mapping ────────────────────────────────────────────────────────────────────── + def test_a_file_that_matches_a_te_table_that_exists_starts_as_one(): assert u.default_mode({"teTableMatch": "orgs"}, ["orgs", "people"]) == u.TE assert u.default_mode({"teTableMatch": "gone"}, ["orgs"]) == u.DYNAMIC @@ -144,7 +160,8 @@ def test_a_file_that_matches_a_te_table_that_exists_starts_as_one(): def test_only_the_renames_the_person_typed_are_sent_against_the_files_own_headers(): assert u.header_mapping(["First Name", "age", "city"], ["given", " ", ""]) == [ - {"original": "First Name", "renamed": "given"}] + {"original": "First Name", "renamed": "given"} + ] assert u.header_mapping(["a"], [" x "]) == [{"original": "a", "renamed": "x"}] assert u.header_mapping(["a", "b"], []) == [] @@ -156,15 +173,23 @@ def test_a_new_table_waits_for_the_confirmation_and_a_te_load_for_a_target(): # ── what is sent ────────────────────────────────────────────────────────────────────────── + def test_a_new_table_sends_the_text_the_original_bytes_the_types_and_that_they_were_confirmed(): p = _prep(raw=b"id,name\n1,x\n") - body = u.build_payload(p, u.DYNAMIC, types=["int8", "text"], confirmed=True, headers=["id", "name"], - renames=["", "who"]) + body = u.build_payload( + p, u.DYNAMIC, types=["int8", "text"], confirmed=True, headers=["id", "name"], renames=["", "who"] + ) - assert body == {"fileName": "a.csv", "content": "id,name\n1,x\n", "mode": "dynamic", - "contentBase64": base64.b64encode(b"id,name\n1,x\n").decode(), "types": ["int8", "text"], - "typesConfirmed": True, "headerMapping": [{"original": "name", "renamed": "who"}]} + assert body == { + "fileName": "a.csv", + "content": "id,name\n1,x\n", + "mode": "dynamic", + "contentBase64": base64.b64encode(b"id,name\n1,x\n").decode(), + "types": ["int8", "text"], + "typesConfirmed": True, + "headerMapping": [{"original": "name", "renamed": "who"}], + } def test_no_renames_means_no_header_mapping_key_at_all(): @@ -194,6 +219,7 @@ def test_an_unconfirmed_new_table_says_so_rather_than_claiming_it_was_checked(): # ── the sample the person checks ────────────────────────────────────────────────────────── + def test_the_sample_is_a_table_of_code_spans_numbered_from_one(): pv = {"columns": ["id", "name"], "sampleRows": [["1", "[x](http://y.test)"], ["2", ""]]} @@ -205,14 +231,18 @@ def test_the_sample_is_a_table_of_code_spans_numbered_from_one(): # ── agreement with the API and Streamlit ───────────────────────────────────────────────── + def test_the_column_types_are_the_ones_the_api_allows(): from api.services.csv_parse import ALLOWED_TYPES + assert set(u.ALLOWED_TYPES) == set(ALLOWED_TYPES) and set(u.TYPE_LABELS) == set(ALLOWED_TYPES) def test_the_default_limit_is_the_apis_default(): - from api.config import settings import os + + from api.config import settings + if "MAX_UPLOAD_BYTES" not in os.environ: assert u.DEFAULT_MAX_UPLOAD_BYTES == settings.MAX_UPLOAD_BYTES @@ -234,24 +264,29 @@ def test_widget_keys_tell_two_names_for_the_same_bytes_apart_and_are_stable(): def test_the_same_name_and_bytes_twice_is_dropped_once_and_different_bytes_are_kept(): - kept, dropped = u.chosen_once([("a.csv", b"x\n1\n"), ("a.csv", b"x\n1\n"), ("a.csv", b"x\n2\n"), ("b.csv", b"x\n1\n")]) + kept, dropped = u.chosen_once( + [("a.csv", b"x\n1\n"), ("a.csv", b"x\n1\n"), ("a.csv", b"x\n2\n"), ("b.csv", b"x\n1\n")] + ) assert [n for n, _ in kept] == ["a.csv", "a.csv", "b.csv"] and dropped == ["a.csv"] -@pytest.mark.parametrize("header, i, label", [ - ("amount", 2, "column 3 (amount)"), - ("Full Name", 0, "column 1 (Full Name)"), - ("first_name-2", 1, "column 2 (first_name-2)"), - ("[click](https://evil.example/x)", 0, "column 1 (click https evil example x)"), - ("**bold** :warning: ", 4, "column 5 (bold warning b)"), - ("www.evil.example a@evil.example", 0, "column 1 (www evil example a evil example)"), - ("", 3, "column 4"), - (" ", 3, "column 4"), - ("!!!", 0, "column 1"), - ("é Ünïcode", 0, "column 1 (é Ünïcode)"), - ("a" * 100, 0, "column 1 (" + "a" * 40 + ")"), -]) +@pytest.mark.parametrize( + "header, i, label", + [ + ("amount", 2, "column 3 (amount)"), + ("Full Name", 0, "column 1 (Full Name)"), + ("first_name-2", 1, "column 2 (first_name-2)"), + ("[click](https://evil.example/x)", 0, "column 1 (click https evil example x)"), + ("**bold** :warning: ", 4, "column 5 (bold warning b)"), + ("www.evil.example a@evil.example", 0, "column 1 (www evil example a evil example)"), + ("", 3, "column 4"), + (" ", 3, "column 4"), + ("!!!", 0, "column 1"), + ("é Ünïcode", 0, "column 1 (é Ünïcode)"), + ("a" * 100, 0, "column 1 (" + "a" * 40 + ")"), + ], +) def test_a_columns_box_label_keeps_what_helps_and_nothing_that_markdown_could_use(header, i, label): assert u.column_label(header, i) == label @@ -262,7 +297,10 @@ def test_a_long_header_is_cut_so_that_a_label_stays_one_readable_line(): assert label == f"column 1 ({'x' * 40})" -@pytest.mark.parametrize("header", ["[x](https://e.test)", "https://e.test", "www.e.test", "a@e.test", "", "`code`", "$x$", ":zap:"]) +@pytest.mark.parametrize( + "header", + ["[x](https://e.test)", "https://e.test", "www.e.test", "a@e.test", "", "`code`", "$x$", ":zap:"], +) def test_no_label_contains_anything_that_forms_a_link_or_formatting(header): label = u.column_label(header, 0) diff --git a/tests/unit/test_test_report_exit_codes.py b/tests/unit/test_test_report_exit_codes.py index d6c7479..437bc22 100644 --- a/tests/unit/test_test_report_exit_codes.py +++ b/tests/unit/test_test_report_exit_codes.py @@ -5,6 +5,7 @@ RESULT: PASS with 0 executed. For the browser job that meant a failed Playwright install would show a green check with no test run. Only exit codes 0 (all passed) and 1 (some failed) mean tests ran, and a pass needs at least one executed. """ + from __future__ import annotations import importlib.util @@ -74,7 +75,13 @@ def test_the_real_script_fails_when_a_conftest_cannot_be_imported(tmp_path): """The case that slipped through: no mocks, the real script and the real pytest on a folder whose conftest raises.""" (tmp_path / "conftest.py").write_text("import a_module_that_does_not_exist_273\n", encoding="utf-8") (tmp_path / "test_x.py").write_text("def test_x():\n assert True\n", encoding="utf-8") - result = subprocess.run([sys.executable, "scripts/test_report.py", "--paths", str(tmp_path), "--strict"], cwd=ROOT, - capture_output=True, text=True, timeout=120, env={**os.environ, "PYTHONIOENCODING": "utf-8"}) + result = subprocess.run( + [sys.executable, "scripts/test_report.py", "--paths", str(tmp_path), "--strict"], + cwd=ROOT, + capture_output=True, + text=True, + timeout=120, + env={**os.environ, "PYTHONIOENCODING": "utf-8"}, + ) assert result.returncode == 1, result.stdout[-600:] assert "RESULT: FAIL" in result.stdout diff --git a/tests/unit/test_test_report_paths.py b/tests/unit/test_test_report_paths.py index 4c11465..1a48093 100644 --- a/tests/unit/test_test_report_paths.py +++ b/tests/unit/test_test_report_paths.py @@ -3,6 +3,7 @@ Until now it ran pytest with no path, so it could only see tests/ and the browser tier was invisible to its final block and to --strict. `--paths` hands the same paths to the collection pass and to the run. """ + from __future__ import annotations import importlib.util diff --git a/tests/unit/test_tier_s_threshold.py b/tests/unit/test_tier_s_threshold.py index 1bc07b0..c153b80 100644 --- a/tests/unit/test_tier_s_threshold.py +++ b/tests/unit/test_tier_s_threshold.py @@ -16,6 +16,7 @@ Lines that are SQL comments (``--``) are ignored. The count matched the live run on 24 Nov 2026: 159 assertion rows in ``te_test_harness.test_run_results`` on PostgreSQL 16 (153 ``assert_*`` calls and 6 ``tf_record`` names). """ + from __future__ import annotations import json @@ -55,7 +56,8 @@ def test_tier_s_threshold_equals_the_assertions_in_the_suites(): assert threshold == total, ( f"{EXPECTED.relative_to(ROOT)} has min_total_assertions {threshold}, but tests/suites/*.sql has {total} " f"assertions ({per_suite}). Set the threshold to {total} and update BR-20 in docs/VCRM.md, so the gate " - "fails if an assertion disappears.") + "fails if an assertion disappears." + ) def test_the_count_sees_a_removed_assertion(): diff --git a/tests/unit/test_tooling_issues.py b/tests/unit/test_tooling_issues.py index 0d9764f..cd60361 100644 --- a/tests/unit/test_tooling_issues.py +++ b/tests/unit/test_tooling_issues.py @@ -33,30 +33,36 @@ def _between(text: str, start: str, end: str, *, include_end: bool = False) -> str: i = text.index(start) j = text.index(end, i) - return text[i:j + (len(end) if include_end else 0)] + return text[i : j + (len(end) if include_end else 0)] def _bash(script: str, **env: str) -> subprocess.CompletedProcess: - return subprocess.run(["bash", "-c", script], capture_output=True, text=True, - env={**os.environ, **env}, timeout=60) + return subprocess.run(["bash", "-c", script], capture_output=True, text=True, env={**os.environ, **env}, timeout=60) # ── #171 ───────────────────────────────────────────────────────────────────── + @pytest.mark.tooling class SetupKeepsPriorConfigOnFailure(unittest.TestCase): """#171: the config is written to a temp file and moved into place only once complete.""" - BLOCK = _between((ROOT / "build/setup.sh").read_text(encoding="utf-8"), - '_config_tmp="${CONFIG_LOCAL}.new"', 'mv -f "$_config_tmp" "$CONFIG_LOCAL"', include_end=True) + BLOCK = _between( + (ROOT / "build/setup.sh").read_text(encoding="utf-8"), + '_config_tmp="${CONFIG_LOCAL}.new"', + 'mv -f "$_config_tmp" "$CONFIG_LOCAL"', + include_end=True, + ) VARS = sorted(set(re.findall(r"\$\{([A-Z][A-Z0-9_]*)\}", BLOCK)) - {"CONFIG_LOCAL"}) def _run(self, omit: str | None): with tempfile.TemporaryDirectory() as d: config = Path(d) / "config.local.env" config.write_text("PRIOR=keep-me\n") - exports = "".join(f'{v}=x; ' for v in self.VARS if v != omit) - script = f'set -euo pipefail; error(){{ echo "$@" >&2; }}; CONFIG_LOCAL="{config}"; {exports}\n{self.BLOCK}\n' + exports = "".join(f"{v}=x; " for v in self.VARS if v != omit) + script = ( + f'set -euo pipefail; error(){{ echo "$@" >&2; }}; CONFIG_LOCAL="{config}"; {exports}\n{self.BLOCK}\n' + ) res = _bash(script) return res, config.read_text(), sorted(p.name for p in Path(d).iterdir()) @@ -79,11 +85,16 @@ def test_an_unset_variable_fails_the_run_but_keeps_the_prior_config(self): # ── #180 ───────────────────────────────────────────────────────────────────── + def _psql_calls(function: str | None = None) -> list[str]: tree = ast.parse((ROOT / "evals/runner.py").read_text(encoding="utf-8")) scope = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == function] if function else [tree] - return [ast.unparse(n) for root in scope for n in ast.walk(root) - if isinstance(n, ast.List) and n.elts and isinstance(n.elts[0], ast.Constant) and n.elts[0].value == "psql"] + return [ + ast.unparse(n) + for root in scope + for n in ast.walk(root) + if isinstance(n, ast.List) and n.elts and isinstance(n.elts[0], ast.Constant) and n.elts[0].value == "psql" + ] @pytest.mark.unit @@ -97,20 +108,26 @@ def test_the_idempotency_eval_stops_at_the_first_sql_error(self): # ── #181 ───────────────────────────────────────────────────────────────────── + @pytest.mark.tooling class SqlWrapperFailsOnAssertionFailures(unittest.TestCase): """#181: psql exits 0 even when assertions record FAIL rows; the wrapper must read the output.""" - BLOCK = _between((ROOT / "tests/run_tests.sh").read_text(encoding="utf-8"), - "if grep -qiE 'FAIL|TEST\\(S\\) FAILED'", 'rm -f "${outfile}"') + BLOCK = _between( + (ROOT / "tests/run_tests.sh").read_text(encoding="utf-8"), + "if grep -qiE 'FAIL|TEST\\(S\\) FAILED'", + 'rm -f "${outfile}"', + ) def _failed_envs(self, output: str) -> str: with tempfile.NamedTemporaryFile("w", suffix=".out", delete=False) as f: f.write(output) try: # The block uses `local`, as it does inside run_suite(). - script = ('set -euo pipefail; error(){ :; }; FAILED_ENVS=(); check(){ local env=dev outfile="%s"\n%s\n}; ' - 'check; echo "failed:${FAILED_ENVS[*]:-}"' % (f.name, self.BLOCK)) + script = ( + 'set -euo pipefail; error(){ :; }; FAILED_ENVS=(); check(){ local env=dev outfile="%s"\n%s\n}; ' + 'check; echo "failed:${FAILED_ENVS[*]:-}"' % (f.name, self.BLOCK) + ) res = _bash(script) self.assertEqual(res.returncode, 0, res.stderr) return res.stdout.strip() @@ -126,10 +143,11 @@ def test_a_clean_run_is_not_marked_failed(self): # ── #182 ───────────────────────────────────────────────────────────────────── + @pytest.mark.tooling class OfflineBundleStopsOnDownloadFailure(unittest.TestCase): SCRIPT = (ROOT / "scripts/offline/build_bundle.sh").read_text(encoding="utf-8") - BLOCK = _between(SCRIPT, "REAL=()", "( cd \"$OUT/debs\" && apt-ftparchive", include_end=False) + BLOCK = _between(SCRIPT, "REAL=()", '( cd "$OUT/debs" && apt-ftparchive', include_end=False) def _run(self, apt_get_body: str) -> subprocess.CompletedProcess: with tempfile.TemporaryDirectory() as d: @@ -140,7 +158,7 @@ def _run(self, apt_get_body: str) -> subprocess.CompletedProcess: (bin_dir / "apt-get").write_text("#!/bin/bash\n" + apt_get_body) for f in bin_dir.iterdir(): f.chmod(0o755) - script = (f'set -euo pipefail; DEPS="pkg-a pkg-b"; PKGS="pkg-a pkg-b"; OUT="{out}"\n{self.BLOCK}\necho BUILT') + script = f'set -euo pipefail; DEPS="pkg-a pkg-b"; PKGS="pkg-a pkg-b"; OUT="{out}"\n{self.BLOCK}\necho BUILT' return _bash(script, PATH=f"{bin_dir}:{os.environ['PATH']}") def test_the_old_swallow_is_gone(self): @@ -164,6 +182,7 @@ def test_a_complete_download_continues(self): # ── #130 ───────────────────────────────────────────────────────────────────── + @pytest.mark.unit class FrontendLockFileMatchesPackageJson(unittest.TestCase): """#130: `npm ci` refuses a lock file that disagrees with package.json.""" @@ -182,6 +201,7 @@ def test_root_entry_and_every_direct_dependency_agree(self): # ── #169 ───────────────────────────────────────────────────────────────────── + @pytest.mark.unit class TestCatalogueGenerator(unittest.TestCase): """The catalogue is generated in CI, not committed, so nothing else notices if the @@ -194,8 +214,7 @@ def test_the_catalogue_lists_every_test_file(self): missing = [] for path in sorted((ROOT / "tests").rglob("test_*.py")): tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) - has_tests = any(isinstance(n, ast.FunctionDef) and n.name.startswith("test") - for n in ast.walk(tree)) + has_tests = any(isinstance(n, ast.FunctionDef) and n.name.startswith("test") for n in ast.walk(tree)) rel = path.relative_to(ROOT).as_posix() if has_tests and f"## `{rel}`" not in text: missing.append(rel) @@ -204,10 +223,15 @@ def test_the_catalogue_lists_every_test_file(self): # ── #194 ───────────────────────────────────────────────────────────────────── + @pytest.mark.unit class CoverageFloorGate(unittest.TestCase): - FILES = ("api/services/csv_parse.py", "api/services/dynamic_loader.py", "api/services/load_common.py", - "api/services/te_loader.py") + FILES = ( + "api/services/csv_parse.py", + "api/services/dynamic_loader.py", + "api/services/load_common.py", + "api/services/te_loader.py", + ) # Package floors (#274, #278): the report must also hold files from these packages, with statement counts. PACKAGE_FILES = {"api/main.py": 100, "streamlit_app/app.py": 100} @@ -221,16 +245,21 @@ def _summary(pct: float, statements: int = 100) -> dict: def _gate(self, pct: dict[str, float], drop: str | None = None, packages: dict | None = None) -> int: report = {"files": {f: {"summary": self._summary(pct[f])} for f in self.FILES if f != drop}} for name, value in {**self.OTHER_PACKAGES, **(self.PACKAGE_FILES if packages is None else packages)}.items(): - if value is None: # None: leave this file out of the report + if value is None: # None: leave this file out of the report continue report["files"][name] = {"summary": value if isinstance(value, dict) else self._summary(value)} with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f: json.dump(report, f) try: # The gate prints box-drawing characters; a Windows console's default encoding can't. - return subprocess.run([sys.executable, "scripts/check_coverage_floors.py", f.name], cwd=ROOT, - capture_output=True, text=True, timeout=30, - env={**os.environ, "PYTHONIOENCODING": "utf-8"}).returncode + return subprocess.run( + [sys.executable, "scripts/check_coverage_floors.py", f.name], + cwd=ROOT, + capture_output=True, + text=True, + timeout=30, + env={**os.environ, "PYTHONIOENCODING": "utf-8"}, + ).returncode finally: os.unlink(f.name) @@ -263,18 +292,21 @@ def test_the_package_floors_name_the_api_and_the_streamlit_app(self): def test_fails_when_the_validator_drops_below_its_package_floor(self): """#304""" - self.assertEqual(self._gate({f: 100.0 for f in self.FILES}, packages={**self.PACKAGE_FILES, - "build/csv/validator.py": 50}), 1) + self.assertEqual( + self._gate({f: 100.0 for f in self.FILES}, packages={**self.PACKAGE_FILES, "build/csv/validator.py": 50}), 1 + ) def test_fails_when_the_evals_runner_drops_below_its_package_floor(self): """#304""" - self.assertEqual(self._gate({f: 100.0 for f in self.FILES}, packages={**self.PACKAGE_FILES, - "evals/runner.py": 30}), 1) + self.assertEqual( + self._gate({f: 100.0 for f in self.FILES}, packages={**self.PACKAGE_FILES, "evals/runner.py": 30}), 1 + ) def test_fails_when_evals_is_not_in_the_report_at_all(self): """#304: taking --cov=evals out must fail the gate, not quietly stop gating it.""" - self.assertEqual(self._gate({f: 100.0 for f in self.FILES}, packages={**self.PACKAGE_FILES, - "evals/runner.py": None}), 1) + self.assertEqual( + self._gate({f: 100.0 for f in self.FILES}, packages={**self.PACKAGE_FILES, "evals/runner.py": None}), 1 + ) def test_fails_when_the_streamlit_app_drops_below_its_package_floor(self): full = {f: 100.0 for f in self.FILES} @@ -293,23 +325,33 @@ def test_fails_when_the_streamlit_app_is_not_in_the_report_at_all(self): def test_a_package_floor_is_weighted_by_statements_not_an_average_of_files(self): full = {f: 100.0 for f in self.FILES} - big_and_good = {"api/main.py": 100, "streamlit_app/app.py": 100, - "streamlit_app/views/a.py": self._summary(100, 1000), "streamlit_app/views/b.py": self._summary(0, 10)} + big_and_good = { + "api/main.py": 100, + "streamlit_app/app.py": 100, + "streamlit_app/views/a.py": self._summary(100, 1000), + "streamlit_app/views/b.py": self._summary(0, 10), + } self.assertEqual(self._gate(full, packages=big_and_good), 0, "1000 of 1110 statements is above the floor") - small_and_good = {"api/main.py": 100, "streamlit_app/app.py": self._summary(100, 10), - "streamlit_app/views/a.py": self._summary(0, 1000)} + small_and_good = { + "api/main.py": 100, + "streamlit_app/app.py": self._summary(100, 10), + "streamlit_app/views/a.py": self._summary(0, 1000), + } self.assertEqual(self._gate(full, packages=small_and_good), 1, "10 of 1010 statements is far below it") # ── #207 ───────────────────────────────────────────────────────────────────── + @pytest.mark.unit class ApiDocDefersToTheGeneratedSchema(unittest.TestCase): DOC = (ROOT / "docs/API_INTEGRATION.md").read_text(encoding="utf-8") def test_no_hand_kept_route_table(self): - self.assertIsNone(re.search(r"^\|\s*`?(GET|POST|PUT|DELETE)\b", self.DOC, re.M), - "a hand-kept route table drifts from the code (#207)") + self.assertIsNone( + re.search(r"^\|\s*`?(GET|POST|PUT|DELETE)\b", self.DOC, re.M), + "a hand-kept route table drifts from the code (#207)", + ) def test_points_at_the_real_schema_urls_not_the_old_404(self): self.assertIn("/docs", self.DOC) @@ -318,7 +360,9 @@ def test_points_at_the_real_schema_urls_not_the_old_404(self): def test_the_documented_urls_are_served_without_a_key(self): from fastapi.testclient import TestClient + from api.main import app + client = TestClient(app) self.assertEqual(client.get("/docs").status_code, 200) paths = client.get("/openapi.json").json()["paths"] From 1c92306095998c9f569b96e09ae558f35c036e8c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 11:16:58 +0000 Subject: [PATCH 3/4] build: list the formatting commit in .git-blame-ignore-revs (#324) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011T6WqmGuQidunwiFfwKeBs --- .git-blame-ignore-revs | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..5300886 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,7 @@ +# Commits that only reformat code, so `git blame` shows who last changed what a line does (#324). +# GitHub's blame view reads this file. For `git blame` locally, once per clone: +# git config blame.ignoreRevsFile .git-blame-ignore-revs +# Add a commit here only when it changes nothing but formatting. + +# ruff format and import order over the tree, except csv_loader/ +20cd32e8e8a203e9db27091cd74f861c5509e994 From 51b5e316a2260d9b274b62808f42ba96b0c0021a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 11:22:11 +0000 Subject: [PATCH 4/4] refactor(services): split five functions the formatter took past 80 lines (#324, #330) Formatting spread these over more lines, so tests/unit/test_function_length.py (#330's limit) failed: _do_upload 109, store_upload 85, effective_rows 84, import_upload 84, upload_dynamic 83. Each now calls helpers, and the statements run in the same order as before: - dynamic_loader: _lost_race and _database_error (upload_dynamic's two error responses); _prepare_version (lock, versions, types, table), _cast_and_log and _flag_earlier_versions (_do_upload's steps) - originals: _store_row_flags - staged_import: _validate_row (effective_rows' per-row check); _refuse_unless_importable and _audit_import (import_upload) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011T6WqmGuQidunwiFfwKeBs --- api/services/dynamic_loader.py | 179 +++++++++++++++++++++------------ api/services/originals.py | 47 +++++---- api/services/staged_import.py | 108 ++++++++++++-------- 3 files changed, 207 insertions(+), 127 deletions(-) diff --git a/api/services/dynamic_loader.py b/api/services/dynamic_loader.py index ba92d38..ec60e05 100644 --- a/api/services/dynamic_loader.py +++ b/api/services/dynamic_loader.py @@ -17,7 +17,7 @@ import re from collections.abc import Callable from dataclasses import dataclass, field -from typing import Any +from typing import Any, NamedTuple import psycopg2.errors from psycopg2 import sql @@ -199,29 +199,35 @@ def upload_dynamic( on_commit=on_commit, ) except psycopg2.errors.UniqueViolation: - # #81: an identical concurrent upload won a race that _do_upload could - # not settle itself (e.g. both creating csv_ at once). Nothing - # from this request was committed. - _log(logs, "duplicate_check", "Lost race to a concurrent identical upload", "warn") - return { - "status": "duplicate_file", - "reason": "content", - "existingFileName": file_name, - "tableName": f"csv_{file_hash[:16]}", - "existingRowCount": 0, - "logs": logs, - } + return _lost_race(file_name, file_hash, logs) except psycopg2.Error as exc: - # Mirror te_loader's structured-error contract: an unexpected DB error - # (e.g. a column type edge case not caught by cast_value) should not - # surface as a raw 500 to the frontend. - logger.warning("Dynamic upload failed for %r: %s", file_name, exc) - _log(logs, "error", "Database error while loading the CSV", "error") - return { - "status": "error", - "message": "The CSV could not be loaded due to a database error. Check the file's data types and try again.", - "logs": logs, - } + return _database_error(file_name, exc, logs) + + +def _lost_race(file_name: str, file_hash: str, logs: list[LogEntry]) -> LoadResult: + """#81: an identical concurrent upload won a race that _do_upload could not settle itself (e.g. both + creating csv_ at once). Nothing from this request was committed.""" + _log(logs, "duplicate_check", "Lost race to a concurrent identical upload", "warn") + return { + "status": "duplicate_file", + "reason": "content", + "existingFileName": file_name, + "tableName": f"csv_{file_hash[:16]}", + "existingRowCount": 0, + "logs": logs, + } + + +def _database_error(file_name: str, exc: psycopg2.Error, logs: list[LogEntry]) -> LoadResult: + """Mirror te_loader's structured-error contract: an unexpected DB error (e.g. a column type edge case not + caught by cast_value) should not surface as a raw 500 to the frontend.""" + logger.warning("Dynamic upload failed for %r: %s", file_name, exc) + _log(logs, "error", "Database error while loading the CSV", "error") + return { + "status": "error", + "message": "The CSV could not be loaded due to a database error. Check the file's data types and try again.", + "logs": logs, + } def _structure_problem(rows: list[list[str]], logs: list[LogEntry]) -> LoadResult | None: @@ -280,39 +286,13 @@ def _do_upload( ) -> LoadResult: with Conn() as conn: with conn.cursor() as cur: - dataset = dataset_slug(file_name) - # One upload per dataset at a time, so two uploads of the same filename can't pick the - # same version. Released at commit or rollback. - # ponytail: held through row casting; take it just before the insert if big same-name uploads queue. - cur.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (f"{schema}.{dataset}",)) - if overwrite: - _log( - logs, "overwrite", "Overwrite is not supported (decision 2): storing a new version instead", "warn" - ) - - duplicate = _same_content(cur, schema, file_hash, logs) - if duplicate: - return duplicate - priors, version = _versions(cur, schema, dataset, logs) - checked = _columns_and_types(rows[0], types, logs) - if isinstance(checked, dict): - return checked - columns, col_types = checked - schema_check = _compare_with_previous(cur, schema, priors, columns, col_types, logs) - - table_name = f"csv_{dataset}_v{version}" - _create_table(cur, schema, table_name, columns, col_types, logs) + target = _prepare_version(cur, schema, file_name, file_hash, rows[0], types, overwrite, logs) + if isinstance(target, dict): + return target + dataset, version, priors, columns, col_types, schema_check, table_name = target data_rows = rows[1:] - cast = cast_rows(data_rows, columns, col_types) - _log( - logs, - "cast_rows", - f"Cast {len(data_rows)} rows → {len(cast.to_insert)} valid, {cast.errors.failed} errors, " - f"{cast.duplicates} in-file duplicates", - "warn" if cast.errors.failed else "info", - count=len(cast.to_insert), - ) + cast = _cast_and_log(data_rows, columns, col_types, logs) # #123: if every row failed, nothing was migrated. Roll back the new # table (and any overwrite) and report a failed upload, not a success. @@ -320,17 +300,7 @@ def _do_upload( conn.rollback() return _every_row_failed(cast.errors, len(data_rows), columns, col_types, logs) - # BR-29: rows whose exact content is already in an earlier version of this dataset are - # still loaded, but flagged. The user decides per row (decision 3), through review. - flags = _earlier_version_matches(cur, schema, priors, [r[-1] for r in cast.to_insert], cast.insert_rows) - if flags: - _log( - logs, - "cross_upload_duplicates", - f"{len(flags)} rows already exist in an earlier version", - "warn", - count=len(flags), - ) + flags = _flag_earlier_versions(cur, schema, priors, cast, logs) inserted = _insert(cur, schema, table_name, columns, cast.to_insert) _log(logs, "insert", f"Inserted {inserted} rows", count=inserted) @@ -376,6 +346,85 @@ def _do_upload( return result +class _Version(NamedTuple): + """The new version of a dataset that an upload becomes, with its table created.""" + + dataset: str + version: int + priors: list[tuple[Any, ...]] + columns: list[str] + col_types: list[str] + schema_check: SchemaCheck | None + table_name: str + + +def _prepare_version( + cur: cursor, + schema: str, + file_name: str, + file_hash: str, + header: list[str], + types: list[str] | None, + overwrite: bool, + logs: list[LogEntry], +) -> _Version | LoadResult: + """Lock the dataset, pick its next version and create that version's table; or the response that stops the load + (the same content is already loaded, or the types are invalid).""" + dataset = dataset_slug(file_name) + # One upload per dataset at a time, so two uploads of the same filename can't pick the + # same version. Released at commit or rollback. + # ponytail: held through row casting; take it just before the insert if big same-name uploads queue. + cur.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (f"{schema}.{dataset}",)) + if overwrite: + _log(logs, "overwrite", "Overwrite is not supported (decision 2): storing a new version instead", "warn") + + duplicate = _same_content(cur, schema, file_hash, logs) + if duplicate: + return duplicate + priors, version = _versions(cur, schema, dataset, logs) + checked = _columns_and_types(header, types, logs) + if isinstance(checked, dict): + return checked + columns, col_types = checked + schema_check = _compare_with_previous(cur, schema, priors, columns, col_types, logs) + + table_name = f"csv_{dataset}_v{version}" + _create_table(cur, schema, table_name, columns, col_types, logs) + return _Version(dataset, version, priors, columns, col_types, schema_check, table_name) + + +def _cast_and_log( + data_rows: list[list[str]], columns: list[str], col_types: list[str], logs: list[LogEntry] +) -> CastRows: + cast = cast_rows(data_rows, columns, col_types) + _log( + logs, + "cast_rows", + f"Cast {len(data_rows)} rows → {len(cast.to_insert)} valid, {cast.errors.failed} errors, " + f"{cast.duplicates} in-file duplicates", + "warn" if cast.errors.failed else "info", + count=len(cast.to_insert), + ) + return cast + + +def _flag_earlier_versions( + cur: cursor, schema: str, priors: list[tuple[Any, ...]], cast: CastRows, logs: list[LogEntry] +) -> list[DuplicateFlag]: + """BR-29: rows whose exact content is already in an earlier version of this dataset are + still loaded, but flagged. The user decides per row (decision 3), through review.""" + flags = _earlier_version_matches(cur, schema, priors, [r[-1] for r in cast.to_insert], cast.insert_rows) + if flags: + _log( + logs, + "cross_upload_duplicates", + f"{len(flags)} rows already exist in an earlier version", + "warn", + count=len(flags), + ) + return flags + + def _ok( file_id: object, table_name: str, diff --git a/api/services/originals.py b/api/services/originals.py index dddd819..8085906 100644 --- a/api/services/originals.py +++ b/api/services/originals.py @@ -103,30 +103,35 @@ def store_upload( page_size=1000, ) if flags: - execute_values( - cur, - sql.SQL( - "INSERT INTO {}.row_flags (upload_id, row_number, kind, " - "matched_file_id, matched_file_name, matched_version) VALUES %s" - ) - .format(s) - .as_string(cur), - [ - ( - upload_id, - f["rowNumber"], - "duplicate_of_earlier_version", - int(f["matchedFileId"]), - f["matchedFileName"], - f["matchedVersion"], - ) - for f in flags - ], - page_size=1000, - ) + _store_row_flags(cur, s, upload_id, flags) return upload_id +def _store_row_flags(cur: cursor, s: sql.Identifier, upload_id: int, flags: list[DuplicateFlag]) -> None: + """The rows that duplicate an earlier version of the dataset (M5, BR-29), as ``row_flags``.""" + execute_values( + cur, + sql.SQL( + "INSERT INTO {}.row_flags (upload_id, row_number, kind, " + "matched_file_id, matched_file_name, matched_version) VALUES %s" + ) + .format(s) + .as_string(cur), + [ + ( + upload_id, + f["rowNumber"], + "duplicate_of_earlier_version", + int(f["matchedFileId"]), + f["matchedFileName"], + f["matchedVersion"], + ) + for f in flags + ], + page_size=1000, + ) + + def record_upload( file_name: str, content: str, diff --git a/api/services/staged_import.py b/api/services/staged_import.py index 7575417..7d7023a 100644 --- a/api/services/staged_import.py +++ b/api/services/staged_import.py @@ -505,21 +505,7 @@ def effective_rows(cur: cursor, upload_id: int, decisions_upto: int, edits_upto: if changed: out["edited"] += 1 cells = [changed[c] if c in changed else (raw[c] if c < len(raw) else "") for c in range(width)] - error: dict[str, str | None] | None = None - if extra_cells(raw, width): - error = { - "column": "(beyond header)", - "value": extra_cells(raw, width)[0], - "reason": ragged_row_reason(raw, width), - } - values: list[Any] = [] - for c in range(width): - if error: - break - ok, val, reason = cast_value(cells[c], types[c]) - if not ok: - error = {"column": columns[c], "value": cells[c], "reason": reason} - values.append(val) + values, error = _validate_row(raw, cells, columns, types) if error: out["invalid"] += 1 if len(out["errors"]) < settings.MAX_ROW_ERRORS_REPORTED: @@ -563,6 +549,68 @@ def _replay(st: dict[str, Any]) -> dict[str, Any]: } +def _validate_row( + raw: list[str], cells: list[str], columns: list[str], types: list[str] +) -> tuple[list[Any], dict[str, str | None] | None]: + """A row's values cast to the column types, and the first problem with it (a cell beyond the header, or a cell + that does not cast), or None.""" + width = len(columns) + error: dict[str, str | None] | None = None + if extra_cells(raw, width): + error = { + "column": "(beyond header)", + "value": extra_cells(raw, width)[0], + "reason": ragged_row_reason(raw, width), + } + values: list[Any] = [] + for c in range(width): + if error: + break + ok, val, reason = cast_value(cells[c], types[c]) + if not ok: + error = {"column": columns[c], "value": cells[c], "reason": reason} + values.append(val) + return values, error + + +def _refuse_unless_importable(st: dict[str, Any]) -> None: + """409 for an upload already imported (under another key: the same key replays instead) or not yet approved.""" + if st["import"]: + raise WorkflowError(409, "This upload has already been imported", state="imported", importId=st["import"]["id"]) + if st["state"] != "approved": + raise WorkflowError( + 409, f"This upload is {st['state']}; only an approved upload can be imported", state=st["state"] + ) + + +def _audit_import( + cur: cursor, + st: dict[str, Any], + upload_id: int, + import_id: int, + file_id: int, + approval_id: int, + table_name: str, + counts: dict[str, Any], +) -> None: + write_audit( + cur, + "import", + file_id, + st["fileName"], + table_name, + "dynamic", + before={"upload": upload_id, "state": "approved"}, + after={ + "upload": upload_id, + "import": import_id, + "approval": approval_id, + "table": table_name, + "reconciliation": counts, + }, + ) + + def import_upload(upload_id: int, key: str, session: dict[str, Any] | None) -> dict[str, Any]: """Import an approved upload in one transaction, or change nothing (ADR-0002). @@ -580,16 +628,9 @@ def import_upload(upload_id: int, key: str, session: dict[str, Any] | None) -> d # One import per upload at a time; a concurrent retry waits, then sees the committed result. cur.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (f"{schema}.import.{upload_id}",)) st = _require(cur, upload_id) - if st["import"]: - if st["import"]["idempotencyKey"] == key: - return _replay(st) - raise WorkflowError( - 409, "This upload has already been imported", state="imported", importId=st["import"]["id"] - ) - if st["state"] != "approved": - raise WorkflowError( - 409, f"This upload is {st['state']}; only an approved upload can be imported", state=st["state"] - ) + if st["import"] and st["import"]["idempotencyKey"] == key: + return _replay(st) + _refuse_unless_importable(st) approval = st["approval"] plan = effective_rows(cur, upload_id, approval["decisionsUpto"], approval["editsUpto"]) if plan["invalid"]: # approval checked this; only a bug or manual DB change gets here @@ -619,22 +660,7 @@ def import_upload(upload_id: int, key: str, session: dict[str, Any] | None) -> d ) _checkpoint("registered") _create_and_fill(conn, cur, schema, table_name, import_id, columns, col_types, valid) - write_audit( - cur, - "import", - file_id, - st["fileName"], - table_name, - "dynamic", - before={"upload": upload_id, "state": "approved"}, - after={ - "upload": upload_id, - "import": import_id, - "approval": int(approval["id"]), - "table": table_name, - "reconciliation": counts, - }, - ) + _audit_import(cur, st, upload_id, import_id, file_id, int(approval["id"]), table_name, counts) conn.commit() return { "status": "ok",