File: importer_service_test.py

package info (click to toggle)
git-ubuntu 1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,688 kB
  • sloc: python: 13,378; sh: 480; makefile: 2
file content (493 lines) | stat: -rw-r--r-- 17,288 bytes parent folder | download
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
import datetime
import os
import sqlite3
import unittest.mock
from unittest.mock import Mock

import pytest

from gitubuntu.importer_service import ImportRequest
import gitubuntu.importer_service as target


# Shortcuts for accessing some enumeration values
REIMPORT = target.ImportRequest.Level.REIMPORT
INCREMENTAL = target.ImportRequest.Level.INCREMENTAL


@pytest.fixture
def state():
    return target.State(':memory:')


def inject_import_request(state, timestamp, reimport, status='needed'):
    """Inject a request into a state instance's database

    Since we haven't implemented requesting reimport via the API, this function
    allows us to do that for test purposes. It also supports incremental
    imports so that we can unify the two cases for easier test parametrization.

    :param target.State state: the state instance
    :param timestamp: the timestamp of the request. This may be a float or an
        integer.
    :param bool reimport: if True, this is a reimport request; False means an
        incremental import.
    :returns: None
    """
    cursor = state.db.cursor()
    cursor.execute(
        '''INSERT INTO request
            (srcpkg, timestamp, status, priority, reimport)
            VALUES ('a', ?, ?, 20, ?)''',
        (timestamp, status, bool(reimport))
    )
    # No need to commit for our tests in general


def test_can_instantiate_state():
    target.State(':memory:')


def test_state_persists(tmpdir):
    state_path = os.path.join(tmpdir, 'db')
    state = target.State(state_path)
    state._write_timestamps({
        'debian': target.Timestamp(time=4, link=None),
        'ubuntu': target.Timestamp(time=4, link=None),
    })
    state = target.State(state_path)
    assert state.read_timestamps(0)['debian'].time == 4


def test_default_timestamp(state):
    assert all([
        state.read_timestamps(2, current_time=1000000)[distro].time == 827200
        for distro in ['debian', 'ubuntu']
    ])


def test_empty_dump_request(state):
    assert state._dump_request() == set()


def test_request_imports(state):
    state.request_imports(['a'], request_time=1)
    assert state._dump_request() == set([('a', 1, 'needed', 20, 0)])


def test_request_imports_updates_timestamps(state):
    timestamps = {
        'debian': target.Timestamp(time=1, link=None),
        'ubuntu': target.Timestamp(time=2, link=None),
    }
    state.request_imports(
        ['a'],
        request_time=1,
        timestamps=timestamps,
    )
    assert state.read_timestamps() == timestamps


@pytest.mark.parametrize(['request_list', 'expected_result'], [
    # incremental import -> request one incremental import
    ([(0, 'needed')], [ImportRequest('a', INCREMENTAL)]),
    # reimport -> request one reimport
    ([(1, 'needed')], [ImportRequest('a', REIMPORT)]),
    # incremental then reimport -> request the reimport
    ([(0, 'needed'), (1, 'needed')], [ImportRequest('a', REIMPORT)]),
    # reimport then incremental -> request the reimport
    ([(1, 'needed'), (0, 'needed')], [ImportRequest('a', REIMPORT)]),
    # incremental already running then reimport -> nothing
    ([(0, 'running'), (1, 'needed')], []),
    # reimport already running then incremental -> nothing
    ([(0, 'needed'), (1, 'running')], []),
])
def test_get_pending_imports(state, request_list, expected_result):
    """State.get_pending_imports() should behave correctly

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    :param list(tuple(int, str)) request_list: for each monotonic pretend clock
        tick, whether a request at that time is for a reimport or an
        incremental import and the status of the request. 0 means incremental;
        1 means reimport, as mapped to the database reimport column. The status
        is mapped directly to the database status column.
    :param ImportRequest expected_result: the expected sole entry of the
        returned list of the get_pending_imports() method.
    """
    for timestamp, (reimport, needed) in enumerate(request_list):
        inject_import_request(state, timestamp, reimport, needed)
    state._normalize(state.db)
    assert list(state.get_pending_imports()) == expected_result


def test_completed_request_removed_successfully(state):
    """A completed request should be removed from the database

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    state.request_imports(['a', 'b'], request_time=1)
    state.mark_import_outcomes(
        reckoning_time=2,
        completed_requests=[ImportRequest('a', INCREMENTAL)],
        failed_requests=[],
    )
    assert state._dump_request() == set([
        ('b', 1.0, 'needed', 20, 0),
    ])
    state._normalize(state.db, assert_no_action=True)


@pytest.mark.parametrize([
        'request_list',
        'reckoning_time',
        'level',
        'expected_result',
], [
    ([0, 1], 1, REIMPORT, {('a', 1.0, 'needed', 20, 1)}),
    ([0, 1], 2, REIMPORT, set()),
    ([1, 0], 1, REIMPORT, {('a', 1.0, 'needed', 20, 0)}),
    ([1, 0], 2, REIMPORT, set()),
    ([0, 1], 1, INCREMENTAL, {('a', 1.0, 'needed', 20, 1)}),
    ([0, 1], 2, INCREMENTAL, {('a', 1.0, 'needed', 20, 1)}),
    ([1, 0], 1, INCREMENTAL, {
        ('a', 0.0, 'needed', 20, 1),
        ('a', 1.0, 'needed', 20, 0),
    }),
    ([1, 0], 2, INCREMENTAL, {('a', 0.0, 'needed', 20, 1)}),
])
def test_correct_request_gets_marked_complete(
    state,
    request_list,
    reckoning_time,
    level,
    expected_result,
):
    """The correct request should get marked complete

    Regardless of reimport/incremental import and timing inputs, the correct
    request should get marked complete on a call to the mark_import_outcomes()
    method.

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    :param list(int) request_list: for each monotonic pretend clock tick,
        whether a request at that time is for a reimport or an incremental
        import. 0 means incremental; 1 means reimport, as mapped to the
        database reimport column.
    :param reckoning_time: pass through to the call to mark_import_outcomes().
    :param Level level: pass through to the ImportRequest constructor for the
        single successful request that will be passed to
        mark_import_outcomes().
    :param set expected_result: the expected return value of the
        _dump_request() method.
    """
    for request in enumerate(request_list):
        inject_import_request(state, *request)
    state._normalize(state.db)

    state.mark_import_outcomes(reckoning_time, [ImportRequest('a', level)], [])
    assert state._dump_request() == expected_result


def test_failed_request_marked_correctly(state):
    """
    A failed request should get marked as errored

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    state.request_imports(['a', 'b'], request_time=1)
    state.mark_import_outcomes(2, [], [ImportRequest('a', INCREMENTAL)])
    assert state._dump_request() == set([
        ('a', 1.0, 'error', 20, 0),
        ('b', 1.0, 'needed', 20, 0),
    ])


def test_request_gets_marked_running(state):
    """
    A request marked as running should get updated in the database accordingly

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    state.request_imports(['a', 'b'], request_time=1)
    state.mark_running([ImportRequest('a', INCREMENTAL)])
    assert state._dump_request() == set([
        ('a', 1.0, 'running', 20, 0),
        ('b', 1.0, 'needed', 20, 0),
    ])


@pytest.mark.parametrize(['level'], [(INCREMENTAL,), (REIMPORT,)])
def test_correct_request_gets_marked_running(state, level):
    """
    The correct request should get marked running

    Regardless of incremental/reimport import inputs, the correct request
    should get marked running on a call to the mark_running() method.

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    :param Level level: which of the two requests we are marking as running.
    """
    # Using this ordering, nothing gets superseded during normalization, so
    # this test can effectively check that the correct entry was marked running
    # because both entries will still exist in both cases.
    for request in enumerate([1, 0]):
        inject_import_request(state, *request)
    state._normalize(state.db)
    state.mark_running([ImportRequest('a', level)])
    assert state._dump_request() == set([
        ('a', float(not level.value), 'running', 20, level.value),
        ('a', float(level.value), 'needed', 20, int(not level.value)),
    ])


def test_normalize_superseding(state):
    state.request_imports(['a', 'b'], request_time=1)
    state.request_imports(['a'], request_time=2)
    assert state._dump_request() == set([
        ('a', 2.0, 'needed', 20, 0),
        ('b', 1.0, 'needed', 20, 0),
    ])
    state._normalize(state.db, assert_no_action=True)


def test_superseding_with_running(state):
    state.request_imports(['a'], request_time=1)
    state.mark_running([ImportRequest('a', INCREMENTAL)])
    state.request_imports(['a'], request_time=2)
    assert state._dump_request() == set([
        ('a', 2.0, 'needed', 20, 0),
        ('a', 1.0, 'running', 20, 0),
    ])


@pytest.mark.parametrize(['request_list', 'expected_result'], [
    (
        # incremental followed by incremental: first incremental gets
        # superseded
        [0, 0],
        [
            ('a', 0.0, 'superseded', 20, 0),
            ('a', 1.0, 'needed', 20, 0),
        ]
    ),
    (
        # reimport followed by reimport: first reimport gets superseded
        [1, 1],
        [
            ('a', 0.0, 'superseded', 20, 1),
            ('a', 1.0, 'needed', 20, 1),
        ]
    ),
    (
        # incremental followed by reimport: incremental gets superseded
        [0, 1],
        [
            ('a', 0.0, 'superseded', 20, 0),
            ('a', 1.0, 'needed', 20, 1),
        ]
    ),
    (
        # reimport followed by incremental: nothing gets superseded
        [1, 0],
        [
            ('a', 0.0, 'needed', 20, 1),
            ('a', 1.0, 'needed', 20, 0),
        ]
    ),
])
def test_superseding_with_reimports(state, request_list, expected_result):
    """Superseding should correctly collapse requests

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    :param list(int) request_list: for each monotonic pretend clock tick,
        whether a request at that time is for a reimport or an incremental
        import. 0 means incremental; 1 means reimport, as mapped to the
        database reimport column.
    :param set expected_result: the expected return value of the
        _dump_request() method.
    """
    for request in enumerate(request_list):
        inject_import_request(state, *request)
    state._mark_superseded(state.db)
    assert state._dump_request() == set(expected_result)


def test_unmark_running(state):
    """unmark_running() should correctly update database state

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    state.request_imports(['a', 'b'], request_time=1)
    state.mark_running([ImportRequest('a', INCREMENTAL)])
    state.unmark_running()
    state._normalize(state.db, assert_no_action=True)
    assert state._dump_request() == set([
        ('a', 1.0, 'error', 20, 0),
        ('b', 1.0, 'needed', 20, 0),
    ])


def test_ensure_reimport_column_when_missing():
    """The reimport column should get added when not present"""
    db = sqlite3.connect(':memory:')
    db.cursor().execute('CREATE TABLE request (foo INTEGER NOT NULL)')
    target.State._ensure_reimport_column(db)
    cursor = db.cursor()
    cursor.execute('SELECT * FROM request')
    # The second column should have a name of 'reimport' now. See
    # https://www.python.org/dev/peps/pep-0249/#description
    assert cursor.description[1][0] == 'reimport'


def test_ensure_reimport_column_when_present():
    """The reimport column should not get added when already present"""
    db = sqlite3.connect(':memory:')
    db.cursor().execute('CREATE TABLE request (reimport INTEGER NOT NULL)')
    target.State._ensure_reimport_column(db)
    cursor = db.cursor()
    cursor.execute('SELECT * FROM request')
    # There should still only be one column
    # https://www.python.org/dev/peps/pep-0249/#description
    assert len(cursor.description) == 1


def test_empty_dump_ipc_worker(state):
    """_dump_ipc_worker() should return an empty set when the table is empty"""
    assert state._dump_ipc_worker() == set()


def test_assign_ipc_worker(state):
    """assign_ipc_worker() should update the request and ipc_worker tables

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    inject_import_request(state, 1, False)
    state.assign_ipc_worker('worker1', ImportRequest('a', INCREMENTAL), 1)
    assert state._dump_request() == {('a', 1.0, 'running', 20, 0)}
    assert state._dump_ipc_worker() == {('worker1', 'a', 0, 1)}


def test_lookup_ipc_worker(state):
    """lookup_ipc_worker() should return details of an assigned worker

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    inject_import_request(state, 1, False)
    state.assign_ipc_worker('worker1', ImportRequest('a', INCREMENTAL), 1)
    state.lookup_ipc_worker('worker1') == ('a', INCREMENTAL, 1)


def test_clear_ipc_worker(state):
    """clear_ipc_worker() should correctly update tables in the normal case

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    inject_import_request(state, 0, False)
    request = ImportRequest('a', INCREMENTAL)
    state.assign_ipc_worker('worker1', request, 1)
    state.mark_import_outcomes(1, [request], [])
    state.clear_ipc_worker('worker1')
    assert state._dump_request() == set()
    assert state._dump_ipc_worker() == set()


def test_clear_ipc_worker_when_not_assigned(state):
    """clear_ipc_worker() should do nothing if a worker isn't assigned

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    state.clear_ipc_worker('worker1')
    assert state._dump_ipc_worker() == set()


def test_clear_ipc_worker_that_never_finished(state):
    """clear_ipc_worker() should mark a request as errored if it isn't done

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    inject_import_request(state, 0, False)
    request = ImportRequest('a', INCREMENTAL)
    state.assign_ipc_worker('worker1', request, 1)
    state.clear_ipc_worker('worker1')
    assert state._dump_request() == {('a', 0.0, 'error', 20, 0)}
    assert state._dump_ipc_worker() == set()


def mock_call_request_new_imports(
    state,
    filter_func,
):
    """Helper to make a mock call to request_new_imports()

    request_new_imports() will be called a single mock publication in Ubuntu
    appearing at time 1 called test-package.

    :param target.State state: must be passed in by the caller: the "state"
        pytest fixture that provides a target.State instance to test.
    :param filter_func: parameter to pass through to the request_new_imports()
        call.
    :returns: None
    """
    lp = Mock(distributions={
        'debian': Mock(
            main_archive=Mock(getPublishedSources=Mock(return_value=[])),
        ),
        'ubuntu': Mock(main_archive=Mock(getPublishedSources=Mock(
            return_value=[
                Mock(
                    date_published=datetime.datetime.fromtimestamp(1),
                    source_package_name='test-package',
                ),
            ],
        ))),
    })
    state._write_timestamps({
        'debian': target.Timestamp(0, None),
        'ubuntu': target.Timestamp(0, None),
    })
    target.request_new_imports(
        lp=lp,
        num_days_ago=None,
        service_state=state,
        filter_func=filter_func,
        request_time=2.0,
    )


def test_request_new_imports_filter_func_true(state):
    """Package is requested when filter_func agrees

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    filter_func=Mock(return_value=False)
    mock_call_request_new_imports(state=state, filter_func=filter_func)
    filter_func.assert_called_once_with('test-package')
    assert state._dump_request() == frozenset()


def test_request_new_imports_filter_func_false(state):
    """Package is not requested when filter_func disagrees

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    filter_func=Mock(return_value=True)
    mock_call_request_new_imports(state=state, filter_func=filter_func)
    filter_func.assert_called_once_with('test-package')
    assert state._dump_request() == frozenset({
        ('test-package', 2.0, 'needed', 20, 0),
    })