Debian Codegraph @

ansible_collections/community/aws/tests/unit/mock/procenv.py

raw
1 # (c) 2016, Matt Davis <[email protected]>
2 # (c) 2016, Toshio Kuratomi <[email protected]>
3 #
4 # This file is part of Ansible
5 #
6 # Ansible is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Ansible is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
18
19 import json
20 import sys
21 import unittest
22 from contextlib import contextmanager
23 from io import BytesIO
24 from io import StringIO
25
26 from ansible.module_utils._text import to_bytes
27
28
29 @contextmanager
30 def swap_stdin_and_argv(stdin_data="", argv_data=tuple()):
31 """
32 context manager that temporarily masks the test runner's values for stdin and argv
33 """
34 real_stdin = sys.stdin
35 real_argv = sys.argv
36
37 fake_stream = StringIO(stdin_data)
38 fake_stream.buffer = BytesIO(to_bytes(stdin_data))
39
40 try:
41 sys.stdin = fake_stream
42 sys.argv = argv_data
43
44 yield
45 finally:
46 sys.stdin = real_stdin
47 sys.argv = real_argv
48
49
50 @contextmanager
51 def swap_stdout():
52 """
53 context manager that temporarily replaces stdout for tests that need to verify output
54 """
55 old_stdout = sys.stdout
56
57 fake_stream = StringIO()
58
59 try:
60 sys.stdout = fake_stream
61
62 yield fake_stream
63 finally:
64 sys.stdout = old_stdout
65
66
67 class ModuleTestCase(unittest.TestCase):
68 def setUp(self, module_args=None):
69 if module_args is None:
70 module_args = {"_ansible_remote_tmp": "/tmp", "_ansible_keep_remote_files": False}
71
72 args = json.dumps(dict(ANSIBLE_MODULE_ARGS=module_args))
73
74 # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
75 self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
76 self.stdin_swap.__enter__()
77
78 def tearDown(self):
79 # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
80 self.stdin_swap.__exit__(None, None, None)