Debian Codegraph @

test/control_file/test_upload_changes.py

raw
1 # test/control_file/test_upload_changes.py
2 # Part of ‘dput’, a Debian package upload toolkit.
3 #
4 # This is free software, and you are welcome to redistribute it under
5 # certain conditions; see the end of this file for copyright
6 # information, grant of license, and disclaimer of warranty.
7
8 """ Unit tests for Debian upload changes control files.
9
10 The Debian upload changes control file is defined in Policy §5.5. It is
11 typically named with a ‘.changes’ suffix.
12 """
13
14 import collections
15 import contextlib
16 import doctest
17 import email.message
18 import hashlib
19 import io
20 import os
21 import os.path
22 import sys
23 import tempfile
24 import textwrap
25 import unittest.mock
26
27 import gpg
28 import testscenarios
29 import testtools
30
31 from dput.control_file import upload_changes
32 import dput.crypto
33 from dput.helper import dputhelper
34
35 from ..helper import (
36 EXIT_STATUS_FAILURE,
37 FakeSystemExit,
38 FileDouble,
39 SubprocessDouble,
40 get_file_doubles_from_fake_file_scenarios,
41 make_fake_file_scenarios,
42 make_fake_locale_scenarios,
43 make_unique_slug,
44 patch_locale_environment_variables,
45 patch_locale_getpreferredencoding,
46 patch_os_stat,
47 patch_subprocess_popen,
48 patch_system_interfaces,
49 set_fake_file_scenario,
50 setup_fake_file_fixtures,
51 setup_file_double_behaviour,
52 )
53 from ..test_configfile import (
54 patch_runtime_config_options,
55 set_config,
56 )
57
58
59 class _FieldsMapping:
60 """ A mapping to stand in for the `dict` of an `email.message.Message`. """
61
62 def __init__(self, *args, **kwargs):
63 try:
64 self._message = kwargs.pop('_message')
65 except KeyError:
66 raise TypeError("no ‘_message’ specified for this mapping")
67 super().__init__(*args, **kwargs)
68
69 def __len__(self, *args, **kwargs):
70 return self._message.__len__(*args, **kwargs)
71
72 def __contains__(self, *args, **kwargs):
73 return self._message.__contains__(*args, **kwargs)
74
75 def __getitem__(self, *args, **kwargs):
76 return self._message.__getitem__(*args, **kwargs)
77
78 def __setitem__(self, *args, **kwargs):
79 self._message.__setitem__(*args, **kwargs)
80
81 def __delitem__(self, *args, **kwargs):
82 self._message.__delitem__(*args, **kwargs)
83
84 def keys(self, *args, **kwargs):
85 return self._message.keys(*args, **kwargs)
86
87 def values(self, *args, **kwargs):
88 return self._message.values(*args, **kwargs)
89
90 def items(self, *args, **kwargs):
91 return self._message.items(*args, **kwargs)
92
93 def get(self, *args, **kwargs):
94 return self._message.get(*args, **kwargs)
95
96
97 class FakeMessage(email.message.Message):
98 """ A fake RFC 2822 message that mocks the obsolete `rfc822.Message`. """
99
100 def __init__(self, *args, **kwargs):
101 super().__init__(*args, **kwargs)
102 self.dict = _FieldsMapping(_message=self)
103
104
105 def make_fake_message(fields):
106 """ Make a fake message instance. """
107 message = FakeMessage()
108 for (name, value) in fields.items():
109 message.add_header(name, value)
110 return message
111
112
113 def make_files_field_value(params_by_name):
114 """ Make a value for “Files” field of a changes document. """
115 result = "\n".join(
116 " ".join(params)
117 for (file_name, params) in params_by_name.items())
118 return result
119
120
121 def make_upload_files_params(checksums_by_file_name, sizes_by_file_name):
122 """ Make a mapping of upload parameters for files. """
123 params_by_name = {
124 file_name: [
125 checksums_by_file_name[file_name],
126 str(sizes_by_file_name[file_name]),
127 "foo", "bar", file_name]
128 for file_name in checksums_by_file_name}
129 return params_by_name
130
131
132 def make_changes_document(fields, upload_params_by_name=None):
133 """ Make a changes document from field values.
134
135 :param fields: Sequence of (name, value) tuples for fields.
136 :param upload_params_by_name: Mapping from filename to upload
137 parameters for each file.
138 :return: The changes document as an RFC 822 formatted text.
139 """
140 document_fields = fields.copy()
141 if upload_params_by_name is not None:
142 files_field_text = make_files_field_value(upload_params_by_name)
143 document_fields.update({'files': files_field_text})
144 document = make_fake_message(document_fields)
145
146 return document
147
148
149 def make_changes_file_scenarios():
150 """ Make fake Debian upload control (‘*.changes’) scenarios. """
151 file_path = make_changes_file_path()
152
153 fake_file_empty = io.StringIO()
154 fake_file_no_format = io.StringIO(textwrap.dedent("""\
155 FOO
156 BAR
157 Files:
158 Lorem ipsum dolor sit amet
159 """))
160 fake_file_with_signature = io.StringIO(textwrap.dedent("""\
161 -----BEGIN PGP SIGNED MESSAGE-----
162 Hash: SHA1
163
164 FOO
165 BAR
166 Files:
167 Lorem ipsum dolor sit amet
168
169 -----BEGIN PGP SIGNATURE-----
170 Version: 0.0
171 Comment: Proin ac massa at orci sagittis fermentum.
172
173 gibberishgibberishgibberishgibberishgibberishgibberish
174 gibberishgibberishgibberishgibberishgibberishgibberish
175 gibberishgibberishgibberishgibberishgibberishgibberish
176 -----END PGP SIGNATURE-----
177 """))
178 fake_file_with_format = io.StringIO(textwrap.dedent("""\
179 Format: FOO
180 Changed-By: Dolor sit amet <[email protected]>
181 Files:
182 Lorem ipsum dolor sit amet
183 """))
184 fake_file_accented_text = io.StringIO(textwrap.dedent("""\
185 Format: FOO
186 Changed-By: Dølòr sít ämêt <[email protected]>
187 Files:
188 Lorem ipsum dolor sit amet
189 """))
190 fake_file_olditalic_text = io.StringIO(textwrap.dedent("""\
191 Format: FOO
192 Changed-By: 𐌃𐌏𐌋𐌏𐌓 𐌔𐌉𐌕 𐌀𐌌𐌄𐌕 <[email protected]>
193 Files:
194 Lorem ipsum dolor sit amet
195 """))
196 fake_file_invalid = io.StringIO(textwrap.dedent("""\
197 Format: FOO
198 Files:
199 FOO BAR
200 """))
201 fake_file_needs_utf8 = io.StringIO(textwrap.dedent("""\
202 # ქართული
203 # 你好
204 Files:
205 Lórem ipsüm dolôr sìt āmet
206 """))
207
208 scenarios = [
209 ('no-format', {
210 'file_double': FileDouble(
211 path=file_path,
212 fake_file=fake_file_no_format),
213 'expected_result': make_changes_document({
214 'files': "Lorem ipsum dolor sit amet",
215 }),
216 }),
217 ('with-pgp-signature', {
218 'file_double': FileDouble(
219 path=file_path,
220 fake_file=fake_file_with_signature),
221 'expected_result': make_changes_document({
222 'files': "Lorem ipsum dolor sit amet",
223 }),
224 }),
225 ('with-format', {
226 'file_double': FileDouble(
227 path=file_path,
228 fake_file=fake_file_with_format),
229 'expected_result': make_changes_document({
230 'changed-by': "Dolor sit amet <[email protected]>",
231 'files': "Lorem ipsum dolor sit amet",
232 }),
233 }),
234 ('non-ascii', {
235 'file_double': FileDouble(
236 path=file_path,
237 fake_file=fake_file_accented_text),
238 'expected_result': make_changes_document({
239 'changed-by': "Dølòr sít ämêt <[email protected]>",
240 'files': "Lorem ipsum dolor sit amet",
241 }),
242 }),
243 ('higher-character-plane', {
244 'file_double': FileDouble(
245 path=file_path,
246 fake_file=fake_file_olditalic_text),
247 'expected_result': make_changes_document({
248 'changed-by': "𐌃𐌏𐌋𐌏𐌓 𐌔𐌉𐌕 𐌀𐌌𐌄𐌕 <[email protected]>",
249 'files': "Lorem ipsum dolor sit amet",
250 }),
251 }),
252 ('error empty', {
253 'file_double': FileDouble(
254 path=file_path, fake_file=fake_file_empty),
255 'expected_error': KeyError,
256 }),
257 ('error invalid', {
258 'file_double': FileDouble(
259 path=file_path,
260 fake_file=fake_file_invalid),
261 'expected_error': FakeSystemExit,
262 }),
263 ('encoding needs-utf8', {
264 'file_double': FileDouble(
265 path=file_path,
266 fake_file=fake_file_needs_utf8),
267 'expected_result': make_changes_document({
268 'files': "Lórem ipsüm dolôr sìt āmet",
269 }),
270 }),
271 ]
272
273 for (scenario_name, scenario) in scenarios:
274 scenario['changes_file_scenario_name'] = scenario_name
275
276 return scenarios
277
278
279 def set_fake_upload_file_paths(testcase):
280 """ Set the fake upload file paths. """
281 testcase.fake_upload_file_paths = [
282 os.path.join(
283 os.path.dirname(testcase.changes_file_double.path),
284 os.path.basename(tempfile.mktemp()))
285 for __ in range(10)]
286
287 required_suffixes = [".dsc", ".tar.xz"]
288 suffixes = required_suffixes + getattr(
289 testcase, 'additional_file_suffixes', [])
290 file_path_base = testcase.fake_upload_file_paths.pop()
291 for suffix in suffixes:
292 file_path = file_path_base + suffix
293 testcase.fake_upload_file_paths.insert(0, file_path)
294
295
296 def set_file_checksums(testcase):
297 """ Set the fake file checksums for the test case. """
298 testcase.fake_checksum_by_file = {
299 os.path.basename(file_path): make_unique_slug(testcase)
300 for file_path in testcase.fake_upload_file_paths}
301
302
303 def set_file_sizes(testcase):
304 """ Set the fake file sizes for the test case. """
305 testcase.fake_size_by_file = {
306 os.path.basename(file_path): testcase.getUniqueInteger()
307 for file_path in testcase.fake_upload_file_paths}
308
309
310 def set_file_doubles(testcase):
311 """ Set the file doubles for the test case. """
312 for file_path in testcase.fake_upload_file_paths:
313 file_double = FileDouble(file_path)
314 file_double.set_os_stat_scenario('okay')
315 file_double.stat_result = file_double.stat_result._replace(
316 st_size=testcase.fake_size_by_file[
317 os.path.basename(file_path)],
318 )
319 file_double.register_for_testcase(testcase)
320
321
322 def setup_upload_file_fixtures(testcase):
323 """ Set fixtures for fake files to upload for the test case. """
324 set_fake_upload_file_paths(testcase)
325 set_file_checksums(testcase)
326 set_file_sizes(testcase)
327 set_file_doubles(testcase)
328
329
330 def make_changes_file_path(file_dir_path=None):
331 """ Make a filesystem path for the changes file. """
332 if file_dir_path is None:
333 file_dir_path = tempfile.mktemp()
334 file_name = os.path.basename(
335 "{base}.changes".format(base=tempfile.mktemp()))
336 file_path = os.path.join(file_dir_path, file_name)
337
338 return file_path
339
340
341 def setup_changes_file_fixtures(testcase):
342 """ Set up fixtures for changes file doubles. """
343 file_path = make_changes_file_path()
344
345 scenarios = make_fake_file_scenarios(file_path)
346 testcase.changes_file_scenarios = scenarios
347
348 file_doubles = get_file_doubles_from_fake_file_scenarios(
349 scenarios.values())
350 setup_file_double_behaviour(testcase, file_doubles)
351
352
353 def set_changes_file_scenario(testcase, name):
354 """ Set the changes file scenario for this test case. """
355 scenario = dict(testcase.changes_file_scenarios)[name]
356 testcase.changes_file_scenario = scenario
357 testcase.changes_file_double = scenario['file_double']
358 testcase.changes_file_double.register_for_testcase(testcase)
359
360
361 class parse_changes_TestCase(
362 testscenarios.WithScenarios,
363 testtools.TestCase):
364 """ Base for test cases for `parse_changes` function. """
365
366 scenarios = NotImplemented
367
368 def setUp(self):
369 """ Set up test fixtures. """
370 super().setUp()
371 patch_system_interfaces(self)
372
373 self.test_infile = io.StringIO()
374
375
376 class parse_changes_SuccessTestCase(parse_changes_TestCase):
377 """ Success test cases for `parse_changes` function. """
378
379 scenarios = [
380 (name, scenario)
381 for (name, scenario) in make_changes_file_scenarios()
382 if not name.startswith('error')]
383
384 def test_gives_expected_result_for_infile(self):
385 """ Should give the expected result for specified input file. """
386 result = upload_changes.parse_changes(self.file_double.fake_file)
387 normalised_result_set = {
388 (key.lower(), value.strip())
389 for (key, value) in result.items()}
390 self.assertEqual(
391 set(self.expected_result.items()), normalised_result_set)
392
393
394 class parse_changes_ErrorTestCase(parse_changes_TestCase):
395 """ Error test cases for `parse_changes` function. """
396
397 scenarios = [
398 (name, scenario)
399 for (name, scenario) in make_changes_file_scenarios()
400 if name.startswith('error')]
401
402 def test_raises_expected_exception_for_infile(self):
403 """ Should raise the expected exception for specified input file. """
404 with testtools.ExpectedException(self.expected_error):
405 upload_changes.parse_changes(self.file_double.fake_file)
406
407
408 def patch_parse_changes(testcase):
409 """ Patch the `parse_changes` function for the test case. """
410 func_patcher = unittest.mock.patch.object(
411 upload_changes, "parse_changes", autospec=True)
412 func_patcher.start()
413 testcase.addCleanup(func_patcher.stop)
414
415
416 class checksum_test_TestCase(
417 testscenarios.WithScenarios,
418 testtools.TestCase):
419 """ Base for test cases for `checksum_test` function. """
420
421 scenarios = NotImplemented
422
423 def setUp(self):
424 """ Set up test fixtures. """
425 super().setUp()
426 patch_system_interfaces(self)
427
428 setup_fake_file_fixtures(self)
429 set_fake_file_scenario(self, self.fake_file_scenario_name)
430
431 file_content = self.file_double.fake_file.getvalue().encode('utf-8')
432 self.file_double.fake_file = io.BytesIO(file_content)
433
434 self.set_test_args()
435
436 def set_test_args(self):
437 """ Set the arguments for the test call to the function. """
438 self.test_args = dict(
439 filename=self.file_double.path,
440 hash_name=self.hash_name,
441 )
442
443
444 class checksum_test_SuccessTestCase(checksum_test_TestCase):
445 """ Success test cases for `checksum_test` function. """
446
447 hash_scenarios = [
448 ('md5', {
449 'hash_name': "md5",
450 'test_hash_func': hashlib.md5,
451 }),
452 ('sha1', {
453 'hash_name': "sha1",
454 'test_hash_func': hashlib.sha1,
455 }),
456 ]
457
458 fake_file_scenarios = [
459 (name, scenario)
460 for (name, scenario) in make_fake_file_scenarios().items()
461 if not name.startswith('error')]
462
463 scenarios = testscenarios.multiply_scenarios(
464 hash_scenarios, fake_file_scenarios)
465
466 def test_returns_expected_result_for_input(self):
467 """ Should return expected result for specified inputs. """
468 expected_hash = self.test_hash_func(
469 self.file_double.fake_file.getvalue())
470 expected_result = expected_hash.hexdigest()
471 result = upload_changes.checksum_test(**self.test_args)
472 self.assertEqual(expected_result, result)
473
474
475 class checksum_test_ErrorTestCase(checksum_test_TestCase):
476 """ Error test cases for `checksum_test` function. """
477
478 hash_scenarios = [
479 ('md5', {
480 'hash_name': "md5",
481 }),
482 ]
483
484 fake_file_scenarios = [
485 (name, scenario)
486 for (name, scenario) in make_fake_file_scenarios().items()
487 if name.startswith('error')]
488
489 scenarios = testscenarios.multiply_scenarios(
490 hash_scenarios, fake_file_scenarios)
491
492 def test_calls_sys_exit_if_error_reading_file(self):
493 """ Should call `sys.exit` if unable to read the file. """
494 set_fake_file_scenario(self, 'error-read-denied')
495 with testtools.ExpectedException(FakeSystemExit):
496 upload_changes.checksum_test(**self.test_args)
497 expected_output = textwrap.dedent("""\
498 Can't open {path}
499 """).format(path=self.file_double.path)
500 self.assertIn(expected_output, sys.stdout.getvalue())
501 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
502
503
504 class check_upload_variant_TestCase(
505 testscenarios.WithScenarios,
506 testtools.TestCase):
507 """ Test cases for `check_upload_variant` function. """
508
509 scenarios = [
510 ('simple', {
511 'fields': {
512 'architecture': "foo bar baz",
513 },
514 'expected_result': True,
515 }),
516 ('arch-missing', {
517 'fields': {
518 'spam': "Lorem ipsum dolor sit amet",
519 },
520 'expected_result': False,
521 }),
522 ('source-only', {
523 'fields': {
524 'architecture': "source",
525 },
526 'expected_result': False,
527 }),
528 ('source-and-others', {
529 'fields': {
530 'architecture': "foo source bar",
531 },
532 'expected_result': False,
533 }),
534 ]
535
536 def setUp(self):
537 """ Set up test fixtures. """
538 super().setUp()
539 patch_system_interfaces(self)
540
541 self.set_changes_document(self.fields)
542 self.set_test_args()
543
544 def set_changes_document(self, fields):
545 """ Set the package changes document based on specified fields. """
546 self.test_changes_document = make_changes_document(fields)
547
548 def set_test_args(self):
549 """ Set the arguments for the test call to the function. """
550 self.test_args = {
551 'changes': self.test_changes_document,
552 'debug': False,
553 }
554
555 def test_returns_expected_result_for_changes_document(self):
556 """ Should return expected result for specified changes document. """
557 result = upload_changes.check_upload_variant(**self.test_args)
558 self.assertEqual(self.expected_result, result)
559
560 def test_emits_debug_message_showing_architecture(self):
561 """ Should emit a debug message for the specified architecture. """
562 if 'architecture' not in self.fields:
563 self.skipTest("Architecture field not in this scenario")
564 self.test_args['debug'] = True
565 upload_changes.check_upload_variant(**self.test_args)
566 expected_output = textwrap.dedent("""\
567 D: Architecture: {arch}
568 """).format(arch=self.fields['architecture'])
569 self.assertIn(expected_output, sys.stdout.getvalue())
570
571 def test_emits_debug_message_for_binary_upload(self):
572 """ Should emit a debug message for the specified architecture. """
573 triggers_binaryonly = bool(self.expected_result)
574 if not triggers_binaryonly:
575 self.skipTest("Scenario does not trigger binary-only upload")
576 self.test_args['debug'] = True
577 upload_changes.check_upload_variant(**self.test_args)
578 expected_output = textwrap.dedent("""\
579 D: Doing a binary upload only.
580 """)
581 self.assertIn(expected_output, sys.stdout.getvalue())
582
583
584 class verify_signature_BaseTestCase(
585 testscenarios.WithScenarios,
586 testtools.TestCase):
587 """ Base for test cases for `verify_signature` function. """
588
589 locale_getpreferredencoding_return_value = "UTF-8"
590
591 scenarios = NotImplemented
592
593 default_args = dict(
594 host="foo",
595 check_only=False,
596 allow_unsigned_uploads=False,
597 binary_upload=False,
598 debug=None,
599 )
600
601 def setUp(self):
602 """ Set up test fixtures. """
603 super().setUp()
604 patch_system_interfaces(self)
605
606 patch_locale_getpreferredencoding(self)
607
608 set_config(
609 self,
610 getattr(self, 'config_scenario_name', 'exist-simple'))
611 patch_runtime_config_options(self)
612
613 self.set_changes_file_scenario('okay')
614 self.set_dsc_file_scenario('okay')
615 self.set_test_args()
616
617 setup_fake_file_fixtures(self)
618 set_fake_file_scenario(self, 'exist-minimal')
619
620 self.patch_check_file_signature()
621
622 def patch_check_file_signature(self):
623 """ Patch the `check_file_signature` function for this test case. """
624 func_patcher = unittest.mock.patch.object(
625 dput.crypto, "check_file_signature", autospec=True)
626 func_patcher.start()
627 self.addCleanup(func_patcher.stop)
628
629 def set_changes_file_scenario(self, name):
630 """ Set the changes file scenario for this test case. """
631 file_double = FileDouble(tempfile.mktemp())
632 file_double.set_open_scenario(name)
633 file_double.register_for_testcase(self)
634 self.changes_file_double = file_double
635
636 def set_dsc_file_scenario(self, name):
637 """ Set the source control file scenario for this test case. """
638 file_double = FileDouble(tempfile.mktemp())
639 file_double.set_open_scenario(name)
640 file_double.register_for_testcase(self)
641 self.dsc_file_double = file_double
642
643 def set_test_args(self):
644 """ Set test args for this test case. """
645 extra_args = getattr(self, 'extra_args', {})
646 self.test_args = self.default_args.copy()
647 self.test_args['config'] = self.runtime_config_parser
648 self.test_args['changes_file_path'] = self.changes_file_double.path
649 self.test_args['dsc_file_path'] = self.dsc_file_double.path
650 self.test_args.update(extra_args)
651
652
653 class verify_signature_DebugMessageTestCase(verify_signature_BaseTestCase):
654 """ Test cases for `verify_signature` debug messages. """
655
656 scenarios = [
657 ('default', {}),
658 ]
659
660 def test_emits_debug_message_showing_files(self):
661 """ Should emit a debug message for the specified files. """
662 self.test_args['debug'] = True
663 upload_changes.verify_signature(**self.test_args)
664 expected_output = textwrap.dedent("""\
665 D: upload control file: {changes_path}
666 D: source control file: {dsc_path}
667 """).format(
668 changes_path=self.test_args['changes_file_path'],
669 dsc_path=self.test_args['dsc_file_path'])
670 self.assertIn(expected_output, sys.stdout.getvalue())
671
672
673 class verify_signature_ChecksTestCase(verify_signature_BaseTestCase):
674 """ Test cases for `verify_signature` checks. """
675
676 file_args_scenarios = [
677 ('default', {
678 'expected_checks': ['changes', 'dsc'],
679 }),
680 ('source unsigned', {
681 'extra_args': {
682 'binary_upload': False,
683 'allow_unsigned_uploads': True,
684 },
685 'expected_checks': [],
686 }),
687 ('source check-only', {
688 'extra_args': {
689 'binary_upload': False,
690 'check_only': True,
691 },
692 'expected_checks': ['changes', 'dsc'],
693 }),
694 ('source allow_unsigned_uploads', {
695 'extra_args': {
696 'binary_upload': False,
697 },
698 'config_scenario_name': 'exist-default-not-unsigned',
699 'expected_checks': ['changes', 'dsc'],
700 }),
701 ('binary unsigned', {
702 'extra_args': {
703 'binary_upload': True,
704 'allow_unsigned_uploads': True,
705 },
706 'expected_checks': [],
707 }),
708 ('binary check-only', {
709 'extra_args': {
710 'binary_upload': True,
711 'check_only': True,
712 },
713 'expected_checks': ['changes'],
714 }),
715 ('binary allow_unsigned_uploads', {
716 'extra_args': {
717 'binary_upload': True,
718 },
719 'config_scenario_name': 'exist-default-not-unsigned',
720 'expected_checks': ['changes'],
721 }),
722 ]
723
724 locale_scenarios = make_fake_locale_scenarios()
725
726 scenarios = testscenarios.multiply_scenarios(
727 file_args_scenarios, locale_scenarios)
728
729 def test_checks_changes_signature_only_when_expected(self):
730 """ Should only check the changes document signature if expected. """
731 upload_changes.verify_signature(**self.test_args)
732 registry = FileDouble.get_registry_for_testcase(self)
733 file_double = registry[self.changes_file_double.path]
734 fake_file = file_double.fake_file_opened_with_mode_and_encoding(
735 encoding='UTF-8')
736 check_call = unittest.mock.call(fake_file)
737 if 'changes' in self.expected_checks:
738 self.assertIn(
739 check_call,
740 dput.crypto.check_file_signature.call_args_list)
741 else:
742 self.assertNotIn(
743 check_call,
744 dput.crypto.check_file_signature.call_args_list)
745
746 def test_calls_sys_exit_when_check_file_signature_raises_gpg_error(self):
747 """ Should `sys.exit` when `check_file_signature` raises GPG error. """
748 if not self.expected_checks:
749 self.skipTest("No signature checks requested")
750 dput.crypto.check_file_signature.side_effect = gpg.errors.GPGMEError(0)
751 with testtools.ExpectedException(FakeSystemExit):
752 upload_changes.verify_signature(**self.test_args)
753 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
754
755 def test_raises_same_error_when_check_file_signature_raises_error(self):
756 """
757 Should re-raise `check_file_signature` error when not a GPG error.
758 """
759 if not self.expected_checks:
760 self.skipTest("No signature checks requested")
761 test_error = RuntimeError("whoops")
762 dput.crypto.check_file_signature.side_effect = test_error
763 with testtools.ExpectedException(type(test_error)):
764 upload_changes.verify_signature(**self.test_args)
765
766 def test_checks_dsc_signature_only_when_expected(self):
767 """ Should only check the ‘dsc’ document signature if expected. """
768 upload_changes.verify_signature(**self.test_args)
769 registry = FileDouble.get_registry_for_testcase(self)
770 file_double = registry[self.dsc_file_double.path]
771 fake_file = file_double.fake_file_opened_with_mode_and_encoding(
772 encoding='UTF-8')
773 check_call = unittest.mock.call(fake_file)
774 if 'dsc' in self.expected_checks:
775 self.assertIn(
776 check_call,
777 dput.crypto.check_file_signature.call_args_list)
778 else:
779 self.assertNotIn(
780 check_call,
781 dput.crypto.check_file_signature.call_args_list)
782
783
784 SourceCheckResult = collections.namedtuple(
785 'SourceCheckResult', ['include_orig', 'include_tar'])
786
787
788 class source_check_BaseTestCase(
789 testscenarios.WithScenarios,
790 testtools.TestCase):
791 """ Base for test cases for `source_check` function. """
792
793 def setUp(self):
794 """ Set up test fixtures. """
795 super().setUp()
796 patch_system_interfaces(self)
797
798 self.make_changes_document()
799 self.set_test_args()
800
801 def make_test_version_string(self):
802 """ Make the test version string from component parts. """
803 version_string = self.test_upstream_version
804 if hasattr(self, 'test_epoch'):
805 version_string = "{epoch}:{version}".format(
806 epoch=self.test_epoch,
807 version=version_string)
808 if hasattr(self, 'test_release'):
809 version_string = "{version}-{release}".format(
810 version=version_string,
811 release=self.test_release)
812 return version_string
813
814 def make_changes_document(self):
815 """ Make the fake document for upload changes control file. """
816 fields = {}
817 if (
818 hasattr(self, 'test_upstream_version')
819 and not hasattr(self, 'test_version')
820 ):
821 self.test_version = self.make_test_version_string()
822 if hasattr(self, 'test_version'):
823 fields.update({'version': self.test_version})
824 self.changes_document = make_changes_document(fields)
825
826 def set_test_args(self):
827 self.test_args = {
828 'changes': self.changes_document,
829 'debug': False,
830 }
831
832
833 class source_check_SuccessTestCase(source_check_BaseTestCase):
834 """ Test cases for `source_check` function, success result. """
835
836 default_expected_result = SourceCheckResult(
837 include_orig=False, include_tar=False)
838
839 scenarios = [
840 ('no-version', {
841 'expected_result': default_expected_result,
842 }),
843 ('no-epoch native-version', {
844 'test_upstream_version': "1.2",
845 'expected_result': SourceCheckResult(
846 include_orig=False, include_tar=True),
847 }),
848 ('epoch native-version', {
849 'test_epoch': "3",
850 'test_upstream_version': "1.2",
851 'expected_result': SourceCheckResult(
852 include_orig=False, include_tar=True),
853 }),
854 ('no-epoch debian-release', {
855 'test_upstream_version': "1.2",
856 'test_release': "5",
857 'expected_result': SourceCheckResult(
858 include_orig=False, include_tar=True),
859 }),
860 ('no-epoch version-with-hyphen debian-release', {
861 'test_upstream_version': "1.2-3",
862 'test_release': "5",
863 'expected_result': SourceCheckResult(
864 include_orig=False, include_tar=True),
865 }),
866 ('epoch debian-release', {
867 'test_epoch': "3",
868 'test_upstream_version': "1.2",
869 'test_release': "5",
870 'expected_result': SourceCheckResult(
871 include_orig=False, include_tar=True),
872 }),
873 ('no-epoch new-upstream-version', {
874 'test_upstream_version': "1.2",
875 'test_release': "1",
876 'expected_result': SourceCheckResult(
877 include_orig=True, include_tar=False),
878 }),
879 ('no-epoch new-upstream-version-with-hyphen', {
880 'test_upstream_version': "1.2-3",
881 'test_release': "1",
882 'expected_result': SourceCheckResult(
883 include_orig=True, include_tar=False),
884 }),
885 ('epoch new_upstream-version', {
886 'test_epoch': "3",
887 'test_upstream_version': "1.2",
888 'test_release': "1",
889 'expected_result': SourceCheckResult(
890 include_orig=True, include_tar=False),
891 }),
892 ('no-epoch nmu', {
893 'test_upstream_version': "1.2",
894 'test_release': "4.5",
895 'expected_result': SourceCheckResult(
896 include_orig=False, include_tar=True),
897 }),
898 ('epoch nmu', {
899 'test_epoch': "3",
900 'test_upstream_version': "1.2",
901 'test_release': "4.5",
902 'expected_result': SourceCheckResult(
903 include_orig=False, include_tar=True),
904 }),
905 ('no-epoch nmu before-first-release', {
906 'test_upstream_version': "1.2",
907 'test_release': "0.1",
908 'expected_result': SourceCheckResult(
909 include_orig=True, include_tar=False),
910 }),
911 ('epoch nmu before-first-release', {
912 'test_epoch': "3",
913 'test_upstream_version': "1.2",
914 'test_release': "0.1",
915 'expected_result': SourceCheckResult(
916 include_orig=True, include_tar=False),
917 }),
918 ('no-epoch nmu after-first-release', {
919 'test_upstream_version': "1.2",
920 'test_release': "1.1",
921 'expected_result': SourceCheckResult(
922 include_orig=True, include_tar=False),
923 }),
924 ('epoch nmu after-first-release', {
925 'test_epoch': "3",
926 'test_upstream_version': "1.2",
927 'test_release': "1.1",
928 'expected_result': SourceCheckResult(
929 include_orig=True, include_tar=False),
930 }),
931 ]
932
933 def test_returns_expected_result_for_changes_document(self):
934 """ Should return expected result for specified changes document. """
935 result = upload_changes.source_check(**self.test_args)
936 self.assertEqual(self.expected_result, result)
937
938 def test_emits_version_string_debug_message_only_if_version(self):
939 """ Should emit message for version only if has version. """
940 self.test_args['debug'] = True
941 version = getattr(self, 'test_version', None)
942 message_lead = "D: Package Version:"
943 expected_output = textwrap.dedent("""\
944 {lead} {version}
945 """).format(
946 lead=message_lead, version=version)
947 upload_changes.source_check(**self.test_args)
948 if hasattr(self, 'test_version'):
949 self.assertIn(expected_output, sys.stdout.getvalue())
950 else:
951 self.assertNotIn(message_lead, sys.stdout.getvalue())
952
953 def test_emits_epoch_debug_message_only_if_epoch(self):
954 """ Should emit message for epoch only if has an epoch. """
955 self.test_args['debug'] = True
956 upload_changes.source_check(**self.test_args)
957 expected_output = textwrap.dedent("""\
958 D: Epoch found
959 """)
960 upload_changes.source_check(**self.test_args)
961 if (hasattr(self, 'test_epoch') and hasattr(self, 'test_release')):
962 self.assertIn(expected_output, sys.stdout.getvalue())
963 else:
964 self.assertNotIn(expected_output, sys.stdout.getvalue())
965
966 def test_emits_upstream_version_debug_message_only_if_nonnative(self):
967 """ Should emit message for upstream version only if non-native. """
968 self.test_args['debug'] = True
969 upstream_version = getattr(self, 'test_upstream_version', None)
970 message_lead = "D: Upstream Version:"
971 expected_output = textwrap.dedent("""\
972 {lead} {version}
973 """).format(
974 lead=message_lead, version=upstream_version)
975 upload_changes.source_check(**self.test_args)
976 if hasattr(self, 'test_release'):
977 self.assertIn(expected_output, sys.stdout.getvalue())
978 else:
979 self.assertNotIn(message_lead, sys.stdout.getvalue())
980
981 def test_emits_debian_release_debug_message_only_if_nonnative(self):
982 """ Should emit message for Debian release only if non-native. """
983 self.test_args['debug'] = True
984 debian_release = getattr(self, 'test_release', None)
985 message_lead = "D: Debian Version:"
986 expected_output = textwrap.dedent("""\
987 {lead} {version}
988 """).format(
989 lead=message_lead, version=debian_release)
990 upload_changes.source_check(**self.test_args)
991 if hasattr(self, 'test_release'):
992 self.assertIn(expected_output, sys.stdout.getvalue())
993 else:
994 self.assertNotIn(message_lead, sys.stdout.getvalue())
995
996
997 class source_check_ErrorTestCase(source_check_BaseTestCase):
998 """ Test cases for `source_check` function, error result. """
999
1000 scenarios = [
1001 ('version-characters-invalid', {
1002 'test_version': "inv@l!d",
1003 'expected_error': (
1004 dputhelper.UploadChangesInvalidVersionDputError),
1005 }),
1006 ('version-epoch-characters-invalid', {
1007 'test_version': "1%3:1.2.3-1",
1008 'expected_error': (
1009 dputhelper.UploadChangesInvalidVersionDputError),
1010 }),
1011 ('version-debian-release-characters-invalid', {
1012 'test_version': "3:1.2.3-1@5",
1013 'expected_error': (
1014 dputhelper.UploadChangesInvalidVersionDputError),
1015 }),
1016 ('version-too-many-epochs', {
1017 'test_version': "3:7:1.2.3-1",
1018 'expected_error': (
1019 dputhelper.UploadChangesInvalidVersionDputError),
1020 }),
1021 ]
1022
1023 def test_raises_expected_exception_for_infile(self):
1024 """ Should raise the expected exception for specified input file. """
1025 with testtools.ExpectedException(self.expected_error):
1026 upload_changes.source_check(**self.test_args)
1027
1028
1029 class verify_files_BaseTestCase(testtools.TestCase):
1030 """ Base for test cases for `verify_files` function. """
1031
1032 function_to_test = staticmethod(upload_changes.verify_files)
1033
1034 default_args = dict(
1035 host="foo",
1036 check_only=None,
1037 check_version=None,
1038 allow_unsigned_uploads=None,
1039 debug=None,
1040 )
1041
1042 def setUp(self):
1043 """ Set up test fixtures. """
1044 super().setUp()
1045 patch_system_interfaces(self)
1046
1047 self.file_double_by_path = {}
1048 set_config(self, 'exist-simple')
1049 patch_runtime_config_options(self)
1050
1051 self.set_test_args()
1052
1053 setup_changes_file_fixtures(self)
1054 set_changes_file_scenario(self, 'exist-minimal')
1055 self.test_args.update(dict(
1056 changes_file_directory=os.path.dirname(
1057 self.changes_file_double.path),
1058 changes_file_name=os.path.basename(
1059 self.changes_file_double.path),
1060 ))
1061
1062 patch_os_stat(self)
1063
1064 setup_upload_file_fixtures(self)
1065 self.set_expected_files_to_upload()
1066
1067 self.patch_checksum_test()
1068 self.patch_parse_changes()
1069 self.patch_check_upload_variant()
1070 self.set_expected_binary_upload()
1071 self.set_expected_source_control_file_path()
1072 self.patch_version_check()
1073 self.patch_verify_signature()
1074 self.patch_source_check()
1075
1076 def set_expected_files_to_upload(self):
1077 """ Set the expected `files_to_upload` result for this test case. """
1078 self.expected_files_to_upload = {
1079 path for path in self.fake_upload_file_paths}
1080 self.expected_files_to_upload.add(self.changes_file_double.path)
1081
1082 def patch_checksum_test(self):
1083 """ Patch `checksum_test` function for this test case. """
1084 func_patcher = unittest.mock.patch.object(
1085 upload_changes, "checksum_test", autospec=True)
1086 mock_func = func_patcher.start()
1087 self.addCleanup(func_patcher.stop)
1088
1089 def get_checksum_for_file(path, hash_name):
1090 return self.fake_checksum_by_file[os.path.basename(path)]
1091 mock_func.side_effect = get_checksum_for_file
1092
1093 def set_changes_document(self):
1094 """ Set the changes document for this test case. """
1095 self.changes_document = make_changes_document(
1096 fields={},
1097 upload_params_by_name=self.upload_params_by_name)
1098 self.test_distribution = getattr(self, 'test_distribution', "lorem")
1099 if self.test_distribution is not None:
1100 self.changes_document.add_header(
1101 'distribution', self.test_distribution)
1102 self.runtime_config_parser.set(
1103 self.test_args['host'], 'allowed_distributions',
1104 self.test_distribution)
1105
1106 upload_changes.parse_changes.return_value = self.changes_document
1107
1108 def set_upload_params(self):
1109 """ Set the upload parameters for this test case. """
1110 self.upload_params_by_name = make_upload_files_params(
1111 self.fake_checksum_by_file,
1112 self.fake_size_by_file)
1113
1114 def patch_parse_changes(self):
1115 """ Patch `parse_changes` function for this test case. """
1116 func_patcher = unittest.mock.patch.object(
1117 upload_changes, "parse_changes", autospec=True)
1118 func_patcher.start()
1119 self.addCleanup(func_patcher.stop)
1120
1121 self.set_upload_params()
1122 self.set_changes_document()
1123
1124 def patch_check_upload_variant(self):
1125 """ Patch `check_upload_variant` function for this test case. """
1126 if not hasattr(self, 'check_upload_variant_return_value'):
1127 self.check_upload_variant_return_value = True
1128
1129 func_patcher = unittest.mock.patch.object(
1130 upload_changes, "check_upload_variant", autospec=True,
1131 return_value=self.check_upload_variant_return_value)
1132 func_patcher.start()
1133 self.addCleanup(func_patcher.stop)
1134
1135 def patch_version_check(self):
1136 """ Patch `version_check` function for this test case. """
1137 func_patcher = unittest.mock.patch.object(
1138 upload_changes, "version_check", autospec=True)
1139 func_patcher.start()
1140 self.addCleanup(func_patcher.stop)
1141
1142 def patch_verify_signature(self):
1143 """ Patch `verify_signature` function for this test case. """
1144 func_patcher = unittest.mock.patch.object(
1145 upload_changes, "verify_signature", autospec=True)
1146 func_patcher.start()
1147 self.addCleanup(func_patcher.stop)
1148
1149 def patch_source_check(self):
1150 """ Patch `source_check` function for this test case. """
1151 func_patcher = unittest.mock.patch.object(
1152 upload_changes, "source_check", autospec=True)
1153 mock_func = func_patcher.start()
1154 self.addCleanup(func_patcher.stop)
1155
1156 source_check_result = getattr(
1157 self, 'source_check_result', SourceCheckResult(
1158 include_orig=False, include_tar=False))
1159 mock_func.return_value = source_check_result
1160
1161 def set_test_args(self):
1162 """ Set test args for this test case. """
1163 extra_args = getattr(self, 'extra_args', {})
1164 self.test_args = self.default_args.copy()
1165 self.test_args['config'] = self.runtime_config_parser
1166 self.test_args.update(extra_args)
1167
1168 def set_expected_binary_upload(self):
1169 """ Set expected value for `binary_upload` flag. """
1170 self.expected_binary_upload = self.check_upload_variant_return_value
1171
1172 def set_expected_source_control_file_path(self):
1173 """ Set expected value for source control file path. """
1174 file_name = next(
1175 os.path.basename(file_path)
1176 for file_path in self.fake_upload_file_paths
1177 if file_path.endswith(".dsc"))
1178 if not self.expected_binary_upload:
1179 self.expected_source_control_file_path = os.path.join(
1180 os.path.dirname(self.changes_file_double.path), file_name)
1181 else:
1182 self.expected_source_control_file_path = ""
1183
1184
1185 class verify_files_TestCase(
1186 testscenarios.WithScenarios,
1187 verify_files_BaseTestCase):
1188 """ Test cases for `verify_files` function. """
1189
1190 filenames_scenarios = [
1191 ('default', {}),
1192 ('include foo.tar.gz', {
1193 'additional_file_suffixes': [".tar.gz"],
1194 'source_check_result': SourceCheckResult(
1195 include_orig=False, include_tar=True),
1196 }),
1197 ('include foo.orig.tar.gz', {
1198 'additional_file_suffixes': [".orig.tar.gz"],
1199 'source_check_result': SourceCheckResult(
1200 include_orig=True, include_tar=False),
1201 }),
1202 ('unexpected foo.tar.gz', {
1203 'additional_file_suffixes': [".tar.gz"],
1204 'expected_rejection_message': (
1205 "Package includes a .tar.gz file although"),
1206 }),
1207 ('unexpected foo.orig.tar.gz', {
1208 'additional_file_suffixes': [".orig.tar.gz"],
1209 'expected_rejection_message': (
1210 "Package includes an .orig.tar.gz file although"),
1211 }),
1212 ]
1213
1214 check_upload_variant_scenarios = [
1215 ('source-and-binary', {}),
1216 ('binary-only', {
1217 'check_upload_variant_return_value': False,
1218 }),
1219 ]
1220
1221 distribution_scenarios = [
1222 ('distribution-default', {}),
1223 ('no-distribution', {
1224 'test_distribution': None,
1225 }),
1226 ]
1227
1228 hash_name_scenarios = [
1229 ('hash-name-default', {}),
1230 ('hash-name-default-sha512', {
1231 'config_extras': {
1232 'default': {
1233 'hash': "sha512",
1234 },
1235 'host': {
1236 'hash': None,
1237 },
1238 },
1239 }),
1240 ('hash-name-host-sha512', {
1241 'config_extras': {
1242 'default': {
1243 'hash': "b0gUs",
1244 },
1245 'host': {
1246 'hash': "sha512",
1247 },
1248 },
1249 }),
1250 ]
1251
1252 scenarios = testscenarios.multiply_scenarios(
1253 filenames_scenarios,
1254 check_upload_variant_scenarios,
1255 distribution_scenarios,
1256 hash_name_scenarios,
1257 )
1258
1259 def test_emits_changes_file_path_debug_message(self):
1260 """ Should emit debug message for changes file path. """
1261 self.test_args['debug'] = True
1262 self.function_to_test(**self.test_args)
1263 expected_output = textwrap.dedent("""\
1264 D: Parsing Debian upload changes control file {path}
1265 """).format(path=self.changes_file_double.path)
1266 self.assertIn(expected_output, sys.stdout.getvalue())
1267
1268 def test_calls_sys_exit_if_input_read_denied(self):
1269 """ Should call `sys.exit` if input file read access is denied. """
1270 set_changes_file_scenario(self, 'error-read-denied')
1271 with testtools.ExpectedException(FakeSystemExit):
1272 self.function_to_test(**self.test_args)
1273 expected_output = textwrap.dedent("""\
1274 Can't open {path}
1275 """).format(path=self.changes_file_double.path)
1276 self.assertIn(expected_output, sys.stdout.getvalue())
1277 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1278
1279 def test_calls_parse_changes_with_changes_files(self):
1280 """ Should call `parse_changes` with changes file. """
1281 self.function_to_test(**self.test_args)
1282 file_double = self.changes_file_double
1283 with open(file_double.path, encoding='UTF-8') as expected_file:
1284 upload_changes.parse_changes.assert_called_with(expected_file)
1285
1286 def test_calls_check_upload_variant_with_changes_document(self):
1287 """ Should call `check_upload_variant` with changes document. """
1288 self.function_to_test(**self.test_args)
1289 upload_changes.check_upload_variant.assert_called_with(
1290 self.changes_document, unittest.mock.ANY)
1291
1292 def test_emits_upload_dsc_file_debug_message(self):
1293 """ Should emit debug message for ‘*.dsc’ file. """
1294 if getattr(self, 'check_upload_variant_return_value', True):
1295 self.skipTest("Binary package upload for this scenario")
1296 self.test_args['debug'] = True
1297 self.function_to_test(**self.test_args)
1298 dsc_file_path = next(
1299 os.path.basename(file_path)
1300 for file_path in self.fake_upload_file_paths
1301 if file_path.endswith(".dsc"))
1302 expected_output = textwrap.dedent("""\
1303 D: dsc-File: {path}
1304 """).format(path=dsc_file_path)
1305 self.assertThat(
1306 sys.stdout.getvalue(),
1307 testtools.matchers.Contains(expected_output))
1308
1309 def test_calls_sys_exit_when_source_upload_omits_dsc_file(self):
1310 """ Should call `sys.exit` when source upload omits ‘*.dsc’ file. """
1311 if getattr(self, 'check_upload_variant_return_value', True):
1312 self.skipTest("Binary package upload for this scenario")
1313 self.fake_checksum_by_file = {
1314 file_path: checksum
1315 for (file_path, checksum)
1316 in self.fake_checksum_by_file.items()
1317 if not file_path.endswith(".dsc")
1318 }
1319 self.set_upload_params()
1320 self.set_changes_document()
1321 with testtools.ExpectedException(FakeSystemExit):
1322 self.function_to_test(**self.test_args)
1323 expected_output = textwrap.dedent("""\
1324 Error: no dsc file found in sourceful upload
1325 """)
1326 self.assertThat(
1327 sys.stderr.getvalue(),
1328 testtools.matchers.Contains(expected_output))
1329 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1330
1331 def test_calls_version_check_when_specified_in_config(self):
1332 """ Should call `version_check` when specified in config. """
1333 self.runtime_config_parser.set(
1334 self.test_args['host'], 'check_version', "true")
1335 self.function_to_test(**self.test_args)
1336 upload_changes.version_check.assert_called_with(
1337 files_directory=os.path.dirname(self.changes_file_double.path),
1338 changes=self.changes_document,
1339 debug=self.test_args['debug'])
1340
1341 def test_calls_version_check_when_specified_in_args(self):
1342 """ Should call `version_check` when specified in arguments. """
1343 self.test_args['check_version'] = True
1344 self.function_to_test(**self.test_args)
1345 upload_changes.version_check.assert_called_with(
1346 files_directory=os.path.dirname(self.changes_file_double.path),
1347 changes=self.changes_document,
1348 debug=self.test_args['debug'])
1349
1350 def test_calls_sys_exit_when_host_section_not_in_config(self):
1351 """ Should call `sys.exit` when specified host not in config. """
1352 self.runtime_config_parser.remove_section(self.test_args['host'])
1353 with testtools.ExpectedException(FakeSystemExit):
1354 self.function_to_test(**self.test_args)
1355 expected_output = textwrap.dedent("""\
1356 Error in config file:
1357 No section: ...
1358 """)
1359 self.assertThat(
1360 sys.stderr.getvalue(),
1361 testtools.matchers.DocTestMatches(
1362 expected_output, doctest.ELLIPSIS))
1363 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1364
1365 def test_calls_verify_signature_with_expected_args(self):
1366 """ Should call `verify_signature` with expected args. """
1367 self.function_to_test(**self.test_args)
1368 upload_changes.verify_signature.assert_called_with(
1369 self.test_args['host'],
1370 self.changes_file_double.path,
1371 self.expected_source_control_file_path,
1372 self.runtime_config_parser,
1373 self.test_args['check_only'],
1374 self.test_args['allow_unsigned_uploads'],
1375 unittest.mock.ANY,
1376 self.test_args['debug'])
1377
1378 def test_calls_source_check_with_changes_document(self):
1379 """ Should call `source_check` with changes document. """
1380 self.function_to_test(**self.test_args)
1381 upload_changes.source_check.assert_called_with(
1382 self.changes_document, self.test_args['debug'])
1383
1384 def test_emits_upload_file_path_debug_message(self):
1385 """ Should emit debug message for each upload file path. """
1386 self.test_args['debug'] = True
1387 self.function_to_test(**self.test_args)
1388 for file_path in self.fake_upload_file_paths:
1389 expected_output = textwrap.dedent("""\
1390 D: File to upload: {path}
1391 """).format(path=file_path)
1392 self.expectThat(
1393 sys.stdout.getvalue(),
1394 testtools.matchers.Contains(expected_output))
1395
1396 def test_calls_checksum_test_with_upload_files(self):
1397 """ Should call `checksum_test` with each upload file path. """
1398 self.function_to_test(**self.test_args)
1399 expected_calls = [
1400 unittest.mock.call(file_path, unittest.mock.ANY)
1401 for file_path in self.fake_upload_file_paths]
1402 upload_changes.checksum_test.assert_has_calls(
1403 expected_calls, any_order=True)
1404
1405 def test_calls_checksum_test_with_configured_hash_name(self):
1406 """ Should call `checksum_test` with expected hash name. """
1407 self.function_to_test(**self.test_args)
1408 expected_hash_name = self.runtime_config_parser.get(
1409 self.test_host, 'hash')
1410 expected_calls = [
1411 unittest.mock.call(unittest.mock.ANY, expected_hash_name)
1412 for file_path in self.fake_upload_file_paths]
1413 upload_changes.checksum_test.assert_has_calls(
1414 expected_calls, any_order=True)
1415
1416 def set_bogus_file_checksums(self):
1417 """ Set bogus file checksums that will not match. """
1418 self.fake_checksum_by_file = {
1419 file_name: self.getUniqueString()
1420 for file_name in self.fake_checksum_by_file}
1421
1422 def test_emits_checksum_okay_debug_message(self):
1423 """ Should emit debug message checksum okay for each file. """
1424 self.test_args['debug'] = True
1425 self.function_to_test(**self.test_args)
1426 for file_path in self.fake_upload_file_paths:
1427 expected_output = textwrap.dedent("""\
1428 D: Checksum for {path} is fine
1429 """).format(path=file_path)
1430 self.expectThat(
1431 sys.stdout.getvalue(),
1432 testtools.matchers.Contains(expected_output))
1433
1434 def test_emits_checksum_mismatch_debug_message(self):
1435 """ Should emit debug message when a checksum does not match. """
1436 self.test_args['debug'] = True
1437 self.set_bogus_file_checksums()
1438 with testtools.ExpectedException(FakeSystemExit):
1439 self.function_to_test(**self.test_args)
1440 expected_output = textwrap.dedent("""\
1441 ...
1442 D: Checksum from .changes: ...
1443 D: Generated Checksum: ...
1444 ...
1445 """)
1446 self.assertThat(
1447 sys.stdout.getvalue(),
1448 testtools.matchers.DocTestMatches(
1449 expected_output, doctest.ELLIPSIS))
1450
1451 def test_calls_sys_exit_when_checksum_mismatch(self):
1452 """ Should call `sys.exit` when a checksum does not match. """
1453 specified_checksum_by_file = self.fake_checksum_by_file
1454 self.set_bogus_file_checksums()
1455 with testtools.ExpectedException(FakeSystemExit):
1456 self.function_to_test(**self.test_args)
1457
1458 expected_output_for_files = [
1459 textwrap.dedent("""\
1460 Checksum doesn't match for {file_name}
1461 """).format(
1462 file_name=os.path.join(
1463 os.path.dirname(self.changes_file_double.path),
1464 file_name),
1465 specified_hash=specified_hash,
1466 computed_hash=self.fake_checksum_by_file[file_name])
1467 for (file_name, specified_hash)
1468 in specified_checksum_by_file.items()]
1469 self.assertThat(
1470 sys.stdout.getvalue(),
1471 testtools.matchers.MatchesAny(*[
1472 testtools.matchers.Contains(expected_output)
1473 for expected_output in expected_output_for_files]))
1474 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1475
1476 def test_calls_os_stat_with_upload_files(self):
1477 """ Should call `os.stat` with each upload file path. """
1478 self.function_to_test(**self.test_args)
1479 expected_calls = [
1480 unittest.mock.call(file_path)
1481 for file_path in self.fake_upload_file_paths]
1482 os.stat.assert_has_calls(expected_calls, any_order=True)
1483
1484 def set_bogus_file_sizes(self):
1485 """ Set bogus file sizes that will not match. """
1486 file_double_registry = FileDouble.get_registry_for_testcase(self)
1487 for file_name in self.fake_size_by_file:
1488 bogus_size = self.getUniqueInteger()
1489 self.fake_size_by_file[file_name] = bogus_size
1490 file_path = os.path.join(
1491 os.path.dirname(self.changes_file_double.path),
1492 file_name)
1493 file_double = file_double_registry[file_path]
1494 file_double.stat_result = file_double.stat_result._replace(
1495 st_size=bogus_size)
1496
1497 def test_emits_size_mismatch_debug_message(self):
1498 """ Should emit debug message when a size does not match. """
1499 self.test_args['debug'] = True
1500 self.set_bogus_file_sizes()
1501 self.function_to_test(**self.test_args)
1502 expected_output = textwrap.dedent("""\
1503 ...
1504 D: size from .changes: ...
1505 D: calculated size: ...
1506 ...
1507 """)
1508 self.assertThat(
1509 sys.stdout.getvalue(),
1510 testtools.matchers.DocTestMatches(
1511 expected_output, doctest.ELLIPSIS))
1512
1513 def test_emits_size_mismatch_message_for_each_file(self):
1514 """ Should emit error message for each file with size mismatch. """
1515 self.set_bogus_file_sizes()
1516 self.function_to_test(**self.test_args)
1517 for file_path in self.fake_upload_file_paths:
1518 expected_output = textwrap.dedent("""\
1519 size doesn't match for {path}
1520 """).format(path=file_path)
1521 self.expectThat(
1522 sys.stdout.getvalue(),
1523 testtools.matchers.Contains(expected_output))
1524
1525 def test_emits_rejection_warning_when_unexpected_tarball(self):
1526 """ Should emit warning of rejection when unexpected tarball. """
1527 if not hasattr(self, 'expected_rejection_message'):
1528 self.skipTest("No rejection message expected")
1529 self.function_to_test(**self.test_args)
1530 sys.stderr.write("calls: {calls!r}\n".format(
1531 calls=sys.stdout.write.mock_calls))
1532 self.assertThat(
1533 sys.stdout.getvalue(),
1534 testtools.matchers.Contains(self.expected_rejection_message))
1535
1536 def test_raises_error_when_distribution_mismatch(self):
1537 """ Should raise error when distribution mismatch against allowed. """
1538 if not getattr(self, 'test_distribution', None):
1539 self.skipTest("No distribution set for this test case")
1540 self.runtime_config_parser.set(
1541 self.test_args['host'], 'allowed_distributions',
1542 "dolor sit amet")
1543 with testtools.ExpectedException(dputhelper.DputUploadFatalError):
1544 self.function_to_test(**self.test_args)
1545
1546 def test_emits_changes_file_upload_debug_message(self):
1547 """ Should emit debug message for upload of changes file. """
1548 self.test_args['debug'] = True
1549 self.function_to_test(**self.test_args)
1550 expected_output = textwrap.dedent("""\
1551 D: File to upload: {path}
1552 """).format(path=self.changes_file_double.path)
1553 self.assertIn(expected_output, sys.stdout.getvalue())
1554
1555 def test_returns_expected_files_to_upload_collection(self):
1556 """ Should return expected `files_to_upload` collection value. """
1557 result = self.function_to_test(**self.test_args)
1558 expected_result = self.expected_files_to_upload
1559 self.assertEqual(expected_result, set(result))
1560
1561
1562 class verify_files_UnusualPreferredEncodingTestCase(
1563 testscenarios.WithScenarios,
1564 verify_files_BaseTestCase):
1565 """
1566 Test cases for `verify_files` function when preferred encoding is unusual.
1567 """
1568
1569 locale_getpreferredencoding_return_value = "ANSI_X3.4-1968"
1570
1571 scenarios = [
1572 ('default', {}),
1573 ]
1574
1575 def setUp(self):
1576 """ Set up test fixtures. """
1577 patch_locale_getpreferredencoding(self)
1578 super().setUp()
1579
1580 set_changes_file_scenario(self, 'exist-needs-utf8')
1581 self.test_args.update(dict(
1582 changes_file_directory=os.path.dirname(
1583 self.changes_file_double.path),
1584 changes_file_name=os.path.basename(
1585 self.changes_file_double.path),
1586 ))
1587
1588 def test_calls_parse_changes_with_changes_files(self):
1589 """ Should call `parse_changes` with changes file. """
1590 self.function_to_test(**self.test_args)
1591 file_double = self.changes_file_double
1592 with open(file_double.path, encoding='UTF-8') as expected_file:
1593 upload_changes.parse_changes.assert_called_with(expected_file)
1594
1595
1596 class guess_upload_host_TestCase(
1597 testscenarios.WithScenarios,
1598 testtools.TestCase):
1599 """ Test cases for `guess_upload_host` function. """
1600
1601 changes_file_scenarios = [
1602 ('no-distribution', {
1603 'fake_file': io.StringIO(textwrap.dedent("""\
1604 Files:
1605 Lorem ipsum dolor sit amet
1606 """)),
1607 }),
1608 ('distribution-spam', {
1609 'fake_file': io.StringIO(textwrap.dedent("""\
1610 Distribution: spam
1611 Files:
1612 Lorem ipsum dolor sit amet
1613 """)),
1614 }),
1615 ('distribution-beans', {
1616 'fake_file': io.StringIO(textwrap.dedent("""\
1617 Distribution: beans
1618 Files:
1619 Lorem ipsum dolor sit amet
1620 """)),
1621 }),
1622 ('needs-utf8 no-distribution', {
1623 'fake_file': io.StringIO(textwrap.dedent("""\
1624 Files:
1625 Lórem ipsüm dolôr sìt āmet
1626 """)),
1627 }),
1628 ]
1629
1630 scenarios = [
1631 ('distribution-found-of-one', {
1632 'changes_file_scenario_name': "distribution-spam",
1633 'test_distribution': "spam",
1634 'config_scenario_name': "exist-distribution-one",
1635 'expected_host': "foo",
1636 }),
1637 ('distribution-notfound-of-one', {
1638 'changes_file_scenario_name': "distribution-beans",
1639 'test_distribution': "beans",
1640 'config_scenario_name': "exist-distribution-one",
1641 'config_default_default_host_main': None,
1642 'expected_host': "ftp-master",
1643 }),
1644 ('distribution-first-of-three', {
1645 'changes_file_scenario_name': "distribution-spam",
1646 'test_distribution': "spam",
1647 'config_scenario_name': "exist-distribution-three",
1648 'expected_host': "foo",
1649 }),
1650 ('distribution-last-of-three', {
1651 'changes_file_scenario_name': "distribution-beans",
1652 'test_distribution': "beans",
1653 'config_scenario_name': "exist-distribution-three",
1654 'expected_host': "foo",
1655 }),
1656 ('no-configured-distribution', {
1657 'changes_file_scenario_name': "distribution-beans",
1658 'config_scenario_name': "exist-distribution-none",
1659 'config_default_default_host_main': None,
1660 'expected_host': "ftp-master",
1661 }),
1662 ('no-distribution', {
1663 'changes_file_scenario_name': "no-distribution",
1664 'config_scenario_name': "exist-simple",
1665 'config_default_default_host_main': None,
1666 'expected_host': "ftp-master",
1667 }),
1668 ('no-distribution nonstandard-default-section', {
1669 'config_scenario_name': (
1670 "exist-simple-nonstandard-default-section"),
1671 'config_extras': {
1672 'default': {
1673 'default_host_main': "pharetra",
1674 },
1675 },
1676 'config_default_default_host_main': None,
1677 'expected_host': "pharetra",
1678 }),
1679 ('default-distribution', {
1680 'config_scenario_name': "exist-default-distribution-only",
1681 'config_default_default_host_main': "consecteur",
1682 'expected_host': "consecteur",
1683 }),
1684 ('unusual-preferred-encoding no-distribution', {
1685 'locale_preferredencoding_return_value': "ANSI_X3.4-1968",
1686 'changes_file_scenario_name': "needs-utf8 no-distribution",
1687 'config_scenario_name': "exist-simple",
1688 'config_default_default_host_main': None,
1689 'expected_host': "ftp-master",
1690 }),
1691 ]
1692
1693 def setUp(self):
1694 """ Set up test fixtures. """
1695 super().setUp()
1696 patch_system_interfaces(self)
1697 if hasattr(self, 'locale_preferredencoding_return_value'):
1698 patch_locale_getpreferredencoding(
1699 self, encoding=self.locale_preferredencoding_return_value)
1700
1701 set_config(
1702 self,
1703 getattr(self, 'config_scenario_name', 'exist-minimal'))
1704 patch_runtime_config_options(self)
1705
1706 self.setup_changes_file_fixtures()
1707 set_changes_file_scenario(
1708 self,
1709 getattr(self, 'changes_file_scenario_name', 'no-distribution'))
1710
1711 self.set_test_args()
1712
1713 def set_test_args(self):
1714 """ Set the arguments for the test call to the function. """
1715 self.test_args = dict(
1716 changes_file_directory=os.path.dirname(
1717 self.changes_file_double.path),
1718 changes_file_name=os.path.basename(
1719 self.changes_file_double.path),
1720 config=self.runtime_config_parser,
1721 debug=False,
1722 )
1723
1724 def setup_changes_file_fixtures(self):
1725 """ Set up fixtures for fake changes file. """
1726 file_path = make_changes_file_path()
1727
1728 scenarios = [s for (__, s) in self.changes_file_scenarios]
1729 for scenario in scenarios:
1730 scenario['file_double'] = FileDouble(
1731 file_path, scenario['fake_file'])
1732 setup_file_double_behaviour(
1733 self,
1734 get_file_doubles_from_fake_file_scenarios(scenarios))
1735
1736 def test_calls_sys_exit_if_read_denied(self):
1737 """ Should call `sys.exit` if read permission denied. """
1738 self.changes_file_double.set_os_access_scenario('denied')
1739 self.changes_file_double.set_open_scenario('read_denied')
1740 with testtools.ExpectedException(FakeSystemExit):
1741 upload_changes.guess_upload_host(**self.test_args)
1742 expected_output = textwrap.dedent("""\
1743 Can't open {path}
1744 """).format(path=self.changes_file_double.path)
1745 self.assertIn(expected_output, sys.stdout.getvalue())
1746 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1747
1748 def test_returns_expected_host(self):
1749 """ Should return expected host value. """
1750 result = upload_changes.guess_upload_host(**self.test_args)
1751 self.assertEqual(self.expected_host, result)
1752
1753 def test_emits_debug_message_for_host(self):
1754 """ Should emit a debug message for the discovered host. """
1755 self.test_args['debug'] = True
1756 config_parser = self.runtime_config_parser
1757 if not (
1758 config_parser.has_section(self.expected_host)
1759 and config_parser.get(self.expected_host, 'distributions')):
1760 self.skipTest("No distributions specified")
1761 upload_changes.guess_upload_host(**self.test_args)
1762 expected_output = textwrap.dedent("""\
1763 D: guessing host {host} based on distribution {dist}
1764 """).format(
1765 host=self.expected_host, dist=self.test_distribution)
1766 self.assertIn(expected_output, sys.stdout.getvalue())
1767
1768
1769 class version_check_TestCase(
1770 testscenarios.WithScenarios,
1771 testtools.TestCase):
1772 """ Base for test cases for `version_check` function. """
1773
1774 package_file_scenarios = [
1775 ('package-arch {arch}'.format(arch=arch), {
1776 'file_double': FileDouble(),
1777 'field_output': textwrap.dedent("""\
1778 Architecture: {arch}
1779 """).format(arch=arch),
1780 })
1781 for arch in ["all", "foo", "bar", "baz"]]
1782
1783 version_scenarios = [
1784 ('version none', {
1785 'upload_version': "lorem",
1786 }),
1787 ('version equal', {
1788 'upload_version': "lorem",
1789 'installed_version': "lorem",
1790 }),
1791 ('version unequal', {
1792 'upload_version': "lorem",
1793 'installed_version': "ipsum",
1794 }),
1795 ]
1796
1797 scenarios = NotImplemented
1798
1799 def setUp(self):
1800 """ Set up test fixtures. """
1801 super().setUp()
1802 patch_system_interfaces(self)
1803
1804 self.patch_dpkg_program_file()
1805
1806 if not hasattr(self, 'test_architectures'):
1807 self.test_architectures = []
1808
1809 setup_changes_file_fixtures(self)
1810 self.set_changes_file_scenario('no-format')
1811
1812 self.set_upload_files()
1813 self.set_changes_document()
1814
1815 self.set_test_args()
1816
1817 patch_subprocess_popen(self)
1818 self.set_dpkg_print_architecture_scenario('simple')
1819 self.set_dpkg_field_scenario('simple')
1820 self.set_dpkg_status_scenario('simple')
1821
1822 def set_changes_file_scenario(self, name):
1823 """ Set the package changes document based on scenario name. """
1824 scenarios = make_changes_file_scenarios()
1825 scenario = dict(scenarios)[name]
1826 self.changes_file_double = scenario['file_double']
1827
1828 def set_upload_files(self):
1829 """ Set the files marked for upload in this scenario. """
1830 package_file_suffix = ".deb"
1831 file_suffix_by_arch = {
1832 arch: "_{arch}{suffix}".format(
1833 arch=arch, suffix=package_file_suffix)
1834 for arch in self.test_architectures}
1835 self.additional_file_suffixes = list(file_suffix_by_arch.values())
1836
1837 setup_upload_file_fixtures(self)
1838
1839 registry = FileDouble.get_registry_for_testcase(self)
1840 for path in self.fake_upload_file_paths:
1841 for (arch, suffix) in file_suffix_by_arch.items():
1842 if path.endswith(suffix):
1843 file_double = registry[path]
1844 package_file_scenario = dict(self.package_file_scenarios)[
1845 "package-arch {arch}".format(arch=arch)]
1846 package_file_scenario['file_double'] = file_double
1847
1848 def set_changes_document(self):
1849 """ Set the changes document for this test case. """
1850 upload_params_by_name = make_upload_files_params(
1851 self.fake_checksum_by_file, self.fake_size_by_file)
1852 self.changes_document = make_changes_document(
1853 fields={
1854 'architecture': " ".join(self.test_architectures),
1855 },
1856 upload_params_by_name=upload_params_by_name)
1857
1858 def set_test_args(self):
1859 """ Set the arguments for the test call to the function. """
1860 self.test_args = dict(
1861 files_directory=os.path.dirname(self.changes_file_double.path),
1862 changes=self.changes_document,
1863 debug=False,
1864 )
1865
1866 def patch_dpkg_program_file(self):
1867 """ Patch the Dpkg program file for this test case. """
1868 file_path = "/usr/bin/dpkg"
1869 file_double = FileDouble(file_path)
1870 file_double.register_for_testcase(self)
1871 self.dpkg_program_file_double = file_double
1872
1873 def set_dpkg_print_architecture_scenario(self, name):
1874 """ Set the scenario for ‘dpkg --print-architecture’ behaviour. """
1875 argv = (
1876 os.path.basename(self.dpkg_program_file_double.path),
1877 "--print-architecture")
1878 double = SubprocessDouble(
1879 self.dpkg_program_file_double.path, argv=argv)
1880 double.register_for_testcase(self)
1881 double.set_subprocess_popen_scenario('success')
1882 double.set_stdout_content(self.host_architecture)
1883 self.dpkg_print_architecture_subprocess_double = double
1884
1885 def set_dpkg_field_scenario(self, name):
1886 """ Set the scenario for ‘dpkg --field’ behaviour. """
1887 for arch in self.test_architectures:
1888 package_file_scenario = dict(self.package_file_scenarios)[
1889 'package-arch {arch}'.format(arch=arch)]
1890 upload_file_path = package_file_scenario['file_double'].path
1891 argv = (
1892 os.path.basename(self.dpkg_program_file_double.path),
1893 "--field", upload_file_path)
1894 double = SubprocessDouble(
1895 self.dpkg_program_file_double.path, argv=argv)
1896 double.register_for_testcase(self)
1897 double.set_subprocess_popen_scenario('success')
1898
1899 package_file_scenario['package_name'] = make_unique_slug(self)
1900 package_file_scenario['package_version'] = self.upload_version
1901 field_output = package_file_scenario['field_output']
1902 field_output += textwrap.dedent("""\
1903 Package: {name}
1904 Version: {version}
1905 """).format(
1906 name=package_file_scenario['package_name'],
1907 version=package_file_scenario['package_version'])
1908 double.set_stdout_content(field_output)
1909
1910 def set_dpkg_status_scenario(self, name):
1911 """ Set the scenario for ‘dpkg -s’ behaviour. """
1912 for arch in self.test_architectures:
1913 package_file_scenario = dict(self.package_file_scenarios)[
1914 'package-arch {arch}'.format(arch=arch)]
1915 argv = (
1916 os.path.basename(self.dpkg_program_file_double.path),
1917 "-s", package_file_scenario['package_name'])
1918 double = SubprocessDouble(
1919 self.dpkg_program_file_double.path, argv=argv)
1920 double.register_for_testcase(self)
1921 double.set_subprocess_popen_scenario('success')
1922
1923 version_field = ""
1924 if hasattr(self, 'installed_version'):
1925 version_field = "Version: {version}\n".format(
1926 version=self.installed_version)
1927 status_output = textwrap.dedent("""\
1928 {version}""").format(version=version_field)
1929 double.set_stdout_content(status_output)
1930
1931 def get_subprocess_doubles_matching_argv_prefix(self, argv_prefix):
1932 """ Get subprocess doubles for this test case matching the argv. """
1933 subprocess_registry = SubprocessDouble.get_registry_for_testcase(self)
1934 subprocess_doubles = [
1935 double for double in subprocess_registry.values()
1936 if double.argv[:len(argv_prefix)] == argv_prefix
1937 ]
1938 return subprocess_doubles
1939
1940
1941 class version_check_ConsoleEncodingTestCase(version_check_TestCase):
1942 """ Test cases for `version_check` with various console text encodings. """
1943
1944 locale_scenarios = make_fake_locale_scenarios()
1945
1946 host_architecture_scenarios = [
1947 ('host-arch foo', {
1948 'host_architecture': "foo",
1949 }),
1950 ]
1951
1952 scenarios = testscenarios.multiply_scenarios(
1953 locale_scenarios,
1954 host_architecture_scenarios,
1955 version_check_TestCase.version_scenarios)
1956
1957 def setUp(self):
1958 """ Set up fixtures for this test case. """
1959 super().setUp()
1960 patch_locale_environment_variables(self)
1961
1962 def test_emits_debug_message_showing_architecture(self):
1963 """ Should emit a debug message for the specified architecture. """
1964 test_architecture = self.getUniqueString()
1965 subprocess_double = self.dpkg_print_architecture_subprocess_double
1966 subprocess_double.set_stdout_content(
1967 "{arch}\n".format(arch=test_architecture))
1968 self.test_args['debug'] = True
1969 with contextlib.suppress(FakeSystemExit):
1970 upload_changes.version_check(**self.test_args)
1971 expected_output = textwrap.dedent("""\
1972 D: detected architecture: '{arch}'
1973 """).format(arch=test_architecture)
1974 self.assertIn(expected_output, sys.stdout.getvalue())
1975
1976
1977 class version_check_ArchitectureMatchTestCase(version_check_TestCase):
1978 """ Test cases for `version_check` when host architecture matches. """
1979
1980 host_architecture_scenarios = [
1981 ('host-arch foo', {
1982 'host_architecture': "foo",
1983 }),
1984 ]
1985
1986 package_architecture_scenarios = [
1987 ('one binary', {
1988 'test_architectures': ["foo"],
1989 }),
1990 ('three binaries', {
1991 'test_architectures': ["foo", "bar", "baz"],
1992 }),
1993 ('all-arch binary', {
1994 'test_architectures': ["all"],
1995 }),
1996 ]
1997
1998 scenarios = testscenarios.multiply_scenarios(
1999 host_architecture_scenarios,
2000 package_architecture_scenarios,
2001 version_check_TestCase.version_scenarios)
2002
2003 def test_emits_debug_message_showing_architecture(self):
2004 """ Should emit a debug message for the specified architecture. """
2005 test_architecture = self.getUniqueString()
2006 subprocess_double = self.dpkg_print_architecture_subprocess_double
2007 subprocess_double.set_stdout_content(
2008 "{arch}\n".format(arch=test_architecture))
2009 self.test_args['debug'] = True
2010 with contextlib.suppress(FakeSystemExit):
2011 upload_changes.version_check(**self.test_args)
2012 expected_output = textwrap.dedent("""\
2013 D: detected architecture: '{arch}'
2014 """).format(arch=test_architecture)
2015 self.assertIn(expected_output, sys.stdout.getvalue())
2016
2017 def test_omits_stderr_output_message_when_not_debug(self):
2018 """ Should omit any debug messages for `stderr` output. """
2019 doubles = self.get_subprocess_doubles_matching_argv_prefix(
2020 ("dpkg", "--print-architecture"))
2021 if self.test_architectures:
2022 doubles.extend(
2023 self.get_subprocess_doubles_matching_argv_prefix(
2024 ("dpkg", "--field")))
2025 doubles.extend(
2026 self.get_subprocess_doubles_matching_argv_prefix(
2027 ("dpkg", "-s")))
2028 for double in doubles:
2029 double.set_stderr_content(self.getUniqueString())
2030 self.test_args['debug'] = False
2031 with contextlib.suppress(FakeSystemExit):
2032 upload_changes.version_check(**self.test_args)
2033 message_snippet = " stderr output:"
2034 self.assertNotIn(message_snippet, sys.stdout.getvalue())
2035
2036 def test_emits_debug_message_for_architecture_stderr_output(self):
2037 """ Should emit debug message for Dpkg architecture `stderr`. """
2038 subprocess_double = self.dpkg_print_architecture_subprocess_double
2039 test_output = self.getUniqueString()
2040 subprocess_double.set_stderr_content(test_output)
2041 self.test_args['debug'] = True
2042 with contextlib.suppress(FakeSystemExit):
2043 upload_changes.version_check(**self.test_args)
2044 expected_output = textwrap.dedent("""\
2045 D: dpkg-architecture stderr output: {output!r}
2046 """).format(output=test_output)
2047 self.assertIn(expected_output, sys.stdout.getvalue())
2048
2049 def test_emits_debug_message_for_field_stderr_output(self):
2050 """ Should emit debug message for Dpkg fields `stderr`. """
2051 test_output = self.getUniqueString()
2052 for double in self.get_subprocess_doubles_matching_argv_prefix(
2053 ("dpkg", "--field")):
2054 double.set_stderr_content(test_output)
2055 self.test_args['debug'] = True
2056 with contextlib.suppress(FakeSystemExit):
2057 upload_changes.version_check(**self.test_args)
2058 expected_output = textwrap.dedent("""\
2059 D: dpkg stderr output: {output!r}
2060 """).format(output=test_output)
2061 self.assertIn(expected_output, sys.stdout.getvalue())
2062
2063 def test_emits_debug_message_for_status_stderr_output(self):
2064 """ Should emit debug message for Dpkg status `stderr`. """
2065 test_output = self.getUniqueString()
2066 for double in self.get_subprocess_doubles_matching_argv_prefix(
2067 ("dpkg", "-s")):
2068 double.set_stderr_content(test_output)
2069 self.test_args['debug'] = True
2070 with contextlib.suppress(FakeSystemExit):
2071 upload_changes.version_check(**self.test_args)
2072 expected_output = textwrap.dedent("""\
2073 D: dpkg stderr output: {output!r}
2074 """).format(output=test_output)
2075 self.assertIn(expected_output, sys.stdout.getvalue())
2076
2077 def test_emits_expected_debug_message_for_installed_version(self):
2078 """ Should emit debug message for package installed version. """
2079 self.test_args['debug'] = True
2080 message_lead = "D: Installed-Version:"
2081 if hasattr(self, 'installed_version'):
2082 upload_changes.version_check(**self.test_args)
2083 expected_output = "{lead} {version}".format(
2084 lead=message_lead, version=self.installed_version)
2085 self.assertIn(expected_output, sys.stdout.getvalue())
2086 else:
2087 with testtools.ExpectedException(FakeSystemExit):
2088 upload_changes.version_check(**self.test_args)
2089 self.assertNotIn(message_lead, sys.stdout.getvalue())
2090
2091 def test_emits_expected_debug_message_for_upload_version(self):
2092 """ Should emit debug message for package upload version. """
2093 self.test_args['debug'] = True
2094 message_lead = "D: Check-Version:"
2095 if hasattr(self, 'installed_version'):
2096 upload_changes.version_check(**self.test_args)
2097 expected_output = "{lead} {version}".format(
2098 lead=message_lead, version=self.upload_version)
2099 self.assertIn(expected_output, sys.stdout.getvalue())
2100 else:
2101 with testtools.ExpectedException(FakeSystemExit):
2102 upload_changes.version_check(**self.test_args)
2103 self.assertNotIn(message_lead, sys.stdout.getvalue())
2104
2105
2106 class version_check_ArchitectureMismatchTestCase(version_check_TestCase):
2107 """ Test cases for `version_check` when no match to host architecture. """
2108
2109 host_architecture_scenarios = [
2110 ('host-arch spam', {
2111 'host_architecture': "spam",
2112 }),
2113 ]
2114
2115 package_architecture_scenarios = [
2116 ('one binary', {
2117 'test_architectures': ["foo"],
2118 }),
2119 ]
2120
2121 scenarios = testscenarios.multiply_scenarios(
2122 host_architecture_scenarios,
2123 package_architecture_scenarios,
2124 version_check_TestCase.version_scenarios)
2125
2126 def test_emits_debug_message_stating_arch_mismatch(self):
2127 """ Should emit a debug message stating the architecture mismatch. """
2128 self.test_args['debug'] = True
2129 upload_changes.version_check(**self.test_args)
2130 file_scenarios = dict(self.package_file_scenarios)
2131 for arch in self.test_architectures:
2132 file_scenario_name = "package-arch {arch}".format(arch=arch)
2133 file_scenario = file_scenarios[file_scenario_name]
2134 file_double = file_scenario['file_double']
2135 expected_output = textwrap.dedent("""\
2136 D: not install-checking {path} due to arch mismatch
2137 """).format(path=file_double.path)
2138 self.expectThat(
2139 sys.stdout.getvalue(),
2140 testtools.matchers.Contains(expected_output))
2141
2142
2143 class version_check_PackageNotInstalledTestCase(version_check_TestCase):
2144 """ Test cases for `version_check` when package is not installed. """
2145
2146 host_architecture_scenarios = [
2147 ('host-arch foo', {
2148 'host_architecture': "foo",
2149 }),
2150 ]
2151
2152 package_architecture_scenarios = [
2153 ('one binary', {
2154 'test_architectures': ["foo"],
2155 }),
2156 ]
2157
2158 version_scenarios = [
2159 ('version none', {
2160 'upload_version': "lorem",
2161 }),
2162 ]
2163
2164 scenarios = testscenarios.multiply_scenarios(
2165 host_architecture_scenarios,
2166 package_architecture_scenarios,
2167 version_scenarios)
2168
2169 def test_emits_message_stating_package_not_installed(self):
2170 """ Should emit message stating package is not installed. """
2171 with testtools.ExpectedException(FakeSystemExit):
2172 upload_changes.version_check(**self.test_args)
2173 expected_output = textwrap.dedent("""\
2174 Uninstalled Package. Test it before uploading it.
2175 """)
2176 self.assertIn(expected_output, sys.stdout.getvalue())
2177
2178 def test_calls_sys_exit_with_error_status(self):
2179 """ Should call `sys.exit` with exit status indicating error. """
2180 with testtools.ExpectedException(FakeSystemExit):
2181 upload_changes.version_check(**self.test_args)
2182 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
2183
2184
2185 # Copyright © 2015–2026 Ben Finney <[email protected]>
2186 #
2187 # This is free software: you may copy, modify, and/or distribute this work
2188 # under the terms of the GNU General Public License as published by the
2189 # Free Software Foundation; version 3 of that license or any later version.
2190 # No warranty expressed or implied. See the file ‘LICENSE.GPL-3’ for details.
2191
2192
2193 # Local variables:
2194 # coding: utf-8
2195 # mode: python
2196 # End:
2197 # vim: fileencoding=utf-8 filetype=python :