Debian Codegraph @

test/test_dcut.py

raw
1 # test/test_dcut.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 ‘dcut’ module. """
9
10 import contextlib
11 import copy
12 import doctest
13 import io
14 import itertools
15 import os
16 import shutil
17 import subprocess
18 import sys
19 import tempfile
20 import textwrap
21 import unittest.mock
22
23 import testscenarios
24 import testtools
25
26 import dput.configfile
27 from dput.control_file import upload_changes
28 import dput.dcut
29 import dput.dput
30 from dput.helper import dputhelper
31
32 from . import test_dput_main
33 from .control_file.test_upload_changes import (
34 make_changes_file_scenarios,
35 patch_parse_changes,
36 set_changes_file_scenario,
37 )
38 from .helper import (
39 ARG_MORE,
40 EXIT_STATUS_FAILURE,
41 EXIT_STATUS_SUCCESS,
42 FakeSystemExit,
43 FileDouble,
44 PasswdEntry,
45 SubprocessDouble,
46 patch_etc_mailname,
47 patch_locale_getpreferredencoding,
48 patch_os_environ,
49 patch_os_getpid,
50 patch_os_getuid,
51 patch_os_rmdir,
52 patch_os_unlink,
53 patch_pwd_getpwuid,
54 patch_shutil_rmtree,
55 patch_subprocess_check_call,
56 patch_subprocess_popen,
57 patch_sys_argv,
58 patch_system_interfaces,
59 patch_tempfile_mkdtemp,
60 patch_time_time,
61 setup_file_double_behaviour,
62 setup_subprocess_double_behaviour,
63 )
64 from .test_configfile import (
65 patch_active_config_files,
66 patch_read_configs,
67 set_config,
68 )
69 from .test_dputhelper import (
70 patch_getopt,
71 )
72
73
74 dummy_pwent = PasswdEntry(
75 pw_name="lorem",
76 pw_passwd="!",
77 pw_uid=1,
78 pw_gid=1,
79 pw_gecos="Lorem Ipsum,spam,eggs,beans",
80 pw_dir=tempfile.mktemp(),
81 pw_shell=tempfile.mktemp())
82
83
84 def patch_getoptions(testcase):
85 """ Patch the `getoptions` function for this test case. """
86 default_options = {
87 'debug': False,
88 'simulate': False,
89 'config': None,
90 'host': "foo",
91 'commandline_passive': None,
92 'changes': None,
93 'filetoupload': None,
94 'filetocreate': None,
95 }
96
97 if not hasattr(testcase, 'getoptions_opts'):
98 testcase.getoptions_opts = {}
99 if not hasattr(testcase, 'getoptions_args'):
100 testcase.getoptions_args = []
101
102 def fake_getoptions():
103 options = dict(default_options)
104 options.update(testcase.getoptions_opts)
105 arguments = list(testcase.getoptions_args)
106 result = (options, arguments)
107 return result
108
109 func_patcher = unittest.mock.patch.object(
110 dput.dcut, "getoptions", autospec=True,
111 side_effect=fake_getoptions)
112 func_patcher.start()
113 testcase.addCleanup(func_patcher.stop)
114
115
116 def make_default_getoptions_options():
117 """ Make a default mapping of options. """
118 default_options = dict()
119 default_options.update({
120 key: None
121 for key in [
122 'config', 'host', 'uploader', 'keyid',
123 'filetocreate', 'filetoupload', 'changes',
124 'commandline_passive',
125 ]
126 })
127 default_options.update({
128 key: False
129 for key in ['debug', 'simulate']
130 })
131 return default_options
132
133
134 def get_upload_method_func(testcase):
135 """ Get the specified upload method. """
136 host = testcase.test_host
137 method_name = testcase.runtime_config_parser.get(host, 'method')
138 method_func = testcase.upload_methods[method_name]
139 return method_func
140
141
142 class make_usage_message_TestCase(testtools.TestCase):
143 """ Test cases for `make_usage_message` function. """
144
145 def setUp(self):
146 """ Set up test fixtures. """
147 super().setUp()
148
149 patch_sys_argv(self)
150
151 def test_returns_text_with_program_name(self):
152 """ Should return text with expected program name. """
153 result = dput.dcut.make_usage_message()
154 expected_result = textwrap.dedent("""\
155 Usage: {progname} ...
156 ...
157 """).format(progname=self.progname)
158 self.expectThat(
159 result,
160 testtools.matchers.DocTestMatches(
161 expected_result, flags=doctest.ELLIPSIS))
162
163
164 class get_uploader_from_system_TestCase(
165 testscenarios.WithScenarios,
166 testtools.TestCase):
167 """ Test cases for `get_uploader_from_system` function. """
168
169 environ_scenarios = [
170 ('environ-none', {
171 'environ_mapping': {},
172 }),
173 ('environ-email-not-delimited', {
174 'environ_mapping': {'EMAIL': "[email protected]"},
175 'expected_environ_uploader': "<[email protected]>",
176 }),
177 ('environ-email-delimited', {
178 'environ_mapping': {'EMAIL': "<[email protected]>"},
179 'expected_environ_uploader': "<[email protected]>",
180 }),
181 ('environ-debemail-not-delimited', {
182 'environ_mapping': {'DEBEMAIL': "[email protected]"},
183 'expected_environ_uploader': "<[email protected]>",
184 }),
185 ('environ-debemail-delimited', {
186 'environ_mapping': {'DEBEMAIL': "<[email protected]>"},
187 'expected_environ_uploader': "<[email protected]>",
188 }),
189 ('environ-both-email-and-debfullname', {
190 'environ_mapping': {
191 'EMAIL': "[email protected]",
192 'DEBFULLNAME': "Lorem Ipsum",
193 },
194 'expected_environ_uploader': "Lorem Ipsum <[email protected]>",
195 }),
196 ('environ-both-debemail-and-debfullname', {
197 'environ_mapping': {
198 'DEBEMAIL': "[email protected]",
199 'DEBFULLNAME': "Lorem Ipsum",
200 },
201 'expected_environ_uploader': "Lorem Ipsum <[email protected]>",
202 }),
203 ('environ-both-email-and-debemail', {
204 'environ_mapping': {
205 'EMAIL': "[email protected]",
206 'DEBEMAIL': "[email protected]",
207 },
208 'expected_environ_uploader': "<[email protected]>",
209 }),
210 ('environ-both-email-and-debemail-and-debfullname', {
211 'environ_mapping': {
212 'EMAIL': "[email protected]",
213 'DEBEMAIL': "[email protected]",
214 'DEBFULLNAME': "Lorem Ipsum",
215 },
216 'expected_environ_uploader': "Lorem Ipsum <[email protected]>",
217 }),
218 ]
219
220 environ_kwarg_scenarios = [
221 ('environ-kwarg-default', {
222 'specify_environ_kwarg': False,
223 }),
224 ('environ-kwarg-specified', {
225 'specify_environ_kwarg': True,
226 }),
227 ]
228
229 system_scenarios = [
230 ('domain-from-mailname-file', {
231 'mailname_fake_file': io.StringIO("consecteur.example.org"),
232 'pwd_getpwuid_return_value': dummy_pwent._replace(
233 pw_name="grue",
234 pw_gecos="Dolor Sit Amet,spam,beans,eggs"),
235 'expected_debug_chatter': textwrap.dedent("""\
236 D: Guessing uploader
237 """),
238 'expected_system_uploader':
239 "Dolor Sit Amet <[email protected]>",
240 }),
241 ('domain-from-hostname-command', {
242 'mailname_file_open_scenario_name': "read_denied",
243 'hostname_stdout_content': "consecteur.example.org\n",
244 'pwd_getpwuid_return_value': dummy_pwent._replace(
245 pw_name="grue",
246 pw_gecos="Dolor Sit Amet,spam,beans,eggs"),
247 'expected_debug_chatter': textwrap.dedent("""\
248 D: Guessing uploader
249 D: Guessing uploader: /etc/mailname was a failure
250 """),
251 'expected_system_uploader':
252 "Dolor Sit Amet <[email protected]>",
253 }),
254 ('domain-failure', {
255 'mailname_file_open_scenario_name': "read_denied",
256 'hostname_stdout_content': "",
257 'pwd_getpwuid_return_value': dummy_pwent._replace(
258 pw_name="grue",
259 pw_gecos="Dolor Sit Amet,spam,beans,eggs"),
260 'expected_debug_chatter': textwrap.dedent("""\
261 D: Guessing uploader
262 D: Guessing uploader: /etc/mailname was a failure
263 D: Couldn't guess uploader
264 """),
265 }),
266 ]
267
268 scenarios = testscenarios.multiply_scenarios(
269 environ_scenarios, environ_kwarg_scenarios, system_scenarios)
270
271 for (scenario_name, scenario) in scenarios:
272 scenario['test_args'] = dict()
273 if scenario['specify_environ_kwarg']:
274 scenario['test_args'].update(
275 environ=scenario['environ_mapping'],
276 )
277 else:
278 scenario['os_environ'] = scenario['environ_mapping']
279
280 def setUp(self, *args, **kwargs):
281 """ Set up test fixtures. """
282 super().setUp(*args, **kwargs)
283 patch_system_interfaces(self)
284
285 patch_os_environ(self)
286 patch_os_getuid(self)
287 patch_pwd_getpwuid(self)
288
289 patch_etc_mailname(self)
290 setup_file_double_behaviour(self, [self.mailname_file_double])
291
292 self.set_hostname_subprocess_double()
293 patch_subprocess_popen(self)
294
295 self.set_expected_uploader()
296
297 def set_hostname_subprocess_double(self):
298 """ Set the test double for the ‘hostname’ subprocess. """
299 path = "/bin/hostname"
300 argv = (path, "--fqdn")
301 double = SubprocessDouble(path, argv=argv)
302 double.register_for_testcase(self)
303
304 double.set_subprocess_popen_scenario('success')
305 double.set_stdout_content(getattr(self, 'hostname_stdout_content', ""))
306
307 self.hostname_subprocess_double = double
308
309 def set_expected_uploader(self):
310 """ Set the expected uploader value for this test case. """
311 self.expected_uploader = None
312 for attrib_name in [
313 'expected_command_line_uploader',
314 'expected_environ_uploader',
315 'expected_system_uploader']:
316 if hasattr(self, attrib_name):
317 self.expected_uploader = getattr(self, attrib_name)
318 break
319
320 def test_emits_debug_message_for_uploader_discovery(self):
321 """ Should emit debug message for uploader discovery. """
322 test_args = copy.deepcopy(self.test_args)
323 test_args['debug'] = True
324 dput.dcut.get_uploader_from_system(**test_args)
325 expected_output_lines = [
326 "D: trying to get maintainer email from environment"]
327 guess_line_template = None
328 if hasattr(self, 'expected_environ_uploader'):
329 guess_line_template = "D: Uploader from env: {uploader}"
330 else:
331 expected_output_lines.extend(
332 self.expected_debug_chatter.split("\n")[:-1])
333 if hasattr(self, 'expected_system_uploader'):
334 guess_line_template = "D: Guessed uploader: {uploader}"
335 if guess_line_template is not None:
336 expected_output_lines.append(guess_line_template.format(
337 uploader=self.expected_uploader))
338 expected_output = "\n".join(expected_output_lines)
339 self.assertIn(expected_output, sys.stdout.getvalue())
340
341 def test_returns_expected_result(self):
342 """ Should return expected uploader value. """
343 result = dput.dcut.get_uploader_from_system(**self.test_args)
344 self.assertEqual(self.expected_uploader, result)
345
346
347 class getoptions_TestCase(testtools.TestCase):
348 """ Base for test cases for `getoptions` function. """
349
350 default_options = NotImplemented
351
352 scenarios = NotImplemented
353
354 def setUp(self):
355 """ Set up test fixtures. """
356 super().setUp()
357 patch_system_interfaces(self)
358
359 patch_os_environ(self)
360 patch_os_getuid(self)
361 patch_pwd_getpwuid(self)
362 patch_sys_argv(self)
363
364 patch_etc_mailname(self)
365 setup_file_double_behaviour(
366 self, [self.mailname_file_double])
367
368 self.set_hostname_subprocess_double()
369 patch_subprocess_popen(self)
370
371 self.patch_getopt()
372 if hasattr(self, 'expected_options'):
373 self.set_expected_result()
374
375 self.patch_get_uploader_from_system()
376 test_dput_main.patch_distribution(self)
377 self.patch_make_usage_message()
378
379 def set_hostname_subprocess_double(self):
380 """ Set the test double for the ‘hostname’ subprocess. """
381 path = "/bin/hostname"
382 argv = (path, "--fqdn")
383 double = SubprocessDouble(path, argv=argv)
384 double.register_for_testcase(self)
385
386 double.set_subprocess_popen_scenario('success')
387 double.set_stdout_content(getattr(self, 'hostname_stdout_content', ""))
388
389 self.hostname_subprocess_double = double
390
391 def patch_getopt(self):
392 """ Patch the `dputhelper.getopt` function. """
393 if not hasattr(self, 'getopt_opts'):
394 self.getopt_opts = []
395 else:
396 self.getopt_opts = list(self.getopt_opts)
397 if not hasattr(self, 'getopt_args'):
398 self.getopt_args = []
399 else:
400 self.getopt_args = list(self.getopt_args)
401
402 patch_getopt(self)
403
404 def set_expected_result(self):
405 """ Set the expected result value. """
406 if not hasattr(self, 'expected_arguments'):
407 self.expected_arguments = []
408 expected_options = self.default_options.copy()
409 expected_options.update(self.expected_options)
410 self.expected_result = (expected_options, self.expected_arguments)
411
412 def patch_get_uploader_from_system(self):
413 """ Patch function `get_uploader_from_system` for this test case. """
414 if not hasattr(self, 'fake_system_uploader'):
415 self.fake_system_uploader = self.getUniqueString()
416 func_patcher = unittest.mock.patch.object(
417 dput.dcut, "get_uploader_from_system", autospec=True,
418 return_value=self.fake_system_uploader)
419 func_patcher.start()
420 self.addCleanup(func_patcher.stop)
421
422 def patch_make_usage_message(self):
423 """ Patch the `make_usage_message` function. """
424 if hasattr(self, 'dcut_usage_message'):
425 text = self.dcut_usage_message
426 else:
427 text = self.getUniqueString()
428 func_patcher = unittest.mock.patch.object(
429 dput.dcut, "make_usage_message", autospec=True,
430 return_value=text)
431 func_patcher.start()
432 self.addCleanup(func_patcher.stop)
433
434
435 class getoptions_UploaderTestCase(
436 testscenarios.WithScenarios,
437 getoptions_TestCase):
438 """ Test cases for `getoptions` function, determining uploader. """
439
440 scenarios = [
441 ('email-address-only', {
442 'fake_system_uploader': "<[email protected]>",
443 'expected_uploader': "<[email protected]>",
444 }),
445 ('full-person-spec', {
446 'fake_system_uploader': "Lorem Ipsum <[email protected]>",
447 'expected_uploader': "Lorem Ipsum <[email protected]>",
448 }),
449 ]
450
451 default_options = make_default_getoptions_options()
452
453 def setUp(self, *args, **kwargs):
454 """ Set up test fixtures. """
455 super().setUp(*args, **kwargs)
456
457 self.expected_options = {
458 'uploader': self.expected_uploader,
459 }
460 self.set_expected_result()
461
462 def test_returns_expected_values(self):
463 """ Should return expected values. """
464 if not hasattr(self, 'expected_result'):
465 self.skipTest("No return result expected")
466 result = dput.dcut.getoptions()
467 self.assertEqual(self.expected_result, result)
468
469
470 class getoptions_ParseCommandLineTestCase(
471 testscenarios.WithScenarios,
472 getoptions_TestCase):
473 """ Test cases for `getoptions` function, parsing command line. """
474
475 dcut_usage_message = "Lorem ipsum, dolor sit amet."
476
477 progname = "lorem"
478 dput_version = "ipsum"
479
480 config_file_path = tempfile.mktemp()
481 changes_file_path = tempfile.mktemp()
482 output_file_path = tempfile.mktemp()
483 upload_file_path = tempfile.mktemp()
484
485 default_options = make_default_getoptions_options()
486
487 option_scenarios = [
488 ('no-options', {
489 'getopt_opts': [],
490 }),
491 ('option-bogus', {
492 'getopt_opts': [("--b0gUs", "BOGUS")],
493 'expected_stderr_output': (
494 "{progname} internal error:"
495 " Option --b0gUs, argument BOGUS unknown").format(
496 progname=progname),
497 'expected_exit_status': EXIT_STATUS_FAILURE,
498 }),
499 ('option-help', {
500 'getopt_opts': [("--help", None)],
501 'expected_stdout_output': dcut_usage_message,
502 'expected_exit_status': EXIT_STATUS_SUCCESS,
503 }),
504 ('option-version', {
505 'getopt_opts': [("--version", None)],
506 'expected_stdout_output': " ".join(
507 [progname, dput_version]),
508 'expected_exit_status': EXIT_STATUS_SUCCESS,
509 }),
510 ('option-filetoupload-and-system-uploader', {
511 'fake_system_uploader': "Lorem Ipsum <[email protected]>",
512 'getopt_opts': [
513 ("--upload", upload_file_path),
514 ],
515 'expected_options': {
516 'uploader': "Lorem Ipsum <[email protected]>",
517 'filetoupload': upload_file_path,
518 },
519 'expected_arguments': [],
520 }),
521 ('option-changes-and-system-uploader', {
522 'fake_system_uploader': "Lorem Ipsum <[email protected]>",
523 'getopt_opts': [
524 ("--input", changes_file_path),
525 ],
526 'expected_options': {
527 'uploader': "Lorem Ipsum <[email protected]>",
528 'changes': changes_file_path,
529 },
530 'expected_arguments': [],
531 }),
532 ('option-filetoupload-and-option-maintaineraddress', {
533 'getopt_opts': [
534 ("--upload", upload_file_path),
535 ("--maintaineraddress", "Lorem Ipsum <[email protected]>"),
536 ],
537 'expected_options': {
538 'uploader': "Lorem Ipsum <[email protected]>",
539 'filetoupload': upload_file_path,
540 },
541 'expected_arguments': [],
542 }),
543 ('option-changes-and-option-maintaineraddress', {
544 'getopt_opts': [
545 ("--input", changes_file_path),
546 ("--maintaineraddress", "Lorem Ipsum <[email protected]>"),
547 ],
548 'expected_options': {
549 'uploader': "Lorem Ipsum <[email protected]>",
550 'changes': changes_file_path,
551 },
552 'expected_arguments': [],
553 }),
554 ('option-filetoupload-with-no-uploader', {
555 'getopt_opts': [("--upload", upload_file_path)],
556 'fake_system_uploader': None,
557 'expected_stderr_output': "command file cannot be created",
558 'expected_exit_status': EXIT_STATUS_FAILURE,
559 }),
560 ('option-changes-with-no-uploader', {
561 'getopt_opts': [("--input", changes_file_path)],
562 'fake_system_uploader': None,
563 'expected_stderr_output': "command file cannot be created",
564 'expected_exit_status': EXIT_STATUS_FAILURE,
565 }),
566 ('option-several', {
567 'getopt_opts': [
568 ("--debug", None),
569 ("--simulate", None),
570 ("--config", config_file_path),
571 ("--maintaineraddress", "Lorem Ipsum <[email protected]>"),
572 ("--keyid", "DEADBEEF"),
573 ("--passive", None),
574 ("--output", output_file_path),
575 ("--host", "quux.example.com"),
576 ],
577 'expected_options': {
578 'debug': True,
579 'simulate': True,
580 'config': config_file_path,
581 'uploader': "Lorem Ipsum <[email protected]>",
582 'keyid': "DEADBEEF",
583 'commandline_passive': True,
584 'filetocreate': output_file_path,
585 'host': "quux.example.com",
586 },
587 'expected_arguments': [],
588 }),
589 ]
590
591 scenarios = option_scenarios
592
593 def test_emits_debug_message_for_program_version(self):
594 """ Should emit debug message for program version. """
595 sys.argv.insert(1, "--debug")
596 expected_progname = self.progname
597 expected_version = self.dput_version
598 with contextlib.suppress(FakeSystemExit):
599 dput.dcut.getoptions()
600 expected_output = textwrap.dedent("""\
601 D: {progname} {version}
602 """).format(
603 progname=expected_progname,
604 version=expected_version)
605 self.assertIn(expected_output, sys.stdout.getvalue())
606
607 def test_calls_getopt_with_expected_args(self):
608 """ Should call `getopt` with expected arguments. """
609 with contextlib.suppress(FakeSystemExit):
610 dput.dcut.getoptions()
611 dputhelper.getopt.assert_called_with(
612 self.sys_argv[1:], unittest.mock.ANY, unittest.mock.ANY)
613
614 def test_emits_debug_message_for_each_option(self):
615 """ Should emit a debug message for each option processed. """
616 sys.argv.insert(1, "--debug")
617 with contextlib.suppress(FakeSystemExit):
618 dput.dcut.getoptions()
619 expected_output_lines = [
620 "D: processing arg \"{opt}\", option \"{arg}\"".format(
621 opt=option, arg=option_argument)
622 for (option, option_argument) in self.getopt_args]
623 expected_output = "\n".join(expected_output_lines)
624 self.assertIn(expected_output, sys.stdout.getvalue())
625
626 def test_emits_expected_message(self):
627 """ Should emit message with expected content. """
628 with contextlib.suppress(FakeSystemExit):
629 dput.dcut.getoptions()
630 if hasattr(self, 'expected_stdout_output'):
631 self.assertIn(self.expected_stdout_output, sys.stdout.getvalue())
632 if hasattr(self, 'expected_stderr_output'):
633 self.assertIn(self.expected_stderr_output, sys.stderr.getvalue())
634
635 def test_calls_sys_exit_with_expected_exit_status(self):
636 """ Should call `sys.exit` with expected exit status. """
637 if not hasattr(self, 'expected_exit_status'):
638 dput.dcut.getoptions()
639 else:
640 with testtools.ExpectedException(FakeSystemExit):
641 dput.dcut.getoptions()
642 sys.exit.assert_called_with(self.expected_exit_status)
643
644 def test_returns_expected_values(self):
645 """ Should return expected values. """
646 if not hasattr(self, 'expected_result'):
647 self.skipTest("No return result expected")
648 result = dput.dcut.getoptions()
649 self.assertEqual(self.expected_result, result)
650
651
652 class getoptions_DetermineHostTestCase(
653 testscenarios.WithScenarios,
654 getoptions_TestCase):
655 """ Test cases for `getoptions` function, determine host name. """
656
657 system_scenarios = [
658 ('domain-from-mailname-file', {
659 'mailname_fake_file': io.StringIO("consecteur.example.org"),
660 }),
661 ]
662
663 default_options = getoptions_ParseCommandLineTestCase.default_options
664
665 command_scenarios = [
666 ('no-opts no-args', {
667 'getopt_opts': [],
668 'getopt_args': [],
669 'expected_options': {
670 'host': None,
671 },
672 }),
673 ('no-opts command-first-arg', {
674 'getopt_opts': [],
675 'getopt_args': ["cancel"],
676 'expected_options': {
677 'host': None,
678 },
679 'expected_arguments': ["cancel"],
680 }),
681 ('no-opts host-first-arg', {
682 'getopt_opts': [],
683 'getopt_args': ["quux.example.com", "cancel"],
684 'expected_options': {
685 'host': "quux.example.com",
686 },
687 'expected_arguments': ["cancel"],
688 'expected_debug_output': textwrap.dedent("""\
689 D: first argument "quux.example.com" treated as host
690 """),
691 }),
692 ('option-host host-first-arg', {
693 'getopt_opts': [("--host", "quux.example.com")],
694 'getopt_args': ["decoy.example.net", "cancel"],
695 'expected_options': {
696 'host': "quux.example.com",
697 },
698 'expected_arguments': ["decoy.example.net", "cancel"],
699 }),
700 ]
701
702 scenarios = testscenarios.multiply_scenarios(
703 system_scenarios, command_scenarios)
704
705 def test_emits_expected_debug_message(self):
706 """ Should emit the expected debug message. """
707 if not hasattr(self, 'expected_debug_output'):
708 self.expected_debug_output = ""
709 self.getopt_opts = list(
710 self.getopt_opts + [("--debug", None)])
711 dput.dcut.getoptions()
712 self.assertIn(self.expected_debug_output, sys.stdout.getvalue())
713
714 def test_returns_expected_values(self):
715 """ Should return expected values. """
716 if not hasattr(self, 'expected_result'):
717 self.skipTest("No return result expected")
718 (options, arguments) = dput.dcut.getoptions()
719 self.assertEqual(self.expected_options['host'], options['host'])
720 self.assertEqual(self.expected_arguments, arguments)
721
722
723 class parse_queuecommands_TestCase(testtools.TestCase):
724 """ Base for test cases for `parse_queuecommands` function. """
725
726 scenarios = NotImplemented
727
728 def setUp(self):
729 """ Set up test fixtures. """
730 super().setUp()
731 patch_system_interfaces(self)
732
733 self.set_test_args()
734
735 def set_test_args(self):
736 """ Set the arguments for the test call to the function. """
737 default_options = {
738 'debug': False,
739 }
740 self.test_args = dict(
741 arguments=getattr(self, 'arguments', []),
742 options=getattr(self, 'options', default_options),
743 config=object(),
744 )
745
746
747 class parse_queuecommands_SuccessTestCase(
748 testscenarios.WithScenarios,
749 parse_queuecommands_TestCase):
750 """ Success test cases for `parse_queuecommands` function. """
751
752 scenarios = [
753 ('one-command-rm', {
754 'arguments': ["rm", "lorem.deb"],
755 'expected_commands': [
756 "rm --searchdirs lorem.deb",
757 ],
758 }),
759 ('one-command-rm nosearchdirs', {
760 'arguments': ["rm", "--nosearchdirs", "lorem.deb"],
761 'expected_commands': [
762 "rm lorem.deb",
763 ],
764 }),
765 ('one-command-cancel', {
766 'arguments': ["cancel", "lorem.deb"],
767 'expected_commands': [
768 "cancel lorem.deb",
769 ],
770 }),
771 ('one-command-cancel nosearchdirs', {
772 'arguments': ["cancel", "--nosearchdirs", "lorem.deb"],
773 'expected_commands': [
774 "cancel --nosearchdirs lorem.deb",
775 ],
776 }),
777 ('one-command-reschedule', {
778 'arguments': ["reschedule", "lorem.deb"],
779 'expected_commands': [
780 "reschedule lorem.deb",
781 ],
782 }),
783 ('one-command-reschedule nosearchdirs', {
784 'arguments': ["reschedule", "--nosearchdirs", "lorem.deb"],
785 'expected_commands': [
786 "reschedule --nosearchdirs lorem.deb",
787 ],
788 }),
789 ('three-commands comma-separated', {
790 'arguments': [
791 "rm", "foo", ",",
792 "cancel", "bar", ",",
793 "reschedule", "baz"],
794 'expected_commands': [
795 "rm --searchdirs foo ",
796 "cancel bar ",
797 "reschedule baz",
798 ],
799 }),
800 ('three-commands semicolon-separated', {
801 'arguments': [
802 "rm", "foo", ";",
803 "cancel", "bar", ";",
804 "reschedule", "baz"],
805 'expected_commands': [
806 "rm --searchdirs foo ",
807 "cancel bar ",
808 "reschedule baz",
809 ],
810 }),
811 ]
812
813 def test_emits_debug_message_for_each_command(self):
814 """ Should emit a debug message for each command. """
815 self.test_args['options'] = dict(self.test_args['options'])
816 self.test_args['options']['debug'] = True
817 dput.dcut.parse_queuecommands(**self.test_args)
818 expected_output = "\n".join(
819 "D: Successfully parsed command \"{command}\"".format(
820 command=command)
821 for command in self.expected_commands)
822 self.assertIn(expected_output, sys.stdout.getvalue())
823
824 def test_returns_expected_commands(self):
825 """ Should return expected commands value. """
826 result = dput.dcut.parse_queuecommands(**self.test_args)
827 self.assertEqual(self.expected_commands, result)
828
829
830 class parse_queuecommands_ErrorTestCase(
831 testscenarios.WithScenarios,
832 parse_queuecommands_TestCase):
833 """ Error test cases for `parse_queuecommands` function. """
834
835 scenarios = [
836 ('no-arguments', {
837 'arguments': [],
838 'expected_debug_output': textwrap.dedent("""\
839 Error: no arguments given, see dcut -h
840 """),
841 'expected_exit_status': EXIT_STATUS_FAILURE,
842 }),
843 ('first-command-bogus', {
844 'arguments': ["b0gUs", "spam", "eggs"],
845 'expected_debug_output': textwrap.dedent("""\
846 Error: Could not parse commands at "b0gUs"
847 """),
848 'expected_exit_status': EXIT_STATUS_FAILURE,
849 }),
850 ('third-command-bogus', {
851 'arguments': ["rm", "foo", ",", "cancel", "bar", ",", "b0gUs"],
852 'expected_debug_output': textwrap.dedent("""\
853 Error: Could not parse commands at "b0gUs"
854 """),
855 'expected_exit_status': EXIT_STATUS_FAILURE,
856 }),
857 ]
858
859 def test_emits_expected_error_message(self):
860 """ Should emit expected error message. """
861 with contextlib.suppress(FakeSystemExit):
862 dput.dcut.parse_queuecommands(**self.test_args)
863 self.assertIn(self.expected_debug_output, sys.stderr.getvalue())
864
865 def test_calls_sys_exit_with_exit_status(self):
866 """ Should call `sys.exit` with expected exit status. """
867 with testtools.ExpectedException(FakeSystemExit):
868 dput.dcut.parse_queuecommands(**self.test_args)
869 sys.exit.assert_called_with(self.expected_exit_status)
870
871
872 class create_commands_TestCase(
873 testscenarios.WithScenarios,
874 testtools.TestCase):
875 """ Test cases for `create_commands` function. """
876
877 scenarios = [
878 ('simple', {
879 'changes_file_scenario_name': "no-format",
880 }),
881 ('unusual-preferred-encoding', {
882 'locale_preferredencoding_return_value': "ANSI_X3.4-1968",
883 'changes_file_scenario_name': "encoding needs-utf8",
884 }),
885 ]
886
887 def setUp(self):
888 """ Set up test fixtures. """
889 super().setUp()
890 patch_system_interfaces(self)
891 if hasattr(self, 'locale_preferredencoding_return_value'):
892 patch_locale_getpreferredencoding(
893 self, encoding=self.locale_preferredencoding_return_value)
894
895 self.changes_file_scenarios = make_changes_file_scenarios()
896 set_changes_file_scenario(self, self.changes_file_scenario_name)
897 setup_file_double_behaviour(self)
898
899 self.set_expected_commands()
900
901 self.set_options()
902
903 patch_parse_changes(self)
904 upload_changes.parse_changes.return_value = self.changes_file_scenario[
905 'expected_result']
906
907 self.set_test_args()
908
909 def set_options(self):
910 """ Set the options mapping to pass to the function. """
911 self.options = {
912 'debug': False,
913 'changes': self.changes_file_double.path,
914 }
915
916 def set_test_args(self):
917 """ Set the arguments for the test call to the function. """
918 self.test_args = dict(
919 options=dict(self.options),
920 parse_changes=upload_changes.parse_changes,
921 )
922
923 def set_expected_commands(self):
924 """ Set the expected commands for this test case. """
925 files_to_remove = [os.path.basename(self.changes_file_double.path)]
926 files_from_changes = self.changes_file_scenario[
927 'expected_result']['files']
928 for line in files_from_changes.split("\n"):
929 files_to_remove.append(line.split(" ")[4])
930 self.expected_commands = [
931 "rm --searchdirs {path}".format(path=path)
932 for path in files_to_remove]
933
934 def test_emits_debug_message_for_changes_file(self):
935 """ Should emit debug message for changes file. """
936 self.options['debug'] = True
937 self.set_test_args()
938 dput.dcut.create_commands(**self.test_args)
939 expected_output = textwrap.dedent("""\
940 D: Parsing changes file ({path}) for files to remove
941 """).format(path=self.changes_file_double.path)
942 self.assertIn(expected_output, sys.stdout.getvalue())
943
944 def test_emits_error_message_when_changes_file_open_error(self):
945 """ Should emit error message when changes file raises error. """
946 self.changes_file_double.set_open_scenario('read_denied')
947 with contextlib.suppress(FakeSystemExit):
948 dput.dcut.create_commands(**self.test_args)
949 expected_output = textwrap.dedent("""\
950 Can't open changes file: {path}
951 """).format(path=self.changes_file_double.path)
952 self.assertIn(expected_output, sys.stdout.getvalue())
953
954 def test_calls_sys_exit_when_changes_file_open_error(self):
955 """ Should call `sys.exit` when changes file raises error. """
956 self.changes_file_double.set_open_scenario('read_denied')
957 with testtools.ExpectedException(FakeSystemExit):
958 dput.dcut.create_commands(**self.test_args)
959 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
960
961 def test_returns_expected_result(self):
962 """ Should return expected result. """
963 result = dput.dcut.create_commands(**self.test_args)
964 self.assertEqual(self.expected_commands, result)
965
966
967 class write_commands_TestCase(
968 testscenarios.WithScenarios,
969 testtools.TestCase):
970 """ Test cases for `write_commands` function. """
971
972 default_options = {
973 'filetocreate': None,
974 }
975
976 path_scenarios = [
977 ('default-path', {}),
978 ('filetocreate', {
979 'option_filetocreate': "ipsum.commands",
980 'expected_result': "ipsum.commands",
981 }),
982 ('no-tempdir', {
983 'tempdir': None,
984 }),
985 ]
986
987 commands_scenarios = [
988 ('commands-none', {
989 'commands': [],
990 }),
991 ('commands-one', {
992 'commands': ["foo"],
993 }),
994 ('commands-three', {
995 'commands': ["foo", "bar", "baz"],
996 }),
997 ]
998
999 keyid_scenarios = [
1000 ('keyid-none', {}),
1001 ('keyid-set', {
1002 'option_keyid': "DEADBEEF",
1003 }),
1004 ]
1005
1006 scenarios = testscenarios.multiply_scenarios(
1007 path_scenarios, commands_scenarios, keyid_scenarios)
1008
1009 for (scenario_name, scenario) in scenarios:
1010 default_options = getoptions_ParseCommandLineTestCase.default_options
1011 options = default_options.copy()
1012 options.update({
1013 'uploader': "Lorem Ipsum <[email protected]>",
1014 })
1015 scenario['uploader_filename_part'] = "Lorem_Ipsum__flup_example_org_"
1016 if 'option_filetocreate' in scenario:
1017 options['filetocreate'] = scenario['option_filetocreate']
1018 if 'option_keyid' in scenario:
1019 options['keyid'] = scenario['option_keyid']
1020 scenario['options'] = options
1021 if 'tempdir' not in scenario:
1022 scenario['tempdir'] = tempfile.mktemp()
1023 del scenario_name, scenario
1024 del default_options, options
1025
1026 def setUp(self):
1027 """ Set up test fixtures. """
1028 super().setUp()
1029 patch_system_interfaces(self)
1030
1031 patch_os_getpid(self)
1032 os.getpid.return_value = self.getUniqueInteger()
1033
1034 self.time_return_value = self.getUniqueInteger()
1035 patch_time_time(self, itertools.repeat(self.time_return_value))
1036
1037 patch_sys_argv(self)
1038 self.set_commands_file_double()
1039 setup_file_double_behaviour(self)
1040 self.set_expected_result()
1041
1042 self.set_commands()
1043
1044 self.set_test_args()
1045
1046 patch_subprocess_popen(self)
1047 patch_subprocess_check_call(self)
1048 self.set_debsign_subprocess_double()
1049 setup_subprocess_double_behaviour(self)
1050
1051 def set_options(self):
1052 """ Set the options mapping to pass to the function. """
1053
1054 def set_test_args(self):
1055 """ Set the arguments for the test call to the function. """
1056 self.test_args = dict(
1057 commands=list(self.commands),
1058 options=dict(self.options),
1059 tempdir=self.tempdir,
1060 )
1061
1062 def make_commands_filename(self):
1063 """ Make the filename for the commands output file. """
1064 expected_progname = self.progname
1065 filename = "{progname}.{uploadpart}.{time:d}.{pid:d}.commands".format(
1066 progname=expected_progname,
1067 uploadpart=self.uploader_filename_part,
1068 time=self.time_return_value,
1069 pid=os.getpid.return_value)
1070 return filename
1071
1072 def set_commands_file_double(self):
1073 """ Set the commands file double for this test case. """
1074 if self.options['filetocreate']:
1075 path = self.options['filetocreate']
1076 else:
1077 output_filename = self.make_commands_filename()
1078 if self.tempdir:
1079 path = os.path.join(self.tempdir, output_filename)
1080 else:
1081 path = output_filename
1082 double = FileDouble(path)
1083 double.register_for_testcase(self)
1084 self.commands_file_double = double
1085
1086 def set_expected_result(self):
1087 """ Set the `expected_result` for this test case. """
1088 self.expected_result = self.commands_file_double.path
1089
1090 def set_commands(self):
1091 """ Set the commands to use for this test case. """
1092 if not hasattr(self, 'commands'):
1093 self.commands = []
1094
1095 def make_expected_content(self):
1096 """ Make the expected content for the output file. """
1097 uploader_value = self.options['uploader']
1098 commands_value = "".join(
1099 " {}\n".format(command)
1100 for command in (self.commands or [""]))
1101 text = textwrap.dedent("""\
1102 Uploader: {uploader}
1103 Commands:
1104 {commands}
1105 """).format(uploader=uploader_value, commands=commands_value)
1106 return text
1107
1108 def set_debsign_subprocess_double(self):
1109 """ Set the ‘debsign’ subprocess double for this test case. """
1110 path = "/usr/bin/debsign"
1111 argv = [os.path.basename(path), ARG_MORE]
1112 double = SubprocessDouble(path, argv)
1113 double.register_for_testcase(self)
1114 self.debsign_subprocess_double = double
1115
1116 def make_expected_debsign_argv(self):
1117 """ Make the expected command-line arguments for ‘debsign’. """
1118 argv = [
1119 "debsign",
1120 "-m{uploader}".format(uploader=self.options['uploader']),
1121 ]
1122 if self.options['keyid']:
1123 argv.append(
1124 "-k{keyid}".format(keyid=self.options['keyid']))
1125 argv.append(self.commands_file_double.path)
1126
1127 return argv
1128
1129 def test_returns_expected_file_path(self):
1130 """ Should return expected file path. """
1131 result = dput.dcut.write_commands(**self.test_args)
1132 self.assertEqual(self.expected_result, result)
1133
1134 def test_output_file_has_expected_content(self):
1135 """ Should have expected content in output file. """
1136 with open(
1137 self.commands_file_double.path, mode='w', encoding='UTF-8',
1138 ) as fake_file:
1139 with unittest.mock.patch.object(fake_file, "close", autospec=True):
1140 dput.dcut.write_commands(**self.test_args)
1141 fake_file.flush()
1142 output_text = str(fake_file.buffer.getvalue(), encoding='UTF-8')
1143 expected_value = self.make_expected_content()
1144 self.assertEqual(expected_value, output_text)
1145
1146 def test_emits_debug_message_for_debsign(self):
1147 """ Should emit debug message for ‘debsign’ command. """
1148 self.options['debug'] = True
1149 self.test_args['options'] = self.options
1150 dput.dcut.write_commands(**self.test_args)
1151 debsign_argv = self.make_expected_debsign_argv()
1152 expected_output = textwrap.dedent("""\
1153 D: calling debsign: {argv}
1154 """).format(argv=debsign_argv)
1155 self.assertIn(expected_output, sys.stdout.getvalue())
1156
1157 def test_calls_subprocess_check_call_with_expected_args(self):
1158 """ Should call `subprocess.check_call` with expected args. """
1159 debsign_argv = self.make_expected_debsign_argv()
1160 expected_args = [debsign_argv]
1161 dput.dcut.write_commands(**self.test_args)
1162 subprocess.check_call.assert_called_with(*expected_args)
1163
1164 def test_emits_error_message_when_debsign_failure(self):
1165 """ Should emit error message when ‘debsign’ command failure. """
1166 self.debsign_subprocess_double.set_subprocess_check_call_scenario(
1167 'failure')
1168 with contextlib.suppress(FakeSystemExit):
1169 dput.dcut.write_commands(**self.test_args)
1170 expected_output = textwrap.dedent("""\
1171 Error: debsign failed.
1172 """)
1173 self.assertIn(expected_output, sys.stderr.getvalue())
1174
1175 def test_calls_sys_exit_when_debsign_failure(self):
1176 """ Should call `sys.exit` when ‘debsign’ command failure. """
1177 self.debsign_subprocess_double.set_subprocess_check_call_scenario(
1178 'failure')
1179 with testtools.ExpectedException(FakeSystemExit):
1180 dput.dcut.write_commands(**self.test_args)
1181 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1182
1183
1184 class dcut_TestCase(testtools.TestCase):
1185 """ Base for test cases for `dput` function. """
1186
1187 function_to_test = staticmethod(dput.dcut.dcut)
1188
1189 def setUp(self):
1190 """ Set up test fixtures. """
1191 super().setUp()
1192 patch_system_interfaces(self)
1193
1194 patch_tempfile_mkdtemp(self)
1195 patch_os_unlink(self)
1196 patch_os_rmdir(self)
1197 patch_shutil_rmtree(self)
1198
1199 set_config(
1200 self,
1201 getattr(self, 'config_scenario_name', 'exist-simple'))
1202 test_dput_main.patch_runtime_config_options(self)
1203
1204 self.set_test_args()
1205
1206 patch_getoptions(self)
1207 patch_active_config_files(self)
1208 patch_parse_changes(self)
1209 patch_read_configs(self)
1210 test_dput_main.set_upload_methods(self)
1211 test_dput_main.patch_import_upload_functions(self)
1212 test_dput_main.patch_upload_files(self)
1213
1214 self.patch_parse_queuecommands()
1215 self.patch_create_commands()
1216 self.patch_write_commands()
1217
1218 def set_test_args(self):
1219 """ Set the arguments for the test call to the function. """
1220 self.test_args = dict()
1221
1222 def patch_parse_queuecommands(self):
1223 """ Patch the `parse_queuecommands` function for this test case. """
1224 func_patcher = unittest.mock.patch.object(
1225 dput.dcut, "parse_queuecommands", autospec=True)
1226 func_patcher.start()
1227 self.addCleanup(func_patcher.stop)
1228
1229 def patch_create_commands(self):
1230 """ Patch the `create_commands` function for this test case. """
1231 func_patcher = unittest.mock.patch.object(
1232 dput.dcut, "create_commands", autospec=True)
1233 func_patcher.start()
1234 self.addCleanup(func_patcher.stop)
1235
1236 def patch_write_commands(self):
1237 """ Patch the `write_commands` function for this test case. """
1238 func_patcher = unittest.mock.patch.object(
1239 dput.dcut, "write_commands", autospec=True)
1240 func_patcher.start()
1241 self.addCleanup(func_patcher.stop)
1242
1243
1244 class dcut_DebugMessageTestCase(dcut_TestCase):
1245 """ Test cases for `dcut` debug messages. """
1246
1247 def test_emits_debug_message_for_read_configs(self):
1248 """ Should emit debug message to begin reading configuration. """
1249 self.getoptions_opts['debug'] = True
1250 self.function_to_test(**self.test_args)
1251 expected_output = textwrap.dedent("""\
1252 D: reading program configuration
1253 """)
1254 self.assertIn(expected_output, sys.stdout.getvalue())
1255
1256
1257 class dcut_ConfigFileTestCase(
1258 testscenarios.WithScenarios,
1259 dcut_TestCase):
1260 """ Test cases for `dcut` specification of configuration file. """
1261
1262 scenarios = [
1263 ('default', {
1264 'expected_config_path': None,
1265 }),
1266 ('config-from-command-line', {
1267 'getoptions_opts': {
1268 'config': "lorem.conf",
1269 },
1270 'expected_config_path': "lorem.conf",
1271 }),
1272 ]
1273
1274 def test_calls_active_config_files_with_expected_args(self):
1275 """ Should call `active_config_files` with expected arguments. """
1276 expected_args = (self.expected_config_path, unittest.mock.ANY)
1277 self.function_to_test(**self.test_args)
1278 dput.configfile.active_config_files.assert_called_with(*expected_args)
1279
1280 def test_calls_read_configs_with_expected_args(self):
1281 """ Should call `read_configs` with expected arguments. """
1282 expected_config_files = self.fake_config_files
1283 expected_args = tuple([expected_config_files])
1284 expected_kwargs = dict(debug=unittest.mock.ANY)
1285 self.function_to_test(**self.test_args)
1286 dput.configfile.read_configs.assert_called_with(
1287 *expected_args, **expected_kwargs)
1288
1289 def test_calls_sys_exit_if_configuration_error_when_opening_files(self):
1290 """
1291 Should call `sys.exit` if `ConfigurationError` from opening files.
1292 """
1293 set_config(self, 'all-not-exist')
1294 self.set_test_args()
1295 fake_error_text = "Could not open any configfile, tried ‘foo’, ‘bar’"
1296 fake_error = dput.configfile.ConfigurationError(fake_error_text)
1297 dput.configfile.active_config_files.side_effect = fake_error
1298 with testtools.ExpectedException(FakeSystemExit):
1299 self.function_to_test(**self.test_args)
1300 expected_output = textwrap.dedent("""\
1301 ...{error_text}...
1302 """.format(error_text=fake_error_text))
1303 self.assertThat(
1304 sys.stderr.getvalue(),
1305 testtools.matchers.DocTestMatches(
1306 expected_output, flags=doctest.ELLIPSIS))
1307 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1308
1309 def test_calls_sys_exit_if_configuration_error_when_reading_files(self):
1310 """
1311 Should call `sys.exit` if `ConfigurationError` from reading files.
1312 """
1313 fake_error_text = "Hidden Illuminati messages in config file"
1314 fake_error = dput.configfile.ConfigurationError(fake_error_text)
1315 dput.configfile.read_configs.side_effect = fake_error
1316 with testtools.ExpectedException(FakeSystemExit):
1317 self.function_to_test(**self.test_args)
1318 expected_output = textwrap.dedent("""\
1319 ...{error_text}...
1320 """.format(error_text=fake_error_text))
1321 self.assertThat(
1322 sys.stderr.getvalue(),
1323 testtools.matchers.DocTestMatches(
1324 expected_output, flags=doctest.ELLIPSIS))
1325 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1326
1327
1328 class dcut_OptionsErrorTestCase(
1329 testscenarios.WithScenarios,
1330 dcut_TestCase):
1331 """ Test cases for `dcut` function, startup options cause error. """
1332
1333 scenarios = [
1334 ('host-not-in-config', {
1335 'config_scenario_name': "exist-minimal",
1336 'expected_output': "Error: Host 'foo' not found in config",
1337 'expected_exit_status': EXIT_STATUS_FAILURE,
1338 }),
1339 ('host-not-in-config nonstandard-default-section', {
1340 'config_scenario_name': (
1341 "exist-simple-nonstandard-default-section"),
1342 'config_extras': {
1343 'default': {
1344 'default_host_main': "pharetra",
1345 },
1346 },
1347 'config_default_default_host_main': "suscipit",
1348 'getoptions_opts': {
1349 'host': None,
1350 },
1351 'expected_output': (
1352 "Error: Host 'pharetra' not found in config"),
1353 'expected_exit_status': EXIT_STATUS_FAILURE,
1354 }),
1355 ('host-not-in-config hardcoded-default', {
1356 'config_default_default_host_main': None,
1357 'getoptions_opts': {
1358 'host': None,
1359 },
1360 'expected_output': (
1361 "Error: Host 'ftp-master' not found in config"),
1362 'expected_exit_status': EXIT_STATUS_FAILURE,
1363 }),
1364 ('default-allow-dcut-false host-allow-dcut-absent', {
1365 'config_default_allow_dcut': False,
1366 'config_allow_dcut': None,
1367 'expected_output': (
1368 "Error: dcut is not supported for this upload queue."),
1369 'expected_exit_status': EXIT_STATUS_FAILURE,
1370 }),
1371 ('host-allow-dcut-false', {
1372 'config_allow_dcut': False,
1373 'expected_output': (
1374 "Error: dcut is not supported for this upload queue."),
1375 'expected_exit_status': EXIT_STATUS_FAILURE,
1376 }),
1377 ('default-allow-dcut-true host-allow-dcut-false', {
1378 'config_default_allow_dcut': True,
1379 'config_allow_dcut': False,
1380 'expected_output': (
1381 "Error: dcut is not supported for this upload queue."),
1382 'expected_exit_status': EXIT_STATUS_FAILURE,
1383 }),
1384 ('filetoupload arguments', {
1385 'getoptions_opts': {
1386 'filetoupload': "{}.commands".format(tempfile.mktemp()),
1387 },
1388 'getoptions_args': ["lorem", "ipsum", "dolor", "sit", "amet"],
1389 'expected_output': (
1390 "Error: cannot take commands"
1391 " when uploading existing file"),
1392 'expected_exit_status': EXIT_STATUS_FAILURE,
1393 }),
1394 ]
1395
1396 def test_emits_expected_error_message(self):
1397 """ Should emit expected error message. """
1398 with contextlib.suppress(FakeSystemExit):
1399 self.function_to_test(**self.test_args)
1400 self.assertIn(self.expected_output, sys.stdout.getvalue())
1401
1402 def test_calls_sys_exit_with_failure_exit_status(self):
1403 """ Should call `sys.exit` with failure exit status. """
1404 with testtools.ExpectedException(FakeSystemExit):
1405 self.function_to_test(**self.test_args)
1406 sys.exit.assert_called_with(self.expected_exit_status)
1407
1408
1409 class dcut_NamedHostTestCase(
1410 testscenarios.WithScenarios,
1411 dcut_TestCase):
1412 """ Test cases for `dcut` function, named host processing. """
1413
1414 scenarios = [
1415 ('host-from-command-line', {
1416 'config_scenario_name': "exist-simple-host-three",
1417 'config_default_default_host_main': "quux",
1418 'getoptions_opts': {
1419 'host': "bar",
1420 },
1421 'expected_host': "bar",
1422 'expected_debug_output': "",
1423 }),
1424 ('host-from-config-default', {
1425 'config_scenario_name': "exist-simple-host-three",
1426 'config_default_default_host_main': "bar",
1427 'getoptions_opts': {
1428 'host': None,
1429 },
1430 'expected_host': "bar",
1431 'expected_debug_output': textwrap.dedent("""\
1432 D: Using host 'bar'
1433 """),
1434 }),
1435 ('host-from-config-default nonstandard-default-section', {
1436 'config_scenario_name': (
1437 "exist-simple-nonstandard-default-section"),
1438 'config_extras': {
1439 'default': {
1440 'default_host_main': "foo",
1441 },
1442 },
1443 'config_default_default_host_main': "suscipit",
1444 'getoptions_opts': {
1445 'host': None,
1446 },
1447 'expected_host': "foo",
1448 'expected_debug_output': textwrap.dedent("""\
1449 D: Using host 'foo'
1450 """),
1451 }),
1452 ('host-from-hardcoded-default', {
1453 'config_scenario_name': "exist-default-distribution-only",
1454 'config_default_default_host_main': None,
1455 'getoptions_opts': {
1456 'host': None,
1457 },
1458 'expected_host': "ftp-master",
1459 'expected_debug_output': textwrap.dedent("""\
1460 D: Using host 'ftp-master'
1461 """),
1462 }),
1463 ]
1464
1465 def test_emits_debug_message_for_discovered_host(self):
1466 """ Should emit debug message for discovered host values. """
1467 self.getoptions_opts['debug'] = True
1468 self.function_to_test(**self.test_args)
1469 self.assertIn(self.expected_debug_output, sys.stdout.getvalue())
1470
1471 def test_calls_write_commands_with_expected_host_option(self):
1472 """ Should call `write_commands` with expected `host` option. """
1473 self.function_to_test(**self.test_args)
1474 self.assertEqual(1, len(dput.dcut.write_commands.mock_calls))
1475 (__, __, call_kwargs) = dput.dcut.write_commands.mock_calls[0]
1476 options = call_kwargs['options']
1477 self.assertEqual(self.expected_host, options['host'])
1478
1479
1480 class dcut_FileToUploadNameTestCase(
1481 testscenarios.WithScenarios,
1482 dcut_TestCase):
1483 """ Test cases for `dcut` function, file to upload with bad name. """
1484
1485 scenarios = [
1486 ('filetoupload suffix-normal', {
1487 'getoptions_args': [],
1488 'getoptions_opts': {
1489 'filetoupload': "{}.commands".format(tempfile.mktemp()),
1490 },
1491 'unwanted_output': "Error",
1492 }),
1493 ('filetoupload suffix-unexpected', {
1494 'getoptions_args': [],
1495 'getoptions_opts': {
1496 'filetoupload': tempfile.mktemp(),
1497 },
1498 'expected_output': (
1499 "Error: I'm insisting on the ‘.commands’ suffix"),
1500 }),
1501 ]
1502
1503 def test_emits_error_message_for_bad_filename(self):
1504 """ Should emit error message for bad filename. """
1505 self.function_to_test(**self.test_args)
1506 if getattr(self, 'expected_output', None):
1507 self.assertIn(self.expected_output, sys.stdout.getvalue())
1508 else:
1509 self.assertNotIn(self.unwanted_output, sys.stdout.getvalue())
1510
1511
1512 class dcut_ParseChangesTestCase(
1513 testscenarios.WithScenarios,
1514 dcut_TestCase):
1515 """ Test cases for `dcut` function, parse upload control file. """
1516
1517 scenarios = [
1518 ('changes-file with-filetoupload with-filetocreate', {
1519 'getoptions_opts': {
1520 'filetoupload': tempfile.mktemp(),
1521 'filetocreate': tempfile.mktemp(),
1522 'changes': tempfile.mktemp(),
1523 },
1524 'expect_create_commands': False,
1525 'expect_write_commands': False,
1526 'expected_tempdir': None,
1527 }),
1528 ('changes-file no-filetoupload with-filetocreate', {
1529 'getoptions_opts': {
1530 'filetoupload': None,
1531 'filetocreate': tempfile.mktemp(),
1532 'changes': tempfile.mktemp(),
1533 },
1534 'expect_create_commands': True,
1535 'expect_write_commands': True,
1536 'expected_tempdir': None,
1537 }),
1538 ('changes-file with-filetoupload no-filetocreate', {
1539 'getoptions_opts': {
1540 'filetoupload': tempfile.mktemp(),
1541 'filetocreate': None,
1542 'changes': tempfile.mktemp(),
1543 },
1544 'expect_create_commands': False,
1545 'expect_write_commands': False,
1546 'expected_tempdir': None,
1547 }),
1548 ('changes-file no-filetoupload no-filetocreate', {
1549 'getoptions_opts': {
1550 'filetoupload': None,
1551 'filetocreate': None,
1552 'changes': tempfile.mktemp(),
1553 },
1554 'expect_create_commands': True,
1555 'expect_write_commands': True,
1556 }),
1557 ]
1558
1559 def test_calls_create_commands_with_expected_args(self):
1560 """ Should call `create_commands` as expected. """
1561 self.function_to_test(**self.test_args)
1562 (expected_options, __) = dput.dcut.getoptions()
1563 expected_parse_changes = upload_changes.parse_changes
1564 if self.expect_create_commands:
1565 dput.dcut.create_commands.assert_called_with(
1566 expected_options, expected_parse_changes)
1567 else:
1568 self.assertFalse(dput.dcut.create_commands.called)
1569
1570 def test_calls_write_commands_with_expected_args(self):
1571 """ Should call `write_commands` as expected. """
1572 expected_commands = dput.dcut.create_commands.return_value
1573 self.function_to_test(**self.test_args)
1574 (expected_options, __) = dput.dcut.getoptions()
1575 expected_tempdir = getattr(
1576 self, 'expected_tempdir',
1577 self.tempfile_mkdtemp_file_double.path)
1578 if self.expect_write_commands:
1579 dput.dcut.write_commands.assert_called_with(
1580 expected_commands,
1581 options=expected_options,
1582 tempdir=expected_tempdir,
1583 )
1584 else:
1585 self.assertFalse(dput.dcut.write_commands.called)
1586
1587
1588 class dcut_ParseCommandsFromArgumentsTestCase(
1589 testscenarios.WithScenarios,
1590 dcut_TestCase):
1591 """ Test cases for `dcut` function, parse commands from arguments. """
1592
1593 scenarios = [
1594 ('no-changes-file with-filetoupload with-filetocreate', {
1595 'getoptions_opts': {
1596 'filetoupload': tempfile.mktemp(),
1597 'filetocreate': tempfile.mktemp(),
1598 'changes': None,
1599 },
1600 'expect_parse_queuecommands': False,
1601 'expect_write_commands': False,
1602 'expected_tempdir': None,
1603 }),
1604 ('no-changes-file no-filetoupload with-filetocreate', {
1605 'getoptions_opts': {
1606 'filetoupload': None,
1607 'filetocreate': tempfile.mktemp(),
1608 'changes': None,
1609 },
1610 'expect_parse_queuecommands': True,
1611 'expect_write_commands': True,
1612 'expected_tempdir': None,
1613 }),
1614 ('no-changes-file with-filetoupload no-filetocreate', {
1615 'getoptions_opts': {
1616 'filetoupload': tempfile.mktemp(),
1617 'filetocreate': None,
1618 'changes': None,
1619 },
1620 'expect_parse_queuecommands': False,
1621 'expect_write_commands': False,
1622 'expected_tempdir': None,
1623 }),
1624 ('no-changes-file no-filetoupload no-filetocreate', {
1625 'getoptions_opts': {
1626 'filetoupload': None,
1627 'filetocreate': None,
1628 'changes': None,
1629 },
1630 'expect_parse_queuecommands': True,
1631 'expect_write_commands': True,
1632 }),
1633 ]
1634
1635 def test_calls_parse_queuecommands_with_expected_args(self):
1636 """ Should call `parse_queuecommands` with expected args. """
1637 self.function_to_test(**self.test_args)
1638 (expected_options, expected_arguments) = dput.dcut.getoptions()
1639 expected_config = self.runtime_config_parser
1640 if self.expect_parse_queuecommands:
1641 dput.dcut.parse_queuecommands.assert_called_with(
1642 expected_arguments, expected_options, expected_config)
1643 else:
1644 self.assertFalse(dput.dcut.parse_queuecommands.called)
1645
1646 def test_calls_write_commands_with_expected_args(self):
1647 """ Should call `write_commands` with expected args. """
1648 expected_commands = dput.dcut.parse_queuecommands.return_value
1649 self.function_to_test(**self.test_args)
1650 (expected_options, __) = dput.dcut.getoptions()
1651 expected_tempdir = getattr(
1652 self, 'expected_tempdir',
1653 self.tempfile_mkdtemp_file_double.path)
1654 if self.expect_write_commands:
1655 dput.dcut.write_commands.assert_called_with(
1656 expected_commands,
1657 options=expected_options,
1658 tempdir=expected_tempdir,
1659 )
1660 else:
1661 self.assertFalse(dput.dcut.write_commands.called)
1662
1663
1664 class dcut_WriteQueueCommandsTestCase(
1665 testscenarios.WithScenarios,
1666 dcut_TestCase):
1667 """ Test cases for `dcut` function, cleanup from exception. """
1668
1669 scenarios = [
1670 ('changes-file with-filetoupload with-filetocreate', {
1671 'getoptions_opts': {
1672 'filetoupload': tempfile.mktemp(),
1673 'filetocreate': tempfile.mktemp(),
1674 'changes': tempfile.mktemp(),
1675 },
1676 'expected_tempdir': None,
1677 }),
1678 ('changes-file no-filetoupload with-filetocreate', {
1679 'getoptions_opts': {
1680 'filetoupload': None,
1681 'filetocreate': tempfile.mktemp(),
1682 'changes': tempfile.mktemp(),
1683 },
1684 'expected_tempdir': None,
1685 }),
1686 ('changes-file with-filetoupload no-filetocreate', {
1687 'getoptions_opts': {
1688 'filetoupload': tempfile.mktemp(),
1689 'filetocreate': None,
1690 'changes': tempfile.mktemp(),
1691 },
1692 'expected_tempdir': None,
1693 }),
1694 ('changes-file no-filetoupload no-filetocreate', {
1695 'getoptions_opts': {
1696 'filetoupload': None,
1697 'filetocreate': None,
1698 'changes': tempfile.mktemp(),
1699 },
1700 }),
1701 ]
1702
1703
1704 class dcut_UploadFilesTestCase(
1705 testscenarios.WithScenarios,
1706 dcut_TestCase):
1707 """ Test cases for `dcut` function, call `upload_files`. """
1708
1709 debug_scenarios = [
1710 ('debug-default', {
1711 'expected_kwarg_debug': False,
1712 }),
1713 ('debug-true', {
1714 'getoptions_option_debug': True,
1715 'expected_kwarg_debug': True,
1716 }),
1717 ]
1718
1719 simulate_scenarios = [
1720 ('simulate-default', {
1721 'expected_kwarg_simulate': False,
1722 }),
1723 ('simulate-true', {
1724 'getoptions_option_simulate': True,
1725 'expected_kwarg_simulate': True,
1726 }),
1727 ]
1728
1729 passive_scenarios = [
1730 ('passive-default', {
1731 'expected_kwarg_commandline_passive': None,
1732 }),
1733 ('passive-true', {
1734 'getoptions_option_commandline_passive': True,
1735 'expected_kwarg_commandline_passive': True,
1736 }),
1737 ]
1738
1739 scenarios = testscenarios.multiply_scenarios(
1740 debug_scenarios, simulate_scenarios, passive_scenarios)
1741
1742 def setUp(self):
1743 """ Set up fixtures for this test case. """
1744 self.set_fake_getoptions()
1745 super().setUp()
1746
1747 self.set_expected_kwargs()
1748
1749 def set_fake_getoptions(self):
1750 """ Set the `getoptions` fake values based on scenario attributes. """
1751 self.getoptions_opts = {}
1752 for option_name in [
1753 'debug',
1754 'simulate',
1755 'commandline_passive',
1756 ]:
1757 scenario_attribute_name = (
1758 "getoptions_option_{}".format(option_name))
1759 if hasattr(self, scenario_attribute_name):
1760 fake_option_value = getattr(self, scenario_attribute_name)
1761 self.getoptions_opts[option_name] = fake_option_value
1762
1763 def set_expected_kwargs(self):
1764 """ Set the `expected_kwargs` based on scenario attributes. """
1765 self.expected_kwargs = {}
1766 for arg_name in [
1767 'debug',
1768 'simulate',
1769 'commandline_passive',
1770 'delay_days',
1771 ]:
1772 scenario_attribute_name = "expected_kwarg_{}".format(arg_name)
1773 if hasattr(self, scenario_attribute_name):
1774 expected_kwarg_value = getattr(self, scenario_attribute_name)
1775 self.expected_kwargs[arg_name] = expected_kwarg_value
1776
1777 def test_calls_upload_files_with_expected_args(self):
1778 """ Should call `upload_files` function with expected args. """
1779 expected_files_to_upload = [dput.dcut.write_commands.return_value]
1780 self.expected_args = (
1781 self.upload_methods,
1782 self.runtime_config_parser,
1783 self.test_host,
1784 expected_files_to_upload,
1785 )
1786 dput.dcut.dcut(**self.test_args)
1787 dput.dput.upload_files.assert_called_with(
1788 *self.expected_args, **self.expected_kwargs)
1789
1790
1791 class dcut_CleanupTestCase(
1792 testscenarios.WithScenarios,
1793 dcut_TestCase):
1794 """ Test cases for `dcut` function, cleanup from exception. """
1795
1796 commands_scenarios = [
1797 ('commands-from-arguments', {
1798 'getoptions_args': ["foo", "bar", "baz"],
1799 'getoptions_opts': {
1800 'filetocreate': None,
1801 'filetoupload': None,
1802 'changes': None,
1803 },
1804 }),
1805 ]
1806
1807 files_scenarios = [
1808 ('files-none', {
1809 'files_to_remove': [],
1810 }),
1811 ('files-one', {
1812 'files_to_remove': [tempfile.mktemp()],
1813 }),
1814 ('files-three', {
1815 'files_to_remove': [tempfile.mktemp() for __ in range(3)],
1816 }),
1817 ]
1818
1819 scenarios = testscenarios.multiply_scenarios(
1820 commands_scenarios, files_scenarios)
1821
1822 def test_removes_temporary_directory(self):
1823 """ Should remove directory `tempdir` at end. """
1824 self.function_to_test(**self.test_args)
1825 shutil.rmtree.assert_called_with(
1826 self.tempfile_mkdtemp_file_double.path)
1827
1828 def test_removes_temporary_directory_when_upload_raises_exception(self):
1829 """ Should remove directory `tempdir` when exception raised. """
1830 upload_method_func = dput.dput.upload_files
1831 upload_error = RuntimeError("Bad stuff happened")
1832 upload_method_func.side_effect = upload_error
1833 with testtools.ExpectedException(type(upload_error)):
1834 self.function_to_test(**self.test_args)
1835 shutil.rmtree.assert_called_with(
1836 self.tempfile_mkdtemp_file_double.path)
1837
1838
1839 # Copyright © 2015–2026 Ben Finney <[email protected]>
1840 #
1841 # This is free software: you may copy, modify, and/or distribute this work
1842 # under the terms of the GNU General Public License as published by the
1843 # Free Software Foundation; version 3 of that license or any later version.
1844 # No warranty expressed or implied. See the file ‘LICENSE.GPL-3’ for details.
1845
1846
1847 # Local variables:
1848 # coding: utf-8
1849 # mode: python
1850 # End:
1851 # vim: fileencoding=utf-8 filetype=python :