-
Notifications
You must be signed in to change notification settings - Fork 708
Expand file tree
/
Copy pathtest_sitemap_request_loader.py
More file actions
295 lines (213 loc) · 10.2 KB
/
test_sitemap_request_loader.py
File metadata and controls
295 lines (213 loc) · 10.2 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
import asyncio
import base64
import gzip
from typing import TYPE_CHECKING
from unittest.mock import patch
from yarl import URL
from crawlee import RequestOptions, RequestTransformAction
from crawlee.http_clients._base import HttpClient
from crawlee.request_loaders._sitemap_request_loader import SitemapRequestLoader
from crawlee.storages import KeyValueStore
if TYPE_CHECKING:
from crawlee._types import JsonSerializable
BASIC_SITEMAP = """
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://not-exists.com/</loc>
<lastmod>2005-02-03</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>http://not-exists.com/catalog?item=12&desc=vacation_hawaii</loc>
<changefreq>weekly</changefreq>
</url>
<url>
<loc>http://not-exists.com/catalog?item=73&desc=vacation_new_zealand</loc>
<lastmod>2004-12-23</lastmod>
<changefreq>weekly</changefreq>
</url>
<url>
<loc>http://not-exists.com/catalog?item=74&desc=vacation_newfoundland</loc>
<lastmod>2004-12-23T18:00:15+00:00</lastmod>
<priority>0.3</priority>
</url>
<url>
<loc>http://not-exists.com/catalog?item=83&desc=vacation_usa</loc>
<lastmod>2004-11-23</lastmod>
</url>
</urlset>
""".strip()
def compress_gzip(data: str) -> bytes:
"""Compress a string using gzip."""
return gzip.compress(data.encode())
def encode_base64(data: bytes) -> str:
"""Encode bytes to a base64 string."""
return base64.b64encode(data).decode('utf-8')
async def test_sitemap_traversal(server_url: URL, http_client: HttpClient) -> None:
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
sitemap_loader = SitemapRequestLoader([str(sitemap_url)], http_client=http_client)
while not await sitemap_loader.is_finished():
item = await sitemap_loader.fetch_next_request()
if item:
await sitemap_loader.mark_request_as_handled(item)
assert await sitemap_loader.is_empty()
assert await sitemap_loader.is_finished()
assert await sitemap_loader.get_total_count() == 5
assert await sitemap_loader.get_handled_count() == 5
async def test_is_empty_does_not_depend_on_fetch_next_request(server_url: URL, http_client: HttpClient) -> None:
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
sitemap_loader = SitemapRequestLoader([str(sitemap_url)], http_client=http_client)
items = []
for _ in range(5):
item = await sitemap_loader.fetch_next_request()
assert item is not None
assert not await sitemap_loader.is_finished()
items.append(item)
assert await sitemap_loader.is_empty()
assert not await sitemap_loader.is_finished()
for item in items:
await sitemap_loader.mark_request_as_handled(item)
assert await sitemap_loader.is_empty()
await asyncio.sleep(0.1)
assert await sitemap_loader.is_finished()
async def test_abort_sitemap_loading(server_url: URL, http_client: HttpClient) -> None:
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
sitemap_loader = SitemapRequestLoader([str(sitemap_url)], max_buffer_size=2, http_client=http_client)
item = await sitemap_loader.fetch_next_request()
assert item is not None
await sitemap_loader.mark_request_as_handled(item)
assert not await sitemap_loader.is_empty()
assert not await sitemap_loader.is_finished()
await sitemap_loader.abort_loading()
item = await sitemap_loader.fetch_next_request()
assert item is not None
await sitemap_loader.mark_request_as_handled(item)
assert await sitemap_loader.is_finished()
async def test_create_persist_state_for_sitemap_loading(
server_url: URL, http_client: HttpClient, key_value_store: KeyValueStore
) -> None:
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
persist_key = 'create_persist_state'
sitemap_loader = SitemapRequestLoader([str(sitemap_url)], http_client=http_client, persist_state_key=persist_key)
assert await sitemap_loader.is_finished() is False
await sitemap_loader.close()
state_data = await key_value_store.get_value(persist_key)
assert state_data is not None
assert state_data['handledCount'] == 0
async def test_data_persistence_for_sitemap_loading(
server_url: URL, http_client: HttpClient, key_value_store: KeyValueStore
) -> None:
async def wait_for_sitemap_loader_not_empty(sitemap_loader: SitemapRequestLoader) -> None:
while await sitemap_loader.is_empty() and not await sitemap_loader.is_finished(): # noqa: ASYNC110
await asyncio.sleep(0.1)
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
persist_key = 'data_persist_state'
sitemap_loader = SitemapRequestLoader([str(sitemap_url)], http_client=http_client, persist_state_key=persist_key)
# Give time to load
await asyncio.wait_for(wait_for_sitemap_loader_not_empty(sitemap_loader), timeout=10)
await sitemap_loader.close()
state_data = await key_value_store.get_value(persist_key)
assert state_data is not None
assert state_data['handledCount'] == 0
assert state_data['totalCount'] == 5
assert len(state_data['urlQueue']) == 5
async def test_recovery_data_persistence_for_sitemap_loading(
server_url: URL, http_client: HttpClient, key_value_store: KeyValueStore
) -> None:
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
persist_key = 'recovery_persist_state'
sitemap_loader = SitemapRequestLoader([str(sitemap_url)], http_client=http_client, persist_state_key=persist_key)
item = await sitemap_loader.fetch_next_request()
assert item is not None
await sitemap_loader.mark_request_as_handled(item)
await sitemap_loader.close()
state_data = await key_value_store.get_value(persist_key)
assert state_data is not None
next_item_in_kvs = state_data['urlQueue'][0]
sitemap_loader = SitemapRequestLoader([str(sitemap_url)], http_client=http_client, persist_state_key=persist_key)
item = await sitemap_loader.fetch_next_request()
assert item is not None
assert item.url == next_item_in_kvs
async def test_transform_request_function(server_url: URL, http_client: HttpClient) -> None:
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
def transform_request(request_options: RequestOptions) -> RequestOptions | RequestTransformAction:
user_data: dict[str, JsonSerializable] = {'transformed': True}
request_options['user_data'] = user_data
return request_options
sitemap_loader = SitemapRequestLoader(
[str(sitemap_url)],
http_client=http_client,
transform_request_function=transform_request,
)
extracted_urls = set()
while not await sitemap_loader.is_finished():
request = await sitemap_loader.fetch_next_request()
if request:
assert request.user_data.get('transformed') is True
extracted_urls.add(request.url)
await sitemap_loader.mark_request_as_handled(request)
assert len(extracted_urls) == 5
assert extracted_urls == {
'http://not-exists.com/',
'http://not-exists.com/catalog?item=12&desc=vacation_hawaii',
'http://not-exists.com/catalog?item=73&desc=vacation_new_zealand',
'http://not-exists.com/catalog?item=74&desc=vacation_newfoundland',
'http://not-exists.com/catalog?item=83&desc=vacation_usa',
}
async def test_transform_request_function_with_skip(server_url: URL, http_client: HttpClient) -> None:
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
def transform_request(_request_options: RequestOptions) -> RequestOptions | RequestTransformAction:
return 'skip'
sitemap_loader = SitemapRequestLoader(
[str(sitemap_url)],
http_client=http_client,
transform_request_function=transform_request,
)
while not await sitemap_loader.is_finished():
request = await sitemap_loader.fetch_next_request()
if request:
await sitemap_loader.mark_request_as_handled(request)
# Even though the sitemap had URLs, all were skipped, so the loader should be empty and finished with
# 0 handled requests.
assert await sitemap_loader.is_empty()
assert await sitemap_loader.is_finished()
assert await sitemap_loader.get_total_count() == 0
assert await sitemap_loader.get_handled_count() == 0
async def test_sitemap_loader_to_tandem(
server_url: URL,
http_client: HttpClient,
) -> None:
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
sitemap_loader = SitemapRequestLoader([str(sitemap_url)], http_client=http_client)
request_manager = await sitemap_loader.to_tandem()
while not await sitemap_loader.is_finished():
request = await request_manager.fetch_next_request()
if request:
await request_manager.mark_request_as_handled(request)
assert await sitemap_loader.is_empty()
assert await sitemap_loader.is_finished()
assert await request_manager.is_empty()
assert await request_manager.is_finished()
async def test_sitemap_loader_to_tandem_with_request_dropped(
server_url: URL,
http_client: HttpClient,
) -> None:
sitemap_url = (server_url / 'sitemap.xml').with_query(base64=encode_base64(BASIC_SITEMAP.encode()))
sitemap_loader = SitemapRequestLoader(
[str(sitemap_url)],
http_client=http_client,
)
request_manager = await sitemap_loader.to_tandem()
with patch.object(
request_manager._read_write_manager, 'add_request', side_effect=Exception('Failed to add request')
):
while not await sitemap_loader.is_finished():
request = await request_manager.fetch_next_request()
if request:
await request_manager.mark_request_as_handled(request)
assert await sitemap_loader.is_empty()
assert await sitemap_loader.is_finished()
assert await request_manager.is_empty()
assert await request_manager.is_finished()