Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

perf(tests): Improve local unit test performance (#4112)

Jan Bucharae1283cc7019
diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md
index 629163493..f5556a263 100644
--- a/.claude/CLAUDE.md
+++ b/.claude/CLAUDE.md
@@ -39,8 +39,8 @@ yarn install
yarn build # Build all packages (Turbo + TypeScript)
# Test
-yarn test # Run all tests (vitest)
-yarn test:full # Include difficult tests (CRAWLEE_DIFFICULT_TESTS=1)
+yarn test # Run all tests (vitest), fast config
+yarn test:full # Difficult tests + full firefox/webkit plugin matrix
yarn vitest run path/to/test.ts # Run specific test file
# Code Quality
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 683776562..cc9024ce9 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -2,6 +2,8 @@ name: Release @latest
env:
RETRY_TESTS: 1
+ # Local runs only exercise the Chromium plugin matrix, see plugins.test.ts.
+ CRAWLEE_TEST_BROWSERS: chromium,firefox,webkit
on:
workflow_dispatch:
diff --git a/.github/workflows/test-ci.yml b/.github/workflows/test-ci.yml
index 847cbe3fd..bf2aa7f46 100644
--- a/.github/workflows/test-ci.yml
+++ b/.github/workflows/test-ci.yml
@@ -8,6 +8,8 @@ on:
env:
RETRY_TESTS: 1
+ # Local runs only exercise the Chromium plugin matrix, see plugins.test.ts.
+ CRAWLEE_TEST_BROWSERS: chromium,firefox,webkit
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 656e3439c..3003bcfba 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -67,6 +67,10 @@ sudo ln -s /usr/lib/libpcre.so /usr/lib/libpcre.so.3
There are a few small differences between how testing in jest and vitest works. Mostly, they relate to what to do, and not do anymore.
+### Running the suite
+
+`pnpm test` runs the fast configuration: two vitest projects one after the other - `unit`, then `browser` for the files that drive real browsers - with capped workers and the Playwright plugin matrix limited to Chromium. `pnpm test:full` runs the lot, as CI does.
+
### Configuration file for tests created in the package they are for
You will need to use this tsconfig.json in the `test` folder in the package (say, if you were adding a test to `packages/core` and there wasn't a `tsconfig.json` file already there)
diff --git a/package.json b/package.json
index 1cec41fac..4444dbfb8 100644
--- a/package.json
+++ b/package.json
@@ -40,7 +40,7 @@
"test:integration": "cross-env CRAWLEE_DIFFICULT_TESTS=1 vitest run --silent=true test/integration",
"test:integration:services:up": "docker network create crawlee-it 2>/dev/null; docker run -d --rm --name crawlee-it-browserless --network crawlee-it -p 3000:3000 -e CONCURRENT=4 ghcr.io/browserless/chromium && docker run -d --rm --name crawlee-it-httpbin --network crawlee-it --network-alias httpbin -p 8080:80 kennethreitz/httpbin",
"test:integration:services:down": "docker stop crawlee-it-browserless crawlee-it-httpbin; docker network rm crawlee-it 2>/dev/null; true",
- "test:full": "cross-env CRAWLEE_DIFFICULT_TESTS=1 vitest run --silent",
+ "test:full": "cross-env CRAWLEE_DIFFICULT_TESTS=1 CRAWLEE_TEST_BROWSERS=chromium,firefox,webkit vitest run --silent",
"tsc-check-tests": "tsc --noEmit --project test/tsconfig.json",
"coverage": "vitest --coverage",
"publish:next": "lerna publish from-package --contents dist --dist-tag v4 --force-publish --yes",
@@ -93,7 +93,6 @@
"@types/express": "^5.0.1",
"@types/fs-extra": "^11.0.4",
"@types/inquirer": "^9.0.8",
- "@types/is-ci": "^3.0.4",
"@types/lodash.isequal": "^4.5.8",
"@types/lodash.merge": "^4.6.9",
"@types/mime-types": "^2.1.4",
@@ -123,7 +122,6 @@
"got": "^14.4.7",
"husky": "^9.1.7",
"iconv-lite": "^0.7.2",
- "is-ci": "^4.1.0",
"lerna": "^9.0.0",
"lint-staged": "^17.0.0",
"nock": "^14.0.10",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7499b0a68..aa0c02400 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -334,9 +334,6 @@ importers:
'@types/inquirer':
specifier: ^9.0.8
version: 9.0.9
- '@types/is-ci':
- specifier: ^3.0.4
- version: 3.0.4
'@types/lodash.isequal':
specifier: ^4.5.8
version: 4.5.8
@@ -424,9 +421,6 @@ importers:
iconv-lite:
specifier: ^0.7.2
version: 0.7.2
- is-ci:
- specifier: ^4.1.0
- version: 4.1.0
lerna:
specifier: ^9.0.0
@@ -5266,9 +5260,6 @@ packages:
resolution: {integrity: sha512-/mWx5136gts2Z2e5izdoRCo46lPp5TMs9R15GTSsgg/XnZyxDWVqoVU3R9lWnccKpqwsJLvRoxbCjoJtZB7DSw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-AkCYCmwlXeuH89DagDCzvCAyltI2v9lh3U3DqSg/GrBYoReAaWwxfXCqMx9UV5MajLZ4ZFwZzV4cABGIxk2XRw==}
-
resolution: {integrity: sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==}
@@ -8925,10 +8916,6 @@ packages:
resolution: {integrity: sha512-ZYvCgrefwqoQ6yTyYUbQu64HsITZ3NfKX1lzaEYdkTDcfKzzCI/wthRRYKkdjHKFVgNiXKAKm65Zo1pk2as/QQ==}
hasBin: true
- resolution: {integrity: sha512-Ab9bQDQ11lWootZUI5qxgN2ZXwxNI5hTwnsvOc1wyxQ7zQ8OkEDw79mI0+9jI3x432NfwbVRru+3noJfXF6lSQ==}
- hasBin: true
-
resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==}
engines: {node: '>= 0.4'}
@@ -18302,10 +18289,6 @@ snapshots:
'@types/through': 0.0.33
rxjs: 7.8.2
- '@types/[email protected]':
- dependencies:
- ci-info: 3.9.0
-
'@types/[email protected]': {}
@@ -22832,10 +22815,6 @@ snapshots:
dependencies:
ci-info: 3.9.0
- dependencies:
- ci-info: 4.4.0
-
dependencies:
hasown: 2.0.4
diff --git a/test/browser-pool/browser-plugins/plugins.test.ts b/test/browser-pool/browser-plugins/plugins.test.ts
index 0a843c27c..44cfb6241 100644
--- a/test/browser-pool/browser-plugins/plugins.test.ts
+++ b/test/browser-pool/browser-plugins/plugins.test.ts
@@ -22,6 +22,11 @@ import { runExampleComServer } from '../../shared/_helper.js';
import { createProxyServer } from './create-proxy-server.js';
+// Chromium goes through the tests faster than Firefox and the results are more useful than with
+// webkit. CI and `pnpm test:full` set CRAWLEE_TEST_BROWSERS to the full list.
+const requestedBrowsers = (process.env.CRAWLEE_TEST_BROWSERS ?? 'chromium').split(',');
+const testedBrowsers = (['chromium', 'firefox', 'webkit'] as const).filter((name) => requestedBrowsers.includes(name));
+
// Firefox browser launch is significantly slower than Chromium/WebKit (~12s vs <1s).
// Under CPU load from parallel tests, it can exceed 2 minutes. Use 5 minute timeout.
vitest.setConfig({ testTimeout: 300_000 });
@@ -420,7 +425,7 @@ describe('Plugins', () => {
await browser.close();
});
- describe.each(['chromium', 'firefox', 'webkit'] as const)('with %s', (browserName) => {
+ describe.each(testedBrowsers)('with %s', (browserName) => {
test('should work with non authenticated proxyUrl', async () => {
const proxyUrl = `http://127.0.0.2:${unprotectedProxy.port}`;
const plugin = new PlaywrightPlugin(playwright[browserName]);
@@ -698,7 +703,7 @@ describe('Plugins', () => {
});
});
- runPluginTest(PlaywrightPlugin, PlaywrightController, playwright.chromium);
- runPluginTest(PlaywrightPlugin, PlaywrightController, playwright.firefox);
- runPluginTest(PlaywrightPlugin, PlaywrightController, playwright.webkit);
+ for (const browserName of testedBrowsers) {
+ runPluginTest(PlaywrightPlugin, PlaywrightController, playwright[browserName]);
+ }
});
diff --git a/test/browser-pool/browser-pool.test.ts b/test/browser-pool/browser-pool.test.ts
index ec4485e44..a351ac96c 100644
--- a/test/browser-pool/browser-pool.test.ts
+++ b/test/browser-pool/browser-pool.test.ts
@@ -324,6 +324,19 @@ describe.each([
});
test('browser lifecycle works correctly', async () => {
+ // A browser whose launch hooks have not resolved yet must survive both inactivity
+ // sweeps. Sub-second windows plus a fast killer interval let each sweep run several
+ // times during the wait, instead of sleeping past the 2s defaults from beforeEach.
+ // The waits stay real: a live browser is launching underneath, and faking the clock
+ // would stall the driver's own timeouts along with the pool's.
+ const pool = new BrowserPool({
+ browserPlugins: [plugin],
+ closeInactiveBrowserAfterSecs: 0.5,
+ retireInactiveBrowserAfterSecs: 0.5,
+ });
+ clearInterval(pool['browserKillerInterval']!);
+ pool['browserKillerInterval'] = setInterval(async () => pool['closeInactiveRetiredBrowsers'](), 100);
+
let resolvePreLaunchHook: (() => void) | null = null;
let resolvePostLaunchHook: (() => void) | null = null;
@@ -334,31 +347,37 @@ describe.each([
resolvePostLaunchHook = resolve;
});
- browserPool.preLaunchHooks = [...browserPool.preLaunchHooks, async () => preLaunchPromise];
+ pool.preLaunchHooks = [...pool.preLaunchHooks, async () => preLaunchPromise];
- browserPool.postLaunchHooks = [...browserPool.postLaunchHooks, async () => postLaunchPromise];
+ pool.postLaunchHooks = [...pool.postLaunchHooks, async () => postLaunchPromise];
- const newPagePromise = browserPool.newPage();
+ try {
+ const newPagePromise = pool.newPage();
- await sleep(200);
+ await sleep(200);
- expect(browserPool.startingBrowserControllers.size).toBe(1);
- expect(browserPool.activeBrowserControllers.size).toBe(0);
- expect(browserPool.retiredBrowserControllers.size).toBe(0);
+ expect(pool.startingBrowserControllers.size).toBe(1);
+ expect(pool.activeBrowserControllers.size).toBe(0);
+ expect(pool.retiredBrowserControllers.size).toBe(0);
- await sleep(5e3); // Make the wait longer than the browser pool's retireInactiveBrowserAfterSecs + closeInactiveBrowserAfterSecs
+ await sleep(1200);
- resolvePreLaunchHook!();
- resolvePostLaunchHook!();
+ resolvePreLaunchHook!();
+ resolvePostLaunchHook!();
- const page = await newPagePromise;
+ const page = await newPagePromise;
- expect(browserPool.startingBrowserControllers.size).toBe(0);
- expect(browserPool.activeBrowserControllers.size).toBe(1);
- expect(browserPool.retiredBrowserControllers.size).toBe(0);
+ expect(pool.startingBrowserControllers.size).toBe(0);
+ expect(pool.activeBrowserControllers.size).toBe(1);
+ expect(pool.retiredBrowserControllers.size).toBe(0);
- await (page.evaluate as any)('() => {}'); // Make sure the page is usable
- await page.close();
+ // Make sure the page is usable. The Puppeteer and Playwright `evaluate`
+ // overloads have no compatible signature, so the union is not callable as-is.
+ await (page.evaluate as unknown as (script: string) => Promise<void>)('() => {}');
+ await page.close();
+ } finally {
+ await pool.destroy();
+ }
});
describe('preLaunchHooks', () => {
@@ -548,222 +567,6 @@ describe.each([
);
});
});
-
- describe('default browser automation masking', () => {
- describe.each(fingerprintingMatrix)('%s', (_name, fingerprintPlugin) => {
- let browserPoolWithDefaults: BrowserPool;
- let page: any;
-
- beforeEach(async () => {
- browserPoolWithDefaults = new BrowserPool({
- browserPlugins: [fingerprintPlugin],
- closeInactiveBrowserAfterSecs: 2,
- });
- page = await browserPoolWithDefaults.newPage();
- });
-
- afterEach(async () => {
- if (page) await page.close();
-
- await browserPoolWithDefaults.destroy();
- });
-
- test('should hide webdriver', async () => {
- await page.goto(`file://${import.meta.dirname}/test.html`);
- const webdriver = await page.evaluate(() => {
- return navigator.webdriver;
- });
- // Can be undefined or false, depending on the chrome version.
- expect(webdriver).toBeFalsy();
- });
- });
- });
-
- describe('fingerprinting', () => {
- describe.each(fingerprintingMatrix)('%s', (_name, fingerprintPlugin) => {
- let browserPoolWithFP: BrowserPool;
- let page: any;
-
- beforeEach(async () => {
- browserPoolWithFP = new BrowserPool({
- browserPlugins: [fingerprintPlugin],
- closeInactiveBrowserAfterSecs: 2,
- useFingerprints: true,
- });
- page = await browserPoolWithFP.newPage();
- });
-
- afterEach(async () => {
- if (page) await page.close();
-
- await browserPoolWithFP.destroy();
- });
-
- test('should override fingerprint', async () => {
- await page.goto(`file://${import.meta.dirname}/test.html`);
- // @ts-expect-error mistypings
- const browserController = browserPoolWithFP.getBrowserControllerByPage(page);
-
- const data: { hardwareConcurrency: number; userAgent: string } = await page.evaluate(() => {
- return {
- hardwareConcurrency: navigator.hardwareConcurrency,
- userAgent: navigator.userAgent,
- };
- });
- // @ts-expect-error mistypings
- const { fingerprint } = browserController!.launchContext!
- .fingerprint as BrowserFingerprintWithHeaders;
-
- expect(data.hardwareConcurrency).toBe(fingerprint?.navigator.hardwareConcurrency);
- expect(data.userAgent).toBe(fingerprint?.navigator.userAgent);
- });
-
- test('should hide webdriver', async () => {
- await page.goto(`file://${import.meta.dirname}/test.html`);
- const webdriver = await page.evaluate(() => {
- return navigator.webdriver;
- });
- // Can be undefined or false, depending on the chrome version.
- expect(webdriver).toBeFalsy();
- });
- });
-
- describe('caching', () => {
- const commonOptions = {
- browserPlugins: [
- new PlaywrightPlugin(playwright.chromium, {
- useIncognitoPages: true,
- }),
- ],
- };
- let browserPoolCache: BrowserPool;
-
- afterEach(async () => {
- await browserPoolCache.destroy();
- });
- test('should use fingerprint cache by default', async () => {
- browserPoolCache = new BrowserPool({
- ...commonOptions,
- useFingerprints: true,
- });
-
- expect(browserPoolCache.fingerprintCache).toBeDefined();
- });
-
- test('should turn off cache', async () => {
- browserPoolCache = new BrowserPool({
- ...commonOptions,
- useFingerprints: true,
- fingerprintOptions: {
- useFingerprintCache: false,
- },
- });
-
- expect(browserPoolCache.fingerprintCache).toBeUndefined();
- });
-
- test('should limit cache size', async () => {
- browserPoolCache = new BrowserPool({
- ...commonOptions,
- useFingerprints: true,
- fingerprintOptions: {
- fingerprintCacheSize: 1,
- },
- });
- // cast to any type in order to access the maxSize property for testing purposes.
- const cache: any = browserPoolCache!.fingerprintCache!;
- expect(cache.maxSize).toBe(1);
- });
-
- test('should cache fingerprints', async () => {
- browserPoolCache = new BrowserPool({
- ...commonOptions,
- useFingerprints: true,
- preLaunchHooks: [
- (_pageId, launchContext) => {
- // @ts-expect-error issue caused by generics
- launchContext.extend({ session: { id: '123' } });
- },
- ],
- });
- const mock = vitest.fn();
- browserPoolCache.fingerprintInjector!.attachFingerprintToPlaywright = mock;
- const page: Page = await browserPoolCache.newPageInNewBrowser();
- expect(mock.mock.calls[0][1]).toBeDefined();
- const page2: Page = await browserPoolCache.newPageInNewBrowser();
- await page.close();
- await page2.close();
- // expect fingerprint parameter of the first call to equal fingerprint parameter of the second call
- expect(mock.mock.calls[0][1]).toBe(mock.mock.calls[1][1]);
- });
- });
- });
- describe('generator configuration', () => {
- const commonOptions = {
- browserPlugins: [
- new PlaywrightPlugin(playwright.firefox, {
- useIncognitoPages: true,
- }),
- ],
- };
- let browserPoolConfig: BrowserPool;
- afterEach(async () => {
- await browserPoolConfig.destroy();
- });
- test('should use native os and browser', async () => {
- browserPoolConfig = new BrowserPool({
- ...commonOptions,
- useFingerprints: true,
- });
- const oldGet = browserPoolConfig.fingerprintGenerator!.getFingerprint;
- const mock = vitest.fn((options) => {
- return oldGet.bind(browserPoolConfig.fingerprintGenerator)(options);
- });
- browserPoolConfig.fingerprintGenerator!.getFingerprint = mock;
-
- const page: Page = await browserPoolConfig.newPage();
- await page.close();
- const defaultOptions = mock.mock.calls[0][0];
-
- expect(defaultOptions.browsers.includes('firefox')).toBe(true);
-
- let os: string;
- switch (process.platform) {
- case 'darwin':
- os = 'macos';
- break;
- case 'win32':
- os = 'windows';
- break;
- default:
- os = 'linux';
- }
- expect(defaultOptions.operatingSystems.includes(os)).toBe(true);
- });
-
- test('should allow changing options', async () => {
- browserPoolConfig = new BrowserPool({
- ...commonOptions,
- useFingerprints: true,
- fingerprintOptions: {
- fingerprintGeneratorOptions: {
- operatingSystems: [OperatingSystemsName.windows],
- browsers: [BrowserName.chrome],
- },
- },
- });
- const oldGet = browserPoolConfig.fingerprintGenerator!.getFingerprint;
- const mock = vitest.fn((options) => {
- return oldGet.bind(browserPoolConfig.fingerprintGenerator)(options);
- });
- browserPoolConfig.fingerprintGenerator!.getFingerprint = mock;
- const page: Page = await browserPoolConfig.newPageInNewBrowser();
- await page.close();
- const [options] = mock.mock.calls[0];
- expect(options.operatingSystems.includes('windows')).toBe(true);
- expect(options.browsers.includes('chrome')).toBe(true);
- });
- });
});
describe('events', () => {
@@ -833,3 +636,222 @@ describe.each([
});
});
});
+
+// These suites bring their own plugins, so they are independent of the plugin parametrization
+// above - nesting them inside it ran every one of them twice with identical inputs.
+describe('BrowserPool - fingerprints', () => {
+ describe('default browser automation masking', () => {
+ describe.each(fingerprintingMatrix)('%s', (_name, fingerprintPlugin) => {
+ let browserPoolWithDefaults: BrowserPool;
+ let page: any;
+
+ beforeEach(async () => {
+ browserPoolWithDefaults = new BrowserPool({
+ browserPlugins: [fingerprintPlugin],
+ closeInactiveBrowserAfterSecs: 2,
+ });
+ page = await browserPoolWithDefaults.newPage();
+ });
+
+ afterEach(async () => {
+ if (page) await page.close();
+
+ await browserPoolWithDefaults.destroy();
+ });
+
+ test('should hide webdriver', async () => {
+ await page.goto(`file://${import.meta.dirname}/test.html`);
+ const webdriver = await page.evaluate(() => {
+ return navigator.webdriver;
+ });
+ // Can be undefined or false, depending on the chrome version.
+ expect(webdriver).toBeFalsy();
+ });
+ });
+ });
+
+ describe('fingerprinting', () => {
+ describe.each(fingerprintingMatrix)('%s', (_name, fingerprintPlugin) => {
+ let browserPoolWithFP: BrowserPool;
+ let page: any;
+
+ beforeEach(async () => {
+ browserPoolWithFP = new BrowserPool({
+ browserPlugins: [fingerprintPlugin],
+ closeInactiveBrowserAfterSecs: 2,
+ useFingerprints: true,
+ });
+ page = await browserPoolWithFP.newPage();
+ });
+
+ afterEach(async () => {
+ if (page) await page.close();
+
+ await browserPoolWithFP.destroy();
+ });
+
+ test('should override fingerprint', async () => {
+ await page.goto(`file://${import.meta.dirname}/test.html`);
+ // @ts-expect-error mistypings
+ const browserController = browserPoolWithFP.getBrowserControllerByPage(page);
+
+ const data: { hardwareConcurrency: number; userAgent: string } = await page.evaluate(() => {
+ return {
+ hardwareConcurrency: navigator.hardwareConcurrency,
+ userAgent: navigator.userAgent,
+ };
+ });
+ // @ts-expect-error mistypings
+ const { fingerprint } = browserController!.launchContext!.fingerprint as BrowserFingerprintWithHeaders;
+
+ expect(data.hardwareConcurrency).toBe(fingerprint?.navigator.hardwareConcurrency);
+ expect(data.userAgent).toBe(fingerprint?.navigator.userAgent);
+ });
+
+ test('should hide webdriver', async () => {
+ await page.goto(`file://${import.meta.dirname}/test.html`);
+ const webdriver = await page.evaluate(() => {
+ return navigator.webdriver;
+ });
+ // Can be undefined or false, depending on the chrome version.
+ expect(webdriver).toBeFalsy();
+ });
+ });
+
+ describe('caching', () => {
+ const commonOptions = {
+ browserPlugins: [
+ new PlaywrightPlugin(playwright.chromium, {
+ useIncognitoPages: true,
+ }),
+ ],
+ };
+ let browserPoolCache: BrowserPool;
+
+ afterEach(async () => {
+ await browserPoolCache.destroy();
+ });
+ test('should use fingerprint cache by default', async () => {
+ browserPoolCache = new BrowserPool({
+ ...commonOptions,
+ useFingerprints: true,
+ });
+
+ expect(browserPoolCache.fingerprintCache).toBeDefined();
+ });
+
+ test('should turn off cache', async () => {
+ browserPoolCache = new BrowserPool({
+ ...commonOptions,
+ useFingerprints: true,
+ fingerprintOptions: {
+ useFingerprintCache: false,
+ },
+ });
+
+ expect(browserPoolCache.fingerprintCache).toBeUndefined();
+ });
+
+ test('should limit cache size', async () => {
+ browserPoolCache = new BrowserPool({
+ ...commonOptions,
+ useFingerprints: true,
+ fingerprintOptions: {
+ fingerprintCacheSize: 1,
+ },
+ });
+ // cast to any type in order to access the maxSize property for testing purposes.
+ const cache: any = browserPoolCache!.fingerprintCache!;
+ expect(cache.maxSize).toBe(1);
+ });
+
+ test('should cache fingerprints', async () => {
+ browserPoolCache = new BrowserPool({
+ ...commonOptions,
+ useFingerprints: true,
+ preLaunchHooks: [
+ (_pageId, launchContext) => {
+ // @ts-expect-error issue caused by generics
+ launchContext.extend({ session: { id: '123' } });
+ },
+ ],
+ });
+ const mock = vitest.fn();
+ browserPoolCache.fingerprintInjector!.attachFingerprintToPlaywright = mock;
+ const page: Page = await browserPoolCache.newPageInNewBrowser();
+ expect(mock.mock.calls[0][1]).toBeDefined();
+ const page2: Page = await browserPoolCache.newPageInNewBrowser();
+ await page.close();
+ await page2.close();
+ // expect fingerprint parameter of the first call to equal fingerprint parameter of the second call
+ expect(mock.mock.calls[0][1]).toBe(mock.mock.calls[1][1]);
+ });
+ });
+ });
+ describe('generator configuration', () => {
+ const commonOptions = {
+ browserPlugins: [
+ new PlaywrightPlugin(playwright.firefox, {
+ useIncognitoPages: true,
+ }),
+ ],
+ };
+ let browserPoolConfig: BrowserPool;
+ afterEach(async () => {
+ await browserPoolConfig.destroy();
+ });
+ test('should use native os and browser', async () => {
+ browserPoolConfig = new BrowserPool({
+ ...commonOptions,
+ useFingerprints: true,
+ });
+ const oldGet = browserPoolConfig.fingerprintGenerator!.getFingerprint;
+ const mock = vitest.fn((options) => {
+ return oldGet.bind(browserPoolConfig.fingerprintGenerator)(options);
+ });
+ browserPoolConfig.fingerprintGenerator!.getFingerprint = mock;
+
+ const page: Page = await browserPoolConfig.newPage();
+ await page.close();
+ const defaultOptions = mock.mock.calls[0][0];
+
+ expect(defaultOptions.browsers.includes('firefox')).toBe(true);
+
+ let os: string;
+ switch (process.platform) {
+ case 'darwin':
+ os = 'macos';
+ break;
+ case 'win32':
+ os = 'windows';
+ break;
+ default:
+ os = 'linux';
+ }
+ expect(defaultOptions.operatingSystems.includes(os)).toBe(true);
+ });
+
+ test('should allow changing options', async () => {
+ browserPoolConfig = new BrowserPool({
+ ...commonOptions,
+ useFingerprints: true,
+ fingerprintOptions: {
+ fingerprintGeneratorOptions: {
+ operatingSystems: [OperatingSystemsName.windows],
+ browsers: [BrowserName.chrome],
+ },
+ },
+ });
+ const oldGet = browserPoolConfig.fingerprintGenerator!.getFingerprint;
+ const mock = vitest.fn((options) => {
+ return oldGet.bind(browserPoolConfig.fingerprintGenerator)(options);
+ });
+ browserPoolConfig.fingerprintGenerator!.getFingerprint = mock;
+ const page: Page = await browserPoolConfig.newPageInNewBrowser();
+ await page.close();
+ const [options] = mock.mock.calls[0];
+ expect(options.operatingSystems.includes('windows')).toBe(true);
+ expect(options.browsers.includes('chrome')).toBe(true);
+ });
+ });
+});
diff --git a/test/core/autoscaling/fixtures/child.js b/test/core/autoscaling/fixtures/child.js
index f47b12e79..b9f15f707 100644
--- a/test/core/autoscaling/fixtures/child.js
+++ b/test/core/autoscaling/fixtures/child.js
@@ -1,4 +1,3 @@
-// dummy script for testing ps-tree.ts
-setTimeout(() => {
- /* Does nothing, but prevents exit */
-}, 5000);
+// Dummy script for testing ps-tree.ts. The lifetime only has to outlast the "children are
+// visible" poll in psTree.test.ts, which then waits for these to exit on their own.
+setTimeout(() => {}, 1500);
diff --git a/vitest.config.mts b/vitest.config.mts
index ee3756b18..9244b2f28 100644
--- a/vitest.config.mts
+++ b/vitest.config.mts
@@ -1,21 +1,39 @@
import { existsSync } from 'node:fs';
+import { availableParallelism, totalmem } from 'node:os';
import { resolve } from 'node:path';
-import isCI from 'is-ci';
-import { defineConfig, mergeConfig } from 'vitest/config';
+import { defaultExclude, defineConfig, mergeConfig } from 'vitest/config';
-let threads: { minThreads: number; maxThreads: number } | undefined;
+// Tests that drive real browsers: ~70% of the suite's CPU time and all of its memory pressure.
+// They get their own project so `maxWorkers` can be capped independently, and `sequence.groupOrder`
+// keeps them from running next to the cheap tests.
+const browserTests = [
+ 'packages/browser-pool/test/**/*.test.ts',
+ 'test/browser-pool/**/*.test.ts',
+ 'test/core/autoscaling/memory-infoV2.test.ts',
+ 'test/core/browser_launchers/*.test.ts',
+ 'test/core/crawlers/adaptive_playwright_crawler.test.ts',
+ 'test/core/crawlers/browser_crawler.test.ts',
+ 'test/core/crawlers/playwright_crawler.test.ts',
+ 'test/core/crawlers/puppeteer_crawler.test.ts',
+ 'test/core/enqueue_links/click_elements.test.ts',
+ 'test/core/enqueue_links/enqueue_links.test.ts',
+ 'test/core/playwright_utils.test.ts',
+ 'test/core/puppeteer_request_interception.test.ts',
+ 'test/core/puppeteer_utils.test.ts',
+];
-if (isCI) {
- console.log(`Running in CI, throttling threads to 1 test at a time`);
- threads = { minThreads: 1, maxThreads: 1 };
-}
+// vitest's default of one worker per core (minus one) is fine for cheap tests but not for tests
+// holding browsers, which cost a process tree and ~1.2 GB each. Both projects scale with the
+// machine, then stop where measurement stopped paying: wall time floors out on the longest single
+// file, so wider runs only buy contention and flakes. Override with CRAWLEE_TEST_WORKERS /
+// CRAWLEE_TEST_BROWSER_WORKERS.
+const cores = availableParallelism();
+const memoryGiB = totalmem() / 1024 ** 3;
+const workers = (override: string | undefined, ...limits: number[]) =>
+ Number(override) || Math.max(1, Math.floor(Math.min(...limits, cores - 1)));
const baseConfig = defineConfig({
- esbuild: {
- target: 'es2022',
- keepNames: true,
- },
test: {
globals: true,
setupFiles: ['./test/vitest.setup.ts'],
@@ -25,7 +43,6 @@ const baseConfig = defineConfig({
exclude: ['**/node_modules/**', '**/dist/**', '**/test/**'],
},
restoreMocks: true,
- ...threads,
testTimeout: 60_000,
hookTimeout: 60_000,
alias: [
@@ -49,18 +66,38 @@ const baseConfig = defineConfig({
{ find: /^test\/(.*)$/, replacement: resolve(__dirname, './test/$1') },
],
retry: process.env.RETRY_TESTS ? 3 : 0,
+ projects: [
+ {
+ extends: true,
+ test: {
+ name: 'unit',
+ exclude: [...defaultExclude, ...browserTests],
+ maxWorkers: workers(process.env.CRAWLEE_TEST_WORKERS, 8),
+ },
+ },
+ {
+ extends: true,
+ test: {
+ name: 'browser',
+ include: browserTests,
+ maxWorkers: workers(process.env.CRAWLEE_TEST_BROWSER_WORKERS, 4, cores / 2, memoryGiB / 3),
+ // `test.concurrent` in the browser-pool tests multiplies the worker cap by
+ // vitest's default of 5 concurrent tests per file, each with its own browser.
+ maxConcurrency: 2,
+ sequence: { groupOrder: 1 },
+ },
+ },
+ ],
},
});
-// Check for local config override
+// Optional local override, gitignored. Resolved once per project, so it must stay side-effect free.
const localConfigPath = resolve(__dirname, './vitest.config.local.mts');
let finalConfig = baseConfig;
if (existsSync(localConfigPath)) {
const localConfigModule = await import(localConfigPath);
- const localConfig = localConfigModule.default;
- console.log(`Applying local vitest config overrides`);
- finalConfig = mergeConfig(baseConfig, localConfig);
+ finalConfig = mergeConfig(baseConfig, localConfigModule.default);
}
export default finalConfig;