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
| 1 | --- |
| 2 | title: Testing an Api |
| 3 | description: Test what each client may do and see, in process, over HTTP, and against a real deployment. |
| 4 | --- |
| 5 | |
| 6 | Stories check your model. To check what a client can do and see through an Api, sessions and all, call the Api with a real client. |
| 7 | |
| 8 | ## Sign sessions in tests |
| 9 | |
| 10 | ```typescript |
| 11 | // packages/server/test/session.ts |
| 12 | import type { Actor } from "@bank/domain/Actor"; |
| 13 | import { sessionClient } from "@bank/domain/Session.middleware"; |
| 14 | import * as Effect from "effect/Effect"; |
| 15 | import * as Layer from "effect/Layer"; |
| 16 | import * as Redacted from "effect/Redacted"; |
| 17 | import { SessionKey, signSession } from "../src/Session.ts"; |
| 18 | |
| 19 | /** A fixed key in place of the deployed stage's random one. */ |
| 20 | export const SessionKeyTest = Layer.succeed( |
| 21 | SessionKey, |
| 22 | Effect.succeed(Redacted.make("a-test-session-key-a-test-session-key")), |
| 23 | ); |
| 24 | |
| 25 | /** Client middleware that sends a session signed for `actor`. */ |
| 26 | export const signedInAs = (actor: Actor) => |
| 27 | Layer.unwrap(Effect.map(signSession(actor), sessionClient)); |
| 28 | ``` |
| 29 | |
| 30 | The bank only accepts sessions it signed. Tests sign their own with a fixed key, so `signedInAs` gives a client any actor without going through sign-in. |
| 31 | |
| 32 | ## Test in process |
| 33 | |
| 34 | `clientInProcess` calls the Api in the same process, through its real middleware. Sign each client in with `signedInAs`, and check every outcome a caller can get. |
| 35 | |
| 36 | ```typescript |
| 37 | // packages/server/test/access.test.ts |
| 38 | import { expect, it } from "@effect/vitest"; |
| 39 | import * as Domain from "@alchemy.run/domain"; |
| 40 | import * as Effect from "effect/Effect"; |
| 41 | import * as Fiber from "effect/Fiber"; |
| 42 | import * as Layer from "effect/Layer"; |
| 43 | import type * as Scope from "effect/Scope"; |
| 44 | import * as Stream from "effect/Stream"; |
| 45 | import { AccountId } from "@bank/domain/Account/Account.id"; |
| 46 | import { Bank, BankHandlers } from "@bank/domain/Bank.model"; |
| 47 | import { MemoryLedgerStore } from "@bank/domain/Ledger/LedgerStore"; |
| 48 | import { CustomerId } from "@bank/domain/Customer/Customer.id"; |
| 49 | import { CustomerApi } from "@bank/domain/CustomerApi.api"; |
| 50 | import { SiftFraudCheck } from "../src/Fraud/SiftFraudCheck.ts"; |
| 51 | import { MfaChallengeLive } from "../src/MfaChallenge.ts"; |
| 52 | import { SessionLive } from "../src/Session.ts"; |
| 53 | import { agent, customer } from "@bank/domain/Actor"; |
| 54 | import { sessionClient } from "@bank/domain/Session.middleware"; |
| 55 | import { StripePayments } from "../src/Settlement/StripePayments.ts"; |
| 56 | import { SupportApi } from "@bank/domain/SupportApi.api"; |
| 57 | import { register } from "./flows.ts"; |
| 58 | import { SessionKeyTest, signedInAs } from "./session.ts"; |
| 59 | |
| 60 | const World = Layer.mergeAll(SessionLive, MfaChallengeLive).pipe( |
| 61 | Layer.provideMerge(Bank.layer(BankHandlers)), |
| 62 | Layer.provide(Layer.mergeAll(Domain.InMemory, SiftFraudCheck, StripePayments, MemoryLedgerStore)), |
| 63 | Layer.provideMerge(SessionKeyTest), |
| 64 | ); |
| 65 | |
| 66 | const asCustomer = (id: string) => |
| 67 | CustomerApi.clientInProcess.pipe(Effect.provide(signedInAs(customer(id)))); |
| 68 | const asAgent = (id: string) => |
| 69 | SupportApi.clientInProcess.pipe(Effect.provide(signedInAs(agent(id)))); |
| 70 | |
| 71 | // Each test gets a fresh bank. |
| 72 | const inBank = <A, E>(effect: Effect.Effect<A, E, Scope.Scope | Layer.Success<typeof World>>) => |
| 73 | effect.pipe(Effect.scoped, Effect.provide(World)); |
| 74 | |
| 75 | it.live("only the owner, or an agent, reads an account", () => |
| 76 | inBank( |
| 77 | Effect.gen(function* () { |
| 78 | const sam = yield* asCustomer("c-1"); |
| 79 | const alex = yield* asCustomer("c-2"); |
| 80 | const support = yield* asAgent("support-7"); |
| 81 | const accountId = yield* register(sam, "c-1", "sam"); |
| 82 | |
| 83 | expect(yield* sam.AccountSummary.get(accountId)).toMatchObject({ balance: 0 }); |
| 84 | expect(yield* support.AccountSummary.get(accountId)).toMatchObject({ balance: 0 }); |
| 85 | expect((yield* alex.AccountSummary.get(accountId).pipe(Effect.flip))._tag).toBe("NotOwner"); |
| 86 | expect( |
| 87 | (yield* alex.CustomerDashboard.get(CustomerId.make("c-1")).pipe(Effect.flip))._tag, |
| 88 | ).toBe("Forbidden"); |
| 89 | }), |
| 90 | ), |
| 91 | ); |
| 92 | |
| 93 | it.live("a request without a session is unauthorized", () => |
| 94 | inBank( |
| 95 | Effect.gen(function* () { |
| 96 | const nobody = yield* CustomerApi.clientInProcess.pipe(Effect.provide(sessionClient("nobody"))); |
| 97 | const refused = yield* nobody.AccountSummary.get(AccountId.make("c-1-main")).pipe(Effect.flip); |
| 98 | expect(refused._tag).toBe("Unauthorized"); |
| 99 | }), |
| 100 | ), |
| 101 | ); |
| 102 | |
| 103 | it.live("a watch ends with NotOwner when the account changes hands", () => |
| 104 | inBank( |
| 105 | Effect.gen(function* () { |
| 106 | const sam = yield* asCustomer("c-1"); |
| 107 | const alex = yield* asCustomer("c-2"); |
| 108 | const support = yield* asAgent("support-7"); |
| 109 | const accountId = yield* register(sam, "c-1", "sam"); |
| 110 | yield* register(alex, "c-2", "alex"); |
| 111 | |
| 112 | const watched = yield* sam.AccountSummary.watch(accountId).pipe( |
| 113 | Stream.result, |
| 114 | Stream.take(2), |
| 115 | Stream.runCollect, |
| 116 | Effect.forkChild, |
| 117 | ); |
| 118 | yield* Effect.sleep("50 millis"); |
| 119 | yield* support.ChangeOwner(accountId, { customerId: CustomerId.make("c-2") }); |
| 120 | |
| 121 | const [first, second] = yield* Fiber.join(watched); |
| 122 | expect(first).toMatchObject({ _tag: "Success", success: { state: { balance: 0 } } }); |
| 123 | expect(second).toMatchObject({ _tag: "Failure", failure: { _tag: "NotOwner" } }); |
| 124 | }), |
| 125 | ), |
| 126 | ); |
| 127 | ``` |
| 128 | |
| 129 | `register` is a helper from the example: it registers a customer, then watches their dashboard until the main account opens. |
| 130 | |
| 131 | ## Test over HTTP |
| 132 | |
| 133 | Serve the Api on a real HTTP server, and call it with the same client a script would use. |
| 134 | |
| 135 | ```typescript |
| 136 | // packages/server/test/HttpTransport.test.ts |
| 137 | import { Bank, BankHandlers } from "@bank/domain/Bank.model"; |
| 138 | import { CustomerId } from "@bank/domain/Customer/Customer.id"; |
| 139 | import { CustomerDashboard } from "@bank/domain/Customer/CustomerDashboard.view"; |
| 140 | import { CustomerApi } from "@bank/domain/CustomerApi.api"; |
| 141 | import { MemoryLedgerStore } from "@bank/domain/Ledger/LedgerStore"; |
| 142 | import { sessionClient } from "@bank/domain/Session.middleware"; |
| 143 | import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; |
| 144 | import { expect, it } from "@effect/vitest"; |
| 145 | import * as Domain from "@alchemy.run/domain"; |
| 146 | import * as Effect from "effect/Effect"; |
| 147 | import * as HttpServer from "effect/http/HttpServer"; |
| 148 | import * as Layer from "effect/Layer"; |
| 149 | import * as Option from "effect/Option"; |
| 150 | import * as Stream from "effect/Stream"; |
| 151 | import { SiftFraudCheck } from "../src/Fraud/SiftFraudCheck.ts"; |
| 152 | import { MfaChallengeLive } from "../src/MfaChallenge.ts"; |
| 153 | import { SessionLive } from "../src/Session.ts"; |
| 154 | import { StripePayments } from "../src/Settlement/StripePayments.ts"; |
| 155 | import { register } from "./flows.ts"; |
| 156 | |
| 157 | // The Worker's HTTP surface (`yield* CustomerApi`, its `fetch`) on a real HTTP server, over the in-memory platform. |
| 158 | const Ports = Layer.mergeAll(SiftFraudCheck, StripePayments, MemoryLedgerStore); |
| 159 | const World = Layer.mergeAll(SessionLive, MfaChallengeLive).pipe( |
| 160 | Layer.provideMerge( |
| 161 | Bank.layer(BankHandlers).pipe(Layer.provide(Layer.mergeAll(Ports, Domain.InMemory))), |
| 162 | ), |
| 163 | Layer.provideMerge(SessionKeyTest), |
| 164 | ); |
| 165 | |
| 166 | // A test server on a random port, plus an HttpClient pointed at it. |
| 167 | const Served = Layer.unwrap(Effect.map(CustomerApi, (api) => HttpServer.serve()(api.fetch))).pipe( |
| 168 | Layer.provideMerge(NodeHttpServer.layerTest), |
| 169 | Layer.provide(World), |
| 170 | ); |
| 171 | |
| 172 | // The test server serves the Api at its root; its HttpClient already targets the server. |
| 173 | const Client = Layer.mergeAll(Domain.protocolHttp(""), signedInAs(customer("c-1"))).pipe( |
| 174 | Layer.provide(SessionKeyTest), |
| 175 | ); |
| 176 | |
| 177 | it.live("the CustomerApi round-trips over HTTP, including a streamed watch", () => |
| 178 | Effect.gen(function* () { |
| 179 | const sam = yield* CustomerApi.client; |
| 180 | const accountId = yield* register(sam, "c-1", "sam"); |
| 181 | yield* sam.DepositMoney(accountId, { amount: 70 }); |
| 182 | const dashboard = yield* sam.CustomerDashboard.watch(CustomerId.make("c-1")).pipe( |
| 183 | Stream.map(({ state }) => state), |
| 184 | Stream.filter((d) => d !== null && CustomerDashboard.computed.totalBalance(d) === 70), |
| 185 | Stream.runHead, |
| 186 | ); |
| 187 | expect(accountId as string).toBe("c-1-main"); |
| 188 | expect(Option.getOrThrow(dashboard)).toMatchObject({ name: "sam" }); |
| 189 | }).pipe(Effect.provide(Client.pipe(Layer.provideMerge(Served))), Effect.scoped), |
| 190 | ); |
| 191 | ``` |
| 192 | |
| 193 | ## Test a deployment |
| 194 | |
| 195 | The example's integration test deploys the whole bank with `@alchemy.run/test/Bun` and drives it over the network. A client that isn't a browser can set headers on its WebSockets, so it sends `Authorization` on each live read, as it does on every call. |
| 196 | |
| 197 | ```typescript |
| 198 | // packages/domain/test/liveClient.ts |
| 199 | import * as Domain from "@alchemy.run/domain"; |
| 200 | import * as Effect from "effect/Effect"; |
| 201 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 202 | import * as HttpClient from "effect/http/HttpClient"; |
| 203 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 204 | import * as Layer from "effect/Layer"; |
| 205 | import * as Socket from "effect/socket/Socket"; |
| 206 | import { CustomerApi } from "../src/CustomerApi.api.ts"; |
| 207 | import { sessionClient } from "../src/Session.middleware.ts"; |
| 208 | |
| 209 | /** Sign a customer in through the bank's `/api/session` route; returns the signed session token. */ |
| 210 | const signIn = Effect.fn(function* (url: string, customerId: string) { |
| 211 | const response = yield* HttpClient.execute( |
| 212 | HttpClientRequest.post(`${url}/api/session`).pipe( |
| 213 | HttpClientRequest.bodyJsonUnsafe({ customerId }), |
| 214 | ), |
| 215 | ).pipe(Effect.provide(FetchHttpClient.layer)); |
| 216 | return ((yield* response.json) as { readonly token: string }).token; |
| 217 | }); |
| 218 | |
| 219 | export const customerClient = Effect.fn(function* (url: string, customerId: string) { |
| 220 | const token = yield* signIn(url, customerId); |
| 221 | // Bun's WebSocket accepts headers; a browser sends its session cookie instead. |
| 222 | const webSockets = Layer.succeed( |
| 223 | Socket.WebSocketConstructor, |
| 224 | (socketUrl, protocols) => |
| 225 | new WebSocket(socketUrl, { |
| 226 | protocols, |
| 227 | headers: { authorization: `Bearer ${token}` }, |
| 228 | } as unknown as string[]), |
| 229 | ); |
| 230 | return yield* CustomerApi.client.pipe( |
| 231 | Effect.provide( |
| 232 | Layer.mergeAll(Domain.protocolWebSocket(`${url}/api`), sessionClient(token)).pipe( |
| 233 | Layer.provide(Layer.mergeAll(FetchHttpClient.layer, webSockets)), |
| 234 | ), |
| 235 | ), |
| 236 | ); |
| 237 | }); |
| 238 | ``` |
| 239 | |
| 240 | The whole test is in [`test/integ.test.ts`](https://github.com/alchemy-run/alchemy/blob/main/examples/cloudflare-domain/test/integ.test.ts). |
| 241 | |
| 242 | :::note |
| 243 | Check the model itself with [stories](/domain/testing-models). Sessions and middleware are covered in [Sessions and middleware](/domain/sessions). |
| 244 | ::: |