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