Repository navigation
feat(mock): add the mock serve and mock generate commands - #474
Draft
Shield-Jaguar wants to merge 18 commits into
Draft
Shield-Jaguar wants to merge 18 commits into
Shield-Jaguar wants to merge 18 commits into
Conversation
The v4 mock server is being ported from C# (apimatic/mock-server-poc-v4) as `apimatic mock serve`. This lays the ground and adds no behaviour: - ajv moves to the runtime dependencies; the loader checks stub files with it - mock-stubs.schema.json, the stub schema, is published with the package - ESLint keeps src/types/mock free of file, process and network access and of imports from the rest of the CLI, and refuses regular expressions in the mock - the three reference stub sets become fixtures under test/resources/mock Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The stub format of the v4 mock server, ported from its C# reference: - a strict JSON reader and writer that keep a number as it was written, so an int64 beyond 2^53 or a decimal such as 250.00 is compared and served unchanged - the stub model: path templates, value and JSON rules, responses with SSE, ndjson and multipart rendering, OAuth2 server settings - StubSchema: ajv decides whether a file is valid, and a walk over the same schema says what is wrong and where, one problem per JSON pointer - parseStub and loadStubs, which report every problem of every file in one run - StubDirectoryService, which lists and reads a stubs directory The three reference stub sets load with no problems. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The matching layer of the v4 mock server, ported from its C# reference: - the request model, with query, cookie, Prefer and multipart/form-data reading - the stub matcher: method, path, headers, cookies, credentials, the closed query set and the body, with Prefer: code= and Prefer: example= - the closest-stub ranking and the 418 problem report with its X-Mock-Mismatch summary The seven wire mutations are named without a server, and the report documents the reference pins are reproduced as written. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… stub The authorization server an oauth2 stub describes: client credentials, authorization code with PKCE (S256), refresh, password and implicit flows. It is stateless (the code carries the challenge, scope and redirect URI; refresh tokens are numbered) and refuses a wrong request with the same 418 report the stubs use. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The host on node:http. It loads a stubs directory, listens on a free loopback port or a fixed host and port, hands every request to the router (the OAuth2 servers first, then the stubs) and writes what was decided: the stub's answer with its length stated, or the 418 report. Routing, the request and the response as they cross the wire, and the body limit are pure and live in src/types/mock/routing. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The mock is stateless, so a retry test counts its attempts in a log of the newest 10,000 requests that reached the router: GET reads it, DELETE clears it, and nothing else exists under /__admin. The paced body of a stream moves into a module of its own with tests for the pause between chunks and for a stream ended by a stop or by a client that leaves. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
apimatic mock serve loads a stubs directory and serves it until stopped, printing MOCKSERVER_URL=<origin> for a test harness to read. Flags choose the port (0 for a free one), the host, the stubs directory, the OAuth2 token lifetime and a request log on stderr. The command and its topic stay hidden until the SDK contract suites pass against it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
docs/mock/stub-format.md is the format the mock loads, with the request log's shape and the requests the mock answers itself. docs/mock/generator-handoff.md says what a generator renders and how a generated test starts the command, finds the origin and stops it, with a table of what changed from the C# proof of concept. CONTEXT.md gains the mock's terms, and the plan records the contract run and what is left. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The C# SDK's contract suite passes against it (103 of 103 on net10.0 and net8.0 over the TesterPoc stubs, with no request missed), so the command and its topic are no longer hidden and the README lists them. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
| refreshTokenPrefix: 'ac-refresh-token-', | ||
| username: 'test-user', | ||
| password: 'test-password', | ||
| passwordAccessToken: 'pw-access-token', |
| clientCredentialsToken: 'cc-access-token', | ||
| username: 'test-user', | ||
| password: 'test-password', | ||
| passwordToken: 'pw-access-token', |
…loud asked for The part names of a multipart form are sorted with the ordinal comparer the rest of the mock uses, and the closest schema branch is folded from the first one explicitly; neither changes what is returned. The two fixed test passwords are marked as such for the analysis. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
apimatic mock generate zips the project's src folder, sends it to codegen's /mock endpoint, waits for the run and replaces the stubs directory with the stub files it downloads. The default destination is the folder mock serve reads by default, so the two commands work in a project directory with no flags. The download is unpacked and loaded as mock serve would load it before the stubs directory is touched, so a run that fails or returns stub files the mock would refuse leaves the last set in place. The three routes and the layout of the download are stated in stub-generation-service.ts alone. The endpoint does not exist yet, so the command is hidden and its tests run against a local stand-in for it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
docs/mock/generator-handoff.md gains a section on the three /mock routes the command calls, the statuses it reads, the layout it expects in the download and the two points still open on the codegen side. The plan records phase 8: what was built, how it differs from plugin generate, what could not be run without the endpoint and what to do when it is live. CONTEXT.md says what mock generate does to the stubs directory. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
mock generate took the download as a stream, so a connection that dropped or stalled after the headers failed while the action saved it, and the error was thrown out of the command. The service now receives the download whole: a break is one more failed request, reported like the others, and the stubs directory keeps the last set. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The Spec S and TesterPoc sets belong with the SDKs whose suites run against them, not with the CLI. Both go, with the Spec S contract tests that existed only to exercise them. The 20 sample stubs the unit and host tests are built on move verbatim into test/helpers/mock-sample.ts; a test that needs them on disk writes them to a temporary directory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
String.raw stays only on the one sample file that holds a backslash, and the stub helpers import the node: built-ins by their prefix. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Nested template literals and ternaries are pulled into named values or small functions, the body reader of openStream into a function of its own, and the stub loader sorts its problems in a statement of its own. Static factories and the serve flags are readonly, the schema keyword lists are Sets, tests assert undefined with to.be.undefined, and the last item is read with at(-1). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.




Adds
apimatic mock serve: a mock HTTP server that answers exactly the requests its stub files describe, for generated SDK tests to run against. It is the TypeScript port of the C# proof of concept in mock-server-poc-v4 (apimatic/codegen-v2#705), with the same stub format and wire contract, so the stub files of the proof of concept load as they are.It also carries
apimatic mock generate, which fetches the stub filesmock servereads. That command is hidden until its endpoint is live; it was #484, and is described in its own section below.What it does
application/problem+jsonnaming the closest stub and every difference from it, plus a one-lineX-Mock-Mismatchheader. It never guesses.Prefer: code=<status>andPrefer: example=<name>.oauth2stub: client credentials, authorization code with PKCE, refresh, password and implicit.chunkDelayMs, multipart and binary./__admin/requests(GETreads the newest 10,000,DELETEclears), so a retry test can count its attempts.MOCKSERVER_URL=<origin>is printed once the mock listens. Exit code 130 means stopped, 1 means stub problems or a port that could not be opened, 2 means a bad flag.Flags:
-p, --port(default 4010;0picks a free loopback port; a busy port is an error),--host,-s, --stubs(default./stubs),--token-ttl,--verbose.How it is built
src/types/mock/**is the pure core: a strict JSON reader and writer, the stub format (schema check with ajv, then a typed parser that reports every problem with its JSON pointer), matching, the 418 report and the OAuth2 server. ESLint keepsfs,http,net, clack and oclif out of it, and bans regular expressions in the mock's folders and tests.src/infrastructure/mock/**is the only I/O: the stubs directory and the host onnode:http.mock-stubs.schema.jsonships in the package;ajvmoves fromdevDependenciestodependencies.docs/mock/stub-format.mdis the format;docs/mock/generator-handoff.mdsays what a generator renders and how a generated test starts and stops the command, and lists what differs from the C# server on purpose (section 5).How it was checked
test/helpers/mock-sample.ts; the reference's Spec S and TesterPoc stub sets belong with the SDKs that run against them and are not kept in this repository.tests/TesterPoc.ContractTests, 103 tests) passes againstapimatic mock serveon .NET 10 and .NET 8, with no request missed.test/e2e/mock-serve.test.tsruns the built CLI: the marker line, exit codes 1 and 2, and exit 130 on SIGINT and SIGTERM (POSIX only).For the reviewer
.ai/plans/mock-server.md(Phase 7 findings) and wait for the release.--hostacceptslocalhostor an IP address only, stub problems go to stdout with the rest of the CLI's output, and the marker line sits inside the CLI's gutter rather than first on stdout.mock generate(hidden)apimatic mock generatesends the project's build to codegen, waits for the run, downloads the stub files and writes them to the folderapimatic mock servereads. In a project directory the two commands work with no flags:The endpoint it calls does not exist yet. The command is written against the planned
/mockcontract, which has the shape of/plugin, and is hidden until that endpoint is live, so a release cannot ship a command that always fails.What it does
plugin generatedoes: a zip ofsrc/, toPOST /mock. It asks for no language and needs nopluginblock or metadata inapimatic.json.GET /mock/{id}/statuswith the sharedpollUntilCompleted, then downloadsGET /mock/{id}/download.mock serveuses. Stub files the mock would refuse are reported problem by problem, and the stubs directory is left as it was. So is a run that fails, and a download without a stub.mock serveloads every file in the folder, so one left from the last set would be served beside the new one. Only a.gitfolder is kept.--forceskips the question.Flags:
--input(the project directory),--destination(defaultstubsin the project directory, so--input Xwrites toX/stubs),--force,--auth-key. Errors use the wording ofplugin generate.How it is built
plugin generatelayer by layer:commands/mock/generate.ts,actions/mock/generate.ts,prompts/mock/generate.ts,infrastructure/services/stub-generation-service.ts, withtypes/stubs-context.tsfor the stubs directory.stub-generation-service.ts: the three routes, and the place of the stub files in the download (STUB_FILES_IN_DOWNLOAD). A change on the codegen side is an edit to that one file.STUBS_DIRECTORY_NAMEintypes/project-layout.tsis now the one name both commands share;mock serve's default is built from it.docs/mock/generator-handoff.mdgains section 6, which states the contract as the CLI reads it..ai/plans/mock-server.mdrecords the work as phase 8, with what to do when the endpoint is live.How it was checked
pnpm build,pnpm lintandpnpm testpass locally (3917 passing, 93 pending). 68 of the tests are new.test/helpers/stub-generation-endpoint.ts), asplugin-service.test.tsdoes for/plugin.mock generatewith only an auth key, thenmock servewith no stubs flag, served the generated set; a second run with--forceremoved a file left from the first.Not run: the real endpoint, since there is none, and the overwrite question in a real terminal.
For the reviewer
/plugin.originsent isAPIMATIC CLI mock:generate, since oclif spells the command's id with a colon, asplugin generatesendsplugin:generate.plugin generatein two places. The overwrite question counts hidden files, because the replace removes them. A run that returns no stub is a failure and leaves the folder as it was.plugin generateandsdk generatestream theirs, so the same break throws while they save it; they are not changed here.stubsis not added to the foldersquickstartputs in a project's.gitignore. Whether it should be is left for when the command is shown.hidden, widen themocktopic's description, runpnpm readme.🤖 Generated with Claude Code