Skip to content

test: add app test harness, fix ID retry - #90

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

uniqueg merged 5 commits into
devfrom
test/app-harness

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #71 and #72. Adds a test harness that goes through the app, so that the FOCA upgrade (#65) and access control (#62) can be verified, and fixes the bugs it found.

  • ID retry (Bug: service ID retry never generates a new ID #72): POST /services retried after a duplicate key error but generated the identifier only once, so a collision returned 500 after ten identical attempts. A new identifier is now drawn on every attempt. RegisterService also no longer modifies the caller's request data (it works on a copy and inserts a copy, so pymongo's _id doesn't leak).
  • Service-info status: postServiceInfo returned the status as the string "201". connexion logs it with %d at debug level, which fails. The app tests turned this into a 500, so it now returns the integer.
  • Fixtures (tests/conftest.py):
    • app/client: the app created from config.yaml, with MongoDB replaced by mongomock and the identity provider (LS Login, the configured issuer) by a mock that issues and checks RS256 tokens.
    • unit_app, services, service_info: the bare Flask app for unit tests, with in-memory collections that have the unique indexes from config.yaml.
    • The fixtures work with FOCA 0.12 (flask_pymongo.PyMongo) and 0.14 (pymongo.MongoClient).
  • App tests (tests/test_app.py): every endpoint through the API: success paths, an empty database, PUT create vs. replace, 404s, schema validation (400), missing tokens and tokens with a forged signature (401), running out of identifiers (500) and the error response format. 403 cannot occur before access control (Cloud Registry backend: public read access, service ownership, ECP_CLN:ADMIN admin role #62); feat!: add owner-based access control #66 tests it. main() in app.py is tested too, and app.py is no longer omitted from coverage.
  • Unit tests: use the shared fixtures instead of building the app and collections by hand. Tests that mocked the collection now check what was stored. The duplicate-ID test now exhausts a one-character ID space against a unique index, instead of passing by accident (see Tests: app-level test harness with fixtures #71).

Closes #32, closes #40.

Verification

  • Python 3.10, FOCA 0.12.1: pytest (55 passed), flake8, black --check . and mypy cloud_registry pass. Coverage 100% (app.py's if __name__ == "__main__": guard is excluded).
  • Test-first: the new retry test and the test for unmodified request data fail on dev and pass with the fix.
  • FOCA 0.14: with this branch merged into feat/foca-0.14 (feat!: upgrade to FOCA 0.14.0 #65), all 55 tests pass on Python 3.12. The merge conflicts that feat!: upgrade to FOCA 0.14.0 #65 will have to resolve are in requirements.txt, Dockerfile and tests/ga4gh/registry/test_service.py.
  • Reviewed before pushing by an adversarial review (no findings; it confirmed that four of the new tests fail on dev) and a maintainability review in 2 rounds (medium and low findings on the tests fixed).
  • CI (run 39361863649): all checks pass: static analysis, tests on 3.10 and 3.12, Docker Compose smoke test, Read the Docs, Codecov (project and patch).

Notes for reviewers

🤖 Generated with Claude Code

Summary by Sourcery

Fix service registration retries and request-data handling while introducing comprehensive API-level testing infrastructure.

New Features:

  • Add end-to-end API tests covering endpoint behavior, authentication, validation, errors, service lifecycle operations, service information, and application startup.
  • Add shared test fixtures with in-memory MongoDB and a cryptographically verified mock identity provider compatible with supported FOCA versions.

Bug Fixes:

  • Generate a fresh service identifier after each duplicate-key collision instead of retrying the same identifier.
  • Prevent service registration from mutating caller-provided request data or leaking database-generated fields.
  • Return the service-info creation status as an integer HTTP status code.

Enhancements:

  • Consolidate unit tests around shared application and database fixtures and verify persisted records directly.
  • Include app.py in coverage while excluding only its direct-execution guard.

Tests:

  • Strengthen duplicate-identifier and exhausted-identifier coverage using unique in-memory indexes.
  • Add coverage for authentication failures, schema validation, empty and missing resources, PUT create/replace behavior, deletion, service types, service information, and main().

uniqueg and others added 4 commits October 20, 2026 04:15
POST /services retried an insert after a duplicate key error, but
generated the identifier only once, so a collision returned 500 after
ten identical attempts. Generate a new identifier on every attempt.

Also stop modifying the caller's request data: RegisterService now
works on a copy, and inserts a copy so that pymongo's `_id` does not
leak into it.

The test for running out of identifiers never configured the
one-character ID space it meant to set up; it now does, against an
in-memory collection with a unique index.

Fixes #72

Co-Authored-By: Claude Opus 5.5 <[email protected]>
postServiceInfo returned the status code as the string "201".
connexion logs the status with "%d" at debug level, which fails for a
string: logging prints a traceback, and wherever logging errors are
raised (e.g. under pytest), the request ends in a 500.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add tests/conftest.py with an app created from config.yaml, MongoDB
replaced by mongomock and the identity provider by a mock that issues
and checks RS256 tokens. The fixtures work with FOCA 0.12
(flask_pymongo) and 0.14 (pymongo), so the same tests can verify the
upgrade in #65.

tests/test_app.py sends requests through the API, covering every
endpoint: success paths, an empty database, PUT create vs. replace,
404s, schema validation (400), missing or invalid tokens (401) and the
error response format. It also tests app.py's main(), which is no
longer omitted from coverage.

The app still fetches remote references in the GA4GH specs at
startup, so these tests need network access until #76.

Closes #32, closes #40
Part of #71

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Replace the app and in-memory collection set up by hand in almost
every unit test with the `unit_app`, `services` and `service_info`
fixtures. The collections now have the unique indexes from
config.yaml, so duplicate identifiers behave as in production.

Tests that replaced the collection with a MagicMock now use the
in-memory collection and also check what was stored. The MagicMock
duplicate-key test is dropped; the duplicate-key retry test covers it
against a real unique index.

Closes #71

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

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR adds a production-configured end-to-end harness with mocked MongoDB and RS256 OIDC authentication, broadens API and startup coverage, refactors unit tests around shared fixtures, and fixes service ID retry/copying behavior plus the service-info status type.

Sequence diagram for retrying service registration with fresh identifiers

sequenceDiagram
    participant Client
    participant RegisterService
    participant MongoDB
    Client->>RegisterService: register_metadata()
    loop retry up to configured limit
        RegisterService->>RegisterService: generate_id(charset, length)
        RegisterService->>MongoDB: insert_one(document=dict(data))
        alt unique identifier available
            MongoDB-->>RegisterService: insert succeeds
            RegisterService-->>Client: service registered
        else DuplicateKeyError
            MongoDB-->>RegisterService: DuplicateKeyError
        end
    end
    RegisterService-->>Client: InternalServerError
Loading

Sequence diagram for service-info response status

sequenceDiagram
    participant Client
    participant API
    participant RegisterServiceInfo
    Client->>API: POST /service-info
    API->>RegisterServiceInfo: set_service_info_from_app_context(data)
    RegisterServiceInfo-->>API: headers
    API-->>Client: HTTP 201
Loading

File-Level Changes

Change Details Files
Fix service registration retries and isolate caller-owned request data from database mutations.
  • Generate a fresh identifier for each POST retry after DuplicateKeyError.
  • Separate PUT replacement from POST insertion and preserve replacement tracking.
  • Deep-copy input data and insert a document copy so MongoDB _id does not leak into caller data.
cloud_registry/ga4gh/registry/service.py
Correct the service-info endpoint response type for framework logging and HTTP handling.
  • Return integer status 201 instead of string status "201".
  • Update the controller return annotation accordingly.
cloud_registry/ga4gh/registry/server.py
Add cross-version, end-to-end test infrastructure with isolated database and identity-provider fakes.
  • Create app and client fixtures from production config using mongomock.
  • Mock OIDC discovery, JWKS, userinfo, and RS256 token validation while preserving unrelated network requests.
  • Provide bare unit-test app and uniquely indexed in-memory collections.
  • Support both FOCA 0.12 and 0.14 MongoDB integration APIs.
tests/conftest.py
Expand API-level coverage across authentication, validation, endpoint behavior, startup, and error handling.
  • Exercise all API endpoints through the Flask/Connexion client, including empty results, CRUD, replacement, service-info updates, and schema failures.
  • Verify missing and forged-token requests return 401 with the expected error shape.
  • Cover identifier exhaustion, duplicate-free generation, main() startup, and missing-config behavior.
tests/test_app.py
pyproject.toml
Refactor unit tests onto shared fixtures and strengthen persistence-focused registration assertions.
  • Replace hand-built Flask apps and mocked collections with shared in-memory fixtures and unique indexes.
  • Assert stored documents, replacement semantics, collection cardinality, and service-info upsert behavior.
  • Add regression coverage for retrying with a new ID, exhausting the ID space, and leaving input data unchanged.
tests/ga4gh/registry/test_server.py
tests/ga4gh/registry/test_service.py
tests/ga4gh/registry/test_service_info.py

Assessment against linked issues

Issue Objective Addressed Explanation
#32 Add unit and application-level tests for app.py and its API endpoints, and include app.py in coverage rather than omitting it from the test pipeline. ✅
#40 Add integration tests that exercise the API endpoints through the application and verify their response scenarios, including successful requests and expected error responses. ✅
#40 Provide integration-test support for authentication, including checking that requests without valid credentials are rejected. ✅
#71 Add app-level tests that exercise the API through the FOCA/Connexion app, covering endpoint responses, validation, authentication, error formatting, and relevant create/replace and missing-resource behavior. ✅
#71 Provide shared fixtures for app and unit tests, cover app.py startup, and include app.py in coverage. ✅
#71 Correct the duplicate-ID test so it exhausts a one-character identifier space with a unique index, and fix ID generation to retry with a new identifier after collisions. ✅

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

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (040e098) to head (1fdd795).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev       #90   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            5         6    +1     
  Lines          189       204   +15     
=========================================
+ Hits           189       204   +15     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Now that app.py is measured, its `if __name__ == "__main__":` guard
is the only line not covered, which made Codecov report a drop in
project coverage.

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

@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 1 issue

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

## Individual Comments

### Comment 1
<location path="tests/conftest.py" line_range="153" />
<code_context>
+    connexion_app = Foca(
+        config_file=APP_DIR / "config.yaml",
+        custom_config_model="service_models.custom_config.CustomConfig",
+    ).create_app()
+    with connexion_app.app.app_context():
+        RegisterServiceInfo().set_service_info_from_config()
</code_context>
<issue_to_address>
**App tests require external network**

When the remote specification host is unavailable or unreachable, `Foca.create_app()` resolves remote OpenAPI references during fixture setup, so tests using `app` or `client` error before reaching their assertions when those hosts are unreachable, even if the application code is correct.

Use local copies of the referenced schemas or otherwise make reference resolution independent of network access.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and if the retry path is wrong, a POST could store a service under an incorrect or duplicate identifier; that record would remain after reverting, but it can be deleted and recreated. The change does not otherwise introduce an irreversible operation.

Blocking findings: tests/conftest.py:153


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

Comment thread tests/conftest.py Resolved
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.

Tests: app-level test harness with fixtures test: add integration tests Test: Write test cases for app.py

1 participant