Package-level declarations

Types

Link copied to clipboard
class FakeBudgetStore(initial: BudgetSnapshot = BudgetSnapshot.Empty) : BudgetStore

A scripted BudgetStore for tests, the worked example of the seam. Holds one snapshot (snapshot, preloaded through the constructor), counts calls, records every successful save, injects failures and delays.

Link copied to clipboard
class FakeHttpTransport(timeSource: TimeSource = TimeSource.Monotonic, maxResponseBytes: Long? = null, unmatched: Unmatched = Unmatched.Fail) : HttpTransport

A scripted HttpTransport for tests: stubs of a RequestMatch and a script of Steps, a call log with virtual stamps, and the two transport behaviours it mirrors. It is the worked example of the HttpTransport seam, written to be read: the @OptIn(ExperimentalForInheritanceWebToolsApi::class) on this class is exactly the line a consumer's own implementation needs.

Link copied to clipboard
class Fixture(val status: Int, val headers: HttpHeaders, body: ByteArray)

A recorded or hand-written response: a status, headers and body bytes, read from and written to the .http format.

Link copied to clipboard

A fixture file could not be read or is not a well-formed .http file: thrown by Fixture.parse and FixtureLoader.load. It is an AssertionError, because a malformed fixture is a fault in the test's own input, so it fails the test instead of being swallowed as an operational failure.

Link copied to clipboard
class FixtureLoader(classLoader: ClassLoader = Thread.currentThread().contextClassLoader ?: FixtureLoader::class.java.classLoader, val root: String = "fixtures")

Loads Fixtures from the consumer's own classpath, under a resource directory (root, fixtures by default). A name ending in .http is parsed as a .http file (Fixture.parse); any other name is a body-only fixture: status 200, the whole resource as the body and a Content-Type chosen by the extension (json ->application/json, xml ->application/xml, rss ->application/rss+xml, atom ->application/atom+xml, txt ->text/plain; charset=utf-8, html/htm ->text/html; charset=utf-8, anything else or none ->application/octet-stream; compared ASCII-lower-cased). The fixtures jar ships no fixture file; a consumer marks its .http files -text in its .gitattributes (a pattern over every .http file below a fixtures directory) so a checkout cannot rewrite their line endings.

Link copied to clipboard
class FixtureRecorder(val directory: Path, gate: RecordingGate.Enabled, val redaction: Redaction = Redaction(), val warnAboveBytes: Int = DEFAULT_WARN_ABOVE_BYTES)

Records the responses a live transport returns as .http fixture files, so a later test replays them through FakeHttpTransport (Step.fixture(FixtureLoader().load(...))). wrap decorates any HttpTransport; each successful response (any status) is serialised, redacted, scrubbed and written; a failure is not recorded; the delegate's result is returned untouched.

Link copied to clipboard

A UrlFetcher over a loopback test server (a mockwebserver3.MockWebServer started on 127.0.0.1), for a consumer's Level 3 tests. Each factory builds the matching LoopbackTransports transport and pre-checks with the same policy; the untrusted one relaxes the pre-check for loopback exactly as the transport is relaxed, so every Untrusted rule except the loopback ones is live in both places. An unrelaxed pre-check would refuse every loopback URL, which is why this fixture exists.

Link copied to clipboard

The real OkHttpTransport over a loopback test server (a mockwebserver3.MockWebServer started on 127.0.0.1), for a consumer's Level 3 tests. Each factory takes the whole policy, so its ports, extra ranges and mixed-answer rule are live, and an optional resolver function in place of the system resolver.

Link copied to clipboard

One call a FakeHttpTransport received: the request, when it arrived and whether a stub matched it.

Link copied to clipboard

A BudgetObserver that records every event, the worked example of the seam (the @OptIn on this class is exactly the line a consumer's own implementation needs).

Link copied to clipboard
sealed interface RecordingGate

Whether recording is allowed in this process: the one way to obtain the Enabled a FixtureRecorder needs. evaluate reads the environment: recording is off unless WEBTOOLS_HTTP_RECORD (RECORD_VARIABLE) holds a recognised value, and is refused whenever any of the twelve CI variables (CI_VARIABLES) is present with any value, the empty string included.

Link copied to clipboard
enum class RecordMode : Enum<RecordMode>

How a FixtureRecorder treats a file that already exists.

Link copied to clipboard
class Redaction(keepQueryParams: Set<String> = emptySet(), extraSensitiveQueryParams: Set<String> = emptySet(), secrets: List<String> = emptyList(), val placeholder: String = DEFAULT_PLACEHOLDER)

What a FixtureRecorder hides: sensitive query names (by token, see the recorder's KDoc) less the keepQueryParams, plus the extraSensitiveQueryParams; and caller-supplied secrets, each replaced by placeholder wherever it appears in the whole serialised file (comment and body included) as raw text, as addQueryParameter encodes it and as java.net.URLEncoder encodes it. After the replacement the file is searched again for those forms, their lower-case-hex variants and the full percent-escape of the secret's bytes; a file in which one survives is refused. That search is a backstop over the exact forms, not a decoder of transformed ones: a secret echoed as base64, hashed, truncated, or percent-escaped only in part (e.g. SECRET%2dCANARY for SECRET-CANARY) is neither replaced nor detected.

Link copied to clipboard
fun interface RequestMatch

A predicate over an HttpRequest that selects the requests a FakeHttpTransport stub answers. It is a fun interface, so a consumer writes RequestMatch { it.url.host == "api.example.com" }; the companion holds the common shapes and and combines them.

Link copied to clipboard
class Step

One scripted answer of a FakeHttpTransport stub: after a virtual-time delay, respond with a built response, a Fixture, a response the consumer's lambda builds, or a TransportFailure. A stub's steps run in order and the last repeats.

Link copied to clipboard
sealed interface Unmatched

What a FakeHttpTransport does with a request no stub matches: Fail throws an UnmatchedRequestError (the default, so a stray request fails the test), Respond serves one Step (the opt-in for a lenient fake). Sealed: the fake interprets exactly these two policies, and the closed pair is the contract.

Link copied to clipboard

A FakeHttpTransport under Unmatched.Fail received a request no stub matches. It is an AssertionError, so it is a test failure that no Result or cache loader swallows: through a loader it surfaces as the fatal Error rethrown to each waiter.

Link copied to clipboard
class VirtualClock(scheduler: TestCoroutineScheduler, val startEpochMillis: Long = DEFAULT_START_EPOCH_MILLIS)

One virtual clock for a test: a monotonic timeSource, a wallClock, a coroutine dispatcher and a maintenanceExecutor, all driven by one kotlinx-coroutines-test TestCoroutineScheduler, so that a cache's ticker, a delay and a wall-clock index move together when advanceBy is called. Under runTest, build it with virtualClock so it shares the test's scheduler.

Functions

Link copied to clipboard
fun MockWebServer.enqueue(fixture: Fixture, method: HttpMethod = HttpMethod.Get)

Queues fixture, written by toMockResponse, on this server's default queue dispatcher.

Link copied to clipboard
fun Fixture.toMockResponse(method: HttpMethod = HttpMethod.Get): MockResponse

Writes this fixture as a mockwebserver3.MockResponse that cannot hang or corrupt the exchange. The status line is HTTP/1.1 <status> <reason> with the fixture codec's reason phrase (none for an uncommon status); every header is written as given, in order, except Content-Length and Transfer-Encoding, which the framing decides: a 204 or 205 gets no body and no Content-Length; a 304, or any response to a HEAD, gets no body and keeps the declared length (for HEAD, the body size when none was declared); a fixture carrying Transfer-Encoding is framed as chunked; every other fixture gets its body and Content-Length from the bytes. Content-Length is written after the other headers. A fixture carrying Content-Encoding: gzip must hold encoded bytes: a mismatch fails the exchange fast with an IOException, never hangs.

Link copied to clipboard
fun TestScope.virtualClock(startEpochMillis: Long = VirtualClock.DEFAULT_START_EPOCH_MILLIS): VirtualClock

Builds a VirtualClock on this test's scheduler, so delay in the test body, on the clock's VirtualClock.dispatcher and in the code under test all move with VirtualClock.advanceBy.

Link copied to clipboard
fun MockWebServer.webtoolsUrl(path: String = "/"): Url

An http URL on the address this server is bound to, written as an IP literal, so the loopback relaxation admits it on every operating system and the URL never reaches the resolver. Never hostName or url(): both reverse-resolve an address created without a name. An HTTPS server's URL is built by hand. A server bound to another 127.0.0.0/8 address gets the address exemption but not the port exemption.