supercov 4.24.8 → 4.26.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/bin/arguments.js +26 -0
- package/bin/supercov.js +2 -1
- package/docs/cli.md +16 -0
- package/docs/workspace-isolation.md +3 -0
- package/package.json +10 -9
- package/runtime/javascript/atomic.mjs +20 -3
- package/runtime/javascript/launchSupervisor.mjs +10 -0
- package/runtime/javascript/playwright.mjs +441 -181
- package/runtime/javascript/playwrightCacheThread.mjs +6 -0
- package/runtime/javascript/register.mjs +84 -10
- package/runtime/javascript/resolve-loader.mjs +45 -3
- package/runtime/javascript/runnerEvidence.mjs +16 -1
- package/runtime/javascript/runtime.mjs +313 -92
- package/runtime/javascript/snapshots.mjs +149 -0
- package/runtime/javascript/transport.mjs +36 -0
- package/runtime/javascript/vitest.mjs +6 -2
|
@@ -18,7 +18,8 @@ import * as standardPlaywright from "@playwright/test";
|
|
|
18
18
|
import * as coverageRuntime from "./runtime.mjs";
|
|
19
19
|
import { inferTestProvenance, testTags } from "./provenance.mjs";
|
|
20
20
|
import { appendJsonLineDurableSync, appendJsonLineSync } from "./atomic.mjs";
|
|
21
|
-
import {
|
|
21
|
+
import { expandSnapshot, mergeSnapshots, columnarEvents } from "./snapshots.mjs";
|
|
22
|
+
import { COVERAGE_DOCUMENT_PHASE_COOKIE, COVERAGE_DOCUMENT_PHASE_SITE_COOKIE, COVERAGE_PHASE_HEADER, COVERAGE_PHASE_COOKIE, COVERAGE_PHASE_SITE_COOKIE, COVERAGE_SCOPE_COOKIE, COVERAGE_SCOPE_HEADER, COVERAGE_SCOPE_SITE_COOKIE, COVERAGE_CARRIER_ENV, encodeCoverageCarrier, encodeCoverageScope, serverEvidenceDirectory, serverEvidencePath, startDocumentInPhase, } from "./transport.mjs";
|
|
22
23
|
export * from "@playwright/test";
|
|
23
24
|
const generatedTargetModule = "__SUPERCOV_PLAYWRIGHT_MODULE__";
|
|
24
25
|
const targetModule = process.env["SUPERCOV_PLAYWRIGHT_MODULE"] ??
|
|
@@ -51,6 +52,33 @@ const browserRuntimePrelude = `(() => { if (globalThis.__SUPERCOV_DIRECT_RUNTIME
|
|
|
51
52
|
const WORKER_ACTIVATION_WAIT_MS = 250;
|
|
52
53
|
const WORKER_SNAPSHOT_WAIT_MS = 5000;
|
|
53
54
|
const WORKER_TIMED_OUT = Symbol("worker did not answer");
|
|
55
|
+
/**
|
|
56
|
+
* Supercov's own Playwright calls, made as one internal API call. Each call a
|
|
57
|
+
* suite makes captures its stack, maps every frame through the runner's
|
|
58
|
+
* source maps, and reports a step and a trace event: the collector's calls at
|
|
59
|
+
* every action did all of that, and on a real suite they were most of what an
|
|
60
|
+
* action waited for, and showed up among the test's own steps. Inside one
|
|
61
|
+
* internal call the rest find its zone: they capture and report nothing. The
|
|
62
|
+
* one stack it captures names nothing anyone reads, so it is not formatted.
|
|
63
|
+
*/
|
|
64
|
+
const unformattedStack = () => "";
|
|
65
|
+
function internally(owner, work) {
|
|
66
|
+
const wrapApiCall = owner?._wrapApiCall;
|
|
67
|
+
if (typeof wrapApiCall !== "function")
|
|
68
|
+
return work();
|
|
69
|
+
const prepareStackTrace = Error.prepareStackTrace;
|
|
70
|
+
Error.prepareStackTrace = unformattedStack;
|
|
71
|
+
try {
|
|
72
|
+
// `{ internal: true }`, or `true` where older releases take a flag.
|
|
73
|
+
return wrapApiCall.call(owner, () => {
|
|
74
|
+
Error.prepareStackTrace = prepareStackTrace;
|
|
75
|
+
return work();
|
|
76
|
+
}, { internal: true });
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
Error.prepareStackTrace = prepareStackTrace;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
54
82
|
function bounded(promise, milliseconds) {
|
|
55
83
|
let timer;
|
|
56
84
|
return Promise.race([
|
|
@@ -96,6 +124,17 @@ function timingCount(bucket, milliseconds = 0) {
|
|
|
96
124
|
entry.ms += milliseconds;
|
|
97
125
|
timingBuckets.set(bucket, entry);
|
|
98
126
|
}
|
|
127
|
+
// How late the test process's event loop runs, while timing: an awaited
|
|
128
|
+
// round trip waits for its reply on this loop as well as on the browser.
|
|
129
|
+
if (timingBuckets) {
|
|
130
|
+
let expected = performance.now() + 5;
|
|
131
|
+
setInterval(() => {
|
|
132
|
+
const now = performance.now();
|
|
133
|
+
if (now - expected > 1)
|
|
134
|
+
timingCount("probe.loopLag", now - expected);
|
|
135
|
+
expected = now + 5;
|
|
136
|
+
}, 5).unref?.();
|
|
137
|
+
}
|
|
99
138
|
async function timed(bucket, work) {
|
|
100
139
|
if (!timingBuckets)
|
|
101
140
|
return work();
|
|
@@ -197,6 +236,7 @@ class CoveragePhaseController {
|
|
|
197
236
|
cdpSessions = new Map();
|
|
198
237
|
newDocumentScriptIds = new Map();
|
|
199
238
|
pendingRegistrations = new Set();
|
|
239
|
+
pendingAssertion;
|
|
200
240
|
pageRegistrations = new WeakMap();
|
|
201
241
|
scriptUpdate = Promise.resolve();
|
|
202
242
|
proxyCache = new WeakMap();
|
|
@@ -211,6 +251,9 @@ class CoveragePhaseController {
|
|
|
211
251
|
// dispose so a worker-scoped context does not keep registering pages with
|
|
212
252
|
// controllers of tests that already finished.
|
|
213
253
|
contextListeners = new Map();
|
|
254
|
+
// Contexts that closed during the test: a phase sent to one failed, and
|
|
255
|
+
// its cookies were then tried again host by host.
|
|
256
|
+
closedContexts = new WeakSet();
|
|
214
257
|
// Snapshots read from pages the suite closed before teardown. A `page`
|
|
215
258
|
// fixture override tears down before the collector's own fixture, and a
|
|
216
259
|
// closed page cannot be evaluated, so the evidence is taken on the way out.
|
|
@@ -257,12 +300,22 @@ class CoveragePhaseController {
|
|
|
257
300
|
allPages() {
|
|
258
301
|
return [...this.pages];
|
|
259
302
|
}
|
|
303
|
+
/** Any Playwright object of this test's, to make internal calls through. */
|
|
304
|
+
anyOwner() {
|
|
305
|
+
for (const owners of [this.contexts, this.pages, this.workers])
|
|
306
|
+
for (const owner of owners)
|
|
307
|
+
return owner;
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
260
310
|
allWorkers() {
|
|
261
311
|
return [...this.workers];
|
|
262
312
|
}
|
|
263
313
|
async collectRuntimeSnapshots() {
|
|
264
314
|
if (this.runtimeSnapshots)
|
|
265
315
|
return this.runtimeSnapshots;
|
|
316
|
+
return internally(this.anyOwner() ?? [...liveTrackedContexts()][0], () => this.collectRuntimeSnapshotsNow());
|
|
317
|
+
}
|
|
318
|
+
async collectRuntimeSnapshotsNow() {
|
|
266
319
|
timingCount("collectRuntimeSnapshots.cold");
|
|
267
320
|
// Contexts the suite created without going through any fixture the
|
|
268
321
|
// collector wraps (a raw `browser.newContext()` mid-test) are found
|
|
@@ -369,6 +422,9 @@ class CoveragePhaseController {
|
|
|
369
422
|
async snapshotBeforeClose(page) {
|
|
370
423
|
if (!this.pages.has(page) || this.snapshottedPages.has(page) || this.runtimeSnapshots)
|
|
371
424
|
return;
|
|
425
|
+
return internally(page, () => this.snapshotBeforeCloseNow(page));
|
|
426
|
+
}
|
|
427
|
+
async snapshotBeforeCloseNow(page) {
|
|
372
428
|
this.snapshottedPages.add(page);
|
|
373
429
|
this.earlySnapshots.push(...(await this.snapshotPage(page)));
|
|
374
430
|
// A dedicated worker ends with the page that owns it, so it is read
|
|
@@ -393,7 +449,7 @@ class CoveragePhaseController {
|
|
|
393
449
|
for (const context of liveTrackedContexts()) {
|
|
394
450
|
if (!this.contexts.has(context)) {
|
|
395
451
|
const headersKnown = trackedContextConfiguredHeaders.has(context);
|
|
396
|
-
await this.registerContext(context, { adopted: !headersKnown }).catch(() => undefined);
|
|
452
|
+
await internally(context, () => this.registerContext(context, { adopted: !headersKnown })).catch(() => undefined);
|
|
397
453
|
}
|
|
398
454
|
}
|
|
399
455
|
}
|
|
@@ -407,8 +463,19 @@ class CoveragePhaseController {
|
|
|
407
463
|
* already has one of this test's phases is left alone: a reset that
|
|
408
464
|
* arrives late must not drop what this test ran.
|
|
409
465
|
*/
|
|
410
|
-
|
|
411
|
-
|
|
466
|
+
/**
|
|
467
|
+
* `pages`, when given, are the pages the test starts with, read from the
|
|
468
|
+
* live contexts while those are being registered: what they carry is in
|
|
469
|
+
* their documents, which registering a context does not touch, so the
|
|
470
|
+
* test's setup need not wait for one before the other.
|
|
471
|
+
*/
|
|
472
|
+
async takeCarriedEvidence(pages) {
|
|
473
|
+
if (pages === undefined)
|
|
474
|
+
await Promise.all([...this.pendingRegistrations]);
|
|
475
|
+
const targets = pages ?? this.allPages();
|
|
476
|
+
return internally(targets[0] ?? this.anyOwner(), () => this.takeCarriedEvidenceNow(targets));
|
|
477
|
+
}
|
|
478
|
+
async takeCarriedEvidenceNow(pages) {
|
|
412
479
|
const prefix = `${this.scope.attemptId}:`;
|
|
413
480
|
const take = (target) => bounded(target
|
|
414
481
|
.evaluate((prefix) => {
|
|
@@ -416,16 +483,17 @@ class CoveragePhaseController {
|
|
|
416
483
|
if (String(coverageGlobal.__SUPERCOV_PHASE_ID__ ?? "").startsWith(prefix))
|
|
417
484
|
return undefined;
|
|
418
485
|
const getSnapshot = coverageGlobal.__SUPERCOV_COVERAGE_SNAPSHOT__;
|
|
486
|
+
const compact = coverageGlobal.__SUPERCOV_COMPACT_SNAPSHOT__;
|
|
419
487
|
const reset = coverageGlobal.__SUPERCOV_RESET__;
|
|
420
488
|
if (!getSnapshot || !reset)
|
|
421
489
|
return undefined;
|
|
422
|
-
const snapshot = JSON.stringify(getSnapshot());
|
|
490
|
+
const snapshot = typeof compact === "function" ? compact(getSnapshot()) : JSON.stringify(getSnapshot());
|
|
423
491
|
reset();
|
|
424
492
|
return snapshot;
|
|
425
493
|
}, prefix)
|
|
426
|
-
.then((text) => (typeof text === "string" ? JSON.parse(text) : undefined))
|
|
494
|
+
.then((text) => (typeof text === "string" ? expandSnapshot(JSON.parse(text)) : undefined))
|
|
427
495
|
.catch(() => undefined), WORKER_ACTIVATION_WAIT_MS);
|
|
428
|
-
const taken = await Promise.all(
|
|
496
|
+
const taken = await Promise.all(pages.flatMap((page) => [
|
|
429
497
|
...page.frames().map(take),
|
|
430
498
|
...page.workers().map(take),
|
|
431
499
|
]));
|
|
@@ -447,7 +515,7 @@ class CoveragePhaseController {
|
|
|
447
515
|
return Promise.resolve();
|
|
448
516
|
let registration = this.pageRegistrations.get(page);
|
|
449
517
|
if (!registration) {
|
|
450
|
-
registration = this.registerNewPage(page);
|
|
518
|
+
registration = internally(page, () => this.registerNewPage(page));
|
|
451
519
|
this.pageRegistrations.set(page, registration);
|
|
452
520
|
}
|
|
453
521
|
return registration;
|
|
@@ -463,7 +531,15 @@ class CoveragePhaseController {
|
|
|
463
531
|
await this.registerContext(context, {
|
|
464
532
|
adopted: !this.contexts.has(context) && tracked && !headersKnown,
|
|
465
533
|
});
|
|
466
|
-
|
|
534
|
+
// A page of a context whose headers are not known learns each phase
|
|
535
|
+
// from a new-document script replaced through a session of its own
|
|
536
|
+
// (activatePage). Every other page needs none: a session with the
|
|
537
|
+
// Page domain on has the browser send it every event of the page a
|
|
538
|
+
// second time, and the browser's own process spent more on that than
|
|
539
|
+
// the renderers spent running the instrumented app.
|
|
540
|
+
const cdp = this.adoptedContexts.has(context)
|
|
541
|
+
? await page.context().newCDPSession(page).catch(() => undefined)
|
|
542
|
+
: undefined;
|
|
467
543
|
if (cdp) {
|
|
468
544
|
// Chromium runs a session's new-document scripts only once the
|
|
469
545
|
// session has enabled the Page domain. Without it the script that
|
|
@@ -471,25 +547,13 @@ class CoveragePhaseController {
|
|
|
471
547
|
// learned its phase only from the next action, after it had
|
|
472
548
|
// loaded, and everything it ran while loading was placed by time.
|
|
473
549
|
await cdp.send("Page.enable").catch(() => undefined);
|
|
474
|
-
// A document that leaves hands its evidence over here: the
|
|
475
|
-
// next one reads what it stored only on the same origin.
|
|
476
|
-
cdp.on("Runtime.bindingCalled", ({ name, payload }) => {
|
|
477
|
-
if (name !== LEAVING_BINDING || this.runtimeSnapshots)
|
|
478
|
-
return;
|
|
479
|
-
try {
|
|
480
|
-
this.leftSnapshots.push(JSON.parse(payload));
|
|
481
|
-
}
|
|
482
|
-
catch {
|
|
483
|
-
// Not evidence.
|
|
484
|
-
}
|
|
485
|
-
});
|
|
486
|
-
await cdp.send("Runtime.enable").catch(() => undefined);
|
|
487
|
-
await cdp.send("Runtime.addBinding", { name: LEAVING_BINDING }).catch(() => undefined);
|
|
488
550
|
this.cdpSessions.set(page, cdp);
|
|
489
551
|
}
|
|
490
552
|
const phaseId = this.requestPhaseId();
|
|
491
|
-
if (phaseId)
|
|
553
|
+
if (phaseId && this.adoptedContexts.has(context))
|
|
492
554
|
await this.activatePage(page, phaseId);
|
|
555
|
+
else if (phaseId)
|
|
556
|
+
await this.activateFrames(phaseId, [page]);
|
|
493
557
|
page.on("worker", (worker) => {
|
|
494
558
|
void this.registerWorker(worker);
|
|
495
559
|
});
|
|
@@ -503,11 +567,23 @@ class CoveragePhaseController {
|
|
|
503
567
|
patchContextPrototype(context);
|
|
504
568
|
if (adopted)
|
|
505
569
|
this.adoptedContexts.add(context);
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
570
|
+
return internally(context, () => this.registerContextNow(context, adopted));
|
|
571
|
+
}
|
|
572
|
+
async registerContextNow(context, adopted) {
|
|
573
|
+
if (timingBuckets) {
|
|
574
|
+
const copies = (contextScriptCopies.get(context) ?? 0) + 1;
|
|
575
|
+
contextScriptCopies.set(context, copies);
|
|
576
|
+
timingCount(copies > 1 ? "registerContext.again" : "registerContext.first", copies);
|
|
577
|
+
}
|
|
578
|
+
// The context's own scripts first: sent when it was made, so they
|
|
579
|
+
// are in place, or sent now for a context made some other way.
|
|
580
|
+
await prepareContext(context);
|
|
581
|
+
// Then what every new document of the context runs for this test, in
|
|
582
|
+
// this order, as one script: one call where several, each awaited,
|
|
583
|
+
// were most of what a test waited for before its page opened. Each
|
|
584
|
+
// part runs on its own, as separate scripts did, so one that throws
|
|
585
|
+
// leaves the others.
|
|
586
|
+
const parts = [];
|
|
511
587
|
// A context that outlives its test (a worker-scoped browser fixture)
|
|
512
588
|
// is registered again by every later test, so this script accumulates
|
|
513
589
|
// on it and each new document runs every copy in registration order.
|
|
@@ -515,55 +591,25 @@ class CoveragePhaseController {
|
|
|
515
591
|
// own attempt, so the newest wins; the fetch patch is installed once
|
|
516
592
|
// and reads the attempt at call time, so a stale copy can never pin an
|
|
517
593
|
// old scope onto a request the way nested wrappers would.
|
|
518
|
-
|
|
519
|
-
const coverageGlobal = globalThis;
|
|
520
|
-
coverageGlobal.__SUPERCOV_ATTEMPT__ = { attemptId, scopeValue };
|
|
521
|
-
coverageGlobal.__SUPERCOV_MCDC_TEST_ID__ = attemptId;
|
|
522
|
-
try {
|
|
523
|
-
document.cookie = `${scopeCookie}=${encodeURIComponent(scopeValue)}; Path=/; SameSite=Lax`;
|
|
524
|
-
// And for this document's frames on another of the app's
|
|
525
|
-
// hosts, where crossing sites is allowed.
|
|
526
|
-
if (globalThis.isSecureContext)
|
|
527
|
-
document.cookie = `${scopeSiteCookie}=${encodeURIComponent(scopeValue)}; Path=/; SameSite=None; Secure`;
|
|
528
|
-
if (!coverageGlobal.__SUPERCOV_BROWSER_FETCH_PATCHED__) {
|
|
529
|
-
const originalFetch = globalThis.fetch?.bind(globalThis);
|
|
530
|
-
if (originalFetch) {
|
|
531
|
-
coverageGlobal.__SUPERCOV_BROWSER_FETCH_PATCHED__ = true;
|
|
532
|
-
globalThis.fetch = ((input, init) => {
|
|
533
|
-
// Only the page's own origin hears the scope. A
|
|
534
|
-
// header on a request to another origin makes the
|
|
535
|
-
// browser ask that origin first, and one that
|
|
536
|
-
// allows only the headers it uses refuses: the
|
|
537
|
-
// page's fetch failed under measurement alone.
|
|
538
|
-
try {
|
|
539
|
-
const target = new URL(input instanceof Request ? input.url : String(input), location.href);
|
|
540
|
-
if (target.origin !== location.origin)
|
|
541
|
-
return originalFetch(input, init);
|
|
542
|
-
}
|
|
543
|
-
catch {
|
|
544
|
-
return originalFetch(input, init);
|
|
545
|
-
}
|
|
546
|
-
const headers = new Headers(init?.headers ??
|
|
547
|
-
(input instanceof Request ? input.headers : undefined));
|
|
548
|
-
headers.set(scopeHeader, coverageGlobal.__SUPERCOV_ATTEMPT__?.scopeValue ?? scopeValue);
|
|
549
|
-
const phase = coverageGlobal.__SUPERCOV_PHASE_ID__;
|
|
550
|
-
if (phase)
|
|
551
|
-
headers.set("x-supercov-phase", phase);
|
|
552
|
-
return originalFetch(input, { ...init, headers });
|
|
553
|
-
});
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
catch {
|
|
558
|
-
// Browser instrumentation must not change application behavior.
|
|
559
|
-
}
|
|
560
|
-
}, {
|
|
594
|
+
parts.push(`(${announceAttempt})(${JSON.stringify({
|
|
561
595
|
attemptId: this.scope.attemptId,
|
|
562
596
|
scopeHeader: COVERAGE_SCOPE_HEADER,
|
|
563
597
|
scopeValue: encodeCoverageScope(this.scope),
|
|
564
598
|
scopeCookie: COVERAGE_SCOPE_COOKIE,
|
|
565
599
|
scopeSiteCookie: COVERAGE_SCOPE_SITE_COOKIE,
|
|
566
|
-
})
|
|
600
|
+
})});`);
|
|
601
|
+
// A new document starts in the last action's phase, from the cookie
|
|
602
|
+
// each action sets: one script per context, where a script replaced on
|
|
603
|
+
// every page at every phase took two Playwright calls each time.
|
|
604
|
+
parts.push(`(${startDocumentInPhase})(${JSON.stringify({
|
|
605
|
+
attemptId: this.scope.attemptId,
|
|
606
|
+
phaseCookie: COVERAGE_DOCUMENT_PHASE_COOKIE,
|
|
607
|
+
phaseSiteCookie: COVERAGE_DOCUMENT_PHASE_SITE_COOKIE,
|
|
608
|
+
})});`);
|
|
609
|
+
await Promise.all([
|
|
610
|
+
context.addInitScript({ content: separately(parts) }).catch(() => undefined),
|
|
611
|
+
adopted ? undefined : this.updateContextHeaders(context, this.requestPhaseId(), this.lastActionId),
|
|
612
|
+
]);
|
|
567
613
|
const register = (page) => {
|
|
568
614
|
const pending = this.registerPage(page).finally(() => this.pendingRegistrations.delete(pending));
|
|
569
615
|
this.pendingRegistrations.add(pending);
|
|
@@ -571,13 +617,13 @@ class CoveragePhaseController {
|
|
|
571
617
|
const registerServiceWorker = (worker) => {
|
|
572
618
|
void this.registerWorker(worker);
|
|
573
619
|
};
|
|
620
|
+
const closed = () => this.closedContexts.add(context);
|
|
574
621
|
context.on("page", register);
|
|
575
622
|
context.on("serviceworker", registerServiceWorker);
|
|
576
|
-
|
|
623
|
+
context.on("close", closed);
|
|
624
|
+
this.contextListeners.set(context, [["page", register], ["serviceworker", registerServiceWorker], ["close", closed]]);
|
|
577
625
|
for (const worker of context.serviceWorkers())
|
|
578
626
|
void this.registerWorker(worker);
|
|
579
|
-
if (!adopted)
|
|
580
|
-
await this.updateContextHeaders(context, this.requestPhaseId());
|
|
581
627
|
for (const page of context.pages())
|
|
582
628
|
register(page);
|
|
583
629
|
}
|
|
@@ -585,6 +631,9 @@ class CoveragePhaseController {
|
|
|
585
631
|
if (this.workers.has(worker))
|
|
586
632
|
return;
|
|
587
633
|
this.workers.add(worker);
|
|
634
|
+
return internally(worker, () => this.registerWorkerNow(worker));
|
|
635
|
+
}
|
|
636
|
+
async registerWorkerNow(worker) {
|
|
588
637
|
const phaseId = this.requestPhaseId();
|
|
589
638
|
const registration = await worker
|
|
590
639
|
.evaluate(({ attemptId, scopeHeader, scopeValue, phaseHeader, phase }) => {
|
|
@@ -636,12 +685,21 @@ class CoveragePhaseController {
|
|
|
636
685
|
const phase = this.createPhase("action", operation);
|
|
637
686
|
this.lastActionId = phase.id;
|
|
638
687
|
this.activePhaseId = phase.id;
|
|
639
|
-
await timed("action.activateInBrowser", () => this.activateInBrowser(phase.id));
|
|
688
|
+
await timed("action.activateInBrowser", () => this.activateInBrowser(phase.id, phase.id));
|
|
640
689
|
return phase;
|
|
641
690
|
}
|
|
642
|
-
beginAssertion(operation, source = callerSource()) {
|
|
691
|
+
beginAssertion(operation, source = callerSource(), reachesBrowser = true) {
|
|
643
692
|
timingCount("beginAssertion");
|
|
644
693
|
const phase = this.createPhase("assertion", operation, this.lastActionId, source);
|
|
694
|
+
// An assertion that is over before any message could reach the
|
|
695
|
+
// browser (`expect(value).toBe(1)`) gets no browser phase: telling the
|
|
696
|
+
// page and the app's cookies afterwards labelled what the page did
|
|
697
|
+
// next, the last action's work, as this assertion's, and queued two
|
|
698
|
+
// calls ahead of the test's next action.
|
|
699
|
+
if (!reachesBrowser) {
|
|
700
|
+
timingCount("assertion.offBrowser");
|
|
701
|
+
return phase;
|
|
702
|
+
}
|
|
645
703
|
this.activePhaseId = phase.id;
|
|
646
704
|
// Playwright queues browser protocol commands in order. Starting this
|
|
647
705
|
// evaluation before an async locator assertion is sufficient to tag its
|
|
@@ -649,12 +707,37 @@ class CoveragePhaseController {
|
|
|
649
707
|
void timed("assertion.activateInBrowser", () => this.activateInBrowser(phase.id));
|
|
650
708
|
return phase;
|
|
651
709
|
}
|
|
710
|
+
/**
|
|
711
|
+
* An instrumented assertion's phase, opened around its arguments as well
|
|
712
|
+
* as its matcher, which reaches the browser just before the first thing
|
|
713
|
+
* in it that can: a call on one of the test's Playwright objects, or a
|
|
714
|
+
* matcher that waits (promotePendingAssertion). Playwright sends calls in
|
|
715
|
+
* order, so the page has the phase before anything the assertion asks of
|
|
716
|
+
* it. One that asks nothing of the page sends nothing.
|
|
717
|
+
*/
|
|
718
|
+
beginBridgedAssertion(operation, source) {
|
|
719
|
+
const phase = this.beginAssertion(operation, source, false);
|
|
720
|
+
this.pendingAssertion = phase;
|
|
721
|
+
return phase;
|
|
722
|
+
}
|
|
723
|
+
promotePendingAssertion() {
|
|
724
|
+
const phase = this.pendingAssertion;
|
|
725
|
+
if (!phase)
|
|
726
|
+
return;
|
|
727
|
+
this.pendingAssertion = undefined;
|
|
728
|
+
timingCount("assertion.promoted");
|
|
729
|
+
this.activePhaseId = phase.id;
|
|
730
|
+
void timed("assertion.activateInBrowser", () => this.activateInBrowser(phase.id));
|
|
731
|
+
}
|
|
652
732
|
requestPhaseId() {
|
|
653
733
|
return this.activePhaseId;
|
|
654
734
|
}
|
|
655
735
|
async dispose() {
|
|
656
736
|
this.disposed = true;
|
|
657
737
|
await Promise.all([...this.pendingRegistrations]);
|
|
738
|
+
return internally(this.anyOwner(), () => this.disposeNow());
|
|
739
|
+
}
|
|
740
|
+
async disposeNow() {
|
|
658
741
|
await this.scriptUpdate;
|
|
659
742
|
for (const [context, listeners] of this.contextListeners) {
|
|
660
743
|
for (const [event, listener] of listeners)
|
|
@@ -662,6 +745,11 @@ class CoveragePhaseController {
|
|
|
662
745
|
}
|
|
663
746
|
this.contextListeners.clear();
|
|
664
747
|
for (const [page, cdp] of this.cdpSessions) {
|
|
748
|
+
// A closed page took its session with it: detaching it failed for
|
|
749
|
+
// every page a test closed, each failure a Playwright error with a
|
|
750
|
+
// stack, and was the only collector call on a slice that failed.
|
|
751
|
+
if (page.isClosed?.())
|
|
752
|
+
continue;
|
|
665
753
|
const identifier = this.newDocumentScriptIds.get(page);
|
|
666
754
|
if (identifier)
|
|
667
755
|
await cdp
|
|
@@ -673,6 +761,8 @@ class CoveragePhaseController {
|
|
|
673
761
|
}
|
|
674
762
|
}
|
|
675
763
|
finish(phase, error) {
|
|
764
|
+
if (this.pendingAssertion === phase)
|
|
765
|
+
this.pendingAssertion = undefined;
|
|
676
766
|
phase.endedAtMs = Date.now();
|
|
677
767
|
phase.status = error === undefined ? "passed" : "failed";
|
|
678
768
|
if (error !== undefined)
|
|
@@ -695,6 +785,7 @@ class CoveragePhaseController {
|
|
|
695
785
|
return value;
|
|
696
786
|
const method = String(property);
|
|
697
787
|
return (...args) => {
|
|
788
|
+
this.promotePendingAssertion();
|
|
698
789
|
const isRequest = REQUEST_METHODS.has(method) &&
|
|
699
790
|
isApiRequestContext(object);
|
|
700
791
|
if (ACTION_METHODS.has(method) || isRequest) {
|
|
@@ -818,19 +909,58 @@ class CoveragePhaseController {
|
|
|
818
909
|
* the 43 extra seconds, with the database worker's bounded wait the
|
|
819
910
|
* largest part).
|
|
820
911
|
*/
|
|
821
|
-
|
|
912
|
+
activateInBrowser(phaseId, documentPhaseId) {
|
|
913
|
+
return internally(this.anyOwner(), () => this.activateInBrowserNow(phaseId, documentPhaseId));
|
|
914
|
+
}
|
|
915
|
+
async activateInBrowserNow(phaseId, documentPhaseId) {
|
|
822
916
|
await Promise.all([
|
|
823
917
|
timed("activate.contextHeaders", () => Promise.all([...this.contexts]
|
|
824
|
-
.filter((context) => !this.adoptedContexts.has(context))
|
|
825
|
-
.map((context) => this.updateContextHeaders(context, phaseId)))),
|
|
918
|
+
.filter((context) => !this.adoptedContexts.has(context) && !this.closedContexts.has(context))
|
|
919
|
+
.map((context) => this.updateContextHeaders(context, phaseId, documentPhaseId)))),
|
|
826
920
|
this.activateFrames(phaseId),
|
|
827
921
|
this.activateWorkers(phaseId),
|
|
828
|
-
|
|
922
|
+
// A context whose headers are not known gets no cookies, so its
|
|
923
|
+
// pages' new documents learn the phase from a script replaced here.
|
|
924
|
+
timed("activate.pageScript", () => Promise.all([...this.pages]
|
|
925
|
+
.filter((page) => this.adoptedContexts.has(page.context()))
|
|
926
|
+
.map((page) => this.activatePage(page, phaseId)))),
|
|
927
|
+
timingBuckets ? this.probeRoundTrips() : undefined,
|
|
928
|
+
]);
|
|
929
|
+
}
|
|
930
|
+
/**
|
|
931
|
+
* While timing, beside each activation: how long a call that does nothing
|
|
932
|
+
* takes to reach a page and come back, and a cookie read of the browser,
|
|
933
|
+
* so an activation's time can be told apart from the round trip's.
|
|
934
|
+
*/
|
|
935
|
+
async probeRoundTrips() {
|
|
936
|
+
const page = [...this.pages].find((candidate) => !candidate.isClosed?.());
|
|
937
|
+
if (!page)
|
|
938
|
+
return;
|
|
939
|
+
const clock = () => performance.timeOrigin + performance.now();
|
|
940
|
+
await Promise.all([
|
|
941
|
+
(async () => {
|
|
942
|
+
const sent = clock();
|
|
943
|
+
const inPage = await page.mainFrame().evaluate(() => performance.timeOrigin + performance.now()).catch(() => undefined);
|
|
944
|
+
const back = clock();
|
|
945
|
+
timingCount("probe.noopEvaluate", back - sent);
|
|
946
|
+
if (typeof inPage === "number") {
|
|
947
|
+
timingCount("probe.toPage", inPage - sent);
|
|
948
|
+
timingCount("probe.fromPage", back - inPage);
|
|
949
|
+
}
|
|
950
|
+
})(),
|
|
951
|
+
timed("probe.noopCookies", () => page.context().cookies("http://supercov.invalid/").catch(() => undefined)),
|
|
829
952
|
]);
|
|
830
953
|
}
|
|
831
|
-
async activateFrames(phaseId) {
|
|
832
|
-
|
|
833
|
-
|
|
954
|
+
async activateFrames(phaseId, pages = this.pages) {
|
|
955
|
+
// The app's own hosts have the phase from the context's cookies, set
|
|
956
|
+
// beside this; a document there writing them again was a round trip
|
|
957
|
+
// to the cookie store per cookie, on every action. A context whose
|
|
958
|
+
// headers are not known gets none, so its documents still write them.
|
|
959
|
+
const covered = (page) => this.adoptedContexts.has(page.context())
|
|
960
|
+
? []
|
|
961
|
+
: this.appHosts.map((url) => new URL(url).hostname);
|
|
962
|
+
await timed("activate.frameEvaluate", () => Promise.all([...pages].filter((page) => !page.isClosed?.()).flatMap((page) => page.frames().map((frame) => [frame, covered(page)])).map(([frame, coveredHosts]) => frame
|
|
963
|
+
.evaluate(({ id, attemptId, storageKey, scopeCookie, scopeValue, phaseCookie, scopeSiteCookie, phaseSiteCookie, coveredHosts }) => {
|
|
834
964
|
globalThis.__SUPERCOV_PHASE_ID__ = id;
|
|
835
965
|
const coverageGlobal = globalThis;
|
|
836
966
|
// A document that loaded under an earlier test's attempt (a page
|
|
@@ -840,6 +970,8 @@ class CoveragePhaseController {
|
|
|
840
970
|
coverageGlobal.__SUPERCOV_ACTIVATE_PROBE_CONTEXT__?.(attemptId, id);
|
|
841
971
|
try {
|
|
842
972
|
localStorage.setItem(storageKey, id);
|
|
973
|
+
if (coveredHosts.includes(location.hostname))
|
|
974
|
+
return;
|
|
843
975
|
document.cookie = `${scopeCookie}=${encodeURIComponent(scopeValue)}; Path=/; SameSite=Lax`;
|
|
844
976
|
document.cookie = `${phaseCookie}=${encodeURIComponent(id)}; Path=/; SameSite=Lax`;
|
|
845
977
|
if (globalThis.isSecureContext) {
|
|
@@ -859,8 +991,9 @@ class CoveragePhaseController {
|
|
|
859
991
|
phaseCookie: COVERAGE_PHASE_COOKIE,
|
|
860
992
|
scopeSiteCookie: COVERAGE_SCOPE_SITE_COOKIE,
|
|
861
993
|
phaseSiteCookie: COVERAGE_PHASE_SITE_COOKIE,
|
|
994
|
+
coveredHosts,
|
|
862
995
|
})
|
|
863
|
-
.catch(() =>
|
|
996
|
+
.catch(() => timingCount("activate.frameRefused")))));
|
|
864
997
|
}
|
|
865
998
|
async activateWorkers(phaseId) {
|
|
866
999
|
await timed("activate.workerEvaluate", () => Promise.all([...this.workers].map(async (worker) => {
|
|
@@ -891,32 +1024,49 @@ class CoveragePhaseController {
|
|
|
891
1024
|
* site from the first navigation on, and, on a secure origin, to frames
|
|
892
1025
|
* of the app's other hosts as well.
|
|
893
1026
|
*/
|
|
894
|
-
async updateContextHeaders(context, phaseId) {
|
|
1027
|
+
async updateContextHeaders(context, phaseId, documentPhaseId) {
|
|
895
1028
|
const scope = encodeURIComponent(encodeCoverageScope(this.scope));
|
|
896
1029
|
const phase = phaseId ? encodeURIComponent(phaseId) : undefined;
|
|
897
|
-
const
|
|
1030
|
+
const documentPhase = documentPhaseId ? encodeURIComponent(documentPhaseId) : undefined;
|
|
1031
|
+
const pairs = (scopeName, phaseName, documentName) => [
|
|
898
1032
|
[scopeName, scope],
|
|
899
1033
|
...(phase ? [[phaseName, phase]] : []),
|
|
1034
|
+
...(documentPhase ? [[documentName, documentPhase]] : []),
|
|
900
1035
|
];
|
|
901
1036
|
// The context's own headers are left alone: they are the suite's, and
|
|
902
1037
|
// a test that sets more with `setExtraHTTPHeaders` keeps them. Setting
|
|
903
1038
|
// them back at every phase dropped a test's `X-Forwarded-For`.
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
1039
|
+
const byHost = this.appHosts.map((url) => {
|
|
1040
|
+
const host = new URL(url);
|
|
1041
|
+
// For the app's own site: requests, navigations and sockets.
|
|
1042
|
+
const cookies = pairs(COVERAGE_SCOPE_COOKIE, COVERAGE_PHASE_COOKIE, COVERAGE_DOCUMENT_PHASE_COOKIE).map(([name, value]) => ({ name, value, url, sameSite: "Lax" }));
|
|
1043
|
+
// For its frames on another of its hosts: a cookie that
|
|
1044
|
+
// crosses sites must be Secure, which needs https or a local
|
|
1045
|
+
// host. Chromium keeps such a cookie only when it is given by
|
|
1046
|
+
// domain; given by an http URL it is dropped without a word.
|
|
1047
|
+
if (host.protocol === "https:" || ["localhost", "127.0.0.1"].includes(host.hostname)) {
|
|
1048
|
+
cookies.push(...pairs(COVERAGE_SCOPE_SITE_COOKIE, COVERAGE_PHASE_SITE_COOKIE, COVERAGE_DOCUMENT_PHASE_SITE_COOKIE).map(([name, value]) => ({ name, value, domain: host.hostname, path: "/", sameSite: "None", secure: true })));
|
|
1049
|
+
}
|
|
1050
|
+
return cookies;
|
|
1051
|
+
});
|
|
1052
|
+
// Every host's cookies in one call: a call per host, each its own
|
|
1053
|
+
// round trip through Playwright, was most of what an action waited
|
|
1054
|
+
// for. A cookie is kept per host, for every port of it: hosts that
|
|
1055
|
+
// differ only by port gave the same cookies twice, and each goes once.
|
|
1056
|
+
// A cookie the browser refuses fails the whole call, so then each host
|
|
1057
|
+
// is given its own and one refused leaves the others theirs.
|
|
1058
|
+
const distinct = new Map();
|
|
1059
|
+
for (const cookie of byHost.flat()) {
|
|
1060
|
+
const target = cookie.url ? new URL(cookie.url) : undefined;
|
|
1061
|
+
const where = target ? `${target.protocol}//${target.hostname}${target.pathname}` : `${cookie.domain}${cookie.path}`;
|
|
1062
|
+
const key = JSON.stringify([cookie.name, cookie.value, where, cookie.sameSite, cookie.secure ?? false]);
|
|
1063
|
+
if (!distinct.has(key))
|
|
1064
|
+
distinct.set(key, cookie);
|
|
1065
|
+
}
|
|
1066
|
+
await context.addCookies([...distinct.values()]).catch((error) => {
|
|
1067
|
+
timingCount(timingBuckets ? `activate.cookiesRefused: ${String(error?.message ?? error).split("\n")[0].slice(0, 120)}` : "activate.cookiesRefused");
|
|
1068
|
+
return Promise.all(byHost.map((cookies) => context.addCookies(cookies).catch(() => timingCount("activate.hostCookiesRefused"))));
|
|
1069
|
+
});
|
|
920
1070
|
}
|
|
921
1071
|
async activatePage(page, phaseId) {
|
|
922
1072
|
const cdp = this.cdpSessions.get(page);
|
|
@@ -948,55 +1098,117 @@ class CoveragePhaseController {
|
|
|
948
1098
|
* the end of every test (20,000 events: 470 ms, against 34 ms as one JSON
|
|
949
1099
|
* string), and doubled a 76-test suite's time.
|
|
950
1100
|
*/
|
|
951
|
-
const LEAVING_BINDING = "__supercovLeaving";
|
|
952
1101
|
/**
|
|
953
|
-
*
|
|
954
|
-
*
|
|
955
|
-
* restored the same evidence and added to it.
|
|
1102
|
+
* The attempt a new document belongs to, for the app's server: its cookies,
|
|
1103
|
+
* and the header its fetch sends to its own origin.
|
|
956
1104
|
*/
|
|
957
|
-
function
|
|
958
|
-
const
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
1105
|
+
function announceAttempt({ attemptId, scopeHeader, scopeValue, scopeCookie, scopeSiteCookie }) {
|
|
1106
|
+
const coverageGlobal = globalThis;
|
|
1107
|
+
coverageGlobal.__SUPERCOV_ATTEMPT__ = { attemptId, scopeValue };
|
|
1108
|
+
coverageGlobal.__SUPERCOV_MCDC_TEST_ID__ = attemptId;
|
|
1109
|
+
try {
|
|
1110
|
+
document.cookie = `${scopeCookie}=${encodeURIComponent(scopeValue)}; Path=/; SameSite=Lax`;
|
|
1111
|
+
// And for this document's frames on another of the app's
|
|
1112
|
+
// hosts, where crossing sites is allowed.
|
|
1113
|
+
if (globalThis.isSecureContext)
|
|
1114
|
+
document.cookie = `${scopeSiteCookie}=${encodeURIComponent(scopeValue)}; Path=/; SameSite=None; Secure`;
|
|
1115
|
+
if (!coverageGlobal.__SUPERCOV_BROWSER_FETCH_PATCHED__) {
|
|
1116
|
+
const originalFetch = globalThis.fetch?.bind(globalThis);
|
|
1117
|
+
if (originalFetch) {
|
|
1118
|
+
coverageGlobal.__SUPERCOV_BROWSER_FETCH_PATCHED__ = true;
|
|
1119
|
+
globalThis.fetch = ((input, init) => {
|
|
1120
|
+
// Only the page's own origin hears the scope. A
|
|
1121
|
+
// header on a request to another origin makes the
|
|
1122
|
+
// browser ask that origin first, and one that
|
|
1123
|
+
// allows only the headers it uses refuses: the
|
|
1124
|
+
// page's fetch failed under measurement alone.
|
|
1125
|
+
try {
|
|
1126
|
+
const target = new URL(input instanceof Request ? input.url : String(input), location.href);
|
|
1127
|
+
if (target.origin !== location.origin)
|
|
1128
|
+
return originalFetch(input, init);
|
|
1129
|
+
}
|
|
1130
|
+
catch {
|
|
1131
|
+
return originalFetch(input, init);
|
|
1132
|
+
}
|
|
1133
|
+
const headers = new Headers(init?.headers ??
|
|
1134
|
+
(input instanceof Request ? input.headers : undefined));
|
|
1135
|
+
headers.set(scopeHeader, coverageGlobal.__SUPERCOV_ATTEMPT__?.scopeValue ?? scopeValue);
|
|
1136
|
+
const phase = coverageGlobal.__SUPERCOV_PHASE_ID__;
|
|
1137
|
+
if (phase)
|
|
1138
|
+
headers.set("x-supercov-phase", phase);
|
|
1139
|
+
return originalFetch(input, { ...init, headers });
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
984
1142
|
}
|
|
985
1143
|
}
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
1144
|
+
catch {
|
|
1145
|
+
// Browser instrumentation must not change application behavior.
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
// While timing: how many tests' scripts each context has run (a context
|
|
1149
|
+
// that outlives its test is registered by every later test).
|
|
1150
|
+
const contextScriptCopies = new WeakMap();
|
|
1151
|
+
const LEAVING_BINDING = "__supercovLeaving";
|
|
1152
|
+
/** Scripts as one, each part run on its own as separate scripts were. */
|
|
1153
|
+
function separately(parts) {
|
|
1154
|
+
return parts.map((part) => `try {\n${part}\n} catch (error) {}`).join("\n");
|
|
1155
|
+
}
|
|
1156
|
+
/** A document that leaves hands its evidence to the test that has its page. */
|
|
1157
|
+
function takeLeavingEvidence(source, payload) {
|
|
1158
|
+
const controller = source?.page ? controllerOwning(source.page) : undefined;
|
|
1159
|
+
if (!controller || controller.runtimeSnapshots)
|
|
1160
|
+
return;
|
|
1161
|
+
try {
|
|
1162
|
+
timingCount("transfer.leavingBytes", typeof payload === "string" ? payload.length : 0);
|
|
1163
|
+
controller.leftSnapshots.push(expandSnapshot(JSON.parse(payload)));
|
|
1164
|
+
}
|
|
1165
|
+
catch {
|
|
1166
|
+
// Not evidence.
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
/**
|
|
1170
|
+
* What a context's documents run whichever test has them -- the runtime, and
|
|
1171
|
+
* the binding through which a leaving document hands its evidence over (the
|
|
1172
|
+
* next one reads what it stored only on the same origin) -- sent once, when
|
|
1173
|
+
* the context is made: Playwright opens the test's page meanwhile, and the
|
|
1174
|
+
* test's setup waits only for its own script and cookies. A context that
|
|
1175
|
+
* outlives its test keeps the one binding: the test that has the page now
|
|
1176
|
+
* takes what it hands over.
|
|
1177
|
+
*/
|
|
1178
|
+
const preparedContexts = new WeakMap();
|
|
1179
|
+
function prepareContext(context) {
|
|
1180
|
+
let prepared = preparedContexts.get(context);
|
|
1181
|
+
if (!prepared) {
|
|
1182
|
+
const parts = [];
|
|
1183
|
+
// A Rust crate compiled to wasm the run measures: pages remember
|
|
1184
|
+
// their wasm instances, so each test's work can be taken from them.
|
|
1185
|
+
if (process.env.SUPERCOV_WASM_REGIONS === "1")
|
|
1186
|
+
parts.push("globalThis.__SUPERCOV_WASM_REGIONS__ = true;");
|
|
1187
|
+
parts.push(browserRuntimePrelude);
|
|
1188
|
+
prepared = Promise.resolve(internally(context, () => Promise.all([
|
|
1189
|
+
context.addInitScript({ content: separately(parts) }).catch(() => undefined),
|
|
1190
|
+
context.exposeBinding(LEAVING_BINDING, takeLeavingEvidence).catch(() => undefined),
|
|
1191
|
+
]))).catch(() => undefined);
|
|
1192
|
+
preparedContexts.set(context, prepared);
|
|
1193
|
+
}
|
|
1194
|
+
return prepared;
|
|
992
1195
|
}
|
|
993
1196
|
function readSnapshot(target) {
|
|
994
1197
|
return target
|
|
995
1198
|
.evaluate(() => {
|
|
996
1199
|
const getSnapshot = globalThis.__SUPERCOV_COVERAGE_SNAPSHOT__;
|
|
997
|
-
|
|
1200
|
+
const compact = globalThis.__SUPERCOV_COMPACT_SNAPSHOT__;
|
|
1201
|
+
if (!getSnapshot)
|
|
1202
|
+
return undefined;
|
|
1203
|
+
return typeof compact === "function" ? compact(getSnapshot()) : JSON.stringify(getSnapshot());
|
|
998
1204
|
})
|
|
999
|
-
.then((text) =>
|
|
1205
|
+
.then((text) => {
|
|
1206
|
+
if (typeof text !== "string")
|
|
1207
|
+
return undefined;
|
|
1208
|
+
// Phase timing counts the bytes each read carried, as its "ms".
|
|
1209
|
+
timingCount("transfer.snapshotBytes", text.length);
|
|
1210
|
+
return expandSnapshot(JSON.parse(text));
|
|
1211
|
+
});
|
|
1000
1212
|
}
|
|
1001
1213
|
let activeController;
|
|
1002
1214
|
let bridgedAssertionDepth = 0;
|
|
@@ -1034,6 +1246,7 @@ function trackContext(context, configuredHeaders) {
|
|
|
1034
1246
|
trackedContexts.add(context);
|
|
1035
1247
|
context.once?.("close", () => trackedContexts.delete(context));
|
|
1036
1248
|
patchContextPrototype(context);
|
|
1249
|
+
void prepareContext(context);
|
|
1037
1250
|
}
|
|
1038
1251
|
function liveTrackedContexts() {
|
|
1039
1252
|
const contexts = new Set(trackedContexts);
|
|
@@ -1090,7 +1303,7 @@ function patchBrowserPrototype(browser) {
|
|
|
1090
1303
|
* way the page is gone by the time the test's snapshots are collected.
|
|
1091
1304
|
*/
|
|
1092
1305
|
/** The cookies Supercov gives a context to carry the test's scope. */
|
|
1093
|
-
const OWN_COOKIES = new Set([COVERAGE_SCOPE_COOKIE, COVERAGE_PHASE_COOKIE, COVERAGE_SCOPE_SITE_COOKIE, COVERAGE_PHASE_SITE_COOKIE]);
|
|
1306
|
+
const OWN_COOKIES = new Set([COVERAGE_SCOPE_COOKIE, COVERAGE_PHASE_COOKIE, COVERAGE_DOCUMENT_PHASE_COOKIE, COVERAGE_SCOPE_SITE_COOKIE, COVERAGE_PHASE_SITE_COOKIE, COVERAGE_DOCUMENT_PHASE_SITE_COOKIE]);
|
|
1094
1307
|
const suiteCookies = (cookies) => (Array.isArray(cookies) ? cookies.filter((cookie) => !OWN_COOKIES.has(cookie?.name)) : cookies);
|
|
1095
1308
|
function patchContextPrototype(context) {
|
|
1096
1309
|
// A test reads and saves the cookies it and its app set, never
|
|
@@ -1162,7 +1375,7 @@ globalThis.__SUPERCOV_ASSERTION_PHASE_BRIDGE__ = (operation, source, callback) =
|
|
|
1162
1375
|
const runtime = directRuntime();
|
|
1163
1376
|
if (!controller || !runtime)
|
|
1164
1377
|
return { handled: false };
|
|
1165
|
-
const phase = controller.
|
|
1378
|
+
const phase = controller.beginBridgedAssertion(operation, source);
|
|
1166
1379
|
bridgedAssertionDepth += 1;
|
|
1167
1380
|
try {
|
|
1168
1381
|
const value = runtime.withCoverageCarrier({ version: 1, scope: controller.scope, phaseId: phase.id }, callback);
|
|
@@ -1194,7 +1407,7 @@ globalThis.__SUPERCOV_ASSERTION_PHASE_OPENER__ = (operation, source) => {
|
|
|
1194
1407
|
const controller = activeController;
|
|
1195
1408
|
if (!controller || !directRuntime())
|
|
1196
1409
|
return undefined;
|
|
1197
|
-
const phase = controller.
|
|
1410
|
+
const phase = controller.beginBridgedAssertion(operation, source);
|
|
1198
1411
|
bridgedAssertionDepth += 1;
|
|
1199
1412
|
let held = true;
|
|
1200
1413
|
const release = () => {
|
|
@@ -1378,7 +1591,45 @@ function installChildProcessScopePropagation() {
|
|
|
1378
1591
|
syncBuiltinESMExports();
|
|
1379
1592
|
}
|
|
1380
1593
|
installChildProcessScopePropagation();
|
|
1381
|
-
|
|
1594
|
+
// expect's own matchers that settle in the call, whatever they are given, on
|
|
1595
|
+
// a value that is no Playwright object: none of them can wait for the page.
|
|
1596
|
+
// Under `expect.poll`, `.resolves` or `.rejects` the same names wait.
|
|
1597
|
+
const SETTLED_MATCHERS = new Set([
|
|
1598
|
+
"toBe",
|
|
1599
|
+
"toBeCloseTo",
|
|
1600
|
+
"toBeDefined",
|
|
1601
|
+
"toBeFalsy",
|
|
1602
|
+
"toBeGreaterThan",
|
|
1603
|
+
"toBeGreaterThanOrEqual",
|
|
1604
|
+
"toBeInstanceOf",
|
|
1605
|
+
"toBeLessThan",
|
|
1606
|
+
"toBeLessThanOrEqual",
|
|
1607
|
+
"toBeNaN",
|
|
1608
|
+
"toBeNull",
|
|
1609
|
+
"toBeTruthy",
|
|
1610
|
+
"toBeUndefined",
|
|
1611
|
+
"toContain",
|
|
1612
|
+
"toContainEqual",
|
|
1613
|
+
"toEqual",
|
|
1614
|
+
"toHaveLength",
|
|
1615
|
+
"toHaveProperty",
|
|
1616
|
+
"toMatch",
|
|
1617
|
+
"toMatchObject",
|
|
1618
|
+
"toStrictEqual",
|
|
1619
|
+
]);
|
|
1620
|
+
const PLAYWRIGHT_VALUE_TYPES = new Set(["APIResponse", "ElementHandle", "Frame", "FrameLocator", "JSHandle", "Locator", "Page"]);
|
|
1621
|
+
function isPlaywrightValue(value) {
|
|
1622
|
+
if (!value || (typeof value !== "object" && typeof value !== "function"))
|
|
1623
|
+
return false;
|
|
1624
|
+
try {
|
|
1625
|
+
return "_guid" in value || "_frame" in value || "_selector" in value ||
|
|
1626
|
+
PLAYWRIGHT_VALUE_TYPES.has(value.constructor?.name);
|
|
1627
|
+
}
|
|
1628
|
+
catch {
|
|
1629
|
+
return true;
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
function wrapMatchers(matchers, path = "expect", settles = false) {
|
|
1382
1633
|
return new Proxy(matchers, {
|
|
1383
1634
|
get(target, property) {
|
|
1384
1635
|
// Matcher objects and built-ins can expose getters whose internal slots
|
|
@@ -1389,14 +1640,19 @@ function wrapMatchers(matchers, path = "expect") {
|
|
|
1389
1640
|
if (value &&
|
|
1390
1641
|
typeof value === "object" &&
|
|
1391
1642
|
(name === "not" || name === "resolves" || name === "rejects"))
|
|
1392
|
-
return wrapMatchers(value, `${path}.${name}
|
|
1643
|
+
return wrapMatchers(value, `${path}.${name}`, settles && name === "not");
|
|
1393
1644
|
if (typeof value !== "function")
|
|
1394
1645
|
return value;
|
|
1395
1646
|
return (...args) => {
|
|
1396
1647
|
const controller = activeController;
|
|
1648
|
+
const settled = settles && SETTLED_MATCHERS.has(name);
|
|
1397
1649
|
const phase = bridgedAssertionDepth === 0
|
|
1398
|
-
? controller?.beginAssertion(`${path}.${name}
|
|
1650
|
+
? controller?.beginAssertion(`${path}.${name}`, undefined, !settled)
|
|
1399
1651
|
: undefined;
|
|
1652
|
+
// Inside an instrumented assertion, a matcher that can wait
|
|
1653
|
+
// takes the assertion's phase to the browser before it starts.
|
|
1654
|
+
if (bridgedAssertionDepth > 0 && !settled)
|
|
1655
|
+
controller?.promotePendingAssertion();
|
|
1400
1656
|
try {
|
|
1401
1657
|
const result = Reflect.apply(value, target, args);
|
|
1402
1658
|
if (result instanceof Promise) {
|
|
@@ -1423,21 +1679,21 @@ function wrapMatchers(matchers, path = "expect") {
|
|
|
1423
1679
|
},
|
|
1424
1680
|
});
|
|
1425
1681
|
}
|
|
1426
|
-
function wrapExpectCallable(callable) {
|
|
1682
|
+
function wrapExpectCallable(callable, polls = false) {
|
|
1427
1683
|
return new Proxy(callable, {
|
|
1428
1684
|
apply(target, thisArg, argumentsList) {
|
|
1429
1685
|
const result = Reflect.apply(target, thisArg, argumentsList);
|
|
1430
1686
|
if (typeof result === "function")
|
|
1431
|
-
return wrapExpectCallable(result);
|
|
1687
|
+
return wrapExpectCallable(result, polls);
|
|
1432
1688
|
if (result && typeof result === "object")
|
|
1433
|
-
return wrapMatchers(result);
|
|
1689
|
+
return wrapMatchers(result, "expect", !polls && !isPlaywrightValue(argumentsList[0]));
|
|
1434
1690
|
return result;
|
|
1435
1691
|
},
|
|
1436
1692
|
get(target, property, receiver) {
|
|
1437
1693
|
const value = Reflect.get(target, property, receiver);
|
|
1438
1694
|
if (typeof value !== "function")
|
|
1439
1695
|
return value;
|
|
1440
|
-
return wrapExpectCallable(value.bind(target));
|
|
1696
|
+
return wrapExpectCallable(value.bind(target), polls || property === "poll");
|
|
1441
1697
|
},
|
|
1442
1698
|
});
|
|
1443
1699
|
}
|
|
@@ -1467,26 +1723,6 @@ function executionScope(testInfo) {
|
|
|
1467
1723
|
attemptId,
|
|
1468
1724
|
};
|
|
1469
1725
|
}
|
|
1470
|
-
function readServerRecords(scope) {
|
|
1471
|
-
try {
|
|
1472
|
-
return readFileSync(serverEvidencePath(scope), "utf8")
|
|
1473
|
-
.split("\n")
|
|
1474
|
-
.filter(Boolean)
|
|
1475
|
-
.flatMap((line) => {
|
|
1476
|
-
try {
|
|
1477
|
-
const record = JSON.parse(line);
|
|
1478
|
-
return record.scope?.attemptId === scope.attemptId ? [record] : [];
|
|
1479
|
-
}
|
|
1480
|
-
catch {
|
|
1481
|
-
// Ignore a final partial line if the server was writing during collection.
|
|
1482
|
-
return [];
|
|
1483
|
-
}
|
|
1484
|
-
});
|
|
1485
|
-
}
|
|
1486
|
-
catch {
|
|
1487
|
-
return [];
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1490
1726
|
function phaseSourceLine(source) {
|
|
1491
1727
|
return source?.replace(/:\d+$/, "");
|
|
1492
1728
|
}
|
|
@@ -1523,6 +1759,12 @@ function mergeCollectedPhases(controllerPhases, fallbackPhases) {
|
|
|
1523
1759
|
* written to one uniquely named, one-shot evidence file in the runner's shared
|
|
1524
1760
|
* directory as well. No test streams into this path.
|
|
1525
1761
|
*/
|
|
1762
|
+
/**
|
|
1763
|
+
* A snapshot's events as columns.
|
|
1764
|
+
* A page records each hit once per test as an event of five fields, and its
|
|
1765
|
+
* thousands of them were most of a test's record. The engine decodes the
|
|
1766
|
+
* columns into exactly these events, in this order.
|
|
1767
|
+
*/
|
|
1526
1768
|
function appendEvidenceLine(serialized) {
|
|
1527
1769
|
const evidenceDirectory = process.env["SUPERCOV_EVIDENCE_DIR"] ??
|
|
1528
1770
|
(GENERATED_EVIDENCE_DIRECTORY.startsWith("__")
|
|
@@ -1542,7 +1784,7 @@ const instrumentedFixtures = {
|
|
|
1542
1784
|
const controller = controllers.get(scope.attemptId);
|
|
1543
1785
|
if (!controller)
|
|
1544
1786
|
throw new Error(`Supercov's automatic Playwright collector was not initialized for ${scope.attemptId}`);
|
|
1545
|
-
await controller.registerPage(page);
|
|
1787
|
+
await timed("fixture.pageSetup", () => controller.registerPage(page));
|
|
1546
1788
|
try {
|
|
1547
1789
|
await use(controller.wrap(page));
|
|
1548
1790
|
}
|
|
@@ -1550,7 +1792,7 @@ const instrumentedFixtures = {
|
|
|
1550
1792
|
// This fixture still owns a live page. The automatic test fixture tears
|
|
1551
1793
|
// down after page dependencies and therefore cannot reliably evaluate
|
|
1552
1794
|
// frames on every Playwright version.
|
|
1553
|
-
await controller.collectRuntimeSnapshots();
|
|
1795
|
+
await timed("fixture.pageTeardown", () => controller.collectRuntimeSnapshots());
|
|
1554
1796
|
}
|
|
1555
1797
|
},
|
|
1556
1798
|
browser: [
|
|
@@ -1580,12 +1822,25 @@ const instrumentedFixtures = {
|
|
|
1580
1822
|
async ({}, use, testInfo) => {
|
|
1581
1823
|
const scope = executionScope(testInfo);
|
|
1582
1824
|
const configuredHeaders = Object.fromEntries(Object.entries(testInfo.project.use.extraHTTPHeaders ?? {}).map(([name, value]) => [name, String(value)]));
|
|
1825
|
+
const setupStarted = performance.now();
|
|
1583
1826
|
const controller = new CoveragePhaseController(scope, configuredHeaders, testInfo.project.use.baseURL);
|
|
1584
1827
|
controllers.set(scope.attemptId, controller);
|
|
1585
1828
|
activeController = controller;
|
|
1586
1829
|
directRuntime()?.activateCoverageScope(scope);
|
|
1587
|
-
|
|
1588
|
-
|
|
1830
|
+
// The pages the test starts with, whose evidence is taken while
|
|
1831
|
+
// their contexts are registered.
|
|
1832
|
+
const startingPages = [...liveTrackedContexts()].flatMap((context) => {
|
|
1833
|
+
try {
|
|
1834
|
+
return context.pages();
|
|
1835
|
+
}
|
|
1836
|
+
catch {
|
|
1837
|
+
return [];
|
|
1838
|
+
}
|
|
1839
|
+
});
|
|
1840
|
+
const [, carried] = await Promise.all([
|
|
1841
|
+
timed("fixture.adopt", () => controller.adoptTrackedContexts().catch(() => undefined)),
|
|
1842
|
+
timed("fixture.carried", () => controller.takeCarriedEvidence(startingPages).catch(() => undefined)),
|
|
1843
|
+
]);
|
|
1589
1844
|
if (carried) {
|
|
1590
1845
|
appendEvidenceLine(`${JSON.stringify({
|
|
1591
1846
|
testId: `__supercov_background__:playwright:${scope.attemptId}`,
|
|
@@ -1593,7 +1848,7 @@ const instrumentedFixtures = {
|
|
|
1593
1848
|
status: "unknown",
|
|
1594
1849
|
provenance: { runner: "background", kind: "background", source: "explicit" },
|
|
1595
1850
|
role: "background",
|
|
1596
|
-
browser: [carried],
|
|
1851
|
+
browser: [columnarEvents(carried)],
|
|
1597
1852
|
})}\n`);
|
|
1598
1853
|
}
|
|
1599
1854
|
const serverOutput = serverEvidencePath(scope);
|
|
@@ -1603,14 +1858,15 @@ const instrumentedFixtures = {
|
|
|
1603
1858
|
// no test is credited by time to the one test running then, and a
|
|
1604
1859
|
// test is running for all of this, not only during its actions.
|
|
1605
1860
|
const startedAtMs = Date.now();
|
|
1861
|
+
timingCount("fixture.testSetup", performance.now() - setupStarted);
|
|
1606
1862
|
try {
|
|
1607
1863
|
await use();
|
|
1608
1864
|
}
|
|
1609
1865
|
finally {
|
|
1866
|
+
const teardownStarted = performance.now();
|
|
1610
1867
|
const endedAtMs = Date.now();
|
|
1611
1868
|
try {
|
|
1612
1869
|
const browser = await controller.collectRuntimeSnapshots();
|
|
1613
|
-
const server = readServerRecords(scope);
|
|
1614
1870
|
// Emit an artifact even when this test touched no application source.
|
|
1615
1871
|
// A complete test-to-coverage matrix must also identify tests that are
|
|
1616
1872
|
// removable without changing coverage.
|
|
@@ -1635,14 +1891,14 @@ const instrumentedFixtures = {
|
|
|
1635
1891
|
}),
|
|
1636
1892
|
phases: mergeCollectedPhases(controller.phases, directRuntime()?.takeNodeAssertionPhases(scope) ?? []),
|
|
1637
1893
|
...(controller.workerEvidenceMissing ? { attribution: "partial" } : {}),
|
|
1638
|
-
browser,
|
|
1639
|
-
server,
|
|
1894
|
+
browser: browser.map(columnarEvents),
|
|
1640
1895
|
span: [startedAtMs, endedAtMs],
|
|
1641
1896
|
};
|
|
1642
1897
|
appendEvidenceLine(`${JSON.stringify(payload)}\n`);
|
|
1643
1898
|
}
|
|
1644
1899
|
finally {
|
|
1645
1900
|
await timed("controller.dispose", () => controller.dispose());
|
|
1901
|
+
timingCount("fixture.testTeardown", performance.now() - teardownStarted);
|
|
1646
1902
|
timingReport(testInfo.title);
|
|
1647
1903
|
directRuntime()?.activateCoverageScope();
|
|
1648
1904
|
if (activeController === controller)
|
|
@@ -1656,6 +1912,10 @@ const instrumentedFixtures = {
|
|
|
1656
1912
|
};
|
|
1657
1913
|
const instrumentedTest = base.extend(instrumentedFixtures);
|
|
1658
1914
|
export const test = instrumentedTest;
|
|
1915
|
+
// `export *` passes no default on, and `import test from "@playwright/test"`
|
|
1916
|
+
// is Playwright's own default export: such a spec found none and failed with
|
|
1917
|
+
// `(0 , _test.default) is not a function`.
|
|
1918
|
+
export default instrumentedTest;
|
|
1659
1919
|
/**
|
|
1660
1920
|
* A Playwright `test` object: callable, and carrying the API a spec drives.
|
|
1661
1921
|
* Facades export several -- one per fixture set -- and every one of them must
|