ortoni-report 4.0.2-beta.1 → 4.0.2

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