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.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
Remove bluebird dependecies and fix autoscaled pool tests on Node 12
Ondra Urbanfebcf243417c
diff --git a/test/actor.test.js b/test/actor.test.jsindex 407a5f2fe..6d6bf16bd 100644--- a/test/actor.test.js+++ b/test/actor.test.js@@ -1,9 +1,9 @@import path from 'path';import _ from 'underscore';import sinon from 'sinon';-import { delayPromise } from 'apify-shared/utilities';import { ENV_VARS, ACT_JOB_STATUSES, LOCAL_ENV_VARS } from 'apify-shared/consts';import { ApifyCallError } from '../build/errors';+import { sleep } from '../build/utils';// NOTE: test use of require() here because this is how its done in actsconst Apify = require('../build/index');@@ -227,7 +227,7 @@ describe('Apify.main()', () => {() => {return testMain({userFunc: async () => {- await delayPromise(20);+ await sleep(20);throw new Error('Test exception II');},exitCode: 91,diff --git a/test/autoscaling/autoscaled_pool.test.js b/test/autoscaling/autoscaled_pool.test.jsindex 0f55d4b4d..9d5777796 100644--- a/test/autoscaling/autoscaled_pool.test.js+++ b/test/autoscaling/autoscaled_pool.test.js@@ -1,6 +1,6 @@import _ from 'underscore';-import { delayPromise } from 'apify-shared/utilities';import log from 'apify-shared/log';+import { sleep } from '../../build/utils';import AutoscaledPool from '../../build/autoscaling/autoscaled_pool';/* eslint-disable no-underscore-dangle */@@ -207,7 +207,7 @@ describe('AutoscaledPool', () => {let count = 0;pool.systemStatus.okNow = false;pool.runTaskFunction = async () => {- await delayPromise(10);+ await sleep(10);count++;};pool.isFinishedFunction = async () => count >= limit;@@ -254,42 +254,35 @@ describe('AutoscaledPool', () => {test('when some of the promises throws', async () => {let counter = 0;- const runTaskFunction = () => {+ const runTaskFunction = async () => {counter++;-- if (counter > 100) return;-- if (counter === 100) {- const err = new Error('some-promise-error');-- return new Promise((resolve, reject) => setTimeout(reject(err), 3));- }-- return delayPromise(3);+ await sleep(1);+ // console.log('AFTER SLEEP');+ if (counter > 20) throw new Error('some-promise-error');};const pool = new AutoscaledPool({- minConcurrency: 10,- maxConcurrency: 10,+ maxConcurrency: 5,+ minConcurrency: 5,runTaskFunction,- isFinishedFunction: () => Promise.resolve(false),- isTaskReadyFunction: () => Promise.resolve(true),+ isFinishedFunction: async () => counter > 200,+ isTaskReadyFunction: async () => true,});await expect(pool.run()).rejects.toThrow('some-promise-error');});test('when runTaskFunction throws', async () => {- const runTaskFunction = () => {+ const runTaskFunction = async () => {+ await sleep(3);throw new Error('some-runtask-error');};const pool = new AutoscaledPool({- minConcurrency: 10,- maxConcurrency: 10,+ maxConcurrency: 1,runTaskFunction,- isFinishedFunction: () => Promise.resolve(false),- isTaskReadyFunction: () => Promise.resolve(true),+ isFinishedFunction: async () => false,+ isTaskReadyFunction: async () => true,});@@ -299,22 +292,25 @@ describe('AutoscaledPool', () => {test('when isFinishedFunction throws', async () => {let count = 0;const pool = new AutoscaledPool({- minConcurrency: 10,- maxConcurrency: 10,- runTaskFunction: async () => { count++; },- isFinishedFunction: async () => { throw new Error('some-finished-error'); },- isTaskReadyFunction: async () => count < 1,+ maxConcurrency: 1,+ runTaskFunction: async () => {+ count++;+ },+ isFinishedFunction: async () => {+ throw new Error('some-finished-error');+ },+ isTaskReadyFunction: async () => {+ return count < 1;+ },});-await expect(pool.run()).rejects.toThrow('some-finished-error');});test('when isTaskReadyFunction throws', async () => {let count = 0;const pool = new AutoscaledPool({- minConcurrency: 10,- maxConcurrency: 10,+ maxConcurrency: 1,runTaskFunction: async () => { count++; },isFinishedFunction: async () => false,isTaskReadyFunction: async () => {@@ -329,57 +325,51 @@ describe('AutoscaledPool', () => {});- test(- 'should not handle tasks added after isFinishedFunction returned true',- async () => {- const isFinished = async () => count > 10;- let count = 0;+ test('should not handle tasks added after isFinishedFunction returned true', async () => {+ const isFinished = async () => count > 10;+ let count = 0;- // Run the pool and close it after 3s.- const pool = new AutoscaledPool({- minConcurrency: 3,- runTaskFunction: async () => delayPromise(1).then(() => { count++; }),- isFinishedFunction: async () => isFinished(),- isTaskReadyFunction: async () => !await isFinished(),- });- pool.maybeRunIntervalMillis = 5;+ // Run the pool and close it after 3s.+ const pool = new AutoscaledPool({+ minConcurrency: 3,+ runTaskFunction: async () => sleep(1).then(() => { count++; }),+ isFinishedFunction: isFinished,+ isTaskReadyFunction: async () => !await isFinished(),+ });+ pool.maybeRunIntervalMillis = 5;- await pool.run();- await delayPromise(10);- expect(count).toBeGreaterThanOrEqual(11);- // Check finished tasks.- expect(count).toBeLessThanOrEqual(13);- },- );-- test(- 'should break and resume when the task queue is empty for a while',- async () => {- const finished = [];- let isFinished = false;- let isTaskReady = true;+ await pool.run();+ await sleep(10);+ expect(count).toBeGreaterThanOrEqual(11);+ // Check finished tasks.+ expect(count).toBeLessThanOrEqual(13);+ });- let counter = 0;- const pool = new AutoscaledPool({- maxConcurrency: 1,- runTaskFunction: async () => {- await delayPromise(1);- if (counter === 10) { isTaskReady = false; setTimeout(() => { isTaskReady = true; }, 10); }- if (counter === 19) { isTaskReady = false; isFinished = true; }- counter++;- finished.push(Date.now());- },- isFinishedFunction: async () => isFinished,- isTaskReadyFunction: async () => !isFinished && isTaskReady,- });- pool.maybeRunIntervalMillis = 1;- await pool.run();+ test('should break and resume when the task queue is empty for a while', async () => {+ const finished = [];+ let isFinished = false;+ let isTaskReady = true;- // Check finished tasks.- expect(finished).toHaveLength(20);- expect(finished[11] - finished[10]).toBeGreaterThan(9);- },- );+ let counter = 0;+ const pool = new AutoscaledPool({+ maxConcurrency: 1,+ runTaskFunction: async () => {+ await sleep(1);+ if (counter === 10) { isTaskReady = false; setTimeout(() => { isTaskReady = true; }, 10); }+ if (counter === 19) { isTaskReady = false; isFinished = true; }+ counter++;+ finished.push(Date.now());+ },+ isFinishedFunction: async () => isFinished,+ isTaskReadyFunction: async () => !isFinished && isTaskReady,+ });+ pool.maybeRunIntervalMillis = 1;+ await pool.run();++ // Check finished tasks.+ expect(finished).toHaveLength(20);+ expect(finished[11] - finished[10]).toBeGreaterThan(9);+ });test('should work with loggingIntervalMillis = null', async () => {const pool = new AutoscaledPool({@@ -420,7 +410,7 @@ describe('AutoscaledPool', () => {const pool = new AutoscaledPool({runTaskFunction: async () => {started = true;- await delayPromise(100);+ await sleep(100);completed = true;},diff --git a/test/crawlers/basic_crawler.test.js b/test/crawlers/basic_crawler.test.jsindex 58aa2c44a..2e3fc1728 100644--- a/test/crawlers/basic_crawler.test.js+++ b/test/crawlers/basic_crawler.test.js@@ -2,10 +2,10 @@ import _ from 'underscore';import sinon from 'sinon';import log from 'apify-shared/log';import { ACTOR_EVENT_NAMES } from 'apify-shared/consts';-import { delayPromise } from 'apify-shared/utilities';import * as Apify from '../../build';import * as keyValueStore from '../../build/key_value_store';import { RequestQueue, RequestQueueLocal } from '../../build/request_queue';+import { sleep } from '../../build/utils';import { LOCAL_STORAGE_DIR } from '../_helper';describe('BasicCrawler', () => {@@ -27,7 +27,7 @@ describe('BasicCrawler', () => {const processed = [];const requestList = new Apify.RequestList({ sources });const handleRequestFunction = async ({ request }) => {- await delayPromise(10);+ await sleep(10);processed.push(_.pick(request, 'url'));};@@ -105,7 +105,7 @@ describe('BasicCrawler', () => {const requestList = new Apify.RequestList({ sources });const handleRequestFunction = async ({ request }) => {- await delayPromise(10);+ await sleep(10);processed[request.url] = request;if (request.url === 'http://example.com/2') {@@ -159,7 +159,7 @@ describe('BasicCrawler', () => {const requestList = new Apify.RequestList({ sources });const handleRequestFunction = async ({ request }) => {- await delayPromise(10);+ await sleep(10);processed[request.url] = request;request.userData.foo = 'bar';throw Error(`This is ${request.retryCount}th error!`);@@ -273,7 +273,7 @@ describe('BasicCrawler', () => {const requestQueue = new RequestQueue('xxx');const handleRequestFunction = async ({ request }) => {- await delayPromise(10);+ await sleep(10);processed[request.url] = request;if (request.url === 'http://example.com/1') {@@ -421,7 +421,7 @@ describe('BasicCrawler', () => {},},handleRequestFunction: async ({ request }) => {- await delayPromise(10);+ await sleep(10);processed.push(request);},});@@ -465,7 +465,7 @@ describe('BasicCrawler', () => {const requestList = new Apify.RequestList({ sources });const handleRequestFunction = async ({ request }) => {- await delayPromise(10);+ await sleep(10);processed[request.url] = request;if (request.url === 'http://example.com/2') throw Error();request.userData.foo = 'bar';@@ -520,7 +520,7 @@ describe('BasicCrawler', () => {requestQueue,maxConcurrency: 1,handleRequestFunction: async () => {- await delayPromise(1);+ await sleep(1);count++;},maxRequestsPerCrawl: 40,@@ -543,7 +543,7 @@ describe('BasicCrawler', () => {requestList,maxConcurrency: 1,handleRequestFunction: async () => {- await delayPromise(1);+ await sleep(1);count++;},maxRequestsPerCrawl: 40,@@ -574,7 +574,7 @@ describe('BasicCrawler', () => {requestQueue,maxConcurrency: 1,handleRequestFunction: async () => {- await delayPromise(1);+ await sleep(1);count++;},maxRequestsPerCrawl: 40,@@ -598,7 +598,7 @@ describe('BasicCrawler', () => {requestList,handleRequestTimeoutSecs: 0.01,maxRequestRetries: 1,- handleRequestFunction: () => delayPromise(1000),+ handleRequestFunction: () => sleep(1000),handleFailedRequestFunction: ({ request }) => results.push(request),});diff --git a/test/crawlers/cheerio_crawler.test.js b/test/crawlers/cheerio_crawler.test.jsindex 03959644b..1e0db23a0 100644--- a/test/crawlers/cheerio_crawler.test.js+++ b/test/crawlers/cheerio_crawler.test.js@@ -4,11 +4,11 @@ import rqst from 'request';import fs from 'fs';import path from 'path';import log from 'apify-shared/log';-import { delayPromise } from 'apify-shared/utilities';import { ENV_VARS } from 'apify-shared/consts';import express from 'express';import bodyParser from 'body-parser';import Apify from '../../build';+import { sleep } from '../../build/utils';// Add common props to mocked request responses.const responseMock = {@@ -137,7 +137,7 @@ describe('CheerioCrawler', () => {});app.get('/timeout', async (req, res) => {- await delayPromise(32000);+ await sleep(32000);res.type('html').send('<div>TEST</div>');});@@ -255,7 +255,7 @@ describe('CheerioCrawler', () => {});cheerioCrawler._requestFunction = async () => {- await delayPromise(300);+ await sleep(300);return '<html><head></head><body>Body</body></html>';};@@ -282,7 +282,7 @@ describe('CheerioCrawler', () => {const failed = [];const requestList = new Apify.RequestList({ sources });const handlePageFunction = async ({ request }) => {- await delayPromise(3000);+ await sleep(3000);processed.push(request);};diff --git a/test/events.test.js b/test/events.test.jsindex 5765d8e34..a2a60b7f5 100644--- a/test/events.test.js+++ b/test/events.test.js@@ -1,8 +1,8 @@import WebSocket from 'ws';import sinon from 'sinon';-import { delayPromise } from 'apify-shared/utilities';import { ENV_VARS } from 'apify-shared/consts';import { ACTOR_EVENT_NAMES_EX } from '../build/constants';+import { sleep } from '../build/utils';import Apify from '../build';@@ -50,10 +50,10 @@ describe('Apify.events', () => {// Run main and store received eventsexpect(isWsConnected).toBe(false);Apify.main(async () => {- await delayPromise(10); // Here must be short sleep to get following line to later tick+ await sleep(10); // Here must be short sleep to get following line to later tickexpect(isWsConnected).toBe(true);Apify.events.on('name-1', data => eventsReceived.push(data));- await delayPromise(1000);+ await sleep(1000);});// Main will call process.exit() so we must stub it.@@ -68,7 +68,7 @@ describe('Apify.events', () => {wss.close();delete process.env[ENV_VARS.ACTOR_EVENTS_WS_URL];delete process.env[ENV_VARS.TOKEN];- await delayPromise(10); // Here must be short sleep to get following line to later tick+ await sleep(10); // Here must be short sleep to get following line to later tickexpect(isWsConnected).toBe(false);done();});@@ -101,16 +101,16 @@ describe('Apify.events', () => {// Connect to websocket and receive events.expect(isWsConnected).toBe(false);await Apify.initializeEvents();- await delayPromise(10); // Here must be short sleep to get following line to later tick+ await sleep(10); // Here must be short sleep to get following line to later tickexpect(isWsConnected).toBe(true);Apify.events.on('name-1', data => eventsReceived.push(data));- await delayPromise(1000);+ await sleep(1000);expect(eventsReceived).toEqual([[1, 2, 3], { foo: 'bar' }]);expect(isWsConnected).toBe(true);Apify.stopEvents();- await delayPromise(10); // Here must be short sleep to get following line to later tick+ await sleep(10); // Here must be short sleep to get following line to later tickexpect(isWsConnected).toBe(false);// Cleanup.@@ -124,11 +124,11 @@ describe('Apify.events', () => {const eventsReceived = [];Apify.events.on(ACTOR_EVENT_NAMES_EX.PERSIST_STATE, data => eventsReceived.push(data));await Apify.initializeEvents();- await delayPromise(10);+ await sleep(10);await Apify.stopEvents();const eventCount = eventsReceived.length;expect(eventCount).toBeGreaterThan(2);- await delayPromise(10);+ await sleep(10);expect(eventsReceived.length).toEqual(eventCount);delete process.env.APIFY_TEST_PERSIST_INTERVAL_MILLIS;diff --git a/test/puppeteer_utils.test.js b/test/puppeteer_utils.test.jsindex ea792495f..563d8b83a 100644--- a/test/puppeteer_utils.test.js+++ b/test/puppeteer_utils.test.js@@ -286,7 +286,7 @@ describe('Apify.utils.puppeteer', () => {throw new Error('Should fail.');} catch (err) {// TODO figure out why the err.message comes out empty in the logs.- expect(err.message).toMatch('Unexpected token const');+ expect(err.message).toMatch(/Unexpected token '?const'?/);}const browser = await Apify.launchPuppeteer({ headless: true });try {diff --git a/test/request_list.test.js b/test/request_list.test.jsindex c7e53f652..0fffe3bac 100644--- a/test/request_list.test.js+++ b/test/request_list.test.js@@ -2,7 +2,6 @@ import _ from 'underscore';import request from 'request-promise-native';import sinon from 'sinon';import log from 'apify-shared/log';-import { delayPromise } from 'apify-shared/utilities';import { ACTOR_EVENT_NAMES_EX } from '../build/constants';import Apify from '../build/index';import * as keyValueStore from '../build/key_value_store';@@ -432,7 +431,7 @@ describe('Apify.RequestList', () => {.withArgs(PERSIST_STATE_KEY, requestList.getState()).returns(Promise.resolve());Apify.events.emit(ACTOR_EVENT_NAMES_EX.PERSIST_STATE);- await delayPromise(1);+ await utils.sleep(1);expect(requestList.isStatePersisted).toBe(true);// Do some other changes and persist it again.@@ -445,7 +444,7 @@ describe('Apify.RequestList', () => {.withArgs(PERSIST_STATE_KEY, requestList.getState()).returns(Promise.resolve());Apify.events.emit(ACTOR_EVENT_NAMES_EX.PERSIST_STATE);- await delayPromise(1);+ await utils.sleep(1);expect(requestList.isStatePersisted).toBe(true);// Reclaim event doesn't change the state.