Skip to content

fix: generate new ID on retry and add app test harness - #89

Closed
montionugera wants to merge 2 commits into
elixir-cloud-aai:devfrom
montionugera:test/issue-71
Closed

montionugera wants to merge 2 commits into
elixir-cloud-aai:devfrom
montionugera:test/issue-71

Conversation

@montionugera

@montionugera montionugera commented Oct 20, 2026 •

Copy link
Copy Markdown

Description

Fixes #71 and #72:

  1. Service ID Collision Retry Fix (Bug: service ID retry never generates a new ID #72):

    • In RegisterService.register_metadata, generates a new random service identifier on each retry iteration instead of re-attempting with the same conflicting ID.
    • Preserves caller data dictionary by copying before ID assignment and MongoDB insertion.
    • Properly sets was_replaced = True on PUT when document was matched or modified.
  2. App-level Test Harness & Coverage (Tests: app-level test harness with fixtures #71):

    • Adds tests/test_app.py exercising all endpoints, OpenAPI validation, authentication, and startup.
    • Refactors unit tests to modern pytest fixtures with mongomock and mock OIDC token validation.
    • Re-enables cloud_registry/app.py coverage in pyproject.toml with 99% overall test coverage.
    • Fixes Tuple[None, int, Dict] status code type in postServiceInfo controller to prevent Connexion logger format errors.

Closes #71
Closes #72
Closes #32
Closes #40

Summary by Sourcery

Prevent service ID collision retries from reusing identifiers and strengthen end-to-end application test coverage.

New Features:

  • Add an application-level test harness covering endpoints, validation, authentication, and startup behavior.

Bug Fixes:

  • Generate a fresh service ID for each POST retry after an identifier collision.
  • Preserve caller payload dictionaries during service registration and correctly report replaced PUT documents.
  • Return an integer status code for service-info creation responses.

Enhancements:

  • Modernize registry and service tests around shared pytest fixtures and in-memory MongoDB.

Tests:

  • Expand coverage to include the application entry point and full endpoint flows, with mocked OIDC authentication and MongoDB.

Chores:

  • Enable application code in coverage measurement and update test database indexes to enforce unique service IDs.

- Generate new random service identifier on each retry attempt in RegisterService (elixir-cloud-aai#72)
- Preserve caller data dictionary by copying before ID assignment and DB insertion
- Add app-level integration test harness via Connexion and FOCA (Closes elixir-cloud-aai#71)
- Refactor unit test suite to use pytest fixtures and mongomock
- Add test coverage for all endpoints, validation errors, and startup (Closes elixir-cloud-aai#32, Closes elixir-cloud-aai#40)
@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR fixes POST service ID collision retries, protects caller payloads, and corrects PUT replacement tracking and service-info status typing. It also introduces a full Connexion/FOCA application test harness with mocked MongoDB and OIDC dependencies, refactors unit tests around shared fixtures, and enables app-level coverage.

Sequence diagram for service ID collision retry

sequenceDiagram
    participant Client
    participant RegisterService
    participant MongoDB

    Client->>RegisterService: register_metadata(retries)
    loop Each retry attempt
        RegisterService->>RegisterService: generate_id(charset, length)
        RegisterService->>MongoDB: insert_one(insert_doc)
        alt DuplicateKeyError
            MongoDB-->>RegisterService: DuplicateKeyError
        else Insert succeeds
            MongoDB-->>RegisterService: Insert result
            RegisterService-->>Client: Service registered
        end
    end
    RegisterService-->>Client: InternalServerError
Loading

Sequence diagram for PUT service replacement tracking

sequenceDiagram
    participant Client
    participant RegisterService
    participant MongoDB

    Client->>RegisterService: register_metadata()
    RegisterService->>MongoDB: replace_one(filter, replacement, upsert=True)
    MongoDB-->>RegisterService: matched_count, modified_count
    alt Document matched or modified
        RegisterService->>RegisterService: was_replaced = True
    end
    RegisterService-->>Client: Replacement complete
Loading

Sequence diagram for service-info POST response

sequenceDiagram
    participant Client
    participant postServiceInfo
    participant RegisterServiceInfo

    Client->>postServiceInfo: POST service-info
    postServiceInfo->>RegisterServiceInfo: set_service_info_from_app_context(data)
    RegisterServiceInfo-->>postServiceInfo: headers
    postServiceInfo-->>Client: 201 with headers
Loading

File-Level Changes

Change Details Files
Generate collision-safe service IDs for POST registrations while preserving input data and correctly tracking PUT replacements.
  • Copy caller data before adding database-managed fields.
  • Generate a fresh ID on every POST retry and raise an internal error after exhausting attempts.
  • Separate PUT upsert handling from POST retry logic and mark replacements when a document is matched or modified.
cloud_registry/ga4gh/registry/service.py
Correct the service-info controller response type and status value for Connexion compatibility.
  • Return HTTP status 201 as an integer rather than a string.
  • Update the response tuple annotation to use an integer status code.
cloud_registry/ga4gh/registry/server.py
Add application-level coverage for endpoint behavior, validation, authentication, startup, and OpenAPI integration.
  • Exercise authenticated and unauthenticated requests across all registry and service-info endpoints.
  • Add tests for validation errors, not-found responses, PUT create/replace behavior, and startup failure paths.
  • Provide reusable fixtures for mongomock databases, FOCA/Connexion clients, payloads, and mocked OIDC/JWT services.
tests/test_app.py
tests/conftest.py
Modernize unit-test setup and expand coverage configuration.
  • Replace repeated ad hoc Flask and MongoDB setup with pytest fixtures.
  • Add regression tests for ID collisions, retry exhaustion, caller-data immutability, and replacement tracking.
  • Enable app.py in coverage and configure unique mock database indexes plus minor formatting/lint settings.
tests/ga4gh/registry/test_server.py
tests/ga4gh/registry/test_service.py
tests/ga4gh/registry/test_service_info.py
tests/mock_data.py
pyproject.toml

Assessment against linked issues

Issue Objective Addressed Explanation
#32 Add unit and app-level tests for app.py, covering application startup and endpoint behavior, and include app.py in test coverage. ✅
#40 Add integration tests that exercise the API endpoints’ response scenarios, including successful requests, validation errors, not-found cases, and authentication behavior. ✅
#40 Provide an app-level test harness that runs requests through the application stack and validates startup behavior. ✅
#71 Provide shared test fixtures for FOCA configuration, a mongomock database with unique indexes, and an authenticated Connexion app client with mocked token validation; migrate existing unit tests to the shared fixtures. ✅
#71 Add app-level tests covering each endpoint’s response and status codes, including validation, authentication, error formatting, empty and unknown-resource cases, and PUT creation/replacement; test app startup and include app.py in coverage. ✅
#71 Correct the duplicate-ID retry test so it exhausts a one-character ID space against a unique index, verifying retries fail when no ID is available and succeed when a fresh ID is generated. ✅
#72 Generate a fresh service ID for each POST insertion attempt after a duplicate-key collision, while leaving the PUT path with its user-supplied ID unchanged. ✅
#72 Avoid modifying the caller's request dictionary or carrying MongoDB's inserted _id into subsequent attempts. ✅
#72 When all ID-generation retries collide, return an HTTP 500 and log the failure; log individual collisions at debug level. ✅

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

@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 2 issues

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

## Individual Comments

### Comment 1
<location path="tests/test_app.py" line_range="254" />
<code_context>
+        monkeypatch.setattr("connexion.apps.flask_app.FlaskApp.run", run_mock)
+
+        app_main()
+        assert run_mock.called
+
+    def test_app_main_missing_config(self, monkeypatch):
</code_context>
<issue_to_address>
**Startup test misses service-info registration**

When `app_main()` starts the app without registering service-info, `test_app_main_startup` asserts only `run_mock.called` at line 254, so `app_main()` can omit service-info registration and the test still passes as long as it starts the app.

Assert that startup persisted the configured service-info document before the patched app run completes.
</issue_to_address>

### Comment 2
<location path="tests/ga4gh/registry/test_service.py" line_range="117" />
<code_context>
+            ):
+                obj = RegisterService(data=data)
+                obj.register_metadata()
+                assert obj.data["id"] == "NEW_UNIQUE_ID"
+                assert "id" not in data
+                assert "_id" not in data
</code_context>
<issue_to_address>
**Retry test accepts unpersisted service**

When the retry assigns `NEW_UNIQUE_ID` to the object but does not insert it into the collection, `test_register_metadata_collision_retry_success` only checks `obj.data["id"]` at line 117; if the retry assigns `NEW_UNIQUE_ID` but skips inserting the service, the test still passes without verifying the registration succeeded.

Assert that the collection contains the registered service with `NEW_UNIQUE_ID` after the retry.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and a successful POST writes a service record under the newly generated ID, and that record remains after reverting this change; if the retry path writes an unintended record, it can be removed or corrected. The changed replacement flag may also affect the response for a no-op PUT, but that behavior is reversible.

Blocking findings: tests/test_app.py:254, tests/ga4gh/registry/test_service.py:117


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

Comment thread tests/test_app.py
monkeypatch.setattr("connexion.apps.flask_app.FlaskApp.run", run_mock)

app_main()
assert run_mock.called

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Startup test misses service-info registration

When app_main() starts the app without registering service-info, test_app_main_startup asserts only run_mock.called at line 254, so app_main() can omit service-info registration and the test still passes as long as it starts the app.

Assert that startup persisted the configured service-info document before the patched app run completes.

Prompt for AI agents
In `tests/test_app.py` at line 254:

**Startup test misses service-info registration**

When `app_main()` starts the app without registering service-info, `test_app_main_startup` asserts only `run_mock.called` at line 254, so `app_main()` can omit service-info registration and the test still passes as long as it starts the app.

Assert that startup persisted the configured service-info document before the patched app run completes.

):
obj = RegisterService(data=data)
obj.register_metadata()
assert obj.data["id"] == "NEW_UNIQUE_ID"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Retry test accepts unpersisted service

When the retry assigns NEW_UNIQUE_ID to the object but does not insert it into the collection, test_register_metadata_collision_retry_success only checks obj.data["id"] at line 117; if the retry assigns NEW_UNIQUE_ID but skips inserting the service, the test still passes without verifying the registration succeeded.

Assert that the collection contains the registered service with NEW_UNIQUE_ID after the retry.

Prompt for AI agents
In `tests/ga4gh/registry/test_service.py` at line 117:

**Retry test accepts unpersisted service**

When the retry assigns `NEW_UNIQUE_ID` to the object but does not insert it into the collection, `test_register_metadata_collision_retry_success` only checks `obj.data["id"]` at line 117; if the retry assigns `NEW_UNIQUE_ID` but skips inserting the service, the test still passes without verifying the registration succeeded.

Assert that the collection contains the registered service with `NEW_UNIQUE_ID` after the retry.

@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 99.52%. Comparing base (040e098) to head (2eced82).

Additional details and impacted files
@@             Coverage Diff             @@
##               dev      #89      +/-   ##
===========================================
- Coverage   100.00%   99.52%   -0.48%     
===========================================
  Files            5        6       +1     
  Lines          189      211      +22     
===========================================
+ Hits           189      210      +21     
- Misses           0        1       +1     

☔ 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.

@uniqueg

uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Thanks a lot for picking this up so quickly! I reviewed it and ran it locally. Here is what I found.

What works

  • The Bug: service ID retry never generates a new ID #72 fix is correct. A new ID is drawn on every retry, and the caller's data is no longer modified. test_register_metadata_collision_retry_success fails on dev and passes with the fix.
  • On dev (FOCA 0.12.1, Python 3.10), all 45 tests pass, and flake8, black and mypy are clean. The "201" → 201 fix in postServiceInfo is right too.

Why it doesn't fully address #71 and #40 yet

  1. It does not work with FOCA 0.14. One acceptance criterion of Tests: app-level test harness with fixtures #71 is that the same tests pass on the FOCA 0.14 upgrade (feat!: upgrade to FOCA 0.14.0 #65); that's what the harness is for. tests/conftest.py and tests/test_app.py import and patch flask_pymongo, which FOCA 0.14 no longer uses. With this branch merged into feat/foca-0.14, the test session fails before collecting any test:

    ImportError while loading conftest 'tests/conftest.py'.
    tests/conftest.py:14: in <module>
        import flask_pymongo
    E   ModuleNotFoundError: No module named 'flask_pymongo'
    

    The FOCA 0.14 equivalent is to patch foca.database.register_mongodb.MongoClient.

  2. The mock identity provider accepts tokens signed with any key. mock_oidc_get answers the user info endpoint for any token it can decode, without checking the signature. Since config.yaml uses validation_checks: any, a token signed with a foreign RSA key (correct iss and kid) gets 200 on GET /services. The 401 tests therefore only cover a missing header or a token that cannot be decoded at all. test: add integration tests #40 asks for authentication testing, and the access control work in Cloud Registry backend: public read access, service ownership, ECP_CLN:ADMIN admin role #62 depends on it.

  3. Smaller points:

    • Some assertions are weak, e.g. len(service_id) > 0 and service_id in service_ids instead of comparing the stored document.
    • sys.path is modified at import time in conftest.py.
    • test_app_main_startup only checks that run was called (not the port or the registered service info).
    • test_app_main_missing_config patches Path.exists globally.

How we'll proceed

While you were working on this, I had a branch for the same issues in progress (the issues were drafted as part of a planned sequence). It is now up as #90. Its harness supports FOCA 0.12 and 0.14, checks token signatures, and also covers a 500 response. Since both PRs touch the same files, only one of them can be merged; I will decide which once both have been reviewed. Either way, your review of the problem was spot on, and thanks again for the contribution!

@uniqueg

uniqueg commented Oct 20, 2026

Copy link
Copy Markdown
Member

Thanks again, @montionugera. #90 has now been merged and closed #71, #72, #32 and #40, so I'm closing this PR. Your diagnosis of #72 matched ours exactly. If you'd like to contribute again, please comment on the issue before you start, so that we can avoid duplicate work.

@uniqueg uniqueg closed this Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants