Repository navigation
Testing
Home · Installation · Compatibility · Tools Reference · Architecture · Providers · Configuration · Reliability · Security · Testing · Troubleshooting · Project Tracker
swift test| Property | Value |
|---|---|
| Tests | 624 (7 skipped by default: the 6 opt-in live tests, which need SEARCH_LIVE_TESTS and a usable key, and the nesting guard's real-page run, which needs MARKUP_DEPTH_CORPUS) |
| Runtime | seconds; the default suite makes no external network calls |
| External network | not required for the default suite |
| Warnings | none, from a clean build |
The commands above are correct for a normal checkout and are exactly what CI runs on a
clean xcode-27 runner. On a machine where the repository lives inside Dropbox, a plain
swift build can still stall even after the evicted .build state has been cleared:
swift-frontend blocks in pread at 0% CPU while fileproviderd saturates a core.
Building to a scratch path outside the synced folder is the verified workaround:
swift build --build-tests --scratch-path ~/Library/Caches/MCPSearch/scratch
swift build -c release --scratch-path ~/Library/Caches/MCPSearch/scratch
swift test --scratch-path ~/Library/Caches/MCPSearch/scratch
python3 scripts/mcp_smoke.py \
"$(swift build -c release --scratch-path ~/Library/Caches/MCPSearch/scratch --show-bin-path)/SwiftWebSearchMCP".build is marked with the com.dropbox.ignored extended attribute so Dropbox leaves it
alone and there are no dataless files under it. This is a local-environment workaround,
not a repository requirement.
End-to-end tests launch the real executable with a scrubbed environment: PATH plus
their own explicit overrides, with every documented provider variable removed.
Without that scrub, an exported TAVILY_API_KEY — exactly what the installation guide
tells a user to set — would make the stub-provider test contact the live vendor and fail.
This was a real defect, so it is now verified rather than assumed. The same list covers
DEEPSEEK_API_KEY and the other synthesis variables: the test asserting that
web_answer degrades to results_only when unconfigured would otherwise make a live,
billed request on any machine where the developer had exported a key. The suite is run
with fake credentials present to prove it:
TAVILY_API_KEY=tvly-fake BRAVE_SEARCH_API_KEY=brave-fake swift testCI runs the whole suite a second time with credentials present for the same reason.
| File | Covers |
|---|---|
CoreUnitTests |
URL canonicalization, configuration parsing, durations, logging |
FusionAndReliabilityTests |
RRF fusion, deduplication, diversity capping, per-result engine attribution, circuit breaker, rate limiter, cache |
URLPolicyTests |
SSRF: schemes, loopback/private/metadata literals, embedded-IPv4 unwrapping, DNS resolution, IP classification |
HTMLExtractorTests |
Readable-text extraction, boilerplate removal, scraper parsing, challenge detection |
FetchBehaviorTests |
web_open's direct fetch path against a real socket: non-2xx is fetchFailed (not a provider network failure), a missing page keeps its own error, a success yields readable text, and a body already opening with the title is detected |
FetchFallbackTests |
The fetch fallback chain above it: thin native text triggers the Jina Reader, the flag disables it, a blocked URL is never laundered through the reader, and the reader's own 429 / 401 / 403 / empty-body cases (11 tests) |
MarkupDepthTests |
The nesting bound above the parser, plus an opt-in run over real fetched pages (MARKUP_DEPTH_CORPUS=<dir>, skipped by default so the suite stays hermetic) that asserts the model never reads shallower than the parser — it found two bypass-direction defects that the hand-written cases could not. Otherwise: the depth model against the tree SwiftSoup actually builds (MarkupDepthTests asserts equality, not just a lower bound, so the model cannot drift upward into a false rejection), the <div></p> bypass, stray and optional end tags, table structure including nested tables, raw-text elements, and quoted attributes |
HTTPClientTests |
Retry, Retry-After, idempotency, size limits, cancellation, Latin-1 fallback |
HTTPTransportTests |
Drives the built executable on an ephemeral loopback port (7 tests) because HTTPMCPHost is internal to the executable target: /health body, initialize session, tools/list over SSE, missing-session and cross-origin refusals, oversized-body framing, unknown paths |
ProviderContractTests |
Per-adapter contract and the shared failure taxonomy, now applied to every adapter rather than Tavily alone (27 → 51 tests) |
AnswerSynthesizerTests |
Grounding rules, citation validation and renumbering, refusal handling, thinking-mode request shape, credential placement |
SearchOrchestratorTests |
Selection, fan-out, refill, failover, timeouts, caching, domain filtering |
StdioServerTests |
Real MCP handshake, tool schemas, tool calls, stdout purity, protocol-revision negotiation, the web_answer end-to-end path |
SchemaCompatibilityTests |
Every advertised schema against the strictest client rules |
TransportConfigurationTests |
CLI flag parsing, defaults and rejection of bad arguments, the transport-flag conflict |
ErrorReportingTests |
Error attribution, explicit-provider fallback, post-error liveness, curated transport text that never echoes a request URL |
ProbeTests |
NodeProbe (up/degraded/down, engine reporting, unresponsive_engines) and ProviderProbe (success, taxonomy, setup hints, cancellation) — 15 tests |
MonitorTests |
Terminal layout, renderer output, model accumulation, probe-query rotation |
MonitorOptionsTests |
mcps-mon CLI parsing, the probe interval floor and its explicit override |
LiveProviderTests |
Opt-in. Real API calls; skipped unless SEARCH_LIVE_TESTS is set and a usable key exists |
LoopbackServer binds 127.0.0.1 and speaks HTTP/1.1, so retry, Retry-After,
idempotency, size limits and cancellation are verified against real socket behaviour
rather than against a mock that would encode the same assumptions as the client.
Every covered adapter must satisfy the same contract:
| Expectation | Assertion |
|---|---|
| Happy path | Normalized results with valid URLs and ranks |
401 / 403
|
Classified as authentication
|
429 |
Classified as rate_limited, with Retry-After parsed |
5xx |
Classified as transient |
| Malformed body | Clean malformed_response failure, never junk results |
| Cancellation | Stops in-flight work |
| Credentials | Never appear in logs or diagnostics |
Every adapter now runs the shared taxonomy: Tavily, Brave, Mojeek, Exa, SearXNG,
DuckDuckGo, Startpage, Open Web Search and Parallel Search MCP; the Jina Reader fetch
fallback is covered separately in FetchFallbackTests. The only remaining gap is live
coverage: LiveProviderTests still exercises Tavily alone, because it is the only key
available, so the others are verified against stubs and the API notes rather than live.
That gap is a consequence of the missing credentials tracked as T1 on the
Project Tracker, not a separate shortcoming.
CircuitBreaker, RateLimiter and SearchCache take an injectable Clock, so cooldown
and expiry tests advance a TestClock instead of sleeping. Timeout tests use short
budgets rather than real waits. Fusion ordering is fully deterministic, so ranking
assertions are stable.
python3 scripts/mcp_smoke.pyA dependency-free client that drives the built binary through a real handshake and asserts that:
-
initializesucceeds and reports the expected server identity; -
tools/listadvertises the four documented tools with usable object schemas. This is a presence check, not an exact-inventory assertion: the exact set is asserted in Swift byStdioServerTests, andSchemaCompatibilityTestslints every schema. The script prints — but does not fail on — any extra tool, so adding a tool cannot require editing two languages in lockstep. An extra tool is visible in the log.web_answermust expose no model-selection argument; -
web_searchwith no provider configured fails as an actionable tool error; - every line written to stdout is valid JSON-RPC;
- diagnostics appear on stderr, never stdout.
Keeping a second exhaustive tool list in the script is exactly what let a fourth tool ship while it still demanded three, which turned CI red for an otherwise-correct release.
It keeps stdin open until all replies have been read, which is what the stdio transport contract requires.
python3 scripts/monitor_tty_smoke.pyThe dashboard's key handling, colour and cursor control only run when stdin and stdout are a terminal. A pipe is not one, and pressing keys by hand needs a window on somebody's desktop, so neither was usable for testing. A pseudo-terminal is a kernel object with no GUI involved: allocating one opens no window and touches no desktop.
The script allocates a PTY, attaches a live mcps-mon to it in a 120x40 window, types the
keys, and asserts on the frames and escape sequences that come back:
- startup hides the cursor and clears the screen;
- every frame homes the cursor and clears to the end of each line and the screen, so a shorter frame cannot leave the previous one's tail behind;
- colour is on by default and
cturns it off without disturbing the layout; -
ehides the per-node engine breakdown — the column header included — and restores it; -
rrepaints immediately rather than on the next tick; -
pprobes providers now, and a loopback SearXNG stub answers, so the provider turns OK; -
qexits 0, restores the cursor, clears to the end of the screen and prints the final summary.
It is hermetic: the stub is served on loopback and every provider variable is scrubbed from the child, so it needs no key, spends no credits and makes no external request.
Writing it paid for itself:
eused to hide the engine data but leave theenginescolumn header in place, so the table advertised data it was not showing.
python3 scripts/dual_client_contract.py "$(swift build -c release --show-bin-path)"The server and the dashboard read the same SearXNG response with two independent parsers —
SearXNGProvider and NodeProbe — and nothing compared what they reported. They have disagreed
before: NodeProbe did not map unresponsive_engines at all, so the dashboard's unavailable-engine
column was empty against every live instance while the provider mapped the same key explicitly.
No Swift test can see that: each side's tests pass on their own, because the disagreement exists only between them. So both binaries are pointed at one stub and each is asked what it sees — the engines that did not answer and the reasons they gave, the engine that did answer, and an instance that returns nothing, which must read as a failure on both sides and must not be reported as an unavailable engine.
Comparing the two answers to each other alone would pass if both drifted the same way, so each is
compared against the value the stub was told to return. The stub lives in scripts/searxng_stub.py,
shared with harness_tests.py.
Writing it proved it can fail: removing
NodeProbe'sunresponsive_enginesmapping — the historical defect — makes it reporttimed out waiting for 'unavailable:' to be drawnand exit 1.
.github/workflows/ci.yml and .github/workflows/codeql.yml both run on the xcode-27 image
(Swift 6.4) for every push and pull request to main; CodeQL additionally runs on a weekly schedule
and on manual dispatch.
ci.yml has two jobs.
build-and-test:
swift build --build-testsswift testswift build -c release-
python3 scripts/mcp_smoke.py— stdio handshake and stdout purity. It also asserts the server reports the version in the repository'sVERSIONfile, so a binary cannot ship claiming a version it was not built from -
python3 scripts/mcp_smoke.py --http— starts the HTTP transport, waits for/health, drives a full stateful session over SSE, and checks that requests without a session, without SSE inAccept, and from a cross-origin page are refused -
python3 scripts/monitor_tty_smoke.py— drives the interactive dashboard through a pseudo-terminal: keys, colour, cursor control, and that quitting (or an externalSIGINT/SIGTERM) leaves the line discipline canonical and echoing again; it also feeds a SearXNG-shaped instance escape sequences in an engine name and asserts none reach the tty -
python3 scripts/dual_client_contract.py— points both executables at one stub and compares what each reports about it: the engines that failed, the reasons they gave, and the engine that answered -
swift testagain with provider credentials present, proving hermeticity - a coverage floor on
Sources/(80 %) and, before it, a lockfile-drift check
static-analysis: swift-format (--strict), SwiftLint (--strict), ruff check and
ruff format --check, pyright (strict, pinned), shellcheck over deploy/provision-node.sh
and tools/*.sh (the release machinery runs with write access), semgrep, a full-history
gitleaks scan, osv-scanner, the third-party-notice check, scripts/harness_tests.py, and the
version-agreement gate — tools/check-version.sh, which fails when VERSION is malformed, when the
generated BuildVersion.swift does not reproduce from it, when CHANGELOG.md has no heading for the
version, or when a version literal appears anywhere else in Sources/.
harness_tests.py is where the harnesses no Swift test can reach are driven: searxng_health.py
against a loopback instance, soak.py's arguments, dotenv parser and credential scan, the
cross-language scrub-list contract, and the two-executable contract above. It also owns soak.py's
provider-selection and run-verdict assertions, which were inline heredocs in this job — the release
gate runs this module and does not read CI's steps, so while they lived there the release checked
less than CI did.
codeql.yml runs CodeQL over the Swift sources in advanced setup, with a manual build — the
repository's own swift build --build-tests -Xswiftc -warnings-as-errors between init and
analyze — because CodeQL's default setup builds with a Swift 6.3.3 runner image that cannot parse
this manifest at all. Because the Swift extractor builds its database by tracing the build, this job
deliberately has no build cache: a restored .build would make the traced build a no-op and
produce an empty database, which is an analysis that reports nothing because it saw nothing.
The toolchain version is asserted before anything else, because a
swift-tools-version: 6.4 manifest cannot even be parsed by an older Swift; if
swift -version cannot be parsed the step fails rather than skipping its own comparison. Actions are
pinned by commit SHA and the SwiftPM dependency graph is cached in ci.yml, so a run is reproducible
and fits the runner budget. The end-to-end harnesses fail rather than skip when the
server binary is missing, so a green run cannot mean the smoke tests never ran.
GitHub's macOS runners are shared capacity, so a run can queue for fifteen minutes or more, and the
workflow's cancel-in-progress group supersedes an in-flight run when a newer commit arrives. "The
check did not run" is therefore not "the check failed", and a superseded run is not evidence about
the commit in either direction. The jobs are deterministic once they start, which is what the pinned
toolchain, the pinned Action SHAs and the cached dependency graph are for.
The suite synchronises on awaited calls, not on sleeps: when an operation's completion is what a
test waits for, await is the synchronisation and a sleep is a race with the scheduler. A real
clock is used only where a real delay is the subject — a token-bucket refill, a Retry-After
delay, a hanging provider cut off by the search budget — and those waits are bounded either by a
race against a timeout (so an unclamped delay fails instead of hanging the run) or by a lower
bound that proves the delay happened. Upper bounds, where they exist at all, are loose enough to
survive a loaded CI runner and only catch a control that never fires.
Automation is not ceremony here: it found three defects that local builds had hidden.
-
macos-14ships Swift 5.10, which cannot parse the manifest. -
Package.swiftdeclared a resource bundle for a directory git does not track, so a clean checkout failed to build while local builds passed. - A trailing-
deferwarning that only a from-scratch build surfaced.
SEARCH_LIVE_TESTS=1 swift test --filter LiveProviderTestsThese call real APIs, so they are opt-in and skipped by default. They run only when
SEARCH_LIVE_TESTS is set and a usable TAVILY_API_KEY is available, either in the
environment or in a git-ignored config.env at the package root. A key alone is
deliberately not enough: on a machine where one is routinely exported, that would make a
plain swift test spend real credits. testLiveTestsRequireAnExplicitOptIn guards the
rule, and testPlaceholderCredentialsAreNotTreatedAsUsable keeps CI's fake keys inert.
They are written to be frugal with a metered free tier: fast mode, small result
counts, and most assertions made against a single live response. The authentication
path is covered with a deliberately invalid key, which costs no credits. Coverage:
| Test | What it proves | Cost |
|---|---|---|
| Invalid key | A rejected credential is classified as authentication, not transient | free |
| Search | Live results normalize correctly, with scores and sequential ranks | 1 credit |
| Recency | A recency filter returns dated results, so the filter is verifiable | 1 credit |
| Orchestration | Full path with fusion and a cache hit on the repeat query | 1 credit |
| Thorough mode | The advanced-depth mapping reaches the live service | 2 credits |
| Status | A live key reports ready and the payload never contains the key |
free |
This suite exists because it found a defect the stub tests could not: Tavily's
published_date silently decoded to nil, since the DTO maps keys explicitly while the
adapter had been applying .convertFromSnakeCase, which rewrites the key before those
mappings are consulted.
SchemaCompatibilityTests walks every advertised input and output schema, via a real
tools/list over stdio, and fails on any construct a mainstream client rejects: a
missing additionalProperties: false, a property that is not also required, a banned
keyword (format, default, oneOf, allOf, not), an object without properties,
an array without items, a non-object root, or an over-long tool or property name. It
also asserts that defaults are documented in descriptions rather than declared, and that
every required-but-optional property is nullable so a strict client can omit it.
See Compatibility for why each rule exists.
python3 scripts/soak.py --queries 50 --mode balancedRuns a list of realistic coding-agent queries through the real binary and reports per-query outcome, provider participation, failure categories and end-of-run provider health. It exists because quota and rate-limit behaviour only appears over a sustained run: a single-query test cannot show that an anonymous tier allows exactly 20 calls, or that a scraper's throttle turns into one error per query once it is exhausted.
It is opt-in, spends real credits, and is not part of CI. Its findings belong in the provider notes rather than on the tracker, which lists work still to be done.
Live provider behaviour is non-deterministic and free tiers are metered. A scheduled live smoke test on CI is open work, tracked as T5 on the Project Tracker.
Home · Installation · Tools Reference · Architecture · Providers · Configuration · Reliability · Security · Self-Hosting · Monitor · Testing · Troubleshooting · Project Tracker