Debian Codegraph @

test/test_configfile.py

raw
1 # test/test_configfile.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 config file behaviour. """
9
10 import configparser
11 import contextlib
12 import doctest
13 import io
14 import os
15 import os.path
16 import sys
17 import tempfile
18 import textwrap
19 import unittest.mock
20
21 import testscenarios
22 import testtools
23 import testtools.matchers
24 import xdg
25
26 import dput.configfile
27 import dput.dput
28 from dput.helper import dputhelper
29
30 from .helper import (
31 EXIT_STATUS_FAILURE,
32 FakeSystemExit,
33 FileDouble,
34 make_expected_error_context,
35 make_unique_slug,
36 patch_os_isatty,
37 patch_os_path_exists,
38 patch_system_interfaces,
39 setup_file_double_behaviour,
40 )
41 from .test_dputhelper import (
42 patch_get_username_from_system,
43 )
44
45
46 def make_config_from_stream(
47 stream,
48 *,
49 init_kwargs=None,
50 ):
51 """ Make a ConfigParser parsed configuration from the stream content.
52
53 :param stream: Text stream content of a config file.
54 :param init_kwargs: Keyword arguments to initialise the new instance.
55 :return: The resulting `ConfigParser` if the content parses correctly,
56 or ``None``.
57 """
58 if init_kwargs is None:
59 init_kwargs = dict()
60 init_kwargs.update(dict(
61 defaults={
62 'allow_unsigned_uploads': "false",
63 },
64 ))
65 config = configparser.ConfigParser(**init_kwargs)
66
67 config_file = io.StringIO(stream)
68 try:
69 config.read_file(config_file)
70 except configparser.ParsingError:
71 config = None
72
73 return config
74
75
76 def make_config_file_scenarios(config_file_paths=None):
77 """ Make a collection of scenarios for testing with config files.
78
79 :return: A collection of scenarios for tests involving config files.
80
81 The collection is a mapping from scenario name to a dictionary of
82 scenario attributes.
83 """
84 if (config_file_paths is None):
85 config_file_paths = {}
86 runtime_config_file_path = config_file_paths.get(
87 'runtime', tempfile.mktemp())
88 global_config_file_path = config_file_paths.get(
89 'global', os.path.join(os.path.sep, "etc", "dput.cf"))
90 user_xdg_config_file_path = config_file_paths.get(
91 'user_xdg', os.path.join(xdg.xdg_config_home(), "dput", "dput.cf"))
92 user_home_config_file_path = config_file_paths.get(
93 'user_home', os.path.join(os.path.expanduser("~"), ".dput.cf"))
94
95 fake_file_empty = io.StringIO()
96 fake_file_bogus = io.StringIO("b0gUs")
97 fake_file_minimal = io.StringIO(textwrap.dedent("""\
98 [DEFAULT]
99 """))
100 fake_file_comments = io.StringIO(textwrap.dedent("""\
101 # Lorem ipsum, dolor sit amet.
102 # Lȏrėm îpsüm, dølòr sĭt ámέt.
103 [DEFAULT]
104 """))
105 fake_file_simple = io.StringIO(textwrap.dedent("""\
106 [DEFAULT]
107 hash = md5
108 [foo]
109 method = ftp
110 fqdn = quux.example.com
111 incoming = quux
112 check_version = false
113 allow_unsigned_uploads = false
114 allowed_distributions =
115 run_dinstall = false
116 """))
117 fake_file_simple_host_three = io.StringIO(textwrap.dedent("""\
118 [DEFAULT]
119 hash = md5
120 [foo]
121 method = ftp
122 fqdn = quux.example.com
123 incoming = quux
124 check_version = false
125 allow_unsigned_uploads = false
126 allowed_distributions =
127 run_dinstall = false
128 [bar]
129 fqdn = xyzzy.example.com
130 incoming = xyzzy
131 [baz]
132 fqdn = chmrr.example.com
133 incoming = chmrr
134 """))
135 fake_file_method_local = io.StringIO(textwrap.dedent("""\
136 [foo]
137 method = local
138 incoming = quux
139 """))
140 fake_file_missing_fqdn = io.StringIO(textwrap.dedent("""\
141 [foo]
142 method = ftp
143 incoming = quux
144 """))
145 fake_file_missing_incoming = io.StringIO(textwrap.dedent("""\
146 [foo]
147 method = ftp
148 fqdn = quux.example.com
149 """))
150 fake_file_default_not_unsigned = io.StringIO(textwrap.dedent("""\
151 [DEFAULT]
152 allow_unsigned_uploads = false
153 [foo]
154 method = ftp
155 fqdn = quux.example.com
156 """))
157 fake_file_default_distribution_only = io.StringIO(textwrap.dedent("""\
158 [DEFAULT]
159 default_host_main = consecteur
160 [ftp-master]
161 method = ftp
162 fqdn = quux.example.com
163 """))
164 fake_file_distribution_none = io.StringIO(textwrap.dedent("""\
165 [foo]
166 method = ftp
167 fqdn = quux.example.com
168 distributions =
169 """))
170 fake_file_distribution_one = io.StringIO(textwrap.dedent("""\
171 [foo]
172 method = ftp
173 fqdn = quux.example.com
174 distributions = spam
175 """))
176 fake_file_distribution_three = io.StringIO(textwrap.dedent("""\
177 [foo]
178 method = ftp
179 fqdn = quux.example.com
180 distributions = spam,eggs,beans
181 """))
182 fake_file_simple_nonstandard_default_section = io.StringIO(
183 textwrap.dedent("""\
184 [common]
185 hash = md5
186 [foo]
187 method = ftp
188 fqdn = quux.example.com
189 incoming = quux
190 check_version = false
191 allow_unsigned_uploads = false
192 allowed_distributions =
193 run_dinstall = false
194 """))
195
196 default_scenario_params = {
197 'runtime': {
198 'file_double_params': dict(
199 path=runtime_config_file_path,
200 fake_file=fake_file_comments),
201 'os_path_exists_scenario_name': 'exist',
202 'open_scenario_name': 'okay',
203 },
204 'global': {
205 'file_double_params': dict(
206 path=global_config_file_path,
207 fake_file=fake_file_comments),
208 'os_path_exists_scenario_name': 'exist',
209 'open_scenario_name': 'okay',
210 },
211 'user_xdg': {
212 'file_double_params': dict(
213 path=user_xdg_config_file_path,
214 fake_file=fake_file_comments),
215 'os_path_exists_scenario_name': 'exist',
216 'open_scenario_name': 'okay',
217 },
218 'user_home': {
219 'file_double_params': dict(
220 path=user_home_config_file_path,
221 fake_file=fake_file_comments),
222 'os_path_exists_scenario_name': 'exist',
223 'open_scenario_name': 'okay',
224 },
225 }
226
227 scenarios = {
228 'default': {
229 'configs_by_name': {
230 'runtime': None,
231 },
232 'expected_config_names': ['global', 'user_xdg'],
233 },
234 'not-exist': {
235 'configs_by_name': {
236 'runtime': {
237 'os_path_exists_scenario_name': 'not_exist',
238 'open_scenario_name': 'nonexist',
239 },
240 },
241 'expected_config_names': [],
242 },
243 'exist-read-denied': {
244 'configs_by_name': {
245 'runtime': {
246 'open_scenario_name': 'read_denied',
247 },
248 },
249 'expected_config_names': [],
250 },
251 'exist-empty': {
252 'configs_by_name': {
253 'runtime': {
254 'file_double_params': dict(
255 path=runtime_config_file_path,
256 fake_file=fake_file_empty),
257 },
258 },
259 'expected_config_names': ['runtime'],
260 },
261 'exist-invalid': {
262 'configs_by_name': {
263 'runtime': {
264 'file_double_params': dict(
265 path=runtime_config_file_path,
266 fake_file=fake_file_bogus),
267 },
268 },
269 'expected_config_names': ['runtime'],
270 },
271 'exist-minimal': {
272 'configs_by_name': {
273 'runtime': {
274 'file_double_params': dict(
275 path=runtime_config_file_path,
276 fake_file=fake_file_minimal),
277 },
278 },
279 'expected_config_names': ['runtime'],
280 },
281 'exist-simple': {
282 'configs_by_name': {
283 'runtime': {
284 'file_double_params': dict(
285 path=runtime_config_file_path,
286 fake_file=fake_file_simple),
287 'test_section': "foo",
288 },
289 },
290 'expected_config_names': ['runtime'],
291 },
292 'exist-simple-host-three': {
293 'configs_by_name': {
294 'runtime': {
295 'file_double_params': dict(
296 path=runtime_config_file_path,
297 fake_file=fake_file_simple_host_three),
298 'test_section': "foo",
299 },
300 },
301 'expected_config_names': ['runtime'],
302 },
303 'exist-method-local': {
304 'configs_by_name': {
305 'runtime': {
306 'file_double_params': dict(
307 path=runtime_config_file_path,
308 fake_file=fake_file_method_local),
309 'test_section': "foo",
310 },
311 },
312 'expected_config_names': ['runtime'],
313 },
314 'exist-missing-fqdn': {
315 'configs_by_name': {
316 'runtime': {
317 'file_double_params': dict(
318 path=runtime_config_file_path,
319 fake_file=fake_file_missing_fqdn),
320 'test_section': "foo",
321 },
322 },
323 'expected_config_names': ['runtime'],
324 },
325 'exist-missing-incoming': {
326 'configs_by_name': {
327 'runtime': {
328 'file_double_params': dict(
329 path=runtime_config_file_path,
330 fake_file=fake_file_missing_incoming),
331 'test_section': "foo",
332 },
333 },
334 'expected_config_names': ['runtime'],
335 },
336 'exist-default-not-unsigned': {
337 'configs_by_name': {
338 'runtime': {
339 'file_double_params': dict(
340 path=runtime_config_file_path,
341 fake_file=fake_file_default_not_unsigned),
342 'test_section': "foo",
343 },
344 },
345 'expected_config_names': ['runtime'],
346 },
347 'exist-default-distribution-only': {
348 'configs_by_name': {
349 'runtime': {
350 'file_double_params': dict(
351 path=runtime_config_file_path,
352 fake_file=fake_file_default_distribution_only),
353 'test_section': "foo",
354 },
355 },
356 'expected_config_names': ['runtime'],
357 },
358 'exist-distribution-none': {
359 'configs_by_name': {
360 'runtime': {
361 'file_double_params': dict(
362 path=runtime_config_file_path,
363 fake_file=fake_file_distribution_none),
364 'test_section': "foo",
365 },
366 },
367 'expected_config_names': ['runtime'],
368 },
369 'exist-distribution-one': {
370 'configs_by_name': {
371 'runtime': {
372 'file_double_params': dict(
373 path=runtime_config_file_path,
374 fake_file=fake_file_distribution_one),
375 'test_section': "foo",
376 },
377 },
378 'expected_config_names': ['runtime'],
379 },
380 'exist-distribution-three': {
381 'configs_by_name': {
382 'runtime': {
383 'file_double_params': dict(
384 path=runtime_config_file_path,
385 fake_file=fake_file_distribution_three),
386 'test_section': "foo",
387 },
388 },
389 'expected_config_names': ['runtime'],
390 },
391 'exist-simple-nonstandard-default-section': {
392 'configs_by_name': {
393 'runtime': {
394 'file_double_params': dict(
395 path=runtime_config_file_path,
396 fake_file=(
397 fake_file_simple_nonstandard_default_section),
398 ),
399 'init_kwargs': dict(
400 default_section="common",
401 ),
402 'test_section': "foo",
403 },
404 },
405 'expected_config_names': ['runtime'],
406 },
407 'global-config-not-exist': {
408 'configs_by_name': {
409 'global': {
410 'os_path_exists_scenario_name': 'not_exist',
411 'open_scenario_name': 'nonexist',
412 },
413 'runtime': None,
414 },
415 'expected_config_names': ['user_xdg'],
416 },
417 'global-config-read-denied': {
418 'configs_by_name': {
419 'global': {
420 'open_scenario_name': 'read_denied',
421 },
422 'runtime': None,
423 },
424 'expected_config_names': ['user_xdg'],
425 },
426 'user-xdg-config-not-exist': {
427 'configs_by_name': {
428 'user_xdg': {
429 'os_path_exists_scenario_name': 'not_exist',
430 'open_scenario_name': 'nonexist',
431 },
432 'user_home': {
433 'open_scenario_name': 'okay',
434 },
435 'runtime': None,
436 },
437 'expected_config_names': ['global', 'user_home'],
438 },
439 'user-xdg-config-read-denied': {
440 'configs_by_name': {
441 'user_xdg': {
442 'open_scenario_name': 'read_denied',
443 },
444 'user_home': {
445 'open_scenario_name': 'okay',
446 },
447 'runtime': None,
448 },
449 'expected_config_names': ['global', 'user_home'],
450 },
451 'user-xdg-config-not-exist-user-home-config-not-exist': {
452 'configs_by_name': {
453 'user_xdg': {
454 'os_path_exists_scenario_name': 'not_exist',
455 'open_scenario_name': 'nonexist',
456 },
457 'user_home': {
458 'os_path_exists_scenario_name': 'not_exist',
459 'open_scenario_name': 'nonexist',
460 },
461 'runtime': None,
462 },
463 'expected_config_names': ['global'],
464 },
465 'user-xdg-config-not-exist-user-home-config-read-denied': {
466 'configs_by_name': {
467 'user_xdg': {
468 'os_path_exists_scenario_name': 'not_exist',
469 'open_scenario_name': 'nonexist',
470 },
471 'user_home': {
472 'open_scenario_name': 'read_denied',
473 },
474 'runtime': None,
475 },
476 'expected_config_names': ['global'],
477 },
478 'all-not-exist': {
479 'configs_by_name': {
480 'global': {
481 'os_path_exists_scenario_name': 'not_exist',
482 'open_scenario_name': 'nonexist',
483 },
484 'user_xdg': {
485 'os_path_exists_scenario_name': 'not_exist',
486 'open_scenario_name': 'nonexist',
487 },
488 'user_home': {
489 'os_path_exists_scenario_name': 'not_exist',
490 'open_scenario_name': 'nonexist',
491 },
492 'runtime': None,
493 },
494 'expected_config_names': [],
495 },
496 'all-read-denied': {
497 'configs_by_name': {
498 'global': {
499 'open_scenario_name': 'read_denied',
500 },
501 'user_xdg': {
502 'open_scenario_name': 'read_denied',
503 },
504 'user_home': {
505 'open_scenario_name': 'read_denied',
506 },
507 'runtime': None,
508 },
509 'expected_config_names': [],
510 },
511 }
512
513 for scenario in scenarios.values():
514 scenario['empty_file'] = fake_file_empty
515 if 'configs_by_name' not in scenario:
516 scenario['configs_by_name'] = {}
517 for (config_name, default_params) in default_scenario_params.items():
518 if config_name not in scenario['configs_by_name']:
519 params = default_params
520 elif scenario['configs_by_name'][config_name] is None:
521 continue
522 else:
523 params = default_params.copy()
524 params.update(scenario['configs_by_name'][config_name])
525 params['file_double'] = FileDouble(**params['file_double_params'])
526 params['file_double'].set_os_path_exists_scenario(
527 params['os_path_exists_scenario_name'])
528 params['file_double'].set_open_scenario(
529 params['open_scenario_name'])
530 params['config'] = make_config_from_stream(
531 params['file_double'].fake_file.getvalue(),
532 init_kwargs=params.get('init_kwargs', None),
533 )
534 scenario['configs_by_name'][config_name] = params
535
536 return scenarios
537
538
539 def get_file_doubles_from_config_file_scenarios(scenarios):
540 """ Get the `FileDouble` instances from config file scenarios.
541
542 :param scenarios: Collection of config file scenarios.
543 :return: Collection of `FileDouble` instances.
544 """
545 doubles = set()
546 for scenario in scenarios:
547 configs_by_name = scenario['configs_by_name']
548 doubles.update(
549 configs_by_name[config_name]['file_double']
550 for config_name in ['global', 'user_home', 'runtime']
551 if configs_by_name[config_name] is not None)
552
553 return doubles
554
555
556 def setup_config_file_fixtures(testcase, config_file_paths=None):
557 """ Set up fixtures for config file doubles. """
558 if (config_file_paths is None):
559 config_file_paths = dput.configfile.default_config_paths
560 scenarios = make_config_file_scenarios(
561 config_file_paths=config_file_paths)
562 testcase.config_file_scenarios = scenarios
563
564 setup_file_double_behaviour(
565 testcase,
566 get_file_doubles_from_config_file_scenarios(scenarios.values()))
567 patch_os_path_exists(testcase)
568
569
570 def set_config(testcase, name):
571 """ Set the config scenario for a specific test case. """
572 scenarios = make_config_file_scenarios()
573 testcase.config_scenario = scenarios[name]
574
575
576 def patch_runtime_config_options(testcase):
577 """ Patch specific options in the runtime config. """
578 config_params_by_name = testcase.config_scenario['configs_by_name']
579 runtime_config_params = config_params_by_name['runtime']
580 testcase.runtime_config_parser = runtime_config_params['config']
581
582 def maybe_set_option(
583 parser, section_name, option_name, value, default=""):
584 if value is not None:
585 if value is NotImplemented:
586 # No specified value. Set a default.
587 value = default
588 parser.set(section_name, option_name, str(value))
589 else:
590 # Specifically requested *no* value for the option.
591 parser.remove_option(section_name, option_name)
592
593 if testcase.runtime_config_parser is not None:
594 testcase.test_host = runtime_config_params.get(
595 'test_section', None)
596
597 default_section_name = testcase.runtime_config_parser.default_section
598 maybe_set_option(
599 testcase.runtime_config_parser,
600 default_section_name, 'method',
601 getattr(testcase, 'config_default_method', "ftp"))
602 maybe_set_option(
603 testcase.runtime_config_parser,
604 default_section_name, 'login',
605 getattr(testcase, 'config_default_login', "username"))
606 maybe_set_option(
607 testcase.runtime_config_parser,
608 default_section_name, 'scp_compress',
609 getattr(testcase, 'config_default_scp_compress', False))
610 maybe_set_option(
611 testcase.runtime_config_parser,
612 default_section_name, 'ssh_config_options',
613 getattr(testcase, 'config_default_ssh_config_options', ""))
614 maybe_set_option(
615 testcase.runtime_config_parser,
616 default_section_name, 'distributions',
617 getattr(testcase, 'config_default_distributions', ""))
618 maybe_set_option(
619 testcase.runtime_config_parser,
620 default_section_name, 'incoming',
621 getattr(testcase, 'config_default_incoming', "quux"))
622 maybe_set_option(
623 testcase.runtime_config_parser,
624 default_section_name, 'allow_dcut',
625 getattr(testcase, 'config_default_allow_dcut', True))
626
627 config_default_default_host_main = getattr(
628 testcase, 'config_default_default_host_main', NotImplemented)
629 maybe_set_option(
630 testcase.runtime_config_parser,
631 default_section_name, 'default_host_main',
632 config_default_default_host_main,
633 default="")
634 config_default_delayed = getattr(
635 testcase, 'config_default_delayed', NotImplemented)
636 maybe_set_option(
637 testcase.runtime_config_parser,
638 default_section_name, 'delayed', config_default_delayed,
639 default=7)
640
641 for section_name in testcase.runtime_config_parser.sections():
642 maybe_set_option(
643 testcase.runtime_config_parser,
644 section_name, 'method',
645 getattr(testcase, 'config_method', "ftp"))
646 maybe_set_option(
647 testcase.runtime_config_parser,
648 section_name, 'allowed_distributions',
649 getattr(
650 testcase, 'config_allowed_distributions', ""))
651 maybe_set_option(
652 testcase.runtime_config_parser,
653 section_name, 'login',
654 getattr(testcase, 'config_login', "username"))
655 maybe_set_option(
656 testcase.runtime_config_parser,
657 section_name, 'fqdn',
658 getattr(testcase, 'config_fqdn', "quux.example.com"))
659 maybe_set_option(
660 testcase.runtime_config_parser,
661 section_name, 'passive_ftp',
662 getattr(testcase, 'config_passive_ftp', False))
663 maybe_set_option(
664 testcase.runtime_config_parser,
665 section_name, 'run_lintian',
666 getattr(testcase, 'config_run_lintian', False))
667 maybe_set_option(
668 testcase.runtime_config_parser,
669 section_name, 'run_dinstall',
670 getattr(testcase, 'config_run_dinstall', False))
671 maybe_set_option(
672 testcase.runtime_config_parser,
673 section_name, 'pre_upload_command',
674 getattr(testcase, 'config_pre_upload_command', ""))
675 maybe_set_option(
676 testcase.runtime_config_parser,
677 section_name, 'post_upload_command',
678 getattr(testcase, 'config_post_upload_command', ""))
679 maybe_set_option(
680 testcase.runtime_config_parser,
681 section_name, 'progress_indicator',
682 getattr(testcase, 'config_progress_indicator', 0))
683 maybe_set_option(
684 testcase.runtime_config_parser,
685 section_name, 'allow_dcut',
686 getattr(testcase, 'config_allow_dcut', True))
687 config_incoming = getattr(
688 testcase, 'config_incoming', NotImplemented)
689 maybe_set_option(
690 testcase.runtime_config_parser,
691 section_name, 'incoming', config_incoming,
692 default=tempfile.mktemp())
693 config_delayed = getattr(
694 testcase, 'config_delayed', NotImplemented)
695 maybe_set_option(
696 testcase.runtime_config_parser,
697 section_name, 'delayed', config_delayed,
698 default=9)
699
700 for (section_type, options) in (
701 getattr(testcase, 'config_extras', {}).items()):
702 section_name = {
703 'default': default_section_name,
704 'host': testcase.test_host,
705 }[section_type]
706 for (option_name, option_value) in options.items():
707 maybe_set_option(
708 testcase.runtime_config_parser,
709 section_name, option_name, option_value)
710
711
712 def set_config_file_scenario(testcase, name=None):
713 """ Set the configuration file scenario for `testcase`.
714
715 :param testcase: The `TestCase` instance to modify.
716 :param name: The identifying name of the scenario to set on `testcase`.
717 :return: ``None``.
718 """
719 if name is None:
720 name = getattr(testcase, 'config_file_scenario_name', 'exist-minimal')
721 testcase.config_file_scenario = testcase.config_file_scenarios[name]
722 testcase.configs_by_name = testcase.config_file_scenario['configs_by_name']
723 for config_params in testcase.configs_by_name.values():
724 if config_params is not None:
725 config_params['file_double'].register_for_testcase(testcase)
726
727
728 def get_path_for_runtime_config_file(testcase):
729 """ Get the path to specify for runtime config file. """
730 path = None
731 runtime_config_params = testcase.configs_by_name['runtime']
732 if runtime_config_params is not None:
733 runtime_config_file_double = runtime_config_params['file_double']
734 path = runtime_config_file_double.path
735 return path
736
737
738 def patch_default_config_paths(testcase, fake_paths=NotImplemented):
739 """ Patch the `default_config_paths` object during `testcase`. """
740 if (fake_paths is NotImplemented):
741 fake_paths = {
742 name: testcase.getUniqueString()
743 for name in ['global', 'user_xdg', 'user_home', 'lorem_ipsum']
744 }
745 patcher = unittest.mock.patch.object(
746 dput.configfile, "default_config_paths",
747 new=fake_paths)
748 patcher.start()
749 testcase.addCleanup(patcher.stop)
750
751
752 class active_config_files_TestCase(
753 testscenarios.WithScenarios,
754 testtools.TestCase):
755 """ Test cases for `active_config_files` function. """
756
757 scenarios = [
758 ('default', {
759 'config_scenario_name': 'default',
760 'expected_debug_output': None,
761 }),
762 ('exist-minimal', {
763 'config_scenario_name': 'exist-minimal',
764 'expected_debug_output': None,
765 }),
766 ('not-exist', {
767 'config_scenario_name': 'not-exist',
768 'expected_debug_output': "skipping",
769 }),
770 ('exist-read-denied', {
771 'config_scenario_name': 'exist-read-denied',
772 'expected_debug_output': "skipping",
773 }),
774 ('global-config-not-exist', {
775 'config_scenario_name': 'global-config-not-exist',
776 'expected_debug_output': "skipping",
777 }),
778 ('user-xdg-config-not-exist', {
779 'config_scenario_name': 'user-xdg-config-not-exist',
780 'expected_debug_output': "skipping",
781 }),
782 ('user-xdg-config-read-denied', {
783 'config_scenario_name': 'user-xdg-config-read-denied',
784 'expected_debug_output': "skipping",
785 }),
786 ('user-xdg-config-not-exist-user-home-config-not-exist', {
787 'config_scenario_name':
788 'user-xdg-config-not-exist-user-home-config-not-exist',
789 'expected_debug_output': "skipping",
790 }),
791 ('user-xdg-config-not-exist-user-home-config-read-denied', {
792 'config_scenario_name':
793 'user-xdg-config-not-exist-user-home-config-read-denied',
794 'expected_debug_output': "skipping",
795 }),
796 ('all-not-exist', {
797 'config_scenario_name': 'all-not-exist',
798 'expected_debug_output': "skipping",
799 }),
800 ('all-read-denied', {
801 'config_scenario_name': 'all-read-denied',
802 'expected_debug_output': "skipping",
803 }),
804 ]
805
806 def setUp(self):
807 """ Set up test fixtures. """
808 super().setUp()
809 patch_system_interfaces(self)
810 patch_default_config_paths(self)
811 setup_config_file_fixtures(self)
812
813 set_config_file_scenario(self, self.config_scenario_name)
814 self.expected_config_names = (
815 self.config_file_scenario['expected_config_names'])
816 self.set_test_args()
817
818 def set_test_args(self):
819 """ Set the arguments for the test call to the function. """
820 runtime_config_file_path = get_path_for_runtime_config_file(self)
821 self.test_args = dict(
822 config_path=runtime_config_file_path,
823 debug=False,
824 )
825
826 def test_emits_skip_message_when_debug_true(self):
827 """ Should emit a “skipping” message when `debug` is true. """
828 if (not self.expected_debug_output):
829 self.skipTest("no skip message expected in this scenario")
830 self.test_args['debug'] = True
831 with contextlib.suppress(dput.configfile.ConfigurationError):
832 all(dput.configfile.active_config_files(**self.test_args))
833 expected_output = self.expected_debug_output
834 self.assertIn(expected_output, sys.stderr.getvalue())
835
836 def test_emits_no_skip_message_when_debug_false(self):
837 """ Should not emit a “skipping” message when `debug` is false. """
838 self.test_args['debug'] = False
839 with contextlib.suppress(dput.configfile.ConfigurationError):
840 all(dput.configfile.active_config_files(**self.test_args))
841 unwanted_output = self.expected_debug_output
842 self.assertNotIn(unwanted_output, sys.stderr.getvalue())
843
844 def test_yields_expected_config_files(self):
845 """ Should yield a sequence of the expected configuration files. """
846 if not self.expected_config_names:
847 self.skipTest("Normal return not expected in this scenario")
848 with contextlib.ExitStack() as exit_stack:
849 expected_files_list = [
850 exit_stack.enter_context(open(path, encoding='UTF-8'))
851 for path in (
852 self.configs_by_name[config_name]['file_double'].path
853 for config_name in self.expected_config_names)
854 ]
855 self.addCleanup(exit_stack.close)
856 result_list = list(
857 dput.configfile.active_config_files(**self.test_args))
858 self.assertEqual(expected_files_list, result_list)
859
860 def test_raise_error_if_all_config_files_fail(self):
861 """
862 Should raise `ConfigurationError` if unable to open any config files.
863 """
864 if self.expected_config_names:
865 self.skipTest("No error expected for this scenario")
866 expected_message_regex = (
867 "^Could not open any configfile, tried .*")
868 with testtools.ExpectedException(
869 dput.configfile.ConfigurationError,
870 value_re=expected_message_regex):
871 all(dput.configfile.active_config_files(**self.test_args))
872
873
874 def patch_active_config_files(testcase):
875 """ Patch the `active_config_files` function for `testcase`. """
876 if not hasattr(testcase, 'fake_config_files'):
877 testcase.fake_config_files = [
878 FileDouble(path)
879 for path in (testcase.getUniqueString() for __ in range(3))
880 ]
881
882 def fake_active_config_files(*args, **kwargs):
883 yield from testcase.fake_config_files
884
885 func_patcher = unittest.mock.patch.object(
886 dput.configfile, "active_config_files", autospec=True,
887 side_effect=fake_active_config_files)
888 func_patcher.start()
889 testcase.addCleanup(func_patcher.stop)
890
891
892 class read_configs_TestCase(
893 testscenarios.WithScenarios,
894 testtools.TestCase):
895 """ Test cases for `read_configs` function. """
896
897 config_file_scenarios = make_config_file_scenarios().items()
898
899 scenarios = testscenarios.multiply_scenarios(config_file_scenarios)
900
901 def setUp(self):
902 """ Set up test fixtures. """
903 super().setUp()
904 patch_system_interfaces(self)
905 setup_config_file_fixtures(self)
906
907 set_config_file_scenario(self)
908 self.test_configparser = self.configs_by_name['runtime']['config']
909 self.patch_class_configparser(instance=self.test_configparser)
910 self.set_test_args()
911
912 def patch_class_configparser(self, *, instance):
913 """ Patch the `ConfigParser` class for this test case. """
914 self.mock_configparser_class = unittest.mock.MagicMock(
915 spec=configparser.ConfigParser,
916 return_value=instance)
917
918 patcher_class_configparser = unittest.mock.patch.object(
919 configparser, "ConfigParser",
920 new=self.mock_configparser_class)
921 patcher_class_configparser.start()
922 self.addCleanup(patcher_class_configparser.stop)
923
924 def set_test_args(self):
925 """ Set the arguments for the test call to the function. """
926 config_files = [
927 config_params['file_double'].fake_file
928 for config_params in self.configs_by_name.values()]
929 self.test_args = [config_files]
930 self.test_kwargs = dict(
931 debug=False,
932 )
933
934 def test_creates_new_parser(self):
935 """ Should invoke the `ConfigParser` constructor. """
936 with contextlib.suppress(FakeSystemExit):
937 dput.configfile.read_configs(*self.test_args, **self.test_kwargs)
938 configparser.ConfigParser.assert_called_with()
939
940 def test_returns_expected_configparser(self):
941 """ Should return expected `ConfigParser` instance. """
942 with contextlib.suppress(FakeSystemExit):
943 result = dput.configfile.read_configs(
944 *self.test_args, **self.test_kwargs)
945 self.assertEqual(self.test_configparser, result)
946
947 def test_sets_default_option_values(self):
948 """ Should set values for options, in default section. """
949 option_names = {
950 'login',
951 'method',
952 'hash',
953 'allow_unsigned_uploads',
954 'allow_dcut',
955 'distributions',
956 'allowed_distributions',
957 'run_lintian',
958 'run_dinstall',
959 'check_version',
960 'scp_compress',
961 'default_host_main',
962 'post_upload_command',
963 'pre_upload_command',
964 'ssh_config_options',
965 'passive_ftp',
966 'progress_indicator',
967 'delayed',
968 }
969 with contextlib.suppress(FakeSystemExit):
970 result = dput.configfile.read_configs(
971 *self.test_args, **self.test_kwargs)
972 option_names_in_default_section = set(result.defaults())
973 self.assertTrue(option_names.issubset(option_names_in_default_section))
974
975 def test_emits_debug_message_on_parsing_config_file(self):
976 """ Should emit a debug message when parsing each config file. """
977 self.test_kwargs['debug'] = True
978 config_file_double = self.configs_by_name['runtime']['file_double']
979 with contextlib.suppress(FakeSystemExit):
980 dput.configfile.read_configs(*self.test_args, **self.test_kwargs)
981 expected_output = textwrap.dedent("""\
982 D: Parsing configuration file ‘{path}’
983 """).format(path=config_file_double.path)
984 self.assertIn(expected_output, sys.stdout.getvalue())
985
986 def test_calls_sys_exit_if_config_parsing_error(self):
987 """ Should call `sys.exit` if a parsing error occurs. """
988 set_config_file_scenario(self, 'exist-invalid')
989 self.set_test_args()
990 self.test_kwargs['debug'] = True
991 with testtools.ExpectedException(FakeSystemExit):
992 dput.configfile.read_configs(*self.test_args, **self.test_kwargs)
993 expected_output = textwrap.dedent("""\
994 Error parsing configuration file:
995 ...
996 """)
997 self.assertThat(
998 sys.stderr.getvalue(),
999 testtools.matchers.DocTestMatches(
1000 expected_output, flags=doctest.ELLIPSIS))
1001 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1002
1003 def test_sets_fqdn_option_if_local_method(self):
1004 """ Should set “fqdn” option for “local” method. """
1005 set_config_file_scenario(self, 'exist-method-local')
1006 self.set_test_args()
1007 with contextlib.suppress(FakeSystemExit):
1008 result = dput.configfile.read_configs(
1009 *self.test_args, **self.test_kwargs)
1010 runtime_config_params = self.configs_by_name['runtime']
1011 test_section = runtime_config_params['test_section']
1012 self.assertTrue(result.has_option(test_section, "fqdn"))
1013
1014 def test_exits_with_error_if_missing_fqdn(self):
1015 """ Should exit with error if config is missing 'fqdn'. """
1016 set_config_file_scenario(self, 'exist-missing-fqdn')
1017 self.set_test_args()
1018 with testtools.ExpectedException(FakeSystemExit):
1019 dput.configfile.read_configs(*self.test_args, **self.test_kwargs)
1020 expected_output = textwrap.dedent("""\
1021 Config error: {host} must have a fqdn set
1022 """).format(host="foo")
1023 self.assertIn(expected_output, sys.stderr.getvalue())
1024 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1025
1026 def test_exits_with_error_if_missing_incoming(self):
1027 """ Should exit with error if config is missing 'incoming'. """
1028 set_config_file_scenario(self, 'exist-missing-incoming')
1029 self.set_test_args()
1030 with testtools.ExpectedException(FakeSystemExit):
1031 dput.configfile.read_configs(*self.test_args, **self.test_kwargs)
1032 expected_output = textwrap.dedent("""\
1033 Config error: {host} must have an incoming directory set
1034 """).format(host="foo")
1035 self.assertIn(expected_output, sys.stderr.getvalue())
1036 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1037
1038
1039 def patch_read_configs(testcase):
1040 """ Patch the `read_configs` function for the test case. """
1041 def fake_read_configs(*args, **kwargs):
1042 return testcase.runtime_config_parser
1043
1044 func_patcher = unittest.mock.patch.object(
1045 dput.configfile, "read_configs", autospec=True,
1046 side_effect=fake_read_configs)
1047 func_patcher.start()
1048 testcase.addCleanup(func_patcher.stop)
1049
1050
1051 class print_config_TestCase(testtools.TestCase):
1052 """ Test cases for `print_config` function. """
1053
1054 def setUp(self):
1055 """ Set up test fixtures. """
1056 super().setUp()
1057 patch_system_interfaces(self)
1058
1059 def test_invokes_config_write_to_stdout(self):
1060 """ Should invoke config's `write` method with `sys.stdout`. """
1061 test_config = make_config_from_stream("")
1062 mock_config = unittest.mock.Mock(test_config)
1063 dput.configfile.print_config(mock_config, debug=False)
1064 mock_config.write.assert_called_with(sys.stdout)
1065
1066
1067 def patch_print_config(testcase):
1068 """ Patch the `print_config` function for the test case. """
1069 func_patcher = unittest.mock.patch.object(
1070 dput.configfile, "print_config", autospec=True)
1071 func_patcher.start()
1072 testcase.addCleanup(func_patcher.stop)
1073
1074
1075 class print_default_upload_method_TestCase(testtools.TestCase):
1076 """ Test cases for `print_default_upload_method` function. """
1077
1078 def setUp(self):
1079 """ Set up test fixtures. """
1080 super().setUp()
1081 patch_system_interfaces(self)
1082
1083 set_config(self, 'exist-simple')
1084 patch_runtime_config_options(self)
1085
1086 self.set_test_args()
1087
1088 def set_test_args(self):
1089 """ Set the arguments for the test call to the function. """
1090 self.test_args = dict(
1091 config=self.runtime_config_parser,
1092 )
1093
1094 def test_emits_default_method(self):
1095 """ Should emit default upload method name to stdout. """
1096 dput.configfile.print_default_upload_method(**self.test_args)
1097 expected_output = textwrap.dedent("""\
1098
1099 Default Method: {method}
1100
1101 """).format(
1102 method=self.runtime_config_parser.get(
1103 self.runtime_config_parser.default_section,
1104 'method'))
1105 self.assertThat(
1106 sys.stdout.getvalue(),
1107 testtools.matchers.DocTestMatches(
1108 expected_output, doctest.ELLIPSIS))
1109
1110
1111 def patch_print_default_upload_method(testcase):
1112 """ Patch `print_default_upload_method` function for the `testcase`. """
1113 func_patcher = unittest.mock.patch.object(
1114 dput.configfile, "print_default_upload_method", autospec=True,
1115 return_value=testcase.config_login)
1116 func_patcher.start()
1117 testcase.addCleanup(func_patcher.stop)
1118
1119
1120 class print_host_list_TestCase(
1121 testscenarios.WithScenarios,
1122 testtools.TestCase):
1123 """ Test cases for `print_host_list` function. """
1124
1125 scenarios = [
1126 ('default', {}),
1127 ('config-distribution-one', {
1128 'config_scenario_name': "exist-distribution-one",
1129 }),
1130 ('config-distribution-three', {
1131 'config_scenario_name': "exist-distribution-three",
1132 }),
1133 ]
1134
1135 def setUp(self):
1136 """ Set up test fixtures. """
1137 super().setUp()
1138 patch_system_interfaces(self)
1139
1140 config_scenario_name = getattr(
1141 self, 'config_scenario_name',
1142 'exist-simple')
1143 set_config(self, config_scenario_name)
1144 patch_runtime_config_options(self)
1145
1146 self.set_test_args()
1147
1148 def set_test_args(self):
1149 """ Set the arguments for the test call to the function. """
1150 self.test_args = dict(
1151 config=self.runtime_config_parser,
1152 )
1153
1154 def test_emits_all_config_sections(self):
1155 """ Should iteratively emit all config sections to stdout. """
1156 dput.configfile.print_host_list(**self.test_args)
1157 expected_output_lines = [
1158 "{section} => {fqdn} (Upload method: {method}...)".format(
1159 section=section_name,
1160 fqdn=self.runtime_config_parser.get(section_name, 'fqdn'),
1161 method=self.runtime_config_parser.get(
1162 section_name, 'method'),
1163 )
1164 for section_name in self.runtime_config_parser.sections()
1165 ] + ["..."]
1166 expected_output = "\n".join(expected_output_lines)
1167 self.assertThat(
1168 sys.stdout.getvalue(),
1169 testtools.matchers.DocTestMatches(
1170 expected_output, doctest.ELLIPSIS))
1171
1172
1173 def patch_print_host_list(testcase):
1174 """ Patch the `print_host_list` function for the `testcase`. """
1175 func_patcher = unittest.mock.patch.object(
1176 dput.configfile, "print_host_list", autospec=True)
1177 func_patcher.start()
1178 testcase.addCleanup(func_patcher.stop)
1179
1180
1181 class verify_distribution_for_host_TestCase(
1182 testscenarios.WithScenarios,
1183 testtools.TestCase):
1184 """ Test cases for `verify_distribution_for_host` function. """
1185
1186 function_to_test = staticmethod(
1187 dput.configfile.verify_distribution_for_host)
1188
1189 scenarios = [
1190 ('distribution-any no-allowed-pattern', {
1191 'test_distribution': "spam",
1192 'config_scenario_name': "exist-distribution-one",
1193 'test_host': "foo",
1194 'expected_result': None,
1195 }),
1196 ('distribution-match allowed-pattern-narrow', {
1197 'test_distribution': "spam",
1198 'config_scenario_name': "exist-distribution-one",
1199 'config_allowed_distributions': "spam",
1200 'test_host': "foo",
1201 'expected_result': None,
1202 }),
1203 ('distribution-no-match allowed-pattern-narrow', {
1204 'test_distribution': "beans",
1205 'config_scenario_name': "exist-distribution-one",
1206 'config_allowed_distributions': "spam",
1207 'test_host': "foo",
1208 'expected_error': dputhelper.DputUploadFatalError,
1209 }),
1210 ('distribution-match allowed-pattern-broad', {
1211 'test_distribution': "spam",
1212 'config_scenario_name': "exist-distribution-one",
1213 'config_allowed_distributions': "(spam|eggs|ham)",
1214 'test_host': "foo",
1215 'expected_result': None,
1216 }),
1217 ('distribution-no-match allowed-pattern-broad', {
1218 'test_distribution': "beans",
1219 'config_scenario_name': "exist-distribution-one",
1220 'config_allowed_distributions': "(spam|eggs|ham)",
1221 'test_host': "foo",
1222 'expected_error': dputhelper.DputUploadFatalError,
1223 }),
1224 ]
1225
1226 def setUp(self):
1227 """ Set up test fixtures. """
1228 super().setUp()
1229 patch_system_interfaces(self)
1230
1231 set_config(self, 'exist-simple')
1232 patch_runtime_config_options(self)
1233
1234 self.set_test_args()
1235
1236 def set_test_args(self):
1237 """ Set test args for this test case. """
1238 self.test_args = []
1239 self.test_kwargs = {
1240 'distribution': self.test_distribution,
1241 'host': self.test_host,
1242 'config': self.runtime_config_parser,
1243 'debug': False,
1244 }
1245
1246 def test_returns_expected_result_or_raises_exception(self):
1247 """ Should return expected result or raise expected exception. """
1248 with make_expected_error_context(self):
1249 result = self.function_to_test(*self.test_args, **self.test_kwargs)
1250 if not hasattr(self, 'expected_error'):
1251 self.assertEqual(self.expected_result, result)
1252
1253 def test_emits_debug_message_when_allowed_distributions(self):
1254 """ Should emit a debug message when `allowed_distributions` set. """
1255 if not getattr(self, 'config_allowed_distributions', ""):
1256 self.skipTest("no `allowed_distributions` to match")
1257 self.test_kwargs['debug'] = True
1258 with make_expected_error_context(self):
1259 self.function_to_test(*self.test_args, **self.test_kwargs)
1260 expected_output_params = dict(
1261 distribution=self.test_distribution,
1262 allowed_distributions=self.config_allowed_distributions,
1263 )
1264 expected_output = (
1265 "D: Checking: distribution {distribution}"
1266 " matches {allowed_distributions}"
1267 ).format(**expected_output_params)
1268 self.assertIn(expected_output, sys.stderr.getvalue())
1269
1270 def test_emits_no_debug_message_when_not_debug(self):
1271 """ Should not emit debug message when `debug` not set. """
1272 if not getattr(self, 'config_allowed_distributions', ""):
1273 self.skipTest("no `allowed_distributions` to match")
1274 self.test_kwargs['debug'] = False
1275 with make_expected_error_context(self):
1276 self.function_to_test(*self.test_args, **self.test_kwargs)
1277 expected_output = "D: Checking: distribution ... matches ..."
1278 self.assertThat(
1279 sys.stderr.getvalue(),
1280 testtools.matchers.Not(
1281 testtools.matchers.DocTestMatches(
1282 expected_output, flags=doctest.ELLIPSIS)
1283 ))
1284
1285 def test_emits_no_debug_message_when_no_allowed_distributions(self):
1286 """
1287 Should not emit debug message when `allowed_distributions` empty.
1288 """
1289 if getattr(self, 'config_allowed_distributions', ""):
1290 self.skipTest("`allowed_distributions` has distributions")
1291 self.test_kwargs['debug'] = True
1292 with make_expected_error_context(self):
1293 self.function_to_test(*self.test_args, **self.test_kwargs)
1294 expected_output = "D: Checking: distribution ... matches ..."
1295 self.assertThat(
1296 sys.stderr.getvalue(),
1297 testtools.matchers.Not(
1298 testtools.matchers.DocTestMatches(
1299 expected_output, flags=doctest.ELLIPSIS)
1300 ))
1301
1302
1303 def patch_verify_distribution_for_host(testcase):
1304 """ Patch `verify_distribution_for_host` function during `testcase`. """
1305 func_patcher = unittest.mock.patch.object(
1306 dput.dput, "verify_distribution_for_host", autospec=True)
1307 func_patcher.start()
1308 testcase.addCleanup(func_patcher.stop)
1309
1310
1311 class get_upload_method_name_for_host_TestCase(
1312 testscenarios.WithScenarios,
1313 testtools.TestCase):
1314 """ Test cases for `get_upload_method_name_for_host` function. """
1315
1316 scenarios = [
1317 ('config-default-method', {
1318 'config_default_method': "method-from-config-default",
1319 'config_method': None,
1320 'expected_result': "method-from-config-default",
1321 }),
1322 ('config-host-method', {
1323 'config_method': "method-from-config-host",
1324 'expected_result': "method-from-config-host",
1325 }),
1326 ('config-default-and-host-method', {
1327 'config_default_method': "method-from-config-default",
1328 'config_method': "method-from-config-host",
1329 'expected_result': "method-from-config-host",
1330 }),
1331 ]
1332
1333 def setUp(self):
1334 """ Set up test fixtures. """
1335 super().setUp()
1336 patch_system_interfaces(self)
1337
1338 set_config(self, 'exist-simple')
1339 patch_runtime_config_options(self)
1340
1341 self.set_test_args()
1342
1343 def set_test_args(self):
1344 """ Set the arguments for the test call to the function. """
1345 self.test_args = dict(
1346 config=self.runtime_config_parser,
1347 host=self.test_host,
1348 )
1349
1350 def test_returns_expected_result(self):
1351 """ Should return expected method name for host configuration. """
1352 result = dput.dput.get_upload_method_name_for_host(**self.test_args)
1353 self.assertEqual(self.expected_result, result)
1354
1355
1356 def patch_get_upload_method_name_for_host(testcase):
1357 """ Patch `get_upload_method_name_for_host` function for `testcase`. """
1358 if not hasattr(testcase, 'get_upload_method_name_for_host_return_value'):
1359 method_name = testcase.runtime_config_parser.get(
1360 testcase.test_host, 'method')
1361 testcase.get_upload_method_name_for_host_return_value = method_name
1362 func_patcher = unittest.mock.patch.object(
1363 dput.dput, "get_upload_method_name_for_host", autospec=True,
1364 return_value=testcase.get_upload_method_name_for_host_return_value)
1365 func_patcher.start()
1366 testcase.addCleanup(func_patcher.stop)
1367
1368
1369 class get_login_for_host_TestCase(
1370 testscenarios.WithScenarios,
1371 testtools.TestCase):
1372 """ Test cases for `get_login_for_host` function. """
1373
1374 function_to_test = staticmethod(dput.dput.get_login_for_host)
1375
1376 scenarios = [
1377 ('config-no-login', {
1378 'config_extras': {
1379 'default': {
1380 'login': None,
1381 },
1382 'host': {
1383 'login': None,
1384 },
1385 },
1386 'system_username': "login-from-system",
1387 'expected_result': "login-from-system",
1388 'expected_output_template': (
1389 "D: Setting 'login' to"
1390 " system account username '{login}'"
1391 ),
1392 }),
1393 ('config-default-login', {
1394 'config_extras': {
1395 'default': {
1396 'login': "login-from-config-default",
1397 },
1398 'host': {
1399 'login': None,
1400 },
1401 },
1402 'system_username': "login-from-system",
1403 'expected_result': "login-from-config-default",
1404 'expected_output_template':
1405 "D: Using configured 'login' value '{login}'",
1406 }),
1407 ('config-host-login', {
1408 'config_extras': {
1409 'default': {
1410 'login': "login-from-config-default",
1411 },
1412 'host': {
1413 'login': "login-from-config-host",
1414 },
1415 },
1416 'system_username': "login-from-system",
1417 'expected_result': "login-from-config-host",
1418 'expected_output_template':
1419 "D: Using configured 'login' value '{login}'",
1420 }),
1421 ('config-default-login sentinel', {
1422 'config_extras': {
1423 'default': {
1424 'login': "username",
1425 },
1426 'host': {
1427 'login': None,
1428 },
1429 },
1430 'system_username': "login-from-system",
1431 'expected_result': "login-from-system",
1432 'expected_output_template': (
1433 "D: Setting 'login' to"
1434 " system account username '{login}'"
1435 ),
1436 }),
1437 ('config-host-login sentinel', {
1438 'config_extras': {
1439 'default': {
1440 'login': "login-from-config-default",
1441 },
1442 'host': {
1443 'login': "username",
1444 },
1445 },
1446 'system_username': "login-from-system",
1447 'expected_result': "login-from-system",
1448 'expected_output_template': (
1449 "D: Setting 'login' to"
1450 " system account username '{login}'"
1451 ),
1452 }),
1453 ]
1454
1455 def setUp(self):
1456 """ Set up test fixtures. """
1457 super().setUp()
1458 patch_system_interfaces(self)
1459
1460 set_config(
1461 self,
1462 getattr(self, 'config_scenario_name', 'exist-simple'))
1463 patch_runtime_config_options(self)
1464
1465 patch_get_username_from_system(self)
1466
1467 self.set_test_args()
1468
1469 def set_test_args(self):
1470 """ Set the arguments for the test call to the function. """
1471 self.test_args = dict(
1472 config=self.runtime_config_parser,
1473 host=self.test_host,
1474 debug=False,
1475 )
1476
1477 def test_emits_debug_message_for_config_interrogation(self):
1478 """ Should emit debug message for interrogation of config. """
1479 self.test_args['debug'] = True
1480 self.function_to_test(**self.test_args)
1481 expected_output = (
1482 "D: Interrogate host '{host}' config for 'login'".format(
1483 host=self.test_host))
1484 self.assertIn(expected_output, sys.stdout.getvalue())
1485
1486 def test_emits_debug_message_for_discovered_values(self):
1487 """ Should emit debug message for values discovered. """
1488 self.test_args['debug'] = True
1489 self.function_to_test(**self.test_args)
1490 expected_output = self.expected_output_template.format(
1491 host=self.test_host, login=self.expected_result)
1492 self.assertIn(expected_output, sys.stdout.getvalue())
1493
1494 def test_returns_expected_result(self):
1495 """ Should return expected login value for host configuration. """
1496 result = self.function_to_test(**self.test_args)
1497 self.assertEqual(self.expected_result, result)
1498
1499
1500 def patch_get_login_for_host(testcase):
1501 """ Patch the `get_login_for_host` function for the `testcase`. """
1502 if not hasattr(testcase, 'config_login'):
1503 testcase.config_login = make_unique_slug(testcase)
1504 func_patcher = unittest.mock.patch.object(
1505 dput.dput, "get_login_for_host", autospec=True,
1506 return_value=testcase.config_login)
1507 func_patcher.start()
1508 testcase.addCleanup(func_patcher.stop)
1509
1510
1511 class get_fqdn_for_host_TestCase(
1512 testscenarios.WithScenarios,
1513 testtools.TestCase):
1514 """ Test cases for `get_fqdn_for_host` function. """
1515
1516 scenarios = [
1517 ('config-method-http', {
1518 'config_extras': {
1519 'host': {
1520 'method': "http",
1521 'fqdn': "fqdn-from-config-host",
1522 },
1523 },
1524 'expected_result': "fqdn-from-config-host",
1525 }),
1526 ('config-method-http port-443', {
1527 'config_extras': {
1528 'host': {
1529 'method': "http",
1530 'fqdn': "fqdn-from-config-host:443",
1531 },
1532 },
1533 'expected_result': "fqdn-from-config-host",
1534 }),
1535 ('config-method-ftp', {
1536 'config_extras': {
1537 'host': {
1538 'method': "ftp",
1539 'fqdn': "fqdn-from-config-host",
1540 },
1541 },
1542 'expected_result': "fqdn-from-config-host",
1543 }),
1544 ('config-method-ftp port-21', {
1545 'config_extras': {
1546 'host': {
1547 'method': "ftp",
1548 'fqdn': "fqdn-from-config-host:21",
1549 },
1550 },
1551 'expected_result': "fqdn-from-config-host",
1552 }),
1553 ('config-method-ftp port-42', {
1554 'config_extras': {
1555 'host': {
1556 'method': "ftp",
1557 'fqdn': "fqdn-from-config-host:42",
1558 },
1559 },
1560 'expected_result': "fqdn-from-config-host",
1561 }),
1562 ('config-method-local', {
1563 'config_extras': {
1564 'host': {
1565 'method': "local",
1566 'fqdn': "fqdn-from-config-host",
1567 },
1568 },
1569 'expected_result': "localhost",
1570 }),
1571 ]
1572
1573 def setUp(self):
1574 """ Set up test fixtures. """
1575 super().setUp()
1576 patch_system_interfaces(self)
1577
1578 set_config(self, 'exist-simple')
1579 patch_runtime_config_options(self)
1580
1581 self.set_test_args()
1582
1583 def set_test_args(self):
1584 """ Set the arguments for the test call to the function. """
1585 self.test_args = dict(
1586 config=self.runtime_config_parser,
1587 host=self.test_host,
1588 )
1589
1590 def test_returns_expected_result(self):
1591 """ Should return expected FQDN value for host configuration. """
1592 result = dput.dput.get_fqdn_for_host(**self.test_args)
1593 self.assertEqual(self.expected_result, result)
1594
1595
1596 def patch_get_fqdn_for_host(testcase):
1597 """ Patch the `get_fqdn_for_host` function for the `testcase`. """
1598 if hasattr(testcase, 'get_fqdn_for_host_return_value'):
1599 return_value = testcase.get_fqdn_for_host_return_value
1600 elif hasattr(testcase, 'config_fqdn'):
1601 return_value = testcase.config_fqdn
1602 else:
1603 return_value = make_unique_slug(testcase)
1604 func_patcher = unittest.mock.patch.object(
1605 dput.dput, "get_fqdn_for_host", autospec=True,
1606 return_value=return_value)
1607 func_patcher.start()
1608 testcase.addCleanup(func_patcher.stop)
1609
1610
1611 class get_port_for_host_TestCase(
1612 testscenarios.WithScenarios,
1613 testtools.TestCase):
1614 """ Test cases for `get_port_for_host` function. """
1615
1616 scenarios = [
1617 ('config-method-http', {
1618 'config_extras': {
1619 'host': {
1620 'method': "http",
1621 'fqdn': "fqdn-from-config-host",
1622 },
1623 },
1624 'expected_result': None,
1625 }),
1626 ('config-method-http port-443', {
1627 'config_extras': {
1628 'host': {
1629 'method': "http",
1630 'fqdn': "fqdn-from-config-host:443",
1631 },
1632 },
1633 'expected_result': 443,
1634 }),
1635 ('config-method-ftp', {
1636 'config_extras': {
1637 'host': {
1638 'method': "ftp",
1639 'fqdn': "fqdn-from-config-host",
1640 },
1641 },
1642 'expected_result': None,
1643 }),
1644 ('config-method-ftp port-21', {
1645 'config_extras': {
1646 'host': {
1647 'method': "ftp",
1648 'fqdn': "fqdn-from-config-host:21",
1649 },
1650 },
1651 'expected_result': 21,
1652 }),
1653 ('config-method-ftp port-42', {
1654 'config_extras': {
1655 'host': {
1656 'method': "ftp",
1657 'fqdn': "fqdn-from-config-host:42",
1658 },
1659 },
1660 'expected_result': 42,
1661 }),
1662 ('config-method-local', {
1663 'config_extras': {
1664 'host': {
1665 'method': "local",
1666 'fqdn': "fqdn-from-config-host",
1667 },
1668 },
1669 'expected_result': None,
1670 }),
1671 ]
1672
1673 def setUp(self):
1674 """ Set up test fixtures. """
1675 super().setUp()
1676 patch_system_interfaces(self)
1677
1678 set_config(self, 'exist-simple')
1679 patch_runtime_config_options(self)
1680
1681 self.set_test_args()
1682
1683 def set_test_args(self):
1684 """ Set the arguments for the test call to the function. """
1685 self.test_args = dict(
1686 config=self.runtime_config_parser,
1687 host=self.test_host,
1688 )
1689
1690 def test_returns_expected_result(self):
1691 """ Should return expected port value for host configuration. """
1692 result = dput.dput.get_port_for_host(**self.test_args)
1693 self.assertEqual(self.expected_result, result)
1694
1695
1696 def patch_get_port_for_host(testcase):
1697 """ Patch the `get_port_for_host` function for the `testcase`. """
1698 if hasattr(testcase, 'get_port_for_host_return_value'):
1699 return_value = testcase.get_port_for_host_return_value
1700 else:
1701 return_value = testcase.getUniqueInteger()
1702 func_patcher = unittest.mock.patch.object(
1703 dput.dput, "get_port_for_host", autospec=True,
1704 return_value=return_value)
1705 func_patcher.start()
1706 testcase.addCleanup(func_patcher.stop)
1707
1708
1709 class get_delayed_days_TestCase(
1710 testscenarios.WithScenarios,
1711 testtools.TestCase):
1712 """ Test cases for `get_delayed_days` function. """
1713
1714 scenarios = [
1715 ('valid numerals', {
1716 'option_arg_text': "11",
1717 'expected_result': 11,
1718 }),
1719 ('invalid none', {
1720 'option_arg_text': None,
1721 'expected_exception': TypeError,
1722 }),
1723 ('invalid empty-string', {
1724 'option_arg_text': "",
1725 'expected_exception': TypeError,
1726 }),
1727 ('invalid not-text', {
1728 'option_arg_text': object(),
1729 'expected_exception': TypeError,
1730 }),
1731 ('invalid <0', {
1732 'option_arg_text': "-1",
1733 'expected_exception': ValueError,
1734 }),
1735 ('invalid >15', {
1736 'option_arg_text': "16",
1737 'expected_exception': ValueError,
1738 }),
1739 ('invalid malformed', {
1740 'option_arg_text': "b0gUs",
1741 'expected_exception': TypeError,
1742 }),
1743 ]
1744
1745 def setUp(self):
1746 """ Set up test fixtures. """
1747 super().setUp()
1748
1749 set_config(self, 'exist-simple')
1750 patch_runtime_config_options(self)
1751
1752 self.set_test_args()
1753
1754 def set_test_args(self):
1755 """ Set the arguments for the test call to the function. """
1756 self.test_args = dict(
1757 days_text=self.option_arg_text,
1758 )
1759
1760 def test_returns_expected_result(self):
1761 """ Should give expected result for inputs. """
1762 if hasattr(self, 'expected_exception'):
1763 with testtools.ExpectedException(self.expected_exception):
1764 dput.dput.get_delayed_days(**self.test_args)
1765 else:
1766 result = dput.dput.get_delayed_days(**self.test_args)
1767 self.assertEqual(self.expected_result, result)
1768
1769
1770 def patch_get_delayed_days(testcase):
1771 """ Patch the `get_delayed_days` function for the `testcase`. """
1772 if not hasattr(testcase, 'get_delayed_days_return_value'):
1773 testcase.get_delayed_days_return_value = None
1774 func_patcher = unittest.mock.patch.object(
1775 dput.dput, 'get_delayed_days', autospec=True,
1776 return_value=testcase.get_delayed_days_return_value)
1777 func_patcher.start()
1778 testcase.addCleanup(func_patcher.stop)
1779
1780
1781 class get_incoming_for_host_TestCase(
1782 testscenarios.WithScenarios,
1783 testtools.TestCase):
1784 """ Test cases for `get_incoming_for_host` function. """
1785
1786 scenarios = [
1787 ('default-incoming', {
1788 'config_default_incoming': "incoming-from-config-default",
1789 'config_incoming': None,
1790 'expected_result': "incoming-from-config-default",
1791 }),
1792 ('host-incoming no-trailing-slash', {
1793 'config_default_incoming': "incoming-from-config-default",
1794 'config_incoming': "incoming-from-config",
1795 'expected_result': "incoming-from-config",
1796 }),
1797 ('host-incoming with-trailing-slash', {
1798 'config_default_incoming': "incoming-from-config-default",
1799 'config_incoming': "incoming-from-config/",
1800 'expected_result': "incoming-from-config",
1801 }),
1802 ]
1803
1804 def setUp(self):
1805 """ Set up test fixtures. """
1806 super().setUp()
1807
1808 set_config(self, 'exist-simple')
1809 patch_runtime_config_options(self)
1810
1811 self.set_test_args()
1812
1813 def set_test_args(self):
1814 """ Set the arguments for the test call to the function. """
1815 self.test_args = dict(
1816 config=self.runtime_config_parser,
1817 host=self.test_host,
1818 )
1819
1820 def test_returns_expected_result(self):
1821 """ Should return expected incoming path value. """
1822 result = dput.dput.get_incoming_for_host(**self.test_args)
1823 self.assertEqual(self.expected_result, result)
1824
1825
1826 def patch_get_incoming_for_host(testcase):
1827 """ Patch the `get_incoming_for_host` function for the `testcase`. """
1828 if not hasattr(testcase, 'get_incoming_for_host_return_value'):
1829 testcase.get_incoming_for_host_return_value = tempfile.mktemp()
1830 func_patcher = unittest.mock.patch.object(
1831 dput.dput, "get_incoming_for_host", autospec=True,
1832 return_value=testcase.get_incoming_for_host_return_value)
1833 func_patcher.start()
1834 testcase.addCleanup(func_patcher.stop)
1835
1836
1837 class get_progress_indicator_for_host_TestCase(
1838 testscenarios.WithScenarios,
1839 testtools.TestCase):
1840 """ Test cases for `get_progress_indicator_for_host` function. """
1841
1842 config_scenarios = [
1843 ('config-default', {
1844 'expected_result': 0,
1845 }),
1846 ('config-specifies-progress', {
1847 'config_progress_indicator': 23,
1848 'expected_result': 23,
1849 }),
1850 ]
1851
1852 isatty_scenarios = [
1853 ('isatty-true', {
1854 'os_isatty_return_value': True,
1855 }),
1856 ('isatty-false', {
1857 'os_isatty_return_value': False,
1858 'progress_indicator_override': 0,
1859 }),
1860 ]
1861
1862 scenarios = testscenarios.multiply_scenarios(
1863 config_scenarios, isatty_scenarios)
1864
1865 for (scenario_name, scenario) in scenarios:
1866 if 'progress_indicator_override' in scenario:
1867 scenario['expected_result'] = scenario[
1868 'progress_indicator_override']
1869
1870 def setUp(self):
1871 """ Set up test fixtures. """
1872 super().setUp()
1873
1874 set_config(
1875 self,
1876 getattr(self, 'config_scenario_name', 'exist-simple'))
1877 patch_runtime_config_options(self)
1878
1879 patch_os_isatty(self)
1880
1881 self.set_test_args()
1882
1883 def set_test_args(self):
1884 """ Set the arguments for the test call to the function. """
1885 self.test_args = dict(
1886 config=self.runtime_config_parser,
1887 host=self.test_host,
1888 )
1889
1890 def test_returns_expected_result(self):
1891 """ Should return expected progress indicator value. """
1892 result = dput.dput.get_progress_indicator_for_host(**self.test_args)
1893 self.assertEqual(self.expected_result, result)
1894
1895
1896 def patch_get_progress_indicator_for_host(testcase):
1897 """ Patch `get_progress_indicator_for_host` function for `testcase`. """
1898 if not hasattr(testcase, 'get_progress_indicator_for_host_return_value'):
1899 testcase.get_progress_indicator_for_host_return_value = 0
1900 func_patcher = unittest.mock.patch.object(
1901 dput.dput, "get_progress_indicator_for_host", autospec=True,
1902 return_value=testcase.get_progress_indicator_for_host_return_value)
1903 func_patcher.start()
1904 testcase.addCleanup(func_patcher.stop)
1905
1906
1907 class get_upload_method_names_TestCase(
1908 testscenarios.WithScenarios,
1909 testtools.TestCase):
1910 """ Test cases for `get_upload_method_names` function. """
1911
1912 function_to_test = staticmethod(dput.configfile.get_upload_method_names)
1913
1914 config_file_scenarios = [
1915 ('exist-simple', {
1916 'config_scenario_name': "exist-simple",
1917 }),
1918 ('exist-simple-nonstandard-default-section', {
1919 'config_scenario_name': (
1920 "exist-simple-nonstandard-default-section"),
1921 }),
1922 ]
1923
1924 config_item_scenarios = [
1925 ('no-default-method no-host-method', {
1926 'config_extras': {
1927 'default': {
1928 'method': None,
1929 },
1930 'host': {
1931 'method': None,
1932 },
1933 },
1934 'expected_result': {
1935 configparser.DEFAULTSECT: None,
1936 'foo': None,
1937 },
1938 }),
1939 ('default-method-bogus no-host-method', {
1940 'config_extras': {
1941 'default': {
1942 'method': "b0gUs",
1943 },
1944 'host': {
1945 'method': None,
1946 },
1947 },
1948 'expected_result': {
1949 configparser.DEFAULTSECT: "b0gUs",
1950 'foo': "b0gUs",
1951 },
1952 }),
1953 ('default-method-bogus host-method-ftp', {
1954 'config_extras': {
1955 'default': {
1956 'method': "b0gUs",
1957 },
1958 'host': {
1959 'method': "ftp",
1960 },
1961 },
1962 'expected_result': {
1963 configparser.DEFAULTSECT: "b0gUs",
1964 'foo': "ftp",
1965 },
1966 }),
1967 ('no-default-method host-method-ftp', {
1968 'config_extras': {
1969 'default': {
1970 'method': None,
1971 },
1972 'host': {
1973 'method': "ftp",
1974 },
1975 },
1976 'expected_result': {
1977 configparser.DEFAULTSECT: None,
1978 'foo': "ftp",
1979 },
1980 }),
1981 ]
1982
1983 scenarios = testscenarios.multiply_scenarios(
1984 config_file_scenarios, config_item_scenarios)
1985
1986 def setUp(self):
1987 """ Set up test fixtures. """
1988 super().setUp()
1989 patch_system_interfaces(self)
1990
1991 set_config(
1992 self,
1993 getattr(self, 'config_scenario_name', 'exist-simple'))
1994 patch_runtime_config_options(self)
1995
1996 self.update_expected_result_for_default_section()
1997
1998 self.set_test_args()
1999
2000 def update_expected_result_for_default_section(self):
2001 """ Update the `expected_result` based on `default_section` value. """
2002 self.expected_result = {
2003 (
2004 self.runtime_config_parser.default_section
2005 if (name == configparser.DEFAULTSECT)
2006 else name
2007 ): value
2008 for (name, value) in self.expected_result.items()
2009 }
2010
2011 def set_test_args(self):
2012 """ Set the arguments for the test call to the function. """
2013 self.test_args = [self.runtime_config_parser]
2014 self.test_kwargs = dict(
2015 host=self.test_host,
2016 )
2017
2018 def test_returns_expected_result(self):
2019 """ Should return expected result, given the configuration. """
2020 result = self.function_to_test(*self.test_args, **self.test_kwargs)
2021 self.assertEqual(self.expected_result, result)
2022
2023
2024 class verify_config_upload_methods_BaseTestCase(
2025 testtools.TestCase):
2026 """ Base for test cases for `verify_config_upload_methods` function. """
2027
2028 function_to_test = staticmethod(dput.dput.verify_config_upload_methods)
2029
2030 def setUp(self):
2031 """ Set up test fixtures. """
2032 super().setUp()
2033 patch_system_interfaces(self)
2034
2035 set_config(
2036 self,
2037 getattr(self, 'config_scenario_name', 'exist-simple'))
2038 patch_runtime_config_options(self)
2039
2040 self.upload_methods = {
2041 name: unittest.mock.MagicMock()
2042 for name in ["local", "ftp", "scp"]}
2043
2044 self.set_test_args()
2045
2046 def set_test_args(self):
2047 """ Set the arguments for the test call to the function. """
2048 self.test_args = [self.runtime_config_parser]
2049 self.test_kwargs = dict(
2050 host=self.test_host,
2051 upload_methods=self.upload_methods,
2052 debug=False,
2053 )
2054
2055
2056 class verify_config_upload_methods_SuccessTestCase(
2057 testscenarios.WithScenarios,
2058 verify_config_upload_methods_BaseTestCase):
2059 """ Test cases for `verify_config_upload_methods`, when successful. """
2060
2061 scenarios = [
2062 ('exist-simple', {
2063 'config_scenario_name': "exist-simple",
2064 }),
2065 ('exist-simple-nonstandard-default-section', {
2066 'config_scenario_name': (
2067 "exist-simple-nonstandard-default-section"),
2068 }),
2069 ]
2070
2071 def test_emits_debug_message_for_discovered_methods(self):
2072 """ Should emit debug message for discovered upload methods. """
2073 self.test_kwargs['debug'] = True
2074 self.function_to_test(*self.test_args, **self.test_kwargs)
2075 expected_output = textwrap.dedent("""\
2076 D: Default Method: {default_method}
2077 D: Host Method: {host_method}
2078 """).format(
2079 default_method=self.runtime_config_parser.get(
2080 self.runtime_config_parser.default_section, 'method'),
2081 host_method=self.runtime_config_parser.get(
2082 self.test_host, 'method'))
2083 self.assertIn(expected_output, sys.stdout.getvalue())
2084
2085
2086 class verify_config_upload_methods_UnknownUploadMethodTestCase(
2087 testscenarios.WithScenarios,
2088 verify_config_upload_methods_BaseTestCase):
2089 """ Test cases for `verify_config_upload_methods`, when unknown method. """
2090
2091 scenarios = [
2092 ('bogus-default-method', {
2093 'config_extras': {
2094 'default': {
2095 'method': "b0gUs",
2096 },
2097 },
2098 'expected_output': "Unknown upload method: b0gUs",
2099 }),
2100 ('bogus-host-method', {
2101 'config_extras': {
2102 'host': {
2103 'method': "b0gUs",
2104 },
2105 },
2106 'expected_output': "Unknown upload method: b0gUs",
2107 }),
2108 ]
2109
2110 def test_emits_error_message_when_unknown_method(self):
2111 """ Should emit error message when unknown upload method. """
2112 with contextlib.suppress(FakeSystemExit):
2113 self.function_to_test(*self.test_args, **self.test_kwargs)
2114 self.assertIn(self.expected_output, sys.stdout.getvalue())
2115
2116 def test_calls_sys_exit_when_unknown_method(self):
2117 """ Should call `sys.exit` when unknown upload method. """
2118 with testtools.ExpectedException(FakeSystemExit):
2119 self.function_to_test(*self.test_args, **self.test_kwargs)
2120 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
2121
2122
2123 def patch_verify_config_upload_methods(testcase):
2124 """ Patch `verify_config_upload_methods` function for the `testcase`. """
2125 func_patcher = unittest.mock.patch.object(
2126 dput.dput, "verify_config_upload_methods", autospec=True)
2127 func_patcher.start()
2128 testcase.addCleanup(func_patcher.stop)
2129
2130
2131 # Copyright © 2015–2026 Ben Finney <[email protected]>
2132 #
2133 # This is free software: you may copy, modify, and/or distribute this work
2134 # under the terms of the GNU General Public License as published by the
2135 # Free Software Foundation; version 3 of that license or any later version.
2136 # No warranty expressed or implied. See the file ‘LICENSE.GPL-3’ for details.
2137
2138
2139 # Local variables:
2140 # coding: utf-8
2141 # mode: python
2142 # End:
2143 # vim: fileencoding=utf-8 filetype=python :