8000 test: one harness for the command tests by dominikwozniak · Pull Request #99 · dominikwozniak/dw-mc · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/adr/0006-source-layout.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ What is a term and what is a rule's input is decided by who has to agree on it.

A module is named, never counted: `#adapters/config.ts`, whether the importer sits in another layer or next door. The name is a node subpath import declared in `package.json`, so it survives the build and reads the same from everywhere, and the layer a module belongs to is stated at each call site rather than inferred from how many `../` precede it. There is no relative import in `src/`, which also means moving a file between layers changes that file and not its importers.

A test lives beside the module it covers, and a module ships the fake its callers need rather than a test-only file next door. The seams are written that way: `src/adapters/spawner.ts` exports the fake spawner, `src/adapters/store.ts` the in-memory store, `src/adapters/picker.ts` the scripted terminal, `src/adapters/config.ts` the in-memory configuration, so a caller's test reaches for one import and gets both the thing and its double.
A test lives beside the module it covers, and a module ships the fake its callers need rather than a test-only file next door. The seams are written that way: `src/adapters/spawner.ts` exports the fake spawner and the stubbed one built on it, `src/adapters/store.ts` the in-memory store, `src/adapters/picker.ts` the scripted terminal and the recording console, `src/adapters/config.ts` the in-memory configuration, so a caller's test reaches for one import and gets both the thing and its double. The rule reaches past the seams to the two things a test would otherwise invent. The shape a read answers with belongs to the adapter that makes the read, so `prViewOf` sits beside `prView` in `src/adapters/gh.ts` and a field added to the read has one fixture to grow. The machine those doubles assemble into belongs to `src/cli/cli.ts`, beside the command that runs on it, because the entry point assembles that same stack out of the real layers: a command's test that built its own would be one more answer to the question of what this tool talks to.

The layout grows with the code and not ahead of it. A directory appears when there is code to put in it. A fifth layer is a change to this record — rewritten in place, no note of what it replaced — not a directory added quietly next to the others.

Expand Down
11 changes: 4 additions & 7 deletions src/adapters/ci.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,13 @@ import {
rollupState,
workflowFailsOn
} from "#adapters/ci.ts"
import { fakeHandle, layerFake } from "#adapters/spawner.ts"
import { fakeHandle, layerStubbed } from "#adapters/spawner.ts"

/** A spawner that answers every program the same way, and records the argv. */
const answering = (spawned: Array<ReadonlyArray<string>>, handle: Parameters<typeof fakeHandle>[0]) =>
layerFake((command) => {
if (command._tag !== "StandardCommand") {
return Effect.die("ci.test: the fake was handed a piped command")
}
spawned.push([command.command, ...command.args])
return Effect.succeed(fakeHandle(handle))
layerStubbed({
onSpawn: (command) => spawned.push([command.command, ...command.args]),
stubs: [() => Effect.succeed(fakeHandle(handle))]
})

describe("rollupState", () => {
Expand Down
69 changes: 33 additions & 36 deletions src/adapters/claude.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { ChildProcess } from "effect/unstable/process"
import { commandReview, findingsTurn, promptReview, reviewTurns, steeredSession } from "#adapters/claude.ts"
import type { Launcher } from "#adapters/config.ts"
import { builtInLauncher } from "#adapters/config.ts"
import { fakeHandle, layerFake } from "#adapters/spawner.ts"
import { fakeHandle, layerFake, layerStubbed, wrote } from "#adapters/spawner.ts"

const launcher = builtInLauncher
const session = "befb6186-5471-4b26-b680-e8ca49df25ac"
Expand Down Expand Up @@ -51,14 +51,12 @@ const claude = (options: {
readonly stderr?: string | undefined
readonly exitCode?: number | undefined
}) =>
layerFake((command) => {
if (command._tag !== "StandardCommand") {
return Effect.die("runner.test: the fake was handed a piped command")
}
options.spawned.push(command)
return Effect.succeed(
fakeHandle({ stdout: options.stdout ?? "", stderr: options.stderr, exitCode: options.exitCode })
)
layerStubbed({
onSpawn: (command) => options.spawned.push(command),
stubs: [
() =>
Effect.succeed(fakeHandle({ stdout: options.stdout ?? "", stderr: options.stderr, exitCode: options.exitCode }))
]
})

const nothing = () => Effect.void
Expand Down Expand Up @@ -468,23 +466,19 @@ describe("one review run, in whichever shape it was configured in", () => {

/** A `claude` that answers the review turn and the findings turn differently. */
const turns = (spawned: Array<ChildProcess.StandardCommand>, reporting?: Record<string, unknown>) =>
layerFake((command) => {
if (command._tag !== "StandardCommand") {
return Effect.die("runner.test: the fake was handed a piped command")
}
spawned.push(command)
const resuming = command.args.includes("--resume")
const answer = JSON.stringify({ ...success, session_id: session, structured_output: found, ...reporting })
return Effect.succeed(
fakeHandle({
stdout: resuming
? answer
: [
JSON.stringify({ type: "assistant", message: { content: [{ type: "text", text: report }] } }),
JSON.stringify({ ...success, structured_output: found })
].join("\n")
})
)
layerStubbed({
onSpawn: (command) => spawned.push(command),
stubs: [
(command) =>
wrote(
command.args.includes("--resume")
? JSON.stringify({ ...success, session_id: session, structured_output: found, ...reporting })
: [
JSON.stringify({ type: "assistant", message: { content: [{ type: "text", text: report }] } }),
JSON.stringify({ ...success, structured_output: found })
].join("\n")
)
]
})

const running = (turn: Parameters<typeof reviewTurns>[0]["turn"]) =>
Expand Down Expand Up @@ -595,16 +589,19 @@ describe("steeredSession", () => {
assert.include(error.message, "no claude on this machine")
}).pipe(
Effect.provide(
layerFake(() =>
Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "no claude on this machine"
})
)
)
layerStubbed({
stubs: [
() =>
Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description: "no claude on this machine"
})
)
]
})
)
)
)
Expand Down
29 changes: 13 additions & 16 deletions src/adapters/gh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@ import {
reviewDecisionOf,
viewer
} from "#adapters/gh.ts"
import { fakeHandle, layerFake } from "#adapters/spawner.ts"
import { fakeHandle, layerFake, layerStubbed, wrote } from "#adapters/spawner.ts"

/** A spawner that answers every program the same way, and records the argv. */
const answering = (spawned: Array<ReadonlyArray<string>>, handle: Parameters<typeof fakeHandle>[0]) =>
layerFake((command) => {
if (command._tag !== "StandardCommand") {
return Effect.die("gh.test: the fake was handed a piped command")
}
spawned.push([command.command, ...command.args])
return Effect.succeed(fakeHandle(handle))
layerStubbed({
onSpawn: (command) => spawned.push([command.command, ...command.args]),
stubs: [() => Effect.succeed(fakeHandle(handle))]
})

describe("requireAuth", () => {
Expand Down Expand Up @@ -139,15 +136,15 @@ describe("viewer", () => {

describe("prComments", () => {
it.effect("says which comments came from an app rather than a person", () => {
const answered = layerFake((command) => {
if (command._tag !== "StandardCommand") {
return Effect.die("gh.test: the fake was handed a piped command")
}
const body =
(command.args[1]?.includes("/issues/") ?? false)
? `[{"created_at":"2026-09-15T08:43:44Z","user":{"login":"coderabbitai[bot]","type":"Bot"}}]`
: `[{"created_at":"2026-09-15T09:00:00Z","user":{"login":"dominikwozniak","type":"User"}}]`
return Effect.succeed(fakeHandle({ stdout: body }))
const answered = layerStubbed({
stubs: [
(command) =>
wrote(
(command.args[1]?.includes("/issues/") ?? false)
? `[{"created_at":"2026-09-15T08:43:44Z","user":{"login":"coderabbitai[bot]","type":"Bot"}}]`
: `[{"created_at":"2026-09-15T09:00:00Z","user":{"login":"dominikwozniak","type":"User"}}]`
)
]
})

return Effect.gen(function* () {
Expand Down
51 changes: 50 additions & 1 deletion src/adapters/gh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,11 @@ const PrView = Schema.fromJsonString(
)
export type PrView = typeof PrView.Type

const viewFields =
/**
* The fields one `gh pr view` asks for, named so a test can spell the vector it
* expects without copying the list and watching it drift.
*/
export const viewFields: string =
"number,title,url,isDraft,headRefOid,headRefName,baseRefName,author,isCrossRepository,mergeable," +
"reviewDecision,statusCheckRollup"

Expand Down Expand Up @@ -443,3 +447,48 @@ export const mergePr = Effect.fnUntraced(function* (repo: string, number: number
})
)
})

/**
* As much of one pull request as a test cares to say, which is less than `gh`
* answers about it.
*
* Every field it leaves out gets the answer a pull request nothing is wrong
* with would give, so a test names only what its own question turns on.
*/
export interface PrFixture {
readonly number: number
readonly title?: string | undefined
readonly isDraft?: boolean | undefined
readonly headRefOid?: string | undefined
readonly headRefName?: string | undefined
readonly baseRefName?: string | undefined
readonly author?: string | undefined
readonly isCrossRepository?: boolean | undefined
readonly mergeable?: string | undefined
readonly reviewDecision?: string | undefined
readonly statusCheckRollup?: ReadonlyArray<Record<string, unknown>> | null | undefined
}

/**
* What `gh pr view --json <viewFields>` answers with about `pr`, for a fake
* `gh`.
*
* It is written here rather than in each test because it is the shape `PrView`
* parses: a field added to the read has one fixture to grow, and a test that
* spelled its own would go on passing against a pull request `gh` no longer
* describes that way.
*/
export const prViewOf = (repo: string, pr: PrFixture): Record<string, unknown> => ({
number: pr.number,
title: pr.title ?? "feat: a pull request",
url: `https://github.com/${repo}/pull/${pr.number}`,
isDraft: pr.isDraft ?? false,
headRefOid: pr.headRefOid ?? "31268022360852f71815404b6bbdd6bd797cfb4c",
headRefName: pr.headRefName ?? `feat/${pr.number}-a-branch`,
baseRefName: pr.baseRefName ?? "main",
author: { login: pr.author ?? "dominikwozniak" },
isCrossRepository: pr.isCrossRepository ?? false,
mergeable: pr.mergeable ?? "MERGEABLE",
reviewDecision: pr.reviewDecision ?? "",
statusCheckRollup: pr.statusCheckRollup ?? []
})
139 changes: 67 additions & 72 deletions src/adapters/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ConfigProvider, Effect, Layer, Path } from "effect"

import { rebaseInPlace, rebaseOnto, standingWorktree, withWorktree } from "#adapters/git.ts"
import { layerScripted } from "#adapters/picker.ts"
import { fakeHandle, layerFake } from "#adapters/spawner.ts"
import { layerStubbed, refused, vectorOf, wrote } from "#adapters/spawner.ts"

const state = "/home/dw/.local/state/dw-mc"
const clone = `${state}/repos/dominikwozniak/dw-mc.git`
Expand Down Expand Up @@ -44,55 +44,50 @@ const git = (options: {
/** Whether the worktree has something staged, as `rerere` leaves it. */
readonly staged?: boolean | undefined
}) =>
layerFake((command) => {
if (command._tag !== "StandardCommand") {
return Effect.die("git.test: the fake was handed a piped command")
}
const argv = command.args.join(" ")
options.spawned.push(`${command.command} ${argv}`)

if (options.refuses?.argv === argv) {
return Effect.succeed(fakeHandle({ exitCode: 128, stderr: options.refuses.detail }))
}
if (argv === `-C ${clone} rev-parse --is-bare-repository`) {
return options.cloned === true
? Effect.succeed(fakeHandle({ stdout: "true\n" }))
: Effect.succeed(fakeHandle({ exitCode: 128, stderr: said.noRepository }))
}
if (argv === `-C ${clone} rev-parse refs/dw-mc/pr/28`) {
return Effect.succeed(fakeHandle({ stdout: `${head}\n` }))
}
if (argv === `-C ${clone} rev-parse --verify --quiet refs/heads/dw-mc/rebase/28`) {
return Effect.succeed(fakeHandle({ exitCode: 1 }))
}
if (argv.endsWith("diff --cached --quiet")) {
return options.staged === true ? Effect.succeed(fakeHandle({ exitCode: 1 })) : Effect.succeed(fakeHandle({}))
}
if (argv === `-C ${standing} diff --name-only --diff-filter=U`) {
return Effect.succeed(fakeHandle({ stdout: (options.unmerged ?? []).map((path) => `${path}\n`).join("") }))
}
if (argv === `-C ${clone} rev-parse --verify --quiet refs/heads/dw-mc/fix/28`) {
return options.ahead === undefined
? Effect.succeed(fakeHandle({ exitCode: 1 }))
: Effect.succeed(fakeHandle({ stdout: `${head}\n` }))
}
if (argv === `-C ${clone} rev-list --count refs/heads/dw-mc/fix/28 ^${head}`) {
return Effect.succeed(fakeHandle({ stdout: `${options.ahead ?? 0}\n` }))
}
if (argv === `-C ${worktree} rev-list --count HEAD..refs/heads/main`) {
return Effect.succeed(fakeHandle({ stdout: `${options.behind ?? 0}\n` }))
}
if (argv === `-C ${worktree} rev-parse HEAD`) {
return Effect.succeed(fakeHandle({ stdout: `${rebased}\n` }))
}
if (argv === `-C ${worktree} diff --name-only --diff-filter=U`) {
return Effect.succeed(fakeHandle({ stdout: (options.unmerged ?? []).map((path) => `${path}\n`).join("") }))
}
if (argv === `-C ${clone} worktree list --porcelain`) {
const listed = (options.worktrees ?? []).map((directory) => `worktree ${directory}\nbare\n`)
return Effect.succeed(fakeHandle({ stdout: [`worktree ${clone}\nbare\n`, ...listed].join("\n") }))
}
return Effect.succeed(fakeHandle({}))
layerStubbed({
onSpawn: (command) => options.spawned.push(vectorOf(command)),
stubs: [
(_, argv) => {
if (options.refuses?.argv === argv) {
return refused(options.refuses.detail, 128)
}
if (argv === `-C ${clone} rev-parse --is-bare-repository`) {
return options.cloned === true ? wrote("true\n") : refused(said.noRepository, 128)
}
if (argv === `-C ${clone} rev-parse refs/dw-mc/pr/28`) {
return wrote(`${head}\n`)
}
if (argv === `-C ${clone} rev-parse --verify --quiet refs/heads/dw-mc/rebase/28`) {
return refused("")
}
if (argv.endsWith("diff --cached --quiet")) {
return options.staged === true ? refused("") : wrote("")
}
if (argv === `-C ${standing} diff --name-only --diff-filter=U`) {
return wrote((options.unmerged ?? []).map((path) => `${path}\n`).join(""))
}
if (argv === `-C ${clone} rev-parse --verify --quiet refs/heads/dw-mc/fix/28`) {
return options.ahead === undefined ? refused("") : wrote(`${head}\n`)
}
if (argv === `-C ${clone} rev-list --count refs/heads/dw-mc/fix/28 ^${head}`) {
return wrote(`${options.ahead ?? 0}\n`)
}
if (argv === `-C ${worktree} rev-list --count HEAD..refs/heads/main`) {
return wrote(`${options.behind ?? 0}\n`)
}
if (argv === `-C ${worktree} rev-parse HEAD`) {
return wrote(`${rebased}\n`)
}
if (argv === `-C ${worktree} diff --name-only --diff-filter=U`) {
return wrote((options.unmerged ?? []).map((path) => `${path}\n`).join(""))
}
if (argv === `-C ${clone} worktree list --porcelain`) {
const listed = (options.worktrees ?? []).map((directory) => `worktree ${directory}\nbare\n`)
return wrote([`worktree ${clone}\nbare\n`, ...listed].join("\n"))
}
return wrote("")
}
]
})

const machine = (spawner: Layer.Layer<never> | ReturnType<typeof git>, drawn?: Array<string>) =>
Expand Down Expand Up @@ -409,28 +404,28 @@ describe("rebasing a branch onto its base", () => {
}).pipe(
Effect.provide(
machine(
layerFake((command) => {
if (command._tag !== "StandardCommand") {
return Effect.die("git.test: the fake was handed a piped command")
}
const argv = command.args.join(" ")
spawned.push(`${command.command} ${argv}`)
if (argv === `-C ${clone} rev-parse --is-bare-repository`) {
return Effect.succeed(fakeHandle({ stdout: "true\n" }))
}
if (argv === `-C ${clone} rev-parse refs/dw-mc/pr/28`) {
return Effect.succeed(fakeHandle({ stdout: `${head}\n` }))
}
if (argv === `-C ${worktree} rev-list --count HEAD..refs/heads/main`) {
return Effect.succeed(fakeHandle({ stdout: "3\n" }))
}
if (argv === `-C ${worktree} rebase refs/heads/main`) {
return Effect.succeed(fakeHandle({ exitCode: 128, stderr: said.noIdentity }))
}
if (argv === `-C ${worktree} rebase --abort`) {
return Effect.succeed(fakeHandle({ exitCode: 128, stderr: said.noRebase }))
}
return Effect.succeed(fakeHandle({}))
layerStubbed({
onSpawn: (command) => spawned.push(vectorOf(command)),
stubs: [
(_, argv) => {
if (argv === `-C ${clone} rev-parse --is-bare-repository`) {
return wrote("true\n")
}
if (argv === `-C ${clone} rev-parse refs/dw-mc/pr/28`) {
return wrote(`${head}\n`)
}
if (argv === `-C ${worktree} rev-list --count HEAD..refs/heads/main`) {
return wrote("3\n")
}
if (argv === `-C ${worktree} rebase refs/heads/main`) {
return refused(said.noIdentity, 128)
}
if (argv === `-C ${worktree} rebase --abort`) {
return refused(said.noRebase, 128)
}
return wrote("")
}
]
})
)
)
Expand Down
Loading
Loading
0