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.

fix tests (#680)

Ondra Urban3f1c1598c518
diff --git a/src/dataset.js b/src/dataset.js
index 30540f53c..c57072239 100644
--- a/src/dataset.js
+++ b/src/dataset.js
@@ -3,9 +3,9 @@ import { promisify } from 'util';
import * as fs from 'fs-extra';
import * as _ from 'underscore';
import { leftpad } from 'apify-shared/utilities';
-import * as LruCache from 'apify-shared/lru_cache';
import { checkParamOrThrow } from 'apify-client/build/utils';
import { ENV_VARS, LOCAL_STORAGE_SUBDIRS, MAX_PAYLOAD_SIZE_BYTES } from 'apify-shared/consts';
+import globalCache from './global_cache';
import { apifyClient, ensureDirExists, openRemoteStorage, openLocalStorage, ensureTokenOrLocalStorageEnvExists } from './utils';
import log from './utils_log';
@@ -13,7 +13,7 @@ export const DATASET_ITERATORS_DEFAULT_LIMIT = 10000;
export const LOCAL_STORAGE_SUBDIR = LOCAL_STORAGE_SUBDIRS.datasets;
export const LOCAL_FILENAME_DIGITS = 9;
export const LOCAL_GET_ITEMS_DEFAULT_LIMIT = 250000;
-const MAX_OPENED_STORES = 1000;
+const MAX_OPENED_DATASETS = 1000;
const SAFETY_BUFFER_PERCENT = 0.01 / 100; // 0.01%
const writeFilePromised = promisify(fs.writeFile);
@@ -25,7 +25,7 @@ const emptyDirPromised = promisify(fs.emptyDir);
const getLocaleFilename = index => `${leftpad(index, LOCAL_FILENAME_DIGITS, 0)}.json`;
const { datasets } = apifyClient;
-const datasetsCache = new LruCache({ maxLength: MAX_OPENED_STORES }); // Open Datasets are stored here.
+const datasetsCache = globalCache.create('dataset-cache', MAX_OPENED_DATASETS); // Open Datasets are stored here.
/**
* Accepts a JSON serializable object as an input, validates its serializability,
diff --git a/src/global_cache.js b/src/global_cache.js
new file mode 100644
index 000000000..f7cd71b6c
--- /dev/null
+++ b/src/global_cache.js
@@ -0,0 +1,30 @@
+import * as LruCache from 'apify-shared/lru_cache';
+
+/**
+ * Used to manage all globally created caches, such as request queue cache
+ * or dataset cache. Before creation of this class, those caches were
+ * created as module scoped globals - untouchable. This proved problematic
+ * especially in tests, where caches would prevent test separation.
+ */
+class GlobalCache {
+ constructor() {
+ this.caches = new Map();
+ }
+
+ create(name, maxSize) {
+ const newCache = new LruCache({ maxLength: maxSize });
+ this.caches.set(name, newCache);
+ return newCache;
+ }
+
+ clear(name) {
+ const cache = this.caches.get(name);
+ cache.clear();
+ }
+
+ clearAll() {
+ this.caches.forEach(cache => cache.clear());
+ }
+}
+
+export default new GlobalCache();
diff --git a/src/key_value_store.js b/src/key_value_store.js
index c75a250d0..958488d2a 100644
--- a/src/key_value_store.js
+++ b/src/key_value_store.js
@@ -3,7 +3,6 @@ import * as path from 'path';
import { promisify } from 'util';
import * as contentTypeParser from 'content-type';
import * as mime from 'mime-types';
-import * as LruCache from 'apify-shared/lru_cache';
import { KEY_VALUE_STORE_KEY_REGEX } from 'apify-shared/regexs';
import { ENV_VARS, LOCAL_STORAGE_SUBDIRS, KEY_VALUE_STORE_KEYS } from 'apify-shared/consts';
import { jsonStringifyExtended } from 'apify-shared/utilities';
@@ -12,6 +11,7 @@ import {
addCharsetToContentType, apifyClient, ensureDirExists, openRemoteStorage, openLocalStorage, ensureTokenOrLocalStorageEnvExists,
} from './utils';
import { APIFY_API_BASE_URL } from './constants';
+import globalCache from './global_cache';
import log from './utils_log';
export const LOCAL_STORAGE_SUBDIR = LOCAL_STORAGE_SUBDIRS.keyValueStores;
@@ -27,7 +27,7 @@ const statPromised = promisify(fs.stat);
const emptyDirPromised = promisify(fs.emptyDir);
const { keyValueStores } = apifyClient;
-const storesCache = new LruCache({ maxLength: MAX_OPENED_STORES }); // Open key-value stores are stored here.
+const storesCache = globalCache.create('key-value-store-cache', MAX_OPENED_STORES); // Open key-value stores are stored here.
/**
* Helper function to validate params of *.getValue().
diff --git a/src/request_queue.js b/src/request_queue.js
index 42a727676..ffaf0d0c2 100644
--- a/src/request_queue.js
+++ b/src/request_queue.js
@@ -7,6 +7,7 @@ import * as ListDictionary from 'apify-shared/list_dictionary';
import { ENV_VARS, LOCAL_STORAGE_SUBDIRS, REQUEST_QUEUE_HEAD_MAX_LIMIT } from 'apify-shared/consts';
import { checkParamPrototypeOrThrow, cryptoRandomObjectId } from 'apify-shared/utilities';
import Request, { RequestOptions } from './request'; // eslint-disable-line import/named,no-unused-vars
+import globalCache from './global_cache';
import {
ensureDirExists, apifyClient, openRemoteStorage, openLocalStorage, ensureTokenOrLocalStorageEnvExists, sleep,
} from './utils';
@@ -36,7 +37,7 @@ const RECENTLY_HANDLED_CACHE_SIZE = 1000;
export const STORAGE_CONSISTENCY_DELAY_MILLIS = 3000;
const { requestQueues } = apifyClient;
-const queuesCache = new LruCache({ maxLength: MAX_OPENED_QUEUES }); // Open queues are stored here.
+const queuesCache = globalCache.create('request-queue-cache', MAX_OPENED_QUEUES); // Open queues are stored here.
/**
* Helper function to validate params of *.addRequest().
diff --git a/test/_helper.js b/test/_helper.js
index 3f2ac3b39..f81be9a5a 100644
--- a/test/_helper.js
+++ b/test/_helper.js
@@ -1,9 +1,6 @@
import fs from 'fs-extra';
-import path from 'path';
import { ENV_VARS } from 'apify-shared/consts';
-export const LOCAL_STORAGE_DIR = path.join(__dirname, '..', 'tmp', 'local-emulation-dir');
-
// Log unhandled rejections.
// process.on('unhandledRejection', (err) => {
// console.log('----------------------------------------------------------------');
@@ -13,13 +10,6 @@ export const LOCAL_STORAGE_DIR = path.join(__dirname, '..', 'tmp', 'local-emulat
// process.exit(1);
// });
-
-export const emptyLocalStorageSubdir = (subdir) => {
- const fullPath = path.resolve(path.join(LOCAL_STORAGE_DIR, subdir));
-
- fs.emptyDirSync(fullPath);
-};
-
export const expectNotUsingLocalStorage = () => expect(process.env[ENV_VARS.LOCAL_STORAGE_DIR]).toBeUndefined();
export const expectDirEmpty = (dirPath) => {
diff --git a/test/crawlers/basic_crawler.test.js b/test/crawlers/basic_crawler.test.js
index 5b3034c07..ee6dc0515 100644
--- a/test/crawlers/basic_crawler.test.js
+++ b/test/crawlers/basic_crawler.test.js
@@ -12,18 +12,16 @@ import LocalStorageDirEmulator from '../local_storage_dir_emulator';
describe('BasicCrawler', () => {
let logLevel;
let localStorageEmulator;
- let LOCAL_STORAGE_DIR;
+ let localStorageDir;
beforeAll(async () => {
logLevel = log.getLevel();
log.setLevel(log.LEVELS.OFF);
localStorageEmulator = new LocalStorageDirEmulator();
- await localStorageEmulator.init();
- LOCAL_STORAGE_DIR = localStorageEmulator.localStorageDir;
});
beforeEach(async () => {
- await localStorageEmulator.clean();
+ localStorageDir = await localStorageEmulator.init();
});
afterAll(async () => {
@@ -265,7 +263,7 @@ describe('BasicCrawler', () => {
test('should also support RequestQueueLocal', () => {
const requestQueue = new RequestQueue('xxx');
- const requestQueueLocal = new RequestQueueLocal('xxx', LOCAL_STORAGE_DIR);
+ const requestQueueLocal = new RequestQueueLocal('xxx', localStorageDir);
const handleRequestFunction = () => {};
expect(() => new Apify.BasicCrawler({ handleRequestFunction, requestQueue })).not.toThrowError();
diff --git a/test/crawlers/cheerio_crawler.test.js b/test/crawlers/cheerio_crawler.test.js
index 277784c59..21f7ba949 100644
--- a/test/crawlers/cheerio_crawler.test.js
+++ b/test/crawlers/cheerio_crawler.test.js
@@ -95,11 +95,10 @@ describe('CheerioCrawler', () => {
server = await startExpressAppPromise(app, 0);
port = server.address().port; //eslint-disable-line
localStorageEmulator = new LocalStorageDirEmulator();
- await localStorageEmulator.init();
});
- afterEach(async () => {
- await localStorageEmulator.clean();
+ beforeEach(async () => {
+ await localStorageEmulator.init();
});
afterAll(async () => {
@@ -533,7 +532,7 @@ describe('CheerioCrawler', () => {
}
});
- test('always when using "!"', async () => {
+ test('always when forced', async () => {
const forceResponseEncoding = 'win1250';
const buf = iconv.encode(html, forceResponseEncoding);
// Ensure it's really encoded.
@@ -556,11 +555,6 @@ describe('CheerioCrawler', () => {
});
});
- test('should encode responses using responseEncoding', async () => {
-
-
- });
-
describe('proxy', () => {
let requestList;
beforeEach(async () => {
@@ -719,7 +713,6 @@ describe('CheerioCrawler', () => {
let requestList;
beforeEach(async () => {
- await localStorageEmulator.clean();
requestList = await Apify.openRequestList('test', sources.slice());
});
diff --git a/test/crawlers/puppeteer_crawler.test.js b/test/crawlers/puppeteer_crawler.test.js
index a12907486..9d884fbdb 100644
--- a/test/crawlers/puppeteer_crawler.test.js
+++ b/test/crawlers/puppeteer_crawler.test.js
@@ -14,10 +14,9 @@ describe('PuppeteerCrawler', () => {
logLevel = log.getLevel();
log.setLevel(log.LEVELS.ERROR);
localStorageEmulator = new LocalStorageDirEmulator();
- await localStorageEmulator.init();
});
- afterEach(async () => {
- await localStorageEmulator.clean();
+ beforeEach(async () => {
+ await localStorageEmulator.init();
});
afterAll(async () => {
log.setLevel(logLevel);
diff --git a/test/dataset.test.js b/test/dataset.test.js
index a368a98cb..36076547a 100644
--- a/test/dataset.test.js
+++ b/test/dataset.test.js
@@ -18,8 +18,6 @@ describe('dataset', () => {
beforeAll(async () => {
apifyClient.setOptions({ token: 'xxx' });
localStorageEmulator = new LocalStorageDirEmulator();
- await localStorageEmulator.init();
- localStorageDir = localStorageEmulator.localStorageDir; // eslint-disable-line
});
afterAll(async () => {
@@ -28,7 +26,7 @@ describe('dataset', () => {
});
beforeEach(async () => {
- await localStorageEmulator.clean();
+ localStorageDir = await localStorageEmulator.init();
});
const read = (datasetName, index) => {
diff --git a/test/key_value_store.test.js b/test/key_value_store.test.js
index d5ae1cf4a..63f078c0a 100644
--- a/test/key_value_store.test.js
+++ b/test/key_value_store.test.js
@@ -16,8 +16,6 @@ describe('KeyValueStore', () => {
beforeAll(async () => {
apifyClient.setOptions({ token: 'xxx' });
localStorageEmulator = new LocalStorageDirEmulator();
- await localStorageEmulator.init();
- localStorageDir = localStorageEmulator.localStorageDir; // eslint-disable-line
});
afterAll(async () => {
@@ -26,7 +24,7 @@ describe('KeyValueStore', () => {
});
beforeEach(async () => {
- await localStorageEmulator.clean();
+ localStorageDir = await localStorageEmulator.init();
});
describe('maybeStringify()', () => {
diff --git a/test/live_view/live_view_server.test.js b/test/live_view/live_view_server.test.js
index 8fb8f5498..35861fd33 100644
--- a/test/live_view/live_view_server.test.js
+++ b/test/live_view/live_view_server.test.js
@@ -4,15 +4,13 @@ import fs from 'fs-extra';
import io from 'socket.io-client';
import { ENV_VARS, LOCAL_ENV_VARS } from 'apify-shared/consts';
import Apify from '../../build/index';
-import { LOCAL_STORAGE_DIR } from '../_helper';
import LiveViewServer from '../../build/live_view/live_view_server';
import { requestAsBrowser } from '../../build/utils_request';
+import LocalStorageDirEmulator from '../local_storage_dir_emulator';
const { utils: { log } } = Apify;
-const emptyDir = promisify(fs.emptyDir);
const readdir = promisify(fs.readdir);
-const LOCAL_STORAGE_SUBDIR = path.join(LOCAL_STORAGE_DIR, 'live_view');
const PORT = LOCAL_ENV_VARS[ENV_VARS.CONTAINER_PORT];
const BASE_URL = `http://localhost:${PORT}`;
@@ -34,19 +32,26 @@ describe('LiveViewServer', () => {
content: async () => 'content',
screenshot: async () => `screenshot${count++}`,
};
- beforeEach(() => {
+ let localStorageDirEmulator;
+ let localStorageSubDir;
+
+ beforeAll(() => {
+ localStorageDirEmulator = new LocalStorageDirEmulator();
+ });
+
+ beforeEach(async () => {
+ const localStorageDir = await localStorageDirEmulator.init();
+ localStorageSubDir = path.join(localStorageDir, 'live_view');
count = 0;
lvs = new LiveViewServer({
- screenshotDirectoryPath: LOCAL_STORAGE_SUBDIR,
+ screenshotDirectoryPath: localStorageSubDir,
maxScreenshotFiles: 2,
maxSnapshotFrequencySecs: 0,
});
});
- afterEach(async () => {
- count = null;
- lvs = null;
- await emptyDir(LOCAL_STORAGE_SUBDIR);
+ afterAll(async () => {
+ await localStorageDirEmulator.destroy();
});
test('should construct', async () => {
@@ -73,11 +78,11 @@ describe('LiveViewServer', () => {
await lvs.start();
expect(lvs.hasClients()).toBe(true);
await lvs.serve(fakePage);
- let files = await readdir(LOCAL_STORAGE_SUBDIR);
+ let files = await readdir(localStorageSubDir);
expect(files.length).toBe(1);
expect(lvs.hasClients()).toBe(false);
await lvs.serve(fakePage);
- files = await readdir(LOCAL_STORAGE_SUBDIR);
+ files = await readdir(localStorageSubDir);
expect(files.length).toBe(1);
await lvs.stop();
});
@@ -122,7 +127,7 @@ describe('LiveViewServer', () => {
}
const files = await new Promise((resolve, reject) => {
const interval = setInterval(async () => {
- const files = await readdir(LOCAL_STORAGE_SUBDIR); // eslint-disable-line no-shadow
+ const files = await readdir(localStorageSubDir); // eslint-disable-line no-shadow
if (files.length === 2) {
clearInterval(interval);
resolve(files);
diff --git a/test/local_storage_dir_emulator.js b/test/local_storage_dir_emulator.js
index 7ceedf3c4..783b06312 100644
--- a/test/local_storage_dir_emulator.js
+++ b/test/local_storage_dir_emulator.js
@@ -3,8 +3,9 @@ import { LOCAL_STORAGE_SUBDIRS, LOCAL_ENV_VARS, ENV_VARS } from 'apify-shared/co
import fs from 'fs-extra';
import path from 'path';
import log from '../build/utils_log';
+import globalCache from '../build/global_cache';
-import { LOCAL_STORAGE_DIR } from './_helper';
+const LOCAL_EMULATION_DIR = path.join(__dirname, '..', 'tmp', 'local-emulation-dir');
const DEFAULT_FOLDERS = Object.values(LOCAL_STORAGE_SUBDIRS)
.concat([
@@ -21,42 +22,40 @@ const DEFAULT_FOLDERS = Object.values(LOCAL_STORAGE_SUBDIRS)
* call `clean()` in afterEach hook and finally call `destroy()` in afterAll hook.
*/
class LocalStorageDirEmulator {
- constructor(localStorageDir = cryptoRandomObjectId(10)) {
- this.localStorageDir = path.join(LOCAL_STORAGE_DIR, localStorageDir);
- log.debug(`Created local storage emulation in folder ${this.localStorageDir}`);
+ constructor() {
+ this.localStorageDirs = [];
}
- async init() {
- await fs.ensureDir(path.resolve(this.localStorageDir));
+ async init(dirName = cryptoRandomObjectId(10)) {
+ globalCache.clearAll();
+ const localStorageDir = path.resolve(LOCAL_EMULATION_DIR, dirName);
+ await fs.ensureDir(localStorageDir);
// prepare structure
- await this._ensureStructure();
- process.env.APIFY_LOCAL_STORAGE_DIR = this.localStorageDir;
+ await this._ensureStructure(localStorageDir);
+ process.env.APIFY_LOCAL_STORAGE_DIR = localStorageDir;
+ this.localStorageDirs.push(localStorageDir);
+ log.debug(`Created local storage emulation in folder ${localStorageDir}`);
+ return localStorageDir;
}
/**
* Removes the folder itself
- * @return {Promise<void>}
+ * @return {Promise}
*/
async destroy() {
- fs.removeSync(this.localStorageDir);
delete process.env.APIFY_LOCAL_STORAGE_DIR;
+ const promises = this.localStorageDirs.map((dir) => {
+ return fs.remove(dir);
+ });
+ return Promise.all(promises);
}
- /**
- * Removes all files/folders form it
- * @return {Promise<void>}
- */
- async clean() {
- for (const folder of DEFAULT_FOLDERS) {
- await fs.emptyDirSync(path.join(this.localStorageDir, folder));
- }
- }
-
- async _ensureStructure() {
+ async _ensureStructure(localStorageDir) {
// create first level
- for (const folder of DEFAULT_FOLDERS) {
- await fs.ensureDir(path.join(this.localStorageDir, folder));
- }
+ const promises = DEFAULT_FOLDERS.map((folder) => {
+ return fs.ensureDir(path.join(localStorageDir, folder));
+ });
+ return Promise.all(promises);
}
}
diff --git a/test/puppeteer_pool.test.js b/test/puppeteer_pool.test.js
index d71343d87..ea2d551c0 100644
--- a/test/puppeteer_pool.test.js
+++ b/test/puppeteer_pool.test.js
@@ -656,11 +656,10 @@ describe('PuppeteerPool', () => {
beforeAll(async () => {
localStorageEmulator = new LocalStorageDirEmulator();
- await localStorageEmulator.init();
});
- afterEach(async () => {
- await localStorageEmulator.clean();
+ beforeEach(async () => {
+ await localStorageEmulator.init();
});
afterAll(async () => {
diff --git a/test/puppeteer_utils.test.js b/test/puppeteer_utils.test.js
index 98d7c9758..9a369420d 100644
--- a/test/puppeteer_utils.test.js
+++ b/test/puppeteer_utils.test.js
@@ -15,11 +15,10 @@ describe('Apify.utils.puppeteer', () => {
ll = log.getLevel();
log.setLevel(log.LEVELS.ERROR);
localStorageEmulator = new LocalStorageDirEmulator();
- await localStorageEmulator.init();
});
beforeEach(async () => {
- await localStorageEmulator.clean();
+ await localStorageEmulator.init();
});
afterAll(async () => {
diff --git a/test/request_queue.test.js b/test/request_queue.test.js
index 1d8c74267..54fae8736 100644
--- a/test/request_queue.test.js
+++ b/test/request_queue.test.js
@@ -28,8 +28,6 @@ describe('RequestQueue', () => {
beforeAll(async () => {
apifyClient.setOptions({ token: 'xxx' });
localStorageEmulator = new LocalStorageDirEmulator();
- await localStorageEmulator.init();
- localStorageDir = localStorageEmulator.localStorageDir; // eslint-disable-line
});
afterAll(async () => {
@@ -38,7 +36,7 @@ describe('RequestQueue', () => {
});
beforeEach(async () => {
- await localStorageEmulator.clean();
+ localStorageDir = await localStorageEmulator.init();
});
test('should work', async () => {
diff --git a/test/session_pool/session_pool.test.js b/test/session_pool/session_pool.test.js
index a13b46c09..3f36d7807 100644
--- a/test/session_pool/session_pool.test.js
+++ b/test/session_pool/session_pool.test.js
@@ -13,17 +13,15 @@ describe('SessionPool - testing session pool', () => {
beforeAll(async () => {
localStorageEmulator = new LocalStorageDirEmulator();
- await localStorageEmulator.init();
});
beforeEach(async () => {
- await localStorageEmulator.clean();
+ await localStorageEmulator.init();
sessionPool = await Apify.openSessionPool();
});
afterEach(async () => {
events.removeAllListeners(ACTOR_EVENT_NAMES_EX.PERSIST_STATE);
- await localStorageEmulator.clean();
});
afterAll(async () => {
@@ -63,9 +61,6 @@ describe('SessionPool - testing session pool', () => {
});
// log is appended to sessionOptions after sessionPool instantiation
expect(sessionPool.sessionOptions).toEqual({ ...opts.sessionOptions, log: expect.any(defaultLog.Log) });
-
- const store = await Apify.openKeyValueStore('TEST');
- await store.drop();
});
test('should work using openSessionPool', async () => {
@@ -92,9 +87,6 @@ describe('SessionPool - testing session pool', () => {
});
// log is appended to sessionOptions after sessionPool instantiation
expect(sessionPool.sessionOptions).toEqual({ ...opts.sessionOptions, log: expect.any(defaultLog.Log) });
-
- const store = await Apify.openKeyValueStore('TEST');
- await store.drop();
});
describe('should retrieve session', () => {
@@ -125,29 +117,26 @@ describe('SessionPool - testing session pool', () => {
expect(isCalled).toBe(true); //eslint-disable-line
});
- test(
- 'should delete picked session when it is usable a create a new one',
- async () => {
- sessionPool.maxPoolSize = 1;
- await sessionPool.getSession();
- const session = sessionPool.sessions[0];
+ test('should delete picked session when it is usable a create a new one', async () => {
+ sessionPool.maxPoolSize = 1;
+ await sessionPool.getSession();
+ const session = sessionPool.sessions[0];
- session.errorScore += session.maxErrorScore;
- let isCalled = false;
- const oldRemove = sessionPool._removeSession; //eslint-disable-line
+ session.errorScore += session.maxErrorScore;
+ let isCalled = false;
+ const oldRemove = sessionPool._removeSession; //eslint-disable-line
- sessionPool._removeSession = (session) => { //eslint-disable-line
- isCalled = true;
- return oldRemove.bind(sessionPool)(session);
- };
+ sessionPool._removeSession = (session) => { //eslint-disable-line
+ isCalled = true;
+ return oldRemove.bind(sessionPool)(session);
+ };
- await sessionPool.getSession();
+ await sessionPool.getSession();
expect(isCalled).toBe(true); //eslint-disable-line
expect(sessionPool.sessions[0].id === session.id).toBe(false); //eslint-disable-line
- expect(sessionPool.sessions).toHaveLength(1);
- },
- );
+ expect(sessionPool.sessions).toHaveLength(1);
+ });
});
test('get state should work', async () => {
diff --git a/test/stealth/stealth.test.js b/test/stealth/stealth.test.js
index ff9d8ba57..8365359f6 100644
--- a/test/stealth/stealth.test.js
+++ b/test/stealth/stealth.test.js
@@ -20,11 +20,10 @@ describe('Stealth - testing headless chrome hiding tricks', () => {
beforeAll(async () => {
localStorageEmulator = new LocalStorageDirEmulator();
- await localStorageEmulator.init();
});
beforeEach(async () => {
- await localStorageEmulator.clean();
+ await localStorageEmulator.init();
});
afterAll(async () => {