File: prepare_upload_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 (521 lines) | stat: -rw-r--r-- 18,173 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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import re
import sys
import unittest.mock
from unittest.mock import patch

import pygit2
import pytest

from gitubuntu.git_repository import GitUbuntuRepository
from gitubuntu.repo_builder import Commit, Placeholder, Repo
from gitubuntu.test_fixtures import repo, pygit2_repo

import gitubuntu.prepare_upload as target


@pytest.fixture
def populated_repo(repo):
    """A pytest fixture that provides a GitUbuntuRepository populated with
    suitable data for the purposes of the tests in this module"""
    Repo(
        commits=[
            Commit(name='main', message='main'),
            Commit(name='other', message='other'),
        ],
        branches={
            'main': Placeholder('main'),
            'other': Placeholder('other'),
        },
    ).write(repo.raw_repo)
    repo.raw_repo.checkout('refs/heads/main')
    yield repo


def test_establish_args_with_branch(populated_repo):
    """Pushes and outputs correct fields when a branch name is specified

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    """
    repo = populated_repo

    repo.raw_repo.remotes.create(
        'testremote',
        'https://git.launchpad.net/test',
    )

    with patch.object(repo, 'git_run') as mock_run:
        result = target.establish_args(
            repo=repo,
            remote_name='testremote',
            branch_name='other',
        )
        mock_run.assert_called_with(
            [
                'push',
                'testremote',
                'refs/heads/other:refs/heads/other',
            ],
            stdout=unittest.mock.ANY,
            stderr=None,
        )

    other_ref = repo.raw_repo.lookup_reference('refs/heads/other')
    commit_hash = other_ref.peel(pygit2.Commit).id
    expected_result = {
        'Vcs-Git': 'https://git.launchpad.net/test',
        'Vcs-Git-Ref': 'refs/heads/other',
        'Vcs-Git-Commit': str(commit_hash),
    }
    assert result.changes_file_headers == expected_result


def test_establish_args_without_branch(populated_repo):
    """Pushes and outputs correct fields when no branch is specified

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    """
    repo = populated_repo

    repo.raw_repo.checkout('refs/heads/other')
    repo.raw_repo.remotes.create(
        'testremote',
        'https://git.launchpad.net/test',
    )

    with patch.object(repo, 'git_run') as mock_run:
        result = target.establish_args(repo=repo, remote_name='testremote')
        mock_run.assert_called_with(
            [
                'push',
                'testremote',
                'refs/heads/other:refs/heads/other',
            ],
            stdout=unittest.mock.ANY,
            stderr=None,
        )

    other_ref = repo.raw_repo.lookup_reference('refs/heads/other')
    commit_hash = other_ref.peel(pygit2.Commit).id
    expected_result = {
        'Vcs-Git': 'https://git.launchpad.net/test',
        'Vcs-Git-Ref': 'refs/heads/other',
        'Vcs-Git-Commit': str(commit_hash),
    }
    assert result.changes_file_headers == expected_result


def test_establish_args_without_remote(populated_repo):
    """Pushes and outputs correct fields when no remote is specified

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    """
    repo = populated_repo
    repo.raw_repo.config['gitubuntu.lpuser'] = 'testuser'

    # Reload GitUbuntuRepository so that lp_user gets read again
    repo = GitUbuntuRepository(repo.raw_repo.workdir)

    repo.raw_repo.remotes.create('testuser', 'https://git.launchpad.net/~test')
    with patch.object(repo, 'git_run') as mock_run:
        result = target.establish_args(repo=repo)
        mock_run.assert_called_with(
            [
                'push',
                'testuser',
                'refs/heads/main:refs/heads/main',
            ],
            stdout=unittest.mock.ANY,
            stderr=None,
        )

    main_ref = repo.raw_repo.lookup_reference('refs/heads/main')
    commit_hash = main_ref.peel(pygit2.Commit).id
    expected_result = {
        'Vcs-Git': 'https://git.launchpad.net/~test',
        'Vcs-Git-Ref': 'refs/heads/main',
        'Vcs-Git-Commit': str(commit_hash),
    }
    assert result.changes_file_headers == expected_result


def test_establish_args_stdout(populated_repo):
    """git push output is written to the terminal

    The user expects to see the output of "git push" on the terminal. However,
    we cannot output to stdout, since that is to be captured for use in command
    line arguments to dpkg-buildpackage or a similar command. So stdout output
    from git must go to stderr, and stderr output must not have been adjusted.

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    """
    repo = populated_repo
    repo.raw_repo.remotes.create(
        'testremote',
        'https://git.launchpad.net/test',
    )
    with patch.object(repo, 'git_run') as mock_run:
        result = target.establish_args(
            repo=repo,
            remote_name='testremote',
            branch_name='other',
        )
    assert mock_run.call_args.kwargs['stdout'] is sys.stderr
    assert mock_run.call_args.kwargs['stderr'] is None


@patch("builtins.print")
@patch("gitubuntu.prepare_upload.establish_args")
def test_establish_args_failure(
    mock_establish_args,
    mock_print,
    populated_repo,
    monkeypatch,
):
    """On failure, the CLI prints an impossible argument

    :param unittest.mock.Mock mock_establish_args: the mocked out
        establish_args function
    :param unittest.mock.Mock mock_print: the mocked out print function
    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param monkeypatch: the standard pytest monkeypatch fixture

    See: LP #1942865
    """
    monkeypatch.chdir(populated_repo.raw_repo.workdir)
    mock_establish_args.side_effect = RuntimeError("Mock failure")
    with pytest.raises(RuntimeError):
        target.cli_printargs(unittest.mock.Mock(
            remote=None,
            branch=None,
            output_format="dpkg-buildpackage",
        ))
    mock_print.assert_called_once_with(
        "--git-ubuntu-prepare-upload-args-failed",
    )


@pytest.mark.parametrize(['remote_url'], [
    ('git+ssh://user@git.launchpad.net/test',),
    ('ssh://user@git.launchpad.net/test',),
])
def test_establish_args_rewrites_lp_ssh_url(populated_repo, remote_url):
    """Rewrites Vcs-Git: to an https: one when git+ssh: or ssh: is used with LP

    See LP: #1942985

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param str remote_url: the URL that we will test is rewritten
    """
    repo = populated_repo
    repo.raw_repo.remotes.create('testremote', remote_url)
    with patch.object(repo, 'git_run') as mock_run:
        result = target.establish_args(
            repo=repo,
            remote_name='testremote',
            branch_name='other',
        )
        mock_run.assert_called_with(
            [
                'push',
                'testremote',
                'refs/heads/other:refs/heads/other',
            ],
            stdout=unittest.mock.ANY,
            stderr=None,
        )

    other_ref = repo.raw_repo.lookup_reference('refs/heads/other')
    commit_hash = other_ref.peel(pygit2.Commit).id
    expected_result = {
        'Vcs-Git': 'https://git.launchpad.net/test',
        'Vcs-Git-Ref': 'refs/heads/other',
        'Vcs-Git-Commit': str(commit_hash),
    }
    assert result.changes_file_headers == expected_result


FAKE_SIGNED_CHANGES_FILE = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

Format: 1.8
Source: test

-----BEGIN PGP SIGNATURE-----

Fake signature data
-----END PGP SIGNATURE-----
"""
@pytest.fixture
def fake_changes_file_path(tmpdir):
    """A fixture to provide a fake changes file ready for mangling

    This fixture does no cleanup on the assumption that the automatic cleanup
    of the tmpdir fixture it uses is sufficient.

    :param tmpdir: the standard pytest tmpdir fixture
    :rtype: str
    :returns: the path to our standard fake changes file in a temporary
        directory
    """
    changes_file_path = str(tmpdir.join('changes'))
    with open(changes_file_path, 'w') as f:
        f.write(FAKE_SIGNED_CHANGES_FILE)
    return changes_file_path


def test_mangle_changes(populated_repo, fake_changes_file_path):
    """Pushes and adds correct fields

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param str fake_changes_file_path: our test changes file fixture
    """
    repo = populated_repo

    repo.raw_repo.checkout('refs/heads/other')
    repo.raw_repo.remotes.create(
        'testremote',
        'https://git.launchpad.net/test',
    )

    with patch.object(repo, 'git_run') as mock_run:
        target.mangle_changes(
            repo=repo,
            remote_name='testremote',
            branch_name='main',
            changes_file_path=fake_changes_file_path,
        )
        mock_run.assert_called_with(
            [
                'push',
                'testremote',
                'refs/heads/main:refs/heads/main',
            ],
            stdout=unittest.mock.ANY,
            stderr=None,
        )

    main_ref = repo.raw_repo.lookup_reference('refs/heads/main')
    commit_hash = main_ref.peel(pygit2.Commit).id
    expected_result = {
        'vcs_git': 'https://git.launchpad.net/test',
        'vcs_git_ref': 'refs/heads/main',
        'vcs_git_commit': str(commit_hash),
    }
    with open(fake_changes_file_path, 'r') as f:
        data = f.read()
    assert sorted(data.splitlines()) == [
        "Format: 1.8",
        "Source: test",
        f"Vcs-Git-Commit: {commit_hash!s}",
        "Vcs-Git-Ref: refs/heads/main",
        "Vcs-Git: https://git.launchpad.net/test",
    ]


def test_mod_changes_file(fake_changes_file_path):
    """mod_changes_file mangles our standard fake changes file as expected

    Note that this includes stripping of the signature.

    :param str fake_changes_file_path: our test changes file fixture
    """
    target.mod_changes_file(
        changes_file_path=fake_changes_file_path,
        replacements={'Added': 'yes'},
    )
    with open(fake_changes_file_path, 'r') as f:
        data = f.read()
    assert data == "Format: 1.8\nSource: test\nAdded: yes\n"


def test_mod_changes_file_idempotent(fake_changes_file_path):
    """mangle_changes operates idempotently

    If run twice, the output should still be as expected. Note that this has
    the effect of verifying that it will also work correctly when the changes
    file is unsigned, since that's the result of the first call.

    :param str fake_changes_file_path: our test changes file fixture
    """
    target.mod_changes_file(fake_changes_file_path, {'Added': 'yes'})
    target.mod_changes_file(fake_changes_file_path, {'Added': 'yes'})
    with open(fake_changes_file_path, 'r') as f:
        data = f.read()
    assert data == "Format: 1.8\nSource: test\nAdded: yes\n"


@patch('gitubuntu.importer.LAUNCHPAD_GIT_HOSTING_URL_PREFIX', '')
@patch('gitubuntu.importer.VCS_GIT_URL_VALIDATION', re.compile(r'.*'))
def test_fetch_gets_called(populated_repo, pygit2_repo):
    """We fetch from the repository during a establish_args operation

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param pygit.Repository pygit2_repo: our empty pygit2 repository fixture.
    """
    # Note that we cannot use a repo instance twice, even if one is via
    # populated_repo, because pytest will give us only one instance. A
    # convenient workaround is that the remote repo doesn't need to be a
    # GitUbuntuRepository and so the pygit2_repo fixture will do as it is
    # independent. We can assert they are definitely different:
    assert populated_repo.raw_repo is not pygit2_repo

    remote_repo = pygit2_repo
    local_repo = populated_repo

    # Allow the push even for our non-bare "remote" test repo
    pygit2_repo.config['receive.denyCurrentBranch'] = 'ignore'

    local_repo.raw_repo.remotes.create('test-remote', pygit2_repo.path)
    local_repo.git_run(["push", "test-remote", "main"])

    with patch.object(local_repo, 'git_run') as mock_run:
        target.establish_args(
            repo=local_repo,
            remote_name='test-remote',
            branch_name='main',
        )
    mock_run.assert_called_with(
        ['fetch', 'test-remote'],
        stdout=unittest.mock.ANY,
        stderr=None,
        env=unittest.mock.ANY,
        check=False,
        verbose_on_failure=False,
    )


@patch('gitubuntu.importer.LAUNCHPAD_GIT_HOSTING_URL_PREFIX', '')
@patch('gitubuntu.importer.VCS_GIT_URL_VALIDATION', re.compile(r'.*'))
def test_no_push_when_already_present(populated_repo, pygit2_repo):
    """If the rich history is already available, we do not try to push again

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param pygit.Repository pygit2_repo: our empty pygit2 repository fixture.
    """
    # Note that we cannot use a repo instance twice, even if one is via
    # populated_repo, because pytest will give us only one instance. A
    # convenient workaround is that the remote repo doesn't need to be a
    # GitUbuntuRepository and so the pygit2_repo fixture will do as it is
    # independent. We can assert they are definitely different:
    assert populated_repo.raw_repo is not pygit2_repo

    remote_repo = pygit2_repo
    local_repo = populated_repo

    # Allow the push even for our non-bare "remote" test repo
    pygit2_repo.config['receive.denyCurrentBranch'] = 'ignore'

    local_repo.raw_repo.remotes.create('test-remote', pygit2_repo.path)
    local_repo.git_run(["push", "test-remote", "main"])

    with patch.object(target, 'push') as mock_push:
        target.establish_args(
            repo=local_repo,
            remote_name='test-remote',
            branch_name='main',
        )
        mock_push.assert_not_called()


@patch('gitubuntu.importer.LAUNCHPAD_GIT_HOSTING_URL_PREFIX', '')
@patch('gitubuntu.importer.VCS_GIT_URL_VALIDATION', re.compile(r'.*'))
def test_rejects_force_push(populated_repo, pygit2_repo):
    """If the remote branch cannot be fast-forwarded and we didn't request a
    force push, then an exception is raised

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param pygit.Repository pygit2_repo: our empty pygit2 repository fixture.
    """
    # Note that we cannot use a repo instance twice, even if one is via
    # populated_repo, because pytest will give us only one instance. A
    # convenient workaround is that the remote repo doesn't need to be a
    # GitUbuntuRepository and so the pygit2_repo fixture will do as it is
    # independent. We can assert they are definitely different:
    assert populated_repo.raw_repo is not pygit2_repo

    remote_repo = pygit2_repo
    local_repo = populated_repo

    # Write something to the remote main branch so it cannot be fast-forwarded
    # with what we have locally
    Repo(
        commits=[
            Commit(name='main', message='mutated'),
        ],
        branches={
            'main': Placeholder('main'),
        },
    ).write(remote_repo)

    local_repo.raw_repo.remotes.create('test-remote', pygit2_repo.path)

    with pytest.raises(target.ForcePushRequired):
        target.establish_args(
            repo=local_repo,
            remote_name='test-remote',
            branch_name='main',
        )


@patch('gitubuntu.importer.LAUNCHPAD_GIT_HOSTING_URL_PREFIX', '')
@patch('gitubuntu.importer.VCS_GIT_URL_VALIDATION', re.compile(r'.*'))
def test_performs_force_push(populated_repo, pygit2_repo):
    """If the remote branch cannot be fast-forwarded and we did request a force
    push, then the remote branch is updated

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param pygit.Repository pygit2_repo: our empty pygit2 repository fixture.
    """
    # Note that we cannot use a repo instance twice, even if one is via
    # populated_repo, because pytest will give us only one instance. A
    # convenient workaround is that the remote repo doesn't need to be a
    # GitUbuntuRepository and so the pygit2_repo fixture will do as it is
    # independent. We can assert they are definitely different:
    assert populated_repo.raw_repo is not pygit2_repo

    remote_repo = pygit2_repo
    local_repo = populated_repo

    # Write something to the remote main branch so it cannot be fast-forwarded
    # with what we have locally
    Repo(
        commits=[
            Commit(name='main', message='mutated'),
        ],
        branches={
            'main': Placeholder('main'),
        },
    ).write(remote_repo)

    # Allow the push even for our non-bare "remote" test repo
    pygit2_repo.config['receive.denyCurrentBranch'] = 'ignore'

    local_repo.raw_repo.remotes.create('test-remote', pygit2_repo.path)

    target.establish_args(
        repo=local_repo,
        remote_name='test-remote',
        branch_name='main',
        force_push=True,
    )

    local_commit_id = (
        populated_repo.raw_repo.references["refs/heads/main"]
        .peel(pygit2.Commit)
        .id
    )
    remote_commit_id = (
        pygit2_repo.references["refs/heads/main"].peel(pygit2.Commit).id
    )
    assert local_commit_id == remote_commit_id