Skip to content

feat(plugins): add plugin test kit - #507

Merged
uniqueg merged 172 commits into
devfrom
feat/plugin-test-kit
Oct 25, 2026
Merged

uniqueg merged 172 commits into
devfrom
feat/plugin-test-kit

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

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_forward and run_response run the earlier phases first; executions and runs are kept per thread.

  • Builders: make_principal, make_inbound, make_backend, make_outbound and make_response.

  • FakeHttp: a stand-in for ctx.http.

    • It records calls and returns canned responses or errors, a copy per call.
    • It mirrors the guarded client's checks: schemes, methods, addresses that aren't public, response size and deadlines.
    • It builds URLs as requests does.
  • check_plugin_contract(): raises ContractViolation with all problems it finds:

    • the class and its metadata, and a title;
    • the JSON Schemas of Config and Params;
    • web framework imports (a lint of the plugin's own module);
    • failed hook calls on sample inputs, once and from several threads with one instance.

    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 via pytest_plugins) has the fixtures plugin_contract and fake_plugin_entry_points, and register_fake_plugins(). FOCA's own tests use them.

  • Fake entry points: FakeDistribution, FakeEntryPoint and fake_entry_points move 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 fake ctx.http clients, which code can set and configuration can't. The docs say so.

Closes #492

Verification

Run locally on 61a5470 (with dev merged):

  • ruff check and ruff format --check: pass.
  • mypy: pass.
  • pytest without MongoDB: pass, with 100% coverage of foca/plugins and foca/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.

  • Round 1:
    • FakeHttp didn't mirror the client's guards (86c465b);
    • a rejected sample hid the later phases;
    • response rejections weren't counted;
    • the framework-import lint missed dynamic imports;
    • thread errors were lost (2831280);
    • no contract fixture, though the issue asks for one (3f64f0f);
    • the fakes were re-exported from FOCA's tests (8a53097);
    • the http_client factory wasn't documented (c5fbced).
  • Round 2:
    • later phases ran without the request hook's ctx.state, so plugins that keep state failed (44771f5);
    • FakeHttp built other URLs than requests (None params, a trailing ?, fragments, empty paths);
    • FakeHttp returned the same mutable response on every call (8b92465).

All are fixed, except the one declined below.

Sourcery: 12 findings. 10 are fixed in 61a5470:

  • FakeHttp refuses bodies that aren't JSON and invalid headers, as the real client does;
  • its errors leave out user info, query and fragment of URLs;
  • it checks the deadline again after waiting for other clients;
  • it records copies of the request arguments;
  • json=None and the builders' None payloads mean JSON null (UNSET is the default);
  • clients made by a FakeHttp, and the harness, keep its guard settings;
  • blank titles without a docstring count as missing;
  • failing schema code is a violation (also when plugins are loaded);
  • import_module is found under aliases and with the keyword name.

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_plugin statically; mkdocs build --strict passes 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

uniqueg and others added 30 commits October 25, 2026 00:24
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
#	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]>
uniqueg and others added 22 commits October 25, 2026 20:13
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]>
- 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]>
@sourcery-ai

sourcery-ai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds 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 harness

sequenceDiagram
    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
Loading

Flow diagram for plugin contract validation

flowchart 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])
Loading

File-Level Changes

Change Details Files
Introduces a framework-free plugin testing API that executes plugins through the production engine.
  • Added builders for principals, requests, backends, outbound requests, and responses.
  • Added a thread-aware harness for phase execution, configuration/parameter validation, HTTP injection, execution records, and run provenance.
  • Added a guarded fake HTTP client with canned responses/errors, request recording, deadline and size enforcement, URL normalization, and per-call response copies.
foca/plugins/testing.py
foca/plugins/engine.py
Adds comprehensive automated validation of the plugin contract.
  • Checks plugin class metadata, titles, Config and Params JSON Schemas, source-level web framework imports, and hook outcomes.
  • Runs samples once and concurrently on one plugin instance, preserving request state for later phases and aggregating failures.
  • Reports all discovered issues through ContractViolation, including response rejections and thread failures.
foca/plugins/testing.py
Adds pytest support and reusable fake entry-point infrastructure for plugin and application tests.
  • Added opt-in plugin_contract and fake_plugin_entry_points fixtures plus register_fake_plugins().
  • Moved fake distribution and entry-point implementations into the public test kit.
  • Updated FOCA tests to use the new fixtures and fakes through the production loader path.
foca/plugins/pytest_plugin.py
foca/plugins/testing.py
tests/conftest.py
tests/plugins/fakes.py
tests/plugins/test_plugin_api.py
tests/plugins/test_plugin_loader.py
tests/plugins/test_plugin_routing.py
tests/plugins/test_plugin_runtime.py
Documents the test kit, HTTP client injection, plugin release workflow, and public API.
  • Documented harness usage, builders, fake HTTP behavior, contract checks, pytest fixtures, and fake entry points.
  • Documented plugin publishing, versioning, deprecation, and CI contract checks.
  • Added testing modules to the API reference.
docs/plugins.md
docs/reference.md
Adds extensive tests covering the new test kit and its edge cases.
  • Tested builders, harness phases and state propagation, fake HTTP guards and requests-compatible URLs, copy semantics, contract failures, framework-import linting, concurrency, timeouts, and entry-point fixtures.
tests/plugins/test_plugin_testing.py

Assessment against linked issues

Issue Objective Addressed Explanation
#492 Provide a framework-free plugin testing kit with a real-engine harness, input builders, and a fake HTTP client. ✅
#492 Provide actionable plugin contract checks for metadata, schemas, hook behavior, framework imports, record limits, and concurrency. ❌ The contract checker covers many of these checks, but it does not verify that the plugin's entry point loads, which is an explicit contract requirement in the issue.
#492 Document plugin authoring, registration, testing, and releasing, and provide a pytest fixture for fake entry points that is used by FOCA tests and restores the loader lookup. ✅

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (04e2017) to head (61a5470).

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     
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.

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]>
@uniqueg
uniqueg marked this pull request as ready for review October 25, 2026 22: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 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


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

Comment thread foca/plugins/testing.py Resolved
Comment thread foca/plugins/testing.py Resolved
Comment thread foca/plugins/testing.py Resolved
Comment thread foca/plugins/testing.py Resolved
Comment thread foca/plugins/testing.py Resolved
Comment thread foca/plugins/testing.py Resolved
Comment thread foca/plugins/testing.py Resolved
Comment thread docs/reference.md Resolved
Comment thread foca/plugins/testing.py Resolved
Comment thread foca/plugins/testing.py Resolved
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]>
@uniqueg
uniqueg merged commit 801a618 into dev Oct 25, 2026
30 checks passed
@uniqueg
uniqueg deleted the feat/plugin-test-kit branch October 25, 2026 23:05
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(plugins): add plugin test kit

1 participant