Skip to content

feat(testing): add pytest plugin and test issuer - #679

Merged
uniqueg merged 6 commits into
devfrom
feat/630-pytest-plugin
Nov 4, 2026
Merged

uniqueg merged 6 commits into
devfrom
feat/630-pytest-plugin

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #630.

Helpers for the tests of FOCA apps, in the new package foca.testing:

  • foca.testing.issuer: a context manager and fixture that serves OIDC discovery, a JWKS and optional user info on a local port (stdlib http.server), and signs access tokens with token(sub=, aud=, typ=, groups=, client_id=, expires_in=, **claims). It doesn't depend on a test client or pytest.
  • foca.testing.pytest_plugin, enabled by name: a network guard, the fixture mongodb (mongomock, or a real MongoDB with MONGODB_TEST_URI) and the fixture issuer.
  • foca.security.auth.clear_caches(), which the issuer uses on stopping.
  • The extra foca[testing].
  • Docs: docs/testing.md, the reference, and a Compose snippet with a mock OIDC server pinned by digest.
  • FOCA's own tests enable the plugin, so the guard runs on them too.

tests/testing/test_end_to_end.py is the example test the issue asks for: it runs the example app with access control against the issuer, with audience validation on.

Verification

  • Local: ruff, mypy, mkdocs strict and pytest with 100% coverage; the tests marked mongodb ran against MongoDB 7.0.
  • Reviewers: both rounds ran; round 2 tested the fixture against a real MongoDB 7.0.
  • Not run: the Compose snippet. I looked up the digest of ghcr.io/navikt/mock-oauth2-server:6.1.4 in the registry but didn't start the image, so the docs only tell readers to check its tokens against audience and token_types. MongoClient.bulk_write on MongoDB 8 wasn't tested either.

FOCA's own tests in tests/security/test_auth.py still mock the identity provider's responses: they test failures of single fetches, which the issuer wouldn't make simpler. tests/examples/test_petstore_access_control.py keeps its stub, as its tests use plain user names as tokens throughout.

Declined review findings

  • Module-level _Handler (medium): the class in __init__ is short and needs only the instance; a server subclass for mypy would add more than it removes.
  • Sphinx roles in docstrings (low): as elsewhere in FOCA.
  • Fixture name issuer (low): the issue names it, and conftest.py can override it.
  • Migration guide entry (medium): nothing to migrate; release notes are written at the release.
  • Guard installed for the whole session and patching sendto (medium): it's a safety net against accidents, and its limits are documented.
  • Allowing replica set members that the URI doesn't name (medium): documented, with directConnection=true.
  • Recording $out, renameCollection, mapReduce and MongoClient.bulk_write targets for the clean-up (medium): the docs now name them; tests relying on them drop their own databases.
  • Raising in mongomock after close() (low): documented.
  • Dropping only databases with recorded successful writes (low): narrows a window with a concurrent writer without closing it; the docs ask for a throwaway MongoDB.
  • Shared RSA key for speed (observation): each issuer has its own key, as tests of foreign keys need; wider fixture scopes are documented.

🤖 Generated with Claude Code

Summary by Sourcery

Provide reusable testing infrastructure for validating FOCA authentication and database interactions in production-like test environments.

New Features:

  • Add foca.testing.issuer, a local OIDC identity provider for end-to-end authentication tests with configurable signed tokens and user info.
  • Add a named pytest plugin providing a network guard plus MongoDB and issuer fixtures.

Enhancements:

  • Add cache clearing for authentication provider data between test identity providers.
  • Add the foca[testing] optional dependency and enable the testing plugin in FOCA's own test suite.

Documentation:

  • Document the testing helpers, pytest fixtures, local OIDC usage, and a development Compose setup.

Tests:

  • Add issuer, pytest plugin, cache-clearing, and end-to-end authentication coverage, including audience and access-control validation.

uniqueg and others added 3 commits November 4, 2026 07:23
`foca.testing.issuer` serves OIDC discovery, keys and user info on a
local port and signs access tokens, so that tests of apps validate
tokens as in production. The pytest plugin adds a network guard and a
MongoDB fixture, in memory or with a real MongoDB. Add a page to the
docs, with a mock OIDC server for development.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Compare command names without case, don't count deletes, pass on
`connect`, and say what the clean-up doesn't cover.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces reusable testing infrastructure for FOCA applications: a local production-like OIDC issuer, pytest network and MongoDB isolation fixtures, authentication cache invalidation, comprehensive unit/end-to-end coverage, and supporting documentation and packaging.

Sequence diagram for local OIDC issuer token validation

sequenceDiagram
    participant Test
    participant Issuer
    participant App
    participant Auth

    Test->>Issuer: issuer()
    Issuer-->>Test: Issuer with url
    Test->>Issuer: token(sub, aud, groups)
    Issuer-->>Test: Signed JWT
    Test->>App: Request with Bearer token
    App->>Auth: Validate token
    Auth->>Issuer: GET OIDC discovery
    Issuer-->>Auth: issuer, jwks_uri, userinfo_endpoint
    Auth->>Issuer: GET /jwks
    Issuer-->>Auth: RSA public key
    Auth->>Issuer: GET /userinfo
    Issuer-->>Auth: User claims
    Auth-->>App: Authenticated identity
    App-->>Test: Protected response
Loading

Flow diagram for pytest infrastructure isolation

flowchart TD
    Test[Test case] --> Guard{allow_network marker?}
    Guard -->|No| Network[Install socket network guard]
    Guard -->|Yes| Fixtures[Use test fixtures]
    Network --> Fixtures
    Fixtures --> Mongo[mongodb fixture]
    Fixtures --> Issuer[issuer fixture]
    Mongo -->|No MONGODB_TEST_URI| Mock[mongomock client]
    Mongo -->|MONGODB_TEST_URI set| Real[Real MongoDB client]
    Real --> Cleanup[Drop newly written databases]
    Issuer --> Local[Local OIDC server]
    Local --> Cache["clear_caches() on stop"]
Loading

File-Level Changes

Change Details Files
Add a standalone local OIDC issuer for production-like authentication tests.
  • Serve discovery metadata, JWKS, and configurable userinfo over a threaded local HTTP server.
  • Generate per-issuer RSA keys and signed tokens with configurable identity, audience, type, expiry, groups, client, and custom claims.
  • Clear authentication caches when issuer state changes or the server stops.
foca/testing/__init__.py
foca/testing/issuer.py
foca/security/auth.py
tests/security/test_auth.py
tests/testing/test_issuer.py
Add an opt-in pytest plugin for network isolation and MongoDB-backed test fixtures.
  • Install an autouse network guard that permits local and configured test-database connections, removes proxy settings, and supports an allow-network marker.
  • Provide a per-test mongodb fixture using mongomock or MONGODB_TEST_URI, patch FOCA client creation, and clean up newly written real databases.
  • Provide a per-test issuer fixture wrapping the local OIDC server.
foca/testing/pytest_plugin.py
pyproject.toml
tests/conftest.py
tests/testing/test_pytest_plugin.py
Exercise the new helpers in end-to-end authentication tests and document their use.
  • Enable the plugin for FOCA's test suite and validate audience, token type, expiry, issuer, and access-control behavior against the example app.
  • Document installation, fixtures, issuer APIs, limitations, and a digest-pinned development OIDC Compose service.
  • Expose testing modules in the API reference and add the testing page to navigation.
tests/testing/test_end_to_end.py
docs/testing.md
docs/reference.md
mkdocs.yml

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 Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (39d6787) to head (623a07c).
⚠️ Report is 1 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #679    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           58        60     +2     
  Lines         7592      7790   +198     
==========================================
+ Hits          7592      7790   +198     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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 4, 2026 06:55

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

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

## Individual Comments

### Comment 1
<location path="foca/security/auth.py" line_range="78-84" />
<code_context>
 _userinfo_cache_lock = threading.Lock()


+def clear_caches() -> None:
+    """Forget what was fetched from identity providers, e.g., between tests."""
+    _oidc_configs.clear()
+    _jwk_sets.clear()
+    _failed_fetches.clear()
+    with _userinfo_cache_lock:
+        _userinfo_cache.clear()
+
+
</code_context>
<issue_to_address>
**Stale issuer data survives cache clearing**

When a validation fetch is in flight when `auth.clear_caches()` runs, the in-flight fetch can store its pre-clear response back in the cache. Later validations then use stale keys or claims; if a stopped issuer’s port is reused with the same key ID, valid tokens from the new issuer are rejected, or outdated user-info claims are accepted.

Prevent fetches started before a cache clear from storing their responses afterward.

Also at `foca/testing/issuer.py:84`.
</issue_to_address>

### Comment 2
<location path="foca/testing/pytest_plugin.py" line_range="287" />
<code_context>
+        """Create a client of the in-memory MongoDB."""
+        return mongomock.MongoClient(_store=store)
+
+    monkeypatch.setattr(register_mongodb, "MongoClient", _create_client)
+    yield _create_client()
+
</code_context>
<issue_to_address>
**Restricted database accounts fail setup**

When `MONGODB_TEST_URI` uses an account that can access the test database but lacks the privilege to list databases, `_use_real_mongodb` calls `client.list_database_names()` before yielding the fixture, so setup raises an authorization error and tests cannot use `mongodb`, even when they only need the test database.

Track the fixture’s databases without requiring the account to list all databases.

Also at `docs/testing.md:28`.
</issue_to_address>

### Comment 3
<location path="foca/testing/pytest_plugin.py" line_range="174" />
<code_context>
+    monkeypatch.setattr(socket.socket, "connect_ex", _guarded_connect_ex)
+
+
[email protected](autouse=True)
+def foca_network_guard(
+    request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch
</code_context>
<issue_to_address>
**Module fixtures bypass network guard**

When A broader-scoped fixture makes a network connection during its setup, `foca_network_guard` is function-scoped, so a module-, class-, or package-scoped fixture that connects externally runs before the guard is installed and succeeds unguarded.

Document that all fixtures broader than function scope run outside the guard, or arrange for the guard to cover their setup too.
</issue_to_address>

### Comment 4
<location path="foca/testing/pytest_plugin.py" line_range="96-97" />
<code_context>
+    return address.is_loopback or address.is_unspecified
+
+
+@lru_cache
+def _get_addresses(uri: str) -> frozenset[tuple[str, int]]:
+    """Get the socket addresses of the hosts of a connection string.
+
</code_context>
<issue_to_address>
**Changed database addresses are blocked**

When a hostname in `MONGODB_TEST_URI` resolves to a new address after its URI has been checked, `_get_addresses` returns the indefinitely cached address set, so `_check` rejects MongoDB connections to the new address and tests using the configured database fail.

Refresh resolved addresses rather than caching them indefinitely.
</issue_to_address>

### Comment 5
<location path="foca/testing/issuer.py" line_range="149-150" />
<code_context>
+            **claims: Claims in addition to the subject of the token, replacing
+                those of earlier calls.
+        """
+        self._userinfo = claims
+        self._userinfo_status = status
+        auth.clear_caches()
+
</code_context>
<issue_to_address>
**Responses mix user-info updates**

When `set_userinfo` changes the response while a user-info request is being handled, the handler reads `_userinfo_status` and `_userinfo` separately, so concurrent updates can make it serve a response assembled from different updates; requests can unexpectedly succeed, fail, or return claims from the wrong update.

Update the status and claims together and have handlers read them as one consistent snapshot.

Also at `foca/testing/issuer.py:125`, `foca/testing/issuer.py:139`.
</issue_to_address>

Linked issues

#630 feat(testing): add pytest plugin and test issuer · 6 of 6 met

# Requirement Status Notes
1 Provide an opt-in pytest plugin with a network guard and MongoDB fixture. ✅ Met The plugin is enabled by name in conftest.py, supplies an autouse network guard and mongodb fixture, and is included in the foca[testing] extra.
2 Provide a public, typed issuer context manager and pytest fixture that serves local OIDC endpoints, signs tokens, and supports optional user-info responses. ✅ Met foca.testing.issuer provides the context manager and typed Issuer API; the pytest plugin exposes the issuer fixture.
3 Document and test discovery, JWKS, audience, typ, groups, and user-info behavior. ✅ Met The issuer tests cover discovery, public JWKS, audience and token-type validation, groups, and user-info claims and failures; the API is documented in docs/testing.md and the reference.
4 Add an example test that validates a token end to end without disabling audience validation. ✅ Met tests/testing/test_end_to_end.py exercises the example app using the issuer and its configured audience.
5 Document a local development OIDC server in a Compose snippet pinned by digest. ✅ Met docs/testing.md includes a mock OAuth server image pinned by digest and explains checking its token claims against the app configuration.
6 Achieve 100% test coverage. ✅ Met The coverage configuration sets fail_under to 100, and the PR verification reports running pytest with 100% coverage.

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and with MONGODB_TEST_URI configured, cleanup drops every database recorded as written to during the test if it was absent at the initial database listing. If that URI targets a shared or unintended MongoDB, this can permanently delete a database created during the test; reverting the plugin cannot restore it.

Blocking findings: foca/security/auth.py:84, foca/testing/pytest_plugin.py:287, foca/testing/pytest_plugin.py:174, foca/testing/pytest_plugin.py:97, foca/testing/issuer.py:150


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

Comment thread foca/security/auth.py Resolved
Comment thread foca/testing/pytest_plugin.py Resolved
Comment thread foca/testing/pytest_plugin.py Resolved
Comment thread foca/testing/pytest_plugin.py Resolved
Comment thread foca/testing/issuer.py Resolved
uniqueg and others added 2 commits November 4, 2026 08:09
Handlers now read both together. Say what the network guard leaves out
and which rights the user of a test database needs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 930ce28 into dev Nov 4, 2026
55 of 56 checks passed
@uniqueg
uniqueg deleted the feat/630-pytest-plugin branch November 4, 2026 07:57
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.

feat(testing): add pytest plugin and test issuer

1 participant