File: source_information_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 (500 lines) | stat: -rw-r--r-- 17,227 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
494
495
496
497
498
499
500
import collections
import functools
from unittest.mock import Mock, sentinel

import keyring
import pytest
from gitubuntu.git_repository import HeadInfoItem
import gitubuntu.source_information as target
from gitubuntu.source_information import derive_codename_from_series
from gitubuntu import source_information


def test_keyring_backend_found():
    """Test that the keyring module can find a suitable backend

    In LP: #1794041, keyring 15.0.0 removed keyring.util.escape; keyrings.alt
    started using its own version in keyrings.alt 3.1. Since git-ubuntu's
    setup.py mandated keyrings.alt 2.3 but specified no requirement for keyring
    itself, this led to an old keyrings.alt being used against a newer
    keyring, which failed because keyring.util.escape was no longer defined
    anywhere.

    The real requirement we have is that _some_ keyring is available. Since the
    keyring module might choose any backend, the real test we need here is to
    ensure that the keyring module didn't fail to find any backend. It has a
    specific "fail" backend for this, so we test here that this isn't the one
    it "found".

    Unfortunately this is a little brittle in case backend arrangements inside
    the keyring module changes, but there doesn't seem to be specified
    mechanism in the API to determine if a backend keyring has been found
    successfully.
    """
    k = keyring.get_keyring()
    assert not isinstance(k, keyring.backends.fail.Keyring)


@pytest.mark.parametrize('codename', [
    'eoan',
    'feisty',
    'sid',
    'bionic'
])
def test_derive_codename_from_series_as_codenames(codename):
    """Test that series names matching codenames return the codename

    For both Debian and Ubuntu, when looking up the codename for
    a series, if we passed in a codename verify that codename gets
    returned, as expected.
    """
    assert derive_codename_from_series(codename) == codename


@pytest.mark.parametrize('alias,codename', [
    ('unstable', 'sid'),
    ('experimental', 'experimental')
])
def test_derive_codename_from_series_as_aliases(alias, codename):
    """Test that aliases as series names are converted to codenames

    Debian (only) allows using aliases for codenames, such as stable,
    unstable, and so on.  The aliases can be pointed at different
    codenames over time as things develop, however two aliases, unstable
    and experimental, always point consistently to specific codenames
    (sid and experimental, respectively).  This test verifies that the
    alias conversion works as expected for these two special cases.
    """
    assert derive_codename_from_series(alias) == codename


@pytest.mark.parametrize('bad_codename', [
    None,
    0,
    123,
    '',
    '0',
    '12345',
    'invalid',
    'beaver',
    'dapper hardy lucid precise trusty xenial bionic',
    'buster buster buster',
    'stablestable'
    ])
def test_derive_codename_from_invalid_series(bad_codename):
    """Tests that passing erroneous values raises expected ValueError exception"""
    with pytest.raises(ValueError):
        derive_codename_from_series(bad_codename)


@pytest.mark.parametrize('series,codename', [
    ('unstable', 'sid'),
    ('experimental', 'experimental'),
    ('bionic', 'bionic'),
    ])
def test_derive_codename_from_broken_distro_info(monkeypatch, series, codename):
    """Test for proper lookup of Ubuntu codenames

    Coverity discovered a cut-and-paste error in
    derive_codename_from_series() where Ubuntu codenames were being
    looked up against Debian instead of Ubuntu.  Fortunately,
    DistroInfo's codename() implementation simply returns codenames it
    doesn't recognize, so in practice the behavior would work as
    expected.  However, we can't count on DistroInfo's permissiveness.

    This test uses a stricter implementation of DebianDistroInfo that
    refuses to pass-thru incorrect codenames.
    """
    MockDistroRelease = collections.namedtuple(
        'MockDistroRelease', 'version,codename,series,created,release,eol'
    )

    class MockDebianDistroInfo:
        """A simplified version of DebianDistroInfo with hardcoded data

        This mock provides a reduced implementation of DebianDistroInfo,
        with the release CSV information included directly in the class
        rather than loading from an external file.

        Additionally, it provides a stricter implementation of the
        codename() routine that throws an exception when looking up
        invalid release names.
        """
        def __init__(self):
            # Snipped data from distro-info-data
            data = [
                '3.0,Woody,woody,2000-08-15,2002-07-19,2006-06-30',
                '6.0,Squeeze,squeeze,2009-02-14,2011-02-06,2014-05-31',
                '9,Stretch,stretch,2015-04-25,2017-06-17,',
                '12,Bookworm,bookworm,2021-08-01,,',
                ',Sid,sid,1993-08-16,,',
                ',Experimental,experimental,1993-08-16,,',
                ]
            self._releases = [MockDistroRelease(*row.split(',')) for row in data]

        def all(self):
            """List codenames of all known distributions."""
            return [x.series for x in self._releases]

        def valid(self, codename):
            return (codename in self.all()) or (codename in ['unstable', 'testing'])

        def codename(self, release, date=None, default=None):
            if release == 'unstable':
                return 'sid'
            elif release == 'experimental':
                return 'experimental'
            elif not self.valid(codename):
                raise ValueError("Provided codename is not valid for Debian")
            else:
                raise NotImplementedError()

    # Replace the DebianDistroInfo object with our mock,
    # but leave the UbuntuDistroInfo object as-is.
    monkeypatch.setattr(source_information, "_ddi", MockDebianDistroInfo())

    assert derive_codename_from_series(series) == codename


@pytest.mark.parametrize(['debian_input', 'ubuntu_input', 'expected'], [
    (
        [],
        [],
        [],
    ),
    (
        [0],
        [0],
        [(0, 'debian'), (0, 'ubuntu')],
    ),
    (
        [1],
        [0],
        [(0, 'ubuntu'), (1, 'debian')],
    ),
])
def test_interleave_launchpad_versions_published_after(
    debian_input,
    ubuntu_input,
    expected,
):
    """Test that interleaving works correctly

    We will always ask for Debian before Ubuntu. When date_created is the same,
    Debian should come first. If date_created is different, the earlier
    date_created should come first.

    :param list(Any) debian_input: the date_created attributes of the fake
        Launchpad source_package_publishing_history objects of the fake
        GitUbuntuSourcePackageInformation objects that will be returned by the
        faked call to launchpad_versions_published_after() call, for the Debian
        distribution.
    :param list(Any) debian_input: the date_created attributes of the fake
        Launchpad source_package_publishing_history objects of the fake
        GitUbuntuSourcePackageInformation objects that will be returned by the
        faked call to launchpad_versions_published_after() call, for the Ubuntu
        distribution.
    :param list(tuple(date_created, distribution)): the expected ordering in
        the return sequence of the
        interleave_launchpad_versions_published_after() call. date_created
        corresponds to the input data from debian_input and ubuntu_input.
        distribution is either the 'debian' string or the 'ubuntu' string
        depending on whether the return value was supposed to come from the
        Debian or Ubuntu fake GitUbuntuSourceInformation object.
    """
    # Store all fake guspis created, since equivalent guspis will be asserted
    # for equality later, and Mock objects that are otherwise identical do not
    # compare equal if they are separate instances. For the same call to
    # fake_guspi() below, we want to return the same Mock object instance so
    # that they do compare equal.
    fake_guspis = {}
    def fake_guspi(dist_link, date_created):
        """Return a fake target.GitUbuntuSourcePackageInformation object

        Multiple calls to this function with the same parameters return the
        same fake objects so that they compare equal.

        :param Any dist_link: a mock distribution_link that can be compared
            against later (for example, use a unittest.mock.sentinel).
        :param Any date_created: the fake date_created attribute of the
            underlying Launchpad source_package_publishing_history object.
        :rtype: Mock
        :returns: the fake target.GitUbuntuSourcePackageInformation object.
        """
        try:
            return fake_guspis[(dist_link, date_created)]
        except KeyError:
            result = Mock(
                spec=target.GitUbuntuSourcePackageInformation,
                _spphr=Mock(
                    distro_series_link=str(hash(dist_link)) + '_distro_series',
                    distro_series=Mock(distribution_link=dist_link),
                    date_created=date_created,
                )
            )
            fake_guspis[(dist_link, date_created)] = result
            return result

    # A fake target.GitUbuntuSourceInformation object to represent the Debian
    # distribution.
    debian = Mock(
        spec=target.GitUbuntuSourceInformation,
        dist=Mock(self_link=sentinel.debian_dist_link),
        launchpad_versions_published_after=Mock(return_value=[
            fake_guspi(sentinel.debian_dist_link, date_created)
            for date_created in debian_input
        ])
    )
    # A fake target.GitUbuntuSourceInformation object to represent the Ubuntu
    # distribution.
    ubuntu = Mock(
        spec=target.GitUbuntuSourceInformation,
        dist=Mock(self_link=sentinel.ubuntu_dist_link),
        launchpad_versions_published_after=Mock(return_value=[
            fake_guspi(sentinel.ubuntu_dist_link, date_created)
            for date_created in ubuntu_input
        ])
    )

    gusi_head_info_tuple_list = [
        (debian, None),
        (ubuntu, None),
    ]
    result = target.GitUbuntuSourceInformation.interleave_launchpad_versions_published_after(
        gusi_head_info_tuple_list=gusi_head_info_tuple_list,
        namespace=None,
    )
    expanded_result = list(result)
    assert expanded_result == [
        fake_guspi(
            dist_link={
                'debian': sentinel.debian_dist_link,
                'ubuntu': sentinel.ubuntu_dist_link,
            }[dist],
            date_created=date_created,
        )
        for date_created, dist in expected
    ]


@pytest.mark.parametrize(['dist_name', 'input_head_info', 'input_spph'], [
    # Empty case
    (
        'debian', {}, [],
    ),
    # Single publication, nothing imported yet
    (
        'debian',
        {},
        [
            ('sid', '1', 1, True),
        ],
    ),
    # Single publication, already imported
    (
        'debian',
        {'sid': ('1', 1)},
        [
            ('sid', '1', 1, False),
        ],
    ),
    # Two identical publications, nothing imported yet
    (
        'debian',
        {},
        [
            ('sid', '1', 2, True),
            ('bullseye', '1', 1, True),
        ],
    ),
    # Two identical publications, already imported
    (
        'debian',
        {
            'sid': ('1', 1),
            'bullseye': ('1', 1),
        },
        [
            ('sid', '1', 2, True),
            ('bullseye', '1', 1, False),
        ],
    ),
    # Two versions in the normal proposed migration way, one imported
    (
        'debian',
        {
            'sid': ('1', 1),
            'bullseye': ('1', 1),
        },
        [
            ('bullseye', '2', 4, True),
            ('sid', '2', 3, True),
            ('bullseye', '1', 2, True),
            ('sid', '1', 1, False),
        ],
    ),
    # Two versions in the normal proposed migration way, both imported
    (
        'debian',
        {
            'sid': ('2', 3),
            'bullseye': ('2', 3),
        },
        [
            ('bullseye', '2', 4, True),
            ('sid', '2', 3, False),
            ('bullseye', '1', 2, False),
            ('sid', '1', 1, False),
        ],
    ),
    # Empty case
    (
        'ubuntu', {}, [],
    ),
    # Single publication, nothing imported yet
    (
        'ubuntu',
        {},
        [
            ('kinetic-proposed', '1', 1, True),
        ],
    ),
    # Single publication, already imported
    (
        'ubuntu',
        {'kinetic-proposed': ('1', 1)},
        [
            ('kinetic-proposed', '1', 1, False),
        ],
    ),
    # Two identical publications, nothing imported yet
    (
        'ubuntu',
        {},
        [
            ('kinetic', '1', 2, True),
            ('kinetic-proposed', '1', 1, True),
        ],
    ),
    # Two identical publications, already imported
    (
        'ubuntu',
        {
            'kinetic': ('1', 1),
            'kinetic-proposed': ('1', 1),
        },
        [
            ('kinetic', '1', 2, True),
            ('kinetic-proposed', '1', 1, False),
        ],
    ),
    # Two versions in the normal proposed migration way, one imported
    (
        'ubuntu',
        {
            'kinetic-proposed': ('1', 1),
            'kinetic': ('1', 1),
        },
        [
            ('kinetic', '2', 4, True),
            ('kinetic-proposed', '2', 3, True),
            ('kinetic', '1', 2, True),
            ('kinetic-proposed', '1', 1, False),
        ],
    ),
    # Two versions in the normal proposed migration way, both imported
    (
        'ubuntu',
        {
            'kinetic-proposed': ('2', 3),
            'kinetic': ('2', 3),
        },
        [
            ('kinetic', '2', 4, True),
            ('kinetic-proposed', '2', 3, False),
            ('kinetic', '1', 2, False),
            ('kinetic-proposed', '1', 1, False),
        ],
    ),
])
def test_launchpad_versions_published_after(
    dist_name,
    input_head_info,
    input_spph,
):
    """If launchpad_versions_published_after() is shown some particular
    head_info and some set of publications in Launchpad, then it should present
    the expected subset of those publications for import.

    :param str dist_name: either 'debian' or 'ubuntu'
    :param dict input_head_info: a dictionary. Keyed by the branch name without
        any namespace or prefix. The value is a tuple(str, int) of
        (package_version, timestamp).
    :param list input_spph: a list of mock publications from Launchpad in
        reverse chronological order by date_created. Each entry is a 4-tuple
        with the following fields:
            str: the name of the apt suite the publication was made in
            str: the package version string
            int: date_created
            bool: True if this entry should be included in the expected result
    """
    namespaced_input_head_info = {
        f'importer/{dist_name}/{suite}':
            HeadInfoItem(
                version=version,
                commit_time=commit_time,
                commit_id=None,
            )
        for suite, (version, commit_time) in input_head_info.items()
    }

    dist = Mock()
    lp = Mock(distributions={dist_name: dist})
    getPublishedSources = dist.main_archive.getPublishedSources

    getPublishedSources_return_value = []
    for i, (suite, version, date_created, _) in enumerate(input_spph):
        # Create a minimal fake record that would be returned by Launchpad's
        # getPublishedSources method on the Launchpad archive object. We have
        # to do this imperatively in order to set the name attributes
        # (https://docs.python.org/3/library/unittest.mock.html#mock-names-and-the-name-attribute).
        distribution_mock = Mock()
        distribution_mock.name = dist_name
        distro_series_mock = Mock(
            distribution=distribution_mock,
            distribution_link=dist_name,
        )
        distro_series_mock.name = suite.split('-')[0]
        spphr_mock = Mock(
            source_package_version=version,
            date_created=Mock(timestamp=Mock(return_value=date_created)),
            pocket=suite.split('-')[1] if '-' in suite else 'release',
            distro_series=distro_series_mock,
            distro_series_link=suite.split('-')[0],
            test_record_id=i,
        )
        getPublishedSources_return_value.append(spphr_mock)
    getPublishedSources.return_value = getPublishedSources_return_value

    gusi = target.GitUbuntuSourceInformation(
        dist_name=dist_name,
        lp=lp,
        pkgname=sentinel.pkgname,
    )

    actual_result = list(gusi.launchpad_versions_published_after(
        head_info=namespaced_input_head_info,
        namespace='importer',
    ))

    getPublishedSources.assert_called_once_with(
        exact_match=True,
        source_name=sentinel.pkgname,
        order_by_date=True,
    )

    assert list(reversed([
        i
        for i, (_, _, _, expected_in_result) in enumerate(input_spph)
        if expected_in_result
    ])) == [m._spphr.test_record_id for m in actual_result]