forked from apify/crawlee-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_basic_crawler.py
More file actions
1804 lines (1381 loc) · 65.5 KB
/
test_basic_crawler.py
File metadata and controls
1804 lines (1381 loc) · 65.5 KB
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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ruff: noqa: ARG001
from __future__ import annotations
import asyncio
import concurrent
import json
import logging
import os
import sys
import time
from collections import Counter
from dataclasses import dataclass
from datetime import timedelta
from itertools import product
from typing import TYPE_CHECKING, Any, Literal, cast
from unittest.mock import AsyncMock, Mock, call, patch
import pytest
from crawlee import ConcurrencySettings, Glob, service_locator
from crawlee._request import Request, RequestState
from crawlee._types import BasicCrawlingContext, EnqueueLinksKwargs, HttpMethod
from crawlee._utils.robots import RobotsTxtFile
from crawlee.configuration import Configuration
from crawlee.crawlers import BasicCrawler
from crawlee.errors import RequestCollisionError, SessionError, UserDefinedErrorHandlerError
from crawlee.events import Event, EventCrawlerStatusData
from crawlee.events._local_event_manager import LocalEventManager
from crawlee.request_loaders import RequestList, RequestManagerTandem
from crawlee.sessions import Session, SessionPool
from crawlee.statistics import FinalStatistics
from crawlee.storage_clients import FileSystemStorageClient, MemoryStorageClient
from crawlee.storages import Dataset, KeyValueStore, RequestQueue
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from pathlib import Path
from yarl import URL
from crawlee._types import JsonSerializable
from crawlee.statistics import StatisticsState
async def test_processes_requests_from_explicit_queue() -> None:
queue = await RequestQueue.open()
await queue.add_requests(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
crawler = BasicCrawler(request_manager=queue)
calls = list[str]()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
calls.append(context.request.url)
await crawler.run()
assert calls == ['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com']
async def test_processes_requests_from_request_source_tandem() -> None:
request_queue = await RequestQueue.open()
await request_queue.add_requests(
['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com']
)
request_list = RequestList(['https://a.placeholder.com', 'https://d.placeholder.com', 'https://e.placeholder.com'])
crawler = BasicCrawler(request_manager=RequestManagerTandem(request_list, request_queue))
calls = set[str]()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
calls.add(context.request.url)
await crawler.run()
assert calls == {
'https://a.placeholder.com',
'https://b.placeholder.com',
'https://c.placeholder.com',
'https://d.placeholder.com',
'https://e.placeholder.com',
}
async def test_processes_requests_from_run_args() -> None:
crawler = BasicCrawler()
calls = list[str]()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
calls.append(context.request.url)
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
assert calls == ['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com']
async def test_allows_multiple_run_calls() -> None:
crawler = BasicCrawler()
calls = list[str]()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
calls.append(context.request.url)
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
assert calls == [
'https://a.placeholder.com',
'https://b.placeholder.com',
'https://c.placeholder.com',
'https://a.placeholder.com',
'https://b.placeholder.com',
'https://c.placeholder.com',
]
async def test_retries_failed_requests() -> None:
crawler = BasicCrawler()
calls = list[str]()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
calls.append(context.request.url)
if context.request.url == 'https://b.placeholder.com':
raise RuntimeError('Arbitrary crash for testing purposes')
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
assert calls == [
'https://a.placeholder.com',
'https://b.placeholder.com',
'https://c.placeholder.com',
'https://b.placeholder.com',
'https://b.placeholder.com',
'https://b.placeholder.com',
]
async def test_respects_no_retry() -> None:
crawler = BasicCrawler(max_request_retries=2)
calls = list[str]()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
calls.append(context.request.url)
raise RuntimeError('Arbitrary crash for testing purposes')
await crawler.run(
[
'https://a.placeholder.com',
'https://b.placeholder.com',
Request.from_url(url='https://c.placeholder.com', no_retry=True),
]
)
assert calls == [
'https://a.placeholder.com',
'https://b.placeholder.com',
'https://c.placeholder.com',
'https://a.placeholder.com',
'https://b.placeholder.com',
'https://a.placeholder.com',
'https://b.placeholder.com',
]
async def test_respects_request_specific_max_retries() -> None:
crawler = BasicCrawler(max_request_retries=0)
calls = list[str]()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
calls.append(context.request.url)
raise RuntimeError('Arbitrary crash for testing purposes')
await crawler.run(
[
'https://a.placeholder.com',
'https://b.placeholder.com',
Request.from_url(url='https://c.placeholder.com', user_data={'__crawlee': {'maxRetries': 1}}),
]
)
assert calls == [
'https://a.placeholder.com',
'https://b.placeholder.com',
'https://c.placeholder.com',
'https://c.placeholder.com',
]
async def test_calls_error_handler() -> None:
# Data structure to better track the calls to the error handler.
@dataclass(frozen=True)
class Call:
url: str
error: Exception
# List to store the information of calls to the error handler.
calls = list[Call]()
crawler = BasicCrawler(max_request_retries=2)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
if context.request.url == 'https://b.placeholder.com':
raise RuntimeError('Arbitrary crash for testing purposes')
@crawler.error_handler
async def error_handler(context: BasicCrawlingContext, error: Exception) -> Request:
# Append the current call information.
calls.append(Call(context.request.url, error))
return context.request
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
# Verify that the error handler was called twice
assert len(calls) == 2
# Check calls
for error_call in calls:
assert error_call.url == 'https://b.placeholder.com'
assert isinstance(error_call.error, RuntimeError)
async def test_calls_error_handler_for_session_errors() -> None:
crawler = BasicCrawler(
max_session_rotations=1,
)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
raise SessionError('Arbitrary session error for testing purposes')
error_handler_mock = AsyncMock()
@crawler.error_handler
async def error_handler(context: BasicCrawlingContext, error: Exception) -> None:
await error_handler_mock(context, error)
await crawler.run(['https://crawlee.dev'])
assert error_handler_mock.call_count == 1
async def test_handles_error_in_error_handler() -> None:
crawler = BasicCrawler(max_request_retries=3)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
if context.request.url == 'https://b.placeholder.com':
raise RuntimeError('Arbitrary crash for testing purposes')
@crawler.error_handler
async def error_handler(context: BasicCrawlingContext, error: Exception) -> None:
raise RuntimeError('Crash in error handler')
with pytest.raises(UserDefinedErrorHandlerError):
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
async def test_calls_failed_request_handler() -> None:
crawler = BasicCrawler(max_request_retries=3)
calls = list[tuple[BasicCrawlingContext, Exception]]()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
if context.request.url == 'https://b.placeholder.com':
raise RuntimeError('Arbitrary crash for testing purposes')
@crawler.failed_request_handler
async def failed_request_handler(context: BasicCrawlingContext, error: Exception) -> None:
calls.append((context, error))
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
assert len(calls) == 1
assert calls[0][0].request.url == 'https://b.placeholder.com'
assert isinstance(calls[0][1], RuntimeError)
@pytest.mark.parametrize('handler', ['failed_request_handler', 'error_handler'])
async def test_handlers_use_context_helpers(tmp_path: Path, handler: str) -> None:
"""Test that context helpers used in `failed_request_handler` and in `error_handler` have effect."""
# Prepare crawler
storage_client = FileSystemStorageClient()
crawler = BasicCrawler(
max_request_retries=1, storage_client=storage_client, configuration=Configuration(storage_dir=str(tmp_path))
)
# Test data
rq_alias = 'other'
test_data = {'some': 'data'}
test_key = 'key'
test_value = 'value'
test_request = Request.from_url('https://d.placeholder.com')
# Request handler with injected error
@crawler.router.default_handler
async def request_handler(context: BasicCrawlingContext) -> None:
raise RuntimeError('Arbitrary crash for testing purposes')
# Apply one of the handlers
@getattr(crawler, handler) # type: ignore[untyped-decorator]
async def handler_implementation(context: BasicCrawlingContext, error: Exception) -> None:
await context.push_data(test_data)
await context.add_requests(requests=[test_request], rq_alias=rq_alias)
kvs = await context.get_key_value_store()
await kvs.set_value(test_key, test_value)
await crawler.run(['https://b.placeholder.com'])
# Verify that the context helpers used in handlers had effect on used storages
dataset = await Dataset.open(storage_client=storage_client)
kvs = await KeyValueStore.open(storage_client=storage_client)
rq = await RequestQueue.open(alias=rq_alias, storage_client=storage_client)
assert test_value == await kvs.get_value(test_key)
assert [test_data] == (await dataset.get_data()).items
assert test_request == await rq.fetch_next_request()
async def test_handles_error_in_failed_request_handler() -> None:
crawler = BasicCrawler(max_request_retries=3)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
if context.request.url == 'https://b.placeholder.com':
raise RuntimeError('Arbitrary crash for testing purposes')
@crawler.failed_request_handler
async def failed_request_handler(context: BasicCrawlingContext, error: Exception) -> None:
raise RuntimeError('Crash in failed request handler')
with pytest.raises(UserDefinedErrorHandlerError):
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
@pytest.mark.parametrize(
('method', 'path', 'payload'),
[
pytest.param('GET', 'get', None, id='get send_request'),
pytest.param('POST', 'post', b'Hello, world!', id='post send_request'),
],
)
async def test_send_request_works(server_url: URL, method: HttpMethod, path: str, payload: None | bytes) -> None:
response_data: dict[str, Any] = {}
crawler = BasicCrawler(max_request_retries=3)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
response = await context.send_request(str(server_url / path), method=method, payload=payload)
response_data['body'] = json.loads(await response.read())
response_data['headers'] = response.headers
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
response_body = response_data.get('body')
assert response_body is not None
assert response_body.get('data') == (payload.decode() if payload else None)
response_headers = response_data.get('headers')
assert response_headers is not None
content_type = response_headers.get('content-type')
assert content_type is not None
assert content_type == 'application/json'
@dataclass
class AddRequestsTestInput:
start_url: str
loaded_url: str
requests: Sequence[str | Request]
expected_urls: Sequence[str]
kwargs: EnqueueLinksKwargs
STRATEGY_TEST_URLS = (
'https://someplace.com/',
'http://someplace.com/index.html',
'https://blog.someplace.com/index.html',
'https://redirect.someplace.com',
'https://other.place.com/index.html',
'https://someplace.jp/',
)
INCLUDE_TEST_URLS = (
'https://someplace.com/',
'https://someplace.com/blog/category/cats',
'https://someplace.com/blog/category/boots',
'https://someplace.com/blog/archive/index.html',
'https://someplace.com/blog/archive/cats',
)
@pytest.mark.parametrize(
'test_input',
argvalues=[
# Basic use case
pytest.param(
AddRequestsTestInput(
start_url='https://a.placeholder.com',
loaded_url='https://a.placeholder.com',
requests=[
'https://a.placeholder.com',
Request.from_url('https://b.placeholder.com'),
'https://c.placeholder.com',
],
kwargs={},
expected_urls=['https://b.placeholder.com', 'https://c.placeholder.com'],
),
id='basic',
),
# Enqueue strategy
pytest.param(
AddRequestsTestInput(
start_url=STRATEGY_TEST_URLS[0],
loaded_url=STRATEGY_TEST_URLS[0],
requests=STRATEGY_TEST_URLS,
kwargs=EnqueueLinksKwargs(),
expected_urls=STRATEGY_TEST_URLS[1:],
),
id='enqueue_strategy_default',
),
pytest.param(
AddRequestsTestInput(
start_url=STRATEGY_TEST_URLS[0],
loaded_url=STRATEGY_TEST_URLS[0],
requests=STRATEGY_TEST_URLS,
kwargs=EnqueueLinksKwargs(strategy='all'),
expected_urls=STRATEGY_TEST_URLS[1:],
),
id='enqueue_strategy_all',
),
pytest.param(
AddRequestsTestInput(
start_url=STRATEGY_TEST_URLS[0],
loaded_url=STRATEGY_TEST_URLS[0],
requests=STRATEGY_TEST_URLS,
kwargs=EnqueueLinksKwargs(strategy='same-domain'),
expected_urls=STRATEGY_TEST_URLS[1:4],
),
id='enqueue_strategy_same_domain',
),
pytest.param(
AddRequestsTestInput(
start_url=STRATEGY_TEST_URLS[0],
loaded_url=STRATEGY_TEST_URLS[0],
requests=STRATEGY_TEST_URLS,
kwargs=EnqueueLinksKwargs(strategy='same-hostname'),
expected_urls=[STRATEGY_TEST_URLS[1]],
),
id='enqueue_strategy_same_hostname',
),
pytest.param(
AddRequestsTestInput(
start_url=STRATEGY_TEST_URLS[0],
loaded_url=STRATEGY_TEST_URLS[0],
requests=STRATEGY_TEST_URLS,
kwargs=EnqueueLinksKwargs(strategy='same-origin'),
expected_urls=[],
),
id='enqueue_strategy_same_origin',
),
# Enqueue strategy with redirect
pytest.param(
AddRequestsTestInput(
start_url=STRATEGY_TEST_URLS[3],
loaded_url=STRATEGY_TEST_URLS[0],
requests=STRATEGY_TEST_URLS,
kwargs=EnqueueLinksKwargs(),
expected_urls=STRATEGY_TEST_URLS[:3] + STRATEGY_TEST_URLS[4:],
),
id='redirect_enqueue_strategy_default',
),
pytest.param(
AddRequestsTestInput(
start_url=STRATEGY_TEST_URLS[3],
loaded_url=STRATEGY_TEST_URLS[0],
requests=STRATEGY_TEST_URLS,
kwargs=EnqueueLinksKwargs(strategy='all'),
expected_urls=STRATEGY_TEST_URLS[:3] + STRATEGY_TEST_URLS[4:],
),
id='redirect_enqueue_strategy_all',
),
pytest.param(
AddRequestsTestInput(
start_url=STRATEGY_TEST_URLS[3],
loaded_url=STRATEGY_TEST_URLS[0],
requests=STRATEGY_TEST_URLS,
kwargs=EnqueueLinksKwargs(strategy='same-domain'),
expected_urls=STRATEGY_TEST_URLS[:3],
),
id='redirect_enqueue_strategy_same_domain',
),
pytest.param(
AddRequestsTestInput(
start_url=STRATEGY_TEST_URLS[3],
loaded_url=STRATEGY_TEST_URLS[0],
requests=STRATEGY_TEST_URLS,
kwargs=EnqueueLinksKwargs(strategy='same-hostname'),
expected_urls=[],
),
id='redirect_enqueue_strategy_same_hostname',
),
pytest.param(
AddRequestsTestInput(
start_url=STRATEGY_TEST_URLS[3],
loaded_url=STRATEGY_TEST_URLS[0],
requests=STRATEGY_TEST_URLS,
kwargs=EnqueueLinksKwargs(strategy='same-origin'),
expected_urls=[],
),
id='redirect_enqueue_strategy_same_origin',
),
# Include/exclude
pytest.param(
AddRequestsTestInput(
start_url=INCLUDE_TEST_URLS[0],
loaded_url=INCLUDE_TEST_URLS[0],
requests=INCLUDE_TEST_URLS,
kwargs=EnqueueLinksKwargs(include=[Glob('https://someplace.com/**/cats')]),
expected_urls=[INCLUDE_TEST_URLS[1], INCLUDE_TEST_URLS[4]],
),
id='include_exclude_1',
),
pytest.param(
AddRequestsTestInput(
start_url=INCLUDE_TEST_URLS[0],
loaded_url=INCLUDE_TEST_URLS[0],
requests=INCLUDE_TEST_URLS,
kwargs=EnqueueLinksKwargs(exclude=[Glob('https://someplace.com/**/cats')]),
expected_urls=[INCLUDE_TEST_URLS[2], INCLUDE_TEST_URLS[3]],
),
id='include_exclude_2',
),
pytest.param(
AddRequestsTestInput(
start_url=INCLUDE_TEST_URLS[0],
loaded_url=INCLUDE_TEST_URLS[0],
requests=INCLUDE_TEST_URLS,
kwargs=EnqueueLinksKwargs(
include=[Glob('https://someplace.com/**/cats')], exclude=[Glob('https://**/archive/**')]
),
expected_urls=[INCLUDE_TEST_URLS[1]],
),
id='include_exclude_3',
),
],
)
async def test_enqueue_strategy(test_input: AddRequestsTestInput) -> None:
visit = Mock()
crawler = BasicCrawler()
@crawler.router.handler('start')
async def start_handler(context: BasicCrawlingContext) -> None:
# Assign test value to loaded_url - BasicCrawler does not do any navigation by itself
context.request.loaded_url = test_input.loaded_url
await context.add_requests(
test_input.requests,
**test_input.kwargs,
)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
visit(context.request.url)
await crawler.run([Request.from_url(test_input.start_url, label='start')])
visited = {call[0][0] for call in visit.call_args_list}
assert visited == set(test_input.expected_urls)
async def test_session_rotation(server_url: URL) -> None:
session_ids: list[str | None] = []
crawler = BasicCrawler(
max_session_rotations=7,
max_request_retries=1,
)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
session_ids.append(context.session.id if context.session else None)
raise SessionError('Test error')
await crawler.run([str(server_url)])
# exactly 7 handler calls happened
assert len(session_ids) == 7
# all session ids are not None
assert None not in session_ids
# and each was a different session
assert len(set(session_ids)) == 7
async def test_final_statistics() -> None:
crawler = BasicCrawler(max_request_retries=2)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
id_param = context.request.get_query_param_from_url('id')
assert id_param is not None
id = int(id_param)
await asyncio.sleep(0.001)
if context.request.retry_count == 0 and id % 2 == 0:
raise RuntimeError('First crash')
if context.request.retry_count == 1 and id % 3 == 0:
raise RuntimeError('Second crash')
if context.request.retry_count == 2 and id % 4 == 0:
raise RuntimeError('Third crash')
final_statistics = await crawler.run(
[Request.from_url(f'https://someplace.com/?id={id}', label='start') for id in range(50)]
)
assert final_statistics.requests_total == 50
assert final_statistics.requests_finished == 45
assert final_statistics.requests_failed == 5
assert final_statistics.retry_histogram == [25, 16, 9]
assert final_statistics.request_avg_finished_duration is not None
assert final_statistics.request_avg_finished_duration > timedelta()
assert final_statistics.request_avg_failed_duration is not None
assert final_statistics.request_avg_failed_duration > timedelta()
assert final_statistics.request_total_duration > timedelta()
assert final_statistics.crawler_runtime > timedelta()
assert final_statistics.requests_finished_per_minute > 0
assert final_statistics.requests_failed_per_minute > 0
async def test_crawler_get_storages() -> None:
crawler = BasicCrawler()
rp = await crawler.get_request_manager()
assert isinstance(rp, RequestQueue)
dataset = await crawler.get_dataset()
assert isinstance(dataset, Dataset)
kvs = await crawler.get_key_value_store()
assert isinstance(kvs, KeyValueStore)
async def test_crawler_run_requests() -> None:
crawler = BasicCrawler()
seen_urls = list[str]()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
seen_urls.append(context.request.url)
start_urls = [
'http://test.io/1',
'http://test.io/2',
'http://test.io/3',
]
stats = await crawler.run(start_urls)
assert seen_urls == start_urls
assert stats.requests_total == 3
assert stats.requests_finished == 3
async def test_context_push_and_get_data() -> None:
crawler = BasicCrawler()
dataset = await Dataset.open()
await dataset.push_data({'a': 1})
assert (await crawler.get_data()).items == [{'a': 1}]
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
await context.push_data({'b': 2})
await dataset.push_data({'c': 3})
assert (await crawler.get_data()).items == [{'a': 1}, {'c': 3}]
stats = await crawler.run(['http://test.io/1'])
assert (await crawler.get_data()).items == [{'a': 1}, {'c': 3}, {'b': 2}]
assert stats.requests_total == 1
assert stats.requests_finished == 1
async def test_context_push_and_get_data_handler_error() -> None:
crawler = BasicCrawler()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
await context.push_data({'b': 2})
raise RuntimeError('Watch me crash')
stats = await crawler.run(['https://a.placeholder.com'])
assert (await crawler.get_data()).items == []
assert stats.requests_total == 1
assert stats.requests_finished == 0
assert stats.requests_failed == 1
async def test_crawler_push_and_export_data(tmp_path: Path) -> None:
crawler = BasicCrawler()
dataset = await Dataset.open()
await dataset.push_data([{'id': 0, 'test': 'test'}, {'id': 1, 'test': 'test'}])
await dataset.push_data({'id': 2, 'test': 'test'})
await crawler.export_data(path=tmp_path / 'dataset.json')
await crawler.export_data(path=tmp_path / 'dataset.csv')
assert json.load((tmp_path / 'dataset.json').open()) == [
{'id': 0, 'test': 'test'},
{'id': 1, 'test': 'test'},
{'id': 2, 'test': 'test'},
]
assert (tmp_path / 'dataset.csv').read_bytes() == b'id,test\r\n0,test\r\n1,test\r\n2,test\r\n'
async def test_context_push_and_export_data(tmp_path: Path) -> None:
crawler = BasicCrawler()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
await context.push_data([{'id': 0, 'test': 'test'}, {'id': 1, 'test': 'test'}])
await context.push_data({'id': 2, 'test': 'test'})
await crawler.run(['http://test.io/1'])
await crawler.export_data(path=tmp_path / 'dataset.json')
await crawler.export_data(path=tmp_path / 'dataset.csv')
assert json.load((tmp_path / 'dataset.json').open()) == [
{'id': 0, 'test': 'test'},
{'id': 1, 'test': 'test'},
{'id': 2, 'test': 'test'},
]
assert (tmp_path / 'dataset.csv').read_bytes() == b'id,test\r\n0,test\r\n1,test\r\n2,test\r\n'
async def test_context_update_kv_store() -> None:
crawler = BasicCrawler()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
store = await context.get_key_value_store()
await store.set_value('foo', 'bar')
await crawler.run(['https://hello.world'])
store = await crawler.get_key_value_store()
assert (await store.get_value('foo')) == 'bar'
async def test_context_use_state() -> None:
crawler = BasicCrawler()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
await context.use_state({'hello': 'world'})
await crawler.run(['https://hello.world'])
kvs = await crawler.get_key_value_store()
value = await kvs.get_value(BasicCrawler._CRAWLEE_STATE_KEY)
assert value == {'hello': 'world'}
async def test_context_handlers_use_state(key_value_store: KeyValueStore) -> None:
state_in_handler_one: dict[str, JsonSerializable] = {}
state_in_handler_two: dict[str, JsonSerializable] = {}
state_in_handler_three: dict[str, JsonSerializable] = {}
crawler = BasicCrawler()
@crawler.router.handler('one')
async def handler_one(context: BasicCrawlingContext) -> None:
state = await context.use_state({'hello': 'world'})
state_in_handler_one.update(state)
state['hello'] = 'new_world'
await context.add_requests([Request.from_url('https://crawlee.dev/docs/quick-start', label='two')])
@crawler.router.handler('two')
async def handler_two(context: BasicCrawlingContext) -> None:
state = await context.use_state({'hello': 'world'})
state_in_handler_two.update(state)
state['hello'] = 'last_world'
@crawler.router.handler('three')
async def handler_three(context: BasicCrawlingContext) -> None:
state = await context.use_state({'hello': 'world'})
state_in_handler_three.update(state)
await crawler.run([Request.from_url('https://crawlee.dev/', label='one')])
await crawler.run([Request.from_url('https://crawlee.dev/docs/examples', label='three')])
# The state in handler_one must match the default state
assert state_in_handler_one == {'hello': 'world'}
# The state in handler_two must match the state updated in handler_one
assert state_in_handler_two == {'hello': 'new_world'}
# The state in handler_three must match the final state updated in previous run
assert state_in_handler_three == {'hello': 'last_world'}
store = await crawler.get_key_value_store()
# The state in the KVS must match with the last set state
assert (await store.get_value(BasicCrawler._CRAWLEE_STATE_KEY)) == {'hello': 'last_world'}
async def test_max_requests_per_crawl() -> None:
start_urls = [
'http://test.io/1',
'http://test.io/2',
'http://test.io/3',
'http://test.io/4',
'http://test.io/5',
]
processed_urls = []
# Set max_concurrency to 1 to ensure testing max_requests_per_crawl accurately
crawler = BasicCrawler(
concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1),
max_requests_per_crawl=3,
)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
processed_urls.append(context.request.url)
stats = await crawler.run(start_urls)
# Verify that only 3 out of the 5 provided URLs were made
assert len(processed_urls) == 3
assert stats.requests_total == 3
assert stats.requests_finished == 3
async def test_max_crawl_depth() -> None:
processed_urls = []
# Set max_concurrency to 1 to ensure testing max_requests_per_crawl accurately
crawler = BasicCrawler(
concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1),
max_crawl_depth=2,
)
@crawler.router.handler('start')
async def start_handler(context: BasicCrawlingContext) -> None:
processed_urls.append(context.request.url)
await context.add_requests(['https://someplace.com/too-deep'])
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
processed_urls.append(context.request.url)
start_request = Request.from_url('https://someplace.com/', label='start')
start_request.crawl_depth = 2
stats = await crawler.run([start_request])
assert len(processed_urls) == 1
assert stats.requests_total == 1
assert stats.requests_finished == 1
@pytest.mark.parametrize(
('total_requests', 'fail_at_request', 'expected_starts', 'expected_finished'),
[
(3, None, 3, 3),
(3, 2, 2, 1),
],
ids=[
'all_requests_successful',
'abort_on_second_request',
],
)
async def test_abort_on_error(
total_requests: int, fail_at_request: int | None, expected_starts: int, expected_finished: int
) -> None:
starts_urls = []
crawler = BasicCrawler(
concurrency_settings=ConcurrencySettings(desired_concurrency=1, max_concurrency=1),
abort_on_error=True,
)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
starts_urls.append(context.request.url)
if context.request.user_data.get('n_request') == fail_at_request:
raise ValueError('Error request')
stats = await crawler.run(
[
Request.from_url('https://crawlee.dev', always_enqueue=True, user_data={'n_request': i + 1})
for i in range(total_requests)
]
)
assert len(starts_urls) == expected_starts
assert stats.requests_finished == expected_finished
def test_crawler_log() -> None:
crawler = BasicCrawler()
assert isinstance(crawler.log, logging.Logger)
crawler.log.info('Test log message')
async def test_consecutive_runs_purge_request_queue() -> None:
crawler = BasicCrawler()
visit = Mock()
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
visit(context.request.url)
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
await crawler.run(['https://a.placeholder.com', 'https://b.placeholder.com', 'https://c.placeholder.com'])
counter = Counter(args[0][0] for args in visit.call_args_list)
assert counter == {
'https://a.placeholder.com': 3,
'https://b.placeholder.com': 3,
'https://c.placeholder.com': 3,
}
@pytest.mark.skipif(os.name == 'nt' and 'CI' in os.environ, reason='Skipped in Windows CI')
@pytest.mark.parametrize(
('statistics_log_format'),
[
pytest.param('table', id='With table for logs'),
pytest.param('inline', id='With inline logs'),
],
)
async def test_logs_final_statistics(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, statistics_log_format: Literal['table', 'inline']
) -> None:
# Set the log level to INFO to capture the final statistics log.
caplog.set_level(logging.INFO)
crawler = BasicCrawler(configure_logging=False, statistics_log_format=statistics_log_format)
@crawler.router.default_handler
async def handler(context: BasicCrawlingContext) -> None:
await context.push_data({'something': 'something'})
fake_statistics = FinalStatistics(
requests_finished=4,
requests_failed=33,
retry_histogram=[1, 4, 8],
request_avg_failed_duration=timedelta(seconds=99),
request_avg_finished_duration=timedelta(milliseconds=483),
requests_finished_per_minute=0.33,
requests_failed_per_minute=0.1,
request_total_duration=timedelta(minutes=12),
requests_total=37,
crawler_runtime=timedelta(minutes=5),
)
monkeypatch.setattr(crawler._statistics, 'calculate', lambda: fake_statistics)
result = await crawler.run()
assert result is fake_statistics
final_statistics = next(
(record for record in caplog.records if record.msg.startswith('Final')),
None,
)
assert final_statistics is not None
if statistics_log_format == 'table':
assert final_statistics.msg.splitlines() == [
'Final request statistics:',
'┌───────────────────────────────┬────────────┐',