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