Spaces:
Running
Running
File size: 33,415 Bytes
15b27a1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports._baseTest = void 0;
Object.defineProperty(exports, "defineConfig", {
enumerable: true,
get: function () {
return _configLoader.defineConfig;
}
});
Object.defineProperty(exports, "expect", {
enumerable: true,
get: function () {
return _expect.expect;
}
});
Object.defineProperty(exports, "mergeExpects", {
enumerable: true,
get: function () {
return _expect.mergeExpects;
}
});
Object.defineProperty(exports, "mergeTests", {
enumerable: true,
get: function () {
return _testType.mergeTests;
}
});
exports.test = void 0;
var fs = _interopRequireWildcard(require("fs"));
var path = _interopRequireWildcard(require("path"));
var playwrightLibrary = _interopRequireWildcard(require("playwright-core"));
var _utils = require("playwright-core/lib/utils");
var _testType = require("./common/testType");
var _globals = require("./common/globals");
var _expect = require("./matchers/expect");
var _configLoader = require("./common/configLoader");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the 'License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const _baseTest = exports._baseTest = _testType.rootTestType.test;
(0, _utils.addInternalStackPrefix)(path.dirname(require.resolve('../package.json')));
if (process['__pw_initiator__']) {
const originalStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 200;
try {
throw new Error('Requiring @playwright/test second time, \nFirst:\n' + process['__pw_initiator__'] + '\n\nSecond: ');
} finally {
Error.stackTraceLimit = originalStackTraceLimit;
}
} else {
process['__pw_initiator__'] = new Error().stack;
}
const playwrightFixtures = {
defaultBrowserType: ['chromium', {
scope: 'worker',
option: true
}],
browserName: [({
defaultBrowserType
}, use) => use(defaultBrowserType), {
scope: 'worker',
option: true
}],
playwright: [async ({}, use) => {
await use(require('playwright-core'));
}, {
scope: 'worker',
box: true
}],
headless: [({
launchOptions
}, use) => {
var _launchOptions$headle;
return use((_launchOptions$headle = launchOptions.headless) !== null && _launchOptions$headle !== void 0 ? _launchOptions$headle : true);
}, {
scope: 'worker',
option: true
}],
channel: [({
launchOptions
}, use) => use(launchOptions.channel), {
scope: 'worker',
option: true
}],
launchOptions: [{}, {
scope: 'worker',
option: true
}],
connectOptions: [async ({
_optionConnectOptions
}, use) => {
await use(connectOptionsFromEnv() || _optionConnectOptions);
}, {
scope: 'worker',
option: true
}],
screenshot: ['off', {
scope: 'worker',
option: true
}],
video: ['off', {
scope: 'worker',
option: true
}],
trace: ['off', {
scope: 'worker',
option: true
}],
_browserOptions: [async ({
playwright,
headless,
channel,
launchOptions
}, use) => {
const options = {
handleSIGINT: false,
...launchOptions
};
if (headless !== undefined) options.headless = headless;
if (channel !== undefined) options.channel = channel;
options.tracesDir = tracing().tracesDir();
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit, playwright._bidiChromium, playwright._bidiFirefox]) browserType._defaultLaunchOptions = options;
await use(options);
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit, playwright._bidiChromium, playwright._bidiFirefox]) browserType._defaultLaunchOptions = undefined;
}, {
scope: 'worker',
auto: true,
box: true
}],
browser: [async ({
playwright,
browserName,
_browserOptions,
connectOptions,
_reuseContext
}, use, testInfo) => {
if (!['chromium', 'firefox', 'webkit', '_bidiChromium', '_bidiFirefox'].includes(browserName)) throw new Error(`Unexpected browserName "${browserName}", must be one of "chromium", "firefox" or "webkit"`);
if (connectOptions) {
var _connectOptions$expos;
const browser = await playwright[browserName].connect({
...connectOptions,
exposeNetwork: (_connectOptions$expos = connectOptions.exposeNetwork) !== null && _connectOptions$expos !== void 0 ? _connectOptions$expos : connectOptions._exposeNetwork,
headers: {
...(_reuseContext ? {
'x-playwright-reuse-context': '1'
} : {}),
// HTTP headers are ASCII only (not UTF-8).
'x-playwright-launch-options': (0, _utils.jsonStringifyForceASCII)(_browserOptions),
...connectOptions.headers
}
});
await use(browser);
await browser._wrapApiCall(async () => {
await browser.close({
reason: 'Test ended.'
});
}, true);
return;
}
const browser = await playwright[browserName].launch();
await use(browser);
await browser._wrapApiCall(async () => {
await browser.close({
reason: 'Test ended.'
});
}, true);
}, {
scope: 'worker',
timeout: 0
}],
acceptDownloads: [({
contextOptions
}, use) => {
var _contextOptions$accep;
return use((_contextOptions$accep = contextOptions.acceptDownloads) !== null && _contextOptions$accep !== void 0 ? _contextOptions$accep : true);
}, {
option: true
}],
bypassCSP: [({
contextOptions
}, use) => {
var _contextOptions$bypas;
return use((_contextOptions$bypas = contextOptions.bypassCSP) !== null && _contextOptions$bypas !== void 0 ? _contextOptions$bypas : false);
}, {
option: true
}],
colorScheme: [({
contextOptions
}, use) => use(contextOptions.colorScheme === undefined ? 'light' : contextOptions.colorScheme), {
option: true
}],
deviceScaleFactor: [({
contextOptions
}, use) => use(contextOptions.deviceScaleFactor), {
option: true
}],
extraHTTPHeaders: [({
contextOptions
}, use) => use(contextOptions.extraHTTPHeaders), {
option: true
}],
geolocation: [({
contextOptions
}, use) => use(contextOptions.geolocation), {
option: true
}],
hasTouch: [({
contextOptions
}, use) => {
var _contextOptions$hasTo;
return use((_contextOptions$hasTo = contextOptions.hasTouch) !== null && _contextOptions$hasTo !== void 0 ? _contextOptions$hasTo : false);
}, {
option: true
}],
httpCredentials: [({
contextOptions
}, use) => use(contextOptions.httpCredentials), {
option: true
}],
ignoreHTTPSErrors: [({
contextOptions
}, use) => {
var _contextOptions$ignor;
return use((_contextOptions$ignor = contextOptions.ignoreHTTPSErrors) !== null && _contextOptions$ignor !== void 0 ? _contextOptions$ignor : false);
}, {
option: true
}],
isMobile: [({
contextOptions
}, use) => {
var _contextOptions$isMob;
return use((_contextOptions$isMob = contextOptions.isMobile) !== null && _contextOptions$isMob !== void 0 ? _contextOptions$isMob : false);
}, {
option: true
}],
javaScriptEnabled: [({
contextOptions
}, use) => {
var _contextOptions$javaS;
return use((_contextOptions$javaS = contextOptions.javaScriptEnabled) !== null && _contextOptions$javaS !== void 0 ? _contextOptions$javaS : true);
}, {
option: true
}],
locale: [({
contextOptions
}, use) => {
var _contextOptions$local;
return use((_contextOptions$local = contextOptions.locale) !== null && _contextOptions$local !== void 0 ? _contextOptions$local : 'en-US');
}, {
option: true
}],
offline: [({
contextOptions
}, use) => {
var _contextOptions$offli;
return use((_contextOptions$offli = contextOptions.offline) !== null && _contextOptions$offli !== void 0 ? _contextOptions$offli : false);
}, {
option: true
}],
permissions: [({
contextOptions
}, use) => use(contextOptions.permissions), {
option: true
}],
proxy: [({
contextOptions
}, use) => use(contextOptions.proxy), {
option: true
}],
storageState: [({
contextOptions
}, use) => use(contextOptions.storageState), {
option: true
}],
clientCertificates: [({
contextOptions
}, use) => use(contextOptions.clientCertificates), {
option: true
}],
timezoneId: [({
contextOptions
}, use) => use(contextOptions.timezoneId), {
option: true
}],
userAgent: [({
contextOptions
}, use) => use(contextOptions.userAgent), {
option: true
}],
viewport: [({
contextOptions
}, use) => use(contextOptions.viewport === undefined ? {
width: 1280,
height: 720
} : contextOptions.viewport), {
option: true
}],
actionTimeout: [0, {
option: true
}],
testIdAttribute: ['data-testid', {
option: true
}],
navigationTimeout: [0, {
option: true
}],
baseURL: [async ({}, use) => {
await use(process.env.PLAYWRIGHT_TEST_BASE_URL);
}, {
option: true
}],
serviceWorkers: [({
contextOptions
}, use) => {
var _contextOptions$servi;
return use((_contextOptions$servi = contextOptions.serviceWorkers) !== null && _contextOptions$servi !== void 0 ? _contextOptions$servi : 'allow');
}, {
option: true
}],
contextOptions: [{}, {
option: true
}],
_combinedContextOptions: [async ({
acceptDownloads,
bypassCSP,
clientCertificates,
colorScheme,
deviceScaleFactor,
extraHTTPHeaders,
hasTouch,
geolocation,
httpCredentials,
ignoreHTTPSErrors,
isMobile,
javaScriptEnabled,
locale,
offline,
permissions,
proxy,
storageState,
viewport,
timezoneId,
userAgent,
baseURL,
contextOptions,
serviceWorkers
}, use) => {
const options = {};
if (acceptDownloads !== undefined) options.acceptDownloads = acceptDownloads;
if (bypassCSP !== undefined) options.bypassCSP = bypassCSP;
if (colorScheme !== undefined) options.colorScheme = colorScheme;
if (deviceScaleFactor !== undefined) options.deviceScaleFactor = deviceScaleFactor;
if (extraHTTPHeaders !== undefined) options.extraHTTPHeaders = extraHTTPHeaders;
if (geolocation !== undefined) options.geolocation = geolocation;
if (hasTouch !== undefined) options.hasTouch = hasTouch;
if (httpCredentials !== undefined) options.httpCredentials = httpCredentials;
if (ignoreHTTPSErrors !== undefined) options.ignoreHTTPSErrors = ignoreHTTPSErrors;
if (isMobile !== undefined) options.isMobile = isMobile;
if (javaScriptEnabled !== undefined) options.javaScriptEnabled = javaScriptEnabled;
if (locale !== undefined) options.locale = locale;
if (offline !== undefined) options.offline = offline;
if (permissions !== undefined) options.permissions = permissions;
if (proxy !== undefined) options.proxy = proxy;
if (storageState !== undefined) options.storageState = storageState;
if (clientCertificates !== null && clientCertificates !== void 0 && clientCertificates.length) options.clientCertificates = resolveClientCerticates(clientCertificates);
if (timezoneId !== undefined) options.timezoneId = timezoneId;
if (userAgent !== undefined) options.userAgent = userAgent;
if (viewport !== undefined) options.viewport = viewport;
if (baseURL !== undefined) options.baseURL = baseURL;
if (serviceWorkers !== undefined) options.serviceWorkers = serviceWorkers;
await use({
...contextOptions,
...options
});
}, {
box: true
}],
_setupContextOptions: [async ({
playwright,
_combinedContextOptions,
actionTimeout,
navigationTimeout,
testIdAttribute
}, use, testInfo) => {
if (testIdAttribute) playwrightLibrary.selectors.setTestIdAttribute(testIdAttribute);
testInfo.snapshotSuffix = process.platform;
if ((0, _utils.debugMode)()) testInfo._setDebugMode();
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit]) {
browserType._defaultContextOptions = _combinedContextOptions;
browserType._defaultContextTimeout = actionTimeout || 0;
browserType._defaultContextNavigationTimeout = navigationTimeout || 0;
}
playwright.request._defaultContextOptions = {
..._combinedContextOptions
};
playwright.request._defaultContextOptions.tracesDir = tracing().tracesDir();
playwright.request._defaultContextOptions.timeout = actionTimeout || 0;
await use();
playwright.request._defaultContextOptions = undefined;
for (const browserType of [playwright.chromium, playwright.firefox, playwright.webkit]) {
browserType._defaultContextOptions = undefined;
browserType._defaultContextTimeout = undefined;
browserType._defaultContextNavigationTimeout = undefined;
}
}, {
auto: 'all-hooks-included',
title: 'context configuration',
box: true
}],
_setupArtifacts: [async ({
playwright,
screenshot
}, use, testInfo) => {
// This fixture has a separate zero-timeout slot to ensure that artifact collection
// happens even after some fixtures or hooks time out.
// Now that default test timeout is known, we can replace zero with an actual value.
testInfo.setTimeout(testInfo.project.timeout);
const artifactsRecorder = new ArtifactsRecorder(playwright, tracing().artifactsDir(), screenshot);
await artifactsRecorder.willStartTest(testInfo);
const tracingGroupSteps = [];
const csiListener = {
onApiCallBegin: (apiName, params, frames, userData, out) => {
userData.apiName = apiName;
const testInfo = (0, _globals.currentTestInfo)();
if (!testInfo || apiName.includes('setTestIdAttribute') || apiName === 'tracing.groupEnd') return;
const step = testInfo._addStep({
location: frames[0],
category: 'pw:api',
title: renderApiCall(apiName, params),
apiName,
params
}, tracingGroupSteps[tracingGroupSteps.length - 1]);
userData.step = step;
out.stepId = step.stepId;
if (apiName === 'tracing.group') tracingGroupSteps.push(step);
},
onApiCallEnd: (userData, error) => {
// "tracing.group" step will end later, when "tracing.groupEnd" finishes.
if (userData.apiName === 'tracing.group') return;
if (userData.apiName === 'tracing.groupEnd') {
const step = tracingGroupSteps.pop();
step === null || step === void 0 || step.complete({
error
});
return;
}
const step = userData.step;
step === null || step === void 0 || step.complete({
error
});
},
onWillPause: ({
keepTestTimeout
}) => {
var _currentTestInfo;
if (!keepTestTimeout) (_currentTestInfo = (0, _globals.currentTestInfo)()) === null || _currentTestInfo === void 0 || _currentTestInfo._setDebugMode();
},
runAfterCreateBrowserContext: async context => {
await (artifactsRecorder === null || artifactsRecorder === void 0 ? void 0 : artifactsRecorder.didCreateBrowserContext(context));
const testInfo = (0, _globals.currentTestInfo)();
if (testInfo) attachConnectedHeaderIfNeeded(testInfo, context.browser());
},
runAfterCreateRequestContext: async context => {
await (artifactsRecorder === null || artifactsRecorder === void 0 ? void 0 : artifactsRecorder.didCreateRequestContext(context));
},
runBeforeCloseBrowserContext: async context => {
await (artifactsRecorder === null || artifactsRecorder === void 0 ? void 0 : artifactsRecorder.willCloseBrowserContext(context));
},
runBeforeCloseRequestContext: async context => {
await (artifactsRecorder === null || artifactsRecorder === void 0 ? void 0 : artifactsRecorder.willCloseRequestContext(context));
}
};
const clientInstrumentation = playwright._instrumentation;
clientInstrumentation.addListener(csiListener);
await use();
clientInstrumentation.removeListener(csiListener);
await artifactsRecorder.didFinishTest();
}, {
auto: 'all-hooks-included',
title: 'trace recording',
box: true,
timeout: 0
}],
_contextFactory: [async ({
browser,
video,
_reuseContext,
_combinedContextOptions /** mitigate dep-via-auto lack of traceability */
}, use, testInfo) => {
const testInfoImpl = testInfo;
const videoMode = normalizeVideoMode(video);
const captureVideo = shouldCaptureVideo(videoMode, testInfo) && !_reuseContext;
const contexts = new Map();
await use(async options => {
const hook = testInfoImpl._currentHookType();
if (hook === 'beforeAll' || hook === 'afterAll') {
throw new Error([`"context" and "page" fixtures are not supported in "${hook}" since they are created on a per-test basis.`, `If you would like to reuse a single page between tests, create context manually with browser.newContext(). See https://aka.ms/playwright/reuse-page for details.`, `If you would like to configure your page before each test, do that in beforeEach hook instead.`].join('\n'));
}
const videoOptions = captureVideo ? {
recordVideo: {
dir: tracing().artifactsDir(),
size: typeof video === 'string' ? undefined : video.size
}
} : {};
const context = await browser.newContext({
...videoOptions,
...options
});
const contextData = {
pagesWithVideo: []
};
contexts.set(context, contextData);
if (captureVideo) context.on('page', page => contextData.pagesWithVideo.push(page));
if (process.env.PW_CLOCK === 'frozen') {
await context._wrapApiCall(async () => {
await context.clock.install({
time: 0
});
await context.clock.pauseAt(1000);
}, true);
} else if (process.env.PW_CLOCK === 'realtime') {
await context._wrapApiCall(async () => {
await context.clock.install({
time: 0
});
}, true);
}
return context;
});
let counter = 0;
const closeReason = testInfo.status === 'timedOut' ? 'Test timeout of ' + testInfo.timeout + 'ms exceeded.' : 'Test ended.';
await Promise.all([...contexts.keys()].map(async context => {
await context._wrapApiCall(async () => {
await context.close({
reason: closeReason
});
}, true);
const testFailed = testInfo.status !== testInfo.expectedStatus;
const preserveVideo = captureVideo && (videoMode === 'on' || testFailed && videoMode === 'retain-on-failure' || videoMode === 'on-first-retry' && testInfo.retry === 1);
if (preserveVideo) {
const {
pagesWithVideo: pagesForVideo
} = contexts.get(context);
const videos = pagesForVideo.map(p => p.video()).filter(Boolean);
await Promise.all(videos.map(async v => {
try {
const savedPath = testInfo.outputPath(`video${counter ? '-' + counter : ''}.webm`);
++counter;
await v.saveAs(savedPath);
testInfo.attachments.push({
name: 'video',
path: savedPath,
contentType: 'video/webm'
});
} catch (e) {
// Silent catch empty videos.
}
}));
}
}));
}, {
scope: 'test',
title: 'context',
box: true
}],
_optionContextReuseMode: ['none', {
scope: 'worker',
option: true
}],
_optionConnectOptions: [undefined, {
scope: 'worker',
option: true
}],
_reuseContext: [async ({
video,
_optionContextReuseMode
}, use) => {
let mode = _optionContextReuseMode;
if (process.env.PW_TEST_REUSE_CONTEXT) mode = 'when-possible';
const reuse = mode === 'when-possible' && normalizeVideoMode(video) === 'off';
await use(reuse);
}, {
scope: 'worker',
title: 'context',
box: true
}],
context: async ({
playwright,
browser,
_reuseContext,
_contextFactory
}, use, testInfo) => {
attachConnectedHeaderIfNeeded(testInfo, browser);
if (!_reuseContext) {
await use(await _contextFactory());
return;
}
const defaultContextOptions = playwright.chromium._defaultContextOptions;
const context = await browser._newContextForReuse(defaultContextOptions);
context[kIsReusedContext] = true;
await use(context);
const closeReason = testInfo.status === 'timedOut' ? 'Test timeout of ' + testInfo.timeout + 'ms exceeded.' : 'Test ended.';
await browser._stopPendingOperations(closeReason);
},
page: async ({
context,
_reuseContext
}, use) => {
if (!_reuseContext) {
await use(await context.newPage());
return;
}
// First time we are reusing the context, we should create the page.
let [page] = context.pages();
if (!page) page = await context.newPage();
await use(page);
},
request: async ({
playwright
}, use) => {
const request = await playwright.request.newContext();
await use(request);
const hook = test.info()._currentHookType();
if (hook === 'beforeAll') {
await request.dispose({
reason: [`Fixture { request } from beforeAll cannot be reused in a test.`, ` - Recommended fix: use a separate { request } in the test.`, ` - Alternatively, manually create APIRequestContext in beforeAll and dispose it in afterAll.`, `See https://playwright.dev/docs/api-testing#sending-api-requests-from-ui-tests for more details.`].join('\n')
});
} else {
await request.dispose();
}
}
};
function normalizeVideoMode(video) {
if (!video) return 'off';
let videoMode = typeof video === 'string' ? video : video.mode;
if (videoMode === 'retry-with-video') videoMode = 'on-first-retry';
return videoMode;
}
function shouldCaptureVideo(videoMode, testInfo) {
return videoMode === 'on' || videoMode === 'retain-on-failure' || videoMode === 'on-first-retry' && testInfo.retry === 1;
}
function normalizeScreenshotMode(screenshot) {
if (!screenshot) return 'off';
return typeof screenshot === 'string' ? screenshot : screenshot.mode;
}
function attachConnectedHeaderIfNeeded(testInfo, browser) {
const connectHeaders = browser === null || browser === void 0 ? void 0 : browser._connectHeaders;
if (!connectHeaders) return;
for (const header of connectHeaders) {
if (header.name !== 'x-playwright-attachment') continue;
const [name, value] = header.value.split('=');
if (!name || !value) continue;
if (testInfo.attachments.some(attachment => attachment.name === name)) continue;
testInfo.attachments.push({
name,
contentType: 'text/plain',
body: Buffer.from(value)
});
}
}
function resolveFileToConfig(file) {
const config = test.info().config.configFile;
if (!config || !file) return file;
if (path.isAbsolute(file)) return file;
return path.resolve(path.dirname(config), file);
}
function resolveClientCerticates(clientCertificates) {
for (const cert of clientCertificates) {
cert.certPath = resolveFileToConfig(cert.certPath);
cert.keyPath = resolveFileToConfig(cert.keyPath);
cert.pfxPath = resolveFileToConfig(cert.pfxPath);
}
return clientCertificates;
}
const kTracingStarted = Symbol('kTracingStarted');
const kIsReusedContext = Symbol('kReusedContext');
function connectOptionsFromEnv() {
const wsEndpoint = process.env.PW_TEST_CONNECT_WS_ENDPOINT;
if (!wsEndpoint) return undefined;
const headers = process.env.PW_TEST_CONNECT_HEADERS ? JSON.parse(process.env.PW_TEST_CONNECT_HEADERS) : undefined;
return {
wsEndpoint,
headers,
exposeNetwork: process.env.PW_TEST_CONNECT_EXPOSE_NETWORK
};
}
class ArtifactsRecorder {
constructor(playwright, artifactsDir, screenshot) {
this._testInfo = void 0;
this._playwright = void 0;
this._artifactsDir = void 0;
this._screenshotMode = void 0;
this._screenshotOptions = void 0;
this._temporaryScreenshots = [];
this._temporaryArtifacts = [];
this._reusedContexts = new Set();
this._screenshotOrdinal = 0;
this._screenshottedSymbol = void 0;
this._startedCollectingArtifacts = void 0;
this._playwright = playwright;
this._artifactsDir = artifactsDir;
this._screenshotMode = normalizeScreenshotMode(screenshot);
this._screenshotOptions = typeof screenshot === 'string' ? undefined : screenshot;
this._screenshottedSymbol = Symbol('screenshotted');
this._startedCollectingArtifacts = Symbol('startedCollectingArtifacts');
}
_createTemporaryArtifact(...name) {
const file = path.join(this._artifactsDir, ...name);
this._temporaryArtifacts.push(file);
return file;
}
async willStartTest(testInfo) {
this._testInfo = testInfo;
testInfo._onDidFinishTestFunction = () => this.didFinishTestFunction();
// Since beforeAll(s), test and afterAll(s) reuse the same TestInfo, make sure we do not
// overwrite previous screenshots.
this._screenshotOrdinal = testInfo.attachments.filter(a => a.name === 'screenshot').length;
// Process existing contexts.
for (const browserType of [this._playwright.chromium, this._playwright.firefox, this._playwright.webkit]) {
const promises = [];
const existingContexts = Array.from(browserType._contexts);
for (const context of existingContexts) {
if (context[kIsReusedContext]) this._reusedContexts.add(context);else promises.push(this.didCreateBrowserContext(context));
}
await Promise.all(promises);
}
{
const existingApiRequests = Array.from(this._playwright.request._contexts);
await Promise.all(existingApiRequests.map(c => this.didCreateRequestContext(c)));
}
}
async didCreateBrowserContext(context) {
await this._startTraceChunkOnContextCreation(context.tracing);
}
async willCloseBrowserContext(context) {
// When reusing context, we get all previous contexts closed at the start of next test.
// Do not record empty traces and useless screenshots for them.
if (this._reusedContexts.has(context)) return;
await this._stopTracing(context.tracing);
if (this._screenshotMode === 'on' || this._screenshotMode === 'only-on-failure' || this._screenshotMode === 'on-first-failure' && this._testInfo.retry === 0) {
// Capture screenshot for now. We'll know whether we have to preserve them
// after the test finishes.
await Promise.all(context.pages().map(page => this._screenshotPage(page, true)));
}
}
async didCreateRequestContext(context) {
const tracing = context._tracing;
await this._startTraceChunkOnContextCreation(tracing);
}
async willCloseRequestContext(context) {
const tracing = context._tracing;
await this._stopTracing(tracing);
}
_shouldCaptureScreenshotUponFinish() {
return this._screenshotMode === 'on' || this._screenshotMode === 'only-on-failure' && this._testInfo._isFailure() || this._screenshotMode === 'on-first-failure' && this._testInfo._isFailure() && this._testInfo.retry === 0;
}
async didFinishTestFunction() {
if (this._shouldCaptureScreenshotUponFinish()) await this._screenshotOnTestFailure();
}
async didFinishTest() {
const captureScreenshots = this._shouldCaptureScreenshotUponFinish();
if (captureScreenshots) await this._screenshotOnTestFailure();
const leftoverContexts = [];
for (const browserType of [this._playwright.chromium, this._playwright.firefox, this._playwright.webkit]) leftoverContexts.push(...browserType._contexts);
const leftoverApiRequests = Array.from(this._playwright.request._contexts);
// Collect traces/screenshots for remaining contexts.
await Promise.all(leftoverContexts.map(async context => {
await this._stopTracing(context.tracing);
}).concat(leftoverApiRequests.map(async context => {
const tracing = context._tracing;
await this._stopTracing(tracing);
})));
// Attach temporary screenshots for contexts closed before collecting the test trace.
if (captureScreenshots) {
for (const file of this._temporaryScreenshots) {
try {
const screenshotPath = this._createScreenshotAttachmentPath();
await fs.promises.rename(file, screenshotPath);
this._attachScreenshot(screenshotPath);
} catch {}
}
}
}
_createScreenshotAttachmentPath() {
const testFailed = this._testInfo._isFailure();
const index = this._screenshotOrdinal + 1;
++this._screenshotOrdinal;
const screenshotPath = this._testInfo.outputPath(`test-${testFailed ? 'failed' : 'finished'}-${index}.png`);
return screenshotPath;
}
async _screenshotPage(page, temporary) {
if (page[this._screenshottedSymbol]) return;
page[this._screenshottedSymbol] = true;
try {
const screenshotPath = temporary ? this._createTemporaryArtifact((0, _utils.createGuid)() + '.png') : this._createScreenshotAttachmentPath();
// Pass caret=initial to avoid any evaluations that might slow down the screenshot
// and let the page modify itself from the problematic state it had at the moment of failure.
await page.screenshot({
...this._screenshotOptions,
timeout: 5000,
path: screenshotPath,
caret: 'initial'
});
if (temporary) this._temporaryScreenshots.push(screenshotPath);else this._attachScreenshot(screenshotPath);
} catch {
// Screenshot may fail, just ignore.
}
}
_attachScreenshot(screenshotPath) {
this._testInfo.attachments.push({
name: 'screenshot',
path: screenshotPath,
contentType: 'image/png'
});
}
async _screenshotOnTestFailure() {
const contexts = [];
for (const browserType of [this._playwright.chromium, this._playwright.firefox, this._playwright.webkit]) contexts.push(...browserType._contexts);
const pages = contexts.map(ctx => ctx.pages()).flat();
await Promise.all(pages.map(page => this._screenshotPage(page, false)));
}
async _startTraceChunkOnContextCreation(tracing) {
const options = this._testInfo._tracing.traceOptions();
if (options) {
const title = this._testInfo._tracing.traceTitle();
const name = this._testInfo._tracing.generateNextTraceRecordingName();
if (!tracing[kTracingStarted]) {
await tracing.start({
...options,
title,
name
});
tracing[kTracingStarted] = true;
} else {
await tracing.startChunk({
title,
name
});
}
} else {
if (tracing[kTracingStarted]) {
tracing[kTracingStarted] = false;
await tracing.stop();
}
}
}
async _stopTracing(tracing) {
if (tracing[this._startedCollectingArtifacts]) return;
tracing[this._startedCollectingArtifacts] = true;
if (this._testInfo._tracing.traceOptions() && tracing[kTracingStarted]) await tracing.stopChunk({
path: this._testInfo._tracing.generateNextTraceRecordingPath()
});
}
}
const paramsToRender = ['url', 'selector', 'text', 'key'];
function renderApiCall(apiName, params) {
if (apiName === 'tracing.group') return params.name;
const paramsArray = [];
if (params) {
for (const name of paramsToRender) {
if (!(name in params)) continue;
let value;
if (name === 'selector' && (0, _utils.isString)(params[name]) && params[name].startsWith('internal:')) {
const getter = (0, _utils.asLocator)('javascript', params[name]);
apiName = apiName.replace(/^locator\./, 'locator.' + getter + '.');
apiName = apiName.replace(/^page\./, 'page.' + getter + '.');
apiName = apiName.replace(/^frame\./, 'frame.' + getter + '.');
} else {
value = params[name];
paramsArray.push(value);
}
}
}
const paramsText = paramsArray.length ? '(' + paramsArray.join(', ') + ')' : '';
return apiName + paramsText;
}
function tracing() {
return test.info()._tracing;
}
const test = exports.test = _baseTest.extend(playwrightFixtures); |