Repository navigation
feat(plugins): add plugin test kit - #507
Conversation
Add `foca.plugins`, a framework-neutral engine for gateway plugins: - plain request model (`InboundRequest`, `Backend`, `OutboundRequest`, `BackendResponse`, `Principal`, case-insensitive `Headers`) and an explicit `Context` per hook call; no Flask, Werkzeug or Connexion types, so plugins run unchanged after the move to Connexion 3 - `Plugin` base with `on_request`, `on_route`, `on_forward` and `on_response` hooks, `NotApplicable`, `Rejected` and `PluginError` - allowlisted loading of entry points (group `foca.plugins`) with distribution and version pins, `RECORD` digests, `enabled: false` kill switch and a startup error with a migration hint for legacy `middlewares` keys - steps with ordered alternatives, copy-and-commit per alternative, failure semantics, timeouts via a bounded thread pool, forwarding attempts with "not accepted" / "outcome unknown" outcomes, a total `forward_timeout`, `Via` headers, loop detection (508) and no routing to the gateway's own public URL - `foca.plugins.adapter`, the only module using Connexion 2 / Flask - config section `plugins`, docs pages, and an ast-grep rule that keeps framework imports out of `foca/plugins` except the adapter Co-Authored-By: Claude Opus 5.5 <[email protected]>
What proTES needs to adopt the engine: - `Foca(gateway=GatewayApp(api, validate, sanitize, validate_outbound))` declares a gateway app; `create_app()` loads its plugins once to fail fast, and `foca.plugins.runtime.get_host()` gives controllers and Celery tasks the host of their process, created on first use after forks (no Flask app context needed) - legacy `middlewares` keys are refused before the app's strict `custom` model is validated - errors of the app's `sanitize` (e.g. 413) stop the request unchanged; `validate` failures stay invalid output - `validate_outbound` per attempt (reason `invalid_outbound`) - `NotAccepted`/`OutcomeUnknown` exceptions with reason codes for the app's client, and `Attempt.report()` - adapter: `request_id()` from a safe `X-Request-ID` or a new one; `Principal.groups` are the mapped roles of access control - string short form of steps (`- <plugin id>`) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Let clients choose the pipeline and the backends of a request in two
reserved tags, under the configurable prefix `plugins.tags.prefix`
(default `gateway.`):
- `gateway.pipeline`: a preset name (`plugins.presets`) or a pipeline
as JSON, validated and authorized before any plugin runs (limits,
roles, `client_selectable`, uniform "plugin not available" errors)
and framed by `client_pipelines.prepend`/`append` (`if_missing_phase`
for a default route step)
- `gateway.backends`: `{"type": "order" | "allow" | "forbid",
"backends": [...]}`, applied to the routed candidates; items that are
no candidates are discarded and recorded
- any other client tag under the prefix is refused with 400
Presets and frames are resolved on startup; presets that need a
disabled plugin are unavailable. Gateway errors move to
`foca.plugins.errors`. `foca.utils.urls` imports Flask only in
`get_public_url()`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`run.provenance()` describes a pipeline run as plain JSON data for the app to store with its resource: - prospective: pipeline source, preset, the client's tag by reference, the resolved pipeline and its `sha256:` hash of the RFC 8785 canonical JSON (own implementation, tested with the RFC's vectors) - retrospective: hook calls with build keys, outcomes, timings, sanitized errors, annotations and changes as hashes and JSON Pointers without values (`plugins.provenance.detail: paths`); route candidates, the client's backend selection, attempts and the final reason - engine: FOCA, plugin API and app versions (`GatewayApp(name, version)`) `ProvenanceStore` takes collections of the app: plugin builds (with an optional image digest from `FOCA_IMAGE_DIGEST`) and default or preset pipelines are stored once by hash; client pipelines stay inline. Failed runs are stored only with `plugins.provenance.record_failed` (default off), with documented TTL index specs. Hook records keep changes instead of the data before and after. The engine's usage example now catches `OutcomeUnknown` before its base class. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.utils.http` sends requests to URLs from users and registries without becoming an SSRF vector, on requests/urllib3 only: - `GuardedClient` checks the peer address of each new connection after connecting and before sending (so DNS rebinding cannot reach internal hosts), never follows redirects, ignores proxies and `.netrc` of the environment, allows `https` only and always verifies TLS, bounds requests by a deadline (connect timeout capped at 10 s) and response bodies by size, and returns a plain `HttpResponse` - errors carry reason codes and tell requests that certainly did not reach the server (`RequestNotSent`) from those that may have (`RequestMaybeSent`), for gateway outcomes - `is_public_address()`, `check_public_host()` and `fetch_json()`, moved from proTES Plugins get a client bound to their deadline as `ctx.http`, configured by `plugins.defaults.http`. The framework-import rule covers the client. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.plugins.backends` gives gateway apps one ordered list of typed backend entries, under a key of their own (proTES: `custom.tes.backends`), replacing configured lists plus one registry: - `ga4gh-tes` entries (`url`, `url_schemes` default `["https"]`, `id`, `auth`, `basic` env var names, `labels`, `location`) and `ga4gh-service-registry` entries (`https` only, refresh interval, timeout, version prefixes, environments, `auth` and labels for the discovered backends, `allow_private_addresses`); unique ids, normalized URLs without user info - registry discovery moved from proTES and made generic by API type: verified services only, type/version/environment filters, `https`, public hosts, no redirects, no token; cache per entry and process with last-good fallback, retries after 30 s at most, fork-safe locks - `BackendList.expand()`: candidates in entry order, de-duplicated by URL at the first position with configured settings winning, the gateway's own public URL and everything below it left out - `entry_for()`, `find(url, refresh=True)` (rate-limited registry re-read, for other processes), `snapshots()` and `describe()` Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.routing.ordered` (`foca.plugins.routing.OrderedRouter`) is the least surprising route step: it keeps the order of the backend list and shuffles the backends of each service registry among themselves (`random.SystemRandom`), with no round-robin state. Optional params: `labels` (keep only candidates with them) and `seed` (tests only, refused unless the admin setting `allow_seed` is on). - FOCA registers it as an entry point; built-ins (`foca.*`, a reserved prefix) are available without a `plugins.available` entry, which may only set `enabled`, `roles`, `client_selectable` and `config`; other distributions must not provide them, and they load from their object reference if FOCA's metadata lacks the entry point - it is the default pipeline, and the default `client_pipelines.append` step for pipelines without a route step (`on_failure: skip`) - `Plugin.check_params()` lets plugins refuse params when pipelines are resolved - `run.route(candidates, snapshots=...)` records the registry read times in the provenance Refs #491 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.plugins.tags` gives gateways a spec-compliant record of where a task or run went, as string tags under `plugins.tags.prefix`: - `creation_tags(run, provenance_path)`: `pipeline_hash`, `pipeline_source` (`default`, `preset:<name>`, `client`), `plugins` (`id@version` of the plugins that ran) and `provenance` - `routing_tags(run)`: `backend`, `backend_task_id`, `forwarded_at`, `attempts`, `route` (compact JSON of the last `max_route_entries` attempts, new setting, default 10) and `route_truncated` - limits: values at most 1 KiB, `route` at most 4 KiB with the earliest attempts dropped first; URLs without user info, query or fragment; reason codes only - `strip_for_forwarding(tags, prefix)` removes every key under the prefix, also the client's choices, from relayed requests Refs #494 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes: - outbound `Via` headers are the inbound request's with this gateway's entry appended (RFC 9110, section 7.6.3), whatever plugins or the app's builder set, so that loops through several gateways are detected (A -> B -> A) - each call gets its own deep copy of the step's parameters, and the caller's claims as a read-only deep copy, so that a hook cannot change them for later calls, requests or provenance - hooks raising `SystemExit` and other `BaseException`s fail like others; `KeyboardInterrupt` and `GeneratorExit` propagate Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.security.access_control.get_current_claims()` returns a copy of the claims of the current request's token, next to `get_current_subject()` and `get_current_groups()`; the plugin adapter uses it instead of a private helper. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apps that configure `plugins` without `Foca(gateway=...)` get a startup warning, as the section is validated but not used. The docs say that there is no runtime API for operators, summarize the steps for gateway app authors, and note that plugins are instantiated once more per process after the startup check. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.plugins.engine` keeps the host, runs and attempts; the rest moves along its seams, with the public imports from `foca.plugins` and `foca.plugins.engine` unchanged: - `errors`: gateway errors with problem details - `outcomes`: `NotAccepted`, `OutcomeUnknown`, `sanitize_error()` and the engine's internal errors - `records`: resolved pipelines, hook call and attempt records - `executor`: the bounded thread pool of hook calls - `checks`: outbound requests, `Via` names and hook output checks Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes of #486; the engine split is redone on this branch's engine module. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes of #486; the engine split is redone on this branch's engine module. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes and engine split of #486. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes and engine split of #486. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes and engine split of #486. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes and engine split of #486. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the second review round of the plugin engine: - Claims of the caller are a FrozenMapping, which plugins can keep in their state: unlike MappingProxyType, it can be deep-copied and pickled. The engine copies state and candidates inside the guarded block, so a failing copy fails that alternative only, not the request. - The engine sets Via before the app's outbound check; inbound Via headers longer than 1024 characters are refused (400, InvalidVia). Docs say that the inbound Via is passed through verbatim. - The default gateway_id is the host and port of the public URL, without user information, and only if it matches the gateway_id pattern. - setup() of plugins may run more than once per process (docstring and author docs); tests import internals from their new modules. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # foca/plugins/__init__.py # foca/plugins/engine.py
# Conflicts: # foca/plugins/engine.py
# Conflicts: # foca/plugins/engine.py # tests/plugins/test_plugin_engine.py
CodeQL flagged reflected XSS in a view that only exists for its URL rule. Return a constant instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Python 3.14 parses unbalanced deep arrays without RecursionError, so the ValueError branch of HttpResponse.json was not covered in CI. The test now also forces the RecursionError. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Error messages name URLs without user info, query and fragment, with control characters escaped (_redact). - Guards track connections, not sockets: a connection belongs to the request that uses it, so a late timer of an earlier request no longer stops it, and one that such a timer stopped is closed before reuse. Timers shut down the current socket of a connection, so TLS sockets that wrap the new one are stopped too. - Sessions keep no cookies, and are created once under a lock. - Docs: cookies, redacted messages, and why network-specific NAT64 prefixes are not checked. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
CodeQL flags host substring checks in tests; compare the whole message instead (with an escape character, since urlsplit drops line breaks itself). Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The retry interval is the difference of two monotonic floats, which is not exact (29.999... in CI). Refs #493 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Services whose verified API version differs from the offered one are not used. - Next reads and staleness count from the end of a registry read. - Threads wait for a running read if the cache expires meanwhile. - The own-URL check compares effective ports; default ports of http and https still count as the same. - expand(snapshots=...) records the read that the candidates of each registry come from; URLs and read time are published together. - Registry timeouts are finite; backend entries must be ordered. Refs #493 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refs #491 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Only InvalidParams from check_params means invalid params (400); validation errors, SystemExit and other errors of the hook are plugin errors. - Other distributions must not claim built-ins, even disabled ones. - test_no_groups routes configured backends only, in exact order. Refs #491 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Lone surrogates no longer break tag values (replaced by ?), and URLs with invalid ports no longer break routing tags (provenance helper). - Provenance paths and backend task ids that do not fit are left out rather than cut, so they never point elsewhere. - The latest attempt stays in the route even if it alone is too large (its URL is cut, route_truncated is set). - gateway.plugins lists the plugins that ran in the request phase, whatever their outcome; the docs say so. Refs #494 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address Sourcery's review of the plugin listing: - Callers without any choice (no inline pipelines and no usable preset) get no steps of the default pipeline, prepend or append, as step identifiers default to plugin identifiers; allowed_for_caller now says whether selection accepts any choice. - service_info_fields() no longer creates the plugin host: before the host is in use, it reads the plugin classes without instantiating them (runtime.current_host(), runtime.plugin_classes() and loader.find_plugin_classes()), so no plugin is set up before workers fork. - check_plugin_class() refuses titles and descriptions that are no strings, and data_transfers that are no list of strings. - The Plugin schema marks all fields that are always returned as required. Refs #489 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The service info test from the listing PR registers the fake plugins with the test kit's fake_plugin_entry_points fixture, as the other tests on this branch do. Refs #492 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideAdds a production-engine-backed, framework-free plugin test kit with builders, a guarded fake HTTP client, contract and concurrency validation, pytest fixtures, fake entry points, documentation, and comprehensive test coverage. Sequence diagram for running a plugin through the test harnesssequenceDiagram
participant Test
participant Harness as PluginHarness
participant Host as PluginHost
participant Run as PipelineRun
participant Plugin
participant Http as FakeHttp
Test->>Harness: run_response(response, inbound, backend)
Harness->>Host: start(inbound, principal)
Host-->>Harness: PipelineRun
Harness->>Run: request()
Run->>Plugin: request(ctx, inbound)
Plugin->>Http: request(method, url, params)
Http-->>Plugin: canned HttpResponse
Plugin-->>Run: updated inbound
Harness->>Run: attempts(backends)
Run->>Plugin: forward(ctx, outbound)
Plugin-->>Run: updated outbound
Run->>Plugin: response(ctx, response)
Plugin-->>Run: updated response
Run-->>Harness: BackendResponse
Harness-->>Test: response output and executions
Flow diagram for plugin contract validationflowchart TD
Start([check_plugin_contract]) --> Class[Validate class and metadata]
Class --> Schema[Validate Config and Params JSON Schemas]
Schema --> Imports[Lint plugin module framework imports]
Imports --> Harness[Create PluginHarness]
Harness --> Once[Run hooks once through the real engine]
Once --> Threads[Run hooks concurrently with one plugin instance]
Threads --> Collect[Collect all failed outcomes and exceptions]
Collect --> Result{Problems found?}
Result -->|Yes| Violation[Raise ContractViolation]
Result -->|No| Pass([Contract passes])
File-Level Changes
Assessment against linked issues
Possibly linked issues
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 #507 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 53 55 +2
Lines 6057 6408 +351
==========================================
+ Hits 6057 6408 +351
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:
|
The lowest supported dependencies accept a host with a space, so the FakeHttp test of invalid URLs uses a URL without host, which requests refuses in all supported versions. Refs #492 Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 12 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/plugins/testing.py" line_range="410" />
<code_context>
+ ResponseTooLarge: The canned body exceeds `max_response_size`.
+ Exception: The canned error.
+ """
+ scheme, host, _ = _split(url)
+ if scheme not in (("https", "http") if self.allow_http else ("https",)):
+ raise InvalidRequestURL(f"Scheme not allowed: {scheme or '(none)'}")
</code_context>
<issue_to_address>
**Invalid requests pass tests**
When a plugin sends a non-JSON body or invalid header, `FakeHttp.request()` skips the JSON-body and header validation performed by `GuardedClient.request()`, so it returns a canned response where the real client raises `InvalidRequest`; plugin tests pass for requests that fail in production.
Apply the same JSON-body and header validation in `FakeHttp.request()` as in `GuardedClient.request()`.
Also at `foca/plugins/testing.py:375-396`.
</issue_to_address>
### Comment 2
<location path="foca/plugins/testing.py" line_range="1073" />
<code_context>
+ with lock:
+ found.extend(problems)
+
+ workers = [threading.Thread(target=work) for _ in range(threads)]
+ for worker in workers:
+ worker.start()
</code_context>
<issue_to_address>
**Timed-out checks hang at exit**
When a plugin hook blocks indefinitely during `check_plugin_contract()`, `_check_threads()` reports its timeout while the hook remains blocked in a `ThreadPoolExecutor` worker; `harness.close()` does not wait for or stop that worker, and Python waits for executor workers at interpreter exit, leaving the test process stuck.
Ensure a timed-out hook cannot leave a worker that blocks interpreter shutdown.
Also at `foca/plugins/testing.py:1081`.
</issue_to_address>
### Comment 3
<location path="foca/plugins/testing.py" line_range="422" />
<code_context>
+ address = None # host names are not resolved
+ if address is not None and not is_public_address(address):
+ raise AddressNotAllowed(
+ f"Host of {url} has an address that is not public: {host}"
+ )
+ remaining = self.remaining()
</code_context>
<issue_to_address>
**Fake HTTP errors expose URL secrets**
When a plugin test sends a URL containing a secret query parameter and `FakeHttp` raises one of these errors, `FakeHttp.request` includes the complete URL in these errors, and the engine logs hook failures through `describe_error`, which removes user info but leaves query strings intact. A plugin test that sends a secret in a URL query therefore exposes it in test logs when one of these errors is raised.
Redact URLs before including them in `FakeHttp` error messages, using the same URL redaction policy as `GuardedClient`.
Also at `foca/plugins/testing.py:426`, `foca/plugins/testing.py:439`, `foca/plugins/testing.py:445`.
</issue_to_address>
### Comment 4
<location path="foca/plugins/testing.py" line_range="424-432" />
<code_context>
+ raise AddressNotAllowed(
+ f"Host of {url} has an address that is not public: {host}"
+ )
+ remaining = self.remaining()
+ if remaining <= 0:
+ raise DeadlineExceeded(f"No time left for {url}")
+ try:
+ url = _prepared_url(method, url, params)
+ except requests.RequestException as exc:
+ raise InvalidRequestURL(f"Invalid URL: {exc}") from exc
+ with self._state.lock:
+ self._state.calls.append(
+ HttpCall(method.upper(), url, params, headers, json, data, remaining)
+ )
</code_context>
<issue_to_address>
**Fake requests outlive deadlines**
When concurrent callers contend for `_state.lock` long enough to pass the request deadline, `FakeHttp.request()` checks `remaining()` before waiting on the shared state lock but does not recheck it before returning the canned response, so lock contention that crosses the deadline makes tests observe success where the real client times out.
Recheck the deadline after acquiring the state lock and before returning a canned response.
</issue_to_address>
### Comment 5
<location path="foca/plugins/testing.py" line_range="362" />
<code_context>
+ if error is not None:
+ result = error
+ else:
+ body = content if json is None else dumps(json).encode()
+ result = HttpResponse(
+ status=status,
</code_context>
<issue_to_address>
**JSON null responses have empty bodies**
When a canned HTTP response needs to return JSON null, `FakeHttp.add()` treats `json=None` as if no JSON body was supplied and stores the default empty content, so callers’ `.json()` calls fail instead of decoding `null`.
Distinguish omitted JSON from explicit `None` and serialize explicit `None` as JSON null.
</issue_to_address>
### Comment 6
<location path="foca/plugins/testing.py" line_range="328" />
<code_context>
+ Returns:
+ Client.
+ """
+ return FakeHttp(_state=self._state, **kwargs)
+
+ def add(
</code_context>
<issue_to_address>
**Harness drops fake client options**
When a harness is given a `FakeHttp` configured with non-default guards, `PluginHarness` uses the supplied `FakeHttp` as a client factory, but `FakeHttp.client()` builds each child from only the factory arguments and discards the original client's options; for example, `http=FakeHttp(allow_http=True)` still produces clients that reject HTTP URLs unless the caller repeats that setting in `defaults` or on each child.
Preserve the base client's guard settings for child clients unless the factory arguments explicitly override them, or make the required configuration through `defaults` explicit in the harness API.
</issue_to_address>
### Comment 7
<location path="foca/plugins/testing.py" line_range="916" />
<code_context>
+ check_plugin_class(plugin, plugin_id=plugin_id, api=api)
+ except ValueError as exc:
+ raise ContractViolation(reference, [str(exc)]) from exc
+ if plugin.title is None and not (plugin.__doc__ or "").strip():
+ problems.append("No title: add a docstring or set `title`")
+ for name in ("Config", "Params"):
</code_context>
<issue_to_address>
**Empty titles pass contract checks**
When a plugin sets `title` to an empty string and has no docstring, `plugin.title == ""` makes this condition false even when the class has no docstring, so `check_plugin_contract()` accepts a plugin with no usable title and reports the contract as passing.
Treat blank or whitespace-only titles as missing, unless a nonblank docstring supplies the title.
</issue_to_address>
### Comment 8
<location path="foca/plugins/testing.py" line_range="844-858" />
<code_context>
+ as an attribute, e.g., `importlib.import_module()`) whose first
+ argument is a string literal.
+ """
+ if not isinstance(node, ast.Call) or not node.args:
+ return False
+ func = node.func
+ name = (
+ func.id
+ if isinstance(func, ast.Name)
+ else func.attr
+ if isinstance(func, ast.Attribute)
+ else None
+ )
+ first = node.args[0]
+ return (
+ name in ("__import__", "import_module")
+ and isinstance(first, ast.Constant)
+ and isinstance(first.value, str)
+ )
+
</code_context>
<issue_to_address>
**Framework imports evade checks**
When a plugin uses a literal framework name with a keyword argument or an aliased `import_module`, `_is_dynamic_import()` only recognizes a positional string argument and the syntactic function name, while `framework_imports()` only reads `node.args[0]`; these imports pass the contract check and a forbidden framework import goes undetected.
Recognize keyword arguments and imported aliases when detecting dynamic framework imports.
</issue_to_address>
### Comment 9
<location path="foca/plugins/testing.py" line_range="914-915" />
<code_context>
+ problems: list[str] = []
+ try:
+ check_plugin_class(plugin, plugin_id=plugin_id, api=api)
+ except ValueError as exc:
+ raise ContractViolation(reference, [str(exc)]) from exc
+ if plugin.title is None and not (plugin.__doc__ or "").strip():
+ problems.append("No title: add a docstring or set `title`")
</code_context>
<issue_to_address>
**Schema errors escape contract check**
When a plugin's `Params.model_json_schema()` implementation raises an exception other than `PydanticUserError`, `check_plugin_contract()` converts only `ValueError` from `check_plugin_class()` into `ContractViolation`. If a plugin's custom schema-generation code raises another exception, such as `RuntimeError`, the exception escapes directly, so callers do not receive the documented contract error.
Convert schema-generation exceptions from `check_plugin_class()` into `ContractViolation` in `check_plugin_contract()`.
</issue_to_address>
### Comment 10
<location path="docs/reference.md" line_range="194" />
<code_context>
+::: foca.plugins.testing
+
+::: foca.plugins.pytest_plugin
+
## Errors
</code_context>
<issue_to_address>
**Docs extra cannot build the reference**
When the documentation is built in an environment installed with only the `docs` extra, the new API-reference directive imports `foca.plugins.pytest_plugin`, which imports `pytest`, but the `docs` extra does not install pytest. A docs-only installation therefore fails when MkDocs renders this reference.
Add pytest to the docs extra or avoid importing the pytest-dependent module while rendering the API reference.
Also at `foca/plugins/pytest_plugin.py:22`.
</issue_to_address>
### Comment 11
<location path="foca/plugins/testing.py" line_range="132" />
<code_context>
+ Returns:
+ Inbound request.
+ """
+ if payload is None:
+ payload = {"executors": [{"image": "alpine", "command": ["true"]}]}
+ return InboundRequest(
</code_context>
<issue_to_address>
**Builders cannot create null payloads**
When a test needs an inbound, backend, or client payload whose value is JSON null, `make_inbound` and `make_response` treat explicit `None` as omission, substituting a default task or `{"id": "remote-1"}`; `make_response` also substitutes the backend payload for an explicit null `client_payload`. Tests cannot use these builders to exercise plugins with legitimate null bodies.
Use a private sentinel for omitted arguments so callers can pass `None` as an actual payload.
Also at `foca/plugins/testing.py:219`, `foca/plugins/testing.py:226`.
</issue_to_address>
### Comment 12
<location path="foca/plugins/testing.py" line_range="433" />
<code_context>
+ raise InvalidRequestURL(f"Invalid URL: {exc}") from exc
+ with self._state.lock:
+ self._state.calls.append(
+ HttpCall(method.upper(), url, params, headers, json, data, remaining)
+ )
+ queue = self._state.responses.get((method.upper(), url))
</code_context>
<issue_to_address>
**Recorded requests change after sending**
When a caller mutates a request argument after `FakeHttp.request()` returns, `HttpCall` retains the caller’s mutable `params`, `headers`, `json`, and `data` objects by reference, so later mutations change what `FakeHttp.calls` reports and tests observe values that were not present at call time.
Copy the request arguments when recording each `HttpCall`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 12 findings to address first, and the new http_client hook lets a caller replace the guarded client used for plugin requests; a less restrictive replacement could permit requests the default client blocks, potentially exposing data outside the service. Reverting restores the default for future calls, but cannot undo requests or disclosures that already happened.
Blocking findings: foca/plugins/testing.py:410, foca/plugins/testing.py:1073, foca/plugins/testing.py:422, foca/plugins/testing.py:432, foca/plugins/testing.py:362, and 7 more
Address Sourcery's review of the plugin test kit: - FakeHttp refuses bodies that are no JSON and invalid headers, as GuardedClient does; its errors leave out user info, query and fragment of URLs; it checks the deadline again after waiting for other clients; and it records copies of the request arguments. - FakeHttp.add(json=None) returns JSON null, and the builders take None as a payload (UNSET is the default). - Clients made by a FakeHttp keep its guard settings, and the harness applies them via plugins.defaults.http unless defaults set it. - The contract check treats blank titles without docstring as missing, reports failing schema code as a violation (also when plugins are loaded), and finds import_module() under aliases and with the keyword name. Refs #492 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Adds
foca.plugins.testing, a framework-free test kit for plugin authors and apps. This is the ninth and last PR of the v0.18.0 plugin stack (#485).PluginHarness: runs one plugin through the real engine (one step, with config and params).run_request,run_route,run_forwardandrun_responserun the earlier phases first; executions and runs are kept per thread.Builders:
make_principal,make_inbound,make_backend,make_outboundandmake_response.FakeHttp: a stand-in forctx.http.requestsdoes.check_plugin_contract(): raisesContractViolationwith all problems it finds:ConfigandParams;Later phases run after the plugin's request hook, so that they get its
ctx.state, and without it if the hook rejected the sample.pytest helpers:
foca.plugins.pytest_plugin(opt-in viapytest_plugins) has the fixturesplugin_contractandfake_plugin_entry_points, andregister_fake_plugins(). FOCA's own tests use them.Fake entry points:
FakeDistribution,FakeEntryPointandfake_entry_pointsmove from FOCA's tests into the kit.Docs: testing and releasing plugins, and the API reference.
PluginHost(http_client=...)is a deliberate injection point for fakectx.httpclients, which code can set and configuration can't. The docs say so.Closes #492
Verification
Run locally on 61a5470 (with dev merged):
ruff checkandruff format --check: pass.mypy: pass.pytestwithout MongoDB: pass, with 100% coverage offoca/pluginsandfoca/utils/http.py.mkdocs build --strict: pass.pre-commit: pass.The MongoDB tests and semgrep did not run locally (CI runs them). CI on 61a5470: 28 checks pass, and 2 are skipped as intended (an earlier run failed with the lowest dependencies, which accept a host with a space; fixed in 446392e).
Review: two rounds of adversarial and quality review.
FakeHttpdidn't mirror the client's guards (86c465b);http_clientfactory wasn't documented (c5fbced).ctx.state, so plugins that keep state failed (44771f5);FakeHttpbuilt other URLs thanrequests(None params, a trailing?, fragments, empty paths);FakeHttpreturned the same mutable response on every call (8b92465).All are fixed, except the one declined below.
Sourcery: 12 findings. 10 are fixed in 61a5470:
FakeHttprefuses bodies that aren't JSON and invalid headers, as the real client does;json=Noneand the builders'Nonepayloads mean JSON null (UNSETis the default);FakeHttp, and the harness, keep its guard settings;import_moduleis found under aliases and with the keywordname.2 are declined (see below).
Declined review findings
Sourcery: hung hooks block the interpreter exit: declined. The engine's pool can't stop a blocked thread (as in production). The check reports the hang, and making the workers daemon threads would change the engine's shutdown behaviour, which is out of scope here.
Sourcery: the docs extra lacks pytest: declined. mkdocstrings reads
foca.plugins.pytest_pluginstatically;mkdocs build --strictpasses with pytest blocked.Releasing-plugins docs are out of scope (round 1, Q2): declined, because issue feat(plugins): add plugin test kit #492 asks for docs on writing, registering, testing and releasing plugins.
Commit hygiene (merge commits from the stack): declined, because the PR is squash-merged.
🤖 Generated with Claude Code