forked from chaoss/grimoirelab-perceval
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest_archive.py
520 lines (407 loc) · 18.3 KB
/
test_archive.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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2020 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
# Valerio Cosentino <[email protected]>
# Santiago Dueñas <[email protected]>
# Miguel Ángel Fernández <[email protected]>
# Jesus M. Gonzalez-Barahona <[email protected]>
#
import os
import pickle
import shutil
import sqlite3
import tempfile
import unittest
import unittest.mock
import httpretty
import requests
from grimoirelab_toolkit.datetime import datetime_utcnow, datetime_to_utc
from perceval.archive import Archive, ArchiveManager
from perceval.errors import ArchiveError, ArchiveManagerError
def count_number_rows(db, table_name):
conn = sqlite3.connect(db)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM " + table_name)
nrows = cursor.fetchone()[0]
cursor.close()
return nrows
class TestArchive(unittest.TestCase):
"""Archive tests"""
def setUp(self):
self.test_path = tempfile.mkdtemp(prefix='perceval_')
def tearDown(self):
shutil.rmtree(self.test_path)
def test_create(self):
"""Test a new an empty archive is created"""
archive_path = os.path.join(self.test_path, 'myarchive')
archive = Archive.create(archive_path)
# Archive file was created
self.assertEqual(archive.archive_path, archive_path)
self.assertEqual(os.path.exists(archive.archive_path), True)
# Properties are initialized
self.assertEqual(archive.created_on, None)
self.assertEqual(archive.origin, None)
self.assertEqual(archive.backend_name, None)
self.assertEqual(archive.backend_version, None)
self.assertEqual(archive.category, None)
self.assertEqual(archive.backend_params, None)
# Tables are empty
nrows = count_number_rows(archive_path, Archive.ARCHIVE_TABLE)
self.assertEqual(nrows, 0)
nrows = count_number_rows(archive_path, Archive.METADATA_TABLE)
self.assertEqual(nrows, 0)
def test_create_existing_archive(self):
"""Test if create method fails when the given archive path already exists"""
archive_path = os.path.join(self.test_path, 'myarchive')
Archive.create(archive_path)
with self.assertRaisesRegex(ArchiveError, "archive %s already exists" % archive_path):
Archive.create(archive_path)
def test_init(self):
"""Test whether an archive is propertly initialized"""
archive_path = os.path.join(self.test_path, 'myarchive')
_ = Archive.create(archive_path)
archive = Archive(archive_path)
self.assertEqual(archive.archive_path, archive_path)
self.assertEqual(archive.created_on, None)
self.assertEqual(archive.origin, None)
self.assertEqual(archive.backend_name, None)
self.assertEqual(archive.backend_version, None)
self.assertEqual(archive.category, None)
self.assertEqual(archive.backend_params, None)
def test_init_not_existing_archive(self):
"""Test if an exception is raised when the given archive does not exist"""
archive_path = os.path.join(self.test_path, 'myarchive')
with self.assertRaisesRegex(ArchiveError, "archive %s does not exist" % archive_path):
_ = Archive(archive_path)
def test_init_not_valid_archive(self):
"""Test if an exception is raised when the file is an invalid archive"""
archive_path = os.path.join(self.test_path, 'invalid_archive')
with open(archive_path, 'w') as fd:
fd.write("Invalid archive file")
with self.assertRaisesRegex(ArchiveError, "invalid archive file"):
_ = Archive(archive_path)
def test_init_metadata(self):
"""Test whether metadata information is properly initialized"""
archive_path = os.path.join(self.test_path, 'myarchive')
archive = Archive.create(archive_path)
before_dt = datetime_to_utc(datetime_utcnow())
archive.init_metadata('marvel.com', 'marvel-comics-backend', '0.1.0',
'issue', {'from_date': before_dt})
after_dt = datetime_to_utc(datetime_utcnow())
archive_copy = Archive(archive_path)
# Both copies should have the same parameters
for arch in [archive, archive_copy]:
self.assertEqual(arch.origin, 'marvel.com')
self.assertEqual(arch.backend_name, 'marvel-comics-backend')
self.assertEqual(arch.backend_version, '0.1.0')
self.assertEqual(arch.category, 'issue')
self.assertGreaterEqual(arch.created_on, before_dt)
self.assertLessEqual(arch.created_on, after_dt)
self.assertDictEqual(arch.backend_params, {'from_date': before_dt})
@httpretty.activate
def test_store(self):
"""Test whether data is properly stored in the archive"""
data_requests = [
("https://example.com/", {'q': 'issues', 'date': '2017-01-10'}, {}),
("https://example.com/", {'q': 'issues', 'date': '2018-01-01'}, {}),
("https://example.com/tasks", {'task_id': 10}, {'Accept': 'application/json'}),
]
httpretty.register_uri(httpretty.GET,
"https://example.com/",
body='{"hey": "there"}',
status=200)
httpretty.register_uri(httpretty.GET,
"https://example.com/tasks",
body='{"task": "my task"}',
status=200)
archive_path = os.path.join(self.test_path, 'myarchive')
archive = Archive.create(archive_path)
# Store data in the archive
responses = []
for dr in data_requests:
response = requests.get(dr[0], params=dr[1], headers=dr[2])
archive.store(dr[0], dr[1], dr[2], response)
responses.append(response)
db = sqlite3.connect(archive.archive_path)
cursor = db.cursor()
cursor.execute("SELECT hashcode, data, uri, payload, headers FROM archive")
data_stored = cursor.fetchall()
cursor.close()
self.assertEqual(len(data_stored), len(data_requests))
ds = data_stored[0]
dr = data_requests[0]
self.assertEqual(ds[0], '0fa4ce047340780f08efca92f22027514263521d')
self.assertEqual(pickle.loads(ds[1]).url, responses[0].url)
self.assertEqual(ds[2], dr[0])
self.assertEqual(pickle.loads(ds[3]), dr[1])
self.assertEqual(pickle.loads(ds[4]), dr[2])
ds = data_stored[1]
dr = data_requests[1]
self.assertEqual(ds[0], '3879a6f12828b7ac3a88b7167333e86168f2f5d2')
self.assertEqual(pickle.loads(ds[1]).url, responses[1].url)
self.assertEqual(ds[2], dr[0])
self.assertEqual(pickle.loads(ds[3]), dr[1])
self.assertEqual(pickle.loads(ds[4]), dr[2])
ds = data_stored[2]
dr = data_requests[2]
self.assertEqual(ds[0], 'ef38f574a0745b63a056e7befdb7a06e7cf1549b')
self.assertEqual(pickle.loads(ds[1]).url, responses[2].url)
self.assertEqual(ds[2], dr[0])
self.assertEqual(pickle.loads(ds[3]), dr[1])
self.assertEqual(pickle.loads(ds[4]), dr[2])
@httpretty.activate
def test_store_duplicate(self):
"""Test whether the insertion of duplicated data throws an error"""
url = "https://example.com/tasks"
payload = {'task_id': 10}
headers = {'Accept': 'application/json'}
httpretty.register_uri(httpretty.GET,
url,
body='{"hey": "there"}',
status=200)
response = requests.get(url, params=payload, headers=headers)
archive_path = os.path.join(self.test_path, 'myarchive')
archive = Archive.create(archive_path)
archive.store(url, payload, headers, response)
# check the unique index filters duplicated API calls
with self.assertRaisesRegex(ArchiveError, "duplicated entry"):
archive.store(url, payload, headers, response)
@httpretty.activate
def test_retrieve(self):
"""Test whether data is properly retrieved from the archive"""
url = "https://example.com/tasks"
payload = {'task_id': 10}
headers = {'Accept': 'application/json'}
httpretty.register_uri(httpretty.GET,
url,
body='{"hey": "there"}',
status=200)
response = requests.get(url, params=payload, headers=headers)
archive_path = os.path.join(self.test_path, 'myarchive')
archive = Archive.create(archive_path)
archive.store(url, payload, headers, response)
data = archive.retrieve(url, payload, headers)
self.assertEqual(data.url, response.url)
def test_retrieve_missing(self):
"""Test whether the retrieval of non archived data throws an error
In the exceptional case of a failure in retrieving data from an archive (e.g., manual modification),
an exception is thrown to stop the retrieval from the archive
"""
archive_path = os.path.join(self.test_path, 'myarchive')
archive = Archive.create(archive_path)
with self.assertRaisesRegex(ArchiveError, "not found in archive"):
_ = archive.retrieve("http://wrong", payload={}, headers={})
ARCHIVE_TEST_DIR = 'archivedir'
class MockUUID:
def __init__(self, uuid):
self.hex = uuid
class TestArchiveManager(unittest.TestCase):
"""Archive Manager tests"""
def setUp(self):
self.test_path = tempfile.mkdtemp(prefix='perceval_')
def tearDown(self):
shutil.rmtree(self.test_path)
def test_struct(self):
"""Test whether the structure of an archive manager directory is created"""
archive_mng_path = os.path.join(self.test_path, ARCHIVE_TEST_DIR)
# Directory does not exist yet
self.assertEqual(os.path.isdir(archive_mng_path), False)
# Object and directory are created
manager = ArchiveManager(archive_mng_path)
self.assertEqual(manager.dirpath, archive_mng_path)
self.assertEqual(os.path.isdir(archive_mng_path), True)
# A new object using the same directory does not create
# a new directory
alt_manager = ArchiveManager(archive_mng_path)
self.assertEqual(alt_manager.dirpath, archive_mng_path)
self.assertEqual(os.path.isdir(archive_mng_path), True)
@unittest.mock.patch('uuid.uuid4')
def test_create_archive(self, mock_uuid):
"""Test if a new archive is created"""
mock_uuid.return_value = MockUUID('AB0123456789')
archive_mng_path = os.path.join(self.test_path, ARCHIVE_TEST_DIR)
manager = ArchiveManager(archive_mng_path)
archive = manager.create_archive()
self.assertIsInstance(archive, Archive)
expected = os.path.join(archive_mng_path, 'AB', '0123456789.sqlite3')
self.assertEqual(archive.archive_path, expected)
self.assertEqual(os.path.exists(archive.archive_path), True)
@unittest.mock.patch('uuid.uuid4')
def test_create_existing_archive(self, mock_uuid):
"""Test if an exception is raised when the archive to create exists"""
mock_uuid.return_value = MockUUID('AB0123456789')
archive_mng_path = os.path.join(self.test_path, ARCHIVE_TEST_DIR)
manager = ArchiveManager(archive_mng_path)
# First we create the archive
archive = manager.create_archive()
self.assertIsInstance(archive, Archive)
expected = os.path.join(archive_mng_path, 'AB', '0123456789.sqlite3')
self.assertEqual(archive.archive_path, expected)
# The archive already exist so it must raise an exception
with self.assertRaisesRegex(ArchiveManagerError, 'archive .+ already exists'):
_ = manager.create_archive()
def test_remove_archive(self):
"""Test if an archive is removed by the archive manager"""
archive_mng_path = os.path.join(self.test_path, ARCHIVE_TEST_DIR)
manager = ArchiveManager(archive_mng_path)
archive = manager.create_archive()
self.assertEqual(os.path.exists(archive.archive_path), True)
manager.remove_archive(archive.archive_path)
self.assertEqual(os.path.exists(archive.archive_path), False)
def test_remove_archive_not_found(self):
"""Test if an exception is raised when the archive is not found"""
archive_mng_path = os.path.join(self.test_path, ARCHIVE_TEST_DIR)
manager = ArchiveManager(archive_mng_path)
with self.assertRaisesRegex(ArchiveManagerError, 'archive mockarchive does not exist'):
manager.remove_archive('mockarchive')
def test_search(self):
"""Test if a set of archives is found based on the given criteria"""
archive_mng_path = os.path.join(self.test_path, ARCHIVE_TEST_DIR)
manager = ArchiveManager(archive_mng_path)
dt = datetime_utcnow()
metadata = [
{
'origin': 'https://example.com',
'backend_name': 'git',
'backend_version': '0.8',
'category': 'commit',
'backend_params': {},
},
{
'origin': 'https://example.com',
'backend_name': 'gerrit',
'backend_version': '0.1',
'category': 'changes',
'backend_params': {}
},
{
'origin': 'https://example.org',
'backend_name': 'git',
'backend_version': '0.1',
'category': 'commit',
'backend_params': {}
},
{
'origin': 'https://example.com',
'backend_name': 'git',
'backend_version': '0.1',
'category': 'commit',
'backend_params': {}
}
]
for meta in metadata:
archive = manager.create_archive()
archive.init_metadata(**meta)
meta['filepath'] = archive.archive_path
archives = manager.search('https://example.com', 'git', 'commit', dt)
expected = [metadata[0]['filepath'], metadata[3]['filepath']]
self.assertListEqual(archives, expected)
def test_search_archived_after(self):
"""Check if a set of archives created after a given date are searched"""
archive_mng_path = os.path.join(self.test_path, ARCHIVE_TEST_DIR)
manager = ArchiveManager(archive_mng_path)
# First set of archives to create
metadata = [
{
'origin': 'https://example.com',
'backend_name': 'git',
'backend_version': '0.8',
'category': 'commit',
'backend_params': {},
},
{
'origin': 'https://example.com',
'backend_name': 'gerrit',
'backend_version': '0.1',
'category': 'changes',
'backend_params': {}
},
]
for meta in metadata:
archive = manager.create_archive()
archive.init_metadata(**meta)
# Second set, archived after the date we'll use to search
after_dt = datetime_utcnow()
metadata = [
{
'origin': 'https://example.org',
'backend_name': 'git',
'backend_version': '0.1',
'category': 'commit',
'backend_params': {}
},
{
'origin': 'https://example.com',
'backend_name': 'git',
'backend_version': '0.1',
'category': 'commit',
'backend_params': {}
}
]
for meta in metadata:
archive = manager.create_archive()
archive.init_metadata(**meta)
meta['filepath'] = archive.archive_path
archives = manager.search('https://example.com', 'git', 'commit',
after_dt)
expected = [metadata[1]['filepath']]
self.assertListEqual(archives, expected)
def test_search_no_match(self):
"""Check if an empty set of archives is returned when none match the criteria"""
archive_mng_path = os.path.join(self.test_path, ARCHIVE_TEST_DIR)
manager = ArchiveManager(archive_mng_path)
dt = datetime_utcnow()
metadata = [
{
'origin': 'https://example.com',
'backend_name': 'git',
'backend_version': '0.8',
'category': 'commit',
'backend_params': {},
},
{
'origin': 'https://example.com',
'backend_name': 'gerrit',
'backend_version': '0.1',
'category': 'changes',
'backend_params': {}
},
{
'origin': 'https://example.org',
'backend_name': 'git',
'backend_version': '0.1',
'category': 'commit',
'backend_params': {}
},
{
'origin': 'https://example.com',
'backend_name': 'git',
'backend_version': '0.1',
'category': 'commit',
'backend_params': {}
}
]
for meta in metadata:
archive = manager.create_archive()
archive.init_metadata(**meta)
meta['filepath'] = archive.archive_path
archives = manager.search('https://example.com', 'bugzilla', 'commit', dt)
self.assertListEqual(archives, [])
if __name__ == "__main__":
unittest.main()