Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tools.test.ts

72 lines2.2 KB

1import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterEach, describe, expect, it } from 'vitest'
5import { createReviewTools } from './tools'
6​
7const bases: Array<string> = []
8​
9async function makeWorktree() {
10 const base = await mkdtemp(join(tmpdir(), 'ai-review-tools-'))
11 const root = join(base, 'work')
12 await mkdir(root)
13 bases.push(base)
14 return root
16​
17afterEach(async () => {
18 const pending = bases.splice(0)
19 for (const base of pending) {
20 await rm(base, { recursive: true, force: true })
21 }
22})
23​
24function toolNamed(tools: ReturnType<typeof createReviewTools>, name: string) {
25 const tool = tools.find((item) => item.name === name)
26 if (tool === undefined) throw new Error(`missing tool ${name}`)
27 return tool
29​
30async function runExecute(tool: ReturnType<typeof toolNamed>, args: unknown) {
31 const execute = tool.execute
32 if (execute === undefined) throw new Error(`${tool.name} has no execute`)
33 return execute(args)
35​
36describe('createReviewTools', () => {
37 it('returns read_file and edit_file with execute', async () => {
38 const root = await makeWorktree()
39 const tools = createReviewTools({ worktreeRoot: root })
40 expect(tools.map((tool) => tool.name)).toEqual(['read_file', 'edit_file'])
41 for (const tool of tools) {
42 expect(tool.execute).toEqual(expect.any(Function))
43 }
44 })
45​
46 it('read_file returns the UTF-8 file contents', async () => {
47 const root = await makeWorktree()
48 await writeFile(join(root, 'note.txt'), 'hello from worktree')
49 const tools = createReviewTools({ worktreeRoot: root })
50​
51 const result = await runExecute(toolNamed(tools, 'read_file'), {
52 path: 'note.txt',
53 })
54​
55 expect(result).toEqual({ content: 'hello from worktree' })
56 })
57​
58 it('edit_file writes the file and returns ok', async () => {
59 const root = await makeWorktree()
60 const tools = createReviewTools({ worktreeRoot: root })
61​
62 const result = await runExecute(toolNamed(tools, 'edit_file'), {
63 path: 'note.txt',
64 content: 'patched by review',
65 })
66​
67 expect(result).toEqual({ ok: true })
68 expect(await readFile(join(root, 'note.txt'), 'utf8')).toBe(
69 'patched by review',
70 )
71 })
72})