playwright-opentelemetry 0.1.1 → 0.3.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.
- package/README.md +4 -60
- package/dist/fixture.mjs +63 -4
- package/dist/index-Di44jFGW.d.mts +47 -0
- package/dist/index.d.mts +28 -0
- package/dist/index.mjs +7 -0
- package/dist/reporter-BYzfT1GS.mjs +510 -0
- package/dist/reporter.d.mts +2 -43
- package/dist/reporter.mjs +1 -313
- package/dist/{trace-files-BnO7hKxI.mjs → trace-files-BK_6TvGO.mjs} +65 -2
- package/package.json +14 -7
package/README.md
CHANGED
|
@@ -1,67 +1,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `playwright-opentelemetry`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A combination of a Playwright reporter and a fixture that allows you to create opentelemetry spans for playwright end-to-end tests.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
For more information on getting started, check out the main [readme](../README.md).
|
|
6
6
|
|
|
7
|
-
##
|
|
8
|
-
|
|
9
|
-
Two things need to be set up for complete opentelemetry tracing:
|
|
10
|
-
|
|
11
|
-
1. A reporter that sends traces to your provider of choice
|
|
12
|
-
2. A fixture that propogates opentelemetry trace headers to enable nested spans
|
|
13
|
-
|
|
14
|
-
### Configure the reporter
|
|
15
|
-
|
|
16
|
-
```ts
|
|
17
|
-
import { defineConfig, devices } from "@playwright/test";
|
|
18
|
-
import type { PlaywrightOpentelemetryReporterOptions } from "playwright-opentelemetry/reporter";
|
|
19
|
-
|
|
20
|
-
export default defineConfig({
|
|
21
|
-
// ... other Playwright config
|
|
22
|
-
reporter: [
|
|
23
|
-
[
|
|
24
|
-
"playwright-opentelemetry/reporter",
|
|
25
|
-
{
|
|
26
|
-
// Or use environment variable OTEL_EXPORTER_OTLP_ENDPOINT
|
|
27
|
-
otlpEndpoint: "https://api.eu1.honeycomb.io/v1/traces",
|
|
28
|
-
// Or use environment variable OTEL_EXPORTER_OTLP_HEADERS
|
|
29
|
-
otlpHeaders: {
|
|
30
|
-
"x-honeycomb-team": "xxxabc",
|
|
31
|
-
}
|
|
32
|
-
} satisfies PlaywrightOpentelemetryReporterOptions,
|
|
33
|
-
],
|
|
34
|
-
],
|
|
35
|
-
// ... rest of Playwright config
|
|
36
|
-
});
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
### Configure the fixture
|
|
40
|
-
|
|
41
|
-
```ts
|
|
42
|
-
import { expect } from "@playwright/test";
|
|
43
|
-
import { test } from "playwright-opentelemetry/fixture";
|
|
44
|
-
|
|
45
|
-
test("has title", async ({ page }) => {
|
|
46
|
-
await page.goto("https://playwright.dev/");
|
|
47
|
-
|
|
48
|
-
await expect(page).toHaveTitle(/Playwright/);
|
|
49
|
-
});
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
## Contributing
|
|
53
|
-
|
|
54
|
-
### Developing `playwright-opentelemetry`
|
|
7
|
+
## Developing the reporter / fixture
|
|
55
8
|
|
|
56
9
|
- `pnpm dev` starts a dev server that outputs `dist/index.mjs`
|
|
57
10
|
- `pnpm build` otherwise creates a one-off compiled build
|
|
58
|
-
- `pnpm test:unit` to run the unit tests
|
|
59
11
|
- `pnpm test:e2e` uses the compiled reporter output
|
|
60
|
-
- `pnpm typecheck` for typescript
|
|
61
|
-
- `pnpm format` to format files
|
|
62
|
-
|
|
63
|
-
### Releasing
|
|
64
|
-
|
|
65
|
-
```
|
|
66
|
-
npx bumpp
|
|
67
|
-
```
|
package/dist/fixture.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { c as getOrCreateTraceId, f as writeNetworkSpan, m as writePageTestMapping, o as generateSpanId, p as writeNetworkSpanParent, s as getCurrentSpanId, u as readNetworkSpanParent } from "./trace-files-BK_6TvGO.mjs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { test as test$1 } from "@playwright/test";
|
|
4
4
|
|
|
@@ -36,6 +36,53 @@ async function fixtureOtelHeaderPropagator({ route, request, testId, outputDir }
|
|
|
36
36
|
//#endregion
|
|
37
37
|
//#region src/fixture/request-response-capture.ts
|
|
38
38
|
/**
|
|
39
|
+
* Detects the resource type based on Content-Type header with URL extension fallback.
|
|
40
|
+
* This categorization mirrors Chrome DevTools Network tab behavior.
|
|
41
|
+
*
|
|
42
|
+
* @param contentType - The Content-Type response header value (may be null)
|
|
43
|
+
* @param url - The request URL (used as fallback)
|
|
44
|
+
* @returns The detected resource type
|
|
45
|
+
*/
|
|
46
|
+
function detectResourceType(contentType, url) {
|
|
47
|
+
if (contentType) {
|
|
48
|
+
const mimeType = contentType.split(";")[0].trim().toLowerCase();
|
|
49
|
+
if (mimeType !== "application/octet-stream") {
|
|
50
|
+
if (mimeType === "text/html" || mimeType === "application/xhtml+xml") return "document";
|
|
51
|
+
if (mimeType === "application/javascript" || mimeType === "text/javascript" || mimeType === "application/x-javascript" || mimeType === "application/ecmascript" || mimeType === "text/ecmascript" || mimeType === "module" || mimeType === "application/wasm") return "script";
|
|
52
|
+
if (mimeType === "text/css") return "stylesheet";
|
|
53
|
+
if (mimeType.startsWith("image/")) return "image";
|
|
54
|
+
if (mimeType.startsWith("font/") || mimeType === "application/font-woff" || mimeType === "application/font-woff2" || mimeType === "application/x-font-ttf" || mimeType === "application/x-font-opentype") return "font";
|
|
55
|
+
if (mimeType.startsWith("video/") || mimeType.startsWith("audio/")) return "media";
|
|
56
|
+
if (mimeType === "application/json" || mimeType === "text/plain" || mimeType === "application/xml" || mimeType === "text/xml" || mimeType.endsWith("+json") || mimeType.endsWith("+xml")) return "fetch";
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const resourceType = detectResourceTypeFromUrl(url);
|
|
60
|
+
if (resourceType) return resourceType;
|
|
61
|
+
return "other";
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Detects resource type from URL file extension.
|
|
65
|
+
* Used as fallback when Content-Type header is missing or generic.
|
|
66
|
+
*/
|
|
67
|
+
function detectResourceTypeFromUrl(url) {
|
|
68
|
+
try {
|
|
69
|
+
const lastSegment = new URL(url).pathname.toLowerCase().split("/").pop() || "";
|
|
70
|
+
const dotIndex = lastSegment.lastIndexOf(".");
|
|
71
|
+
if (dotIndex === -1) return null;
|
|
72
|
+
const extension = lastSegment.slice(dotIndex + 1);
|
|
73
|
+
if (extension === "html" || extension === "htm" || extension === "xhtml") return "document";
|
|
74
|
+
if (extension === "js" || extension === "mjs" || extension === "cjs" || extension === "jsx" || extension === "ts" || extension === "tsx" || extension === "wasm") return "script";
|
|
75
|
+
if (extension === "css") return "stylesheet";
|
|
76
|
+
if (extension === "png" || extension === "jpg" || extension === "jpeg" || extension === "gif" || extension === "svg" || extension === "webp" || extension === "ico" || extension === "bmp" || extension === "avif") return "image";
|
|
77
|
+
if (extension === "woff" || extension === "woff2" || extension === "ttf" || extension === "otf" || extension === "eot") return "font";
|
|
78
|
+
if (extension === "mp4" || extension === "webm" || extension === "ogg" || extension === "mp3" || extension === "wav" || extension === "m4a" || extension === "aac" || extension === "flac" || extension === "avi" || extension === "mov") return "media";
|
|
79
|
+
if (extension === "json" || extension === "xml") return "fetch";
|
|
80
|
+
return null;
|
|
81
|
+
} catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
39
86
|
* OpenTelemetry SpanKind values
|
|
40
87
|
* @see https://opentelemetry.io/docs/specs/otel/trace/api/#spankind
|
|
41
88
|
*/
|
|
@@ -77,13 +124,17 @@ async function fixtureCaptureRequestResponse({ request, response, testId, output
|
|
|
77
124
|
const serverPort = parsedUrl.port !== "" ? Number.parseInt(parsedUrl.port, 10) : parsedUrl.protocol === "https:" ? 443 : 80;
|
|
78
125
|
let statusCodeValue = SPAN_STATUS_CODE_UNSET;
|
|
79
126
|
if (statusCode >= 400) statusCodeValue = SPAN_STATUS_CODE_ERROR;
|
|
127
|
+
const resourceType = detectResourceType(await response.headerValue("content-type"), url);
|
|
80
128
|
const attributes = {
|
|
81
129
|
"http.request.method": method,
|
|
82
130
|
"url.full": url,
|
|
131
|
+
"url.path": parsedUrl.pathname,
|
|
83
132
|
"server.address": serverAddress,
|
|
84
133
|
"server.port": serverPort,
|
|
85
|
-
"http.response.status_code": statusCode
|
|
134
|
+
"http.response.status_code": statusCode,
|
|
135
|
+
"http.resource.type": resourceType
|
|
86
136
|
};
|
|
137
|
+
if (parsedUrl.search) attributes["url.query"] = parsedUrl.search.slice(1);
|
|
87
138
|
if (statusCodeValue === SPAN_STATUS_CODE_ERROR) attributes["error.type"] = statusCode.toString();
|
|
88
139
|
writeNetworkSpan(outputDir, testId, traceHeader, {
|
|
89
140
|
traceId,
|
|
@@ -94,7 +145,8 @@ async function fixtureCaptureRequestResponse({ request, response, testId, output
|
|
|
94
145
|
startTime,
|
|
95
146
|
endTime,
|
|
96
147
|
status: { code: statusCodeValue },
|
|
97
|
-
attributes
|
|
148
|
+
attributes,
|
|
149
|
+
serviceName: "playwright-browser"
|
|
98
150
|
});
|
|
99
151
|
}
|
|
100
152
|
|
|
@@ -118,8 +170,15 @@ const test = test$1.extend({
|
|
|
118
170
|
await use(context);
|
|
119
171
|
},
|
|
120
172
|
page: async ({ page, testTraceInfo: { testId, outputDir } }, use) => {
|
|
173
|
+
const pageGuid = page._guid;
|
|
174
|
+
writePageTestMapping(outputDir, testId, pageGuid);
|
|
175
|
+
const pendingRequests = /* @__PURE__ */ new Map();
|
|
176
|
+
page.on("response", (response) => {
|
|
177
|
+
pendingRequests.set(response.request(), response);
|
|
178
|
+
});
|
|
121
179
|
page.on("requestfinished", async (request) => {
|
|
122
|
-
const response =
|
|
180
|
+
const response = pendingRequests.get(request);
|
|
181
|
+
pendingRequests.delete(request);
|
|
123
182
|
if (!response) return;
|
|
124
183
|
await fixtureCaptureRequestResponse({
|
|
125
184
|
request,
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { FullConfig, FullResult, Reporter, Suite, TestCase, TestResult, TestStep } from "@playwright/test/reporter";
|
|
2
|
+
|
|
3
|
+
//#region src/reporter/reporter.d.ts
|
|
4
|
+
interface PlaywrightOpentelemetryReporterOptions {
|
|
5
|
+
otlpEndpoint?: string;
|
|
6
|
+
otlpHeaders?: Record<string, string>;
|
|
7
|
+
playwrightTraceApiEndpoint?: string;
|
|
8
|
+
playwrightTraceApiHeaders?: Record<string, string>;
|
|
9
|
+
storeTraceZip?: boolean;
|
|
10
|
+
serviceName?: string;
|
|
11
|
+
debug?: boolean;
|
|
12
|
+
}
|
|
13
|
+
declare class PlaywrightOpentelemetryReporter implements Reporter {
|
|
14
|
+
private options;
|
|
15
|
+
private spans;
|
|
16
|
+
private rootDir?;
|
|
17
|
+
private playwrightVersion?;
|
|
18
|
+
private resolvedEndpoint;
|
|
19
|
+
private resolvedHeaders;
|
|
20
|
+
private resolvedTraceApiEndpoint;
|
|
21
|
+
private resolvedTraceApiHeaders;
|
|
22
|
+
private resolvedServiceName;
|
|
23
|
+
/** Maps test.id to its project's outputDir */
|
|
24
|
+
private testOutputDirs;
|
|
25
|
+
/** File system watchers for output directories */
|
|
26
|
+
private directoryWatchers;
|
|
27
|
+
private testSpans;
|
|
28
|
+
private testTraceIds;
|
|
29
|
+
private stepSpanIds;
|
|
30
|
+
/** Tracks the span context stack per test for append-only file writes */
|
|
31
|
+
private spanContextStacks;
|
|
32
|
+
constructor(options?: PlaywrightOpentelemetryReporterOptions);
|
|
33
|
+
onBegin(config: FullConfig, suite: Suite): void;
|
|
34
|
+
onTestBegin(test: TestCase): void;
|
|
35
|
+
onStepBegin(test: TestCase, _result: TestResult, step: TestStep): Promise<void>;
|
|
36
|
+
onStepEnd(test: TestCase, _result: TestResult, _step: TestStep): void;
|
|
37
|
+
onTestEnd(test: TestCase, result: TestResult): Promise<void>;
|
|
38
|
+
onEnd(_result: FullResult): Promise<void>;
|
|
39
|
+
private processTestStep;
|
|
40
|
+
onStdOut(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
|
|
41
|
+
onStdErr(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
|
|
42
|
+
printsToStdio(): boolean;
|
|
43
|
+
private getOutputDir;
|
|
44
|
+
private sendTestJsonToTraceApi;
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
export { PlaywrightOpentelemetryReporterOptions as n, PlaywrightOpentelemetryReporter as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-Di44jFGW.mjs";
|
|
2
|
+
import { TestCase, TestStatus } from "@playwright/test/reporter";
|
|
3
|
+
|
|
4
|
+
//#region src/reporter/trace-zip-builder.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Test metadata stored in test.json at the root of the trace zip.
|
|
8
|
+
*/
|
|
9
|
+
interface TestInfo {
|
|
10
|
+
/** Test name (from test.title) */
|
|
11
|
+
name: string;
|
|
12
|
+
/** Describe blocks containing this test (from titlePath, excluding root/project/file/test) */
|
|
13
|
+
describes: string[];
|
|
14
|
+
/** Relative file path to the test file */
|
|
15
|
+
file: string;
|
|
16
|
+
/** Line number where the test is defined */
|
|
17
|
+
line: number;
|
|
18
|
+
/** Test result status */
|
|
19
|
+
status: TestStatus;
|
|
20
|
+
/** OpenTelemetry trace ID for this test */
|
|
21
|
+
traceId: string;
|
|
22
|
+
/** Start time in nanoseconds since Unix epoch (as string to preserve precision) */
|
|
23
|
+
startTimeUnixNano: string;
|
|
24
|
+
/** End time in nanoseconds since Unix epoch (as string to preserve precision) */
|
|
25
|
+
endTimeUnixNano: string;
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
export { type PlaywrightOpentelemetryReporterOptions, type TestInfo, PlaywrightOpentelemetryReporter as default };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
import { a as createNetworkDirs, c as getOrCreateTraceId, d as writeCurrentSpanId, i as copyScreenshotForTest, l as getScreenshotsDir, n as cleanupTestFiles, o as generateSpanId, r as collectNetworkSpans, t as PW_OTEL_DIR } from "./trace-files-BK_6TvGO.mjs";
|
|
2
|
+
import { existsSync, mkdirSync, watch } from "node:fs";
|
|
3
|
+
import fs, { readFile, readdir } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { BlobWriter, TextReader, ZipWriter } from "@zip.js/zip.js";
|
|
6
|
+
|
|
7
|
+
//#region src/reporter/otel-attributes.ts
|
|
8
|
+
const ATTR_CODE_FILE_PATH = "code.file.path";
|
|
9
|
+
const ATTR_CODE_LINE_NUMBER = "code.line.number";
|
|
10
|
+
const ATTR_TEST_CASE_NAME = "test.case.name";
|
|
11
|
+
const ATTR_TEST_CASE_TITLE = "test.case.title";
|
|
12
|
+
const ATTR_TEST_CASE_RESULT_STATUS = "test.case.result.status";
|
|
13
|
+
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/reporter/reporter-attributes.ts
|
|
16
|
+
const TEST_SPAN_NAME = "playwright.test";
|
|
17
|
+
const TEST_STEP_SPAN_NAME = "playwright.test.step";
|
|
18
|
+
const ATTR_TEST_STEP_NAME = "test.step.name";
|
|
19
|
+
const ATTR_TEST_STEP_TITLE = "test.step.title";
|
|
20
|
+
const ATTR_TEST_STEP_CATEGORY = "test.step.category";
|
|
21
|
+
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region package.json
|
|
24
|
+
var version = "0.3.0";
|
|
25
|
+
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/reporter/sender.ts
|
|
28
|
+
function dateToNanoseconds(date) {
|
|
29
|
+
return (BigInt(date.getTime()) * BigInt(1e6)).toString();
|
|
30
|
+
}
|
|
31
|
+
function toOtlpAttributes(attributes) {
|
|
32
|
+
return Object.entries(attributes).map(([key, value]) => {
|
|
33
|
+
if (typeof value === "number") return {
|
|
34
|
+
key,
|
|
35
|
+
value: Number.isInteger(value) ? { intValue: value } : { doubleValue: value }
|
|
36
|
+
};
|
|
37
|
+
else if (typeof value === "boolean") return {
|
|
38
|
+
key,
|
|
39
|
+
value: { boolValue: value }
|
|
40
|
+
};
|
|
41
|
+
else return {
|
|
42
|
+
key,
|
|
43
|
+
value: { stringValue: value }
|
|
44
|
+
};
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
const SPAN_KIND_INTERNAL = 1;
|
|
48
|
+
function buildResourceSpan(spans, serviceName, playwrightVersion) {
|
|
49
|
+
const otlpSpans = spans.map((span) => ({
|
|
50
|
+
traceId: span.traceId,
|
|
51
|
+
spanId: span.spanId,
|
|
52
|
+
parentSpanId: span.parentSpanId || void 0,
|
|
53
|
+
name: span.name,
|
|
54
|
+
kind: span.kind ?? SPAN_KIND_INTERNAL,
|
|
55
|
+
startTimeUnixNano: dateToNanoseconds(span.startTime),
|
|
56
|
+
endTimeUnixNano: dateToNanoseconds(span.endTime),
|
|
57
|
+
attributes: toOtlpAttributes(span.attributes),
|
|
58
|
+
droppedAttributesCount: 0,
|
|
59
|
+
events: [],
|
|
60
|
+
droppedEventsCount: 0,
|
|
61
|
+
status: span.status,
|
|
62
|
+
links: [],
|
|
63
|
+
droppedLinksCount: 0
|
|
64
|
+
}));
|
|
65
|
+
return {
|
|
66
|
+
resource: { attributes: [
|
|
67
|
+
{
|
|
68
|
+
key: "service.name",
|
|
69
|
+
value: { stringValue: serviceName }
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
key: "service.namespace",
|
|
73
|
+
value: { stringValue: "playwright" }
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
key: "service.version",
|
|
77
|
+
value: { stringValue: playwrightVersion }
|
|
78
|
+
}
|
|
79
|
+
] },
|
|
80
|
+
scopeSpans: [{
|
|
81
|
+
scope: {
|
|
82
|
+
name: "playwright-opentelemetry",
|
|
83
|
+
version
|
|
84
|
+
},
|
|
85
|
+
spans: otlpSpans
|
|
86
|
+
}]
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function buildOtlpRequest(spans, serviceName, playwrightVersion) {
|
|
90
|
+
const spansByService = /* @__PURE__ */ new Map();
|
|
91
|
+
for (const span of spans) {
|
|
92
|
+
const spanServiceName = span.serviceName ?? serviceName;
|
|
93
|
+
const serviceSpans = spansByService.get(spanServiceName);
|
|
94
|
+
if (serviceSpans) serviceSpans.push(span);
|
|
95
|
+
else spansByService.set(spanServiceName, [span]);
|
|
96
|
+
}
|
|
97
|
+
const resourceSpans = [];
|
|
98
|
+
for (const [svcName, svcSpans] of spansByService) resourceSpans.push(buildResourceSpan(svcSpans, svcName, playwrightVersion));
|
|
99
|
+
return { resourceSpans };
|
|
100
|
+
}
|
|
101
|
+
async function sendSpans(spans, options) {
|
|
102
|
+
if (spans.length === 0) return;
|
|
103
|
+
const endpoint = options.tracesEndpoint;
|
|
104
|
+
const headers = options.headers || {};
|
|
105
|
+
const body = JSON.stringify(buildOtlpRequest(spans, options.serviceName, options.playwrightVersion));
|
|
106
|
+
if (options.debug) console.log("Sending spans to", endpoint);
|
|
107
|
+
const response = await fetch(endpoint, {
|
|
108
|
+
method: "POST",
|
|
109
|
+
body,
|
|
110
|
+
headers: {
|
|
111
|
+
"content-type": "application/json",
|
|
112
|
+
...headers
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
if (!response.ok) {
|
|
116
|
+
const error = await response.text();
|
|
117
|
+
throw new Error(`Failed to send spans: ${response.status} ${response.statusText}, ${error}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/reporter/trace-zip-builder.ts
|
|
123
|
+
/**
|
|
124
|
+
* Get the zip filename based on test location and ID.
|
|
125
|
+
* Format: {basename(file)}:{line}-{testId}-pw-otel.zip
|
|
126
|
+
* Fallback: {testId}-pw-otel.zip (if no location info)
|
|
127
|
+
*/
|
|
128
|
+
function getZipFilename(test, testId) {
|
|
129
|
+
if (test.location) return `${path.basename(test.location.file)}:${test.location.line}-${testId}-pw-otel.zip`;
|
|
130
|
+
return `${testId}-pw-otel.zip`;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Get all screenshots for a test from its dedicated screenshots directory.
|
|
134
|
+
* Returns a Map of filename -> file buffer.
|
|
135
|
+
*/
|
|
136
|
+
async function getTestScreenshots(outputDir, testId) {
|
|
137
|
+
const screenshots = /* @__PURE__ */ new Map();
|
|
138
|
+
const screenshotsDir = getScreenshotsDir(outputDir, testId);
|
|
139
|
+
try {
|
|
140
|
+
const files = await fs.readdir(screenshotsDir);
|
|
141
|
+
for (const file of files) {
|
|
142
|
+
if (!file.endsWith(".jpeg") && !file.endsWith(".jpg")) continue;
|
|
143
|
+
const filePath = path.join(screenshotsDir, file);
|
|
144
|
+
const buffer = await fs.readFile(filePath);
|
|
145
|
+
screenshots.set(file, buffer);
|
|
146
|
+
}
|
|
147
|
+
} catch (err) {
|
|
148
|
+
if (err.code !== "ENOENT") throw err;
|
|
149
|
+
}
|
|
150
|
+
return screenshots;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Build the TestInfo object for test.json.
|
|
154
|
+
*/
|
|
155
|
+
function buildTestInfo(options, traceId) {
|
|
156
|
+
const { test, relativeFilePath, status, startTime, duration } = options;
|
|
157
|
+
const titlePath = test.titlePath();
|
|
158
|
+
const describes = titlePath.length > 4 ? titlePath.slice(3, -1) : [];
|
|
159
|
+
const line = test.location?.line ?? 0;
|
|
160
|
+
const startTimeUnixNano = (startTime.getTime() * 1e6).toString();
|
|
161
|
+
const endTimeUnixNano = ((startTime.getTime() + duration) * 1e6).toString();
|
|
162
|
+
return {
|
|
163
|
+
name: test.title,
|
|
164
|
+
describes,
|
|
165
|
+
file: relativeFilePath,
|
|
166
|
+
line,
|
|
167
|
+
status,
|
|
168
|
+
traceId,
|
|
169
|
+
startTimeUnixNano,
|
|
170
|
+
endTimeUnixNano
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Create a zip file containing the OTLP trace JSON, test.json, and screenshots for a test.
|
|
175
|
+
*/
|
|
176
|
+
async function createTraceZip(options) {
|
|
177
|
+
const { outputDir, testId, test, spans, serviceName, playwrightVersion } = options;
|
|
178
|
+
const otlpRequest = buildOtlpRequest(spans, serviceName, playwrightVersion);
|
|
179
|
+
const traceJson = JSON.stringify(otlpRequest, null, 2);
|
|
180
|
+
const testInfo = buildTestInfo(options, spans.find((s) => s.name === "playwright.test")?.traceId ?? "");
|
|
181
|
+
const testInfoJson = JSON.stringify(testInfo, null, 2);
|
|
182
|
+
const screenshots = await getTestScreenshots(outputDir, testId);
|
|
183
|
+
const zipWriter = new ZipWriter(new BlobWriter("application/zip"));
|
|
184
|
+
await zipWriter.add("test.json", new TextReader(testInfoJson));
|
|
185
|
+
await zipWriter.add("opentelemetry-protocol/playwright-opentelemetry.json", new TextReader(traceJson));
|
|
186
|
+
for (const [filename, buffer] of screenshots) {
|
|
187
|
+
const blob = new Blob([buffer]);
|
|
188
|
+
await zipWriter.add(`screenshots/${filename}`, blob.stream());
|
|
189
|
+
}
|
|
190
|
+
const zipBlob = await zipWriter.close();
|
|
191
|
+
const zipFilename = getZipFilename(test, testId);
|
|
192
|
+
const zipPath = path.join(outputDir, zipFilename);
|
|
193
|
+
const arrayBuffer = await zipBlob.arrayBuffer();
|
|
194
|
+
await fs.writeFile(zipPath, Buffer.from(arrayBuffer));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
//#endregion
|
|
198
|
+
//#region src/reporter/reporter.ts
|
|
199
|
+
var PlaywrightOpentelemetryReporter = class {
|
|
200
|
+
spans = [];
|
|
201
|
+
rootDir;
|
|
202
|
+
playwrightVersion;
|
|
203
|
+
resolvedEndpoint;
|
|
204
|
+
resolvedHeaders;
|
|
205
|
+
resolvedTraceApiEndpoint;
|
|
206
|
+
resolvedTraceApiHeaders;
|
|
207
|
+
resolvedServiceName;
|
|
208
|
+
/** Maps test.id to its project's outputDir */
|
|
209
|
+
testOutputDirs = /* @__PURE__ */ new Map();
|
|
210
|
+
/** File system watchers for output directories */
|
|
211
|
+
directoryWatchers = [];
|
|
212
|
+
testSpans = /* @__PURE__ */ new Map();
|
|
213
|
+
testTraceIds = /* @__PURE__ */ new Map();
|
|
214
|
+
stepSpanIds = /* @__PURE__ */ new Map();
|
|
215
|
+
/** Tracks the span context stack per test for append-only file writes */
|
|
216
|
+
spanContextStacks = /* @__PURE__ */ new Map();
|
|
217
|
+
constructor(options = {}) {
|
|
218
|
+
this.options = options;
|
|
219
|
+
this.resolvedEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || options.otlpEndpoint || "";
|
|
220
|
+
const envHeaders = process.env.OTEL_EXPORTER_OTLP_HEADERS ? parseOtlpHeaders(process.env.OTEL_EXPORTER_OTLP_HEADERS) : {};
|
|
221
|
+
this.resolvedHeaders = {
|
|
222
|
+
...options.otlpHeaders,
|
|
223
|
+
...envHeaders
|
|
224
|
+
};
|
|
225
|
+
this.resolvedTraceApiEndpoint = options.playwrightTraceApiEndpoint || "";
|
|
226
|
+
this.resolvedTraceApiHeaders = options.playwrightTraceApiHeaders || {};
|
|
227
|
+
this.resolvedServiceName = process.env.OTEL_SERVICE_NAME || options.serviceName || "playwright-tests";
|
|
228
|
+
if (!this.resolvedEndpoint && !this.resolvedTraceApiEndpoint && !this.options.storeTraceZip) throw new Error(getConfigurationErrorMessage());
|
|
229
|
+
}
|
|
230
|
+
onBegin(config, suite) {
|
|
231
|
+
this.rootDir = config.rootDir;
|
|
232
|
+
this.playwrightVersion = config.version;
|
|
233
|
+
const watchedDirs = /* @__PURE__ */ new Set();
|
|
234
|
+
for (const test of suite.allTests()) {
|
|
235
|
+
const project = test.parent.project();
|
|
236
|
+
if (project?.outputDir) {
|
|
237
|
+
this.testOutputDirs.set(test.id, project.outputDir);
|
|
238
|
+
mkdirSync(path.join(project.outputDir, PW_OTEL_DIR), { recursive: true });
|
|
239
|
+
if (this.options.storeTraceZip && !watchedDirs.has(project.outputDir)) {
|
|
240
|
+
watchedDirs.add(project.outputDir);
|
|
241
|
+
const watcher = watch(project.outputDir, { recursive: true }, (_eventType, filename) => {
|
|
242
|
+
if (!filename || !filename.endsWith(".jpg") && !filename.endsWith(".jpeg")) return;
|
|
243
|
+
const sourcePath = path.join(project.outputDir, filename);
|
|
244
|
+
if (!existsSync(sourcePath)) return;
|
|
245
|
+
const basename = path.basename(filename);
|
|
246
|
+
const lastDashIndex = basename.lastIndexOf("-");
|
|
247
|
+
if (lastDashIndex === -1) return;
|
|
248
|
+
const pageGuid = basename.slice(0, lastDashIndex);
|
|
249
|
+
try {
|
|
250
|
+
copyScreenshotForTest(project.outputDir, pageGuid, sourcePath, basename);
|
|
251
|
+
} catch (_err) {}
|
|
252
|
+
});
|
|
253
|
+
this.directoryWatchers.push(watcher);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
onTestBegin(test) {
|
|
259
|
+
const testId = test.id;
|
|
260
|
+
const outputDir = this.getOutputDir(testId);
|
|
261
|
+
const traceId = getOrCreateTraceId(outputDir, testId);
|
|
262
|
+
this.testTraceIds.set(testId, traceId);
|
|
263
|
+
const testSpanId = generateSpanId();
|
|
264
|
+
this.testSpans.set(testId, testSpanId);
|
|
265
|
+
this.spanContextStacks.set(testId, [testSpanId]);
|
|
266
|
+
writeCurrentSpanId(outputDir, testId, testSpanId);
|
|
267
|
+
createNetworkDirs(outputDir, testId);
|
|
268
|
+
}
|
|
269
|
+
async onStepBegin(test, _result, step) {
|
|
270
|
+
const testId = test.id;
|
|
271
|
+
const outputDir = this.getOutputDir(testId);
|
|
272
|
+
const stepId = getStepId(test, step);
|
|
273
|
+
const stepSpanId = generateSpanId();
|
|
274
|
+
this.stepSpanIds.set(stepId, stepSpanId);
|
|
275
|
+
const stack = this.spanContextStacks.get(testId);
|
|
276
|
+
if (stack) {
|
|
277
|
+
stack.push(stepSpanId);
|
|
278
|
+
writeCurrentSpanId(outputDir, testId, stepSpanId);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
onStepEnd(test, _result, _step) {
|
|
282
|
+
const testId = test.id;
|
|
283
|
+
const outputDir = this.getOutputDir(testId);
|
|
284
|
+
const stack = this.spanContextStacks.get(testId);
|
|
285
|
+
if (stack && stack.length > 1) {
|
|
286
|
+
stack.pop();
|
|
287
|
+
const currentParent = stack[stack.length - 1];
|
|
288
|
+
writeCurrentSpanId(outputDir, testId, currentParent);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
async onTestEnd(test, result) {
|
|
292
|
+
const testId = test.id;
|
|
293
|
+
const outputDir = this.getOutputDir(testId);
|
|
294
|
+
const traceId = this.testTraceIds.get(testId);
|
|
295
|
+
const testSpanId = this.testSpans.get(testId);
|
|
296
|
+
if (!traceId || !testSpanId) throw new Error(`Test ${testId} not found`);
|
|
297
|
+
const attributes = {};
|
|
298
|
+
const titlePath = test.titlePath();
|
|
299
|
+
if (titlePath.length >= 3) attributes[ATTR_TEST_CASE_NAME] = titlePath.slice(3).join(" > ");
|
|
300
|
+
attributes[ATTR_TEST_CASE_TITLE] = test.title;
|
|
301
|
+
attributes[ATTR_TEST_CASE_RESULT_STATUS] = result.status;
|
|
302
|
+
if (test.location) {
|
|
303
|
+
const { file, line } = test.location;
|
|
304
|
+
attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
|
|
305
|
+
attributes[ATTR_CODE_LINE_NUMBER] = line;
|
|
306
|
+
}
|
|
307
|
+
const processedSteps = /* @__PURE__ */ new Map();
|
|
308
|
+
if (result.steps && result.steps.length > 0) for (const step of result.steps) this.processTestStep(test, step, testSpanId, traceId, [], processedSteps);
|
|
309
|
+
const stepSpans = [];
|
|
310
|
+
for (const [key, stepSpan] of processedSteps.entries()) if (!key.startsWith("__skip__")) stepSpans.push(stepSpan);
|
|
311
|
+
const networkSpans = await collectNetworkSpans(outputDir, testId);
|
|
312
|
+
let minStartTime = result.startTime;
|
|
313
|
+
let maxEndTime = new Date(result.startTime.getTime() + result.duration);
|
|
314
|
+
for (const stepSpan of stepSpans) {
|
|
315
|
+
if (stepSpan.startTime < minStartTime) minStartTime = stepSpan.startTime;
|
|
316
|
+
if (stepSpan.endTime > maxEndTime) maxEndTime = stepSpan.endTime;
|
|
317
|
+
}
|
|
318
|
+
for (const networkSpan of networkSpans) {
|
|
319
|
+
if (networkSpan.startTime < minStartTime) minStartTime = networkSpan.startTime;
|
|
320
|
+
if (networkSpan.endTime > maxEndTime) maxEndTime = networkSpan.endTime;
|
|
321
|
+
}
|
|
322
|
+
const testSpans = [
|
|
323
|
+
{
|
|
324
|
+
traceId,
|
|
325
|
+
spanId: testSpanId,
|
|
326
|
+
name: TEST_SPAN_NAME,
|
|
327
|
+
startTime: minStartTime,
|
|
328
|
+
endTime: maxEndTime,
|
|
329
|
+
attributes,
|
|
330
|
+
status: { code: result.status === test.expectedStatus ? 1 : 2 }
|
|
331
|
+
},
|
|
332
|
+
...stepSpans,
|
|
333
|
+
...networkSpans
|
|
334
|
+
];
|
|
335
|
+
this.spans.push(...testSpans);
|
|
336
|
+
const relativeFilePath = test.location && this.rootDir ? path.relative(this.rootDir, test.location.file) : test.location?.file ?? "";
|
|
337
|
+
const computedDuration = maxEndTime.getTime() - minStartTime.getTime();
|
|
338
|
+
if (this.options.storeTraceZip) await createTraceZip({
|
|
339
|
+
outputDir,
|
|
340
|
+
testId,
|
|
341
|
+
test,
|
|
342
|
+
spans: testSpans,
|
|
343
|
+
serviceName: this.resolvedServiceName,
|
|
344
|
+
playwrightVersion: this.playwrightVersion || "unknown",
|
|
345
|
+
relativeFilePath,
|
|
346
|
+
status: result.status,
|
|
347
|
+
startTime: minStartTime,
|
|
348
|
+
duration: computedDuration
|
|
349
|
+
});
|
|
350
|
+
if (this.resolvedTraceApiEndpoint) await this.sendTestJsonToTraceApi({
|
|
351
|
+
test,
|
|
352
|
+
result,
|
|
353
|
+
traceId,
|
|
354
|
+
outputDir,
|
|
355
|
+
relativeFilePath,
|
|
356
|
+
startTime: minStartTime,
|
|
357
|
+
computedDuration
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
async onEnd(_result) {
|
|
361
|
+
for (const watcher of this.directoryWatchers) watcher.close();
|
|
362
|
+
this.directoryWatchers = [];
|
|
363
|
+
if (this.resolvedEndpoint) await sendSpans(this.spans, {
|
|
364
|
+
tracesEndpoint: this.resolvedEndpoint,
|
|
365
|
+
headers: this.resolvedHeaders,
|
|
366
|
+
serviceName: this.resolvedServiceName,
|
|
367
|
+
playwrightVersion: this.playwrightVersion || "unknown",
|
|
368
|
+
debug: this.options.debug ?? false
|
|
369
|
+
});
|
|
370
|
+
if (this.resolvedTraceApiEndpoint) await sendSpans(this.spans, {
|
|
371
|
+
tracesEndpoint: `${this.resolvedTraceApiEndpoint}/v1/traces`,
|
|
372
|
+
headers: this.resolvedTraceApiHeaders,
|
|
373
|
+
serviceName: this.resolvedServiceName,
|
|
374
|
+
playwrightVersion: this.playwrightVersion || "unknown",
|
|
375
|
+
debug: this.options.debug ?? false
|
|
376
|
+
});
|
|
377
|
+
for (const [testId, outputDir] of this.testOutputDirs.entries()) await cleanupTestFiles(outputDir, testId);
|
|
378
|
+
}
|
|
379
|
+
processTestStep(test, step, parentSpanId, traceId, parentTitlePath, processedSteps) {
|
|
380
|
+
const isInternalFixture = step.category === "fixture" && step.location?.file.includes("playwright-opentelemetry") && (step.location?.file.endsWith("fixture.mjs") || step.location?.file.endsWith("fixture/index.ts"));
|
|
381
|
+
const stepId = getStepId(test, step);
|
|
382
|
+
if (isInternalFixture) {
|
|
383
|
+
processedSteps.set(`__skip__${stepId}`, {});
|
|
384
|
+
if (processedSteps.has(stepId)) processedSteps.delete(stepId);
|
|
385
|
+
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps);
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
if (processedSteps.has(`__skip__${stepId}`)) {
|
|
389
|
+
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
const currentTitlePath = [...parentTitlePath, step.title];
|
|
393
|
+
const stepSpanId = this.stepSpanIds.get(stepId) ?? generateSpanId();
|
|
394
|
+
const existingSpan = processedSteps.get(stepId);
|
|
395
|
+
if (existingSpan) {
|
|
396
|
+
if (step.location && !existingSpan.attributes[ATTR_CODE_FILE_PATH]) {
|
|
397
|
+
const { file, line } = step.location;
|
|
398
|
+
const relativePath = this.rootDir ? path.relative(this.rootDir, file) : file;
|
|
399
|
+
existingSpan.attributes[ATTR_CODE_FILE_PATH] = relativePath;
|
|
400
|
+
existingSpan.attributes[ATTR_CODE_LINE_NUMBER] = line;
|
|
401
|
+
}
|
|
402
|
+
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, existingSpan.spanId, traceId, currentTitlePath, processedSteps);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
const attributes = {};
|
|
406
|
+
attributes[ATTR_TEST_STEP_NAME] = currentTitlePath.join(" > ");
|
|
407
|
+
attributes[ATTR_TEST_STEP_TITLE] = step.title;
|
|
408
|
+
attributes[ATTR_TEST_STEP_CATEGORY] = step.category;
|
|
409
|
+
if (step.location) {
|
|
410
|
+
const { file, line } = step.location;
|
|
411
|
+
attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
|
|
412
|
+
attributes[ATTR_CODE_LINE_NUMBER] = line;
|
|
413
|
+
}
|
|
414
|
+
const stepSpan = {
|
|
415
|
+
traceId,
|
|
416
|
+
spanId: stepSpanId,
|
|
417
|
+
parentSpanId,
|
|
418
|
+
name: TEST_STEP_SPAN_NAME,
|
|
419
|
+
startTime: step.startTime,
|
|
420
|
+
endTime: new Date(step.startTime.getTime() + step.duration),
|
|
421
|
+
attributes,
|
|
422
|
+
status: { code: step.error ? 2 : 1 }
|
|
423
|
+
};
|
|
424
|
+
processedSteps.set(stepId, stepSpan);
|
|
425
|
+
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, stepSpan.spanId, traceId, currentTitlePath, processedSteps);
|
|
426
|
+
}
|
|
427
|
+
onStdOut(chunk, _test, _result) {
|
|
428
|
+
if (this.options.debug) console.log(chunk.toString().slice(0, -1));
|
|
429
|
+
}
|
|
430
|
+
onStdErr(chunk, _test, _result) {
|
|
431
|
+
if (this.options.debug) console.log(chunk.toString().slice(0, -1));
|
|
432
|
+
}
|
|
433
|
+
printsToStdio() {
|
|
434
|
+
return this.options.debug ?? false;
|
|
435
|
+
}
|
|
436
|
+
getOutputDir(testId) {
|
|
437
|
+
const outputDir = this.testOutputDirs.get(testId);
|
|
438
|
+
if (!outputDir) throw new Error(`No outputDir found for test "${testId}" - onBegin must be called first and test must exist in suite`);
|
|
439
|
+
return outputDir;
|
|
440
|
+
}
|
|
441
|
+
async sendTestJsonToTraceApi(params) {
|
|
442
|
+
const { test, result, traceId, outputDir, relativeFilePath, startTime, computedDuration } = params;
|
|
443
|
+
const titlePath = test.titlePath();
|
|
444
|
+
const describes = titlePath.length > 4 ? titlePath.slice(3, -1) : [];
|
|
445
|
+
const line = test.location?.line ?? 0;
|
|
446
|
+
const startTimeUnixNano = (startTime.getTime() * 1e6).toString();
|
|
447
|
+
const endTimeUnixNano = ((startTime.getTime() + computedDuration) * 1e6).toString();
|
|
448
|
+
const testJson = {
|
|
449
|
+
name: test.title,
|
|
450
|
+
describes,
|
|
451
|
+
file: relativeFilePath,
|
|
452
|
+
line,
|
|
453
|
+
status: result.status,
|
|
454
|
+
traceId,
|
|
455
|
+
startTimeUnixNano,
|
|
456
|
+
endTimeUnixNano
|
|
457
|
+
};
|
|
458
|
+
const testJsonUrl = `${this.resolvedTraceApiEndpoint}/otel-playwright-reporter/test.json`;
|
|
459
|
+
await fetch(testJsonUrl, {
|
|
460
|
+
method: "PUT",
|
|
461
|
+
headers: {
|
|
462
|
+
"content-type": "application/json",
|
|
463
|
+
"x-trace-id": traceId,
|
|
464
|
+
...this.resolvedTraceApiHeaders
|
|
465
|
+
},
|
|
466
|
+
body: JSON.stringify(testJson)
|
|
467
|
+
});
|
|
468
|
+
const screenshotsDir = path.join(outputDir, PW_OTEL_DIR, test.id, "screenshots");
|
|
469
|
+
if (existsSync(screenshotsDir)) {
|
|
470
|
+
const screenshotFiles = (await readdir(screenshotsDir)).filter((file) => file.endsWith(".jpeg") || file.endsWith(".jpg"));
|
|
471
|
+
await Promise.all(screenshotFiles.map(async (file) => {
|
|
472
|
+
const buffer = await readFile(path.join(screenshotsDir, file));
|
|
473
|
+
const screenshotUrl = `${this.resolvedTraceApiEndpoint}/otel-playwright-reporter/screenshots/${file}`;
|
|
474
|
+
await fetch(screenshotUrl, {
|
|
475
|
+
method: "PUT",
|
|
476
|
+
headers: {
|
|
477
|
+
"content-type": "image/jpeg",
|
|
478
|
+
"x-trace-id": traceId,
|
|
479
|
+
...this.resolvedTraceApiHeaders
|
|
480
|
+
},
|
|
481
|
+
body: buffer
|
|
482
|
+
});
|
|
483
|
+
}));
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
function parseOtlpHeaders(headersString) {
|
|
488
|
+
const headers = {};
|
|
489
|
+
const pairs = headersString.split(",");
|
|
490
|
+
for (const pair of pairs) {
|
|
491
|
+
const [key, ...valueParts] = pair.split("=");
|
|
492
|
+
if (key && valueParts.length > 0) headers[key.trim()] = valueParts.join("=").trim();
|
|
493
|
+
}
|
|
494
|
+
return headers;
|
|
495
|
+
}
|
|
496
|
+
function getConfigurationErrorMessage() {
|
|
497
|
+
return "playwright-opentelemetry reporter requires an OTLP endpoint to be configured.\n\nYou can configure it using environment variables:\n\n export OTEL_EXPORTER_OTLP_ENDPOINT=\"https://api.honeycomb.io\"\n export OTEL_EXPORTER_OTLP_HEADERS=\"x-honeycomb-team=YOUR_API_KEY\"\n export OTEL_SERVICE_NAME=\"my-service\"\n\nOr via playwright.config.ts:\n\nimport { defineConfig } from '@playwright/test';\nimport type { PlaywrightOpentelemetryReporterOptions } from 'playwright-opentelemetry';\n\nexport default defineConfig({\n reporter: [\n [\n 'playwright-opentelemetry/reporter',\n {\n otlpEndpoint: 'http://localhost:4317/v1/traces',\n otlpHeaders: {\n Authorization: 'Bearer YOUR_TOKEN',\n },\n serviceName: 'my-service',\n } satisfies PlaywrightOpentelemetryReporterOptions,\n ],\n ],\n});\n\nNote: Environment variables take precedence over config file options.\n";
|
|
498
|
+
}
|
|
499
|
+
function getStepId(test, step) {
|
|
500
|
+
const startTimeMs = step.startTime.getTime();
|
|
501
|
+
return [
|
|
502
|
+
test.id,
|
|
503
|
+
step.category,
|
|
504
|
+
startTimeMs,
|
|
505
|
+
...step.titlePath()
|
|
506
|
+
].join(" > ");
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
//#endregion
|
|
510
|
+
export { PlaywrightOpentelemetryReporter as t };
|
package/dist/reporter.d.mts
CHANGED
|
@@ -1,43 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
//#region src/reporter/reporter.d.ts
|
|
4
|
-
interface PlaywrightOpentelemetryReporterOptions {
|
|
5
|
-
otlpEndpoint?: string;
|
|
6
|
-
otlpHeaders?: Record<string, string>;
|
|
7
|
-
serviceName?: string;
|
|
8
|
-
debug?: boolean;
|
|
9
|
-
}
|
|
10
|
-
declare class PlaywrightOpentelemetryReporter implements Reporter {
|
|
11
|
-
private options;
|
|
12
|
-
private spans;
|
|
13
|
-
private rootDir?;
|
|
14
|
-
private playwrightVersion?;
|
|
15
|
-
private resolvedEndpoint;
|
|
16
|
-
private resolvedHeaders;
|
|
17
|
-
private resolvedServiceName;
|
|
18
|
-
/** Maps test.id to its project's outputDir */
|
|
19
|
-
private testOutputDirs;
|
|
20
|
-
private testSpans;
|
|
21
|
-
private testTraceIds;
|
|
22
|
-
private stepSpanIds;
|
|
23
|
-
/** Tracks the span context stack per test for append-only file writes */
|
|
24
|
-
private spanContextStacks;
|
|
25
|
-
constructor(options?: PlaywrightOpentelemetryReporterOptions);
|
|
26
|
-
onBegin(config: FullConfig, suite: Suite): void;
|
|
27
|
-
onTestBegin(test: TestCase): void;
|
|
28
|
-
onStepBegin(test: TestCase, _result: TestResult, step: TestStep): Promise<void>;
|
|
29
|
-
onStepEnd(test: TestCase, _result: TestResult, _step: TestStep): void;
|
|
30
|
-
onTestEnd(test: TestCase, result: TestResult): Promise<void>;
|
|
31
|
-
onEnd(_result: FullResult): Promise<void>;
|
|
32
|
-
private processTestStep;
|
|
33
|
-
onStdOut(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
|
|
34
|
-
onStdErr(chunk: string | Buffer, _test: TestCase, _result: TestResult): void;
|
|
35
|
-
printsToStdio(): boolean;
|
|
36
|
-
/**
|
|
37
|
-
* Get the output directory for a test ID.
|
|
38
|
-
* Throws if the test ID was not registered in onBegin.
|
|
39
|
-
*/
|
|
40
|
-
private getOutputDir;
|
|
41
|
-
}
|
|
42
|
-
//#endregion
|
|
43
|
-
export { type PlaywrightOpentelemetryReporterOptions, PlaywrightOpentelemetryReporter as default };
|
|
1
|
+
import { n as PlaywrightOpentelemetryReporterOptions, t as PlaywrightOpentelemetryReporter } from "./index-Di44jFGW.mjs";
|
|
2
|
+
export { PlaywrightOpentelemetryReporterOptions, PlaywrightOpentelemetryReporter as default };
|
package/dist/reporter.mjs
CHANGED
|
@@ -1,317 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { mkdirSync } from "node:fs";
|
|
3
|
-
import path from "node:path";
|
|
1
|
+
import { t as PlaywrightOpentelemetryReporter } from "./reporter-BYzfT1GS.mjs";
|
|
4
2
|
|
|
5
|
-
//#region src/reporter/otel-attributes.ts
|
|
6
|
-
const ATTR_CODE_FILE_PATH = "code.file.path";
|
|
7
|
-
const ATTR_CODE_LINE_NUMBER = "code.line.number";
|
|
8
|
-
const ATTR_TEST_CASE_NAME = "test.case.name";
|
|
9
|
-
const ATTR_TEST_CASE_TITLE = "test.case.title";
|
|
10
|
-
const ATTR_TEST_CASE_RESULT_STATUS = "test.case.result.status";
|
|
11
|
-
|
|
12
|
-
//#endregion
|
|
13
|
-
//#region src/reporter/reporter-attributes.ts
|
|
14
|
-
const TEST_SPAN_NAME = "playwright.test";
|
|
15
|
-
const TEST_STEP_SPAN_NAME = "playwright.test.step";
|
|
16
|
-
const ATTR_TEST_STEP_NAME = "test.step.name";
|
|
17
|
-
const ATTR_TEST_STEP_TITLE = "test.step.title";
|
|
18
|
-
const ATTR_TEST_STEP_CATEGORY = "test.step.category";
|
|
19
|
-
|
|
20
|
-
//#endregion
|
|
21
|
-
//#region package.json
|
|
22
|
-
var version = "0.1.1";
|
|
23
|
-
|
|
24
|
-
//#endregion
|
|
25
|
-
//#region src/reporter/sender.ts
|
|
26
|
-
function dateToNanoseconds(date) {
|
|
27
|
-
return (BigInt(date.getTime()) * BigInt(1e6)).toString();
|
|
28
|
-
}
|
|
29
|
-
function toOtlpAttributes(attributes) {
|
|
30
|
-
return Object.entries(attributes).map(([key, value]) => {
|
|
31
|
-
if (typeof value === "number") return {
|
|
32
|
-
key,
|
|
33
|
-
value: Number.isInteger(value) ? { intValue: value } : { doubleValue: value }
|
|
34
|
-
};
|
|
35
|
-
else if (typeof value === "boolean") return {
|
|
36
|
-
key,
|
|
37
|
-
value: { boolValue: value }
|
|
38
|
-
};
|
|
39
|
-
else return {
|
|
40
|
-
key,
|
|
41
|
-
value: { stringValue: value }
|
|
42
|
-
};
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
const SPAN_KIND_INTERNAL = 1;
|
|
46
|
-
function buildOtlpRequest(spans, serviceName, playwrightVersion) {
|
|
47
|
-
const otlpSpans = spans.map((span) => ({
|
|
48
|
-
traceId: span.traceId,
|
|
49
|
-
spanId: span.spanId,
|
|
50
|
-
parentSpanId: span.parentSpanId || void 0,
|
|
51
|
-
name: span.name,
|
|
52
|
-
kind: SPAN_KIND_INTERNAL,
|
|
53
|
-
startTimeUnixNano: dateToNanoseconds(span.startTime),
|
|
54
|
-
endTimeUnixNano: dateToNanoseconds(span.endTime),
|
|
55
|
-
attributes: toOtlpAttributes(span.attributes),
|
|
56
|
-
droppedAttributesCount: 0,
|
|
57
|
-
events: [],
|
|
58
|
-
droppedEventsCount: 0,
|
|
59
|
-
status: span.status,
|
|
60
|
-
links: [],
|
|
61
|
-
droppedLinksCount: 0
|
|
62
|
-
}));
|
|
63
|
-
return { resourceSpans: [{
|
|
64
|
-
resource: { attributes: [
|
|
65
|
-
{
|
|
66
|
-
key: "service.name",
|
|
67
|
-
value: { stringValue: serviceName }
|
|
68
|
-
},
|
|
69
|
-
{
|
|
70
|
-
key: "service.namespace",
|
|
71
|
-
value: { stringValue: "playwright" }
|
|
72
|
-
},
|
|
73
|
-
{
|
|
74
|
-
key: "service.version",
|
|
75
|
-
value: { stringValue: playwrightVersion }
|
|
76
|
-
}
|
|
77
|
-
] },
|
|
78
|
-
scopeSpans: [{
|
|
79
|
-
scope: {
|
|
80
|
-
name: "playwright-opentelemetry",
|
|
81
|
-
version
|
|
82
|
-
},
|
|
83
|
-
spans: otlpSpans
|
|
84
|
-
}]
|
|
85
|
-
}] };
|
|
86
|
-
}
|
|
87
|
-
async function sendSpans(spans, options) {
|
|
88
|
-
if (spans.length === 0) return;
|
|
89
|
-
const endpoint = options.tracesEndpoint;
|
|
90
|
-
const headers = options.headers || {};
|
|
91
|
-
const body = JSON.stringify(buildOtlpRequest(spans, options.serviceName, options.playwrightVersion));
|
|
92
|
-
if (options.debug) console.log("Sending spans to", endpoint);
|
|
93
|
-
const response = await fetch(endpoint, {
|
|
94
|
-
method: "POST",
|
|
95
|
-
body,
|
|
96
|
-
headers: {
|
|
97
|
-
"content-type": "application/json",
|
|
98
|
-
...headers
|
|
99
|
-
}
|
|
100
|
-
});
|
|
101
|
-
if (!response.ok) {
|
|
102
|
-
const error = await response.text();
|
|
103
|
-
throw new Error(`Failed to send spans: ${response.status} ${response.statusText}, ${error}`);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
//#endregion
|
|
108
|
-
//#region src/reporter/reporter.ts
|
|
109
|
-
var PlaywrightOpentelemetryReporter = class {
|
|
110
|
-
spans = [];
|
|
111
|
-
rootDir;
|
|
112
|
-
playwrightVersion;
|
|
113
|
-
resolvedEndpoint;
|
|
114
|
-
resolvedHeaders;
|
|
115
|
-
resolvedServiceName;
|
|
116
|
-
/** Maps test.id to its project's outputDir */
|
|
117
|
-
testOutputDirs = /* @__PURE__ */ new Map();
|
|
118
|
-
testSpans = /* @__PURE__ */ new Map();
|
|
119
|
-
testTraceIds = /* @__PURE__ */ new Map();
|
|
120
|
-
stepSpanIds = /* @__PURE__ */ new Map();
|
|
121
|
-
/** Tracks the span context stack per test for append-only file writes */
|
|
122
|
-
spanContextStacks = /* @__PURE__ */ new Map();
|
|
123
|
-
constructor(options = {}) {
|
|
124
|
-
this.options = options;
|
|
125
|
-
this.resolvedEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || options.otlpEndpoint || "";
|
|
126
|
-
const envHeaders = process.env.OTEL_EXPORTER_OTLP_HEADERS ? parseOtlpHeaders(process.env.OTEL_EXPORTER_OTLP_HEADERS) : {};
|
|
127
|
-
this.resolvedHeaders = {
|
|
128
|
-
...options.otlpHeaders,
|
|
129
|
-
...envHeaders
|
|
130
|
-
};
|
|
131
|
-
this.resolvedServiceName = process.env.OTEL_SERVICE_NAME || options.serviceName || "playwright-tests";
|
|
132
|
-
if (!this.resolvedEndpoint) throw new Error(getConfigurationErrorMessage());
|
|
133
|
-
}
|
|
134
|
-
onBegin(config, suite) {
|
|
135
|
-
this.rootDir = config.rootDir;
|
|
136
|
-
this.playwrightVersion = config.version;
|
|
137
|
-
for (const test of suite.allTests()) {
|
|
138
|
-
const project = test.parent.project();
|
|
139
|
-
if (project?.outputDir) {
|
|
140
|
-
mkdirSync(path.join(project.outputDir, PW_OTEL_DIR), { recursive: true });
|
|
141
|
-
this.testOutputDirs.set(test.id, project.outputDir);
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
onTestBegin(test) {
|
|
146
|
-
const testId = test.id;
|
|
147
|
-
const outputDir = this.getOutputDir(testId);
|
|
148
|
-
const traceId = getOrCreateTraceId(outputDir, testId);
|
|
149
|
-
this.testTraceIds.set(testId, traceId);
|
|
150
|
-
const testSpanId = generateSpanId();
|
|
151
|
-
this.testSpans.set(testId, testSpanId);
|
|
152
|
-
this.spanContextStacks.set(testId, [testSpanId]);
|
|
153
|
-
writeCurrentSpanId(outputDir, testId, testSpanId);
|
|
154
|
-
createNetworkDirs(outputDir, testId);
|
|
155
|
-
}
|
|
156
|
-
async onStepBegin(test, _result, step) {
|
|
157
|
-
const testId = test.id;
|
|
158
|
-
const outputDir = this.getOutputDir(testId);
|
|
159
|
-
const stepId = getStepId(test, step);
|
|
160
|
-
const stepSpanId = generateSpanId();
|
|
161
|
-
this.stepSpanIds.set(stepId, stepSpanId);
|
|
162
|
-
const stack = this.spanContextStacks.get(testId);
|
|
163
|
-
if (stack) {
|
|
164
|
-
stack.push(stepSpanId);
|
|
165
|
-
writeCurrentSpanId(outputDir, testId, stepSpanId);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
onStepEnd(test, _result, _step) {
|
|
169
|
-
const testId = test.id;
|
|
170
|
-
const outputDir = this.getOutputDir(testId);
|
|
171
|
-
const stack = this.spanContextStacks.get(testId);
|
|
172
|
-
if (stack && stack.length > 1) {
|
|
173
|
-
stack.pop();
|
|
174
|
-
const currentParent = stack[stack.length - 1];
|
|
175
|
-
writeCurrentSpanId(outputDir, testId, currentParent);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
async onTestEnd(test, result) {
|
|
179
|
-
const testId = test.id;
|
|
180
|
-
const outputDir = this.getOutputDir(testId);
|
|
181
|
-
const traceId = this.testTraceIds.get(testId);
|
|
182
|
-
const testSpanId = this.testSpans.get(testId);
|
|
183
|
-
if (!traceId || !testSpanId) throw new Error(`Test ${testId} not found`);
|
|
184
|
-
const attributes = {};
|
|
185
|
-
const titlePath = test.titlePath();
|
|
186
|
-
if (titlePath.length >= 3) attributes[ATTR_TEST_CASE_NAME] = titlePath.slice(3).join(" > ");
|
|
187
|
-
attributes[ATTR_TEST_CASE_TITLE] = test.title;
|
|
188
|
-
attributes[ATTR_TEST_CASE_RESULT_STATUS] = result.status;
|
|
189
|
-
if (test.location) {
|
|
190
|
-
const { file, line } = test.location;
|
|
191
|
-
attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
|
|
192
|
-
attributes[ATTR_CODE_LINE_NUMBER] = line;
|
|
193
|
-
}
|
|
194
|
-
const span = {
|
|
195
|
-
traceId,
|
|
196
|
-
spanId: testSpanId,
|
|
197
|
-
name: TEST_SPAN_NAME,
|
|
198
|
-
startTime: result.startTime,
|
|
199
|
-
endTime: new Date(result.startTime.getTime() + result.duration),
|
|
200
|
-
attributes,
|
|
201
|
-
status: { code: result.status === test.expectedStatus ? 1 : 2 }
|
|
202
|
-
};
|
|
203
|
-
this.spans.push(span);
|
|
204
|
-
const processedSteps = /* @__PURE__ */ new Map();
|
|
205
|
-
if (result.steps && result.steps.length > 0) for (const step of result.steps) this.processTestStep(test, step, testSpanId, traceId, [], processedSteps);
|
|
206
|
-
const networkSpans = await collectNetworkSpans(outputDir, testId);
|
|
207
|
-
for (const networkSpan of networkSpans) this.spans.push(networkSpan);
|
|
208
|
-
}
|
|
209
|
-
async onEnd(_result) {
|
|
210
|
-
await sendSpans(this.spans, {
|
|
211
|
-
tracesEndpoint: this.resolvedEndpoint,
|
|
212
|
-
headers: this.resolvedHeaders,
|
|
213
|
-
serviceName: this.resolvedServiceName,
|
|
214
|
-
playwrightVersion: this.playwrightVersion || "unknown",
|
|
215
|
-
debug: this.options.debug ?? false
|
|
216
|
-
});
|
|
217
|
-
for (const [testId, outputDir] of this.testOutputDirs.entries()) await cleanupTestFiles(outputDir, testId);
|
|
218
|
-
}
|
|
219
|
-
processTestStep(test, step, parentSpanId, traceId, parentTitlePath, processedSteps) {
|
|
220
|
-
const isInternalFixture = step.category === "fixture" && step.location?.file.includes("playwright-opentelemetry") && (step.location?.file.endsWith("fixture.mjs") || step.location?.file.endsWith("fixture/index.ts"));
|
|
221
|
-
const stepId = getStepId(test, step);
|
|
222
|
-
if (isInternalFixture) {
|
|
223
|
-
processedSteps.set(`__skip__${stepId}`, {});
|
|
224
|
-
const existingSpan$1 = processedSteps.get(stepId);
|
|
225
|
-
if (existingSpan$1) {
|
|
226
|
-
const spanIndex = this.spans.indexOf(existingSpan$1);
|
|
227
|
-
if (spanIndex !== -1) this.spans.splice(spanIndex, 1);
|
|
228
|
-
processedSteps.delete(stepId);
|
|
229
|
-
}
|
|
230
|
-
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps);
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
if (processedSteps.has(`__skip__${stepId}`)) {
|
|
234
|
-
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, parentSpanId, traceId, parentTitlePath, processedSteps);
|
|
235
|
-
return;
|
|
236
|
-
}
|
|
237
|
-
const currentTitlePath = [...parentTitlePath, step.title];
|
|
238
|
-
const stepSpanId = this.stepSpanIds.get(stepId) ?? generateSpanId();
|
|
239
|
-
const existingSpan = processedSteps.get(stepId);
|
|
240
|
-
if (existingSpan) {
|
|
241
|
-
if (step.location && !existingSpan.attributes[ATTR_CODE_FILE_PATH]) {
|
|
242
|
-
const { file, line } = step.location;
|
|
243
|
-
const relativePath = this.rootDir ? path.relative(this.rootDir, file) : file;
|
|
244
|
-
existingSpan.attributes[ATTR_CODE_FILE_PATH] = relativePath;
|
|
245
|
-
existingSpan.attributes[ATTR_CODE_LINE_NUMBER] = line;
|
|
246
|
-
}
|
|
247
|
-
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, existingSpan.spanId, traceId, currentTitlePath, processedSteps);
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
const attributes = {};
|
|
251
|
-
attributes[ATTR_TEST_STEP_NAME] = currentTitlePath.join(" > ");
|
|
252
|
-
attributes[ATTR_TEST_STEP_TITLE] = step.title;
|
|
253
|
-
attributes[ATTR_TEST_STEP_CATEGORY] = step.category;
|
|
254
|
-
if (step.location) {
|
|
255
|
-
const { file, line } = step.location;
|
|
256
|
-
attributes[ATTR_CODE_FILE_PATH] = this.rootDir ? path.relative(this.rootDir, file) : file;
|
|
257
|
-
attributes[ATTR_CODE_LINE_NUMBER] = line;
|
|
258
|
-
}
|
|
259
|
-
const stepSpan = {
|
|
260
|
-
traceId,
|
|
261
|
-
spanId: stepSpanId,
|
|
262
|
-
parentSpanId,
|
|
263
|
-
name: TEST_STEP_SPAN_NAME,
|
|
264
|
-
startTime: step.startTime,
|
|
265
|
-
endTime: new Date(step.startTime.getTime() + step.duration),
|
|
266
|
-
attributes,
|
|
267
|
-
status: { code: step.error ? 2 : 1 }
|
|
268
|
-
};
|
|
269
|
-
this.spans.push(stepSpan);
|
|
270
|
-
processedSteps.set(stepId, stepSpan);
|
|
271
|
-
if (step.steps && step.steps.length > 0) for (const childStep of step.steps) this.processTestStep(test, childStep, stepSpan.spanId, traceId, currentTitlePath, processedSteps);
|
|
272
|
-
}
|
|
273
|
-
onStdOut(chunk, _test, _result) {
|
|
274
|
-
if (this.options.debug) console.log(chunk.toString().slice(0, -1));
|
|
275
|
-
}
|
|
276
|
-
onStdErr(chunk, _test, _result) {
|
|
277
|
-
if (this.options.debug) console.log(chunk.toString().slice(0, -1));
|
|
278
|
-
}
|
|
279
|
-
printsToStdio() {
|
|
280
|
-
return this.options.debug ?? false;
|
|
281
|
-
}
|
|
282
|
-
/**
|
|
283
|
-
* Get the output directory for a test ID.
|
|
284
|
-
* Throws if the test ID was not registered in onBegin.
|
|
285
|
-
*/
|
|
286
|
-
getOutputDir(testId) {
|
|
287
|
-
const outputDir = this.testOutputDirs.get(testId);
|
|
288
|
-
if (!outputDir) throw new Error(`No outputDir found for test "${testId}" - onBegin must be called first and test must exist in suite`);
|
|
289
|
-
return outputDir;
|
|
290
|
-
}
|
|
291
|
-
};
|
|
292
|
-
function parseOtlpHeaders(headersString) {
|
|
293
|
-
const headers = {};
|
|
294
|
-
const pairs = headersString.split(",");
|
|
295
|
-
for (const pair of pairs) {
|
|
296
|
-
const [key, ...valueParts] = pair.split("=");
|
|
297
|
-
if (key && valueParts.length > 0) headers[key.trim()] = valueParts.join("=").trim();
|
|
298
|
-
}
|
|
299
|
-
return headers;
|
|
300
|
-
}
|
|
301
|
-
function getConfigurationErrorMessage() {
|
|
302
|
-
return "playwright-opentelemetry reporter requires an OTLP endpoint to be configured.\n\nYou can configure it using environment variables:\n\n export OTEL_EXPORTER_OTLP_ENDPOINT=\"https://api.honeycomb.io\"\n export OTEL_EXPORTER_OTLP_HEADERS=\"x-honeycomb-team=YOUR_API_KEY\"\n export OTEL_SERVICE_NAME=\"my-service\"\n\nOr via playwright.config.ts:\n\nimport { defineConfig } from '@playwright/test';\nimport type { PlaywrightOpentelemetryReporterOptions } from 'playwright-opentelemetry';\n\nexport default defineConfig({\n reporter: [\n [\n 'playwright-opentelemetry/reporter',\n {\n otlpEndpoint: 'http://localhost:4317/v1/traces',\n otlpHeaders: {\n Authorization: 'Bearer YOUR_TOKEN',\n },\n serviceName: 'my-service',\n } satisfies PlaywrightOpentelemetryReporterOptions,\n ],\n ],\n});\n\nNote: Environment variables take precedence over config file options.\n";
|
|
303
|
-
}
|
|
304
|
-
function getStepId(test, step) {
|
|
305
|
-
const startTimeMs = step.startTime.getTime();
|
|
306
|
-
return [
|
|
307
|
-
test.id,
|
|
308
|
-
step.category,
|
|
309
|
-
startTimeMs,
|
|
310
|
-
...step.titlePath()
|
|
311
|
-
].join(" > ");
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
//#endregion
|
|
315
3
|
//#region src/reporter/index.ts
|
|
316
4
|
var reporter_default = PlaywrightOpentelemetryReporter;
|
|
317
5
|
|
|
@@ -1,9 +1,42 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
-
import path from "node:path";
|
|
3
2
|
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
4
|
|
|
5
5
|
//#region src/shared/trace-files.ts
|
|
6
6
|
const PW_OTEL_DIR = "playwright-opentelemetry";
|
|
7
|
+
/**
|
|
8
|
+
* Get the screenshots directory for a specific test.
|
|
9
|
+
*/
|
|
10
|
+
function getScreenshotsDir(outputDir, testId) {
|
|
11
|
+
return path.join(outputDir, PW_OTEL_DIR, `${sanitizeTestId(testId)}-screenshots`);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Copy a screenshot to the appropriate test's screenshots directory.
|
|
15
|
+
* Uses the page-test mapping to determine which test owns this screenshot.
|
|
16
|
+
*
|
|
17
|
+
* @param outputDir - The Playwright output directory
|
|
18
|
+
* @param pageGuid - The page GUID extracted from the screenshot filename
|
|
19
|
+
* @param sourcePath - The source path of the screenshot file
|
|
20
|
+
* @param filename - The screenshot filename
|
|
21
|
+
* @returns true if the screenshot was copied, false if no matching test was found
|
|
22
|
+
*/
|
|
23
|
+
function copyScreenshotForTest(outputDir, pageGuid, sourcePath, filename) {
|
|
24
|
+
const mappingPath = getPageMappingPath(outputDir);
|
|
25
|
+
let mappings = [];
|
|
26
|
+
try {
|
|
27
|
+
const content = readFileSync(mappingPath, "utf-8");
|
|
28
|
+
mappings = JSON.parse(content);
|
|
29
|
+
} catch (err) {
|
|
30
|
+
if (err.code !== "ENOENT") throw err;
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
const mapping = mappings.find((m) => m.pageGuid === pageGuid);
|
|
34
|
+
if (!mapping) return false;
|
|
35
|
+
const screenshotsDir = getScreenshotsDir(outputDir, mapping.testId);
|
|
36
|
+
mkdirSync(screenshotsDir, { recursive: true });
|
|
37
|
+
writeFileSync(path.join(screenshotsDir, filename), readFileSync(sourcePath));
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
7
40
|
function getOrCreateTraceId(outputDir, testId) {
|
|
8
41
|
const tracePath = getTracePath(outputDir, testId);
|
|
9
42
|
if (existsSync(tracePath)) return readFileSync(tracePath, "utf-8");
|
|
@@ -81,6 +114,28 @@ async function collectNetworkSpans(outputDir, testId) {
|
|
|
81
114
|
}
|
|
82
115
|
}
|
|
83
116
|
/**
|
|
117
|
+
* Store a page GUID to test ID mapping.
|
|
118
|
+
* This is used to filter screenshots when creating trace zip files.
|
|
119
|
+
*
|
|
120
|
+
* @param outputDir - The Playwright output directory
|
|
121
|
+
* @param testId - The unique test identifier
|
|
122
|
+
* @param pageGuid - The internal Playwright page GUID
|
|
123
|
+
*/
|
|
124
|
+
function writePageTestMapping(outputDir, testId, pageGuid) {
|
|
125
|
+
const mappingPath = getPageMappingPath(outputDir);
|
|
126
|
+
mkdirSync(path.dirname(mappingPath), { recursive: true });
|
|
127
|
+
let mappings = [];
|
|
128
|
+
if (existsSync(mappingPath)) {
|
|
129
|
+
const content = readFileSync(mappingPath, "utf-8");
|
|
130
|
+
mappings = JSON.parse(content);
|
|
131
|
+
}
|
|
132
|
+
mappings.push({
|
|
133
|
+
testId,
|
|
134
|
+
pageGuid
|
|
135
|
+
});
|
|
136
|
+
writeFileSync(mappingPath, JSON.stringify(mappings, null, 2));
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
84
139
|
* Cleanup all trace files for a test.
|
|
85
140
|
* Called by the reporter after onTestEnd has processed the spans.
|
|
86
141
|
*
|
|
@@ -108,6 +163,14 @@ async function cleanupTestFiles(outputDir, testId) {
|
|
|
108
163
|
} catch (err) {
|
|
109
164
|
if (err.code !== "ENOENT") throw err;
|
|
110
165
|
}
|
|
166
|
+
try {
|
|
167
|
+
await fs.rm(getScreenshotsDir(outputDir, testId), { recursive: true });
|
|
168
|
+
} catch (err) {
|
|
169
|
+
if (err.code !== "ENOENT") throw err;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
function getPageMappingPath(outputDir) {
|
|
173
|
+
return path.join(outputDir, PW_OTEL_DIR, "page-test-mappings.json");
|
|
111
174
|
}
|
|
112
175
|
function getTracePath(outputDir, testId) {
|
|
113
176
|
return path.join(outputDir, PW_OTEL_DIR, `${sanitizeTestId(testId)}.trace`);
|
|
@@ -148,4 +211,4 @@ function generateSpanId() {
|
|
|
148
211
|
}
|
|
149
212
|
|
|
150
213
|
//#endregion
|
|
151
|
-
export {
|
|
214
|
+
export { createNetworkDirs as a, getOrCreateTraceId as c, writeCurrentSpanId as d, writeNetworkSpan as f, copyScreenshotForTest as i, getScreenshotsDir as l, writePageTestMapping as m, cleanupTestFiles as n, generateSpanId as o, writeNetworkSpanParent as p, collectNetworkSpans as r, getCurrentSpanId as s, PW_OTEL_DIR as t, readNetworkSpanParent as u };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "playwright-opentelemetry",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "A reporter for Playwright that can export traces and spans in opentelemetry format.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -23,7 +23,14 @@
|
|
|
23
23
|
"files": [
|
|
24
24
|
"dist"
|
|
25
25
|
],
|
|
26
|
+
"main": "./dist/index.mjs",
|
|
27
|
+
"module": "./dist/index.mjs",
|
|
28
|
+
"types": "./dist/index.d.mts",
|
|
26
29
|
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.mts",
|
|
32
|
+
"default": "./dist/index.mjs"
|
|
33
|
+
},
|
|
27
34
|
"./fixture": {
|
|
28
35
|
"types": "./dist/fixture.d.mts",
|
|
29
36
|
"default": "./dist/fixture.mjs"
|
|
@@ -37,20 +44,20 @@
|
|
|
37
44
|
"peerDependencies": {
|
|
38
45
|
"@playwright/test": "*"
|
|
39
46
|
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@zip.js/zip.js": "^2.8.11"
|
|
49
|
+
},
|
|
40
50
|
"devDependencies": {
|
|
41
51
|
"@biomejs/biome": "2.3.10",
|
|
42
52
|
"@playwright/test": "^1.57.0",
|
|
53
|
+
"@types/bun": "^1.2.6",
|
|
43
54
|
"@types/node": "^25.0.3",
|
|
44
|
-
"tsdown": "^0.18.1"
|
|
45
|
-
"typescript": "^5.9.3",
|
|
46
|
-
"vitest": "^4.0.16"
|
|
55
|
+
"tsdown": "^0.18.1"
|
|
47
56
|
},
|
|
48
57
|
"scripts": {
|
|
49
58
|
"build": "tsdown",
|
|
50
59
|
"dev": "tsdown --watch",
|
|
51
|
-
"test:unit": "vitest",
|
|
52
60
|
"test:e2e": "playwright test",
|
|
53
|
-
"
|
|
54
|
-
"format": "biome format --write"
|
|
61
|
+
"verify:trace-zips": "bun scripts/verify-trace-zips.ts"
|
|
55
62
|
}
|
|
56
63
|
}
|