dsh-flakefinder 0.4.22 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,377 @@
1
+ /**
2
+ * 测试框架适配器与注册表:覆盖 vitest / jest / pytest / node:test,
3
+ * 支持 monorepo 向上查找 node_modules、workspace .venv 自动探测、
4
+ * 精准过滤、关闭覆盖率与顺序打乱(shuffle + seed)。
5
+ * 全程 argv 数组、无 shell,避免 npx 下载与命令注入。
6
+ *
7
+ * @module dsh-flakefinder/adapters
8
+ */
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { assertTarget } from './config.js';
14
+ const MAX_SEED = 2147483647;
15
+ /** 从 cwd 向上逐级查找本地 node_modules 里的 CLI 入口(适配 monorepo hoisted 依赖)。 */
16
+ export function findLocalModuleEntry(cwd, ...parts) {
17
+ let current = path.resolve(cwd);
18
+ while (true) {
19
+ const candidate = path.join(current, ...parts);
20
+ if (fs.existsSync(candidate))
21
+ return candidate;
22
+ const parent = path.dirname(current);
23
+ if (parent === current)
24
+ return null;
25
+ current = parent;
26
+ }
27
+ }
28
+ /** 在 cwd 中查找 pytest 配置文件路径。 */
29
+ export function findPytestConfig(cwd) {
30
+ const pytestIni = path.join(cwd, 'pytest.ini');
31
+ if (fs.existsSync(pytestIni))
32
+ return pytestIni;
33
+ const toxIni = path.join(cwd, 'tox.ini');
34
+ if (fs.existsSync(toxIni))
35
+ return toxIni;
36
+ const pyproject = path.join(cwd, 'pyproject.toml');
37
+ if (fs.existsSync(pyproject)) {
38
+ try {
39
+ if (/\[tool\.pytest(\.ini_options)?\]/.test(fs.readFileSync(pyproject, 'utf8')))
40
+ return pyproject;
41
+ }
42
+ catch {
43
+ // 读不了就当没有配置,继续探测 setup.cfg。
44
+ }
45
+ }
46
+ const setupCfg = path.join(cwd, 'setup.cfg');
47
+ if (!fs.existsSync(setupCfg))
48
+ return null;
49
+ try {
50
+ return /\[tool:pytest\]/.test(fs.readFileSync(setupCfg, 'utf8')) ? setupCfg : null;
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ }
56
+ function venvPythonCandidates(venvRoot, platform) {
57
+ if (platform === 'win32') {
58
+ return [path.join(venvRoot, 'Scripts', 'python.exe')];
59
+ }
60
+ return [
61
+ path.join(venvRoot, 'bin', 'python'),
62
+ path.join(venvRoot, 'bin', 'python3'),
63
+ ];
64
+ }
65
+ function existingVenvPython(venvRoot, platform) {
66
+ for (const candidate of venvPythonCandidates(venvRoot, platform)) {
67
+ if (fs.existsSync(candidate))
68
+ return candidate;
69
+ }
70
+ return null;
71
+ }
72
+ /**
73
+ * 解析 pytest 使用的 Python 解释器路径及来源。
74
+ * 当用户未显式配置 pythonPath / DSH_FLAKEFINDER_PYTHON 时,按顺序自动探测:
75
+ * VIRTUAL_ENV -> 向上查找 .venv / venv -> 平台默认 python / python3。
76
+ */
77
+ export function resolvePythonPathInfo(cwd, cfg, runtime) {
78
+ const env = runtime?.env ?? process.env;
79
+ const platform = runtime?.platform ?? process.platform;
80
+ if (cfg?.pythonPathExplicit === true && typeof cfg.pythonPath === 'string' && cfg.pythonPath.trim() !== '') {
81
+ return { pythonPath: cfg.pythonPath.trim(), source: 'explicit' };
82
+ }
83
+ if (cfg === undefined) {
84
+ const envPy = env.DSH_FLAKEFINDER_PYTHON?.trim();
85
+ if (envPy)
86
+ return { pythonPath: envPy, source: 'explicit' };
87
+ }
88
+ const virtualEnv = env.VIRTUAL_ENV?.trim();
89
+ if (virtualEnv) {
90
+ const found = existingVenvPython(virtualEnv, platform);
91
+ if (found !== null)
92
+ return { pythonPath: found, source: 'virtual-env' };
93
+ }
94
+ let current = path.resolve(cwd);
95
+ while (true) {
96
+ for (const dirName of ['.venv', 'venv']) {
97
+ const found = existingVenvPython(path.join(current, dirName), platform);
98
+ if (found !== null)
99
+ return { pythonPath: found, source: 'workspace-venv' };
100
+ }
101
+ const parent = path.dirname(current);
102
+ if (parent === current)
103
+ break;
104
+ current = parent;
105
+ }
106
+ const fallback = typeof cfg?.pythonPath === 'string' && cfg.pythonPath.trim() !== ''
107
+ ? cfg.pythonPath.trim()
108
+ : (platform === 'win32' ? 'python' : 'python3');
109
+ return { pythonPath: fallback, source: 'default' };
110
+ }
111
+ /** 解析 pytest 使用的 Python 解释器路径。 */
112
+ export function resolvePythonPath(cwd, cfg, runtime) {
113
+ return resolvePythonPathInfo(cwd, cfg, runtime).pythonPath;
114
+ }
115
+ function validateTestName(raw) {
116
+ if (raw === undefined)
117
+ return undefined;
118
+ const trimmed = raw.trim();
119
+ if (trimmed === '')
120
+ throw new Error('testName 不能为空字符串。');
121
+ if (trimmed.startsWith('-'))
122
+ throw new Error('testName 不能以 - 开头:' + raw);
123
+ return trimmed;
124
+ }
125
+ function resolveShuffleSeed(options) {
126
+ const enableShuffle = options?.shuffle === true || (options?.shuffle === undefined && options?.seed !== undefined);
127
+ if (!enableShuffle)
128
+ return undefined;
129
+ if (options?.seed !== undefined) {
130
+ if (typeof options.seed !== 'number' || !Number.isFinite(options.seed) || !Number.isInteger(options.seed)) {
131
+ throw new Error('seed 必须是整数。');
132
+ }
133
+ if (options.seed < 0 || options.seed > MAX_SEED) {
134
+ throw new Error('seed 必须在 0-' + String(MAX_SEED) + ' 之间。');
135
+ }
136
+ return options.seed;
137
+ }
138
+ return crypto.randomInt(1, MAX_SEED);
139
+ }
140
+ function toPosixTarget(target) {
141
+ return target.replace(/\\/g, '/');
142
+ }
143
+ const vitestAdapter = {
144
+ id: 'vitest',
145
+ reportKind: 'json',
146
+ priority: 10,
147
+ requireLocalOnExplicit: true,
148
+ detect(cwd) {
149
+ return findLocalModuleEntry(cwd, 'node_modules', 'vitest', 'vitest.mjs');
150
+ },
151
+ missingMessage(cwd) {
152
+ return 'framework=vitest,但在 ' + cwd + ' 下找不到 node_modules/vitest/vitest.mjs。请先安装 vitest(例如 pnpm add -D vitest)。';
153
+ },
154
+ buildPlan({ cwd, target, runIndex, token, options }) {
155
+ const entry = this.detect(cwd);
156
+ if (entry === null)
157
+ throw new Error('未找到本地 vitest 入口:node_modules/vitest/vitest.mjs');
158
+ const normalizedTarget = toPosixTarget(target);
159
+ const testName = validateTestName(options?.testName);
160
+ const noCoverage = options?.noCoverage !== false;
161
+ const seed = resolveShuffleSeed(options);
162
+ const reportPath = path.join(os.tmpdir(), 'dsh-flakefinder-vitest-' + process.pid + '-' + String(runIndex) + '-' + token + '.json');
163
+ const argv = [process.execPath, entry, 'run', normalizedTarget, '--reporter=json', '--outputFile', reportPath];
164
+ if (noCoverage)
165
+ argv.push('--coverage.enabled=false');
166
+ if (seed !== undefined)
167
+ argv.push('--sequence.shuffle', '--sequence.seed=' + String(seed));
168
+ if (testName !== undefined)
169
+ argv.push('-t', testName);
170
+ return {
171
+ framework: 'vitest',
172
+ reportKind: 'json',
173
+ reportPath,
174
+ argv,
175
+ label: 'vitest run ' + normalizedTarget,
176
+ target: normalizedTarget,
177
+ ...(seed !== undefined ? { seed } : {}),
178
+ };
179
+ },
180
+ };
181
+ const jestAdapter = {
182
+ id: 'jest',
183
+ reportKind: 'json',
184
+ priority: 20,
185
+ requireLocalOnExplicit: true,
186
+ detect(cwd) {
187
+ return findLocalModuleEntry(cwd, 'node_modules', 'jest', 'bin', 'jest.js');
188
+ },
189
+ missingMessage(cwd) {
190
+ return 'framework=jest,但在 ' + cwd + ' 下找不到 node_modules/jest/bin/jest.js。请先安装 jest。';
191
+ },
192
+ buildPlan({ cwd, target, runIndex, token, options }) {
193
+ const entry = this.detect(cwd);
194
+ if (entry === null)
195
+ throw new Error('未找到本地 jest 入口:node_modules/jest/bin/jest.js');
196
+ const normalizedTarget = toPosixTarget(target);
197
+ const testName = validateTestName(options?.testName);
198
+ const noCoverage = options?.noCoverage !== false;
199
+ const seed = resolveShuffleSeed(options);
200
+ const useRunInBand = (options?.concurrency ?? 1) <= 1 && seed === undefined;
201
+ const reportPath = path.join(os.tmpdir(), 'dsh-flakefinder-jest-' + process.pid + '-' + String(runIndex) + '-' + token + '.json');
202
+ const argv = [process.execPath, entry];
203
+ if (useRunInBand)
204
+ argv.push('--runInBand');
205
+ argv.push('--json', '--outputFile', reportPath);
206
+ if (noCoverage)
207
+ argv.push('--coverage=false');
208
+ if (seed !== undefined)
209
+ argv.push('--randomize', '--seed=' + String(seed));
210
+ if (testName !== undefined)
211
+ argv.push('-t', testName);
212
+ argv.push(normalizedTarget);
213
+ return {
214
+ framework: 'jest',
215
+ reportKind: 'json',
216
+ reportPath,
217
+ argv,
218
+ label: 'jest run ' + normalizedTarget,
219
+ target: normalizedTarget,
220
+ ...(seed !== undefined ? { seed } : {}),
221
+ };
222
+ },
223
+ };
224
+ const pytestAdapter = {
225
+ id: 'pytest',
226
+ aliases: ['py'],
227
+ reportKind: 'junit',
228
+ priority: 30,
229
+ detect(cwd) {
230
+ return findPytestConfig(cwd);
231
+ },
232
+ buildPlan({ cwd, target, runIndex, token, pythonPath, options }) {
233
+ const testName = validateTestName(options?.testName);
234
+ const explicit = options?.pythonPathExplicit ?? (pythonPath !== undefined);
235
+ const resolvedPython = explicit && pythonPath !== undefined && pythonPath.trim() !== ''
236
+ ? pythonPath.trim()
237
+ : (pythonPath === undefined && options?.pythonPathExplicit === undefined
238
+ ? resolvePythonPath(cwd)
239
+ : resolvePythonPath(cwd, { pythonPath: pythonPath ?? '', pythonPathExplicit: false }));
240
+ const reportPath = path.join(os.tmpdir(), 'dsh-flakefinder-pytest-' + process.pid + '-' + String(runIndex) + '-' + token + '.xml');
241
+ const argv = [resolvedPython, '-m', 'pytest', target, '-q', '--junitxml=' + reportPath];
242
+ if (testName !== undefined)
243
+ argv.push('-k', testName);
244
+ return {
245
+ framework: 'pytest',
246
+ reportKind: 'junit',
247
+ reportPath,
248
+ argv,
249
+ label: 'pytest ' + target,
250
+ target,
251
+ };
252
+ },
253
+ };
254
+ const nodeAdapter = {
255
+ id: 'node',
256
+ aliases: ['node:test'],
257
+ reportKind: 'tap',
258
+ priority: 40,
259
+ detect() {
260
+ return process.execPath;
261
+ },
262
+ buildPlan({ target, options }) {
263
+ const testName = validateTestName(options?.testName);
264
+ const argv = [process.execPath, '--test', '--test-reporter=tap'];
265
+ if (testName !== undefined)
266
+ argv.push('--test-name-pattern=' + testName);
267
+ argv.push(target);
268
+ return {
269
+ framework: 'node',
270
+ reportKind: 'tap',
271
+ reportPath: '',
272
+ argv,
273
+ label: 'node --test ' + target,
274
+ target,
275
+ };
276
+ },
277
+ };
278
+ const registry = new Map();
279
+ const aliasMap = new Map();
280
+ /** 注册一个测试框架适配器(覆盖同 id 适配器并更新别名映射)。 */
281
+ export function registerAdapter(adapter) {
282
+ registry.set(adapter.id, adapter);
283
+ aliasMap.set(adapter.id, adapter.id);
284
+ if (adapter.aliases !== undefined) {
285
+ for (const alias of adapter.aliases) {
286
+ aliasMap.set(alias.toLowerCase(), adapter.id);
287
+ }
288
+ }
289
+ }
290
+ /** 按框架 id 获取适配器。 */
291
+ export function getAdapter(id) {
292
+ const found = registry.get(id);
293
+ if (found === undefined)
294
+ throw new Error('未注册的测试框架适配器:' + id);
295
+ return found;
296
+ }
297
+ /** 返回按 auto 优先级排序的所有已注册适配器。 */
298
+ export function listAdapters() {
299
+ return [...registry.values()].sort((a, b) => a.priority - b.priority);
300
+ }
301
+ registerAdapter(vitestAdapter);
302
+ registerAdapter(jestAdapter);
303
+ registerAdapter(pytestAdapter);
304
+ registerAdapter(nodeAdapter);
305
+ /** 解析 framework 参数(含别名 node:test -> node、py -> pytest);非法值抛中文错误。 */
306
+ export function readFramework(raw) {
307
+ if (raw === undefined || raw === null)
308
+ return 'auto';
309
+ if (typeof raw === 'string') {
310
+ const normalized = raw.trim().toLowerCase();
311
+ if (normalized === 'auto')
312
+ return 'auto';
313
+ const mapped = aliasMap.get(normalized);
314
+ if (mapped !== undefined)
315
+ return mapped;
316
+ }
317
+ throw new Error('framework 只支持 auto / vitest / jest / pytest / node,收到:' + String(raw));
318
+ }
319
+ /** 在 cwd 里探测本地框架 CLI 入口;显式指定时缺失会给出中文指引。 */
320
+ export function detectFramework(cwd, requested) {
321
+ if (requested !== 'auto') {
322
+ const adapter = getAdapter(requested);
323
+ if (adapter.requireLocalOnExplicit && adapter.detect(cwd) === null) {
324
+ throw new Error(adapter.missingMessage ? adapter.missingMessage(cwd) : '未找到本地 ' + requested + ' 框架入口。');
325
+ }
326
+ return requested;
327
+ }
328
+ for (const adapter of listAdapters()) {
329
+ if (adapter.detect(cwd) !== null)
330
+ return adapter.id;
331
+ }
332
+ return 'node';
333
+ }
334
+ /** 构建一次测试运行的执行计划。runIndex 仅用于给临时报告文件命名。 */
335
+ export function buildPlan(cwd, target, requested, runIndex, pythonPath, options) {
336
+ const safeTarget = assertTarget(target);
337
+ const framework = detectFramework(cwd, requested);
338
+ const token = crypto.randomBytes(6).toString('hex');
339
+ const adapter = getAdapter(framework);
340
+ return adapter.buildPlan({
341
+ cwd,
342
+ target: safeTarget,
343
+ runIndex,
344
+ token,
345
+ pythonPath,
346
+ options,
347
+ });
348
+ }
349
+ /** 汇总当前工作区可用的测试框架与解释器环境,供 flaky_health 自检使用。 */
350
+ export function detectEnvironment(cwd, cfg) {
351
+ const vitestPath = vitestAdapter.detect(cwd);
352
+ const jestPath = jestAdapter.detect(cwd);
353
+ const pytestConfig = pytestAdapter.detect(cwd);
354
+ const pythonInfo = resolvePythonPathInfo(cwd, cfg);
355
+ const defaultFramework = detectFramework(cwd, 'auto');
356
+ return {
357
+ cwd,
358
+ defaultFramework,
359
+ nodeVersion: process.version,
360
+ nodePath: process.execPath,
361
+ vitest: { available: vitestPath !== null, entryPath: vitestPath },
362
+ jest: { available: jestPath !== null, entryPath: jestPath },
363
+ pytest: {
364
+ configFound: pytestConfig !== null,
365
+ configPath: pytestConfig,
366
+ pythonPath: pythonInfo.pythonPath,
367
+ pythonSource: pythonInfo.source,
368
+ },
369
+ frameworks: {
370
+ vitest: vitestPath,
371
+ jest: jestPath,
372
+ pytestConfig,
373
+ pythonPath: pythonInfo.pythonPath,
374
+ node: process.version,
375
+ },
376
+ };
377
+ }
package/lib/args.d.ts CHANGED
@@ -1,21 +1,6 @@
1
1
  /**
2
- * 测试框架探测与 argv 构建:直接调用本地 node_modules 里的 CLI 入口,
3
- * 全程 argv 数组、无 shell,避免 npx 下载与命令注入。
2
+ * 测试框架探测与 argv 构建(向后兼容门面,具体实现已拆入 adapters.ts)。
4
3
  *
5
4
  * @module dsh-flakefinder/args
6
5
  */
7
- export type Framework = 'auto' | 'vitest' | 'jest' | 'pytest' | 'node';
8
- export type ReportKind = 'json' | 'tap' | 'junit';
9
- export interface TestPlan {
10
- framework: Exclude<Framework, 'auto'>;
11
- reportKind: ReportKind;
12
- reportPath: string;
13
- argv: string[];
14
- label: string;
15
- }
16
- /** 解析 framework 参数;非法值抛中文错误。 */
17
- export declare function readFramework(raw: unknown): Framework;
18
- /** 在 cwd 里探测本地框架 CLI 入口;显式指定时缺失会给出中文指引。 */
19
- export declare function detectFramework(cwd: string, requested: Framework): Exclude<Framework, 'auto'>;
20
- /** 构建一次测试运行的执行计划。runIndex 仅用于给临时报告文件命名。 */
21
- export declare function buildPlan(cwd: string, target: string, requested: Framework, runIndex: number, pythonPath?: string): TestPlan;
6
+ export { buildPlan, detectEnvironment, detectFramework, findLocalModuleEntry, findPytestConfig, getAdapter, listAdapters, readFramework, registerAdapter, resolvePythonPath, resolvePythonPathInfo, type AdapterContext, type ConcreteFramework, type EnvironmentDetection, type Framework, type FrameworkAdapter, type PlanBuildOptions, type PythonPathSource, type PythonResolution, type ReportKind, type TestPlan, } from './adapters.js';
package/lib/args.js CHANGED
@@ -1,116 +1,6 @@
1
1
  /**
2
- * 测试框架探测与 argv 构建:直接调用本地 node_modules 里的 CLI 入口,
3
- * 全程 argv 数组、无 shell,避免 npx 下载与命令注入。
2
+ * 测试框架探测与 argv 构建(向后兼容门面,具体实现已拆入 adapters.ts)。
4
3
  *
5
4
  * @module dsh-flakefinder/args
6
5
  */
7
- import fs from 'node:fs';
8
- import os from 'node:os';
9
- import path from 'node:path';
10
- import crypto from 'node:crypto';
11
- import { assertTarget } from './config.js';
12
- /** 解析 framework 参数;非法值抛中文错误。 */
13
- export function readFramework(raw) {
14
- if (raw === undefined || raw === null)
15
- return 'auto';
16
- if (raw === 'auto' || raw === 'vitest' || raw === 'jest' || raw === 'pytest' || raw === 'node')
17
- return raw;
18
- throw new Error('framework 只支持 auto / vitest / jest / pytest / node,收到:' + String(raw));
19
- }
20
- function localEntry(cwd, ...parts) {
21
- const full = path.join(cwd, ...parts);
22
- return fs.existsSync(full) ? full : null;
23
- }
24
- function hasPytestConfig(cwd) {
25
- if (fs.existsSync(path.join(cwd, 'pytest.ini')) || fs.existsSync(path.join(cwd, 'tox.ini')))
26
- return true;
27
- const pyproject = path.join(cwd, 'pyproject.toml');
28
- if (fs.existsSync(pyproject)) {
29
- try {
30
- if (/\[tool\.pytest(\.ini_options)?\]/.test(fs.readFileSync(pyproject, 'utf8')))
31
- return true;
32
- }
33
- catch {
34
- // 读不了就当没有配置,继续探测 setup.cfg。
35
- }
36
- }
37
- const setupCfg = path.join(cwd, 'setup.cfg');
38
- if (!fs.existsSync(setupCfg))
39
- return false;
40
- try {
41
- return /\[tool:pytest\]/.test(fs.readFileSync(setupCfg, 'utf8'));
42
- }
43
- catch {
44
- return false;
45
- }
46
- }
47
- /** 在 cwd 里探测本地框架 CLI 入口;显式指定时缺失会给出中文指引。 */
48
- export function detectFramework(cwd, requested) {
49
- const vitest = localEntry(cwd, 'node_modules', 'vitest', 'vitest.mjs');
50
- const jest = localEntry(cwd, 'node_modules', 'jest', 'bin', 'jest.js');
51
- if (requested !== 'auto') {
52
- if (requested === 'vitest' && vitest === null) {
53
- throw new Error('framework=vitest,但在 ' + cwd + ' 下找不到 node_modules/vitest/vitest.mjs。请先安装 vitest(例如 pnpm add -D vitest)。');
54
- }
55
- if (requested === 'jest' && jest === null) {
56
- throw new Error('framework=jest,但在 ' + cwd + ' 下找不到 node_modules/jest/bin/jest.js。请先安装 jest。');
57
- }
58
- return requested;
59
- }
60
- if (vitest !== null)
61
- return 'vitest';
62
- if (jest !== null)
63
- return 'jest';
64
- if (hasPytestConfig(cwd))
65
- return 'pytest';
66
- return 'node';
67
- }
68
- /** 构建一次测试运行的执行计划。runIndex 仅用于给临时报告文件命名。 */
69
- export function buildPlan(cwd, target, requested, runIndex, pythonPath = 'python') {
70
- const safeTarget = assertTarget(target);
71
- const framework = detectFramework(cwd, requested);
72
- const token = crypto.randomBytes(6).toString('hex');
73
- if (framework === 'vitest') {
74
- const entry = localEntry(cwd, 'node_modules', 'vitest', 'vitest.mjs');
75
- if (entry === null)
76
- throw new Error('未找到本地 vitest 入口:node_modules/vitest/vitest.mjs');
77
- const reportPath = path.join(os.tmpdir(), 'dsh-flakefinder-vitest-' + process.pid + '-' + String(runIndex) + '-' + token + '.json');
78
- return {
79
- framework,
80
- reportKind: 'json',
81
- reportPath,
82
- argv: [process.execPath, entry, 'run', safeTarget, '--reporter=json', '--outputFile', reportPath],
83
- label: 'vitest run ' + safeTarget,
84
- };
85
- }
86
- if (framework === 'jest') {
87
- const entry = localEntry(cwd, 'node_modules', 'jest', 'bin', 'jest.js');
88
- if (entry === null)
89
- throw new Error('未找到本地 jest 入口:node_modules/jest/bin/jest.js');
90
- const reportPath = path.join(os.tmpdir(), 'dsh-flakefinder-jest-' + process.pid + '-' + String(runIndex) + '-' + token + '.json');
91
- return {
92
- framework,
93
- reportKind: 'json',
94
- reportPath,
95
- argv: [process.execPath, entry, '--runInBand', '--json', '--outputFile', reportPath, safeTarget],
96
- label: 'jest run ' + safeTarget,
97
- };
98
- }
99
- if (framework === 'pytest') {
100
- const reportPath = path.join(os.tmpdir(), 'dsh-flakefinder-pytest-' + process.pid + '-' + String(runIndex) + '-' + token + '.xml');
101
- return {
102
- framework,
103
- reportKind: 'junit',
104
- reportPath,
105
- argv: [pythonPath, '-m', 'pytest', safeTarget, '-q', '--junitxml=' + reportPath],
106
- label: 'pytest ' + safeTarget,
107
- };
108
- }
109
- return {
110
- framework: 'node',
111
- reportKind: 'tap',
112
- reportPath: '',
113
- argv: [process.execPath, '--test', '--test-reporter=tap', safeTarget],
114
- label: 'node --test ' + safeTarget,
115
- };
116
- }
6
+ export { buildPlan, detectEnvironment, detectFramework, findLocalModuleEntry, findPytestConfig, getAdapter, listAdapters, readFramework, registerAdapter, resolvePythonPath, resolvePythonPathInfo, } from './adapters.js';
package/lib/classify.d.ts CHANGED
@@ -1,11 +1,30 @@
1
1
  /**
2
- * 多轮结果聚合与 flaky 判定:纯函数,便于单测边界。
2
+ * 多轮结果聚合、flaky 判定与根因诊断:纯函数,零运行时依赖,便于单测边界。
3
3
  *
4
4
  * @module dsh-flakefinder/classify
5
5
  */
6
- import type { NormalizedRun } from './parse.js';
6
+ import type { NormalizedRun, TestErrorInfo } from './parse.js';
7
7
  export type RunVerdict = 'stable-pass' | 'stable-fail' | 'flaky' | 'empty' | 'skipped';
8
8
  export type TestVerdict = 'stable-pass' | 'stable-fail' | 'flaky' | 'skipped';
9
+ export type TimelineSymbol = 'P' | 'F' | 'S' | 'T' | '-';
10
+ export type FlakePattern = 'cold-start' | 'state-leak' | 'timeout-race' | 'order-dependent' | 'teardown-crash' | 'intermittent';
11
+ export interface AggregateRunInput {
12
+ index: number;
13
+ report: NormalizedRun | null;
14
+ durationMs: number;
15
+ error?: string;
16
+ timedOut?: boolean;
17
+ truncated?: boolean;
18
+ seed?: number;
19
+ }
20
+ export interface ErrorCluster {
21
+ fingerprint: string;
22
+ count: number;
23
+ type?: string;
24
+ message: string;
25
+ sampleStack?: string;
26
+ runIndices: number[];
27
+ }
9
28
  export interface RunRecord {
10
29
  runIndex: number;
11
30
  success: boolean;
@@ -13,6 +32,10 @@ export interface RunRecord {
13
32
  failed: number;
14
33
  skipped: number;
15
34
  durationMs: number;
35
+ timedOut?: boolean;
36
+ truncated?: boolean;
37
+ seed?: number;
38
+ error?: string;
16
39
  }
17
40
  export interface TestRecord {
18
41
  id: string;
@@ -23,6 +46,14 @@ export interface TestRecord {
23
46
  skips: number;
24
47
  failureRate: number;
25
48
  verdict: TestVerdict;
49
+ timeline: TimelineSymbol[];
50
+ passDurationAvgMs: number | null;
51
+ failDurationAvgMs: number | null;
52
+ maxDurationMs: number;
53
+ p95DurationMs: number;
54
+ errorClusters: ErrorCluster[];
55
+ patterns: FlakePattern[];
56
+ failedSeeds?: number[];
26
57
  }
27
58
  export interface DetectionResult {
28
59
  runs: RunRecord[];
@@ -33,16 +64,35 @@ export interface DetectionResult {
33
64
  skippedCount: number;
34
65
  tests: TestRecord[];
35
66
  durationMs: number;
67
+ confidence95MaxFlakeRate?: number;
36
68
  }
37
- export declare function aggregate(runs: Array<{
38
- index: number;
39
- report: NormalizedRun | null;
40
- durationMs: number;
41
- error?: string;
42
- }>): DetectionResult;
43
- /** 结果里需要写入历史的 flaky 用例。 */
44
- export declare function flakyTests(result: DetectionResult): Array<{
69
+ export interface FlakyTestSummary {
45
70
  file: string;
46
71
  name: string;
47
72
  failureRate: number;
48
- }>;
73
+ patterns?: FlakePattern[];
74
+ topError?: string;
75
+ }
76
+ /** 脱敏常见密钥/令牌,避免写入诊断报告或堆栈采样。 */
77
+ export declare function redactSecrets(text: string): string;
78
+ /** 归一化错误文本中的动态噪声(时间戳、UUID、地址、端口、临时路径、数字差异),用于聚类指纹。 */
79
+ export declare function normalizeErrorForFingerprint(text: string): string;
80
+ /** 计算结构化错误指纹,用于把同一根因的多次失败归为一簇。 */
81
+ export declare function errorFingerprint(error: TestErrorInfo): string;
82
+ /** 压缩代表堆栈:脱敏、保留头部与关键业务帧,限制行数(默认 12 行)与字符数(默认 1200)。 */
83
+ export declare function compactStack(stack: string, maxLines?: number, maxChars?: number): string;
84
+ /** 根因模式的简明中文说明。 */
85
+ export declare function patternLabel(pattern: FlakePattern): string;
86
+ /**
87
+ * 连续全通过 runs 轮后,在指定置信度下的最大潜在偶发失败率上界(百分比,保留 1 位小数)。
88
+ * 公式:1 - (1 - confidence)^(1 / runs)
89
+ */
90
+ export declare function confidenceUpperBound(runs: number, confidence?: number): number;
91
+ /**
92
+ * 在指定置信度下,要将潜在偶发失败率压到 maxFlakeRate 以下所需的最少全通过轮数。
93
+ * maxFlakeRate 同时支持百分比(如 5 表示 5%、10 表示 10%)与比例(如 0.05、0.1)。
94
+ */
95
+ export declare function runsNeededForThreshold(maxFlakeRate: number, confidence?: number): number;
96
+ export declare function aggregate(runs: AggregateRunInput[]): DetectionResult;
97
+ /** 结果里需要写入历史的 flaky 用例(保持精简,不携带大堆栈)。 */
98
+ export declare function flakyTests(result: DetectionResult): FlakyTestSummary[];