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

environment-version-probe.test.ts

214 lines6.4 KB

1import { afterEach, describe, expect, it, vi } from 'vitest'
2import {
3 chmod,
4 mkdtemp,
5 readFile,
6 realpath,
7 rm,
8 writeFile,
9} from 'node:fs/promises'
10import { delimiter, dirname, join } from 'node:path'
11import { tmpdir } from 'node:os'
12​
13import { createDefaultEnvironment } from '../src/environment.js'
14​
15let directory: string | undefined
16let pidFile: string | undefined
17let probePending = false
18​
19async function installShim(body: string) {
20 directory = await mkdtemp(join(tmpdir(), 'tanstack-version-probe-'))
21 pidFile = join(directory, 'probe.pid')
22 const script = join(directory, 'pnpm')
23 const contents = [
24 '#!/usr/bin/env node',
25 "import { writeFileSync } from 'node:fs'",
26 'writeFileSync(' + JSON.stringify(pidFile) + ', String(process.pid))',
27 'writeFileSync(' +
28 JSON.stringify(join(directory, 'cwd')) +
29 ', process.cwd())',
30 body,
31 ].join('\n')
32 await writeFile(join(directory, 'package.json'), '{"type":"module"}')
33 await writeFile(script, contents)
34 await chmod(script, 0o755)
35 if (process.platform === 'win32') {
36 await writeFile(
37 join(directory, 'pnpm.cmd'),
38 '@"' + process.execPath + '" "' + script + '" %*\r\n',
39 )
40 }
41 vi.stubEnv(
42 'PATH',
43 [directory, dirname(process.execPath), process.env.PATH ?? ''].join(
44 delimiter,
45 ),
46 )
47 return directory
49​
50afterEach(async () => {
51 vi.unstubAllEnvs()
52 if (pidFile && probePending) {
53 try {
54 const pid = Number(await readFile(pidFile, 'utf8'))
55 // Clean up only the child created by this fixture if an assertion failed.
56 try {
57 process.kill(pid, 'SIGKILL')
58 } catch {}
59 } catch {}
60 }
61 if (directory) {
62 try {
63 const pid = Number(
64 await readFile(join(directory, 'descendant.pid'), 'utf8'),
65 )
66 try {
67 process.kill(pid, 'SIGKILL')
68 } catch {}
69 } catch {}
70 await rm(directory, { recursive: true, force: true })
71 }
72 directory = undefined
73 pidFile = undefined
74})
75​
76async function probe(
77 environment: ReturnType<typeof createDefaultEnvironment>,
78 cwd: string,
79) {
80 probePending = true
81 try {
82 return await environment.getPackageManagerVersion?.('pnpm', cwd)
83 } finally {
84 probePending = false
85 }
87​
88describe('package-manager version subprocess', () => {
89 it('terminates descendants holding the probe pipes open', async () => {
90 const cwd = await installShim(
91 "const { spawn } = await import('node:child_process');" +
92 "const child = spawn(process.execPath, ['-e', " +
93 JSON.stringify(
94 "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)",
95 ) +
96 "], { stdio: ['ignore', 'inherit', 'inherit'] });" +
97 "writeFileSync('descendant.pid', String(child.pid)); setInterval(() => {}, 1000)",
98 )
99 const environment = createDefaultEnvironment()
100 const started = Date.now()
101 await expect(probe(environment, cwd)).resolves.toBeUndefined()
102 expect(Date.now() - started).toBeLessThan(23_000)
103 const pid = Number(await readFile(join(cwd, 'descendant.pid'), 'utf8'))
104 await expect
105 .poll(
106 () => {
107 try {
108 process.kill(pid, 0)
109 return false
110 } catch {
111 return true
112 }
113 },
114 { timeout: 2_000 },
115 )
116 .toBe(true)
117 // Remove the receipt so cleanup cannot target a later reused PID.
118 await rm(join(cwd, 'descendant.pid'))
119 expect(environment.getErrors()).toEqual([])
120 }, 30_000)
121​
122 it('cancels the owned probe tree before returning the fallback', async () => {
123 const cwd = await installShim(
124 "const { spawn } = await import('node:child_process');" +
125 "const child = spawn(process.execPath, ['-e', " +
126 JSON.stringify(
127 "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)",
128 ) +
129 "], { stdio: ['ignore', 'inherit', 'inherit'] });" +
130 "writeFileSync('descendant.pid', String(child.pid)); setInterval(() => {}, 1000)",
131 )
132 const controller = new AbortController()
133 const environment = createDefaultEnvironment(controller.signal)
134 const pending = probe(environment, cwd)
135 await expect
136 .poll(
137 async () => {
138 try {
139 await readFile(join(cwd, 'descendant.pid'), 'utf8')
140 return true
141 } catch {
142 return false
143 }
144 },
145 { timeout: 5_000 },
146 )
147 .toBe(true)
148 const descendant = Number(
149 await readFile(join(cwd, 'descendant.pid'), 'utf8'),
150 )
151 const started = Date.now()
152 controller.abort()
153 await expect(pending).resolves.toBeUndefined()
154 expect(Date.now() - started).toBeLessThan(7_000)
155 await expect
156 .poll(
157 () => {
158 try {
159 process.kill(descendant, 0)
160 return false
161 } catch {
162 return true
163 }
164 },
165 { timeout: 2_000 },
166 )
167 .toBe(true)
168 await rm(join(cwd, 'descendant.pid'))
169 expect(environment.getErrors()).toEqual([])
170 }, 25_000)
171​
172 it('does not launch a probe after cancellation', async () => {
173 const cwd = await installShim('setInterval(() => {}, 1000)')
174 const controller = new AbortController()
175 controller.abort()
176 await expect(
177 probe(createDefaultEnvironment(controller.signal), cwd),
178 ).resolves.toBeUndefined()
179 await expect(readFile(join(cwd, 'probe.pid'), 'utf8')).rejects.toThrow()
180 })
181​
182 it('reads and trims the version in the target project', async () => {
183 const cwd = await installShim(
184 "process.stdout.write(' 10.2.0 ' + String.fromCharCode(10))",
185 )
186 const environment = createDefaultEnvironment()
187 await expect(probe(environment, cwd)).resolves.toBe('10.2.0')
188 expect(await realpath(await readFile(join(cwd, 'cwd'), 'utf8'))).toBe(
189 await realpath(cwd),
190 )
191 expect(environment.getErrors()).toEqual([])
192 })
193​
194 it('stops a stalled optional probe and keeps the unknown-version fallback', async () => {
195 const cwd = await installShim('setInterval(() => {}, 1000)')
196 const environment = createDefaultEnvironment()
197 await expect(probe(environment, cwd)).resolves.toBeUndefined()
198 const pid = Number(await readFile(join(cwd, 'probe.pid'), 'utf8'))
199 await expect
200 .poll(
201 () => {
202 try {
203 process.kill(pid, 0)
204 return false
205 } catch {
206 return true
207 }
208 },
209 { timeout: 2_000 },
210 )
211 .toBe(true)
212 expect(environment.getErrors()).toEqual([])
213 }, 30_000)
214})