Debian Codegraph @

test/test_dputhelper.py

raw
1 # test/test_dputhelper.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 ‘dput.helper.dputhelper’ module. """
9
10 import collections
11 import doctest
12 import io
13 import subprocess
14 import sys
15 import textwrap
16 import unittest.mock
17
18 import testscenarios
19 import testtools
20 import testtools.matchers
21
22 from dput.helper import dputhelper
23
24 from .helper import (
25 EXIT_STATUS_COMMAND_NOT_FOUND,
26 EXIT_STATUS_FAILURE,
27 EXIT_STATUS_SUCCESS,
28 PasswdEntry,
29 SubprocessDouble,
30 make_fake_distribution,
31 make_unique_slug,
32 patch_importlib_metadata_distribution,
33 patch_locale_getpreferredencoding,
34 patch_os_environ,
35 patch_os_getuid,
36 patch_pwd_getpwuid,
37 patch_subprocess_check_call,
38 patch_sys_argv,
39 patch_system_interfaces,
40 )
41
42
43 class check_call_TestCase(
44 testscenarios.WithScenarios,
45 testtools.TestCase):
46 """ Test cases for `check_call` function. """
47
48 default_args = collections.OrderedDict([
49 ('args', ["arg-{}".format(n) for n in range(5)]),
50 ])
51
52 scenarios = [
53 ('success', {
54 'test_args': default_args.copy(),
55 'subprocess_check_call_scenario_name': 'success',
56 'expected_exit_status': EXIT_STATUS_SUCCESS,
57 }),
58 ('failure', {
59 'test_args': default_args.copy(),
60 'subprocess_check_call_scenario_name': 'failure',
61 'expected_exit_status': EXIT_STATUS_FAILURE,
62 'expected_output': textwrap.dedent("""\
63 Warning: The execution of '...' as
64 '...'
65 returned a nonzero exit code.
66 """)
67 }),
68 ('not-found', {
69 'test_args': default_args.copy(),
70 'subprocess_check_call_scenario_name': 'not_found',
71 'expected_exit_status': EXIT_STATUS_COMMAND_NOT_FOUND,
72 'expected_output': textwrap.dedent("""\
73 Error: Failed to execute '...'.
74 The file may not exist or not be executable.
75 """)
76 }),
77 ]
78
79 def setUp(self):
80 """ Set up test fixtures. """
81 super().setUp()
82 patch_system_interfaces(self)
83
84 patch_subprocess_check_call(self)
85
86 self.set_subprocess_double()
87
88 def set_subprocess_double(self):
89 """ Set the test double for the subprocess. """
90 command_file_path = self.test_args['args'][0]
91 command_argv = self.test_args['args']
92 double = SubprocessDouble(command_file_path, command_argv)
93 double.register_for_testcase(self)
94 double.set_subprocess_check_call_scenario(
95 self.subprocess_check_call_scenario_name)
96 self.subprocess_double = double
97
98 def test_calls_os_spawnv_with_specified_args(self):
99 """ Should call `subprocess.check_call` with specified arguments. """
100 dputhelper.check_call(*self.test_args.values())
101 subprocess.check_call.assert_called_with(*self.test_args.values())
102
103 def test_returns_expected_exit_status(self):
104 """ Should return expected exit status for subprocess. """
105 exit_status = dputhelper.check_call(*self.test_args.values())
106 self.assertEqual(self.expected_exit_status, exit_status)
107
108 def test_emits_expected_output(self):
109 """ Should emit the expected output messages. """
110 if not hasattr(self, 'expected_output'):
111 self.expected_output = ""
112 dputhelper.check_call(*self.test_args.values())
113 self.assertThat(
114 sys.stderr.getvalue(),
115 testtools.matchers.DocTestMatches(
116 self.expected_output, flags=doctest.ELLIPSIS))
117
118
119 class FileWithProgress_TestCase(
120 testscenarios.WithScenarios,
121 testtools.TestCase):
122 """ Base for test cases for the `FileWithProgress` class. """
123
124 default_args = {
125 'ptype': dputhelper.ProgressOutputStyle.NONE,
126 'progressf': sys.__stdout__,
127 'size': -1,
128 'step': 1024,
129 }
130
131 def setUp(self):
132 """ Set up test fixtures. """
133 super().setUp()
134 patch_system_interfaces(self)
135
136 self.test_file = io.StringIO(
137 getattr(self, 'content', ""))
138
139 self.set_test_args()
140 self.make_instance()
141
142 def set_test_args(self):
143 """ Set the arguments for the test instance constructor. """
144 self.test_args = dict(
145 f=self.test_file,
146 )
147 if hasattr(self, 'test_ptype'):
148 self.test_args['ptype'] = self.test_ptype
149 if hasattr(self, 'test_progressf'):
150 self.test_args['progressf'] = self.test_progressf
151 if hasattr(self, 'test_size'):
152 self.test_args['size'] = self.test_size
153 if hasattr(self, 'test_step'):
154 self.test_args['step'] = self.test_step
155
156 def make_instance(self):
157 """ Make the test instance of the class. """
158 self.instance = dputhelper.FileWithProgress(**self.test_args)
159
160
161 class FileWithProgress_ArgsTestCase(FileWithProgress_TestCase):
162 """ Test cases for constructor arguments for `FileWithProgress` class. """
163
164 scenarios = [
165 ('simple', {}),
166 ('all args', {
167 'test_ptype': dputhelper.ProgressOutputStyle.SPINNER,
168 'test_progressf': io.StringIO(),
169 'test_size': 10,
170 'test_step': 2,
171 }),
172 ]
173
174 def test_has_specified_file(self):
175 """ Should have specified file object as `f` attribute. """
176 self.assertIs(self.test_file, self.instance.f)
177
178 def test_has_specified_ptype(self):
179 """ Should have specified progress type value as `ptype` attribute. """
180 expected_ptype = getattr(
181 self, 'test_ptype', self.default_args['ptype'])
182 self.assertEqual(expected_ptype, self.instance.ptype)
183
184 def test_has_specified_progressf(self):
185 """ Should have specified progress file as `progressf` attribute. """
186 expected_progressf = getattr(
187 self, 'test_progressf', self.default_args['progressf'])
188 self.assertEqual(expected_progressf, self.instance.progressf)
189
190 def test_has_specified_size(self):
191 """ Should have specified size value as `size` attribute. """
192 expected_size = getattr(
193 self, 'test_size', self.default_args['size'])
194 self.assertEqual(expected_size, self.instance.size)
195
196 def test_has_specified_step(self):
197 """ Should have specified step value as `step` attribute. """
198 expected_step = getattr(
199 self, 'test_step', self.default_args['step'])
200 self.assertEqual(expected_step, self.instance.step)
201
202 def test_has_attributes_from_component_file(self):
203 """ Should have attributes directly from component file. """
204 attr_names = [
205 'b0gUs',
206 'mode', 'name', 'encoding',
207 'readable', 'seekable', 'writable',
208 'seek', 'tell', 'write',
209 ]
210 for attr_name in attr_names:
211 expected_attr_value = getattr(self.test_file, attr_name, None)
212 self.expectThat(
213 getattr(self.instance, attr_name, None),
214 testtools.matchers.Equals(expected_attr_value))
215
216
217 class FileWithProgress_OutputTestCase(FileWithProgress_TestCase):
218 """ Test cases for progress output for `FileWithProgress` class. """
219
220 content_scenarios = [
221 ('empty', {
222 'content': "",
223 }),
224 ('10 000 chars', {
225 'content': "0123456789\n" * 1000,
226 }),
227 ('10 000 000 chars', {
228 'content': "0123456789\n" * 1000000,
229 }),
230 ]
231
232 ptype_scenarios = [
233 ('ptype default', {}),
234 ('ptype NONE', {
235 'test_ptype': dputhelper.ProgressOutputStyle.NONE,
236 }),
237 ('ptype SPINNER', {
238 'test_ptype': dputhelper.ProgressOutputStyle.SPINNER
239 }),
240 ('ptype COUNT_AND_TOTAL', {
241 'test_ptype': dputhelper.ProgressOutputStyle.COUNT_AND_TOTAL,
242 }),
243 ]
244
245 size_scenarios = [
246 ('size default', {}),
247 ('size 0', {
248 'test_size': 0,
249 }),
250 ('size specified', {
251 'specify_file_size': True,
252 }),
253 ]
254
255 step_scenarios = [
256 ('step default', {}),
257 ('step 5', {'test_step': 5}),
258 ('step 500', {'test_step': 500}),
259 ('step 50 000', {'test_step': 50000}),
260 ]
261
262 scenarios = testscenarios.multiply_scenarios(
263 content_scenarios, ptype_scenarios,
264 size_scenarios, step_scenarios)
265
266 def setUp(self):
267 """ Set up test fixtures. """
268 super().setUp()
269
270 self.test_file = io.StringIO(self.content)
271 self.test_progressf = io.StringIO()
272 self.set_test_args()
273 self.make_instance()
274
275 if getattr(self, 'specify_file_size', False):
276 self.test_size = len(self.content)
277 self.set_expected_output()
278
279 def set_expected_output(self):
280 """ Set the expected output for this test case. """
281 ptype = getattr(self, 'test_ptype', self.default_args['ptype'])
282 match ptype:
283 case dputhelper.ProgressOutputStyle.SPINNER:
284 self.expected_output = "/"
285 case dputhelper.ProgressOutputStyle.COUNT_AND_TOTAL:
286 step = getattr(self, 'test_step', 1024)
287 total_bytes = len(self.content)
288 total_hunks = int(total_bytes / step)
289 total_hunks_text = "{size:d}k".format(size=total_hunks)
290 file_size = getattr(
291 self, 'test_size', self.default_args['size'])
292 total_steps = int(
293 (total_bytes + step - 1) / step)
294 if not file_size:
295 total_steps = 0
296 total_steps_text = "{size:d}k".format(size=total_steps)
297 progress_text = "{hunks}/{steps}".format(
298 hunks=total_hunks_text, steps=total_steps_text)
299 if file_size < 0 or getattr(self, 'specify_file_size', False):
300 progress_text = total_hunks_text
301 self.expected_output = progress_text
302 case (dputhelper.ProgressOutputStyle.NONE | _):
303 self.expected_output = ""
304
305 if not self.content:
306 # No progress output for an empty file.
307 self.expected_output = ""
308
309 def test_emits_expected_output_for_content(self):
310 """ Should emit expected output for file content. """
311 self.instance.read()
312 output_stream_content = self.test_progressf.getvalue()
313 self.assertEqual(
314 self.expected_output, output_stream_content)
315
316 def test_clears_output_on_close(self):
317 """ Should clear progress output when closed. """
318 self.instance.read()
319 self.instance.close()
320 expected_output = "{output}{backspaces}{spaces}{backspaces}".format(
321 output=self.expected_output,
322 backspaces=(len(self.expected_output) * "\b"),
323 spaces=(len(self.expected_output) * " "),
324 )
325 output_stream_content = self.test_progressf.getvalue()
326 self.assertEqual(expected_output, output_stream_content)
327
328
329 def patch_filewithprogress(testcase):
330 """ Patch the `FileWithProgress` class for the test case. """
331 if not hasattr(testcase, 'fake_filewithprogress'):
332 testcase.fake_filewithprogress = unittest.mock.MagicMock(
333 spec=dputhelper.FileWithProgress, name="FileWithProgress")
334
335 def fake_filewithprogress_factory(
336 f, ptype=0, progressf=sys.stdout, size=-1, step=1024):
337 result = testcase.fake_filewithprogress
338 result.f = f
339 result.ptype = ptype
340 result.progressf = progressf
341 result.size = size
342 result.step = step
343 return result
344
345 func_patcher = unittest.mock.patch.object(
346 dputhelper, "FileWithProgress", autospec=True,
347 side_effect=fake_filewithprogress_factory)
348 func_patcher.start()
349 testcase.addCleanup(func_patcher.stop)
350
351
352 class make_text_stream_TestCase(
353 testscenarios.WithScenarios,
354 testtools.TestCase):
355 """ Test cases for `make_text_stream` function. """
356
357 locale_getpreferredencoding_return_value = "johab"
358
359 scenarios = [
360 ('text-stream-no-encoding', {
361 'fake_file_params': {
362 'type': io.StringIO,
363 'content': "Lorem ipsum",
364 'encoding': None,
365 },
366 'expected_encoding': None,
367 'expected_content': "Lorem ipsum",
368 }),
369 ('text-stream', {
370 'fake_file_params': {
371 'type': io.TextIOWrapper,
372 'content': "Lorem ipsum",
373 'encoding': "utf-8",
374 },
375 'expected_encoding': "utf-8",
376 'expected_content': "Lorem ipsum",
377 }),
378 ('byte-stream', {
379 'fake_file_params': {
380 'type': io.BytesIO,
381 'content': "Lorem ipsum".encode(
382 locale_getpreferredencoding_return_value),
383 },
384 'expected_encoding': locale_getpreferredencoding_return_value,
385 'expected_content': "Lorem ipsum",
386 }),
387 ]
388
389 def setUp(self):
390 """ Set up test fixtures. """
391 super().setUp()
392
393 patch_locale_getpreferredencoding(self)
394
395 self.set_fake_file()
396
397 self.set_test_args()
398
399 def set_test_args(self):
400 """ Set the arguments for the test call to the function. """
401 self.test_args = dict(
402 stream=self.fake_file,
403 )
404
405 def set_fake_file(self):
406 """ Set the fake file for this test case. """
407 file_params = self.fake_file_params
408 file_type = file_params['type']
409
410 content = file_params['content']
411 if file_params.get('encoding', None) is not None:
412 content_bytestream = io.BytesIO(
413 content.encode(file_params['encoding']))
414 elif isinstance(content, bytes):
415 content_bytestream = io.BytesIO(content)
416 else:
417 content_bytestream = None
418
419 if isinstance(file_type, type):
420 if issubclass(file_type, io.TextIOWrapper):
421 fake_file = file_type(
422 content_bytestream, encoding=file_params['encoding'])
423 else:
424 fake_file = file_type(content)
425 else:
426 # Not actually a type, but a factory function.
427 fake_file = file_type()
428 fake_file.write(file_params['content'])
429 fake_file.seek(0)
430
431 self.fake_file = fake_file
432
433 def test_result_is_specified_stream_if_has_encoding(self):
434 """ Result should be the same stream if it has an encoding. """
435 if not isinstance(self.fake_file, io.TextIOBase):
436 self.skipTest("Specified stream is not text")
437 result = dputhelper.make_text_stream(**self.test_args)
438 self.assertIs(self.fake_file, result)
439
440 def test_result_has_expected_encoding(self):
441 """ Result should have the expected `encoding` attribute. """
442 result = dputhelper.make_text_stream(**self.test_args)
443 self.assertEqual(self.expected_encoding, result.encoding)
444
445 def test_result_emits_expected_content(self):
446 """ Result should emit the expected content. """
447 result = dputhelper.make_text_stream(**self.test_args)
448 if isinstance(result, io.BufferedRandom):
449 with open(
450 result.name, mode='r',
451 encoding=self.fake_file.encoding) as infile:
452 content = infile.read()
453 else:
454 content = result.read()
455 self.assertEqual(self.expected_content, content)
456
457
458 GetoptResult = collections.namedtuple('GetoptResult', ['optlist', 'args'])
459
460
461 class getopt_SuccessTestCase(
462 testscenarios.WithScenarios,
463 testtools.TestCase):
464 """ Success test cases for `getopt` function. """
465
466 scenarios = [
467 ('empty', {
468 'test_argv': [object()],
469 'expected_result': GetoptResult(
470 optlist=[], args=[]),
471 }),
472 ('no opts', {
473 'test_argv': [object(), "foo", "bar", "baz"],
474 'expected_result': GetoptResult(
475 optlist=[], args=["foo", "bar", "baz"]),
476 }),
477 ('only short opts', {
478 'test_argv': [object(), "-a", "-b", "-c"],
479 'test_shortopts': "axbycz",
480 'expected_result': GetoptResult(
481 optlist=[
482 ('-a', ""),
483 ('-b', ""),
484 ('-c', ""),
485 ],
486 args=[]),
487 }),
488 ('only long opts', {
489 'test_argv': [object(), "--alpha", "--beta", "--gamma"],
490 'test_longopts': [
491 "wibble", "alpha", "wobble",
492 "beta", "wubble", "gamma",
493 ],
494 'expected_result': GetoptResult(
495 optlist=[
496 ('--alpha', ""),
497 ('--beta', ""),
498 ('--gamma', ""),
499 ],
500 args=[]),
501 }),
502 ('long opt prefix', {
503 'test_argv': [object(), "--al", "--be", "--ga"],
504 'test_longopts': [
505 "wibble", "alpha", "wobble",
506 "beta", "wubble", "gamma",
507 ],
508 'expected_result': GetoptResult(
509 optlist=[
510 ('--alpha', ""),
511 ('--beta', ""),
512 ('--gamma', ""),
513 ],
514 args=[]),
515 }),
516 ('short opt cluster', {
517 'test_argv': [object(), "-abc"],
518 'test_shortopts': "abc",
519 'expected_result': GetoptResult(
520 optlist=[
521 ('-a', ""),
522 ('-b', ""),
523 ('-c', ""),
524 ],
525 args=[]),
526 }),
527 ('short with args', {
528 'test_argv': [object(), "-a", "-b", "eggs", "-cbeans"],
529 'test_shortopts': "ab:c:",
530 'expected_result': GetoptResult(
531 optlist=[
532 ('-a', ""),
533 ('-b', "eggs"),
534 ('-c', "beans"),
535 ],
536 args=[]),
537 }),
538 ('long with args', {
539 'test_argv': [
540 object(),
541 "--alpha",
542 "--beta=eggs",
543 "--gamma", "beans"],
544 'test_longopts': [
545 "wibble", "alpha", "wobble",
546 "beta=", "wubble", "gamma=",
547 ],
548 'expected_result': GetoptResult(
549 optlist=[
550 ('--alpha', ""),
551 ('--beta', "eggs"),
552 ('--gamma', "beans"),
553 ],
554 args=[]),
555 }),
556 ('long with optional args', {
557 'test_argv': [
558 object(),
559 "--alpha",
560 "--beta=eggs",
561 "--gamma"],
562 'test_longopts': [
563 "wibble", "alpha", "wobble",
564 "beta==", "wubble", "gamma==",
565 ],
566 'expected_result': GetoptResult(
567 optlist=[
568 ('--alpha', ""),
569 ('--beta', "eggs"),
570 ('--gamma', ""),
571 ],
572 args=[]),
573 }),
574 ('single hyphen arg', {
575 'test_argv': [object(), "-a", "-b", "-c", "-"],
576 'test_shortopts': "axbycz",
577 'expected_result': GetoptResult(
578 optlist=[
579 ('-a', ""),
580 ('-b', ""),
581 ('-c', ""),
582 ],
583 args=["-"]),
584 }),
585 ('explicit end of opts', {
586 'test_argv': [
587 object(),
588 "--alpha",
589 "--beta",
590 "--",
591 "--spam"],
592 'test_longopts': [
593 "wibble", "alpha", "wobble",
594 "beta", "wubble", "gamma",
595 ],
596 'expected_result': GetoptResult(
597 optlist=[
598 ('--alpha', ""),
599 ('--beta', ""),
600 ],
601 args=["--spam"]),
602 }),
603 ]
604
605 def test_returns_expected_result_for_argv(self):
606 """ Should return expected result for specified argv. """
607 shortopts = getattr(self, 'test_shortopts', "")
608 longopts = getattr(self, 'test_longopts', "")
609 result = dputhelper.getopt(
610 self.test_argv[1:], shortopts, longopts)
611 self.assertEqual(self.expected_result, result)
612
613
614 class getopt_ErrorTestCase(
615 testscenarios.WithScenarios,
616 testtools.TestCase):
617 """ Error test cases for `getopt` function. """
618
619 scenarios = [
620 ('short opt unknown', {
621 'test_argv': [object(), "-a", "-b", "-z", "-c"],
622 'test_shortopts': "abc",
623 'expected_error': dputhelper.DputException,
624 }),
625 ('short missing arg', {
626 'test_argv': [object(), "-a", "-b", "-c"],
627 'test_shortopts': "abc:",
628 'expected_error': dputhelper.DputException,
629 }),
630 ('long opt unknown', {
631 'test_argv': [
632 object(), "--alpha", "--beta", "--zeta", "--gamma"],
633 'test_longopts': [
634 "alpha", "beta", "gamma"],
635 'expected_error': dputhelper.DputException,
636 }),
637 ('long ambiguous prefix', {
638 'test_argv': [
639 object(), "--alpha", "--be", "--gamma"],
640 'test_longopts': [
641 "alpha", "beta", "bettong", "bertha", "gamma"],
642 'expected_error': dputhelper.DputException,
643 }),
644 ('long missing arg', {
645 'test_argv': [object(), "--alpha", "--beta", "--gamma"],
646 'test_longopts': [
647 "alpha", "beta", "gamma="],
648 'expected_error': dputhelper.DputException,
649 }),
650 ('long unexpected arg', {
651 'test_argv': [
652 object(), "--alpha", "--beta=beans", "--gamma"],
653 'test_longopts': [
654 "alpha", "beta", "gamma"],
655 'expected_error': dputhelper.DputException,
656 }),
657 ]
658
659 def test_raises_expected_error_for_argv(self):
660 """ Should raise expected error for specified argv. """
661 shortopts = getattr(self, 'test_shortopts', "")
662 longopts = getattr(self, 'test_longopts', "")
663 with testtools.ExpectedException(self.expected_error):
664 dputhelper.getopt(
665 self.test_argv[1:], shortopts, longopts)
666
667
668 def patch_getopt(testcase):
669 """ Patch the `getopt` function for the specified test case. """
670 def fake_getopt(args, shortopts, longopts):
671 result = (testcase.getopt_opts, testcase.getopt_args)
672 return result
673
674 func_patcher = unittest.mock.patch.object(
675 dputhelper, "getopt", autospec=True,
676 side_effect=fake_getopt)
677 func_patcher.start()
678 testcase.addCleanup(func_patcher.stop)
679
680
681 class get_progname_TestCase(
682 testscenarios.WithScenarios,
683 testtools.TestCase):
684 """ Test cases for `get_progname` function. """
685
686 command_name_scenarios = [
687 ('command-simple', {
688 'argv_zero': "amet",
689 'expected_progname': "amet",
690 }),
691 ('command-relative', {
692 'argv_zero': "lorem/ipsum/dolor/sit/amet",
693 'expected_progname': "amet",
694 }),
695 ('command-absolute', {
696 'argv_zero': "/lorem/ipsum/dolor/sit/amet",
697 'expected_progname': "amet",
698 }),
699 ]
700
701 subsequent_args_scenarios = [
702 ('args-empty', {
703 'argv_remain': [],
704 }),
705 ('args-one-word', {
706 'argv_remain': ["spam"],
707 }),
708 ('args-three-words', {
709 'argv_remain': ["spam", "beans", "eggs"],
710 }),
711 ('args-one-option', {
712 'argv_remain': ["--spam"],
713 }),
714 ]
715
716 scenarios = testscenarios.multiply_scenarios(
717 command_name_scenarios, subsequent_args_scenarios)
718
719 def setUp(self):
720 """ Set up test fixtures. """
721 super().setUp()
722
723 self.test_argv = [self.argv_zero] + self.argv_remain
724
725 def test_returns_expected_progname(self):
726 """ Should return expected progname value for command line. """
727 result = dputhelper.get_progname(self.test_argv)
728 self.assertEqual(self.expected_progname, result)
729
730 def test_queries_sys_argv_if_argv_unspecified(self):
731 """ Should query `sys.argv` if no `argv` specified. """
732 self.sys_argv = self.test_argv
733 patch_sys_argv(self)
734 result = dputhelper.get_progname()
735 self.assertEqual(self.expected_progname, result)
736
737
738 class get_distribution_version_TestCase(
739 testscenarios.WithScenarios,
740 testtools.TestCase):
741 """ Test cases for `get_distribution_version` function. """
742
743 scenarios = [
744 ('simple', {
745 'fake_distribution': make_fake_distribution(
746 name="lorem", version="42.23"),
747 }),
748 ]
749
750 def setUp(self):
751 """ Set up test fixtures. """
752 super().setUp()
753
754 patch_importlib_metadata_distribution(self)
755
756 def test_returns_expected_result(self):
757 """ Should return expected version for the distribution. """
758 result = dputhelper.get_distribution_version()
759 expected_version = self.fake_distribution.version
760 self.assertEqual(expected_version, result)
761
762
763 class make_person_text_from_fields_TestCase(
764 testscenarios.WithScenarios,
765 testtools.TestCase):
766 """ Test cases for `make_person_text_from_fields` function. """
767
768 scenarios = [
769 ('raw-text-ready full-name-unspecified', {
770 'test_args': {
771 'raw_text': "Lorem Ipsum <[email protected]>",
772 },
773 'expected_result': "Lorem Ipsum <[email protected]>",
774 }),
775 ('raw-text-ready full-name-specified', {
776 'test_args': {
777 'raw_text': "Lorem Ipsum <[email protected]>",
778 'full_name': "Dolor Sit Amet",
779 },
780 'expected_result': "Lorem Ipsum <[email protected]>",
781 }),
782 ('raw-text-email-only full-name-unspecified', {
783 'test_args': {
784 'raw_text': "[email protected]",
785 },
786 'expected_result': "<[email protected]>",
787 }),
788 ('raw-text-email-only full-name-specified', {
789 'test_args': {
790 'raw_text': "[email protected]",
791 'full_name': "Dolor Sit Amet",
792 },
793 'expected_result': "Dolor Sit Amet <[email protected]>",
794 }),
795 ]
796
797 def setUp(self, *args, **kwargs):
798 """ Set up test fixtures. """
799 super().setUp(*args, **kwargs)
800
801 def test_returns_expected_result_for_input_fields(self):
802 """ Should return the expected result for the input fields. """
803 result = dputhelper.make_person_text_from_fields(**self.test_args)
804 self.assertEqual(self.expected_result, result)
805
806
807 class get_username_from_system_TestCase(
808 testscenarios.WithScenarios,
809 testtools.TestCase):
810 """ Test cases for `get_username_from_system` function. """
811
812 scenarios = [
813 ('login-from-environ', {
814 'os_environ': {
815 'USER': "username-from-environ",
816 },
817 'os_getuid_return_value': 13,
818 'expected_username': "username-from-environ",
819 }),
820 ('login-from-pwd', {
821 'os_environ': {},
822 'os_getuid_return_value': 17,
823 'pwd_getpwuid_return_value': PasswdEntry(
824 *(["username-from-pwd"] + [object()] * 6)),
825 'expected_uid': 17,
826 'expected_username': "username-from-pwd",
827 }),
828 ]
829
830 def setUp(self):
831 """ Set up test fixtures. """
832 super().setUp()
833 patch_system_interfaces(self)
834
835 patch_os_environ(self)
836 patch_os_getuid(self)
837 patch_pwd_getpwuid(self)
838
839 self.set_test_args()
840
841 def set_test_args(self):
842 """ Set the arguments for the test call to the function. """
843 self.test_args = dict(
844 debug=False,
845 )
846
847 def test_emits_debug_message_for_username(self):
848 """ Should emit a debug message for the username. """
849 self.test_args['debug'] = True
850 dputhelper.get_username_from_system(**self.test_args)
851 expected_output = textwrap.dedent("""\
852 D: Login: {username}
853 """).format(username=self.expected_username)
854 self.assertIn(expected_output, sys.stderr.getvalue())
855
856 def test_emits_debug_message_for_userid(self):
857 """ Should emit a debug message for the user ID. """
858 if not hasattr(self, 'expected_uid'):
859 self.skipTest("No UID generated for this scenario")
860 self.test_args['debug'] = True
861 dputhelper.get_username_from_system(**self.test_args)
862 expected_output = textwrap.dedent("""\
863 D: User-ID: {uid}
864 """).format(uid=self.expected_uid)
865 self.assertIn(expected_output, sys.stderr.getvalue())
866
867 def test_returns_expected_username(self):
868 """ Should return expected username value. """
869 result = dputhelper.get_username_from_system(**self.test_args)
870 self.assertEqual(self.expected_username, result)
871
872
873 def patch_get_username_from_system(testcase):
874 """ Patch the `get_username_from_system` function for the `testcase`. """
875 if not hasattr(testcase, 'system_username'):
876 testcase.system_username = make_unique_slug(testcase)
877 func_patcher = unittest.mock.patch.object(
878 dputhelper, "get_username_from_system", autospec=True,
879 return_value=testcase.system_username)
880 func_patcher.start()
881 testcase.addCleanup(func_patcher.stop)
882
883
884 # Copyright © 2015–2026 Ben Finney <[email protected]>
885 #
886 # This is free software: you may copy, modify, and/or distribute this work
887 # under the terms of the GNU General Public License as published by the
888 # Free Software Foundation; version 3 of that license or any later version.
889 # No warranty expressed or implied. See the file ‘LICENSE.GPL-3’ for details.
890
891
892 # Local variables:
893 # coding: utf-8
894 # mode: python
895 # End:
896 # vim: fileencoding=utf-8 filetype=python :