@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
mdx 222 lines 11.3 KB
Raw
1 ---
2 title: Testing a model
3 description: Test your model's rules, views, policies and deadlines with stories that run it in memory.
4 ---
5
6 Your model is tested with [stories](/domain/story): given some history, when a command is sent, then these events are recorded. This page sets up a story runner and covers what a story can check.
7
8 ## Create a story runner
9
10 Give `Story.make` your model, its policies' Layer, and the external systems to fake, in `stub`. The story answers their calls itself. Any other external system the model calls runs for real, from a Layer you provide.
11
12 ```typescript
13 // packages/domain/test/withdrawals.test.ts
14 import { it } from "@effect/vitest";
15 import { Story } from "@alchemy.run/domain/Story";
16 import { Account } from "../src/Account/Account.aggregate.ts";
17 import { AccountSummary } from "../src/Account/AccountSummary.view.ts";
18 import { MoneyDeposited } from "../src/Account/DepositMoney.command.ts";
19 import { InsufficientFunds } from "../src/Account/InsufficientFunds.rejection.ts";
20 import { AccountOpened } from "../src/Account/OpenAccount.command.ts";
21 import { Statement } from "../src/Account/Statement.view.ts";
22 import { MoneyWithdrawn, WithdrawMoney } from "../src/Account/WithdrawMoney.command.ts";
23 import { customer } from "../src/Actor.ts";
24 import * as Layer from "effect/Layer";
25 import { Bank, BankHandlers } from "../src/Bank.model.ts";
26 import { MemoryLedgerStore } from "../src/Ledger/LedgerStore.ts";
27 import { CurrentActor } from "../src/CurrentActor.context.ts";
28 import { CustomerId } from "../src/Customer/Customer.id.ts";
29 import { FraudCheck } from "../src/Fraud/FraudCheck.external.ts";
30 import { Payments } from "../src/Settlement/Payments.external.ts";
31
32 const story = Story.make(Bank, {
33 layer: BankHandlers.pipe(Layer.provide(MemoryLedgerStore)),
34 stub: [FraudCheck, Payments],
35 });
36 const account = Account.ref("a-1");
37 const opened = new AccountOpened({ customerId: CustomerId.make("c-1"), owner: "sam" });
38 const asSam = Story.provide(CurrentActor, customer("c-1"));
39
40 it.effect("a withdrawal replies with the balance and updates the views", () =>
41 story(
42 Story.given(account, opened, new MoneyDeposited({ amount: 100, balanceAfter: 100 })),
43 asSam,
44 Story.when(account, new WithdrawMoney({ amount: 30 })),
45 Story.then(account, new MoneyWithdrawn({ amount: 30, balanceAfter: 70 })),
46 Story.replied({ balance: 70 }),
47 Story.view(AccountSummary, account, { balance: 70 }),
48 Story.emitted(Statement, account, [
49 { kind: "deposit", amount: 100, balance: 100 },
50 { kind: "withdrawal", amount: 30, balance: 70 },
51 ]),
52 ),
53 );
54
55 it.effect("an overdraft is rejected with the evidence", () =>
56 story(
57 Story.given(account, opened, new MoneyDeposited({ amount: 50, balanceAfter: 50 })),
58 asSam,
59 Story.when(account, new WithdrawMoney({ amount: 80 })),
60 Story.rejected(new InsufficientFunds({ balance: 50, requested: 80 })),
61 ),
62 );
63 ```
64
65 Run stories with Vitest and `@effect/vitest`: each story is an Effect, so `it.effect` runs it.
66
67 ## Check every outcome
68
69 The test above uses most of the checks. `then` checks the next events recorded on an instance; with no events, it checks that nothing new was recorded. Every recorded event needs a `then`, on every instance, including the ones a policy writes. `replied` checks the last command's reply, and `rejected` checks that it was refused with exactly this rejection. `state` checks an instance's current state directly, or part of it.
70
71 Views and streams are checked as a client would read them. `view` checks a view key's state, or part of it, and `emitted` checks every event a view key has emitted. `streamed` checks the next entries a projection appended to a stream key.
72
73 Commands run as whoever `provide` says, as their middleware would. Here `asSam` provides `CurrentActor`, so the account's ownership check passes.
74
75 The checks after a `when` are type-checked against its command. `rejected` takes only a rejection the command declares, and `replied` only its reply type. A `when` needs a `provide` step before it for every service its command's middleware provides, so without `asSam` the story does not compile.
76
77 ## Answer outside systems
78
79 External system calls wait until you answer them, so you decide what the outside world says, and when.
80
81 ```typescript
82 // packages/domain/test/fraud.test.ts
83 import { it } from "@effect/vitest";
84 import { Story } from "@alchemy.run/domain/Story";
85 import { Account } from "../src/Account/Account.aggregate.ts";
86 import { MoneyDeposited } from "../src/Account/DepositMoney.command.ts";
87 import { AccountFrozen } from "../src/Account/FreezeAccount.command.ts";
88 import { AccountOpened } from "../src/Account/OpenAccount.command.ts";
89 import { MoneyWithdrawn, WithdrawMoney } from "../src/Account/WithdrawMoney.command.ts";
90 import { customer, system } from "../src/Actor.ts";
91 import * as Layer from "effect/Layer";
92 import { Bank, BankHandlers } from "../src/Bank.model.ts";
93 import { MemoryLedgerStore } from "../src/Ledger/LedgerStore.ts";
94 import { CurrentActor } from "../src/CurrentActor.context.ts";
95 import { CustomerId } from "../src/Customer/Customer.id.ts";
96 import { FraudCheck } from "../src/Fraud/FraudCheck.external.ts";
97 import { Payments } from "../src/Settlement/Payments.external.ts";
98
99 const story = Story.make(Bank, {
100 layer: BankHandlers.pipe(Layer.provide(MemoryLedgerStore)),
101 stub: [FraudCheck, Payments],
102 });
103 const account = Account.ref("a-1");
104
105 it.effect("a risky withdrawal freezes the account", () =>
106 story(
107 Story.given(
108 account,
109 new AccountOpened({ customerId: CustomerId.make("c-1"), owner: "sam" }),
110 new MoneyDeposited({ amount: 90_000, balanceAfter: 90_000 }),
111 ),
112 Story.provide(CurrentActor, customer("c-1")),
113 Story.when(account, new WithdrawMoney({ amount: 60_000 })),
114 Story.then(account, new MoneyWithdrawn({ amount: 60_000, balanceAfter: 30_000 })),
115 Story.call(FraudCheck.score, { accountId: account.id, amount: 60_000 }),
116 Story.succeed(FraudCheck.score, { risk: 0.95 }),
117 Story.then(account, new AccountFrozen({ reason: "fraud risk 0.95", by: system("FraudReview") })),
118 ),
119 );
120 ```
121
122 A story checks its answers like an adapter's: a value the operation's schema rejects fails the policy, and so do arguments the policy sends that the schema rejects. See [Calls are checked against the schemas](/domain/external-system#calls-are-checked-against-the-schemas).
123
124 ## Answer several calls
125
126 `succeed` answers the only call waiting on an operation. When several are waiting, name each one as you expect it, and answer it by name:
127
128 ```typescript
129 Story.call("a-1", FraudCheck.score, { accountId: a1.id }),
130 Story.call("a-2", FraudCheck.score, { accountId: a2.id }),
131 Story.succeed("a-2", FraudCheck.score, { risk: 0.1 }),
132 Story.succeed("a-1", FraudCheck.score, { risk: 0.95 }),
133 ```
134
135 Every call needs a `call` step before it's answered, so a story always checks what was sent. Each `call` step matches one call, the earliest made. A `succeed` without a name fails if more than one call is waiting, so a story never answers the wrong one.
136
137 ## Fail a call
138
139 An operation can declare the error its vendor answers with when it refuses ([Declare its errors](/domain/external-system#declare-its-errors)). `Story.fail` answers a waiting call with that error, so a story can test the branch where the vendor says no. It finds the call the way `succeed` does, and only the operation's declared error type-checks:
140
141 ```typescript
142 Story.call(Payments.refund, { settlementId: "st_1" }),
143 Story.fail(Payments.refund, new RefundDeclined({ reason: "card-closed" })),
144 ```
145
146 When the operation declares several errors, `fail` takes any one of them, so a story can test each branch.
147
148 `Story.die` fails a call with a defect instead, as when the connection to the vendor breaks:
149
150 ```typescript
151 Story.call(Payments.refund, { settlementId: "st_1" }),
152 Story.die(Payments.refund, new Error("socket closed")),
153 ```
154
155 ## Assert real calls
156
157 An external system you don't stub is called for real, through its adapter. Provide the adapter's Layer to the story; the story's type requires it.
158
159 ```typescript
160 const story = Story.make(Bank, {
161 layer: BankHandlers.pipe(Layer.provide(MemoryLedgerStore)),
162 stub: [FraudCheck],
163 });
164
165 it.effect("refunds through the real payments adapter", () =>
166 story(
167 Story.when(account, new RecordSettlement({ settlementId: "st_1", amount: 500 })),
168 Story.then(account, new SettlementOnClosedAccount({ settlementId: "st_1", amount: 500 })),
169 Story.call(Payments.refund, { settlementId: "st_1", amount: 500 }),
170 Story.returned(Payments.refund, { refundId: "re_st_1" }),
171 ).pipe(Effect.provide(StripePayments)),
172 );
173 ```
174
175 The story records every real call. `call` checks what a call was sent, and `returned` checks what it returned. `failed` checks a declared error instead, and `died` a defect. Like a stubbed call, each real call needs its `call` step first, and a story fails if no step asserts how a real call ended. The story waits for real calls to finish before each step.
176
177 ## Run the same tests against every adapter
178
179 An external system often has several adapters: the vendor's, an in-memory fake for tests, a no-op for a dev stage. An adapter is a Layer for the system's service, so one set of tests can run against each of them, and the fake can't drift from the vendor.
180
181 ```typescript
182 // packages/server/test/Sms.test.ts
183 import { describe, expect, it } from "@effect/vitest";
184 import * as Effect from "effect/Effect";
185 import { Sms, Undeliverable } from "@bank/domain/Messaging/Sms.external";
186 import { FakeSms } from "../src/Messaging/FakeSms.ts";
187 import { TwilioSms } from "../src/Messaging/TwilioSms.ts";
188
189 for (const [adapter, layer] of [["Twilio", TwilioSms], ["fake", FakeSms]] as const) {
190 describe(`Sms: ${adapter}`, () => {
191 it.effect("counts the segments", () =>
192 Effect.gen(function* () {
193 const sms = yield* Sms;
194 const sent = yield* sms.send({ to: "+15550100", body: "x".repeat(200) });
195 expect(sent.segments).toBe(2);
196 }).pipe(Effect.provide(layer)),
197 );
198
199 it.effect("refuses a landline", () =>
200 Effect.gen(function* () {
201 const sms = yield* Sms;
202 const error = yield* sms.send({ to: "+15550199", body: "hi" }).pipe(Effect.flip);
203 expect(error).toEqual(new Undeliverable({ reason: "landline" }));
204 }).pipe(Effect.provide(layer)),
205 );
206 });
207 }
208 ```
209
210 Every call through a `toLayer` adapter is also checked against the operation's schemas, so an adapter that returns a value or error the declaration rejects fails the test with an `ExternalSystemSchemaError`.
211
212 ## Move the clock
213
214 A story's clock starts at `2026-01-01T00:00:00Z`, and `Story.clock` moves it to an ISO string, epoch milliseconds or a `DateTime`. The clock only moves forward. A `clock` step with only `provide` steps before it may set any time; after that, a time earlier than the current one fails the story. `Story.advance("1 day")` moves it forward by a duration instead of to a time. Commands are stamped with it, so time-based rules like a daily limit are easy to test, and scheduled commands fire when it passes their time. See [Deadlines](/domain/deadlines).
215
216 ## Trust a passing story
217
218 A story fails if an event is committed and no `then` step checks it, if a command is rejected and no `rejected` step checks it, if a call is answered or asserted before a `call` step checks it, if a stubbed call is left waiting at the end, or if no step asserts how a real call ended. A passing story has accounted for every outcome.
219
220 :::note
221 Test what clients see through an Api in [Testing an Api](/domain/testing-apis).
222 :::