* Generic fixture management helper * Handles caching, reading, writing fixtures for any data type
( input: unknown, fixtureName: string, f: () => Promise<T>, )
| 40 | * Handles caching, reading, writing fixtures for any data type |
| 41 | */ |
| 42 | async function withFixture<T>( |
| 43 | input: unknown, |
| 44 | fixtureName: string, |
| 45 | f: () => Promise<T>, |
| 46 | ): Promise<T> { |
| 47 | if (!shouldUseVCR()) { |
| 48 | return await f() |
| 49 | } |
| 50 | |
| 51 | // Create hash of input for fixture filename |
| 52 | const hash = createHash('sha1') |
| 53 | .update(jsonStringify(input)) |
| 54 | .digest('hex') |
| 55 | .slice(0, 12) |
| 56 | const filename = join( |
| 57 | process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT ?? getCwd(), |
| 58 | `fixtures/${fixtureName}-${hash}.json`, |
| 59 | ) |
| 60 | |
| 61 | // Fetch cached fixture |
| 62 | try { |
| 63 | const cached = jsonParse( |
| 64 | await readFile(filename, { encoding: 'utf8' }), |
| 65 | ) as T |
| 66 | return cached |
| 67 | } catch (e: unknown) { |
| 68 | const code = getErrnoCode(e) |
| 69 | if (code !== 'ENOENT') { |
| 70 | throw e |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | if ((env.isCI || process.env.CI) && !isEnvTruthy(process.env.VCR_RECORD)) { |
| 75 | throw new Error( |
| 76 | `Fixture missing: ${filename}. Re-run tests with VCR_RECORD=1, then commit the result.`, |
| 77 | ) |
| 78 | } |
| 79 | |
| 80 | // Create & write new fixture |
| 81 | const result = await f() |
| 82 | |
| 83 | await mkdir(dirname(filename), { recursive: true }) |
| 84 | await writeFile(filename, jsonStringify(result, null, 2), { |
| 85 | encoding: 'utf8', |
| 86 | }) |
| 87 | |
| 88 | return result |
| 89 | } |
| 90 | |
| 91 | export async function withVCR( |
| 92 | messages: Message[], |
no test coverage detected