NetworkMock Core
The devview-networkmock-core module is the shared engine for network mocking. It owns OpenAPI spec parsing, request matching, response variant discovery, and DataStore state persistence. Both devview-networkmock (UI) and devview-networkmock-ktor (Ktor plugin) depend on it — it exists specifically to let those two modules share state without depending on each other.
OpenAPI Spec Format
Configuration is one OpenAPI 3.x document (JSON, or YAML on a best-effort basis) per API group — one spec file = one group, placed anywhere under composeResources/files/networkmocks/, e.g. composeResources/files/networkmocks/specs/my-backend.json:
{
"info": { "title": "My Backend" },
"servers": [
{ "url": "https://staging.api.example.com" },
{ "url": "https://api.example.com" }
],
"x-devview": { "delayMs": 200 },
"paths": {
"/v1/users/{userId}": {
"get": {
"operationId": "getUser",
"summary": "Get User",
"responses": {
"200": {
"content": {
"application/json": {
"examples": {
"default": { "externalValue": "responses/getUser/getUser-200.json" }
}
}
}
}
}
}
},
"/v2/users/{userId}": {
"get": {
"operationId": "getUserV2",
"x-devview": { "delayMs": 500 },
"responses": { "...": "..." }
}
}
}
}
Key concepts:
- info.title → the spec's display name; slugified into its id (e.g. "My Backend" → "my-backend").
- servers[].url → every base URL this group can be reached at. There is no environment axis — an app talks to exactly one base URL at a time, so a request matches this spec if its hostname matches any declared server.
- No manifest, no per-environment overrides. A group spanning multiple API versions (/v1/..., /v2/...) is simply multiple paths entries — and therefore multiple distinct operationIds — in the same document.
- responses.<code>.content.<mediaType>.examples.<name> → one entry per response variant this operation can mock; externalValue points at the response body file on disk. By convention the primary/original response for a status code is named "default".
- parameters with in: query → a literal example value on a query parameter becomes a required match for that operation (e.g. listUsers only matches requests carrying ?type=user).
- requestBody.content.<mediaType>.schema → optionally disambiguates operations that collide on path/method/query — see Request body matching below.
- x-devview.delayMs → simulated response delay, at the document root (spec-wide default) and/or per operation (overrides the default). See x-devview extension below.
- {param} placeholders: Path segments like {userId} match any value during request matching.
- tags → display-only labels, read into Operation.tags — see Tags below.
Version Tags
Operation.version is a display-only tag extracted from a /v{n}/ segment in the operation's
path (e.g. /api/v2/x → "v2", /health → null). It drives the version chip and filter in
the NetworkMock UI — see NetworkMock UI.
This is purely a UI label: request matching is unaffected, so /api/v1/x and /api/v2/x
remain two distinct operations matched only by path, method, and query params (see
Request Matching below). The extraction pattern is not currently
configurable.
Tags
Operation.tags is read verbatim from the operation's OpenAPI tags array (emptyList() if
absent) — purely a display/filter label, like version: it has no effect on
request matching. It drives the NetworkMock UI's tag filter chips and its "Tag" sort option —
see NetworkMock UI.
"paths": {
"/api/users": {
"get": {
"operationId": "listUsers",
"tags": ["Users", "Admin"],
"responses": { "...": "..." }
}
}
}
Request Matching
MockConfigRepository.findMatchingMock(host, path, method, queryParameters, requestBody) resolves a mock in four steps:
- Hostname match — compares the request host (case-insensitive) against every hostname declared in the spec's
servers[]. If two specs both declare a matching hostname, the first spec (in configuration order) that also has a matching operation wins. - Path match — splits path by
/, compares segment by segment;{param}segments match any value; non-param segments are case-sensitive. - Method match — case-sensitive exact match. Use uppercase (
"GET","POST"). - Request body match (only for operations that declare one — see below) — narrow, non-validating checks against the operation's declared
requestBodyschema.
Operation.method is typed as HttpMethod, a small value class modeled after Ktor's own
io.ktor.http.HttpMethod (open set, HttpMethod.Get/.Post/etc. constants, plus
HttpMethod.DefaultMethods for canonical ordering) — this module has no dependency on Ktor
itself, so the type exists to give the NetworkMock UI's method filter the same shape without
pulling one in. findMatchingMock's own method parameter stays a plain String, since it
receives the raw wire value from devview-networkmock-ktor.
There is no stored active-server selection. The matching server is determined purely from the request hostname at interception time.
Request body matching
An operation's requestBody.content.<mediaType>.schema (application/json if declared,
otherwise whichever media type comes first) is read into a narrow RequestBodyMatch — this
exists purely to disambiguate operations that would otherwise collide on path, method, and
query alone (e.g. two specs sharing a host, each declaring POST /api/payments, differing only
by body shape); it is not a substitute for path/method/query matching, and an operation without
requestBodyMatch still matches any body.
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"required": ["amount"],
"discriminator": { "propertyName": "type" },
"properties": {
"type": { "type": "string", "enum": ["card"] }
}
}
}
}
}
Two things are read from the schema, both deliberately narrow (not full JSON Schema validation):
| Schema field | Becomes | Matching rule |
|---|---|---|
required |
RequestBodyMatch.requiredFields |
every listed property must be a top-level key in the request body |
discriminator.propertyName |
RequestBodyMatch.discriminatorField |
that property must be a top-level key |
that property's own single-value enum |
RequestBodyMatch.discriminatorValue |
if present, the key's value must equal it exactly |
If the schema yields neither a required field nor a usable discriminator (no discriminator, or
one whose property doesn't declare a single-value enum), requestBodyMatch is null — same
as an operation declaring no requestBody at all. $refs (both the requestBody itself, under
components.requestBodies, and its schema, under components.schemas) resolve the same way as
elsewhere in this document.
devview-networkmock-ktor's plugin only reads the request body when it's already a fully
in-memory OutgoingContent.ByteArrayContent (the shape Ktor's content negotiation produces for
a JSON-serialized body) — a streaming or multipart body is never touched, and requestBodyMatch
simply doesn't apply to it (treated as no body). Reading it is a pure, repeatable operation that
never consumes or mutates anything the real network call still needs to send.
Response Variant Discovery
Response bodies live wherever externalValue points them — the sample app uses composeResources/files/networkmocks/responses/{specId}/{operationId}/{operationId}-{status}[-{suffix}].json, but this is only a convention, not a requirement.
Discovery reads exactly the (statusCode, mediaType, exampleName) triples declared in the spec — there is no probing of status codes or file-name suffixes. If a variant isn't declared, it doesn't exist.
discoverResponseFiles/loadMockResponse read and decode response body files — this is real I/O, on top of the one-time spec parse. MockConfigRepository doesn't call either eagerly; devview-networkmock's main operation list is built from parsed spec metadata alone (OperationDescriptor carries only key and config, no responses), and a given operation's variants are only discovered when its operation sheet actually opens. See NetworkMock UI.
MockConfigRepository(
specPaths = listOf("files/networkmocks/specs/my-backend.json"),
resourceLoader = NetworkMockResourceLoader { path -> Res.readBytes(path) }
)
Multiple media types per status code
When an operation declares multiple media types under the same status code (e.g. application/json
and application/xml under 200), each media type's examples are retained as distinct response
variants identified by (statusCode, mediaType, exampleName). The UI displays the media type
as a secondary label whenever an operation's variants span more than one media type, allowing
developers to explicitly choose which payload format to simulate. Callers of
loadMockResponse(key, statusCode, mediaType, exampleName) pass the declared media type to load
that exact variant.
Response headers and content type
responses.<code>.headers declares extra headers to serve alongside a mocked response, and the
media type key under responses.<code>.content (e.g. application/json) becomes the response's
Content-Type — both are threaded through to the app via the Ktor plugin's synthetic response.
"200": {
"headers": {
"X-RateLimit-Remaining": { "example": "42" }
},
"content": {
"application/json": {
"examples": {
"default": { "externalValue": "responses/getUser-200.json" }
}
}
}
}
Like query parameters, a header's literal example value is the only field
read — no schema resolution. A response without content exposes an empty-body default
variant and omits the media-type-derived Content-Type. Declared headers are retained; an
explicit Content-Type entry under headers overrides any media-type-derived value.
$ref resolution
Parameters, responses, examples, and headers may be declared via $ref instead of inline:
- Local: "$ref": "#/components/parameters/UserId" resolves against the same document's components.
- External: "$ref": "./common.json#/components/responses/Error" loads another file via the same NetworkMockResourceLoader.
A file path in a $ref (or an externalValue) is relative to the file that contains it, not to the root spec — so after specs/api.json references ./shared/a.json, a ./b.json inside a.json means specs/shared/b.json. A leading / is relative to the resources root. Local #/... refs inside an external file resolve against that file's own components.
Refs are followed as a chain — a referenced component's own $ref (if any) is resolved again,
until a non-ref entry is reached — with a cycle guard that fails clearly instead of hanging on a
circular reference. Each ref's fragment must name the section its context expects (e.g. a response
$ref must point into components/responses), so a same-named entry in a different section is
never resolved by mistake.
Wildcard content-type resolution
OpenAPI responses.<code>.content keys may declare media ranges rather than concrete
MIME types (*/*, application/*, text/*). DevView resolves ranges to a concrete
MockResponse.contentType header value based on the loaded body content so HTTP
client converters (such as Ktor's ContentNegotiation) can deserialize mocked responses:
| Declared range | Body content | Resolved Content-Type |
|---|---|---|
*/* or application/* |
Parses as JSON | application/json |
*/* |
Not JSON | text/plain |
application/* |
Not JSON | application/octet-stream |
text/* |
Any | text/plain |
Explicit media types (no *) pass through unchanged. Bodyless responses retain an
empty contentType string so no media-type-derived header is sent.
Bodyless responses
A response with no content (or an empty content: {} map) is available as one
"default" variant, including a response resolved through $ref. For example,
"204": { "description": "No Content" } needs no example or fixture file.
Its MockResponse.content and contentType are empty strings, and isSynthesized
is false: it is not schema-generated and gets no "Generated" badge. The Ktor plugin
returns zero body bytes without adding a media-type-derived Content-Type header;
declared response header examples are still served, including an explicit Content-Type.
This also supports bodyless 200 responses such as logout. A declared media type with
neither examples nor a schema remains unmockable. Once a variant is selected, a missing or
unreadable fixture fails the Ktor request without a real-network fallback. Missing configuration,
unmatched operations and Network selections still pass through; this is not blanket isolation.
Schema-based response synthesis
A status code with no examples at all, but a declared content.<mediaType>.schema,
synthesizes one placeholder body per such media type instead of being unmockable:
"200": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"status": { "type": "string", "enum": ["ACTIVE", "INACTIVE"] }
}
}
}
}
}
synthesizes {"id":0,"status":"ACTIVE"} under the example name "default". A status code that
declares any examples for a media type never falls back to synthesis for that media type,
even if it also declares a schema — an author-provided example always wins. MockResponse.isSynthesized
is true for a synthesized body, false otherwise; the operation picker page shows a small
"Generated" label on a synthesized response's row.
This is deliberately narrow, not full JSON Schema conformance — no required,
additionalProperties, string patterns, minimum/maximum, etc. (anything that would matter for
validating a body rather than synthesizing one plausible value):
| Shape | Synthesized value |
|---|---|
string |
"string", or the first non-null enum value if declared |
integer / number |
0 |
boolean |
false |
object (or any schema with properties) |
each property synthesized recursively |
array (or any schema with items) |
a single-element array of the synthesized item |
allOf |
member schemas' properties merged into one object; conflicting property definitions across members throw a clear error |
oneOf |
the first declared variant — discriminator is parsed but doesn't currently steer variant selection, since there's no concrete request/response data at spec-parse time to disambiguate against |
nullable is read but ignored — a real value is always synthesized, never a JSON null, since
this library mocks responses rather than exercising null-handling. OpenAPI 3.1 type arrays
(e.g. [string, "null"]) are accepted in JSON and YAML specs; the first non-"null" type
is used. Null entries in enum are skipped when synthesizing values or matching a request-body
discriminator. A schema shape outside this
list (or a schema declaring none of type/properties/items/enum/allOf/oneOf) throws a
clear error rather than guessing. $refs inside a schema (including nested ones under
properties/items/allOf/oneOf) resolve against components/schemas the same way as
elsewhere in this document — including relative to the file containing the $ref, so a schema
in an external file can reference its own #/components/schemas/... siblings.
x-devview extension
Vanilla OpenAPI has no field for response delay simulation or failure injection, so both live under the standard x--prefixed Specification Extensions mechanism:
x-devview:
delayMs: 200 # document root — spec-wide default
failureRate: 0.1 # ignored at the document root, see below
paths:
/users/{userId}:
get:
x-devview:
delayMs: 500 # per-operation — overrides the document default
failureRate: 0.1 # per-operation only — 10% of otherwise-mocked requests fail
failureRate, unlike delayMs, has no spec-wide default — a document-root failureRate is
parsed but ignored. "Some percentage of everything fails" is a much blunter tool than "this
specific flaky endpoint fails sometimes", so it's deliberately operation-level only. See
Simulating failures.
Simulating failures
An operation can be made to fail instead of returning a response, two ways:
- Deterministically, by selecting a failure kind in the operation sheet's picker page (a
Failurerow alongside the response variants) — every request to that operation fails the same way until the selection changes, the same wayMockalways serves the same response. - Probabilistically, via the spec's
x-devview.failureRate(0.0–1.0) — each request to an otherwise-mocked operation independently rolls against the configured rate. This only applies when the operation would otherwise serve a mock response; an operation left onNetworkpassthrough is never affected, keeping real network traffic untouched by default.
Two failure kinds are supported, each mirroring the exception a real Ktor engine (OkHttp on Android, Darwin on iOS) throws for the equivalent real condition, so an app's existing error handling exercises the same code path:
| Kind | Mirrors |
|---|---|
| Timeout | io.ktor.client.plugins.HttpRequestTimeoutException |
| Connection Refused | a connection-level kotlinx.io.IOException |
The probabilistic roll uses an injectable Random (NetworkMockConfig.random, defaulting to
Random.Default) — override it in tests to pin the outcome deterministically.
Caching & Reload
MockConfigRepository parses every configured spec once and caches the result — subsequent
loadConfiguration() calls return the cached value without re-reading any file. Call
invalidate() to clear that cache, then loadConfiguration() (or anything that calls it
internally, like findMatchingMock) to force a fresh read — this is how a developer picks up
an edited spec file without restarting the app. In devview-networkmock, the "Reload Config"
toolbar action does exactly this through the registered module; see
NetworkMock UI.
DataStore Schema
State is persisted via MockStateRepository:
| Key | Type | Meaning |
|---|---|---|
network_mock_global_enabled |
Boolean | Master toggle |
network_mock_last_modified |
Long | Epoch ms of last change |
network_mock_revision |
Long | Shared state revision; absent means zero |
network_mock_schema_version |
Int | Gates the one-shot pre-0.2.0 migration below |
network_mock_operation_{compositeKey} |
String (JSON) | Per-operation state |
OperationMockState is serialized as {"type":"network"} (pass-through),
{"type":"mock","statusCode":200,"mediaType":"application/json","exampleName":"default"}, or
{"type":"failure","kind":"timeout"} / {"type":"failure","kind":"connection_refused"}, or
{"type":"sequence","responses":[...],"currentIndex":0} — an ordered list of Mock steps plus
the position to serve next. The position is part of this same persisted value, not a separate
key, so resetting the operation to Network (or resetting all mocks) discards it along with
everything else about the sequence. See Simulating a staged/polling flow.
Upgrading from a pre-0.2.0 release: the operation-state key shape changed ({groupId}-{environmentId}-{endpointId} → {specId}-{operationId}), and so did the Mock payload (a response file name → (statusCode, exampleName) in schema 1, then gaining mediaType in schema 2). On first launch after upgrading across schema changes, legacy operation entries are wiped once — this is disabled-by-default developer-tooling state, not user data, so previously-selected mocks are reset rather than translated. The global mocking toggle is unaffected. See the migration guide for converting an existing mocks.json.
State coordination
MockStateRepository.getStateSnapshot() reads the state and revision from the same persisted snapshot. Unlike getState(), it propagates I/O failures instead of returning default state. The revision is additive to schema 2: existing valid selections remain readable without migration or reset.
Every explicit state write increments the shared revision, including equal-value toggles, replacements and resets. compareAndAdvanceSequence(key, expectedRevision, expectedSequence) validates the current revision, global toggle and exact sequence inside one DataStore transaction. It returns false without writing if they changed or no current response exists. A successful non-terminal consume advances the position; the terminal step repeats and still validates, without incrementing the revision. Persistence errors propagate. Step order is successful commit order, not request-start or response-completion order.
resetOperationSequencePosition(key) reads the latest sequence inside its transaction and resets only its position. It preserves the latest response list, increments the revision even when already at zero, and does nothing for a non-sequence operation. resetKnownOperationsToNetwork() covers both persisted keys and pre-registered operations, including another repository's entries, without changing the global toggle.
The Ktor plugin uses these operations to avoid lost updates, stale prepared responses and equal-value ABA replacements. See interception behaviour.
Logging
MockConfigRepository logs spec-load outcomes through Kermit, tagged DevViewNetworkMock — the same tag used by devview-networkmock and devview-networkmock-ktor, so a host can filter every NetworkMock-related log line by tag regardless of which module emitted it. Spec load success logs at debug, load failures at warn with the causing throwable attached. Request-matching outcomes (findMatchingMock) log at verbose, since they fire on every intercepted request.
No response body content is ever logged. To silence NetworkMock's logs (or raise/lower their verbosity) in a host app, configure Kermit directly — this module adds no separate on/off flag of its own:
import co.touchlab.kermit.Logger
import co.touchlab.kermit.Severity
// Silence everything below warnings, repo-wide (affects every Kermit-backed DevView module)
Logger.setMinSeverity(Severity.Warn)
devview-consolelogger, if installed, captures these logs into DevView's own in-app console screen for free — no extra wiring needed.
NetworkMockResourceLoader
Added in v0.1.3.
NetworkMockResourceLoader is a fun interface that abstracts how mock resource bytes are loaded from a path. It exists to support DI-friendly architectures where the spec files live in a different Gradle module than the one constructing NetworkMock.
Basic Usage
NetworkMock(
resourceLoader = NetworkMockResourceLoader { path -> Res.readBytes(path) },
specPaths = listOf("files/networkmocks/specs/my-backend.json")
)
DI Usage (Koin example)
In the module that owns the mock resource files:
In the presentation module where NetworkMock is constructed:
val loader = koinInject<NetworkMockResourceLoader>()
val modules = rememberModules {
module(NetworkMock(resourceLoader = loader, specPaths = listOf("files/networkmocks/specs/my-backend.json")))
}
Why This Exists
Before v0.1.3, NetworkMock accepted a raw suspend (String) -> ByteArray lambda. This worked but was impossible to register as a typed binding in DI frameworks (Koin, Hilt) across Gradle module boundaries. The named NetworkMockResourceLoader type solves this.
Related Modules
- NetworkMock: UI layer and module entry point.
- NetworkMock Ktor: Ktor client plugin.