Skip to content

test: add app test harness and fix the tests - #236

Merged
uniqueg merged 5 commits into
devfrom
test/app-test-harness
Oct 22, 2026
Merged

uniqueg merged 5 commits into
devfrom
test/app-test-harness

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Rebuilds the test suite on an app test harness, as in cloud-registry (elixir-cloud-aai/cloud-registry#90, elixir-cloud-aai/cloud-registry#164), and replaces the CI integration tests against public TES instances with a Compose smoke test against a local fake TES backend (S14 of the migration plan).

  • Layout: tests/ mirrors pro_tes/ (ga4gh/tes/, tasks/, middleware/, plugins/…, utils/); the uncollectable tests/unitTest (fix: unit tests #168) and tests/test_integration are removed, with pytest-ordering and the ruff/mypy excludes.
  • Harness (tests/conftest.py): mongomock by default, a real MongoDB if MONGODB_TEST_URI is set (databases taskStore and protes dropped before each test, refused if present); network access blocked except to the test database (connect, connect_ex), and no name resolution in the distance-based middleware. tests/test_fixtures.py tests the harness.
  • TES endpoints (tests/ga4gh/tes/test_server.py) with fake backends: relay, fallback to the next backend (invalid URL, rejected task), no backend (500, SYSTEM_ERROR), backend that doesn't serve the task yet, Funnel, invalid tasks, views, not found, cancellation (also of finished tasks and of legacy nested forwards).
  • Enforce immutability for incoming task document #142: the task as received is stored once and is not changed by the middlewares, the tracking or the cancellation.
  • test: unit test for tasks module #149: the Celery task: database (MONGO_DBNAME), client URL and credentials, state changes and polling interval, retries, attempts exceeded, backend unavailable, missing logs, missing document.
  • fix: unit tests #168: middleware handler (import, alternatives, failures, invalid paths), distance-based (mocked DNS and geolocation) and random distribution, strip_auth, get_custom_config.
  • CI: test (Python 3.10, 3.12), test_mongodb (MongoDB 7.0 service) and the stable aggregate check "Run tests" (tests_passed), as in cloud-registry; smoke_test runs docker compose up --wait with tests/smoke/compose.yaml (fake TES in the app image, config overlay with only that backend and random distribution) and tests/smoke/check.sh (task relayed, tracked by the Celery worker via RabbitMQ to COMPLETE, listing, cancel, 404, the fake backend got it). publish now needs these jobs. No test or CI job contacts external TES instances.
  • Docs: docs/development.md (running the tests, against MongoDB, and the smoke test locally).

App bugs found on the way are left to #208 (next in the stack) or listed below; the tests here avoid asserting the buggy behaviour.

Closes #207
Closes #142
Closes #149
Closes #168

How it was verified

  • pytest: 118 passed (mongomock, Python 3.12); MONGODB_TEST_URI=mongodb://127.0.0.1:27391 pytest against a local MongoDB 7.0: 117 passed (before the last test was added), only admin/config/local left afterwards.
  • ruff format --check, ruff check, mypy, ast-grep scan, ast-grep test, semgrep (.semgrep), actionlint: clean.
  • tests/smoke/fake_tes.py driven with py-tes locally (service info, create, get, list, cancel). The Compose smoke test itself only runs in CI (docker run is not available locally); docker compose config with the override checked.
  • Reviews: adversarial and quality reviewer subagents (2 rounds of the adversarial one).
  • CI: all checks pass (the first run found the flat middlewares list of the smoke overlay, which the Celery worker rejected; fixed, with a test that validates the overlay with the app).

Declined review findings

  • Coverage measurement, fail_under and the Codecov upload in the test job (as in the template): that is test: enforce 100% coverage #159, next but one in the stack; tests of the error branches of pro_tes/utils/db.py and app.py are left to it too.
  • Concurrent test runs against the same MongoDB: documented as unsupported ("one per test run"), as in cloud-registry; no ownership marker added.
  • Moving the network guard into a helper module: kept in conftest.py, as in the template.
  • Sourcery: blocking DNS and UDP too: connect/connect_ex and gethostbyname in the distance middleware cover the connections and lookups the tests make (reasons in the thread).
  • Sourcery: adding tests/__init__.py: it exists already.

Follow-ups (found while writing the tests)

  • For fix: task listing, timestamps and relay bugs #208: inputs and outputs relayed as URL strings to non-Funnel backends (B1); GET /tasks paging (B2); name_prefix regex (S5); timestamps (B3); BASIC view projects the wrong paths (task.system_logs, task.logs.stdout); storeLogs.execution_trace: False stores a metadata dict that cancellation can't read.
  • Not in an issue yet: the backend's state fetched right after relaying is discarded (the task stays UNKNOWN until the Celery worker updates it); the unique index of tasks is on task_id/worker_id, but the field is task.id, so duplicate generated task IDs are never detected.

🤖 Generated with Claude Code

uniqueg and others added 3 commits October 22, 2026 22:42
Mirror the package in `tests/` and replace the tests that could not be
collected (`tests/unitTest`) and the integration tests against public
TES instances (`tests/test_integration`):

- conftest: real MongoDB via `MONGODB_TEST_URI` (databases dropped per
  test, refused if present), no network access except to it, no name
  resolution in the distance-based middleware
- TES endpoints with fake backends: relay, fallback to the next
  backend, failures, Funnel, views, cancellation
- task as received stored once and never changed (#142)
- Celery task: states, polling, retries, failures (#149)
- middleware handler and task distribution middlewares (#168)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Run all tests in CI (no ignored directories), on Python 3.10 and 3.12,
and against MongoDB 7.0 (`MONGODB_TEST_URI`), with a stable "Run tests"
check, as in cloud-registry.

Replace the integration tests against public TES instances with a
Compose smoke test: a Compose override and config overlay
(`tests/smoke/`) relay tasks to a fake TES backend, and the job checks
that a task is relayed to it and tracked by the Celery worker until it
is complete.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes: the Compose smoke checks move from the workflow to
`tests/smoke/check.sh`, which also runs locally; the network guard of the
tests also covers `socket.connect_ex()`; the docs describe the test
layout and the network guard, and require a standalone MongoDB for
`MONGODB_TEST_URI`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR replaces legacy and externally dependent tests with an app-centered, deterministic harness, substantially broadens endpoint, middleware, and Celery coverage, and updates CI and documentation to validate both mongomock/MongoDB test runs and a local fake-TES Compose deployment.

Sequence diagram for task relay and tracking smoke test

sequenceDiagram
    participant Check as Smoke check
    participant App as proTES API
    participant Queue as RabbitMQ
    participant Worker as Celery worker
    participant TES as Fake TES backend

    Check->>App: POST /tasks
    App->>TES: Create task
    TES-->>App: Task response
    App->>Queue: Submit tracking task
    App-->>Check: Task ID
    Queue->>Worker: Track task progress
    Worker->>TES: Get task
    TES-->>Worker: COMPLETE
    Worker->>App: Store task state
    Check->>App: GET /tasks/{id}
    App-->>Check: COMPLETE task
Loading

Flow diagram for deterministic test harness database selection

flowchart TD
    Start[Test execution] --> URI{MONGODB_TEST_URI set?}
    URI -->|No| Mock[mongomock in-memory database]
    URI -->|Yes| Mongo[Standalone MongoDB test database]
    Mock --> Reset[Reset taskStore and protes before each test]
    Mongo --> Reset
    Reset --> Guard[Block network access except test database]
    Guard --> Tests[Run app, endpoint, middleware, and Celery tests]
Loading

File-Level Changes

Change Details Files
Rebuilt the Python test suite around a shared application harness with isolated database and network behavior.
  • Added app, client, MongoDB/mongomock, and network-blocking fixtures.
  • Added coverage for harness behavior and smoke-test configuration.
  • Removed obsolete uncollectable unit and external integration test trees and related dependencies/exclusions.
tests/conftest.py
tests/test_fixtures.py
tests/test_app.py
pyproject.toml
tests/.gitkeep
tests/unitTest/*
tests/test_integration/*
Expanded endpoint and middleware tests using deterministic local fakes instead of external TES services.
  • Added fake-backend tests for task relay, fallback, failures, tracking, views, cancellation, and task immutability.
  • Added middleware handler, distribution, URL-auth stripping, and configuration tests with mocked DNS/geolocation.
  • Reorganized tests to mirror the application package layout.
tests/ga4gh/tes/test_server.py
tests/ga4gh/tes/test_models.py
tests/tasks/test_track_task_progress.py
tests/middleware/test_middleware_handler.py
tests/plugins/middlewares/task_distribution/test_distance.py
tests/plugins/middlewares/task_distribution/test_random.py
tests/utils/test_misc.py
tests/test_tasks.py
tests/test_track_task_progress.py
Replaced CI's public TES integration testing with MongoDB validation and a local Docker Compose smoke test.
  • Runs the full suite on Python 3.10 and 3.12 with mongomock and separately against MongoDB 7.0.
  • Adds a stable aggregate test check used by publishing.
  • Adds a Compose environment containing the app, worker, RabbitMQ, MongoDB, and an in-image fake TES backend.
  • Smoke script verifies relay, Celery tracking to completion, listing, cancellation, not-found behavior, and backend receipt.
.github/workflows/checks.yaml
tests/smoke/compose.yaml
tests/smoke/config.yaml
tests/smoke/fake_tes.py
tests/smoke/check.sh
Documented the new local and CI test workflows.
  • Updated development instructions for the default harness, standalone MongoDB runs, and Compose smoke tests.
  • Removed references to the deleted legacy test suites and external TES integration tests.
docs/development.md

Assessment against linked issues

Issue Objective Addressed Explanation
#142 Preserve the client-provided task document unchanged for audit purposes, while allowing middleware to modify the outgoing task request. ✅
#149 Add unit tests for the task-tracking Celery task that exercise TES polling, client URL and credentials, retry behavior, and task-state transitions. ✅
#149 Test the task's database-connector interactions, including the expected get_document and update_task_state calls and the final upsert_fields_in_root_object update. ❌ The tests verify state updates and check the final persisted task state and outputs, but they do not assert that get_document is called with the expected arguments or that upsert_fields_in_root_object is called with the expected root and fields.
#168 Make the test suite runnable with pytest, including resolving stale imports of removed exceptions and other obsolete imports. ✅
#207 Provide a collectable test suite and app harness that uses mongomock by default or a real MongoDB when configured, and replace the obsolete tests with tests for the current application. ✅
#207 Test Celery task progress tracking and verify that the incoming task is stored once and remains unchanged through middleware, tracking, and cancellation. ✅
#207 Update CI and test documentation so tests run with mongomock and MongoDB, and the Compose smoke test uses a local fake TES rather than contacting public TES instances. ✅

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

The middlewares of the config are lists of alternatives; the Celery
worker refused the flat list of the smoke test overlay. A test now
validates the overlay with the app.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review October 22, 2026 21:31

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="tests/conftest.py" line_range="39" />
<code_context>
+# Database set via environment variable `MONGO_DBNAME` in tests
+OTHER_DB = "protes"
+# Databases that the tests use, and drop
+DBS = (DB, OTHER_DB)
+# URI of a MongoDB to test against instead of mongomock (see above)
+MONGODB_TEST_URI = os.environ.get("MONGODB_TEST_URI", "")
</code_context>
<issue_to_address>
**Test database escapes cleanup**

When `MONGODB_TEST_URI` is set and `MONGO_DBNAME` names a database outside `taskStore` and `protes`, `_check_no_db` and the cleanup loops use only `DBS`, so the app can read or modify that database and tests leave its data mixed with existing data.

Include the configured `MONGO_DBNAME` in the database safety checks and cleanup.
</issue_to_address>

### Comment 2
<location path="tests/conftest.py" line_range="134-138" />
<code_context>
+
+
[email protected](autouse=True)
+def no_network(monkeypatch: pytest.MonkeyPatch) -> None:
+    """Block network access of all tests, except to the test database."""
+    monkeypatch.setattr(socket.socket, "connect", _no_network)
+    monkeypatch.setattr(socket.socket, "connect_ex", _no_network_ex)
+    monkeypatch.setattr(distance, "gethostbyname", _no_name_resolution)
+
+
</code_context>
<issue_to_address>
**Network traffic escapes test isolation**

When a test or dependency resolves an external hostname through the system resolver or sends UDP traffic, `no_network` patches TCP connection methods and the distance middleware’s resolver, but leaves system DNS resolution and UDP `sendto` unblocked, so DNS queries or datagrams reach external hosts despite the harness’s no-network guarantee.

Block system DNS resolution and UDP sends as well, and add tests that verify both paths are blocked.

Also at `tests/test_fixtures.py:79`.
</issue_to_address>

### Comment 3
<location path="tests/ga4gh/tes/test_server.py" line_range="17" />
<code_context>
+from pro_tes.ga4gh.tes.models import TesTask
+from pro_tes.tasks import track_task_progress
+from pro_tes.utils.misc import get_custom_config
+from tests.conftest import DB
+
+BASE_PATH = "/ga4gh/tes/v1"
</code_context>
<issue_to_address>
**Test imports resolve elsewhere**

When a regular top-level `tests` package appears earlier in import resolution, the local `tests` directory has no `__init__.py`, so `from tests.conftest import DB` resolves to the other package and pytest fails to collect the test.

Make the local `tests` package unambiguous, for example by adding `tests/__init__.py`.

Also at `tests/tasks/test_track_task_progress.py:18`, `tests/test_fixtures.py:15-16`.
</issue_to_address>

### Comment 4
<location path="docs/development.md" line_range="31-32" />
<code_context>
+
+```bash
+docker run -d --rm --name mongodb-test -p 127.0.0.1:27017:27017 mongo:7.0
+MONGODB_TEST_URI=mongodb://localhost:27017 pytest
+docker stop mongodb-test
+```
+
</code_context>
<issue_to_address>
**MongoDB example races startup**

When mongoDB takes longer than five seconds to become ready, `pytest` begins immediately after `docker run -d`, while the container can still be initializing. The `_mongodb` fixture’s five-second server-selection timeout then expires, so the documented local MongoDB test command fails on a slow startup.

Wait for MongoDB’s ping health check to succeed before invoking pytest.
</issue_to_address>

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: tests/conftest.py:39, tests/conftest.py:138, tests/ga4gh/tes/test_server.py:17, docs/development.md:32


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread tests/conftest.py Resolved
Comment thread tests/conftest.py Resolved
Comment thread tests/ga4gh/tes/test_server.py Resolved
Comment thread docs/development.md Resolved
Apps created in tests would use the database named by `MONGO_DBNAME`
of the environment, which the tests neither check nor drop. The docs
wait for the local test MongoDB to be ready before running the tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 47b3e5a into dev Oct 22, 2026
12 checks passed
@uniqueg
uniqueg deleted the test/app-test-harness branch October 22, 2026 22:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test: add app test harness and fix the tests fix: unit tests test: unit test for tasks module Enforce immutability for incoming task document

1 participant