-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrun-tests.js
More file actions
207 lines (176 loc) · 7.63 KB
/
run-tests.js
File metadata and controls
207 lines (176 loc) · 7.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/**
* @fileoverview Скрипт для запуска всех тестов проекта
*
* Находит и запускает все .test.ts файлы в папке lib/tests
* Использует tsx для поддержки TypeScript импортов
*
* @module run-tests
*/
import { run } from 'node:test';
import { spec } from 'node:test/reporters';
import { glob } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createWriteStream, mkdirSync } from 'node:fs';
import { PassThrough } from 'node:stream';
const __dirname = dirname(fileURLToPath(import.meta.url));
// Установка UTF-8 кодировки для Windows
if (process.platform === 'win32') {
process.stdout.setDefaultEncoding('utf8');
process.stderr.setDefaultEncoding('utf8');
}
// Проверка флага --coverage
const useCoverage = process.argv.includes('--coverage');
// Проверка флага --templates (только тесты шаблонов)
const onlyTemplates = process.argv.includes('--templates');
// Проверка флага --unit (только unit тесты)
const onlyUnit = process.argv.includes('--unit');
// Проверка флага --integration (только integration тесты)
const onlyIntegration = process.argv.includes('--integration');
// Проверка флага --pattern (фильтр по имени файла)
const patternIndex = process.argv.indexOf('--pattern');
const filePattern = patternIndex !== -1
? process.argv[patternIndex + 1]
: process.argv.find(arg => arg.endsWith('.test.ts'));
async function runTests() {
const testFiles = [];
// Ищем все .test.ts файлы в lib/tests (unit и integration)
const testDir = join(__dirname, 'lib', 'tests');
// Ищем все .test.ts файлы в lib/templates (шаблоны)
const templatesDir = join(__dirname, 'lib', 'templates');
// Ищем тесты в lib/bot-generator (core утилиты генератора)
const botGeneratorDir = join(__dirname, 'lib', 'bot-generator');
// Ищем тесты в client (UI утилиты)
const clientDir = join(__dirname, 'client');
/**
* Добавляет файлы из директории в список тестов с фильтрацией по паттерну
* @param {string} dir - Директория для поиска
* @param {string} pattern - Glob-паттерн
*/
async function collectTests(dir, pattern) {
try {
for await (const file of glob(pattern, { cwd: dir })) {
const fullPath = join(dir, file);
if (filePattern && !fullPath.includes(filePattern)) continue;
if (!testFiles.includes(fullPath)) testFiles.push(fullPath);
}
} catch {
// директория может не существовать — игнорируем
}
}
try {
// Ищем unit тесты в lib/tests
if (!onlyTemplates && !onlyIntegration) {
for await (const file of glob('**/*.test.ts', { cwd: testDir })) {
const fullPath = join(testDir, file);
if (filePattern && !fullPath.includes(filePattern)) continue;
testFiles.push(fullPath);
}
// Ищем phase-тесты (test-phase*.ts)
for await (const file of glob('test-phase*.ts', { cwd: testDir })) {
const fullPath = join(testDir, file);
if (filePattern && !fullPath.includes(filePattern)) continue;
if (!testFiles.includes(fullPath)) testFiles.push(fullPath);
}
}
// Ищем тесты шаблонов в lib/templates
if (!onlyTemplates && !onlyUnit) {
for await (const file of glob('**/*.test.ts', { cwd: templatesDir })) {
const fullPath = join(templatesDir, file);
if (filePattern && !fullPath.includes(filePattern)) continue;
testFiles.push(fullPath);
}
} else if (onlyTemplates) {
// Только тесты шаблонов
for await (const file of glob('**/*.test.ts', { cwd: templatesDir })) {
const fullPath = join(templatesDir, file);
if (filePattern && !fullPath.includes(filePattern)) continue;
testFiles.push(fullPath);
}
} else if (onlyUnit) {
// Только unit тесты
for await (const file of glob('**/*.test.ts', { cwd: testDir })) {
const fullPath = join(testDir, file);
if (filePattern && !fullPath.includes(filePattern)) continue;
testFiles.push(fullPath);
}
for await (const file of glob('test-phase*.ts', { cwd: testDir })) {
const fullPath = join(testDir, file);
if (filePattern && !fullPath.includes(filePattern)) continue;
if (!testFiles.includes(fullPath)) testFiles.push(fullPath);
}
} else if (onlyIntegration) {
// Только integration тесты
for await (const file of glob('integration/**/*.test.ts', { cwd: testDir })) {
const fullPath = join(testDir, file);
if (filePattern && !fullPath.includes(filePattern)) continue;
testFiles.push(fullPath);
}
}
// Всегда добавляем тесты из lib/bot-generator и client (если не onlyIntegration)
if (!onlyIntegration) {
await collectTests(botGeneratorDir, '**/*.test.ts');
await collectTests(clientDir, '**/*.test.ts');
}
} catch (error) {
console.error('Ошибка поиска тестов:', error.message);
process.exit(1);
}
if (testFiles.length === 0) {
console.log('Тесты не найдены');
process.exit(0);
}
console.log(`Найдено тестов: ${testFiles.length}`);
console.log('Запуск тестов...\n');
// Создаём поток для записи в файл
const outputDir = join(__dirname, 'test-results');
mkdirSync(outputDir, { recursive: true });
const logStream = createWriteStream(join(outputDir, 'output.txt'), { encoding: 'utf8' });
// PassThrough stream для дублирования вывода
const teeStream = new PassThrough();
// Перенаправляем вывод из teeStream в консоль и файл
teeStream.on('data', (chunk) => {
process.stdout.write(chunk);
logStream.write(chunk);
});
// Запускаем тесты через tsx для поддержки TypeScript
const execArgv = ['--import', 'tsx/esm'];
// Добавляем флаг для покрытия если запрошено
if (useCoverage) {
console.log('📊 Сбор метрик покрытия...\n');
}
const testRun = run({
files: testFiles,
timeout: 300000, // 5 минут на тест для обработки долгой генерации кода
execArgv
});
// Выводим результаты через tee-поток
testRun.compose(new spec()).pipe(teeStream);
// Ждём завершения
return new Promise((resolve, reject) => {
testRun.on('test:fail', (data) => {
console.error(`\n❌ Тест не прошёл: ${data.name}`);
if (data.details?.error) {
console.error(data.details.error);
}
});
testRun.on('test:pass', () => {
// Тест прошёл
});
testRun.on('end', () => {
console.log('\n✅ Все тесты завершены');
console.log('📄 Результаты сохранены в test-results/output.txt');
logStream.close();
teeStream.end();
resolve(undefined);
});
testRun.on('error', (error) => {
console.error('Ошибка выполнения тестов:', error);
reject(error);
});
});
}
runTests().catch(error => {
console.error('Ошибка выполнения тестов:', error);
process.exit(1);
});