Skip to content

test: run tests against a real MongoDB - #164

Merged
uniqueg merged 5 commits into
devfrom
test/real-mongodb
Oct 21, 2026
Merged

uniqueg merged 5 commits into
devfrom
test/real-mongodb

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

All tests ran against mongomock. With this PR, the full suite can run against a real MongoDB, and CI does so against MongoDB 7.0.

  • tests/conftest.py:
    • If MONGODB_TEST_URI is set, the fixtures use the MongoDB at that URI. One client serves the whole session, and database serviceStore is dropped before each test (and at the end). Without the variable, the tests use mongomock as before. The run ends with a usage error, before any test, if that MongoDB already has a database serviceStore (for example a deployment's data; Sourcery review).
    • _no_network still blocks network access, but allows connections to the resolved addresses of the URI's hosts (DB_ADDRESSES).
    • Unit tests (unit_app) use database serviceStore of the same client (was: db of their own mongomock client).
    • COLLECTION_CLASS (pymongo's or mongomock's Collection) is the patch target of the race tests in tests/test_access_control.py, which patched mongomock's class before.
  • tests/test_fixtures.py: tests of the switch, the per-test isolation, the address resolution and the network block.
  • CI: new job Run tests (MongoDB 7.0) (test_mongodb), with a mongo:7.0 service container, as in docker-compose.yaml (8.0 doesn't start on some runner kernels). The stable Run tests check now requires it, and the job fails if the URI is missing instead of silently using mongomock.
  • docs/development.md: how to run the tests against a local MongoDB.

Real differences found: none. The full suite passed unchanged against MongoDB 7.0, including the race tests, which assert that their interleaving ran.

Closes #154

Verification

  • Local mongod 7.0.34 (MONGODB_TEST_URI=mongodb://127.0.0.1:12345): the full suite passed (884 passed after the Sourcery fix). The mongod log shows the session client (3 connections) and the per-test drops. The adversarial reviewer independently got 738 passed and 145 skipped (helm missing) against its own mongod, plus a localhost URI run. Afterwards no database was left besides admin/config/local.
  • mongomock (default), with Helm 3.22.1: coverage run --source cloud_registry,scripts -m pytest gave 884 passed and 100% coverage.
  • ruff check and format, mypy, ast-grep, actionlint 1.7.12 with shellcheck 0.11.0, and mkdocs build --strict: all pass.
  • CI: all checks pass. The new Run tests (MongoDB 7.0) job ran the full suite against the service container (883 passed, chart tests included). Also passing: static analysis, tests on 3.10 and 3.12, Helm chart, docs, Docker Compose smoke test and Read the Docs.

Declined review findings

  • Rename COLLECTION_CLASS (quality, low). Kept; its comment says what it is for.

  • Drop the typed local variable in db_client (quality, low). It avoids a type: ignore.

  • Deduplicate the setup steps of test_mongodb (quality, low). The other jobs of checks.yaml follow the same pattern.

  • Allow replica-set members discovered at runtime, or re-resolve DNS at connect time (adversarial, low). The docs and the conftest docstring now require a single-node MongoDB, as in CI.

  • A database name per run, so that concurrent runs can share a MongoDB (adversarial, low). The docs now ask for one MongoDB per run; the tests hard-code serviceStore in places.

  • Separate databases per pytest-xdist worker (Sourcery, medium). The project doesn't run tests in parallel, and the database name comes from config.yaml. The docs ask for one MongoDB per run.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits October 22, 2026 00:48
If MONGODB_TEST_URI is set, the fixtures use the MongoDB at that URI
instead of mongomock: one client for the session, with database
serviceStore dropped before each test, and network access allowed to
the database's addresses only. Unit tests use database serviceStore
too (was: db). Collection patches use the collection class of the
tests' database. Without the variable, the tests use mongomock as
before. Document how to run the tests against a local MongoDB.

The full suite passes against MongoDB 7.0 without changes to the app.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add job test_mongodb, which runs the full suite against a MongoDB 7.0
service container (MONGODB_TEST_URI), and require it for the stable
"Run tests" check.

Closes #154

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fail the MongoDB job if MONGODB_TEST_URI is missing instead of falling
back to mongomock, check the mode against the environment in the
fixture tests, publish the test MongoDB on localhost only in the docs,
and say that each run needs its own single-node MongoDB.

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

sourcery-ai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR extends the test fixtures to optionally use a real, isolated MongoDB while retaining mongomock by default, adapts race-test patching and network controls accordingly, adds fixture coverage, and introduces a required MongoDB 7.0 CI job with local-development documentation.

Sequence diagram for isolated real MongoDB tests

sequenceDiagram
    participant Runner as Test runner
    participant Fixtures as Test fixtures
    participant MongoDB as MongoDB
    participant Test as Test case

    Runner->>Fixtures: create session client from MONGODB_TEST_URI
    Fixtures->>MongoDB: drop_database(serviceStore)
    Fixtures->>Test: provide client and serviceStore database
    Test->>MongoDB: execute test operations
    Test-->>Fixtures: test completes
    Fixtures->>MongoDB: drop_database(serviceStore)
    Runner->>Fixtures: finish test session
    Fixtures->>MongoDB: drop_database(serviceStore)
Loading

Flow diagram for selecting the test database backend

flowchart TD
    Start[Test suite starts] --> URI{MONGODB_TEST_URI set?}
    URI -->|Yes| Resolve[Resolve URI host addresses]
    Resolve --> Allow[_no_network allows resolved addresses]
    Allow --> Real[Use session MongoDB client]
    URI -->|No| Mock[Use mongomock client]
    Real --> Isolate[Drop serviceStore before each test]
    Mock --> Run[Run tests]
    Isolate --> Run
Loading

File-Level Changes

Change Details Files
Add an opt-in real MongoDB backend for the shared test fixtures while preserving mongomock as the default.
  • Select MongoDB from MONGODB_TEST_URI or create a mongomock client otherwise.
  • Reuse one real client per test session and drop serviceStore before each test and during teardown.
  • Permit socket connections only to resolved MongoDB URI addresses while retaining the test network block.
  • Use the selected collection implementation in access-control race-test patches.
  • Add fixture tests covering backend selection, isolation, address resolution, and network permissions.
tests/conftest.py
tests/test_access_control.py
tests/test_fixtures.py
Run the complete test suite against MongoDB 7.0 in CI and make it required for the stable test status.
  • Add a MongoDB 7.0 service container and test_mongodb job using MONGODB_TEST_URI.
  • Fail the MongoDB job if the URI is absent rather than silently falling back to mongomock.
  • Require both the existing matrix and MongoDB job to pass in tests_passed.
  • Clarify the database-backed Docker Compose smoke-test coverage comment.
.github/workflows/checks.yaml
Document local execution against an isolated single-node MongoDB instance.
  • Explain the URI-based fixture switch and serviceStore cleanup behavior.
  • Provide a MongoDB 7.0 Docker command and pytest example.
  • Document the single-node, one-run-per-database requirements.
docs/development.md

Assessment against linked issues

Issue Objective Addressed Explanation
#154 Allow test fixtures to use a real MongoDB when MONGODB_TEST_URI is set, while continuing to use mongomock by default. ✅
#154 Run the full test suite in CI against MongoDB 7.0 and require that job to pass. ✅
#154 Check for MongoDB-specific behavioral differences, address any that arise, and document how to run the tests against a local MongoDB. ✅

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 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (aec4061) to head (2eefaa7).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #164   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           11        11           
  Lines          880       880           
=========================================
  Hits           880       880           

☔ 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 October 21, 2026 23:21

@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/conftest.py" line_range="245" />
<code_context>
+    if _mongodb is None:
+        client: MongoClient[dict[str, Any]] = mongomock.MongoClient()
+        return client
+    _mongodb.drop_database(DB)
+    return _mongodb
+
</code_context>
<issue_to_address>
**Test run deletes service data**

When a developer or CI operator sets `MONGODB_TEST_URI` to a shared or production MongoDB that contains `serviceStore`, `db_client` unconditionally calls `_mongodb.drop_database(DB)` for each test, deleting every collection in `serviceStore` on the configured server; the operator loses that data.

Require an explicit destructive-test opt-in or otherwise verify that the configured target is disposable before dropping `DB`.
</issue_to_address>

### Comment 2
<location path="tests/conftest.py" line_range="245" />
<code_context>
+    if _mongodb is None:
+        client: MongoClient[dict[str, Any]] = mongomock.MongoClient()
+        return client
+    _mongodb.drop_database(DB)
+    return _mongodb
+
</code_context>
<issue_to_address>
**Parallel workers erase each other's data**

When pytest-xdist runs tests in multiple workers against the same `MONGODB_TEST_URI`, worker A can drop `serviceStore` while worker B's test is using it, so B loses its records or indexes and its assertions fail. Use a worker-specific database or serialize tests that share this database.

Give each worker an isolated database, or prevent parallel workers from sharing the test database.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and when MONGODB_TEST_URI is set, the test fixture drops the serviceStore database before each test. If the URI points to a database with real data, that data is deleted and reverting the change cannot restore it.

Blocking findings: tests/conftest.py:245, tests/conftest.py:245


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
End the test run before any test if the MongoDB at MONGODB_TEST_URI
already has database serviceStore (e.g., of a deployment), instead of
dropping it (Sourcery review).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 8bea9ad into dev Oct 21, 2026
13 checks passed
@uniqueg
uniqueg deleted the test/real-mongodb branch October 21, 2026 23:39
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: run tests against a real MongoDB

1 participant