Repository navigation
feat(testing): add pytest plugin and test issuer - #679
Conversation
`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]>
Reviewer's GuideIntroduces 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 validationsequenceDiagram
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
Flow diagram for pytest infrastructure isolationflowchart 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"]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
# Conflicts: # docs/reference.md
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
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 (stdlibhttp.server), and signs access tokens withtoken(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 fixturemongodb(mongomock, or a real MongoDB withMONGODB_TEST_URI) and the fixtureissuer.foca.security.auth.clear_caches(), which the issuer uses on stopping.foca[testing].docs/testing.md, the reference, and a Compose snippet with a mock OIDC server pinned by digest.tests/testing/test_end_to_end.pyis the example test the issue asks for: it runs the example app with access control against the issuer, with audience validation on.Verification
mongodbran against MongoDB 7.0.ghcr.io/navikt/mock-oauth2-server:6.1.4in the registry but didn't start the image, so the docs only tell readers to check its tokens againstaudienceandtoken_types.MongoClient.bulk_writeon MongoDB 8 wasn't tested either.FOCA's own tests in
tests/security/test_auth.pystill 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.pykeeps its stub, as its tests use plain user names as tokens throughout.Declined review findings
_Handler(medium): the class in__init__is short and needs only the instance; a server subclass for mypy would add more than it removes.issuer(low): the issue names it, andconftest.pycan override it.sendto(medium): it's a safety net against accidents, and its limits are documented.directConnection=true.$out,renameCollection,mapReduceandMongoClient.bulk_writetargets for the clean-up (medium): the docs now name them; tests relying on them drop their own databases.close()(low): 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:
foca.testing.issuer, a local OIDC identity provider for end-to-end authentication tests with configurable signed tokens and user info.Enhancements:
foca[testing]optional dependency and enable the testing plugin in FOCA's own test suite.Documentation:
Tests: