Repository navigation
feat(testing): add an httpx-style test client - #729
Conversation
Add foca.testing.Client, with the API of httpx and Starlette's TestClient, and foca.testing.request_context, which sets up a request without HTTP, with optional token info. On Connexion 2, both build on Flask's test tooling. The pytest plugin gets the fixture foca_client, for apps that define foca_app. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Werkzeug's cookie jar replaces the Cookie header of requests, so the test client sends requests without a jar, and cookies as headers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Send requests via foca.testing.Client and set up requests via request_context instead of Flask's test client and test request contexts. Tests of WSGI middleware (request IDs, the body-size limit) and of how the accessors read the WSGI environment keep Werkzeug's client and environment builder. A test guards against new uses of Flask's test tooling. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe foca.testing.Client, request_context and the fixture foca_client, add the client to the API reference, and list how tests move from Flask's test tooling in the migration guide. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review findings: - params replace query parameters of the same name in the URL, and None values are sent empty, as in httpx. - JSON bodies are compact UTF-8 without NaN; form fields are encoded by the client, so that another Content-Type doesn't drop them. - Charsets of responses that aren't text encodings fall back to UTF-8. - request_context checks the root path; setting token info keeps other entries of Connexion's context. - The guard against Flask's test tooling in FOCA's tests is an ast-grep rule instead of a parametrized test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Say what the context manager does on Connexion 2, how params merge, how request contexts take query parameters but no body, and define the names in the examples. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review findings: URLs with fragments lost their query parameters, and a parameter given as an empty sequence didn't remove that name from the URL's query string, unlike httpx. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideAPIAdd the public
Expose pytest fixtures for an app supplied by the consuming project and a client of that app.
ImplementationAdd token-info setup for request contexts while preserving other Connexion context entries.
ConfigurationAdd an ast-grep rule and rule tests that prevent Flask test tooling in FOCA's tests.
DocumentationDocument the new client, request contexts, pytest fixture, API reference, and migration from Flask test tooling.
TestsMigrate FOCA's existing tests to the new testing APIs, retaining Werkzeug tooling for WSGI-specific checks.
Add focused coverage for client requests and responses, request contexts, and the pytest fixtures.
Exercise the new client in the end-to-end identity-provider test.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #729 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 72 74 +2
Lines 9166 9325 +159
==========================================
+ Hits 9166 9325 +159
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/testing/client.py" line_range="325" />
<code_context>
+ ValueError: Raised if more than one of `json`, `content` and
+ `data` is given.
+ """
+ bodies = [body for body in (json, content, data) if body is not None]
+ if len(bodies) > 1:
+ raise ValueError("Give only one of json, content and data")
</code_context>
<issue_to_address>
**JSON null becomes an empty request**
When the caller explicitly passes `json=None`, the body filter and `json is not None` check treat explicit `None` as no body, so the request reaches the app without the JSON `null` payload or its content type; endpoints receive an empty request instead of JSON null.
Distinguish an omitted `json` argument from an explicit `None` and serialize the latter as JSON `null`.
Also at `foca/testing/client.py:332`.
</issue_to_address>
### Comment 2
<location path="foca/testing/client.py" line_range="341" />
<code_context>
+ elif content is not None:
+ body = content.encode() if isinstance(content, str) else content
+ elif data is not None:
+ body = urlencode(list(data.items())).encode()
+ media_type = "application/x-www-form-urlencoded"
+ if media_type is not None and not has_type:
</code_context>
<issue_to_address>
**Repeated form values arrive malformed**
When a form field has multiple values, `urlencode(list(data.items()))` encodes each list-valued field as one scalar using its Python list representation instead of emitting repeated form fields, so handlers receive incorrect form data.
Encode the form data with sequence values expanded into repeated fields.
</issue_to_address>
### Comment 3
<location path="foca/testing/client.py" line_range="224" />
<code_context>
+ Raises:
+ json.JSONDecodeError: Raised if the body isn't JSON.
+ """
+ return json_module.loads(self.text)
+
+ def __repr__(self) -> str:
</code_context>
<issue_to_address>
**JSON response strings are corrupted**
When a JSON response declares a charset different from the encoding of its body, `Response.json()` parses `Response.text`, which decodes using the declared charset and replaces undecodable bytes; valid JSON strings therefore reach the caller with altered characters.
Parse the JSON from the response body bytes before applying the declared text charset.
</issue_to_address>
### Comment 4
<location path="foca/testing/client.py" line_range="617" />
<code_context>
+ raise ValueError(f"Root path {root_path!r} doesn't start with '/'")
+ root_path = root_path.rstrip("/")
+ flask_app = Flask(__name__) if app is None else _get_flask_app(app)
+ environ_base = {} if client_address is None else {"REMOTE_ADDR": client_address}
+ with flask_app.test_request_context(
+ _with_params(path, params),
</code_context>
<issue_to_address>
**Unknown client address becomes loopback**
When `request_context` is called with `client_address=None`, `environ_base` omits `REMOTE_ADDR`, so Werkzeug supplies `127.0.0.1` and `current_request().client_address` reports a local address instead of `None`.
Pass an explicit environment value that preserves a `None` client address instead of omitting `REMOTE_ADDR`.
</issue_to_address>
### Comment 5
<location path="foca/testing/client.py" line_range="113" />
<code_context>
+ in its query string, in their place (an empty sequence removes
+ them), and the others follow.
+ """
+ if params is None:
+ return url
+ parts = urlsplit(url)
</code_context>
<issue_to_address>
**URL fragments alter test requests**
When A request URL contains a fragment and `params` is `None`, `_with_params` returns the URL unchanged, leaving the fragment for Werkzeug to treat as part of the request path or query; the test client therefore targets a different route or sends a different query than an HTTP client would.
Strip the fragment from the URL whether or not query parameters are supplied.
</issue_to_address>Linked issues
#635 feat(testing): add an httpx-style test client · 6 of 6 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Provide foca.testing.Client with the requested httpx-style methods, request options, response attributes, context-manager support, and redirect default. | ✅ Met | Client and Response are exported from foca.testing; tests cover request bodies, headers, query parameters, redirects, and response accessors. |
| 2 | Provide foca.testing.request_context for request setup without HTTP, including optional token info. | ✅ Met | The context manager supports the requested request settings and app, and sets token info while preserving other Connexion context entries. |
| 3 | Provide documented pytest fixtures, including foca_client for an app supplied by foca_app. | ✅ Met | The plugin defines both fixtures, and docs/testing.md shows how to define foca_app and use foca_client. |
| 4 | Port FOCA's HTTP-level tests to the client and use request_context for unit tests; guard against renewed Flask test-tooling use. | ✅ Met | The diff migrates the tests and adds the ast-grep guard; a search found no remaining direct test_client(), test_request_context(), or FlaskClient() use in tests. |
| 5 | Make foca.testing public, typed, and documented, including migration guidance for test_client(), app_context(), and test_request_context(). | ✅ Met | The package exports the typed helpers; the API reference, testing guide, and migration guide document them and the transitions from Flask tooling. |
| 6 | Keep coverage at 100% and test the client's API against a real app, including JSON, bytes, headers, query parameters, and redirects. | ✅ Met | tests/testing/test_client.py exercises these behaviors against a Connexion app; the PR description reports 100% coverage in the full suite. |
Sourcery assessment
Approval pending. 5 findings to address first.
Blocking findings: foca/testing/client.py:325, foca/testing/client.py:341, foca/testing/client.py:224, foca/testing/client.py:617, foca/testing/client.py:113
Review findings: form fields with sequences of values are sent as repeated fields, Response.json() parses the bytes of the body as httpx does instead of the text decoded with the declared charset, and URLs lose their fragments also without params. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Adds a test client and request contexts that keep their API on ASGI, and moves FOCA's own tests to them.
foca.testing.Client(app): the API of httpx and Starlette'sTestClient.get,head,options,delete,post,put,patchandrequest.params,headers,json,content,dataandfollow_redirects.status_code,headers(case-insensitive, withgetlist()),content,textandjson().follow_redirects=Falseto Starlette.paramsmerge as in httpx, and JSON is sent compact in UTF-8, without NaN.Cookieheaders.foca.testing.request_context(path, method, headers, token_info, *, app, params, root_path, client_address):test_request_context. Token info is set via the new privatefoca.context._set_token_info, which keeps other entries of Connexion's context.foca_app(apps define it) andfoca_client.test_client()ortest_request_context()left. The new ast-grep ruleflask-test-toolingguardstests/.Client/EnvironBuilderdirectly.docs/testing.md: new sections "Test client" and "Requests without HTTP", thefoca_clientfixture, and the identity-provider example now usesfoca_app/foca_client.docs/migration-0.22.md: new section "Test client", with an "Instead of / Use" table fortest_client(), response attributes,query_string, raw bodies,open(), cookies,test_request_context(), token info andapp_context().docs/reference.md:foca.testing.client.Closes #635
Verification
FOCA, full suite with MongoDB 7.0 on a private port: 4859 passed, 2 skipped, 100% coverage at the head (a2d7312).
ruff, mypy, pre-commit on all files (including semgrep, ast-grep and its rule tests), and
mkdocs build --strict: pass.Downstream, on their
devheads with FOCA from this branch (mongomock):Both changes are additive, so their tests don't use the client yet.
CI: passed (
CI passed) on 89b6642 and a2d7312.Declined review findings
1, 2). WSGI joins them in the environ; there is nothing to fix on Connexion 2.params={}keeps the URL's query. httpx 0.28 drops it, which is an edge case no test relies on. Parameters given as empty sequences do remove their names, as in httpx.127.0.0.1. The tests next to it check a non-default address viarequest_context(client_address=...). The migration guide no longer promises the client's address.QUERY_STRINGviaapp.request_context(EnvironBuilder(...).get_environ()). They test how the WSGI adapter decodes Latin-1 query strings, which only exists on WSGI.foca.testingimports the private_set_token_info. It stays within the package; the accessors are the one place that touches Connexion's context.json=Noneshould send JSONnull. httpx and Starlette treatjson=Noneas no body; sendcontent=b"null"instead. Sourcery's other findings were fixed (repeated form fields, JSON parsed from bytes, fragments) or not reproducible (client_address=None).Open questions
None.
🤖 Generated with Claude Code