Skip to content

test: add integration tests with MongoDB - #76

Merged
uniqueg merged 5 commits into
devfrom
test/integration-mongodb
Nov 7, 2026
Merged

uniqueg merged 5 commits into
devfrom
test/integration-mongodb

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

Integration tests of the API against a real database, following cloud-registry:

  • Integration tests (tests/integration/):
    • They run the app as deployed: create_app() with the app's own configuration and response validation.
    • They test, through the API:
      • registering users (verified by an admin), repositories and subscriptions;
      • publishing prebuilt images;
      • notifying a local subscriber: delivered, error response, unreachable, and not matching;
      • error cases: unverified user, unknown repository, wrong repository token;
      • that repositories don't show their tokens.
    • They use mongomock, or the MongoDB at MONGODB_TEST_URI. Its database pubgradeStore is dropped before each test, and the tests refuse to start if it already exists.
    • FOCA's MONGO_* settings and its configuration overlay are cleared from the environment.
  • CI: the job test becomes a matrix. Test (mongomock) runs all tests with coverage to Codecov. Test (MongoDB 7.0) runs the integration tests against a MongoDB 7.0 service, the chart's default. The unit tests always use mongomock, so they don't run twice.
  • Clone tests: the unit tests that cloned drs-filer from GitHub now clone a local stand-in. Git rewrites the URL (url.<base>.insteadOf in a Git configuration of the tests' own), so the tests need no network access. They also check the commit or tag that was checked out.
  • Docs: docs/development.md explains the test levels, MONGODB_TEST_URI and the CI matrix.

Closes #39

Verification

  • pytest --cov: 501 passed, 100% coverage, with no network access (run in a sandbox without github.com).
  • MONGODB_TEST_URI=mongodb://127.0.0.1:27117 pytest tests/integration against a throwaway mongo:7.0: 10 passed. The database is gone afterwards.
  • ruff check, ruff format --check, mypy: clean.
  • pre-commit run --all-files and gitleaks-all: passed. actionlint was skipped locally (the sandbox can't download its Go toolchain); CI runs it.
  • CI: all checks pass. Test (mongomock): 501 passed with coverage. Test (MongoDB 7.0): the 10 integration tests pass against the service.

Review

Full review: adversarial and quality reviewers, two rounds.

  • Round 1: no high findings. Fixed:

    • the MongoDB entry runs only the integration tests, and the docs say so;
    • shared request helpers with expected statuses;
    • more error cases;
    • the client is closed after each test;
    • MONGO_* settings are ignored;
    • a test of the response-validation setting;
    • a clearer clone-failure test;
    • the CI step conditions use matrix.database.
  • Round 2: no high or medium findings. Fixed: the refused port stays bound while it is used, more FOCA environment settings are cleared, and comments are clearer.

  • Sourcery (4 threads):

    • Fixed: rejected subscriptions are checked to store nothing; in the clone-failure test, the first clone must succeed.
    • Declined: the MongoDB service with an empty image (GitHub doesn't start it, and Test (mongomock) passes); a separate database per test process (the test MongoDB is a throwaway for one run, as documented).
  • CI: all checks pass on 3aeabdb.

Declined review findings

  • Typed NamedTuple for the local repository fixture (low). SimpleNamespace with three attributes, used in five tests, is clear enough.
  • Git 2.32 or newer needed for GIT_CONFIG_GLOBAL (low). CI and current distributions have it, and older versions only fail the clone tests.
  • Helpers whose return type depends on the expected status (low). This is documented in their docstrings, and it keeps every request payload in one place.
  • Behavioural test of response validation (low). The test checks the configuration, which is what this PR controls. Connexion applies the setting.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits November 7, 2026 07:49
The tests that clone drs-filer from GitHub now clone a local stand-in,
with Git rewriting the URL (url.<base>.insteadOf), so that they need
no network access. They also check the checked-out commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Test registering, publishing and notifying through the API of the app
as deployed (create_app(), with response validation), with a local
subscriber. The tests use mongomock, or the MongoDB at
MONGODB_TEST_URI; CI runs all tests in a matrix with mongomock (with
coverage) and against MongoDB 7.0, the chart's default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cover unreachable subscribers, publishing without subscriptions and
unknown repositories, check that responses are validated, share the
request helpers, close the app's client after each test and ignore
MONGO_* settings from the environment. Run only the integration tests
against MongoDB in CI, as the unit tests always use mongomock, and
say so in the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep the refused port bound while it is used, clear the remaining
FOCA settings from the environment that would affect the tests, and
clarify what the fixtures and checks do.

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

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Configuration

Run the full suite with mongomock and the integration suite against MongoDB 7.0, reporting coverage only from the mongomock job.

  • .github/workflows/ci.yml L107-136, L156-168

Documentation

Document the test levels, network-free unit tests, MongoDB configuration, and how to run integration tests locally.

  • docs/development.md L18, L27-42, L98-106

Tests

Replace GitHub clones in unit tests with a local repository stand-in and assert the expected commit or tag is checked out.

  • tests/conftest.py L5-10, L38-101
  • tests/pubgrade/endpoints/test_builds.py L547-561, L566-581, L587-601 (+6 small edits)

Exercise the deployed API against mongomock or MongoDB, including registration, publishing, notification outcomes, and rejected requests.

  • tests/integration/__init__.py L1
  • tests/integration/conftest.py L1-186
  • tests/integration/test_api.py L1-271
  • tests/integration/test_fixtures.py L1-27

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

@read-the-docs-community

read-the-docs-community Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 Pubgrade | 🛠️ Build #35715385 | 📁 Comparing 3aeabdb against latest (3107df6)

  🔍 Preview build  

1 file changed
± development/index.html

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (3107df6) to head (3aeabdb).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev       #76   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           17        17           
  Lines         1257      1257           
=========================================
  Hits          1257      1257           

☔ 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 marked this pull request as ready for review November 7, 2026 07:17
@uniqueg
uniqueg requested a review from akash2237778 as a code owner November 7, 2026 07:17

@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=".github/workflows/ci.yml" line_range="128-129" />
<code_context>
+    services:
+      # Not started for an empty image (the `mongomock` entry)
+      mongodb:
+        image: ${{ matrix.image }}
+        ports: ["27017:27017"]
+        options: >-
+          --health-cmd "mongosh --quiet --eval 'db.adminCommand({ping: 1}).ok'"
</code_context>
<issue_to_address>
**Mongomock job fails during setup**

When the mongomock matrix entry is selected, the `mongodb` service still uses the empty `matrix.image`, so the runner rejects or fails to start the service before the mongomock tests run; the job fails instead of skipping MongoDB.

Define the `mongodb` service only for matrix entries with a non-empty image.
</issue_to_address>

### Comment 2
<location path="tests/integration/conftest.py" line_range="114" />
<code_context>
+        )
+    else:
+        monkeypatch.setenv("MONGO_URI", MONGODB_TEST_URI)
+        mongodb.drop_database(DB)
+    app = create_app().app
+    yield app.test_client()
</code_context>
<issue_to_address>
**Test runs delete shared database data**

When another test process passes the initial database check concurrently, or another process starts using the database after that check, the `mongodb` fixture check does not reserve `DB`, and the `api` fixture drops it before tests and again at session teardown, deleting another process's in-progress or newly created data and causing API failures or lost results.

Give each test process an isolated database and only drop that process's database.

Also at `tests/integration/conftest.py:63`, `tests/integration/conftest.py:70`.
</issue_to_address>

### Comment 3
<location path="tests/integration/test_api.py" line_range="231" />
<code_context>
+    """Users need to be verified by an admin before they can subscribe."""
+    user = register_user(api, verify=False)
+    repository = register_repository(api)
+    subscribe(api, user, repository["id"], subscriber.url, status=403)
+
+
</code_context>
<issue_to_address>
**Rejected requests can still create subscriptions**

When a subscription request creates a record before returning 403 or 404, when either rejected subscription request writes a record before returning its error, `test_unverified_user_cannot_subscribe` and `test_subscribe_to_unknown_repository` pass because `subscribe` checks only the HTTP status. The caller sees 403 or 404 while a subscription persists.

After each rejected request, assert that no subscription was persisted and that the related state is unchanged.

Also at `tests/integration/test_api.py:238`.
</issue_to_address>

### Comment 4
<location path="tests/pubgrade/endpoints/test_builds.py" line_range="599-606" />
<code_context>
             repo_url=self.repository_url,
             branch="dev",
-            commit="122c34d",
+            commit=drs_filer.commit,
             base_dir=".",
             build_id="build123",
</code_context>
<issue_to_address>
**Broken clones pass the error test**

When `git_clone_and_checkout` raises `GitCloningError` on every call, `test_git_clone_and_checkout_git_command_error` (lines 595–609) puts the first valid clone inside `pytest.raises`; if `git_clone_and_checkout` raises `GitCloningError` for every clone, the test passes before reaching the second call. A regression that breaks all successful clones is therefore hidden.

Assert that the first valid clone succeeds outside `pytest.raises`, then check that the second clone raises.
</issue_to_address>

Linked issues

#39 test: add integration tests with MongoDB · 4 of 4 met

# Requirement Status Notes
1 Run the integration tests with mongomock and MongoDB in a CI matrix using MONGODB_TEST_URI. ✅ Met The mongomock matrix entry runs the full test suite, including integration tests; the MongoDB 7.0 entry sets MONGODB_TEST_URI and runs tests/integration.
2 Test the API through the app with response validation on. ✅ Met The integration fixture creates the app with create_app(), and test_response_validation checks that response validation is enabled.
3 Use a local repository instead of GitHub for unit tests that clone a public repository. ✅ Met The clone tests use a locally created drs-filer repository, with Git URL rewriting configured by the fixture.
4 Test registering, publishing and notifying through the API against MongoDB in CI. ✅ Met The API tests exercise registration, publishing and subscriber notifications; the MongoDB CI entry runs them against its MongoDB 7.0 service.

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and when MONGODB_TEST_URI is set, the test fixture drops the pubgradeStore database before each test and again at session end. It refuses to run if that database exists initially, but another process that writes to it after the check could have its records deleted; reverting the PR would not restore them.

Blocking findings: .github/workflows/ci.yml:129, tests/integration/conftest.py:114, tests/integration/test_api.py:231, tests/pubgrade/endpoints/test_builds.py:606


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

Comment thread .github/workflows/ci.yml Resolved
Comment thread tests/integration/conftest.py Resolved
Comment thread tests/integration/test_api.py Resolved
Comment thread tests/pubgrade/endpoints/test_builds.py Resolved
Rejected subscriptions must not be stored, and the clone that should
succeed in the clone-failure test now runs outside pytest.raises.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 867c7dd into dev Nov 7, 2026
46 checks passed
@uniqueg
uniqueg deleted the test/integration-mongodb branch November 7, 2026 07:45
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 integration tests with MongoDB

1 participant