@nhonh/qabot 0.6.1 → 1.0.1

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.
@@ -2,8 +2,9 @@ import chalk from "chalk";
2
2
  import ora from "ora";
3
3
  import path from "node:path";
4
4
  import { writeFile, readFile } from "node:fs/promises";
5
- import { execSync } from "node:child_process";
6
- import { logger } from "../../core/logger.js";
5
+ import { execSync, spawn } from "node:child_process";
6
+ import Enquirer from "enquirer";
7
+ import { logger, formatMs } from "../../core/logger.js";
7
8
  import { loadConfig } from "../../core/config.js";
8
9
  import { analyzeProject } from "../../analyzers/project-analyzer.js";
9
10
  import { AIEngine } from "../../ai/ai-engine.js";
@@ -23,6 +24,14 @@ import {
23
24
  } from "../../utils/file-utils.js";
24
25
  import { ReportGenerator } from "../../reporter/report-generator.js";
25
26
 
27
+ const V = chalk.hex("#A78BFA");
28
+ const V2 = chalk.hex("#7C3AED");
29
+ const DIM = chalk.hex("#6B7280");
30
+ const W = chalk.hex("#F3F4F6");
31
+ const G = chalk.hex("#34D399");
32
+ const R = chalk.hex("#F87171");
33
+ const Y = chalk.hex("#FBBF24");
34
+
26
35
  const MAX_FIX_ATTEMPTS = 3;
27
36
 
28
37
  export function registerTestCommand(program) {
@@ -54,26 +63,25 @@ async function runTest(feature, options) {
54
63
  config.environments?.[options.env] || config.environments?.default;
55
64
  const baseUrl = options.url || envConfig?.url || "http://localhost:3000";
56
65
 
57
- logger.header("QABot \u2014 E2E Automation Test");
66
+ logger.header("E2E Automation Test");
58
67
  logger.blank();
59
- logger.info(`Feature: ${chalk.bold(feature || "all")}`);
60
- logger.info(`Target: ${chalk.bold.cyan(baseUrl)}`);
61
- logger.info(`Environment: ${chalk.bold(options.env)}`);
62
- logger.info(
63
- `Browser: ${options.headed ? "Headed (visible)" : "Headless"}`,
64
- );
68
+ console.log(DIM(" Feature: ") + W(feature || "all"));
69
+ console.log(DIM(" Target: ") + chalk.hex("#22D3EE")(baseUrl));
70
+ console.log(DIM(" Browser: ") + W(options.headed ? "Headed" : "Headless"));
65
71
  logger.blank();
66
- console.log(chalk.dim(` ${"\u2500".repeat(50)}`));
67
72
 
68
- const spinner = ora("Setting up Playwright...").start();
73
+ const spinner = ora({
74
+ text: V(" Setting up Playwright..."),
75
+ spinner: "dots",
76
+ }).start();
69
77
  try {
70
78
  await ensurePlaywright(projectDir);
71
79
  await ensureE2EStructure(projectDir);
72
80
  await writePlaywrightConfig(projectDir, config);
73
81
  await writeAuthHelper(projectDir, config);
74
- spinner.succeed("Playwright ready");
82
+ spinner.succeed(G(" Playwright ready"));
75
83
  } catch (err) {
76
- spinner.fail(`Playwright setup failed: ${err.message}`);
84
+ spinner.fail(R(` Setup failed: ${err.message}`));
77
85
  return;
78
86
  }
79
87
 
@@ -84,22 +92,15 @@ async function runTest(feature, options) {
84
92
  if (options.skipGen) {
85
93
  const existing = await findFiles(specDir, "*.spec.js");
86
94
  if (existing.length === 0) {
87
- logger.error(
88
- "No existing E2E specs found. Run without --skip-gen to generate.",
89
- );
95
+ logger.error("No existing E2E specs found. Run without --skip-gen.");
90
96
  return;
91
97
  }
92
98
  specFile = feature
93
99
  ? existing.find((f) => f.toLowerCase().includes(feature.toLowerCase()))
94
100
  : null;
95
- logger.info(
96
- `Running ${specFile ? path.basename(specFile) : "all"} existing specs`,
97
- );
98
101
  } else {
99
102
  if (!feature) {
100
- logger.error(
101
- "Feature name required for test generation. Usage: qabot test <feature>",
102
- );
103
+ logger.error("Feature name required. Usage: qabot test <feature>");
103
104
  return;
104
105
  }
105
106
 
@@ -112,9 +113,10 @@ async function runTest(feature, options) {
112
113
  return;
113
114
  }
114
115
 
115
- const spinner2 = ora(
116
- "AI is analyzing feature and generating E2E tests...",
117
- ).start();
116
+ const spinner2 = ora({
117
+ text: V(" AI analyzing feature..."),
118
+ spinner: "dots",
119
+ }).start();
118
120
 
119
121
  let sourceCode = "";
120
122
  if (featureConfig?.src) {
@@ -159,183 +161,225 @@ async function runTest(feature, options) {
159
161
  authProvider: config.auth?.provider || "none",
160
162
  useCases,
161
163
  });
162
-
163
164
  specFile = path.join(specDir, `${feature}.spec.js`);
164
165
  await writeFile(specFile, spec, "utf-8");
165
166
  spinner2.succeed(
166
- `E2E spec generated: ${chalk.underline(path.relative(projectDir, specFile))}`,
167
+ G(` E2E spec: ${chalk.underline(path.relative(projectDir, specFile))}`),
167
168
  );
168
169
  } catch (err) {
169
- spinner2.fail(`E2E generation failed: ${err.message}`);
170
+ spinner2.fail(R(` Generation failed: ${err.message}`));
170
171
  return;
171
172
  }
172
173
 
173
174
  if (options.fix !== false) {
174
- const aiForFix = ai;
175
-
176
175
  for (let attempt = 1; attempt <= MAX_FIX_ATTEMPTS; attempt++) {
177
176
  logger.blank();
178
- logger.step(
179
- attempt,
180
- MAX_FIX_ATTEMPTS,
181
- `Running E2E tests (attempt ${attempt})...`,
182
- );
177
+ logger.step(attempt, MAX_FIX_ATTEMPTS, `Attempt ${attempt}`);
178
+ logger.blank();
183
179
 
184
- const {
185
- exitCode,
186
- error: testError,
187
- stdout,
188
- } = runPlaywright(projectDir, specFile, options);
180
+ const result = await runPlaywrightStreaming(
181
+ projectDir,
182
+ specFile,
183
+ options,
184
+ baseUrl,
185
+ );
189
186
 
190
- if (exitCode === 0) {
191
- printPlaywrightSummary(stdout);
192
- logger.blank();
193
- logger.success(`E2E tests passed on attempt ${attempt}!`);
187
+ if (result.exitCode === 0) {
188
+ logger.summary(
189
+ result.passed,
190
+ result.failed,
191
+ result.skipped,
192
+ result.duration,
193
+ );
194
+ if (result.passed > 0)
195
+ logger.success(`E2E passed on attempt ${attempt}`);
194
196
  await generateE2EReport(
195
197
  projectDir,
196
198
  config,
197
199
  feature,
198
200
  options.env,
199
201
  baseUrl,
202
+ result,
200
203
  );
201
204
  return;
202
205
  }
203
206
 
204
207
  if (attempt >= MAX_FIX_ATTEMPTS) {
205
- printPlaywrightSummary(stdout || testError);
206
- logger.blank();
207
- logger.warn(
208
- `E2E tests still failing after ${MAX_FIX_ATTEMPTS} attempts.`,
208
+ logger.summary(
209
+ result.passed,
210
+ result.failed,
211
+ result.skipped,
212
+ result.duration,
209
213
  );
210
- logger.dim(` Review: cat ${path.relative(projectDir, specFile)}`);
211
- logger.dim(` Debug: qabot test ${feature} --headed`);
214
+ logger.warn(`Still failing after ${MAX_FIX_ATTEMPTS} attempts`);
215
+ logger.dim(`Review: cat ${path.relative(projectDir, specFile)}`);
216
+ logger.dim(`Debug: qabot test ${feature} --headed`);
212
217
  await generateE2EReport(
213
218
  projectDir,
214
219
  config,
215
220
  feature,
216
221
  options.env,
217
222
  baseUrl,
223
+ result,
218
224
  );
219
225
  return;
220
226
  }
221
227
 
222
- logger.dim(` ${extractFirstError(testError || stdout)}`);
223
- logger.step(attempt, MAX_FIX_ATTEMPTS, "AI is fixing E2E test...");
224
-
228
+ const fixSpinner = ora({
229
+ text: V(" AI fixing errors..."),
230
+ spinner: "dots",
231
+ }).start();
225
232
  try {
226
233
  const currentCode = await readFile(specFile, "utf-8");
227
- const fixedCode = await fixE2ESpec(
228
- aiForFix,
229
- currentCode,
230
- testError || stdout,
231
- {
232
- baseUrl,
233
- authProvider: config.auth?.provider,
234
- },
235
- );
234
+ const fixedCode = await fixE2ESpec(ai, currentCode, result.rawError, {
235
+ baseUrl,
236
+ authProvider: config.auth?.provider,
237
+ });
236
238
  await writeFile(specFile, fixedCode, "utf-8");
237
- logger.dim(" Fix applied. Re-running...");
239
+ fixSpinner.succeed(G(" Fix applied"));
238
240
  } catch (err) {
239
- logger.warn(` AI fix failed: ${err.message}`);
241
+ fixSpinner.fail(R(` Fix failed: ${err.message}`));
240
242
  break;
241
243
  }
242
244
  }
245
+ return;
243
246
  }
244
247
  }
245
248
 
246
249
  if (!specFile && !options.skipGen) return;
247
250
 
248
- logger.blank();
249
- logger.info("Running E2E tests...");
250
-
251
- const {
252
- exitCode,
253
- stdout,
254
- error: testError,
255
- } = runPlaywright(projectDir, specFile, options);
256
- printPlaywrightSummary(stdout || testError);
251
+ logger.section("Running E2E");
252
+ const result = await runPlaywrightStreaming(
253
+ projectDir,
254
+ specFile,
255
+ options,
256
+ baseUrl,
257
+ );
258
+ logger.summary(result.passed, result.failed, result.skipped, result.duration);
257
259
  await generateE2EReport(
258
260
  projectDir,
259
261
  config,
260
262
  feature || "all",
261
263
  options.env,
262
264
  baseUrl,
265
+ result,
263
266
  );
264
-
265
- if (exitCode !== 0) process.exit(1);
267
+ if (result.failed > 0) process.exit(1);
266
268
  }
267
269
 
268
- function runPlaywright(projectDir, specFile, options) {
269
- const configPath = path.join(projectDir, "e2e", "playwright.config.js");
270
- const parts = ["npx", "playwright", "test"];
271
- if (specFile)
272
- parts.push(path.relative(path.join(projectDir, "e2e"), specFile));
273
- parts.push(`--config="${configPath}"`);
274
- parts.push("--project=chromium");
275
- if (options.headed) parts.push("--headed");
276
-
277
- const env = {
278
- ...process.env,
279
- E2E_ENV: options.env || "default",
280
- FORCE_COLOR: "0",
281
- };
270
+ function runPlaywrightStreaming(projectDir, specFile, options, baseUrl) {
271
+ return new Promise((resolve) => {
272
+ const configPath = path.join(projectDir, "e2e", "playwright.config.js");
273
+ const args = ["playwright", "test"];
274
+ if (specFile)
275
+ args.push(path.relative(path.join(projectDir, "e2e"), specFile));
276
+ args.push(
277
+ `--config=${configPath}`,
278
+ "--project=chromium",
279
+ "--reporter=line",
280
+ );
281
+ if (options.headed) args.push("--headed");
282
282
 
283
- try {
284
- const stdout = execSync(parts.join(" "), {
283
+ const env = {
284
+ ...process.env,
285
+ E2E_ENV: options.env || "default",
286
+ BASE_URL: baseUrl,
287
+ FORCE_COLOR: "1",
288
+ };
289
+
290
+ const startTime = Date.now();
291
+ let stdout = "";
292
+ let stderr = "";
293
+ let passed = 0;
294
+ let failed = 0;
295
+ let skipped = 0;
296
+ let testIndex = 0;
297
+
298
+ const child = spawn("npx", args, {
285
299
  cwd: projectDir,
286
- stdio: "pipe",
287
- timeout: 120000,
288
300
  env,
289
- }).toString();
290
- return { exitCode: 0, stdout, error: "" };
291
- } catch (err) {
292
- return {
293
- exitCode: err.status || 1,
294
- stdout: err.stdout?.toString() || "",
295
- error: err.stderr?.toString() || err.stdout?.toString() || "",
296
- };
297
- }
301
+ stdio: ["pipe", "pipe", "pipe"],
302
+ });
303
+
304
+ child.stdout.on("data", (data) => {
305
+ const text = data.toString();
306
+ stdout += text;
307
+
308
+ for (const line of text.split("\n")) {
309
+ const trimmed = line.trim();
310
+ if (!trimmed) continue;
311
+
312
+ if (
313
+ trimmed.includes("\u2713") ||
314
+ trimmed.includes("passed") ||
315
+ trimmed.match(/\[.*\].*ok/i)
316
+ ) {
317
+ testIndex++;
318
+ passed++;
319
+ const name = extractTestName(trimmed);
320
+ logger.testResult(name, "passed", extractDuration(trimmed));
321
+ } else if (
322
+ trimmed.includes("\u2717") ||
323
+ trimmed.includes("failed") ||
324
+ trimmed.includes("FAIL")
325
+ ) {
326
+ testIndex++;
327
+ failed++;
328
+ const name = extractTestName(trimmed);
329
+ logger.testResult(name, "failed", extractDuration(trimmed));
330
+ } else if (trimmed.includes("skipped")) {
331
+ testIndex++;
332
+ skipped++;
333
+ const name = extractTestName(trimmed);
334
+ logger.testResult(name, "skipped", 0);
335
+ } else if (trimmed.match(/Running \d+ test/)) {
336
+ logger.dim(trimmed);
337
+ } else if (trimmed.includes("Error") || trimmed.includes("expect")) {
338
+ logger.dim(R(` ${trimmed.slice(0, 120)}`));
339
+ }
340
+ }
341
+ });
342
+
343
+ child.stderr.on("data", (data) => {
344
+ stderr += data.toString();
345
+ });
346
+
347
+ child.on("close", (exitCode) => {
348
+ const duration = Date.now() - startTime;
349
+ resolve({
350
+ exitCode: exitCode ?? 1,
351
+ passed,
352
+ failed,
353
+ skipped,
354
+ duration,
355
+ stdout,
356
+ stderr,
357
+ rawError: (stderr || stdout).slice(0, 4000),
358
+ tests: [],
359
+ });
360
+ });
361
+ });
298
362
  }
299
363
 
300
- function printPlaywrightSummary(output) {
301
- if (!output) return;
302
- const lines = output.split("\n");
303
- for (const line of lines) {
304
- const trimmed = line.trim();
305
- if (!trimmed) continue;
306
- if (trimmed.includes("\u2713") || trimmed.includes("passed")) {
307
- logger.success(trimmed);
308
- } else if (
309
- trimmed.includes("\u2717") ||
310
- trimmed.includes("failed") ||
311
- trimmed.includes("Error")
312
- ) {
313
- logger.error(trimmed);
314
- } else if (
315
- trimmed.includes("─") ||
316
- trimmed.includes("Running") ||
317
- trimmed.includes("test")
318
- ) {
319
- logger.dim(trimmed);
320
- }
321
- }
364
+ function extractTestName(line) {
365
+ const cleaned = line
366
+ .replace(/\u2713|\u2717|\u25CB/g, "")
367
+ .replace(/\[.*?\]/g, "")
368
+ .replace(/\(\d+(\.\d+)?[ms]+\)/g, "")
369
+ .replace(/›/g, " > ")
370
+ .replace(/\s+/g, " ")
371
+ .trim();
372
+ const parts = cleaned.split(" > ");
373
+ return parts[parts.length - 1] || cleaned;
322
374
  }
323
375
 
324
- function extractFirstError(output) {
325
- if (!output) return "Unknown error";
326
- const lines = output.split("\n").filter((l) => l.trim());
327
- const errorLine = lines.find(
328
- (l) =>
329
- l.includes("Error") ||
330
- l.includes("expect") ||
331
- l.includes("Timeout") ||
332
- l.includes("locator"),
333
- );
334
- return (
335
- errorLine?.trim().slice(0, 150) ||
336
- lines[0]?.trim().slice(0, 150) ||
337
- "Test failed"
338
- );
376
+ function extractDuration(line) {
377
+ const match = line.match(/\((\d+(?:\.\d+)?)(ms|s|m)\)/);
378
+ if (!match) return 0;
379
+ const val = parseFloat(match[1]);
380
+ if (match[2] === "s") return val * 1000;
381
+ if (match[2] === "m") return val * 60000;
382
+ return val;
339
383
  }
340
384
 
341
385
  function guessRoute(featureName) {
@@ -356,112 +400,67 @@ function guessRoute(featureName) {
356
400
  return routes[featureName] || `/${featureName}`;
357
401
  }
358
402
 
359
- async function generateE2EReport(projectDir, config, feature, env, baseUrl) {
403
+ async function generateE2EReport(
404
+ projectDir,
405
+ config,
406
+ feature,
407
+ env,
408
+ baseUrl,
409
+ result,
410
+ ) {
360
411
  try {
361
- const screenshotsDir = path.join(projectDir, "e2e", "screenshots");
362
- const screenshots = await findFiles(screenshotsDir, "*.png").catch(
363
- () => [],
364
- );
365
-
366
412
  const reporter = new ReportGenerator(config);
413
+ const tests = result.tests || [];
367
414
  const results = {
368
415
  summary: {
369
- totalTests: 0,
370
- totalPassed: 0,
371
- totalFailed: 0,
372
- totalSkipped: 0,
373
- overallPassRate: 0,
374
- byLayer: {},
416
+ totalTests: result.passed + result.failed + result.skipped,
417
+ totalPassed: result.passed,
418
+ totalFailed: result.failed,
419
+ totalSkipped: result.skipped,
420
+ overallPassRate:
421
+ result.passed + result.failed + result.skipped > 0
422
+ ? Math.round(
423
+ (result.passed /
424
+ (result.passed + result.failed + result.skipped)) *
425
+ 100,
426
+ )
427
+ : 0,
428
+ totalDuration: result.duration,
429
+ byLayer: {
430
+ e2e: {
431
+ total: result.passed + result.failed + result.skipped,
432
+ passed: result.passed,
433
+ failed: result.failed,
434
+ skipped: result.skipped,
435
+ },
436
+ },
375
437
  },
376
- results: [],
438
+ results: [
439
+ {
440
+ runner: "playwright",
441
+ layer: "e2e",
442
+ feature,
443
+ tests,
444
+ summary: {
445
+ total: result.passed + result.failed + result.skipped,
446
+ passed: result.passed,
447
+ failed: result.failed,
448
+ skipped: result.skipped,
449
+ },
450
+ },
451
+ ],
377
452
  };
378
453
 
379
- const pwResultsPath = path.join(
380
- projectDir,
381
- "qabot-reports",
382
- "playwright",
383
- "results.json",
384
- );
385
- if (await fileExists(pwResultsPath)) {
386
- try {
387
- const pwResults = JSON.parse(await readFile(pwResultsPath, "utf-8"));
388
- if (pwResults.suites) {
389
- const tests = [];
390
- flattenSuites(pwResults.suites, tests);
391
- results.results = [
392
- {
393
- runner: "playwright",
394
- layer: "e2e",
395
- feature,
396
- tests,
397
- summary: {
398
- total: tests.length,
399
- passed: tests.filter((t) => t.status === "passed").length,
400
- failed: tests.filter((t) => t.status === "failed").length,
401
- skipped: tests.filter((t) => t.status === "skipped").length,
402
- },
403
- },
404
- ];
405
- results.summary.totalTests = tests.length;
406
- results.summary.totalPassed = tests.filter(
407
- (t) => t.status === "passed",
408
- ).length;
409
- results.summary.totalFailed = tests.filter(
410
- (t) => t.status === "failed",
411
- ).length;
412
- results.summary.overallPassRate =
413
- tests.length > 0
414
- ? Math.round((results.summary.totalPassed / tests.length) * 100)
415
- : 0;
416
- }
417
- } catch {
418
- /* skip malformed results */
419
- }
420
- }
421
-
422
454
  const reportPaths = await reporter.generate(results, {
423
455
  feature,
424
456
  environment: env,
425
457
  projectName: config.project?.name || "unknown",
426
458
  timestamp: new Date().toISOString(),
427
- duration: 0,
459
+ duration: result.duration,
428
460
  });
429
461
 
430
- logger.blank();
431
462
  logger.info(`Report: ${chalk.underline(reportPaths.htmlPath)}`);
432
463
  } catch {
433
- /* report generation is best-effort */
434
- }
435
- }
436
-
437
- function flattenSuites(suites, tests) {
438
- for (const suite of suites || []) {
439
- for (const spec of suite.specs || []) {
440
- for (const test of spec.tests || []) {
441
- const result = test.results?.[test.results.length - 1];
442
- tests.push({
443
- name: spec.title,
444
- suite: suite.title,
445
- file: suite.file || "",
446
- status:
447
- test.status === "expected"
448
- ? "passed"
449
- : test.status === "skipped"
450
- ? "skipped"
451
- : "failed",
452
- duration: result?.duration || 0,
453
- error: result?.error
454
- ? {
455
- message: result.error.message || "",
456
- stack: result.error.stack || "",
457
- }
458
- : null,
459
- screenshots: (result?.attachments || [])
460
- .filter((a) => a.contentType?.startsWith("image/"))
461
- .map((a) => a.path),
462
- });
463
- }
464
- }
465
- if (suite.suites) flattenSuites(suite.suites, tests);
464
+ /* best-effort */
466
465
  }
467
466
  }