|
| 1 | +# Test Fixtures Guide |
| 2 | + |
| 3 | +## Temporary Directory Fixture |
| 4 | + |
| 5 | +The `tmpdir` function in `fixture/fixture.ts` creates temporary directories for tests with automatic cleanup. |
| 6 | + |
| 7 | +### Basic Usage |
| 8 | + |
| 9 | +```typescript |
| 10 | +import { tmpdir } from "./fixture/fixture" |
| 11 | + |
| 12 | +test("example", async () => { |
| 13 | + await using tmp = await tmpdir() |
| 14 | + // tmp.path is the temp directory path |
| 15 | + // automatically cleaned up when test ends |
| 16 | +}) |
| 17 | +``` |
| 18 | + |
| 19 | +### Options |
| 20 | + |
| 21 | +- `git?: boolean` - Initialize a git repo with a root commit |
| 22 | +- `config?: Partial<Config.Info>` - Write an `opencode.json` config file |
| 23 | +- `init?: (dir: string) => Promise<T>` - Custom setup function, returns value accessible as `tmp.extra` |
| 24 | +- `dispose?: (dir: string) => Promise<T>` - Custom cleanup function |
| 25 | + |
| 26 | +### Examples |
| 27 | + |
| 28 | +**Git repository:** |
| 29 | + |
| 30 | +```typescript |
| 31 | +await using tmp = await tmpdir({ git: true }) |
| 32 | +``` |
| 33 | + |
| 34 | +**With config file:** |
| 35 | + |
| 36 | +```typescript |
| 37 | +await using tmp = await tmpdir({ |
| 38 | + config: { model: "test/model", username: "testuser" }, |
| 39 | +}) |
| 40 | +``` |
| 41 | + |
| 42 | +**Custom initialization (returns extra data):** |
| 43 | + |
| 44 | +```typescript |
| 45 | +await using tmp = await tmpdir<string>({ |
| 46 | + init: async (dir) => { |
| 47 | + await Bun.write(path.join(dir, "file.txt"), "content") |
| 48 | + return "extra data" |
| 49 | + }, |
| 50 | +}) |
| 51 | +// Access extra data via tmp.extra |
| 52 | +console.log(tmp.extra) // "extra data" |
| 53 | +``` |
| 54 | + |
| 55 | +**With cleanup:** |
| 56 | + |
| 57 | +```typescript |
| 58 | +await using tmp = await tmpdir({ |
| 59 | + init: async (dir) => { |
| 60 | + const specialDir = path.join(dir, "special") |
| 61 | + await fs.mkdir(specialDir) |
| 62 | + return specialDir |
| 63 | + }, |
| 64 | + dispose: async (dir) => { |
| 65 | + // Custom cleanup logic |
| 66 | + await fs.rm(path.join(dir, "special"), { recursive: true }) |
| 67 | + }, |
| 68 | +}) |
| 69 | +``` |
| 70 | + |
| 71 | +### Returned Object |
| 72 | + |
| 73 | +- `path: string` - Absolute path to the temp directory (realpath resolved) |
| 74 | +- `extra: T` - Value returned by the `init` function |
| 75 | +- `[Symbol.asyncDispose]` - Enables automatic cleanup via `await using` |
| 76 | + |
| 77 | +### Notes |
| 78 | + |
| 79 | +- Directories are created in the system temp folder with prefix `opencode-test-` |
| 80 | +- Use `await using` for automatic cleanup when the variable goes out of scope |
| 81 | +- Paths are sanitized to strip null bytes (defensive fix for CI environments) |
0 commit comments