Debian Codegraph @

test/helper.py

raw
1 # test/helper.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 """ Helper functionality for DPut test suite. """
9
10 import base64
11 import builtins
12 import collections
13 import collections.abc
14 import contextlib
15 import errno
16 import functools
17 import importlib.metadata
18 import io
19 import itertools
20 import locale
21 import os
22 import os.path
23 import pwd
24 import shlex
25 import shutil
26 import signal
27 import subprocess
28 import sys
29 import tempfile
30 import time
31 import types
32 import unittest.mock
33 import weakref
34
35 import faker
36 import testtools
37
38
39 fake_factory = faker.Faker()
40
41
42 def make_unique_slug(testcase):
43 """ Make a unique slug for the test case. """
44 text = base64.b64encode(
45 testcase.getUniqueString().encode('utf-8')
46 ).decode('utf-8')
47 result = text[-30:]
48 return result
49
50
51 def make_fake_fqdn(testcase):
52 """ Make a fake Fully-Qualified Domain Name (FQDN). """
53 slug = make_unique_slug(testcase)
54 fqdn = "{}.example.net".format(slug)
55 return fqdn
56
57
58 def make_expected_error_context(
59 testcase,
60 *,
61 expected_error_attr_name='expected_error',
62 expected_error_message_regex_attr_name='expected_error_message_regex',
63 ):
64 """ Make a context for the `testcase.expected_error`, if any.
65
66 :param testcase: The `TestCase` instance to inspect.
67 :param expected_error_attr_name: Name (text) of an attribute of
68 `testcase` to inspect; the value is the exception type to expect.
69 :param expected_error_message_regex_attr_name: Name (text) of an
70 attribute of `testcase` to inspect; the value is the regex pattern
71 to expect match in the exception object caught.
72 :return: The Python context to wrap test calls.
73
74 If the `testcase.expected_error` attribute is bound, return a
75 `testtools.ExpectedException` for that exception type; otherwise,
76 return a `contextlib.nullcontext`.
77
78 If the `testcase.expected_error` attribute is bound and the
79 `testcase.expected_error_message_regex` attribute is bound, use that
80 value as the `value_re` specification of regular expression pattern
81 that must match the exception's message.
82 """
83 expected_error = getattr(testcase, expected_error_attr_name, None)
84 expected_error_message_regex = (
85 getattr(
86 testcase,
87 expected_error_message_regex_attr_name,
88 None)
89 if (expected_error is not None)
90 else None
91 )
92 context = (
93 testtools.ExpectedException(
94 expected_error,
95 value_re=expected_error_message_regex,
96 )
97 if (expected_error is not None)
98 else contextlib.nullcontext()
99 )
100 return context
101
102
103 def patch_stdout(testcase):
104 """ Patch `sys.stdout` for the specified test case. """
105 patcher = unittest.mock.patch.object(
106 sys, "stdout", wraps=io.StringIO())
107 patcher.start()
108 testcase.addCleanup(patcher.stop)
109
110
111 def patch_stderr(testcase):
112 """ Patch `sys.stderr` for the specified test case. """
113 patcher = unittest.mock.patch.object(
114 sys, "stderr", wraps=io.StringIO())
115 patcher.start()
116 testcase.addCleanup(patcher.stop)
117
118
119 def patch_signal_signal(testcase):
120 """ Patch `signal.signal` for the specified test case. """
121 func_patcher = unittest.mock.patch.object(
122 signal, "signal", autospec=True)
123 func_patcher.start()
124 testcase.addCleanup(func_patcher.stop)
125
126
127 class FakeSystemExit(SystemExit):
128 """ Fake double for `SystemExit` exception. """
129
130
131 EXIT_STATUS_SUCCESS = os.EX_OK
132 EXIT_STATUS_FAILURE = 1
133 EXIT_STATUS_COMMAND_NOT_FOUND = 127
134
135
136 def patch_sys_exit(testcase):
137 """ Patch `sys.exit` for the specified test case. """
138 func_patcher = unittest.mock.patch.object(
139 sys, "exit", autospec=True,
140 side_effect=FakeSystemExit())
141 func_patcher.start()
142 testcase.addCleanup(func_patcher.stop)
143
144
145 def patch_sys_argv(testcase):
146 """ Patch the `sys.argv` sequence for the test case. """
147 if not hasattr(testcase, 'progname'):
148 testcase.progname = make_unique_slug(testcase)
149 if not hasattr(testcase, 'sys_argv'):
150 testcase.sys_argv = [testcase.progname]
151 patcher = unittest.mock.patch.object(
152 sys, "argv",
153 new=list(testcase.sys_argv))
154 patcher.start()
155 testcase.addCleanup(patcher.stop)
156
157
158 def patch_system_interfaces(testcase):
159 """ Patch system interfaces that are disruptive to the test runner. """
160 patch_stdout(testcase)
161 patch_stderr(testcase)
162 patch_sys_exit(testcase)
163 patch_sys_argv(testcase)
164
165
166 def patch_time_time(testcase, values=None):
167 """ Patch the `time.time` function for the specified test case.
168
169 :param testcase: The `TestCase` instance for binding to the patch.
170 :param values: An iterable to provide return values.
171 :return: None.
172 """
173 if values is None:
174 values = itertools.count()
175
176 def generator_fake_time():
177 while True:
178 yield next(values)
179
180 func_patcher = unittest.mock.patch.object(time, "time", autospec=True)
181 func_patcher.start()
182 testcase.addCleanup(func_patcher.stop)
183
184 time.time.side_effect = generator_fake_time()
185
186
187 def patch_os_environ(testcase):
188 """ Patch the `os.environ` mapping. """
189 if not hasattr(testcase, 'os_environ'):
190 testcase.os_environ = {}
191 patcher = unittest.mock.patch.object(
192 os, "environ", new=testcase.os_environ)
193 patcher.start()
194 testcase.addCleanup(patcher.stop)
195
196
197 def patch_os_getpid(testcase):
198 """ Patch `os.getpid` for the specified test case. """
199 func_patcher = unittest.mock.patch.object(os, "getpid", autospec=True)
200 func_patcher.start()
201 testcase.addCleanup(func_patcher.stop)
202
203
204 def patch_os_getuid(testcase):
205 """ Patch the `os.getuid` function. """
206 if not hasattr(testcase, 'os_getuid_return_value'):
207 testcase.os_getuid_return_value = testcase.getUniqueInteger()
208 func_patcher = unittest.mock.patch.object(
209 os, "getuid", autospec=True,
210 return_value=testcase.os_getuid_return_value)
211 func_patcher.start()
212 testcase.addCleanup(func_patcher.stop)
213
214
215 PasswdEntry = collections.namedtuple(
216 "PasswdEntry",
217 "pw_name pw_passwd pw_uid pw_gid pw_gecos pw_dir pw_shell")
218
219
220 def patch_pwd_getpwuid(testcase):
221 """ Patch the `pwd.getpwuid` function. """
222 if not hasattr(testcase, 'pwd_getpwuid_return_value'):
223 testcase.pwd_getpwuid_return_value = PasswdEntry(
224 pw_name=make_unique_slug(testcase),
225 pw_passwd=make_unique_slug(testcase),
226 pw_uid=testcase.getUniqueInteger(),
227 pw_gid=testcase.getUniqueInteger(),
228 pw_gecos=testcase.getUniqueString(),
229 pw_dir=tempfile.mktemp(),
230 pw_shell=tempfile.mktemp())
231 if not isinstance(testcase.pwd_getpwuid_return_value, pwd.struct_passwd):
232 pwent = pwd.struct_passwd(testcase.pwd_getpwuid_return_value)
233 else:
234 pwent = testcase.pwd_getpwuid_return_value
235 func_patcher = unittest.mock.patch.object(
236 pwd, "getpwuid", autospec=True,
237 return_value=pwent)
238 func_patcher.start()
239 testcase.addCleanup(func_patcher.stop)
240
241
242 def patch_os_path_exists(testcase):
243 """ Patch `os.path.exists` behaviour for this test case.
244
245 When the patched function is called, the registry of
246 `FileDouble` instances for this test case will be used to get
247 the instance for the path specified.
248 """
249 orig_os_path_exists = os.path.exists
250
251 def fake_os_path_exists(path):
252 registry = FileDouble.get_registry_for_testcase(testcase)
253 if path in registry:
254 file_double = registry[path]
255 result = file_double.os_path_exists_scenario.call_hook()
256 else:
257 result = orig_os_path_exists(path)
258 return result
259
260 func_patcher = unittest.mock.patch.object(
261 os.path, "exists", autospec=True,
262 side_effect=fake_os_path_exists)
263 func_patcher.start()
264 testcase.addCleanup(func_patcher.stop)
265
266
267 def patch_os_access(testcase):
268 """ Patch `os.access` behaviour for this test case.
269
270 When the patched function is called, the registry of
271 `FileDouble` instances for this test case will be used to get
272 the instance for the path specified.
273 """
274 orig_os_access = os.access
275
276 def fake_os_access(path, mode):
277 registry = FileDouble.get_registry_for_testcase(testcase)
278 if path in registry:
279 file_double = registry[path]
280 result = file_double.os_access_scenario.call_hook(mode)
281 else:
282 result = orig_os_access(path, mode)
283 return result
284
285 func_patcher = unittest.mock.patch.object(
286 os, "access", autospec=True,
287 side_effect=fake_os_access)
288 func_patcher.start()
289 testcase.addCleanup(func_patcher.stop)
290
291
292 StatResult = collections.namedtuple(
293 'StatResult', [
294 'st_mode',
295 'st_ino', 'st_dev', 'st_nlink',
296 'st_uid', 'st_gid',
297 'st_size',
298 'st_atime', 'st_mtime', 'st_ctime',
299 ])
300
301
302 def patch_os_stat(testcase):
303 """ Patch `os.stat` behaviour for this test case.
304
305 When the patched function is called, the registry of
306 `FileDouble` instances for this test case will be used to get
307 the instance for the path specified.
308 """
309 orig_os_stat = os.stat
310
311 def fake_os_stat(path):
312 registry = FileDouble.get_registry_for_testcase(testcase)
313 if path in registry:
314 file_double = registry[path]
315 result = file_double.os_stat_scenario.call_hook()
316 else:
317 result = orig_os_stat(path)
318 return result
319
320 func_patcher = unittest.mock.patch.object(
321 os, "stat", autospec=True,
322 side_effect=fake_os_stat)
323 func_patcher.start()
324 testcase.addCleanup(func_patcher.stop)
325
326
327 def patch_os_lstat(testcase):
328 """ Patch `os.lstat` behaviour for this test case.
329
330 When the patched function is called, the registry of
331 `FileDouble` instances for this test case will be used to get
332 the instance for the path specified.
333 """
334 orig_os_lstat = os.lstat
335
336 def fake_os_lstat(path):
337 registry = FileDouble.get_registry_for_testcase(testcase)
338 if path in registry:
339 file_double = registry[path]
340 result = file_double.os_lstat_scenario.call_hook()
341 else:
342 result = orig_os_lstat(path)
343 return result
344
345 func_patcher = unittest.mock.patch.object(
346 os, "lstat", autospec=True,
347 side_effect=fake_os_lstat)
348 func_patcher.start()
349 testcase.addCleanup(func_patcher.stop)
350
351
352 def patch_os_isatty(testcase):
353 """ Patch the `os.isatty` function for the `testcase`. """
354 if not hasattr(testcase, 'os_isatty_return_value'):
355 testcase.os_isatty_return_value = False
356 func_patcher = unittest.mock.patch.object(
357 os, "isatty", return_value=testcase.os_isatty_return_value)
358 func_patcher.start()
359 testcase.addCleanup(func_patcher.stop)
360
361
362 def patch_os_unlink(testcase):
363 """ Patch `os.unlink` behaviour for this test case.
364
365 When the patched function is called, the registry of
366 `FileDouble` instances for this test case will be used to get
367 the instance for the path specified.
368 """
369 orig_os_unlink = os.unlink
370
371 def fake_os_unlink(path):
372 registry = FileDouble.get_registry_for_testcase(testcase)
373 if path in registry:
374 file_double = registry[path]
375 result = file_double.os_unlink_scenario.call_hook()
376 else:
377 result = orig_os_unlink(path)
378 return result
379
380 func_patcher = unittest.mock.patch.object(
381 os, "unlink", autospec=True,
382 side_effect=fake_os_unlink)
383 func_patcher.start()
384 testcase.addCleanup(func_patcher.stop)
385
386
387 def patch_os_rmdir(testcase):
388 """ Patch `os.rmdir` behaviour for this test case.
389
390 When the patched function is called, the registry of
391 `FileDouble` instances for this test case will be used to get
392 the instance for the path specified.
393 """
394 orig_os_rmdir = os.rmdir
395
396 def fake_os_rmdir(path):
397 registry = FileDouble.get_registry_for_testcase(testcase)
398 if path in registry:
399 file_double = registry[path]
400 result = file_double.os_rmdir_scenario.call_hook()
401 else:
402 result = orig_os_rmdir(path)
403 return result
404
405 func_patcher = unittest.mock.patch.object(
406 os, "rmdir", autospec=True,
407 side_effect=fake_os_rmdir)
408 func_patcher.start()
409 testcase.addCleanup(func_patcher.stop)
410
411
412 def patch_shutil_rmtree(testcase):
413 """ Patch `shutil.rmtree` behaviour for this test case.
414
415 When the patched function is called, the registry of
416 `FileDouble` instances for this test case will be used to get
417 the instance for the path specified.
418 """
419 orig_shutil_rmtree = shutil.rmtree
420
421 def fake_shutil_rmtree(path, ignore_errors=False, onerror=None):
422 registry = FileDouble.get_registry_for_testcase(testcase)
423 if path in registry:
424 file_double = registry[path]
425 result = file_double.shutil_rmtree_scenario.call_hook()
426 else:
427 result = orig_shutil_rmtree(
428 path,
429 ignore_errors=ignore_errors,
430 onerror=onerror,
431 )
432 return result
433
434 func_patcher = unittest.mock.patch.object(
435 shutil, "rmtree", autospec=True,
436 side_effect=fake_shutil_rmtree)
437 func_patcher.start()
438 testcase.addCleanup(func_patcher.stop)
439
440
441 def patch_tempfile_mkdtemp(testcase):
442 """ Patch the `tempfile.mkdtemp` function for this test case. """
443 if not hasattr(testcase, 'tempfile_mkdtemp_file_double'):
444 testcase.tempfile_mkdtemp_file_double = FileDouble(tempfile.mktemp())
445
446 double = testcase.tempfile_mkdtemp_file_double
447 double.set_os_unlink_scenario('okay')
448 double.set_os_rmdir_scenario('okay')
449 double.register_for_testcase(testcase)
450
451 func_patcher = unittest.mock.patch.object(
452 tempfile, "mkdtemp", autospec=True)
453 func_patcher.start()
454 testcase.addCleanup(func_patcher.stop)
455
456 tempfile.mkdtemp.return_value = testcase.tempfile_mkdtemp_file_double.path
457
458
459 def make_fake_file_scenarios(path=None):
460 """ Make a collection of scenarios for testing with fake files.
461
462 :path: The filesystem path of the fake file. If not specified,
463 a valid random path will be generated.
464 :return: A collection of scenarios for tests involving input files.
465
466 The collection is a mapping from scenario name to a dictionary of
467 scenario attributes.
468 """
469 if path is None:
470 file_path = tempfile.mktemp()
471 else:
472 file_path = path
473
474 fake_file_empty = io.StringIO()
475 fake_file_minimal = io.StringIO("Lorem ipsum.")
476 fake_file_large = io.StringIO("\n".join(
477 "ABCDEFGH" * 100
478 for __ in range(1000)))
479 fake_file_needs_utf8 = io.StringIO("Lórem ipsüm dolôr sìt āmet.")
480
481 default_scenario_params = {
482 'open_scenario_name': 'okay',
483 'file_double_params': dict(
484 path=file_path, fake_file=fake_file_minimal),
485 }
486
487 scenarios = {
488 'default': {},
489 'error-not-exist': {
490 'open_scenario_name': 'nonexist',
491 },
492 'error-exist': {
493 'open_scenario_name': 'exist_error',
494 },
495 'error-read-denied': {
496 'open_scenario_name': 'read_denied',
497 },
498 'not-found': {
499 'file_double_params': dict(
500 path=file_path, fake_file=fake_file_empty),
501 },
502 'exist-empty': {
503 'file_double_params': dict(
504 path=file_path, fake_file=fake_file_empty),
505 },
506 'exist-minimal': {
507 'file_double_params': dict(
508 path=file_path, fake_file=fake_file_minimal),
509 },
510 'exist-large': {
511 'file_double_params': dict(
512 path=file_path, fake_file=fake_file_large),
513 },
514 'exist-needs-utf8': {
515 'file_double_params': dict(
516 path=file_path, fake_file=fake_file_needs_utf8),
517 },
518 }
519
520 for (name, scenario) in scenarios.items():
521 params = default_scenario_params.copy()
522 params.update(scenario)
523 scenario.update(params)
524 scenario['file_double'] = FileDouble(**scenario['file_double_params'])
525 scenario['file_double'].set_open_scenario(params['open_scenario_name'])
526 scenario['fake_file_scenario_name'] = name
527
528 return scenarios
529
530
531 def get_file_doubles_from_fake_file_scenarios(scenarios):
532 """ Get the `FileDouble` instances from fake file scenarios.
533
534 :param scenarios: Collection of fake file scenarios.
535 :return: Collection of `FileDouble` instances.
536 """
537 doubles = {
538 scenario['file_double']
539 for scenario in scenarios
540 if scenario['file_double'] is not None}
541
542 return doubles
543
544
545 def setup_file_double_behaviour(testcase, doubles=None):
546 """ Set up file double instances and behaviour.
547
548 :param testcase: The `TestCase` instance to modify.
549 :param doubles: Collection of `FileDouble` instances.
550 :return: None.
551
552 If `doubles` is ``None``, a default collection will be made
553 from the result of `make_fake_file_scenarios` result.
554 """
555 if doubles is None:
556 scenarios = make_fake_file_scenarios()
557 doubles = get_file_doubles_from_fake_file_scenarios(
558 scenarios.values())
559
560 for file_double in doubles:
561 file_double.register_for_testcase(testcase)
562
563 orig_open = builtins.open
564
565 def fake_open(path, mode='rt', buffering=-1, encoding=None):
566 registry = FileDouble.get_registry_for_testcase(testcase)
567 if path in registry:
568 file_double = registry[path]
569 result = file_double.builtins_open_scenario.call_hook(
570 mode, buffering, encoding)
571 else:
572 result = orig_open(path, mode, buffering, encoding)
573 return result
574
575 mock_open = unittest.mock.mock_open()
576 mock_open.side_effect = fake_open
577
578 func_patcher = unittest.mock.patch.object(
579 builtins, "open", new=mock_open)
580 func_patcher.start()
581 testcase.addCleanup(func_patcher.stop)
582
583
584 def setup_fake_file_fixtures(testcase):
585 """ Set up fixtures for fake file doubles.
586
587 :param testcase: The `TestCase` instance to modify.
588 :return: None.
589 """
590 scenarios = make_fake_file_scenarios()
591 testcase.fake_file_scenarios = scenarios
592
593 file_doubles = get_file_doubles_from_fake_file_scenarios(
594 scenarios.values())
595 setup_file_double_behaviour(testcase, file_doubles)
596
597
598 def set_fake_file_scenario(testcase, name):
599 """ Set the named fake file scenario for the test case. """
600 scenario = testcase.fake_file_scenarios[name]
601 testcase.fake_file_scenario = scenario
602 testcase.file_double = scenario['file_double']
603 testcase.file_double.register_for_testcase(testcase)
604
605
606 def rewrap_fake_file_as_bytes(
607 fake_file, *,
608 fake_file_type=io.BytesIO,
609 name=None,
610 encoding='utf-8'):
611 """ Re-wrap the `fake_file` to be opened as a bytes stream.
612
613 :param fake_file: The `io.StringIO` acting as the fake file.
614 :param fake_file_type: The type of the return result.
615 :param name: The filesystem path (string) for the `name` attribute of
616 the wrapped file.
617 :param encoding: The text encoding to encode the text as bytes.
618 :return: A fake file (of type `fake_file_type`) that contains the same
619 content as `fake_file`, wrapped as a bytes stream..
620 """
621 if isinstance(fake_file, io.BytesIO):
622 result = fake_file
623 else:
624 content_encoded = fake_file.getvalue().encode('utf-8')
625 result = fake_file_type(content_encoded)
626 result.name = name
627 return result
628
629
630 def rewrap_fake_file_with_encoding(
631 fake_file, *,
632 fake_file_type=io.TextIOWrapper,
633 name=None,
634 encoding=None):
635 """ Re-wrap the `fake_file` to be opened with `encoding`.
636
637 :param fake_file: The `io.StringIO` acting as the fake file.
638 :param fake_file_type: The type of the return result.
639 :param name: The filesystem path (string) for the `name` attribute of
640 the wrapped file.
641 :param encoding: The text encoding to use for the wrapper.
642 :return: A fake file (of type `fake_file_type`) that contains the same
643 content as `fake_file`, re-encoded using `encoding`.
644
645 As with the `builtins.open` behaviour, if `encoding` is ``None``, use
646 the value from `get_default_encoding_for_builtins_open()`.
647 """
648 if encoding is None:
649 encoding = get_default_encoding_for_builtins_open()
650 content_encoded = fake_file.getvalue().encode('utf-8')
651 content_stream = io.BytesIO(content_encoded)
652 result = fake_file_type(content_stream, encoding=encoding)
653 return result
654
655
656 class TestDoubleFunctionScenario:
657 """ Scenario for fake behaviour of a specific function. """
658
659 def __init__(self, scenario_name, double):
660 self.scenario_name = scenario_name
661 self.double = double
662
663 self.call_hook = getattr(
664 self, "_hook_{name}".format(name=self.scenario_name))
665
666 def __repr__(self):
667 text = (
668 "<{class_name} instance: {id}"
669 " name: {name!r},"
670 " call_hook name: {hook_name!r}"
671 " double: {double!r}"
672 ">").format(
673 class_name=self.__class__.__name__, id=id(self),
674 name=self.scenario_name, double=self.double,
675 hook_name=self.call_hook.__name__)
676 return text
677
678 def __eq__(self, other):
679 result = True
680 if not self.scenario_name == other.scenario_name:
681 result = False
682 if not self.double == other.double:
683 result = False
684 if not self.call_hook.__name__ == other.call_hook.__name__:
685 result = False
686 return result
687
688 def __ne__(self, other):
689 result = not self.__eq__(other)
690 return result
691
692
693 class os_path_exists_scenario(TestDoubleFunctionScenario):
694 """ Scenario for `os.path.exists` behaviour. """
695
696 def _hook_exist(self):
697 return True
698
699 def _hook_not_exist(self):
700 return False
701
702
703 class os_access_scenario(TestDoubleFunctionScenario):
704 """ Scenario for `os.access` behaviour. """
705
706 def _hook_okay(self, mode):
707 return True
708
709 def _hook_not_exist(self, mode):
710 return False
711
712 def _hook_read_only(self, mode):
713 if mode & (os.W_OK | os.X_OK):
714 result = False
715 else:
716 result = True
717 return result
718
719 def _hook_denied(self, mode):
720 if mode & (os.R_OK | os.W_OK | os.X_OK):
721 result = False
722 else:
723 result = True
724 return result
725
726
727 class os_stat_scenario(TestDoubleFunctionScenario):
728 """ Scenario for `os.stat` behaviour. """
729
730 def _hook_okay(self):
731 return self.double.stat_result
732
733 def _hook_notfound_error(self):
734 raise FileNotFoundError(
735 errno.ENOENT, "No such file or directory", self.double.path)
736
737 def _hook_denied_error(self):
738 raise PermissionError(
739 errno.EPERM, "Permission denied", self.double.path)
740
741
742 class os_lstat_scenario(os_stat_scenario):
743 """ Scenario for `os.lstat` behaviour. """
744
745
746 class os_unlink_scenario(TestDoubleFunctionScenario):
747 """ Scenario for `os.unlink` behaviour. """
748
749 def _hook_okay(self):
750 return None
751
752 def _hook_nonexist(self):
753 error = FileNotFoundError(
754 errno.ENOENT, "No such file or directory", self.double.path)
755 raise error
756
757 def _hook_denied(self):
758 error = PermissionError(
759 errno.EPERM, "Permission denied", self.double.path)
760 raise error
761
762
763 class os_rmdir_scenario(TestDoubleFunctionScenario):
764 """ Scenario for `os.rmdir` behaviour. """
765
766 def _hook_okay(self):
767 return None
768
769 def _hook_nonexist(self):
770 error = FileNotFoundError(
771 errno.ENOENT, "No such file or directory", self.double.path)
772 raise error
773
774 def _hook_denied(self):
775 error = PermissionError(
776 errno.EPERM, "Permission denied", self.double.path)
777 raise error
778
779
780 class shutil_rmtree_scenario(TestDoubleFunctionScenario):
781 """ Scenario for `shutil.rmtree` behaviour. """
782
783 def _hook_okay(self):
784 return None
785
786 def _hook_nonexist(self):
787 error = FileNotFoundError(
788 errno.ENOENT, "No such file or directory", self.double.path)
789 raise error
790
791 def _hook_denied(self):
792 error = PermissionError(
793 errno.EPERM, "Permission denied", self.double.path)
794 raise error
795
796
797 class builtins_open_scenario(TestDoubleFunctionScenario):
798 """ Scenario for `builtins.open` behaviour. """
799
800 def _hook_okay(self, mode, buffering, encoding):
801 result = self.double.fake_file_opened_with_mode_and_encoding(
802 mode, encoding)
803 return result
804
805 def _hook_nonexist(self, mode, buffering, encoding):
806 if mode.startswith('r'):
807 error = FileNotFoundError(
808 errno.ENOENT,
809 "No such file or directory",
810 self.double.path)
811 raise error
812 result = self.double.fake_file_opened_with_mode_and_encoding(
813 mode, encoding)
814 return result
815
816 def _hook_exist_error(self, mode, buffering, encoding):
817 if mode.startswith(('w', 'a')):
818 error = FileExistsError(
819 errno.EEXIST, "File already exists", self.double.path)
820 raise error
821 result = self.double.fake_file_opened_with_mode_and_encoding(
822 mode, encoding)
823 return result
824
825 def _hook_read_denied(self, mode, buffering, encoding):
826 if mode.startswith('r'):
827 error = PermissionError(
828 errno.EPERM, "Read denied", self.double.path)
829 raise error
830 result = self.double.fake_file_opened_with_mode_and_encoding(
831 mode, encoding)
832 return result
833
834 def _hook_write_denied(self, mode, buffering, encoding):
835 if mode.startswith(('w', 'a')):
836 error = PermissionError(
837 errno.EPERM, "Write denied", self.double.path)
838 raise error
839 result = self.double.fake_file_opened_with_mode_and_encoding(
840 mode, encoding)
841 return result
842
843
844 class TestDoubleWithRegistry:
845 """ Abstract base class for a test double with a test case registry. """
846
847 registry_class = NotImplemented
848 registries = NotImplemented
849
850 function_scenario_params_by_class = NotImplemented
851
852 def __new__(cls, *args, **kwargs):
853 superclass = super()
854 if superclass.__new__ is object.__new__:
855 # The ‘object’ implementation complains about extra arguments.
856 instance = superclass.__new__(cls)
857 else:
858 instance = superclass.__new__(cls, *args, **kwargs)
859 instance.make_set_scenario_methods()
860
861 return instance
862
863 def __init__(self, *args, **kwargs):
864 super().__init__(*args, **kwargs)
865 self._set_method_per_scenario()
866
867 def _make_set_scenario_method(self, scenario_class, params):
868 def method(self, name):
869 scenario = scenario_class(name, double=self)
870 setattr(self, scenario_class.__name__, scenario)
871 method.__doc__ = (
872 """ Set the scenario for `{name}` behaviour. """
873 ).format(name=scenario_class.__name__)
874 method.__name__ = str(params['set_scenario_method_name'])
875 return method
876
877 def make_set_scenario_methods(self):
878 """ Make `set_<scenario_class_name>` methods on this class. """
879 for (function_scenario_class, function_scenario_params) in (
880 self.function_scenario_params_by_class.items()):
881 method = self._make_set_scenario_method(
882 function_scenario_class, function_scenario_params)
883 setattr(self.__class__, method.__name__, method)
884 function_scenario_params['set_scenario_method'] = method
885
886 def _set_method_per_scenario(self):
887 """ Set the method to be called for each scenario. """
888 for function_scenario_params in (
889 self.function_scenario_params_by_class.values()):
890 function_scenario_params['set_scenario_method'](
891 self, function_scenario_params['default_scenario_name'])
892
893 @classmethod
894 def get_registry_for_testcase(cls, testcase):
895 """ Get the FileDouble registry for the specified test case. """
896 # Key in a dict must be hashable.
897 key = (testcase.__class__, id(testcase))
898 registry = cls.registries.setdefault(key, cls.registry_class())
899 return registry
900
901 def get_registry_key(self):
902 """ Get the registry key for this double. """
903 raise NotImplementedError
904
905 def register_for_testcase(self, testcase):
906 """ Add this instance to registry for the specified testcase. """
907 registry = self.get_registry_for_testcase(testcase)
908 key = self.get_registry_key()
909 registry[key] = self
910 unregister_func = functools.partial(
911 self.unregister_for_testcase, testcase)
912 testcase.addCleanup(unregister_func)
913
914 def unregister_for_testcase(self, testcase):
915 """ Remove this instance from registry for the specified testcase. """
916 registry = self.get_registry_for_testcase(testcase)
917 key = self.get_registry_key()
918 if key in registry:
919 registry.pop(key)
920
921
922 def copy_fake_file(fake_file):
923 """ Make a copy of the `StringIO` instance. """
924 fake_file_type = io.StringIO
925 content = ""
926 if fake_file is not None:
927 fake_file_type = type(fake_file)
928 content = fake_file.getvalue()
929 result = fake_file_type(content)
930 if (
931 hasattr(fake_file, 'encoding')
932 and not hasattr(result, 'encoding')
933 ):
934 result.encoding = fake_file.encoding
935 return result
936
937
938 class FileDouble(TestDoubleWithRegistry):
939 """ A testing double for a file. """
940
941 registry_class = dict
942 registries = {}
943
944 function_scenario_params_by_class = {
945 os_path_exists_scenario: {
946 'default_scenario_name': 'not_exist',
947 'set_scenario_method_name': 'set_os_path_exists_scenario',
948 },
949 os_access_scenario: {
950 'default_scenario_name': 'okay',
951 'set_scenario_method_name': 'set_os_access_scenario',
952 },
953 os_stat_scenario: {
954 'default_scenario_name': 'okay',
955 'set_scenario_method_name': 'set_os_stat_scenario',
956 },
957 os_lstat_scenario: {
958 'default_scenario_name': 'okay',
959 'set_scenario_method_name': 'set_os_lstat_scenario',
960 },
961 builtins_open_scenario: {
962 'default_scenario_name': 'okay',
963 'set_scenario_method_name': 'set_open_scenario',
964 },
965 os_unlink_scenario: {
966 'default_scenario_name': 'okay',
967 'set_scenario_method_name': 'set_os_unlink_scenario',
968 },
969 os_rmdir_scenario: {
970 'default_scenario_name': 'okay',
971 'set_scenario_method_name': 'set_os_rmdir_scenario',
972 },
973 shutil_rmtree_scenario: {
974 'default_scenario_name': 'okay',
975 'set_scenario_method_name': 'set_shutil_rmtree_scenario',
976 },
977 }
978
979 def __init__(self, path=None, fake_file=None, *args, **kwargs):
980 self.path = path
981 self.fake_file = copy_fake_file(fake_file)
982 self.fake_file.name = path
983 self._fake_file_opened_with_encoding = dict()
984
985 self._set_stat_result()
986
987 super().__init__(*args, **kwargs)
988
989 def _set_stat_result(self):
990 """ Set the `os.stat` result for this file. """
991 size = len(self.fake_file.getvalue())
992 self.stat_result = StatResult(
993 st_mode=0,
994 st_ino=None, st_dev=None, st_nlink=None,
995 st_uid=0, st_gid=0,
996 st_size=size,
997 st_atime=None, st_mtime=None, st_ctime=None,
998 )
999
1000 def __repr__(self):
1001 text = "FileDouble(path={path!r}, fake_file={fake_file!r})".format(
1002 path=self.path, fake_file=self.fake_file)
1003 return text
1004
1005 def get_registry_key(self):
1006 """ Get the registry key for this double. """
1007 result = self.path
1008 return result
1009
1010 def fake_file_opened_with_mode_and_encoding(self, mode='r', encoding=None):
1011 """
1012 Return `fake_file`, maybe wrapped with the specified `encoding`.
1013
1014 :param mode: The `mode` argument to `open` for opening this file.
1015 :param encoding: The text encoding to wrap this file with when opened.
1016 :return: If the mode includes 'b' (“binary”), return `self.fake_file`;
1017 otherwise, return an `io.TextIOWrapper` for `fake_file` using
1018 `encoding`.
1019 """
1020 encoding_key = (
1021 (encoding.lower() if encoding is not None else None)
1022 if ('b' not in mode) else None)
1023 if encoding_key not in self._fake_file_opened_with_encoding:
1024 if encoding_key is None:
1025 # The file is to be opened in binary (non-text) mode. Wrap as a
1026 # bytes stream.
1027 wrapped_file = rewrap_fake_file_as_bytes(
1028 self.fake_file,
1029 name=self.path)
1030 else:
1031 wrapped_file = rewrap_fake_file_with_encoding(
1032 self.fake_file,
1033 name=self.path,
1034 encoding=encoding)
1035 self._fake_file_opened_with_encoding[encoding_key] = wrapped_file
1036 result = self._fake_file_opened_with_encoding[encoding_key]
1037 return result
1038
1039
1040 class os_popen_scenario(TestDoubleFunctionScenario):
1041 """ Scenario for `os.popen` behaviour. """
1042
1043 stream_name_by_mode = {
1044 'w': 'stdin',
1045 'r': 'stdout',
1046 }
1047
1048 def _hook_success(self, argv, mode, buffering):
1049 stream_name = self.stream_name_by_mode[mode]
1050 stream_double = getattr(
1051 self.double, "{}_double".format(stream_name))
1052 result = stream_double.fake_file
1053 return result
1054
1055 def _hook_failure(self, argv, mode, buffering):
1056 result = io.StringIO()
1057 return result
1058
1059 def _hook_not_found(self, argv, mode, buffering):
1060 result = io.StringIO()
1061 return result
1062
1063
1064 class os_waitpid_scenario(TestDoubleFunctionScenario):
1065 """ Scenario for `os.waitpid` behaviour. """
1066
1067 def _hook_success(self, pid, options):
1068 result = (pid, EXIT_STATUS_SUCCESS)
1069 return result
1070
1071 def _hook_failure(self, pid, options):
1072 result = (pid, EXIT_STATUS_FAILURE)
1073 return result
1074
1075 def _hook_not_found(self, pid, options):
1076 error = OSError(errno.ECHILD)
1077 raise error
1078
1079
1080 class os_system_scenario(TestDoubleFunctionScenario):
1081 """ Scenario for `os.system` behaviour. """
1082
1083 def _hook_success(self, command):
1084 result = EXIT_STATUS_SUCCESS
1085 return result
1086
1087 def _hook_failure(self, command):
1088 result = EXIT_STATUS_FAILURE
1089 return result
1090
1091 def _hook_not_found(self, command):
1092 result = EXIT_STATUS_COMMAND_NOT_FOUND
1093 return result
1094
1095
1096 class os_spawnv_scenario(TestDoubleFunctionScenario):
1097 """ Scenario for `os.spawnv` behaviour. """
1098
1099 def _hook_success(self, mode, file, args):
1100 result = EXIT_STATUS_SUCCESS
1101 return result
1102
1103 def _hook_failure(self, mode, file, args):
1104 result = EXIT_STATUS_FAILURE
1105 return result
1106
1107 def _hook_not_found(self, mode, file, args):
1108 result = EXIT_STATUS_COMMAND_NOT_FOUND
1109 return result
1110
1111
1112 ARG_ANY = object()
1113 ARG_MORE = object()
1114
1115
1116 class PopenDouble:
1117 """ A testing double for `subprocess.Popen`. """
1118
1119 def __init__(self, args, *posargs, **kwargs):
1120 self.stdin = None
1121 self.stdout = None
1122 self.stderr = None
1123 self.pid = None
1124 self.returncode = None
1125
1126 if kwargs.get('shell', False):
1127 self.argv = shlex.split(args)
1128 else:
1129 # The paramter is already a sequence of command-line arguments.
1130 self.argv = args
1131
1132 def set_streams(self, subprocess_double, popen_kwargs):
1133 """ Set the streams on the `PopenDouble`.
1134
1135 :param subprocess_double: The `SubprocessDouble` from
1136 which to get existing stream doubles.
1137 :param popen_kwargs: The keyword arguments to the
1138 `subprocess.Popen` call.
1139 :return: ``None``.
1140 """
1141 for stream_name in (
1142 name for name in ['stdin', 'stdout', 'stderr']
1143 if name in popen_kwargs):
1144 stream_spec = popen_kwargs[stream_name]
1145 match stream_spec:
1146 case subprocess.PIPE:
1147 stream_double = getattr(
1148 subprocess_double,
1149 "{name}_double".format(name=stream_name))
1150 stream_file = stream_double.fake_file
1151 case subprocess.STDOUT:
1152 stream_file = subprocess_double.stdout_double.fake_file
1153 case _:
1154 stream_file = stream_spec
1155 setattr(self, stream_name, stream_file)
1156
1157 def wait(self):
1158 """ Wait for subprocess to terminate. """
1159 return self.returncode
1160
1161
1162 class subprocess_popen_scenario(TestDoubleFunctionScenario):
1163 """ Scenario for `subprocess.Popen` behaviour. """
1164
1165 def _hook_success(self, testcase, args, *posargs, **kwargs):
1166 double = self.double.popen_double
1167 double.set_streams(self.double, kwargs)
1168 return double
1169
1170
1171 def patch_subprocess_popen(testcase):
1172 """ Patch `subprocess.Popen` constructor for this test case.
1173
1174 :param testcase: The `TestCase` instance to modify.
1175 :return: None.
1176
1177 When the patched function is called, the registry of
1178 `SubprocessDouble` instances for this test case will be used
1179 to get the instance for the program path specified.
1180 """
1181 orig_subprocess_popen = subprocess.Popen
1182
1183 def fake_subprocess_popen(args, *posargs, **kwargs):
1184 if kwargs.get('shell', False):
1185 argv = shlex.split(args)
1186 else:
1187 argv = args
1188 registry = SubprocessDouble.get_registry_for_testcase(testcase)
1189 if argv in registry:
1190 subprocess_double = registry[argv]
1191 result = subprocess_double.subprocess_popen_scenario.call_hook(
1192 testcase, args, *posargs, **kwargs)
1193 else:
1194 result = orig_subprocess_popen(args, *posargs, **kwargs)
1195 return result
1196
1197 func_patcher = unittest.mock.patch.object(
1198 subprocess, "Popen", autospec=True,
1199 side_effect=fake_subprocess_popen)
1200 func_patcher.start()
1201 testcase.addCleanup(func_patcher.stop)
1202
1203
1204 class subprocess_call_scenario(TestDoubleFunctionScenario):
1205 """ Scenario for `subprocess.call` behaviour. """
1206
1207 def _hook_success(self, command):
1208 result = EXIT_STATUS_SUCCESS
1209 return result
1210
1211 def _hook_failure(self, command):
1212 result = EXIT_STATUS_FAILURE
1213 return result
1214
1215 def _hook_not_found(self, command):
1216 result = EXIT_STATUS_COMMAND_NOT_FOUND
1217 return result
1218
1219
1220 def patch_subprocess_call(testcase):
1221 """ Patch `subprocess.call` function for this test case.
1222
1223 :param testcase: The `TestCase` instance to modify.
1224 :return: None.
1225
1226 When the patched function is called, the registry of
1227 `SubprocessDouble` instances for this test case will be used
1228 to get the instance for the program path specified.
1229 """
1230 orig_subprocess_call = subprocess.call
1231
1232 def fake_subprocess_call(command, *posargs, **kwargs):
1233 if kwargs.get('shell', False):
1234 command_argv = shlex.split(command)
1235 else:
1236 command_argv = command
1237 registry = SubprocessDouble.get_registry_for_testcase(testcase)
1238 if command_argv in registry:
1239 subprocess_double = registry[command_argv]
1240 result = subprocess_double.subprocess_call_scenario.call_hook(
1241 command)
1242 else:
1243 result = orig_subprocess_call(command, *posargs, **kwargs)
1244 return result
1245
1246 func_patcher = unittest.mock.patch.object(
1247 subprocess, "call", autospec=True,
1248 side_effect=fake_subprocess_call)
1249 func_patcher.start()
1250 testcase.addCleanup(func_patcher.stop)
1251
1252
1253 class subprocess_check_call_scenario(TestDoubleFunctionScenario):
1254 """ Scenario for `subprocess.check_call` behaviour. """
1255
1256 def _hook_success(self, command):
1257 return None
1258
1259 def _hook_failure(self, command):
1260 result = EXIT_STATUS_FAILURE
1261 error = subprocess.CalledProcessError(result, command)
1262 raise error
1263
1264 def _hook_not_found(self, command):
1265 result = EXIT_STATUS_COMMAND_NOT_FOUND
1266 error = subprocess.CalledProcessError(result, command)
1267 raise error
1268
1269
1270 def patch_subprocess_check_call(testcase):
1271 """ Patch `subprocess.check_call` function for this test case.
1272
1273 :param testcase: The `TestCase` instance to modify.
1274 :return: None.
1275
1276 When the patched function is called, the registry of
1277 `SubprocessDouble` instances for this test case will be used
1278 to get the instance for the program path specified.
1279 """
1280 orig_subprocess_check_call = subprocess.check_call
1281
1282 def fake_subprocess_check_call(command, *posargs, **kwargs):
1283 if kwargs.get('shell', False):
1284 command_argv = shlex.split(command)
1285 else:
1286 command_argv = command
1287 registry = SubprocessDouble.get_registry_for_testcase(testcase)
1288 if command_argv in registry:
1289 subprocess_double = registry[command_argv]
1290 scenario = subprocess_double.subprocess_check_call_scenario
1291 result = scenario.call_hook(command)
1292 else:
1293 result = orig_subprocess_check_call(command, *posargs, **kwargs)
1294 return result
1295
1296 func_patcher = unittest.mock.patch.object(
1297 subprocess, "check_call", autospec=True,
1298 side_effect=fake_subprocess_check_call)
1299 func_patcher.start()
1300 testcase.addCleanup(func_patcher.stop)
1301
1302
1303 class SubprocessDoubleRegistry(collections.abc.MutableMapping):
1304 """ Registry of `SubprocessDouble` instances by `argv`. """
1305
1306 def __init__(self, *args, **kwargs):
1307 items = []
1308 if args:
1309 if isinstance(args[0], collections.abc.Mapping):
1310 items = args[0].items()
1311 if isinstance(args[0], collections.abc.Iterable):
1312 items = args[0]
1313 self._mapping = dict(items)
1314
1315 def __repr__(self):
1316 text = "<{class_name} object: {mapping}>".format(
1317 class_name=self.__class__.__name__, mapping=self._mapping)
1318 return text
1319
1320 def _match_argv(self, argv):
1321 """ Match the specified `argv` with our registered keys. """
1322 match = None
1323 if not isinstance(argv, collections.abc.Sequence):
1324 return match
1325 candidates = iter(self._mapping)
1326 while match is None:
1327 try:
1328 candidate = next(candidates)
1329 except StopIteration:
1330 break
1331 found = None
1332 if candidate == argv:
1333 # An exact match.
1334 found = True
1335 word_iter = enumerate(candidate)
1336 while found is None:
1337 try:
1338 (word_index, candidate_word) = next(word_iter)
1339 except StopIteration:
1340 break
1341 if candidate_word is ARG_MORE:
1342 # Candiate matches any remaining words. We have a match.
1343 found = True
1344 elif word_index > len(argv):
1345 # Candidate is too long for the specified argv.
1346 found = False
1347 elif candidate_word is ARG_ANY:
1348 # Candidate matches any word at this position.
1349 continue
1350 elif candidate_word == argv[word_index]:
1351 # Candidate matches the word at this position.
1352 continue
1353 else:
1354 # This candidate does not match.
1355 found = False
1356 if found is None:
1357 # Reached the end of the candidate without a mismatch.
1358 found = True
1359 if found:
1360 match = candidate
1361 return match
1362
1363 def __getitem__(self, key):
1364 match = self._match_argv(key)
1365 if match is None:
1366 raise KeyError(key)
1367 result = self._mapping[match]
1368 return result
1369
1370 def __setitem__(self, key, value):
1371 if key in self:
1372 del self[key]
1373 self._mapping[key] = value
1374
1375 def __delitem__(self, key):
1376 match = self._match_argv(key)
1377 if match is not None:
1378 del self._mapping[match]
1379
1380 def __iter__(self):
1381 return self._mapping.__iter__()
1382
1383 def __len__(self):
1384 return self._mapping.__len__()
1385
1386
1387 class SubprocessDouble(TestDoubleWithRegistry):
1388 """ A testing double for a subprocess. """
1389
1390 registry_class = SubprocessDoubleRegistry
1391 registries = {}
1392
1393 double_by_pid = weakref.WeakValueDictionary()
1394
1395 function_scenario_params_by_class = {
1396 subprocess_popen_scenario: {
1397 'default_scenario_name': 'success',
1398 'set_scenario_method_name': 'set_subprocess_popen_scenario',
1399 },
1400 subprocess_call_scenario: {
1401 'default_scenario_name': 'success',
1402 'set_scenario_method_name': 'set_subprocess_call_scenario',
1403 },
1404 subprocess_check_call_scenario: {
1405 'default_scenario_name': 'success',
1406 'set_scenario_method_name':
1407 'set_subprocess_check_call_scenario',
1408 },
1409 os_popen_scenario: {
1410 'default_scenario_name': 'success',
1411 'set_scenario_method_name': 'set_os_popen_scenario',
1412 },
1413 os_waitpid_scenario: {
1414 'default_scenario_name': 'success',
1415 'set_scenario_method_name': 'set_os_waitpid_scenario',
1416 },
1417 os_system_scenario: {
1418 'default_scenario_name': 'success',
1419 'set_scenario_method_name': 'set_os_system_scenario',
1420 },
1421 os_spawnv_scenario: {
1422 'default_scenario_name': 'success',
1423 'set_scenario_method_name': 'set_os_spawnv_scenario',
1424 },
1425 }
1426
1427 def __init__(self, path=None, argv=None, *args, **kwargs):
1428 if path is None:
1429 path = tempfile.mktemp()
1430 self.path = path
1431
1432 if argv is None:
1433 command_name = os.path.basename(path)
1434 argv = [command_name]
1435 self.argv = argv
1436
1437 self.pid = self._make_pid()
1438 self._register_by_pid()
1439
1440 self.set_popen_double()
1441
1442 stream_class = SubprocessDouble.stream_class
1443 for stream_name in ['stdin', 'stdout', 'stderr']:
1444 fake_file = stream_class()
1445 file_double = FileDouble(fake_file=fake_file)
1446 stream_double_name = '{name}_double'.format(name=stream_name)
1447 setattr(self, stream_double_name, file_double)
1448
1449 super().__init__(*args, **kwargs)
1450
1451 def set_popen_double(self):
1452 """ Set the `PopenDouble` for this instance. """
1453 double = PopenDouble(self.argv)
1454 double.pid = self.pid
1455
1456 self.popen_double = double
1457
1458 def __repr__(self):
1459 text = (
1460 "<SubprocessDouble instance: {id}"
1461 " path: {path!r},"
1462 " argv: {argv!r}"
1463 " stdin_double: {stdin_double!r}"
1464 " stdout_double: {stdout_double!r}"
1465 " stderr_double: {stderr_double!r}"
1466 ">").format(
1467 id=id(self),
1468 path=self.path, argv=self.argv,
1469 stdin_double=self.stdin_double,
1470 stdout_double=self.stdout_double,
1471 stderr_double=self.stderr_double)
1472 return text
1473
1474 @classmethod
1475 def _make_pid(cls):
1476 """ Make a unique PID for a subprocess. """
1477 yield from itertools.count(firstval=1)
1478
1479 def _register_by_pid(self):
1480 """ Register this subprocess by its PID. """
1481 self.__class__.double_by_pid[self.pid] = self
1482
1483 def get_registry_key(self):
1484 """ Get the registry key for this double. """
1485 result = tuple(self.argv)
1486 return result
1487
1488 stream_class = io.BytesIO
1489 stream_encoding = "utf-8"
1490
1491 def set_stdin_content(self, text, bytes_encoding=stream_encoding):
1492 """ Set the content of the `stdin` stream for this double. """
1493 content = text.encode(bytes_encoding)
1494 fake_file = self.stream_class(content)
1495 self.stdin_double.fake_file = fake_file
1496
1497 def set_stdout_content(self, text, bytes_encoding=stream_encoding):
1498 """ Set the content of the `stdout` stream for this double. """
1499 content = text.encode(bytes_encoding)
1500 fake_file = self.stream_class(content)
1501 self.stdout_double.fake_file = fake_file
1502
1503 def set_stderr_content(self, text, bytes_encoding=stream_encoding):
1504 """ Set the content of the `stderr` stream for this double. """
1505 content = text.encode(bytes_encoding)
1506 fake_file = self.stream_class(content)
1507 self.stderr_double.fake_file = fake_file
1508
1509
1510 def make_fake_subprocess_scenarios(path=None):
1511 """ Make a collection of scenarios for testing with fake files.
1512
1513 :path: The filesystem path of the fake program. If not specified,
1514 a valid random path will be generated.
1515 :return: A collection of scenarios for tests involving subprocesses.
1516
1517 The collection is a mapping from scenario name to a dictionary of
1518 scenario attributes.
1519 """
1520 if path is None:
1521 file_path = tempfile.mktemp()
1522 else:
1523 file_path = path
1524
1525 default_scenario_params = {
1526 'return_value': EXIT_STATUS_SUCCESS,
1527 'program_path': file_path,
1528 'argv_after_command_name': [],
1529 }
1530
1531 scenarios = {
1532 'default': {},
1533 'not-found': {
1534 'return_value': EXIT_STATUS_COMMAND_NOT_FOUND,
1535 },
1536 }
1537
1538 for (name, scenario) in scenarios.items():
1539 params = default_scenario_params.copy()
1540 params.update(scenario)
1541 scenario.update(params)
1542 program_path = params['program_path']
1543 program_name = os.path.basename(params['program_path'])
1544 argv = [program_name]
1545 argv.extend(params['argv_after_command_name'])
1546 subprocess_double_params = dict(
1547 path=program_path,
1548 argv=argv,
1549 )
1550 subprocess_double = SubprocessDouble(**subprocess_double_params)
1551 scenario['subprocess_double'] = subprocess_double
1552 scenario['fake_file_scenario_name'] = name
1553
1554 return scenarios
1555
1556
1557 def get_subprocess_doubles_from_fake_subprocess_scenarios(scenarios):
1558 """ Get the `SubprocessDouble` instances from fake subprocess scenarios.
1559
1560 :param scenarios: Collection of fake subprocess scenarios.
1561 :return: Collection of `SubprocessDouble` instances.
1562 """
1563 doubles = {
1564 scenario['subprocess_double']
1565 for scenario in scenarios
1566 if scenario['subprocess_double'] is not None}
1567
1568 return doubles
1569
1570
1571 def setup_subprocess_double_behaviour(testcase, doubles=None):
1572 """ Set up subprocess double instances and behaviour.
1573
1574 :param testcase: The `TestCase` instance to modify.
1575 :param doubles: Collection of `SubprocessDouble` instances.
1576 :return: None.
1577
1578 If `doubles` is ``None``, a default collection will be made
1579 from the return value of `make_fake_subprocess_scenarios`.
1580 """
1581 if doubles is None:
1582 scenarios = make_fake_subprocess_scenarios()
1583 doubles = get_subprocess_doubles_from_fake_subprocess_scenarios(
1584 scenarios.values())
1585
1586 for double in doubles:
1587 double.register_for_testcase(testcase)
1588
1589
1590 def setup_fake_subprocess_fixtures(testcase):
1591 """ Set up fixtures for fake subprocess doubles.
1592
1593 :param testcase: The `TestCase` instance to modify.
1594 :return: None.
1595 """
1596 scenarios = make_fake_subprocess_scenarios()
1597 testcase.fake_subprocess_scenarios = scenarios
1598
1599 doubles = get_subprocess_doubles_from_fake_subprocess_scenarios(
1600 scenarios.values())
1601 setup_subprocess_double_behaviour(testcase, doubles)
1602
1603
1604 def patch_os_popen(testcase):
1605 """ Patch `os.popen` behaviour for this test case.
1606
1607 :param testcase: The `TestCase` instance to modify.
1608 :return: None.
1609
1610 When the patched function is called, the registry of
1611 `SubprocessDouble` instances for this test case will be used
1612 to get the instance for the program path specified.
1613 """
1614 orig_os_popen = os.popen
1615
1616 def fake_os_popen(cmd, mode='r', buffering=-1):
1617 registry = SubprocessDouble.get_registry_for_testcase(testcase)
1618 if isinstance(cmd, str):
1619 command_argv = shlex.split(cmd)
1620 else:
1621 command_argv = cmd
1622 if command_argv in registry:
1623 subprocess_double = registry[command_argv]
1624 result = subprocess_double.os_popen_scenario.call_hook(
1625 command_argv, mode, buffering)
1626 else:
1627 result = orig_os_popen(cmd, mode, buffering)
1628 return result
1629
1630 func_patcher = unittest.mock.patch.object(
1631 os, "popen", autospec=True,
1632 side_effect=fake_os_popen)
1633 func_patcher.start()
1634 testcase.addCleanup(func_patcher.stop)
1635
1636
1637 def patch_os_waitpid(testcase):
1638 """ Patch `os.waitpid` behaviour for this test case.
1639
1640 :param testcase: The `TestCase` instance to modify.
1641 :return: None.
1642
1643 When the patched function is called, the registry of
1644 `SubprocessDouble` instances for this test case will be used
1645 to get the instance for the program path specified.
1646 """
1647 orig_os_waitpid = os.waitpid
1648
1649 def fake_os_waitpid(pid, options):
1650 registry = SubprocessDouble.double_by_pid
1651 if pid in registry:
1652 subprocess_double = registry[pid]
1653 result = subprocess_double.os_waitpid_scenario.call_hook(
1654 pid, options)
1655 else:
1656 result = orig_os_waitpid(pid, options)
1657 return result
1658
1659 func_patcher = unittest.mock.patch.object(
1660 os, "waitpid", autospec=True,
1661 side_effect=fake_os_waitpid)
1662 func_patcher.start()
1663 testcase.addCleanup(func_patcher.stop)
1664
1665
1666 def patch_os_system(testcase):
1667 """ Patch `os.system` behaviour for this test case.
1668
1669 :param testcase: The `TestCase` instance to modify.
1670 :return: None.
1671
1672 When the patched function is called, the registry of
1673 `SubprocessDouble` instances for this test case will be used
1674 to get the instance for the program path specified.
1675 """
1676 orig_os_system = os.system
1677
1678 def fake_os_system(command):
1679 registry = SubprocessDouble.get_registry_for_testcase(testcase)
1680 command_argv = shlex.split(command)
1681 if command_argv in registry:
1682 subprocess_double = registry[command_argv]
1683 result = subprocess_double.os_system_scenario.call_hook(
1684 command)
1685 else:
1686 result = orig_os_system(command)
1687 return result
1688
1689 func_patcher = unittest.mock.patch.object(
1690 os, "system", autospec=True,
1691 side_effect=fake_os_system)
1692 func_patcher.start()
1693 testcase.addCleanup(func_patcher.stop)
1694
1695
1696 def patch_os_spawnv(testcase):
1697 """ Patch `os.spawnv` behaviour for this test case.
1698
1699 :param testcase: The `TestCase` instance to modify.
1700 :return: None.
1701
1702 When the patched function is called, the registry of
1703 `SubprocessDouble` instances for this test case will be used
1704 to get the instance for the program path specified.
1705 """
1706 orig_os_spawnv = os.spawnv
1707
1708 def fake_os_spawnv(mode, file, args):
1709 registry = SubprocessDouble.get_registry_for_testcase(testcase)
1710 registry_key = tuple(args)
1711 if registry_key in registry:
1712 subprocess_double = registry[registry_key]
1713 result = subprocess_double.os_spawnv_scenario.call_hook(
1714 mode, file, args)
1715 else:
1716 result = orig_os_spawnv(mode, file, args)
1717 return result
1718
1719 func_patcher = unittest.mock.patch.object(
1720 os, "spawnv", autospec=True,
1721 side_effect=fake_os_spawnv)
1722 func_patcher.start()
1723 testcase.addCleanup(func_patcher.stop)
1724
1725
1726 def make_options_namespace(options_mapping):
1727 """ Make a fake options namespace from `options_mapping`.
1728
1729 :param options_mapping: Mapping of options {`name`: `value`} to assign
1730 to the namespace.
1731 :return: The namespace of options.
1732 """
1733 options = types.SimpleNamespace()
1734 for (name, value) in options_mapping.items():
1735 setattr(options, name, value)
1736 return options
1737
1738
1739 def make_fake_locale_scenarios():
1740 """ Make a collection of scenarios for the locale of the process.
1741
1742 :return: A collection of scenarios for tests that specify the text
1743 locale.
1744
1745 The collection is a mapping from scenario name to a dictionary of
1746 scenario attributes.
1747 """
1748 scenarios = [
1749 ('locale unchanged', {
1750 }),
1751 ('locale unspecified', {
1752 'terminal_locale': None,
1753 'locale_getpreferredencoding_return_value': None,
1754 }),
1755 ('locale C.UTF-8', {
1756 'terminal_locale': "C.UTF-8",
1757 'locale_getpreferredencoding_return_value': "UTF-8",
1758 }),
1759 ('locale C', {
1760 'terminal_locale': "C",
1761 'locale_getpreferredencoding_return_value': None,
1762 }),
1763 ('locale en.UTF-8', {
1764 'terminal_locale': "en.UTF-8",
1765 'locale_getpreferredencoding_return_value': "en.UTF-8",
1766 }),
1767 ('locale en_AU.UTF-8', {
1768 'terminal_locale': "en_AU.UTF-8",
1769 'locale_getpreferredencoding_return_value': "UTF-8",
1770 }),
1771 ('locale en_AU.ASCII', {
1772 'terminal_locale': "en_AU.ASCII",
1773 'locale_getpreferredencoding_return_value': "ASCII",
1774 }),
1775 ('locale en_AU.ANSI_X3.4-1968', {
1776 'terminal_locale': "en_AU.ANSI_X3.4-1968",
1777 'locale_getpreferredencoding_return_value': "ANSI_X3.4-1968",
1778 }),
1779 ('locale de_DE.ISO8859-1', {
1780 'terminal_locale': "de_DE.ISO8859-1",
1781 'locale_getpreferredencoding_return_value': "ISO8859-1",
1782 }),
1783 ('locale zh_SG.GBK', {
1784 'terminal_locale': "zh_SG.GBK",
1785 'locale_getpreferredencoding_return_value': "GBK",
1786 }),
1787 ]
1788
1789 return scenarios
1790
1791
1792 def patch_locale_environment_variables(testcase, locale=None):
1793 """ Patch the environment variables for locale for the `testcase`.
1794
1795 :param testcase: The `TestCase` instance for binding to the patch.
1796 :param locale: The locale name to set.
1797 If ``None``, use the `testcase.terminal_locale` value.
1798 :return: ``None``.
1799
1800 The `os.environ` dictionary is patched for the test case, and the fake
1801 dictionary is modified to have environment variables set for the
1802 terminal locale name `locale`.
1803 """
1804 if locale is None:
1805 locale = getattr(testcase, 'terminal_locale', None)
1806
1807 patch_os_environ(testcase)
1808 for variable_name in ['LANG', 'LANGUAGE', 'LC_ALL']:
1809 if locale is not None:
1810 os.environ[variable_name] = locale
1811 else:
1812 # Remove the variable, thereby omitting the locale specification.
1813 if variable_name in os.environ:
1814 del os.environ[variable_name]
1815
1816
1817 def patch_locale_getpreferredencoding(testcase, encoding=None):
1818 """
1819 Patch `locale.getpreferredencoding` to return `encoding` for `testcase`.
1820
1821 :param encoding: The text encoding to return from
1822 `locale.getpreferredencoding`. If ``None``, use the
1823 `testcase.locale_getpreferredencoding_return_value` value.
1824 :return: ``None``.
1825 """
1826 if encoding is None:
1827 encoding = testcase.locale_getpreferredencoding_return_value
1828 func_patcher = unittest.mock.patch.object(
1829 locale, "getpreferredencoding", autospec=True,
1830 return_value=encoding)
1831 func_patcher.start()
1832 testcase.addCleanup(func_patcher.stop)
1833
1834
1835 def get_default_encoding_for_builtins_open():
1836 """ Get the default text encoding for `builtins-open`.
1837
1838 :return: The text encoding (a string name).
1839
1840 See the documentation for ‘builtins.open’ for this behaviour
1841 <URL:https://docs.python.org/3/library/functions.html#open>:
1842
1843 > In text mode, if encoding is not specified the encoding used is
1844 > platform-dependent: `locale.getpreferredencoding(False)` is called
1845 > to get the current locale encoding.
1846 """
1847 return locale.getpreferredencoding(False)
1848
1849
1850 def make_fake_text_encoding_scenarios():
1851 """ Make a collection of scenarios for testing with fake text encodings.
1852
1853 :return: A collection of scenarios for tests involving text encoding.
1854
1855 The collection is a mapping from scenario name to a dictionary of
1856 scenario attributes.
1857 """
1858 scenarios = [
1859 ('encoding-unspecified', {
1860 'text_encoding': None,
1861 }),
1862 ('encoding-UTF-8', {
1863 'text_encoding': "UTF-8",
1864 }),
1865 ('encoding-ASCII', {
1866 'text_encoding': "ASCII",
1867 }),
1868 ('encoding-ANSI_X3.4-1968', {
1869 'text_encoding': "ANSI_X3.4-1968",
1870 }),
1871 ('encoding-ISO8859-1', {
1872 'text_encoding': "ISO8859-1",
1873 }),
1874 ('encoding-GBK', {
1875 'text_encoding': "GBK",
1876 }),
1877 ]
1878
1879 return scenarios
1880
1881
1882 def patch_etc_mailname(testcase):
1883 """ Patch the ‘/etc/mailname’ file for the `testcase`.
1884
1885 :param testcase: The `TestCase` instance for binding to the patch.
1886 :return: ``None``.
1887 """
1888 path = "/etc/mailname"
1889 if hasattr(testcase, 'mailname_fake_file'):
1890 double = FileDouble(path, testcase.mailname_fake_file)
1891 else:
1892 double = FileDouble(path, io.StringIO())
1893 if hasattr(testcase, 'mailname_file_open_scenario_name'):
1894 double.set_open_scenario(testcase.mailname_file_open_scenario_name)
1895 testcase.mailname_file_double = double
1896
1897
1898 class FakeDistribution(importlib.metadata.Distribution):
1899 """ A fake `Distribution` instance for testing. """
1900
1901 def __init__(self, *, name=None, version=None):
1902 """ Initialise this instance. """
1903 self._metadata = {
1904 'Name': name,
1905 'Version': version,
1906 }
1907
1908 @property
1909 def metadata(self):
1910 """ Get the distribution metadata mapping. """
1911 return self._metadata
1912
1913 @metadata.setter
1914 def set_metadata(self, value):
1915 """ Set the distribution metadata mapping to `value`. """
1916 self._metadata = value
1917
1918 @property
1919 def name(self):
1920 """ Get the 'Name' metadata of this distribution. """
1921 return self.metadata['Name']
1922
1923 @name.setter
1924 def set_name(self, value):
1925 """ Set the 'Name' metadata of this distribution to `value`. """
1926 self.metadata['Name'] = value
1927
1928 @property
1929 def version(self):
1930 """ Get the 'Version' metadata of this distribution. """
1931 return self.metadata['Version']
1932
1933 @version.setter
1934 def set_version(self, value):
1935 """ Set the 'Version' metadata of this distribution to `value`. """
1936 self.metadata['Version'] = value
1937
1938
1939 def make_fake_version():
1940 """ Make a fake software version text.
1941
1942 :return: A version (text) from fake random digits.
1943 """
1944 version = ".".join(
1945 str(fake_factory.random_digit()) for __ in range(3))
1946 return version
1947
1948
1949 def make_fake_distribution(name=None, *, version=None):
1950 """ Make a fake `Distribution` to represent a distribution package.
1951
1952 :param name: The identifying name of the distribution.
1953 :param version: The release version of the distribution.
1954 :return: An instance of `importlib.metadata.Distribution`.
1955 """
1956 if name is None:
1957 name = fake_factory.word()
1958 if version is None:
1959 version = make_fake_version()
1960 fake_distribution = FakeDistribution(name=name, version=version)
1961 return fake_distribution
1962
1963
1964 def patch_importlib_metadata_distribution(testcase, *, fake_distribution=None):
1965 """ Patch `importlib.metadata.distribution` for the `testcase`.
1966
1967 :param testcase: The `TestCase` instance for binding to the patch.
1968 :param fake_distribution: The object to serve as the fake
1969 `Distribution` instance, or ``None`` to create a new fake instance.
1970 :return: ``None``.
1971 """
1972 if fake_distribution is None:
1973 if not hasattr(testcase, 'fake_distribution'):
1974 fake_distribution = make_fake_distribution()
1975 testcase.fake_distribution = fake_distribution
1976 else:
1977 fake_distribution = testcase.fake_distribution
1978 func_patcher = unittest.mock.patch.object(
1979 importlib.metadata, "distribution", autospec=True,
1980 return_value=fake_distribution)
1981 func_patcher.start()
1982 testcase.addCleanup(func_patcher.stop)
1983
1984
1985 # Copyright © 2015–2026 Ben Finney <[email protected]>
1986 #
1987 # This is free software: you may copy, modify, and/or distribute this work
1988 # under the terms of the GNU General Public License as published by the
1989 # Free Software Foundation; version 3 of that license or any later version.
1990 # No warranty expressed or implied. See the file ‘LICENSE.GPL-3’ for details.
1991
1992
1993 # Local variables:
1994 # coding: utf-8
1995 # mode: python
1996 # End:
1997 # vim: fileencoding=utf-8 filetype=python :