autotel-playwright 0.4.39 → 0.4.40
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/package.json +2 -3
- package/src/index.test.ts +0 -426
- package/src/index.ts +0 -369
- package/src/reporter.test.ts +0 -81
- package/src/reporter.ts +0 -105
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "autotel-playwright",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.40",
|
|
4
4
|
"description": "Playwright fixture for OpenTelemetry: one span per test and trace context injected into API requests",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -21,12 +21,11 @@
|
|
|
21
21
|
},
|
|
22
22
|
"files": [
|
|
23
23
|
"dist",
|
|
24
|
-
"src",
|
|
25
24
|
"README.md",
|
|
26
25
|
"skills"
|
|
27
26
|
],
|
|
28
27
|
"dependencies": {
|
|
29
|
-
"autotel": "4.
|
|
28
|
+
"autotel": "4.2.0"
|
|
30
29
|
},
|
|
31
30
|
"peerDependencies": {
|
|
32
31
|
"@playwright/test": ">=1.60.0"
|
package/src/index.test.ts
DELETED
|
@@ -1,426 +0,0 @@
|
|
|
1
|
-
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
-
|
|
3
|
-
type Fixtures = {
|
|
4
|
-
_otelTestSpan?: TestSpanFixtureFn | [TestSpanFixtureFn, { scope: 'test' }];
|
|
5
|
-
requestWithTrace?: (
|
|
6
|
-
args: { request: unknown; _otelTestSpan: unknown },
|
|
7
|
-
use: (wrapped: any) => Promise<void>,
|
|
8
|
-
) => Promise<void>;
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
type TestSpanFixtureFn = (
|
|
12
|
-
args: Record<string, never>,
|
|
13
|
-
use: (spanData: unknown) => Promise<void>,
|
|
14
|
-
testInfo: {
|
|
15
|
-
annotations: Array<{ type: string; description?: string }>;
|
|
16
|
-
file?: string;
|
|
17
|
-
line?: number;
|
|
18
|
-
project: { name: string };
|
|
19
|
-
title: string;
|
|
20
|
-
},
|
|
21
|
-
) => Promise<void>;
|
|
22
|
-
|
|
23
|
-
const state: { fixtures?: Fixtures } = {};
|
|
24
|
-
let spanIdCounter = 0;
|
|
25
|
-
let mockDrainResult: unknown[] = [];
|
|
26
|
-
const contextWithSpy = vi.fn((_ctx: unknown, fn: () => Promise<unknown>) => fn());
|
|
27
|
-
const createdSpans: Array<{
|
|
28
|
-
end: ReturnType<typeof vi.fn>;
|
|
29
|
-
recordException: ReturnType<typeof vi.fn>;
|
|
30
|
-
setAttribute: ReturnType<typeof vi.fn>;
|
|
31
|
-
setStatus: ReturnType<typeof vi.fn>;
|
|
32
|
-
spanContext: () => { traceId: string; spanId: string };
|
|
33
|
-
}> = [];
|
|
34
|
-
|
|
35
|
-
vi.mock('@playwright/test', () => ({
|
|
36
|
-
expect,
|
|
37
|
-
test: {
|
|
38
|
-
extend: (fixtures: Fixtures) => {
|
|
39
|
-
state.fixtures = fixtures;
|
|
40
|
-
return fixtures;
|
|
41
|
-
},
|
|
42
|
-
},
|
|
43
|
-
}));
|
|
44
|
-
|
|
45
|
-
vi.mock('autotel', () => ({
|
|
46
|
-
SpanStatusCode: { UNSET: 0, OK: 1, ERROR: 2 },
|
|
47
|
-
context: {
|
|
48
|
-
active: () => ({}),
|
|
49
|
-
with: contextWithSpy,
|
|
50
|
-
},
|
|
51
|
-
getTracer: () => ({
|
|
52
|
-
startSpan: () => {
|
|
53
|
-
const id = String(++spanIdCounter);
|
|
54
|
-
const span = {
|
|
55
|
-
end: vi.fn(),
|
|
56
|
-
recordException: vi.fn(),
|
|
57
|
-
setAttribute: vi.fn(),
|
|
58
|
-
setStatus: vi.fn(),
|
|
59
|
-
spanContext: () => ({ traceId: `trace-${id}`, spanId: `span-${id}` }),
|
|
60
|
-
};
|
|
61
|
-
createdSpans.push(span);
|
|
62
|
-
return span;
|
|
63
|
-
},
|
|
64
|
-
}),
|
|
65
|
-
propagation: {
|
|
66
|
-
inject: (_ctx: unknown, carrier: Record<string, string>) => {
|
|
67
|
-
carrier.traceparent = '00-testtrace-testspan-01';
|
|
68
|
-
},
|
|
69
|
-
},
|
|
70
|
-
otelTrace: {
|
|
71
|
-
setSpan: () => ({}),
|
|
72
|
-
},
|
|
73
|
-
getAutotelTracerProvider: vi.fn(() => ({})),
|
|
74
|
-
getTraceContext: vi.fn(() => null),
|
|
75
|
-
resolveTraceUrl: vi.fn(() => undefined),
|
|
76
|
-
isTracing: vi.fn(() => false),
|
|
77
|
-
enrichWithTraceContext: vi.fn((obj: unknown) => obj),
|
|
78
|
-
}));
|
|
79
|
-
|
|
80
|
-
vi.mock('autotel/test-span-collector', () => ({
|
|
81
|
-
TestSpanCollector: class {
|
|
82
|
-
export = vi.fn();
|
|
83
|
-
drainTrace = vi.fn(() => mockDrainResult);
|
|
84
|
-
shutdown = vi.fn(() => Promise.resolve());
|
|
85
|
-
forceFlush = vi.fn(() => Promise.resolve());
|
|
86
|
-
},
|
|
87
|
-
}));
|
|
88
|
-
|
|
89
|
-
vi.mock('autotel/processors', () => ({
|
|
90
|
-
SimpleSpanProcessor: class {
|
|
91
|
-
constructor() {}
|
|
92
|
-
},
|
|
93
|
-
}));
|
|
94
|
-
|
|
95
|
-
describe('autotel-playwright requestWithTrace.fetch', () => {
|
|
96
|
-
afterEach(() => {
|
|
97
|
-
delete process.env.API_BASE_URL;
|
|
98
|
-
delete process.env.AUTOTEL_PLAYWRIGHT_API_ORIGIN;
|
|
99
|
-
state.fixtures = undefined;
|
|
100
|
-
createdSpans.length = 0;
|
|
101
|
-
spanIdCounter = 0;
|
|
102
|
-
mockDrainResult = [];
|
|
103
|
-
contextWithSpy.mockClear();
|
|
104
|
-
vi.resetModules();
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
it('injects trace headers for string URLs', async () => {
|
|
108
|
-
await import('./index');
|
|
109
|
-
|
|
110
|
-
const requestWithTraceFixture = state.fixtures?.requestWithTrace;
|
|
111
|
-
expect(requestWithTraceFixture).toBeTypeOf('function');
|
|
112
|
-
|
|
113
|
-
const fetchSpy = vi.fn(async () => ({ ok: true }));
|
|
114
|
-
const request = { fetch: fetchSpy } as any;
|
|
115
|
-
let wrapped: any;
|
|
116
|
-
|
|
117
|
-
await requestWithTraceFixture?.(
|
|
118
|
-
{
|
|
119
|
-
request,
|
|
120
|
-
_otelTestSpan: {
|
|
121
|
-
apiBaseUrls: ['http://localhost:3000'],
|
|
122
|
-
carrier: { traceparent: '00-testtrace-testspan-01' },
|
|
123
|
-
testInfo: { title: 'fetch string url' },
|
|
124
|
-
},
|
|
125
|
-
},
|
|
126
|
-
async (value) => {
|
|
127
|
-
wrapped = value;
|
|
128
|
-
},
|
|
129
|
-
);
|
|
130
|
-
|
|
131
|
-
await wrapped.fetch('http://localhost:3000/health');
|
|
132
|
-
|
|
133
|
-
expect(fetchSpy).toHaveBeenCalledWith(
|
|
134
|
-
'http://localhost:3000/health',
|
|
135
|
-
expect.objectContaining({
|
|
136
|
-
headers: expect.objectContaining({
|
|
137
|
-
traceparent: '00-testtrace-testspan-01',
|
|
138
|
-
'x-test-name': 'fetch string url',
|
|
139
|
-
}),
|
|
140
|
-
}),
|
|
141
|
-
);
|
|
142
|
-
});
|
|
143
|
-
|
|
144
|
-
it('injects trace headers for Playwright Request objects', async () => {
|
|
145
|
-
await import('./index');
|
|
146
|
-
|
|
147
|
-
const requestWithTraceFixture = state.fixtures?.requestWithTrace;
|
|
148
|
-
expect(requestWithTraceFixture).toBeTypeOf('function');
|
|
149
|
-
|
|
150
|
-
const fetchSpy = vi.fn(async () => ({ ok: true }));
|
|
151
|
-
const request = { fetch: fetchSpy } as any;
|
|
152
|
-
let wrapped: any;
|
|
153
|
-
|
|
154
|
-
await requestWithTraceFixture?.(
|
|
155
|
-
{
|
|
156
|
-
request,
|
|
157
|
-
_otelTestSpan: {
|
|
158
|
-
apiBaseUrls: ['http://localhost:3000'],
|
|
159
|
-
carrier: { traceparent: '00-testtrace-testspan-01' },
|
|
160
|
-
testInfo: { title: 'fetch request object' },
|
|
161
|
-
},
|
|
162
|
-
},
|
|
163
|
-
async (value) => {
|
|
164
|
-
wrapped = value;
|
|
165
|
-
},
|
|
166
|
-
);
|
|
167
|
-
|
|
168
|
-
const playwrightRequestLike = {
|
|
169
|
-
url: () => 'http://localhost:3000/health',
|
|
170
|
-
};
|
|
171
|
-
|
|
172
|
-
await wrapped.fetch(playwrightRequestLike);
|
|
173
|
-
|
|
174
|
-
expect(fetchSpy).toHaveBeenCalledWith(
|
|
175
|
-
playwrightRequestLike,
|
|
176
|
-
expect.objectContaining({
|
|
177
|
-
headers: expect.objectContaining({
|
|
178
|
-
traceparent: '00-testtrace-testspan-01',
|
|
179
|
-
'x-test-name': 'fetch request object',
|
|
180
|
-
}),
|
|
181
|
-
}),
|
|
182
|
-
);
|
|
183
|
-
});
|
|
184
|
-
});
|
|
185
|
-
|
|
186
|
-
describe('autotel-playwright annotations', () => {
|
|
187
|
-
afterEach(() => {
|
|
188
|
-
delete process.env.API_BASE_URL;
|
|
189
|
-
delete process.env.AUTOTEL_PLAYWRIGHT_API_ORIGIN;
|
|
190
|
-
state.fixtures = undefined;
|
|
191
|
-
createdSpans.length = 0;
|
|
192
|
-
spanIdCounter = 0;
|
|
193
|
-
mockDrainResult = [];
|
|
194
|
-
contextWithSpy.mockClear();
|
|
195
|
-
vi.resetModules();
|
|
196
|
-
});
|
|
197
|
-
|
|
198
|
-
it('supports semicolon-delimited autotel.attribute key-value pairs', async () => {
|
|
199
|
-
await import('./index');
|
|
200
|
-
|
|
201
|
-
const spanFixture = state.fixtures?._otelTestSpan;
|
|
202
|
-
const spanFixtureFn = Array.isArray(spanFixture) ? spanFixture[0] : spanFixture;
|
|
203
|
-
expect(spanFixtureFn).toBeTypeOf('function');
|
|
204
|
-
|
|
205
|
-
await spanFixtureFn?.(
|
|
206
|
-
{},
|
|
207
|
-
async () => {},
|
|
208
|
-
{
|
|
209
|
-
annotations: [
|
|
210
|
-
{
|
|
211
|
-
type: 'autotel.attribute',
|
|
212
|
-
description: 'team=checkout;flow=signup',
|
|
213
|
-
},
|
|
214
|
-
],
|
|
215
|
-
project: { name: 'chromium' },
|
|
216
|
-
title: 'annotation parsing',
|
|
217
|
-
},
|
|
218
|
-
);
|
|
219
|
-
|
|
220
|
-
const span = createdSpans[0];
|
|
221
|
-
expect(span).toBeDefined();
|
|
222
|
-
expect(span.setAttribute).toHaveBeenCalledWith('team', 'checkout');
|
|
223
|
-
expect(span.setAttribute).toHaveBeenCalledWith('flow', 'signup');
|
|
224
|
-
});
|
|
225
|
-
|
|
226
|
-
it('attaches otel-spans annotation to testInfo when collector returns spans', async () => {
|
|
227
|
-
mockDrainResult = [
|
|
228
|
-
{ spanId: 's1', name: 'e2e:test', startTimeMs: 1000, durationMs: 100, status: 'ok' },
|
|
229
|
-
];
|
|
230
|
-
|
|
231
|
-
await import('./index');
|
|
232
|
-
|
|
233
|
-
const spanFixture = state.fixtures?._otelTestSpan;
|
|
234
|
-
const spanFixtureFn = Array.isArray(spanFixture) ? spanFixture[0] : spanFixture;
|
|
235
|
-
|
|
236
|
-
const annotations: Array<{ type: string; description?: string }> = [];
|
|
237
|
-
await spanFixtureFn?.(
|
|
238
|
-
{},
|
|
239
|
-
async () => {},
|
|
240
|
-
{
|
|
241
|
-
annotations,
|
|
242
|
-
project: { name: 'chromium' },
|
|
243
|
-
title: 'otel-spans test',
|
|
244
|
-
},
|
|
245
|
-
);
|
|
246
|
-
|
|
247
|
-
const spansAnnotation = annotations.find((a) => a.type === 'otel-spans');
|
|
248
|
-
expect(spansAnnotation).toBeDefined();
|
|
249
|
-
expect(JSON.parse(spansAnnotation!.description!)).toEqual([
|
|
250
|
-
{ spanId: 's1', name: 'e2e:test', startTimeMs: 1000, durationMs: 100, status: 'ok' },
|
|
251
|
-
]);
|
|
252
|
-
});
|
|
253
|
-
|
|
254
|
-
it('marks the test span as error and records exception when test body throws', async () => {
|
|
255
|
-
await import('./index');
|
|
256
|
-
|
|
257
|
-
const spanFixture = state.fixtures?._otelTestSpan;
|
|
258
|
-
const spanFixtureFn = Array.isArray(spanFixture) ? spanFixture[0] : spanFixture;
|
|
259
|
-
expect(spanFixtureFn).toBeTypeOf('function');
|
|
260
|
-
|
|
261
|
-
const testError = new Error('fixture blew up');
|
|
262
|
-
await expect(
|
|
263
|
-
spanFixtureFn?.(
|
|
264
|
-
{},
|
|
265
|
-
async () => {
|
|
266
|
-
throw testError;
|
|
267
|
-
},
|
|
268
|
-
{
|
|
269
|
-
annotations: [],
|
|
270
|
-
project: { name: 'chromium' },
|
|
271
|
-
title: 'failing fixture test',
|
|
272
|
-
},
|
|
273
|
-
),
|
|
274
|
-
).rejects.toThrow('fixture blew up');
|
|
275
|
-
|
|
276
|
-
const span = createdSpans[0];
|
|
277
|
-
expect(span).toBeDefined();
|
|
278
|
-
expect(span.setStatus).toHaveBeenCalled();
|
|
279
|
-
expect(span.recordException).toHaveBeenCalledWith(testError);
|
|
280
|
-
});
|
|
281
|
-
|
|
282
|
-
it('runs test body inside the test span context', async () => {
|
|
283
|
-
await import('./index');
|
|
284
|
-
|
|
285
|
-
const spanFixture = state.fixtures?._otelTestSpan;
|
|
286
|
-
const spanFixtureFn = Array.isArray(spanFixture) ? spanFixture[0] : spanFixture;
|
|
287
|
-
expect(spanFixtureFn).toBeTypeOf('function');
|
|
288
|
-
|
|
289
|
-
await spanFixtureFn?.(
|
|
290
|
-
{},
|
|
291
|
-
async () => {},
|
|
292
|
-
{
|
|
293
|
-
annotations: [],
|
|
294
|
-
project: { name: 'chromium' },
|
|
295
|
-
title: 'context propagation test',
|
|
296
|
-
},
|
|
297
|
-
);
|
|
298
|
-
|
|
299
|
-
// Once to build carrier, once to run the test body under the span context.
|
|
300
|
-
expect(contextWithSpy).toHaveBeenCalledTimes(2);
|
|
301
|
-
});
|
|
302
|
-
});
|
|
303
|
-
|
|
304
|
-
describe('autotel-playwright step', () => {
|
|
305
|
-
afterEach(() => {
|
|
306
|
-
createdSpans.length = 0;
|
|
307
|
-
vi.resetModules();
|
|
308
|
-
});
|
|
309
|
-
|
|
310
|
-
it('marks step span as error and records exception when the step throws', async () => {
|
|
311
|
-
const { step } = await import('./index');
|
|
312
|
-
const err = new Error('step failed');
|
|
313
|
-
|
|
314
|
-
await expect(step('boom', async () => Promise.reject(err))).rejects.toThrow('step failed');
|
|
315
|
-
|
|
316
|
-
const stepSpan = createdSpans.at(-1);
|
|
317
|
-
expect(stepSpan).toBeDefined();
|
|
318
|
-
expect(stepSpan?.setStatus).toHaveBeenCalled();
|
|
319
|
-
expect(stepSpan?.recordException).toHaveBeenCalledWith(err);
|
|
320
|
-
});
|
|
321
|
-
});
|
|
322
|
-
|
|
323
|
-
describe('trace context helper re-exports', () => {
|
|
324
|
-
it('re-exports getTraceContext', async () => {
|
|
325
|
-
const mod = await import('./index');
|
|
326
|
-
expect(mod.getTraceContext).toBeTypeOf('function');
|
|
327
|
-
});
|
|
328
|
-
|
|
329
|
-
it('re-exports resolveTraceUrl', async () => {
|
|
330
|
-
const mod = await import('./index');
|
|
331
|
-
expect(mod.resolveTraceUrl).toBeTypeOf('function');
|
|
332
|
-
});
|
|
333
|
-
|
|
334
|
-
it('re-exports isTracing', async () => {
|
|
335
|
-
const mod = await import('./index');
|
|
336
|
-
expect(mod.isTracing).toBeTypeOf('function');
|
|
337
|
-
});
|
|
338
|
-
|
|
339
|
-
it('re-exports enrichWithTraceContext', async () => {
|
|
340
|
-
const mod = await import('./index');
|
|
341
|
-
expect(mod.enrichWithTraceContext).toBeTypeOf('function');
|
|
342
|
-
});
|
|
343
|
-
});
|
|
344
|
-
|
|
345
|
-
// Minimal APIRequestContext mock for createTestSpansClient tests
|
|
346
|
-
function makeRequest(responseBody: unknown, status = 200) {
|
|
347
|
-
const mockResponse = {
|
|
348
|
-
ok: () => status >= 200 && status < 300,
|
|
349
|
-
status: () => status,
|
|
350
|
-
json: async () => responseBody,
|
|
351
|
-
};
|
|
352
|
-
return {
|
|
353
|
-
get: vi.fn().mockResolvedValue(mockResponse),
|
|
354
|
-
delete: vi.fn().mockResolvedValue(mockResponse),
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
describe('createTestSpansClient', () => {
|
|
359
|
-
afterEach(() => {
|
|
360
|
-
vi.resetModules();
|
|
361
|
-
});
|
|
362
|
-
|
|
363
|
-
it('getSpans calls GET /api/test-spans', async () => {
|
|
364
|
-
const { createTestSpansClient } = await import('./index');
|
|
365
|
-
const mockSpan = {
|
|
366
|
-
name: 'sendMoney.handler',
|
|
367
|
-
spanId: 'abc',
|
|
368
|
-
traceId: 'trace',
|
|
369
|
-
attributes: {},
|
|
370
|
-
status: { code: 0 },
|
|
371
|
-
durationMs: 100,
|
|
372
|
-
};
|
|
373
|
-
const req = makeRequest({ spans: [mockSpan] });
|
|
374
|
-
const client = createTestSpansClient('http://localhost:3100');
|
|
375
|
-
const spans = await client.getSpans(req as any);
|
|
376
|
-
expect(req.get).toHaveBeenCalledWith('http://localhost:3100/api/test-spans');
|
|
377
|
-
expect(spans).toHaveLength(1);
|
|
378
|
-
expect(spans[0].name).toBe('sendMoney.handler');
|
|
379
|
-
});
|
|
380
|
-
|
|
381
|
-
it('getSpans uses custom path when provided', async () => {
|
|
382
|
-
const { createTestSpansClient } = await import('./index');
|
|
383
|
-
const req = makeRequest({ spans: [] });
|
|
384
|
-
const client = createTestSpansClient('http://localhost:3100', { path: '/custom/spans' });
|
|
385
|
-
await client.getSpans(req as any);
|
|
386
|
-
expect(req.get).toHaveBeenCalledWith('http://localhost:3100/custom/spans');
|
|
387
|
-
});
|
|
388
|
-
|
|
389
|
-
it('getSpans throws when response not ok', async () => {
|
|
390
|
-
const { createTestSpansClient } = await import('./index');
|
|
391
|
-
const req = makeRequest({ error: 'not found' }, 404);
|
|
392
|
-
const client = createTestSpansClient('http://localhost:3100');
|
|
393
|
-
await expect(client.getSpans(req as any)).rejects.toThrow('GET /api/test-spans failed: 404');
|
|
394
|
-
});
|
|
395
|
-
|
|
396
|
-
it('clearSpans calls DELETE /api/test-spans', async () => {
|
|
397
|
-
const { createTestSpansClient } = await import('./index');
|
|
398
|
-
const req = makeRequest({ ok: true });
|
|
399
|
-
const client = createTestSpansClient('http://localhost:3100');
|
|
400
|
-
await client.clearSpans(req as any);
|
|
401
|
-
expect(req.delete).toHaveBeenCalledWith('http://localhost:3100/api/test-spans');
|
|
402
|
-
});
|
|
403
|
-
|
|
404
|
-
it('clearSpans uses custom path when provided', async () => {
|
|
405
|
-
const { createTestSpansClient } = await import('./index');
|
|
406
|
-
const req = makeRequest({ ok: true });
|
|
407
|
-
const client = createTestSpansClient('http://localhost:3100', { path: '/custom/spans' });
|
|
408
|
-
await client.clearSpans(req as any);
|
|
409
|
-
expect(req.delete).toHaveBeenCalledWith('http://localhost:3100/custom/spans');
|
|
410
|
-
});
|
|
411
|
-
|
|
412
|
-
it('clearSpans throws when response not ok', async () => {
|
|
413
|
-
const { createTestSpansClient } = await import('./index');
|
|
414
|
-
const req = makeRequest({ error: 'not found' }, 404);
|
|
415
|
-
const client = createTestSpansClient('http://localhost:3100');
|
|
416
|
-
await expect(client.clearSpans(req as any)).rejects.toThrow('DELETE /api/test-spans failed: 404');
|
|
417
|
-
});
|
|
418
|
-
|
|
419
|
-
it('strips trailing slash from baseUrl', async () => {
|
|
420
|
-
const { createTestSpansClient } = await import('./index');
|
|
421
|
-
const req = makeRequest({ spans: [] });
|
|
422
|
-
const client = createTestSpansClient('http://localhost:3100/');
|
|
423
|
-
await client.getSpans(req as any);
|
|
424
|
-
expect(req.get).toHaveBeenCalledWith('http://localhost:3100/api/test-spans');
|
|
425
|
-
});
|
|
426
|
-
});
|
package/src/index.ts
DELETED
|
@@ -1,369 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* autotel-playwright
|
|
3
|
-
*
|
|
4
|
-
* Playwright fixture that creates one OTel span per test and injects W3C trace
|
|
5
|
-
* context into requests to your API so "test → API" appears as one trace.
|
|
6
|
-
*
|
|
7
|
-
* @example
|
|
8
|
-
* // globalSetup.ts: init({ service: 'e2e-tests' });
|
|
9
|
-
* // In spec:
|
|
10
|
-
* import { test, expect } from 'autotel-playwright';
|
|
11
|
-
* test('checks health', async ({ page }) => {
|
|
12
|
-
* await page.goto(API_BASE_URL + '/health'); // request gets traceparent
|
|
13
|
-
* });
|
|
14
|
-
* // Node-side API calls with trace context:
|
|
15
|
-
* test('api health', async ({ requestWithTrace }) => {
|
|
16
|
-
* const res = await requestWithTrace.get(API_BASE_URL + '/health');
|
|
17
|
-
* expect(res.ok()).toBeTruthy();
|
|
18
|
-
* });
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
import { test as base } from '@playwright/test';
|
|
22
|
-
import type { Page, APIRequestContext, Request as PlaywrightRequest } from '@playwright/test';
|
|
23
|
-
import type { TestInfo } from '@playwright/test';
|
|
24
|
-
import type { AutotelConfig } from 'autotel';
|
|
25
|
-
import {
|
|
26
|
-
getTracer,
|
|
27
|
-
getAutotelTracerProvider,
|
|
28
|
-
context as otelContext,
|
|
29
|
-
propagation,
|
|
30
|
-
otelTrace,
|
|
31
|
-
SpanStatusCode,
|
|
32
|
-
} from 'autotel';
|
|
33
|
-
import { TestSpanCollector } from 'autotel/test-span-collector';
|
|
34
|
-
import { SimpleSpanProcessor } from 'autotel/processors';
|
|
35
|
-
|
|
36
|
-
const TRACER_NAME = 'playwright-tests';
|
|
37
|
-
const TRACER_VERSION = '0.1.0';
|
|
38
|
-
|
|
39
|
-
let collector: TestSpanCollector | null = null;
|
|
40
|
-
|
|
41
|
-
interface TracerProviderWithProcessor {
|
|
42
|
-
addSpanProcessor(processor: unknown): void;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function ensureCollector(): TestSpanCollector {
|
|
46
|
-
if (!collector) {
|
|
47
|
-
collector = new TestSpanCollector();
|
|
48
|
-
const provider = getAutotelTracerProvider();
|
|
49
|
-
if ('addSpanProcessor' in provider) {
|
|
50
|
-
(provider as TracerProviderWithProcessor).addSpanProcessor(
|
|
51
|
-
new SimpleSpanProcessor(collector),
|
|
52
|
-
);
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
return collector;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/** Env keys for API base URL (requests to this origin get trace context injected). */
|
|
59
|
-
const ENV_API_BASE_URL = 'API_BASE_URL';
|
|
60
|
-
const ENV_API_ORIGIN = 'AUTOTEL_PLAYWRIGHT_API_ORIGIN';
|
|
61
|
-
|
|
62
|
-
function getApiBaseUrls(): string[] {
|
|
63
|
-
const a = process.env[ENV_API_BASE_URL];
|
|
64
|
-
const b = process.env[ENV_API_ORIGIN];
|
|
65
|
-
const urls: string[] = [];
|
|
66
|
-
if (a) urls.push(a.replace(/\/$/, ''));
|
|
67
|
-
if (b) urls.push(b.replace(/\/$/, ''));
|
|
68
|
-
return [...new Set(urls)];
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Returns true if requestUrl should receive trace headers for the given apiBaseUrls.
|
|
73
|
-
* When a base URL includes a path (e.g. http://localhost:3000/api), only requests
|
|
74
|
-
* whose path starts with that path segment match; same-origin but different path
|
|
75
|
-
* (e.g. /health) must not match to avoid leaking trace context to unrelated endpoints.
|
|
76
|
-
*/
|
|
77
|
-
function urlMatchesApiOrigin(requestUrl: string, apiBaseUrls: string[]): boolean {
|
|
78
|
-
if (apiBaseUrls.length === 0) return false;
|
|
79
|
-
try {
|
|
80
|
-
const u = new URL(requestUrl);
|
|
81
|
-
const requestOrigin = u.origin;
|
|
82
|
-
const requestPathname = u.pathname;
|
|
83
|
-
return apiBaseUrls.some((base) => {
|
|
84
|
-
try {
|
|
85
|
-
const b = new URL(base);
|
|
86
|
-
if (requestOrigin !== b.origin) return false;
|
|
87
|
-
const basePathname = b.pathname.replace(/\/$/, '') || '/';
|
|
88
|
-
if (basePathname === '/') return true;
|
|
89
|
-
return (
|
|
90
|
-
requestPathname === basePathname || requestPathname.startsWith(basePathname + '/')
|
|
91
|
-
);
|
|
92
|
-
} catch {
|
|
93
|
-
return requestUrl.startsWith(base);
|
|
94
|
-
}
|
|
95
|
-
});
|
|
96
|
-
} catch {
|
|
97
|
-
return apiBaseUrls.some((base) => requestUrl.startsWith(base));
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Annotation type for custom span attributes: description should be "key=value" or "key=value1;key2=value2". */
|
|
102
|
-
export const AUTOTEL_ATTRIBUTE_ANNOTATION = 'autotel.attribute';
|
|
103
|
-
|
|
104
|
-
function setAttributesFromAnnotations(
|
|
105
|
-
span: { setAttribute: (k: string, v: string | number | boolean) => void },
|
|
106
|
-
testInfo: { annotations: Array<{ type: string; description?: string }> },
|
|
107
|
-
): void {
|
|
108
|
-
for (const a of testInfo.annotations) {
|
|
109
|
-
if (a.type !== AUTOTEL_ATTRIBUTE_ANNOTATION || !a.description) continue;
|
|
110
|
-
const entries = a.description.split(';');
|
|
111
|
-
for (const entry of entries) {
|
|
112
|
-
const parts = entry.split('=');
|
|
113
|
-
if (parts.length >= 2) {
|
|
114
|
-
const key = parts[0].trim();
|
|
115
|
-
const value = parts.slice(1).join('=').trim();
|
|
116
|
-
span.setAttribute(key, value);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/** Internal: options for get/post/put/patch/delete/head/fetch that may include headers. */
|
|
123
|
-
type RequestOptions = Record<string, unknown> & { headers?: Record<string, string> };
|
|
124
|
-
|
|
125
|
-
function mergeTraceHeaders(
|
|
126
|
-
url: string,
|
|
127
|
-
options: RequestOptions | undefined,
|
|
128
|
-
apiBaseUrls: string[],
|
|
129
|
-
carrier: Record<string, string>,
|
|
130
|
-
testName: string,
|
|
131
|
-
): RequestOptions {
|
|
132
|
-
const opts = options ?? {};
|
|
133
|
-
if (!urlMatchesApiOrigin(url, apiBaseUrls)) return opts;
|
|
134
|
-
return {
|
|
135
|
-
...opts,
|
|
136
|
-
headers: { ...(opts.headers as Record<string, string>), ...carrier, 'x-test-name': testName },
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/** Wraps APIRequestContext so requests to API_BASE_URL get trace context injected. */
|
|
141
|
-
function createRequestWithTrace(
|
|
142
|
-
request: APIRequestContext,
|
|
143
|
-
apiBaseUrls: string[],
|
|
144
|
-
carrier: Record<string, string>,
|
|
145
|
-
testInfo: TestInfo,
|
|
146
|
-
): APIRequestContext {
|
|
147
|
-
const merge = (url: string, options?: RequestOptions) =>
|
|
148
|
-
mergeTraceHeaders(url, options, apiBaseUrls, carrier, testInfo.title);
|
|
149
|
-
|
|
150
|
-
return {
|
|
151
|
-
get: (url: string, options?: RequestOptions) => request.get(url, merge(url, options)),
|
|
152
|
-
post: (url: string, options?: RequestOptions) => request.post(url, merge(url, options)),
|
|
153
|
-
put: (url: string, options?: RequestOptions) => request.put(url, merge(url, options)),
|
|
154
|
-
patch: (url: string, options?: RequestOptions) => request.patch(url, merge(url, options)),
|
|
155
|
-
delete: (url: string, options?: RequestOptions) => request.delete(url, merge(url, options)),
|
|
156
|
-
head: (url: string, options?: RequestOptions) => request.head(url, merge(url, options)),
|
|
157
|
-
fetch: (urlOrRequest: string | PlaywrightRequest, options?: RequestOptions) =>
|
|
158
|
-
request.fetch(urlOrRequest, merge(typeof urlOrRequest === 'string' ? urlOrRequest : urlOrRequest.url(), options)),
|
|
159
|
-
storageState: (options?: { path?: string }) => request.storageState(options),
|
|
160
|
-
dispose: () => request.dispose(),
|
|
161
|
-
} as APIRequestContext;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
type OtelTestSpan = {
|
|
165
|
-
carrier: Record<string, string>;
|
|
166
|
-
apiBaseUrls: string[];
|
|
167
|
-
testInfo: TestInfo;
|
|
168
|
-
};
|
|
169
|
-
|
|
170
|
-
export const test = base.extend<{
|
|
171
|
-
page: Page;
|
|
172
|
-
requestWithTrace: APIRequestContext;
|
|
173
|
-
_otelTestSpan: OtelTestSpan;
|
|
174
|
-
}>({
|
|
175
|
-
_otelTestSpan: [
|
|
176
|
-
// eslint-disable-next-line no-empty-pattern
|
|
177
|
-
async ({}, use, testInfo) => {
|
|
178
|
-
ensureCollector();
|
|
179
|
-
const apiBaseUrls = getApiBaseUrls();
|
|
180
|
-
const tracer = getTracer(TRACER_NAME, TRACER_VERSION);
|
|
181
|
-
const spanName = `e2e:${testInfo.title}`;
|
|
182
|
-
const span = tracer.startSpan(spanName, {
|
|
183
|
-
attributes: {
|
|
184
|
-
'test.title': testInfo.title,
|
|
185
|
-
'test.project': testInfo.project.name,
|
|
186
|
-
'test.file': testInfo.file ?? '',
|
|
187
|
-
'test.line': testInfo.line ?? 0,
|
|
188
|
-
},
|
|
189
|
-
});
|
|
190
|
-
setAttributesFromAnnotations(span, testInfo);
|
|
191
|
-
const ctx = otelTrace.setSpan(otelContext.active(), span);
|
|
192
|
-
const carrier: Record<string, string> = {};
|
|
193
|
-
otelContext.with(ctx, () => {
|
|
194
|
-
propagation.inject(otelContext.active(), carrier);
|
|
195
|
-
});
|
|
196
|
-
try {
|
|
197
|
-
await otelContext.with(ctx, () => use({ carrier, apiBaseUrls, testInfo }));
|
|
198
|
-
} catch (error) {
|
|
199
|
-
span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : 'Unknown error' });
|
|
200
|
-
span.recordException(error instanceof Error ? error : new Error(String(error)));
|
|
201
|
-
throw error;
|
|
202
|
-
} finally {
|
|
203
|
-
span.end();
|
|
204
|
-
const traceId = span.spanContext().traceId;
|
|
205
|
-
const rootSpanId = span.spanContext().spanId;
|
|
206
|
-
const spans = collector!.drainTrace(traceId, rootSpanId);
|
|
207
|
-
if (spans.length > 0) {
|
|
208
|
-
testInfo.annotations.push({
|
|
209
|
-
type: 'otel-spans',
|
|
210
|
-
description: JSON.stringify(spans),
|
|
211
|
-
});
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
},
|
|
215
|
-
{ scope: 'test' },
|
|
216
|
-
],
|
|
217
|
-
|
|
218
|
-
page: async ({ page, _otelTestSpan }, use) => {
|
|
219
|
-
const { carrier, apiBaseUrls, testInfo } = _otelTestSpan;
|
|
220
|
-
if (apiBaseUrls.length > 0) {
|
|
221
|
-
await page.route('**/*', async (route) => {
|
|
222
|
-
const request = route.request();
|
|
223
|
-
const url = request.url();
|
|
224
|
-
if (urlMatchesApiOrigin(url, apiBaseUrls)) {
|
|
225
|
-
const headers = {
|
|
226
|
-
...request.headers(),
|
|
227
|
-
...carrier,
|
|
228
|
-
'x-test-name': testInfo.title,
|
|
229
|
-
};
|
|
230
|
-
await route.continue({ headers });
|
|
231
|
-
} else {
|
|
232
|
-
await route.continue();
|
|
233
|
-
}
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
await use(page);
|
|
237
|
-
},
|
|
238
|
-
|
|
239
|
-
requestWithTrace: async ({ request, _otelTestSpan }, use) => {
|
|
240
|
-
const wrapped = createRequestWithTrace(
|
|
241
|
-
request,
|
|
242
|
-
_otelTestSpan.apiBaseUrls,
|
|
243
|
-
_otelTestSpan.carrier,
|
|
244
|
-
_otelTestSpan.testInfo,
|
|
245
|
-
);
|
|
246
|
-
await use(wrapped);
|
|
247
|
-
},
|
|
248
|
-
});
|
|
249
|
-
|
|
250
|
-
export { expect } from '@playwright/test';
|
|
251
|
-
|
|
252
|
-
// Re-export trace context helpers for DX convenience
|
|
253
|
-
export {
|
|
254
|
-
getTraceContext,
|
|
255
|
-
resolveTraceUrl,
|
|
256
|
-
isTracing,
|
|
257
|
-
enrichWithTraceContext,
|
|
258
|
-
} from 'autotel';
|
|
259
|
-
|
|
260
|
-
export type { OtelTraceContext } from 'autotel';
|
|
261
|
-
|
|
262
|
-
/**
|
|
263
|
-
* Runs a named step as a child span of the current test span. Use inside a test to get
|
|
264
|
-
* step-level spans (e.g. "step:login", "step:navigate") under the test span in the same trace.
|
|
265
|
-
*
|
|
266
|
-
* @example
|
|
267
|
-
* test('user flow', async ({ page }) => {
|
|
268
|
-
* await step('login', async () => {
|
|
269
|
-
* await page.click('button[type=submit]');
|
|
270
|
-
* });
|
|
271
|
-
* await step('open profile', async () => {
|
|
272
|
-
* await page.goto('/profile');
|
|
273
|
-
* });
|
|
274
|
-
* });
|
|
275
|
-
*/
|
|
276
|
-
export async function step<T>(name: string, fn: () => Promise<T>): Promise<T> {
|
|
277
|
-
const tracer = getTracer(TRACER_NAME, TRACER_VERSION);
|
|
278
|
-
const span = tracer.startSpan(`step:${name}`, {
|
|
279
|
-
attributes: { 'step.name': name },
|
|
280
|
-
});
|
|
281
|
-
try {
|
|
282
|
-
return await otelContext.with(otelTrace.setSpan(otelContext.active(), span), fn);
|
|
283
|
-
} catch (error) {
|
|
284
|
-
span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : 'Unknown error' });
|
|
285
|
-
span.recordException(error instanceof Error ? error : new Error(String(error)));
|
|
286
|
-
throw error;
|
|
287
|
-
} finally {
|
|
288
|
-
span.end();
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* Returns a function suitable for Playwright globalSetup that inits autotel.
|
|
294
|
-
* Call autotel.init() with the given options (or defaults) so test spans are exported.
|
|
295
|
-
*/
|
|
296
|
-
export function createGlobalSetup(initOptions?: AutotelConfig): () => Promise<void> {
|
|
297
|
-
return async () => {
|
|
298
|
-
const { init } = await import('autotel');
|
|
299
|
-
init({
|
|
300
|
-
service: 'e2e-tests',
|
|
301
|
-
debug: true,
|
|
302
|
-
...initOptions,
|
|
303
|
-
});
|
|
304
|
-
};
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/**
|
|
308
|
-
* Serialized span returned by the test-spans endpoint (matches autotel-tanstack/testing SerializedSpan).
|
|
309
|
-
*/
|
|
310
|
-
export interface SerializedSpan {
|
|
311
|
-
name: string;
|
|
312
|
-
spanId: string;
|
|
313
|
-
traceId: string;
|
|
314
|
-
parentSpanId?: string;
|
|
315
|
-
attributes?: Record<string, unknown>;
|
|
316
|
-
status: { code: number; message?: string };
|
|
317
|
-
durationMs: number;
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
/**
|
|
321
|
-
* Creates a typed client for the test-spans HTTP endpoint.
|
|
322
|
-
*
|
|
323
|
-
* Pairs with `createTestSpansHandlers()` from `autotel-tanstack/testing`.
|
|
324
|
-
*
|
|
325
|
-
* @param baseUrl - Base URL of the app under test (e.g. 'http://localhost:3100')
|
|
326
|
-
* @param options.path - Path of the test-spans endpoint (default: '/api/test-spans')
|
|
327
|
-
*
|
|
328
|
-
* @example
|
|
329
|
-
* ```typescript
|
|
330
|
-
* const spansClient = createTestSpansClient('http://localhost:3100');
|
|
331
|
-
*
|
|
332
|
-
* test('server function is traced', async ({ request }) => {
|
|
333
|
-
* await spansClient.clearSpans(request);
|
|
334
|
-
* await page.goto('/');
|
|
335
|
-
* // ... trigger action ...
|
|
336
|
-
* const spans = await spansClient.getSpans(request);
|
|
337
|
-
* expect(spans.find(s => s.name === 'sendMoney.handler')).toBeDefined();
|
|
338
|
-
* });
|
|
339
|
-
* ```
|
|
340
|
-
*/
|
|
341
|
-
export function createTestSpansClient(
|
|
342
|
-
baseUrl: string,
|
|
343
|
-
options?: { path?: string },
|
|
344
|
-
): {
|
|
345
|
-
getSpans(request: APIRequestContext): Promise<SerializedSpan[]>;
|
|
346
|
-
clearSpans(request: APIRequestContext): Promise<void>;
|
|
347
|
-
} {
|
|
348
|
-
const base = baseUrl.replace(/\/$/, '');
|
|
349
|
-
const path = options?.path ?? '/api/test-spans';
|
|
350
|
-
const url = `${base}${path}`;
|
|
351
|
-
|
|
352
|
-
return {
|
|
353
|
-
async getSpans(request: APIRequestContext): Promise<SerializedSpan[]> {
|
|
354
|
-
const res = await request.get(url);
|
|
355
|
-
if (!res.ok()) {
|
|
356
|
-
throw new Error(`GET ${path} failed: ${res.status()}`);
|
|
357
|
-
}
|
|
358
|
-
const body = await res.json() as { spans: SerializedSpan[] };
|
|
359
|
-
return body.spans;
|
|
360
|
-
},
|
|
361
|
-
|
|
362
|
-
async clearSpans(request: APIRequestContext): Promise<void> {
|
|
363
|
-
const res = await request.delete(url);
|
|
364
|
-
if (!res.ok()) {
|
|
365
|
-
throw new Error(`DELETE ${path} failed: ${res.status()}`);
|
|
366
|
-
}
|
|
367
|
-
},
|
|
368
|
-
};
|
|
369
|
-
}
|
package/src/reporter.test.ts
DELETED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
import { afterEach, describe, it, expect, vi } from 'vitest';
|
|
2
|
-
|
|
3
|
-
const spans: Array<{ end: ReturnType<typeof vi.fn> }> = [];
|
|
4
|
-
|
|
5
|
-
vi.mock('autotel', () => ({
|
|
6
|
-
SpanStatusCode: { ERROR: 2 },
|
|
7
|
-
context: {
|
|
8
|
-
active: () => ({}),
|
|
9
|
-
with: (_ctx: unknown, fn: () => void) => fn(),
|
|
10
|
-
},
|
|
11
|
-
getTracer: () => ({
|
|
12
|
-
startSpan: () => {
|
|
13
|
-
const span = {
|
|
14
|
-
end: vi.fn(),
|
|
15
|
-
recordException: vi.fn(),
|
|
16
|
-
setStatus: vi.fn(),
|
|
17
|
-
};
|
|
18
|
-
spans.push(span);
|
|
19
|
-
return span;
|
|
20
|
-
},
|
|
21
|
-
}),
|
|
22
|
-
otelTrace: {
|
|
23
|
-
setSpan: () => ({}),
|
|
24
|
-
},
|
|
25
|
-
}));
|
|
26
|
-
|
|
27
|
-
describe('OtelReporter', () => {
|
|
28
|
-
afterEach(() => {
|
|
29
|
-
spans.length = 0;
|
|
30
|
-
vi.resetModules();
|
|
31
|
-
});
|
|
32
|
-
|
|
33
|
-
it('tracks same file/line/title tests independently (no key collisions)', async () => {
|
|
34
|
-
const { OtelReporter } = await import('./reporter');
|
|
35
|
-
const reporter = new OtelReporter();
|
|
36
|
-
|
|
37
|
-
const testA = {
|
|
38
|
-
id: 'project-a-id',
|
|
39
|
-
title: 'shared title',
|
|
40
|
-
location: { file: 'e2e/spec.ts', line: 7 },
|
|
41
|
-
} as any;
|
|
42
|
-
const testB = {
|
|
43
|
-
id: 'project-b-id',
|
|
44
|
-
title: 'shared title',
|
|
45
|
-
location: { file: 'e2e/spec.ts', line: 7 },
|
|
46
|
-
} as any;
|
|
47
|
-
|
|
48
|
-
reporter.onTestBegin(testA, {} as any);
|
|
49
|
-
reporter.onTestBegin(testB, {} as any);
|
|
50
|
-
|
|
51
|
-
reporter.onTestEnd(testA, { status: 'passed' } as any);
|
|
52
|
-
|
|
53
|
-
expect(spans).toHaveLength(2);
|
|
54
|
-
expect(spans[0].end).toHaveBeenCalledTimes(1);
|
|
55
|
-
expect(spans[1].end).not.toHaveBeenCalled();
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
it('marks a step span as error when step.error exists even if result.status is passed', async () => {
|
|
59
|
-
const { OtelReporter } = await import('./reporter');
|
|
60
|
-
const reporter = new OtelReporter();
|
|
61
|
-
|
|
62
|
-
const test = {
|
|
63
|
-
id: 'project-a-id',
|
|
64
|
-
title: 'step failure case',
|
|
65
|
-
location: { file: 'e2e/spec.ts', line: 12 },
|
|
66
|
-
} as any;
|
|
67
|
-
|
|
68
|
-
const step = {
|
|
69
|
-
title: 'failing step',
|
|
70
|
-
error: { message: 'boom', stack: 'stack' },
|
|
71
|
-
} as any;
|
|
72
|
-
|
|
73
|
-
reporter.onTestBegin(test, {} as any);
|
|
74
|
-
reporter.onStepBegin(test, {} as any, step);
|
|
75
|
-
reporter.onStepEnd(test, { status: 'passed' } as any, step);
|
|
76
|
-
|
|
77
|
-
const stepSpan = spans[1] as any;
|
|
78
|
-
expect(stepSpan.recordException).toHaveBeenCalled();
|
|
79
|
-
expect(stepSpan.setStatus).toHaveBeenCalledWith({ code: 2 });
|
|
80
|
-
});
|
|
81
|
-
});
|
package/src/reporter.ts
DELETED
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Optional Playwright reporter that creates OTel spans for each test and step.
|
|
3
|
-
* Runs in the runner process; ensure autotel.init() is called in globalSetup so spans are exported.
|
|
4
|
-
*
|
|
5
|
-
* Use when you want test/step timing and hierarchy in OTLP from the runner side.
|
|
6
|
-
* For "test → API" in one trace (worker side), use the test fixture and requestWithTrace.
|
|
7
|
-
*
|
|
8
|
-
* @example
|
|
9
|
-
* // playwright.config.ts
|
|
10
|
-
* import { defineConfig } from '@playwright/test';
|
|
11
|
-
*
|
|
12
|
-
* export default defineConfig({
|
|
13
|
-
* reporter: [['list'], ['autotel-playwright/reporter']],
|
|
14
|
-
* globalSetup: './globalSetup.ts', // must call init()
|
|
15
|
-
* });
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
import type {
|
|
19
|
-
FullConfig,
|
|
20
|
-
FullResult,
|
|
21
|
-
Reporter,
|
|
22
|
-
Suite,
|
|
23
|
-
TestCase,
|
|
24
|
-
TestResult,
|
|
25
|
-
TestStep,
|
|
26
|
-
} from '@playwright/test/reporter';
|
|
27
|
-
import { getTracer, context as otelContext, otelTrace, SpanStatusCode } from 'autotel';
|
|
28
|
-
|
|
29
|
-
const TRACER_NAME = 'playwright-reporter';
|
|
30
|
-
const TRACER_VERSION = '0.1.0';
|
|
31
|
-
|
|
32
|
-
function testKey(test: TestCase): string {
|
|
33
|
-
return test.id;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** Convert Playwright TestError (no `name` field) to a standard Error for OTel. */
|
|
37
|
-
function toError(testError: { message?: string; stack?: string }): Error {
|
|
38
|
-
const err = new Error(testError.message ?? 'Unknown error');
|
|
39
|
-
if (testError.stack) err.stack = testError.stack;
|
|
40
|
-
return err;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Playwright Reporter that creates one span per test and one per step (as children).
|
|
45
|
-
* Requires autotel.init() in globalSetup so spans are exported.
|
|
46
|
-
*/
|
|
47
|
-
class OtelReporter implements Reporter {
|
|
48
|
-
private testSpans = new Map<string, ReturnType<ReturnType<typeof getTracer>['startSpan']>>();
|
|
49
|
-
private stepSpans = new WeakMap<TestStep, ReturnType<ReturnType<typeof getTracer>['startSpan']>>();
|
|
50
|
-
|
|
51
|
-
onTestBegin(test: TestCase, _result: TestResult): void {
|
|
52
|
-
const tracer = getTracer(TRACER_NAME, TRACER_VERSION);
|
|
53
|
-
const span = tracer.startSpan(`e2e:${test.title}`, {
|
|
54
|
-
attributes: {
|
|
55
|
-
'test.title': test.title,
|
|
56
|
-
'test.file': test.location?.file ?? '',
|
|
57
|
-
'test.line': test.location?.line ?? 0,
|
|
58
|
-
},
|
|
59
|
-
});
|
|
60
|
-
this.testSpans.set(testKey(test), span);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
onTestEnd(test: TestCase, result: TestResult): void {
|
|
64
|
-
const key = testKey(test);
|
|
65
|
-
const span = this.testSpans.get(key);
|
|
66
|
-
if (span) {
|
|
67
|
-
if (result.status !== 'passed' && result.status !== 'skipped') {
|
|
68
|
-
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
69
|
-
if (result.error) span.recordException(toError(result.error));
|
|
70
|
-
}
|
|
71
|
-
span.end();
|
|
72
|
-
this.testSpans.delete(key);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
onStepBegin(test: TestCase, _result: TestResult, step: TestStep): void {
|
|
77
|
-
const testSpan = this.testSpans.get(testKey(test));
|
|
78
|
-
if (!testSpan) return;
|
|
79
|
-
otelContext.with(otelTrace.setSpan(otelContext.active(), testSpan), () => {
|
|
80
|
-
const tracer = getTracer(TRACER_NAME, TRACER_VERSION);
|
|
81
|
-
const span = tracer.startSpan(`step:${step.title}`, {
|
|
82
|
-
attributes: { 'step.name': step.title },
|
|
83
|
-
});
|
|
84
|
-
this.stepSpans.set(step, span);
|
|
85
|
-
});
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
onStepEnd(_test: TestCase, result: TestResult, step: TestStep): void {
|
|
89
|
-
const span = this.stepSpans.get(step);
|
|
90
|
-
if (span) {
|
|
91
|
-
if (step.error) {
|
|
92
|
-
span.recordException(toError(step.error));
|
|
93
|
-
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
94
|
-
}
|
|
95
|
-
span.end();
|
|
96
|
-
this.stepSpans.delete(step);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
onBegin?(_config: FullConfig, _suite: Suite): void {}
|
|
101
|
-
onEnd?(_result: FullResult): void {}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
export { OtelReporter };
|
|
105
|
-
export default OtelReporter;
|