Skip to content

feat(testing): add an httpx-style test client - #729

Merged
uniqueg merged 8 commits into
devfrom
feat/testing-client
Nov 7, 2026
Merged

uniqueg merged 8 commits into
devfrom
feat/testing-client

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

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's TestClient.
    • Methods: get, head, options, delete, post, put, patch and request.
    • Arguments: params, headers, json, content, data and follow_redirects.
    • Responses have status_code, headers (case-insensitive, with getlist()), content, text and json().
    • The client is a context manager. On Connexion 2 it wraps Flask's test client and has nothing to start.
    • Like httpx, it doesn't follow redirects by default; the ASGI release passes follow_redirects=False to Starlette.
    • params merge as in httpx, and JSON is sent compact in UTF-8, without NaN.
    • Cookies aren't kept between requests, because Werkzeug's cookie jar would replace Cookie headers.
  • foca.testing.request_context(path, method, headers, token_info, *, app, params, root_path, client_address):
    • Sets up a request without HTTP, for unit tests of code that reads the accessors.
    • On Connexion 2 it enters Flask's test_request_context. Token info is set via the new private foca.context._set_token_info, which keeps other entries of Connexion's context.
  • Pytest plugin: new fixtures foca_app (apps define it) and foca_client.
  • FOCA's tests:
    • No test_client() or test_request_context() left. The new ast-grep rule flask-test-tooling guards tests/.
    • Tests of WSGI middleware (request IDs, the body-size limit) and of how the accessors decode raw WSGI query strings use Werkzeug's Client/EnvironBuilder directly.
  • Docs:
    • docs/testing.md: new sections "Test client" and "Requests without HTTP", the foca_client fixture, and the identity-provider example now uses foca_app/foca_client.
    • docs/migration-0.22.md: new section "Test client", with an "Instead of / Use" table for test_client(), response attributes, query_string, raw bodies, open(), cookies, test_request_context(), token info and app_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 dev heads with FOCA from this branch (mongomock):

    Repo Commit Result
    proTES 74b88a6 1690 passed, 11 skipped, 100% coverage
    cloud-registry 31c7b8f 2338 passed, 11 skipped, 100% coverage

    Both changes are additive, so their tests don't use the client yet.

  • CI: passed (CI passed) on 89b6642 and a2d7312.

Declined review findings

  • Repeated request headers arrive joined (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.
  • The logging test asserts the default client address 127.0.0.1. The tests next to it check a non-default address via request_context(client_address=...). The migration guide no longer promises the client's address.
  • Three tests set raw QUERY_STRING via app.request_context(EnvironBuilder(...).get_environ()). They test how the WSGI adapter decodes Latin-1 query strings, which only exists on WSGI.
  • foca.testing imports the private _set_token_info. It stays within the package; the accessors are the one place that touches Connexion's context.
  • Sourcery: json=None should send JSON null. httpx and Starlette treat json=None as no body; send content=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

uniqueg and others added 7 commits November 7, 2026 04:33
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]>
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 7, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Add the public Client, Response, and request_context interfaces and export them from foca.testing.

  • foca/testing/__init__.py L3-14
  • foca/testing/client.py L1-634

Expose pytest fixtures for an app supplied by the consuming project and a client of that app.

  • foca/testing/pytest_plugin.py L339-367 (+3 small edits)

Implementation

Add token-info setup for request contexts while preserving other Connexion context entries.

  • foca/context.py L165, L396-417

Configuration

Add an ast-grep rule and rule tests that prevent Flask test tooling in FOCA's tests.

  • .ast-grep/rule-tests/flask-test-tooling-test.yml L1-10
  • .ast-grep/rules/flask-test-tooling.yml L1-16

Documentation

Document the new client, request contexts, pytest fixture, API reference, and migration from Flask test tooling.

  • docs/migration-0.22.md L150-180
  • docs/reference.md L345-346
  • docs/testing.md L38-55, L61-125, L147-156 (+2 small edits)

Tests

Migrate FOCA's existing tests to the new testing APIs, retaining Werkzeug tooling for WSGI-specific checks.

  • tests/api/test_register_openapi.py L23, L827-830, L882
  • tests/api/test_routes.py L280-284 (+3 small edits)
  • tests/api/test_service_info.py L449-453, L506-509, L578-582 (+8 small edits)
  • tests/api/test_validation.py L421-425, L620-627, L910-918 (+30 small edits)
  • tests/api/test_writing_controllers.py L280-293, L310-315, L320-325 (+10 small edits)
  • tests/errors/test_errors.py L628-632, L790-794, L1099-1102 (+32 small edits)
  • tests/examples/test_gateway.py L45-49, L80-83, L92-95 (+7 small edits)
  • tests/examples/test_petstore_access_control.py L49-58, L78-86, L111-116 (+12 small edits)
  • tests/factories/test_connexion_app.py L86-89 (+27 small edits)
  • tests/plugins/test_plugin_adapter.py L76-80, L106-109, L166-169 (+17 small edits)
  • tests/plugins/test_plugin_api.py L436-441, L476-482 (+5 small edits)
  • tests/security/access_control/callers.py L11 (removed lines), L19, L93-94
  • tests/security/access_control/test_access_control_server.py L13-552 (18 small edits)
  • tests/security/access_control/test_enforcement.py L1485-1489, L1525-1529, L2351-2359 (+72 small edits)
  • tests/security/access_control/test_enforcer_cache.py L51, L1006
  • tests/security/access_control/test_me.py L227-230 (+16 small edits)
  • tests/security/access_control/test_ownership_server.py L16-968 (32 small edits)
  • tests/security/access_control/test_path_helpers.py L41-830 (6 small edits)
  • tests/security/access_control/test_service_clients.py L36, L100
  • tests/security/test_auth.py L31-1489 (4 small edits)
  • tests/security/test_cors.py L9, L27, L37-48
  • tests/security/test_optional_tokens.py L27-464 (10 small edits)
  • tests/test_audit.py L44-577 (9 small edits)
  • tests/test_cli.py L27, L648-650, L670-672
  • tests/test_context.py L428-436, L493-499, L525-529 (+28 small edits)
  • tests/test_foca.py L116-119, L129-132, L146-150 (+5 small edits)
  • tests/test_recipes.py L24, L206
  • tests/utils/test_logging.py L102-106 (+13 small edits)
  • tests/utils/test_logging_context.py L30-551 (9 small edits)
  • tests/utils/test_pagination.py L12-193 (11 small edits)
  • tests/utils/test_urls.py L615-621 (+9 small edits)

Add focused coverage for client requests and responses, request contexts, and the pytest fixtures.

  • tests/testing/test_client.py L1-467

Exercise the new client in the end-to-end identity-provider test.

  • tests/testing/test_end_to_end.py L7-53 (6 small edits)

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

Copy link
Copy Markdown

Codecov Report

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

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     
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 7, 2026 05:46

@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/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


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

Comment thread foca/testing/client.py Resolved
Comment thread foca/testing/client.py Resolved
Comment thread foca/testing/client.py Resolved
Comment thread foca/testing/client.py Resolved
Comment thread foca/testing/client.py Resolved
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]>
@uniqueg
uniqueg merged commit 0b886fc into dev Nov 7, 2026
84 of 108 checks passed
@uniqueg
uniqueg deleted the feat/testing-client branch November 7, 2026 06:15
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 an httpx-style test client

1 participant