-
Notifications
You must be signed in to change notification settings - Fork 12
/
test_extensions.py
352 lines (277 loc) · 12.8 KB
/
test_extensions.py
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
import json
import os
from tempfile import TemporaryDirectory
from unittest.mock import Mock, patch
import pytest
from scrapy.exceptions import NotConfigured
from kingfisher_scrapy.extensions import KingfisherFilesStore, KingfisherProcessAPI
from kingfisher_scrapy.items import FileError
from tests import spider_with_crawler
def spider_with_files_store(files_store, **kwargs):
spider = spider_with_crawler(**kwargs)
spider.crawler.settings['FILES_STORE'] = files_store
spider.crawler.settings['KINGFISHER_API_URI'] = 'http://httpbin.org/anything'
spider.crawler.settings['KINGFISHER_API_KEY'] = 'xxx'
return spider
def test_from_crawler():
spider = spider_with_crawler()
spider.crawler.settings['KINGFISHER_API_URI'] = 'http://httpbin.org/anything'
spider.crawler.settings['KINGFISHER_API_KEY'] = 'xxx'
spider.crawler.settings['KINGFISHER_API_LOCAL_DIRECTORY'] = 'localdir'
api_extension = KingfisherProcessAPI.from_crawler(spider.crawler)
assert api_extension.directory == 'localdir'
@pytest.mark.parametrize('api_url,api_key', [
(None, None),
('http://httpbin.org/anything', None),
(None, 'xxx'),
])
def test_from_crawler_missing_arguments(api_url, api_key):
spider = spider_with_crawler()
spider.crawler.settings['KINGFISHER_API_URI'] = api_url
spider.crawler.settings['KINGFISHER_API_KEY'] = api_key
with pytest.raises(NotConfigured) as excinfo:
KingfisherProcessAPI.from_crawler(spider.crawler)
assert str(excinfo.value) == 'KINGFISHER_API_URI and/or KINGFISHER_API_KEY is not set.'
@pytest.mark.parametrize('sample,is_sample,path', [
(None, False, os.path.join('test', '20010203_040506', 'file.json')),
('true', True, os.path.join('test_sample', '20010203_040506', 'file.json')),
])
@pytest.mark.parametrize('note', ['', 'Started by NAME.'])
@pytest.mark.parametrize('encoding,encoding2', [(None, 'utf-8'), ('iso-8859-1', 'iso-8859-1')])
@pytest.mark.parametrize('directory', [False, True])
@pytest.mark.parametrize('ok', [True, False])
@pytest.mark.parametrize('post_to_api', [True, False])
def test_item_scraped_file(sample, is_sample, path, note, encoding, encoding2, directory, ok, post_to_api, tmpdir,
caplog):
spider = spider_with_files_store(tmpdir, sample=sample, note=note)
if directory:
spider.crawler.settings['KINGFISHER_API_LOCAL_DIRECTORY'] = str(tmpdir.join('xxx'))
store_extension = KingfisherFilesStore.from_crawler(spider.crawler)
api_extension = KingfisherProcessAPI.from_crawler(spider.crawler)
kwargs = {}
if encoding:
kwargs['encoding'] = encoding
item = spider.build_file(b'{"key": "value"}', 'file.json', url='https://example.com/remote.json',
data_type='release_package', post_to_api=post_to_api, **kwargs)
store_extension.item_scraped(item, spider)
with patch('requests.post') as mocked:
response = Mock()
response.ok = ok
response.status_code = 400
mocked.return_value = response
api_extension.item_scraped(item, spider)
if not ok:
if not post_to_api:
assert len(caplog.records) == 0
else:
message = 'Failed to post [https://example.com/remote.json]. API status code: 400'
assert len(caplog.records) == 1
assert caplog.records[0].name == 'test'
assert caplog.records[0].levelname == 'WARNING'
assert caplog.records[0].message == message
expected = {
'collection_source': 'test',
'collection_data_version': '2001-02-03 04:05:06',
'collection_sample': is_sample,
'file_name': 'file.json',
'url': 'https://example.com/remote.json',
# Specific to this test case.
'data_type': 'release_package',
'encoding': encoding2,
}
if note:
expected['collection_note'] = note
if directory:
expected['local_file_name'] = tmpdir.join('xxx', path)
if not post_to_api:
assert mocked.call_count == 0
else:
with open(tmpdir.join(path), 'rb') as f:
assert mocked.call_count == 1
assert mocked.call_args[0] == ('http://httpbin.org/anything/api/v1/submit/file/',)
assert mocked.call_args[1]['headers'] == {'Authorization': 'ApiKey xxx'}
assert mocked.call_args[1]['data'] == expected
assert len(mocked.call_args[1]) == 3
if directory:
assert mocked.call_args[1]['files'] == {}
else:
assert len(mocked.call_args[1]['files']) == 1
assert len(mocked.call_args[1]['files']['file']) == 3
assert mocked.call_args[1]['files']['file'][0] == 'file.json'
assert mocked.call_args[1]['files']['file'][1].read() == f.read()
assert mocked.call_args[1]['files']['file'][2] == 'application/json'
@pytest.mark.parametrize('sample,is_sample', [(None, False), ('true', True)])
@pytest.mark.parametrize('note', ['', 'Started by NAME.'])
@pytest.mark.parametrize('encoding,encoding2', [(None, 'utf-8'), ('iso-8859-1', 'iso-8859-1')])
@pytest.mark.parametrize('ok', [True, False])
def test_item_scraped_file_item(sample, is_sample, note, encoding, encoding2, ok, tmpdir, caplog):
spider = spider_with_files_store(tmpdir, sample=sample, note=note)
api_extension = KingfisherProcessAPI.from_crawler(spider.crawler)
with patch('requests.post') as mocked:
response = Mock()
response.ok = ok
response.status_code = 400
mocked.return_value = response
kwargs = {}
if encoding:
kwargs['encoding'] = encoding
item = spider.build_file_item(
1,
b'{"key": "value"}',
data_type='release_package',
url='https://example.com/remote.json',
encoding=encoding2,
file_name='data.json',
)
api_extension.item_scraped(item, spider)
if not ok:
message = 'Failed to post [https://example.com/remote.json]. API status code: 400'
assert len(caplog.records) == 1
assert caplog.records[0].name == 'test'
assert caplog.records[0].levelname == 'WARNING'
assert caplog.records[0].message == message
expected = {
'collection_source': 'test',
'collection_data_version': '2001-02-03 04:05:06',
'collection_sample': is_sample,
'file_name': 'data.json',
'url': 'https://example.com/remote.json',
# Specific to this test case.
'data_type': 'release_package',
'encoding': encoding2,
'number': 1,
'data': b'{"key": "value"}',
}
if note:
expected['collection_note'] = note
mocked.assert_called_once_with(
'http://httpbin.org/anything/api/v1/submit/item/',
headers={
'Authorization': 'ApiKey xxx',
},
data=expected,
)
@pytest.mark.parametrize('sample,is_sample', [(None, False), ('true', True)])
@pytest.mark.parametrize('ok', [True, False])
def test_item_scraped_file_error(sample, is_sample, ok, tmpdir, caplog):
spider = spider_with_files_store(tmpdir, sample=sample)
api_extension = KingfisherProcessAPI.from_crawler(spider.crawler)
with patch('requests.post') as mocked:
response = Mock()
response.ok = ok
response.status_code = 400
mocked.return_value = response
data = FileError({
'file_name': 'file.json',
'url': 'https://example.com/remote.json',
'errors': {'http_code': 500},
})
api_extension.item_scraped(data, spider)
if not ok:
message = 'Failed to post [https://example.com/remote.json]. File Errors API status code: 400'
assert len(caplog.records) == 1
assert caplog.records[0].name == 'test'
assert caplog.records[0].levelname == 'WARNING'
assert caplog.records[0].message == message
expected = {
'collection_source': 'test',
'collection_data_version': '2001-02-03 04:05:06',
'collection_sample': is_sample,
'file_name': 'file.json',
'url': 'https://example.com/remote.json',
# Specific to this test case.
'errors': '{"http_code": 500}',
}
mocked.assert_called_once_with(
'http://httpbin.org/anything/api/v1/submit/file_errors/',
headers={
'Authorization': 'ApiKey xxx',
},
data=expected,
)
@pytest.mark.parametrize('sample,is_sample', [(None, False), ('true', True)])
@pytest.mark.parametrize('ok', [True, False])
def test_spider_closed(sample, is_sample, ok, tmpdir, caplog):
spider = spider_with_files_store(tmpdir, sample=sample)
api_extension = KingfisherProcessAPI.from_crawler(spider.crawler)
with patch('requests.post') as mocked:
response = Mock()
response.ok = ok
response.status_code = 400
mocked.return_value = response
api_extension.spider_closed(spider, 'finished')
mocked.assert_called_once_with(
'http://httpbin.org/anything/api/v1/submit/end_collection_store/',
headers={
'Authorization': 'ApiKey xxx',
},
data={
'collection_source': 'test',
'collection_data_version': '2001-02-03 04:05:06',
'collection_sample': is_sample,
},
)
if not ok:
assert len(caplog.records) == 1
assert caplog.records[0].name == 'test'
assert caplog.records[0].levelname == 'WARNING'
assert caplog.records[0].message == 'Failed to post End Collection Store. API status code: 400'
def test_spider_closed_other_reason(tmpdir):
spider = spider_with_files_store(tmpdir)
api_extension = KingfisherProcessAPI.from_crawler(spider.crawler)
with patch('requests.post') as mocked:
api_extension.spider_closed(spider, 'xxx')
mocked.assert_not_called()
@pytest.mark.parametrize('sample,path', [
(None, os.path.join('test', '20010203_040506', 'file.json')),
('true', os.path.join('test_sample', '20010203_040506', 'file.json')),
])
def test_item_scraped_with_build_file_from_response(sample, path, tmpdir):
spider = spider_with_files_store(tmpdir, sample=sample)
store_extension = KingfisherFilesStore.from_crawler(spider.crawler)
response = Mock()
response.body = b'{"key": "value"}'
response.request = Mock()
response.request.url = 'https://example.com/remote.json'
item = spider.build_file_from_response(response, 'file.json', data_type='release_package', encoding='iso-8859-1')
store_extension.item_scraped(item, spider)
with open(tmpdir.join(path)) as f:
assert f.read() == '{"key": "value"}'
with open(tmpdir.join(path + '.fileinfo')) as f:
assert json.load(f) == {
'url': 'https://example.com/remote.json',
'data_type': 'release_package',
'encoding': 'iso-8859-1',
}
assert item['path'] == path
assert item['files_store'] == tmpdir
@pytest.mark.parametrize('sample,path', [
(None, os.path.join('test', '20010203_040506', 'file.json')),
('true', os.path.join('test_sample', '20010203_040506', 'file.json')),
])
def test_item_scraped_with_build_file(sample, path, tmpdir):
spider = spider_with_files_store(tmpdir, sample=sample)
store_extension = KingfisherFilesStore.from_crawler(spider.crawler)
data = b'{"key": "value"}'
url = 'https://example.com/remote.json'
item = spider.build_file(data, 'file.json', url=url, data_type='release_package', encoding='iso-8859-1')
store_extension.item_scraped(item, spider)
with open(tmpdir.join(path)) as f:
assert f.read() == '{"key": "value"}'
with open(tmpdir.join(path + '.fileinfo')) as f:
assert json.load(f) == {
'url': 'https://example.com/remote.json',
'data_type': 'release_package',
'encoding': 'iso-8859-1',
}
assert item['path'] == path
assert item['files_store'] == tmpdir
def test_build_file_with_existing_directory():
spider = spider_with_crawler()
with TemporaryDirectory() as tmpdirname:
files_store = os.path.join(tmpdirname, 'data')
spider.crawler.settings['FILES_STORE'] = files_store
store_extension = KingfisherFilesStore.from_crawler(spider.crawler)
os.makedirs(os.path.join(files_store, 'test', '20010203_040506'))
# No FileExistsError exception.
store_extension.item_scraped(spider.build_file(b'{"key": "value"}', 'file.json'), spider)