ortoni-report 4.0.0 → 4.0.2-beta.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,635 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
10
+
11
+ // src/helpers/fileManager.ts
12
+ import fs from "fs";
13
+ import path from "path";
14
+ var FileManager = class {
15
+ constructor(folderPath) {
16
+ this.folderPath = folderPath;
17
+ }
18
+ ensureReportDirectory() {
19
+ const ortoniDataFolder = path.join(this.folderPath, "ortoni-data");
20
+ if (!fs.existsSync(this.folderPath)) {
21
+ fs.mkdirSync(this.folderPath, { recursive: true });
22
+ } else {
23
+ if (fs.existsSync(ortoniDataFolder)) {
24
+ fs.rmSync(ortoniDataFolder, { recursive: true, force: true });
25
+ }
26
+ }
27
+ }
28
+ writeReportFile(filename, data) {
29
+ const templatePath = path.join(__dirname, "..", "index.html");
30
+ console.log(templatePath);
31
+ let html = fs.readFileSync(templatePath, "utf-8");
32
+ const reportJSON = JSON.stringify({
33
+ data
34
+ });
35
+ html = html.replace("__ORTONI_TEST_REPORTDATA__", reportJSON);
36
+ console.log(`Writing report to ${reportJSON}`);
37
+ const outputPath = path.join(process.cwd(), this.folderPath, filename);
38
+ console.log(`Writing report to ${outputPath}`);
39
+ fs.writeFileSync(outputPath, html);
40
+ return outputPath;
41
+ }
42
+ writeRawFile(filename, data) {
43
+ const outputPath = path.join(process.cwd(), this.folderPath, filename);
44
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
45
+ const content = typeof data === "string" ? data : JSON.stringify(data, null, 2);
46
+ fs.writeFileSync(outputPath, content, "utf-8");
47
+ return outputPath;
48
+ }
49
+ copyTraceViewerAssets(skip) {
50
+ if (skip) return;
51
+ const traceViewerFolder = path.join(
52
+ __require.resolve("playwright-core"),
53
+ "..",
54
+ "lib",
55
+ "vite",
56
+ "traceViewer"
57
+ );
58
+ const traceViewerTargetFolder = path.join(this.folderPath, "trace");
59
+ const traceViewerAssetsTargetFolder = path.join(
60
+ traceViewerTargetFolder,
61
+ "assets"
62
+ );
63
+ fs.mkdirSync(traceViewerAssetsTargetFolder, { recursive: true });
64
+ for (const file of fs.readdirSync(traceViewerFolder)) {
65
+ if (file.endsWith(".map") || file.includes("watch") || file.includes("assets"))
66
+ continue;
67
+ fs.copyFileSync(
68
+ path.join(traceViewerFolder, file),
69
+ path.join(traceViewerTargetFolder, file)
70
+ );
71
+ }
72
+ const assetsFolder = path.join(traceViewerFolder, "assets");
73
+ for (const file of fs.readdirSync(assetsFolder)) {
74
+ if (file.endsWith(".map") || file.includes("xtermModule")) continue;
75
+ fs.copyFileSync(
76
+ path.join(assetsFolder, file),
77
+ path.join(traceViewerAssetsTargetFolder, file)
78
+ );
79
+ }
80
+ }
81
+ };
82
+
83
+ // src/utils/groupProjects.ts
84
+ function groupResults(config, results) {
85
+ if (config.showProject) {
86
+ const groupedResults = results.reduce((acc, result, index) => {
87
+ const testId = `${result.filePath}:${result.projectName}:${result.title}`;
88
+ const key = `${testId}-${result.key}-${result.retryAttemptCount}`;
89
+ const { filePath, suite, projectName } = result;
90
+ acc[filePath] = acc[filePath] || {};
91
+ acc[filePath][suite] = acc[filePath][suite] || {};
92
+ acc[filePath][suite][projectName] = acc[filePath][suite][projectName] || [];
93
+ acc[filePath][suite][projectName].push({ ...result, index, testId, key });
94
+ return acc;
95
+ }, {});
96
+ return groupedResults;
97
+ } else {
98
+ const groupedResults = results.reduce((acc, result, index) => {
99
+ const testId = `${result.filePath}:${result.projectName}:${result.title}`;
100
+ const key = `${testId}-${result.key}-${result.retryAttemptCount}`;
101
+ const { filePath, suite } = result;
102
+ acc[filePath] = acc[filePath] || {};
103
+ acc[filePath][suite] = acc[filePath][suite] || [];
104
+ acc[filePath][suite].push({ ...result, index, testId, key });
105
+ return acc;
106
+ }, {});
107
+ return groupedResults;
108
+ }
109
+ }
110
+
111
+ // src/helpers/HTMLGenerator.ts
112
+ var HTMLGenerator = class {
113
+ constructor(ortoniConfig, dbManager) {
114
+ this.ortoniConfig = ortoniConfig;
115
+ this.dbManager = dbManager;
116
+ }
117
+ async generateFinalReport(filteredResults, totalDuration, results, projectSet) {
118
+ const data = await this.prepareReportData(
119
+ filteredResults,
120
+ totalDuration,
121
+ results,
122
+ projectSet
123
+ );
124
+ return data;
125
+ }
126
+ async getReportData() {
127
+ return {
128
+ summary: await this.dbManager.getSummaryData(),
129
+ trends: await this.dbManager.getTrends(),
130
+ flakyTests: await this.dbManager.getFlakyTests(),
131
+ slowTests: await this.dbManager.getSlowTests()
132
+ };
133
+ }
134
+ async prepareReportData(filteredResults, totalDuration, results, projectSet) {
135
+ const totalTests = filteredResults.length;
136
+ const passedTests = results.filter((r) => r.status === "passed").length;
137
+ const flakyTests = results.filter((r) => r.status === "flaky").length;
138
+ const failed = filteredResults.filter(
139
+ (r) => r.status === "failed" || r.status === "timedOut"
140
+ ).length;
141
+ const successRate = ((passedTests + flakyTests) / totalTests * 100).toFixed(2);
142
+ const allTags = /* @__PURE__ */ new Set();
143
+ results.forEach(
144
+ (result) => result.testTags.forEach((tag) => allTags.add(tag))
145
+ );
146
+ const projectResults = this.calculateProjectResults(
147
+ filteredResults,
148
+ results,
149
+ projectSet
150
+ );
151
+ const lastRunDate = (/* @__PURE__ */ new Date()).toLocaleString();
152
+ const testHistories = await Promise.all(
153
+ results.map(async (result) => {
154
+ const testId = `${result.filePath}:${result.projectName}:${result.title}`;
155
+ const history = await this.dbManager.getTestHistory(testId);
156
+ return {
157
+ testId,
158
+ history
159
+ };
160
+ })
161
+ );
162
+ return {
163
+ summary: {
164
+ overAllResult: {
165
+ pass: passedTests,
166
+ fail: failed,
167
+ skip: results.filter((r) => r.status === "skipped").length,
168
+ retry: results.filter((r) => r.retryAttemptCount).length,
169
+ flaky: flakyTests,
170
+ total: filteredResults.length
171
+ },
172
+ successRate,
173
+ lastRunDate,
174
+ totalDuration,
175
+ stats: this.extractProjectStats(projectResults)
176
+ },
177
+ testResult: {
178
+ tests: groupResults(this.ortoniConfig, results),
179
+ testHistories,
180
+ allTags: Array.from(allTags),
181
+ set: projectSet
182
+ },
183
+ userConfig: {
184
+ projectName: this.ortoniConfig.projectName,
185
+ authorName: this.ortoniConfig.authorName,
186
+ type: this.ortoniConfig.testType,
187
+ title: this.ortoniConfig.title
188
+ },
189
+ userMeta: {
190
+ meta: this.ortoniConfig.meta
191
+ },
192
+ preferences: {
193
+ logo: this.ortoniConfig.logo || void 0,
194
+ showProject: this.ortoniConfig.showProject || false
195
+ },
196
+ analytics: {
197
+ reportData: await this.getReportData()
198
+ }
199
+ };
200
+ }
201
+ calculateProjectResults(filteredResults, results, projectSet) {
202
+ return Array.from(projectSet).map((projectName) => {
203
+ const projectTests = filteredResults.filter(
204
+ (r) => r.projectName === projectName
205
+ );
206
+ const allProjectTests = results.filter(
207
+ (r) => r.projectName === projectName
208
+ );
209
+ return {
210
+ projectName,
211
+ passedTests: projectTests.filter((r) => r.status === "passed").length,
212
+ failedTests: projectTests.filter(
213
+ (r) => r.status === "failed" || r.status === "timedOut"
214
+ ).length,
215
+ skippedTests: allProjectTests.filter((r) => r.status === "skipped").length,
216
+ retryTests: allProjectTests.filter((r) => r.retryAttemptCount).length,
217
+ flakyTests: allProjectTests.filter((r) => r.status === "flaky").length,
218
+ totalTests: projectTests.length
219
+ };
220
+ });
221
+ }
222
+ extractProjectStats(projectResults) {
223
+ return {
224
+ projectNames: projectResults.map((result) => result.projectName),
225
+ totalTests: projectResults.map((result) => result.totalTests),
226
+ passedTests: projectResults.map((result) => result.passedTests),
227
+ failedTests: projectResults.map((result) => result.failedTests),
228
+ skippedTests: projectResults.map((result) => result.skippedTests),
229
+ retryTests: projectResults.map((result) => result.retryTests),
230
+ flakyTests: projectResults.map((result) => result.flakyTests)
231
+ };
232
+ }
233
+ };
234
+
235
+ // src/utils/utils.ts
236
+ import path2 from "path";
237
+ function normalizeFilePath(filePath) {
238
+ const normalizedPath = path2.normalize(filePath);
239
+ return path2.basename(normalizedPath);
240
+ }
241
+ function ensureHtmlExtension(filename) {
242
+ const ext = path2.extname(filename);
243
+ if (ext && ext.toLowerCase() === ".html") {
244
+ return filename;
245
+ }
246
+ return `${filename}.html`;
247
+ }
248
+ function escapeHtml(unsafe) {
249
+ if (typeof unsafe !== "string") {
250
+ return String(unsafe);
251
+ }
252
+ return unsafe.replace(/[&<"']/g, function(match) {
253
+ const escapeMap = {
254
+ "&": "&amp;",
255
+ "<": "&lt;",
256
+ ">": "&gt;",
257
+ '"': "&quot;",
258
+ "'": "&#039;"
259
+ };
260
+ return escapeMap[match] || match;
261
+ });
262
+ }
263
+ function formatDateLocal(dateInput) {
264
+ const date = typeof dateInput === "string" ? new Date(dateInput) : dateInput;
265
+ const options = {
266
+ year: "numeric",
267
+ month: "short",
268
+ day: "2-digit",
269
+ hour: "2-digit",
270
+ minute: "2-digit",
271
+ hour12: true,
272
+ timeZoneName: "short"
273
+ // or "Asia/Kolkata"
274
+ };
275
+ return new Intl.DateTimeFormat(void 0, options).format(date);
276
+ }
277
+ function extractSuites(titlePath) {
278
+ const tagPattern = /@[\w]+/g;
279
+ const suiteParts = titlePath.slice(3, titlePath.length - 1).map((p) => p.replace(tagPattern, "").trim());
280
+ return {
281
+ hierarchy: suiteParts.join(" > "),
282
+ // full hierarchy
283
+ topLevelSuite: suiteParts[0] ?? "",
284
+ // first suite
285
+ parentSuite: suiteParts[suiteParts.length - 1] ?? ""
286
+ // last suite
287
+ };
288
+ }
289
+
290
+ // src/utils/expressServer.ts
291
+ import express from "express";
292
+ import path3 from "path";
293
+ import { spawn } from "child_process";
294
+ function startReportServer(reportFolder, reportFilename, port = 2004, open2) {
295
+ const app = express();
296
+ app.use(express.static(reportFolder));
297
+ app.get("/", (_req, res) => {
298
+ try {
299
+ res.sendFile(path3.resolve(reportFolder, reportFilename));
300
+ } catch (error) {
301
+ console.error("Ortoni-Report: Error sending report file:", error);
302
+ res.status(500).send("Error loading report");
303
+ }
304
+ });
305
+ try {
306
+ const server = app.listen(port, () => {
307
+ console.log(
308
+ `Server is running at http://localhost:${port}
309
+ Press Ctrl+C to stop.`
310
+ );
311
+ if (open2 === "always" || open2 === "on-failure") {
312
+ try {
313
+ openBrowser(`http://localhost:${port}`);
314
+ } catch (error) {
315
+ console.error("Ortoni-Report: Error opening browser:", error);
316
+ }
317
+ }
318
+ });
319
+ server.on("error", (error) => {
320
+ if (error.code === "EADDRINUSE") {
321
+ console.error(
322
+ `Ortoni-Report: Port ${port} is already in use. Trying a different port...`
323
+ );
324
+ } else {
325
+ console.error("Ortoni-Report: Server error:", error);
326
+ }
327
+ });
328
+ } catch (error) {
329
+ console.error("Ortoni-Report: Error starting the server:", error);
330
+ }
331
+ }
332
+ function openBrowser(url) {
333
+ const platform = process.platform;
334
+ let command;
335
+ try {
336
+ if (platform === "win32") {
337
+ command = "cmd";
338
+ spawn(command, ["/c", "start", url]);
339
+ } else if (platform === "darwin") {
340
+ command = "open";
341
+ spawn(command, [url]);
342
+ } else {
343
+ command = "xdg-open";
344
+ spawn(command, [url]);
345
+ }
346
+ } catch (error) {
347
+ console.error("Ortoni-Report: Error opening the browser:", error);
348
+ }
349
+ }
350
+
351
+ // src/helpers/databaseManager.ts
352
+ import { open } from "sqlite";
353
+ import sqlite3 from "sqlite3";
354
+ var DatabaseManager = class {
355
+ constructor() {
356
+ this.db = null;
357
+ }
358
+ async initialize(dbPath) {
359
+ try {
360
+ this.db = await open({
361
+ filename: dbPath,
362
+ driver: sqlite3.Database
363
+ });
364
+ await this.createTables();
365
+ await this.createIndexes();
366
+ } catch (error) {
367
+ console.error("OrtoniReport: Error initializing database:", error);
368
+ }
369
+ }
370
+ async createTables() {
371
+ if (!this.db) {
372
+ console.error("OrtoniReport: Database not initialized");
373
+ return;
374
+ }
375
+ try {
376
+ await this.db.exec(`
377
+ CREATE TABLE IF NOT EXISTS test_runs (
378
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
379
+ run_date TEXT
380
+ );
381
+
382
+ CREATE TABLE IF NOT EXISTS test_results (
383
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
384
+ run_id INTEGER,
385
+ test_id TEXT,
386
+ status TEXT,
387
+ duration INTEGER, -- store duration as raw ms
388
+ error_message TEXT,
389
+ FOREIGN KEY (run_id) REFERENCES test_runs (id)
390
+ );
391
+ `);
392
+ } catch (error) {
393
+ console.error("OrtoniReport: Error creating tables:", error);
394
+ }
395
+ }
396
+ async createIndexes() {
397
+ if (!this.db) {
398
+ console.error("OrtoniReport: Database not initialized");
399
+ return;
400
+ }
401
+ try {
402
+ await this.db.exec(`
403
+ CREATE INDEX IF NOT EXISTS idx_test_id ON test_results (test_id);
404
+ CREATE INDEX IF NOT EXISTS idx_run_id ON test_results (run_id);
405
+ `);
406
+ } catch (error) {
407
+ console.error("OrtoniReport: Error creating indexes:", error);
408
+ }
409
+ }
410
+ async saveTestRun() {
411
+ if (!this.db) {
412
+ console.error("OrtoniReport: Database not initialized");
413
+ return null;
414
+ }
415
+ try {
416
+ const runDate = (/* @__PURE__ */ new Date()).toISOString();
417
+ const { lastID } = await this.db.run(
418
+ `
419
+ INSERT INTO test_runs (run_date)
420
+ VALUES (?)
421
+ `,
422
+ [runDate]
423
+ );
424
+ return lastID;
425
+ } catch (error) {
426
+ console.error("OrtoniReport: Error saving test run:", error);
427
+ return null;
428
+ }
429
+ }
430
+ async saveTestResults(runId, results) {
431
+ if (!this.db) {
432
+ console.error("OrtoniReport: Database not initialized");
433
+ return;
434
+ }
435
+ try {
436
+ await this.db.exec("BEGIN TRANSACTION;");
437
+ const stmt = await this.db.prepare(`
438
+ INSERT INTO test_results (run_id, test_id, status, duration, error_message)
439
+ VALUES (?, ?, ?, ?, ?)
440
+ `);
441
+ for (const result of results) {
442
+ await stmt.run([
443
+ runId,
444
+ `${result.filePath}:${result.projectName}:${result.title}`,
445
+ result.status,
446
+ result.duration,
447
+ // store raw ms
448
+ result.errors.join("\n")
449
+ ]);
450
+ }
451
+ await stmt.finalize();
452
+ await this.db.exec("COMMIT;");
453
+ } catch (error) {
454
+ await this.db.exec("ROLLBACK;");
455
+ console.error("OrtoniReport: Error saving test results:", error);
456
+ }
457
+ }
458
+ async getTestHistory(testId, limit = 10) {
459
+ if (!this.db) {
460
+ console.error("OrtoniReport: Database not initialized");
461
+ return [];
462
+ }
463
+ try {
464
+ const results = await this.db.all(
465
+ `
466
+ SELECT tr.status, tr.duration, tr.error_message, trun.run_date
467
+ FROM test_results tr
468
+ JOIN test_runs trun ON tr.run_id = trun.id
469
+ WHERE tr.test_id = ?
470
+ ORDER BY trun.run_date DESC
471
+ LIMIT ?
472
+ `,
473
+ [testId, limit]
474
+ );
475
+ return results.map((result) => ({
476
+ ...result,
477
+ run_date: formatDateLocal(result.run_date)
478
+ }));
479
+ } catch (error) {
480
+ console.error("OrtoniReport: Error getting test history:", error);
481
+ return [];
482
+ }
483
+ }
484
+ async close() {
485
+ if (this.db) {
486
+ try {
487
+ await this.db.close();
488
+ } catch (error) {
489
+ console.error("OrtoniReport: Error closing database:", error);
490
+ } finally {
491
+ this.db = null;
492
+ }
493
+ }
494
+ }
495
+ async getSummaryData() {
496
+ if (!this.db) {
497
+ console.error("OrtoniReport: Database not initialized");
498
+ return {
499
+ totalRuns: 0,
500
+ totalTests: 0,
501
+ passed: 0,
502
+ failed: 0,
503
+ passRate: 0,
504
+ avgDuration: 0
505
+ };
506
+ }
507
+ try {
508
+ const summary = await this.db.get(`
509
+ SELECT
510
+ (SELECT COUNT(*) FROM test_runs) as totalRuns,
511
+ (SELECT COUNT(*) FROM test_results) as totalTests,
512
+ (SELECT COUNT(*) FROM test_results WHERE status = 'passed') as passed,
513
+ (SELECT COUNT(*) FROM test_results WHERE status = 'failed') as failed,
514
+ (SELECT AVG(duration) FROM test_results) as avgDuration
515
+ `);
516
+ const passRate = summary.totalTests ? (summary.passed / summary.totalTests * 100).toFixed(2) : 0;
517
+ return {
518
+ totalRuns: summary.totalRuns,
519
+ totalTests: summary.totalTests,
520
+ passed: summary.passed,
521
+ failed: summary.failed,
522
+ passRate: parseFloat(passRate.toString()),
523
+ avgDuration: Math.round(summary.avgDuration || 0)
524
+ // raw ms avg
525
+ };
526
+ } catch (error) {
527
+ console.error("OrtoniReport: Error getting summary data:", error);
528
+ return {
529
+ totalRuns: 0,
530
+ totalTests: 0,
531
+ passed: 0,
532
+ failed: 0,
533
+ passRate: 0,
534
+ avgDuration: 0
535
+ };
536
+ }
537
+ }
538
+ async getTrends(limit = 100) {
539
+ if (!this.db) {
540
+ console.error("OrtoniReport: Database not initialized");
541
+ return [];
542
+ }
543
+ try {
544
+ const rows = await this.db.all(
545
+ `
546
+ SELECT trun.run_date,
547
+ SUM(CASE WHEN tr.status = 'passed' THEN 1 ELSE 0 END) AS passed,
548
+ SUM(CASE WHEN tr.status = 'failed' THEN 1 ELSE 0 END) AS failed,
549
+ AVG(tr.duration) AS avg_duration
550
+ FROM test_results tr
551
+ JOIN test_runs trun ON tr.run_id = trun.id
552
+ GROUP BY trun.run_date
553
+ ORDER BY trun.run_date DESC
554
+ LIMIT ?
555
+ `,
556
+ [limit]
557
+ );
558
+ return rows.reverse().map((row) => ({
559
+ ...row,
560
+ run_date: formatDateLocal(row.run_date),
561
+ avg_duration: Math.round(row.avg_duration || 0)
562
+ // raw ms avg
563
+ }));
564
+ } catch (error) {
565
+ console.error("OrtoniReport: Error getting trends data:", error);
566
+ return [];
567
+ }
568
+ }
569
+ async getFlakyTests(limit = 10) {
570
+ if (!this.db) {
571
+ console.error("OrtoniReport: Database not initialized");
572
+ return [];
573
+ }
574
+ try {
575
+ return await this.db.all(
576
+ `
577
+ SELECT
578
+ test_id,
579
+ COUNT(*) AS total,
580
+ SUM(CASE WHEN status = 'flaky' THEN 1 ELSE 0 END) AS flaky,
581
+ AVG(duration) AS avg_duration
582
+ FROM test_results
583
+ GROUP BY test_id
584
+ HAVING flaky > 0
585
+ ORDER BY flaky DESC
586
+ LIMIT ?
587
+ `,
588
+ [limit]
589
+ );
590
+ } catch (error) {
591
+ console.error("OrtoniReport: Error getting flaky tests:", error);
592
+ return [];
593
+ }
594
+ }
595
+ async getSlowTests(limit = 10) {
596
+ if (!this.db) {
597
+ console.error("OrtoniReport: Database not initialized");
598
+ return [];
599
+ }
600
+ try {
601
+ const rows = await this.db.all(
602
+ `
603
+ SELECT
604
+ test_id,
605
+ AVG(duration) AS avg_duration
606
+ FROM test_results
607
+ GROUP BY test_id
608
+ ORDER BY avg_duration DESC
609
+ LIMIT ?
610
+ `,
611
+ [limit]
612
+ );
613
+ return rows.map((row) => ({
614
+ test_id: row.test_id,
615
+ avg_duration: Math.round(row.avg_duration || 0)
616
+ // raw ms avg
617
+ }));
618
+ } catch (error) {
619
+ console.error("OrtoniReport: Error getting slow tests:", error);
620
+ return [];
621
+ }
622
+ }
623
+ };
624
+
625
+ export {
626
+ __publicField,
627
+ FileManager,
628
+ HTMLGenerator,
629
+ normalizeFilePath,
630
+ ensureHtmlExtension,
631
+ escapeHtml,
632
+ extractSuites,
633
+ startReportServer,
634
+ DatabaseManager
635
+ };