fork of hey-api/openapi-ts because I need some additional things
1import fs from 'node:fs';
2import path from 'node:path';
3
4import { py } from '../../index';
5import { snapshotsDir, tmpDir } from '../constants';
6
7function getCallerFile(): string {
8 const error = new Error();
9 const stack = (error.stack ?? '').split('\n');
10 const callerLine = stack.find((line) => line.includes('.test.ts'));
11 if (!callerLine) {
12 throw new Error('Could not find test file in stack trace');
13 }
14 const match = callerLine.match(/\(([^)]+)\)/) || callerLine.match(/at (.+):\d+:\d+/);
15 if (!match?.[1]) {
16 throw new Error('Could not extract file path');
17 }
18 return match[1];
19}
20
21function ensureInitFiles(dir: string, rootDir: string): void {
22 let current = dir;
23 while (current.startsWith(rootDir) && current !== rootDir) {
24 const initPath = path.join(current, '__init__.py');
25 if (!fs.existsSync(initPath)) {
26 fs.writeFileSync(initPath, '');
27 }
28 current = path.dirname(current);
29 }
30
31 const rootInit = path.join(rootDir, '__init__.py');
32 if (!fs.existsSync(rootInit)) {
33 fs.writeFileSync(rootInit, '');
34 }
35}
36
37export async function assertPrintedMatchesSnapshot(
38 file: py.SourceFile,
39 filename: string,
40): Promise<void> {
41 const result = py.createPrinter().printFile(file);
42
43 const caller = getCallerFile();
44 const relPath = path
45 .relative(path.join(process.cwd(), 'src', 'ts-python', '__tests__'), caller)
46 .replace(/\.test\.ts$/, '');
47 const outputPath = path.join(tmpDir, relPath, filename);
48 const outputDir = path.dirname(outputPath);
49
50 fs.mkdirSync(outputDir, { recursive: true });
51 fs.writeFileSync(outputPath, result);
52
53 ensureInitFiles(outputDir, tmpDir);
54
55 const snapshotPath = path.join(snapshotsDir, relPath, filename);
56
57 const snapshotDir = path.dirname(snapshotPath);
58 fs.mkdirSync(snapshotDir, { recursive: true });
59 ensureInitFiles(snapshotDir, snapshotsDir);
60
61 await expect(result).toMatchFileSnapshot(snapshotPath);
62}