Debian Codegraph @

ansible_collections/cisco/aci/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 # Make coding more python3-ish
20 from __future__ import absolute_import, division, print_function
21
22 __metaclass__ = type
23
24 import sys
25 import json
26
27 from contextlib import contextmanager
28 from io import BytesIO, StringIO
29 from ansible_collections.cisco.aci.tests.unit.compat import unittest
30 from ansible.module_utils.six import PY3
31 from ansible.module_utils._text import to_bytes
32
33
34 @contextmanager
35 def swap_stdin_and_argv(stdin_data="", argv_data=tuple()):
36 """
37 context manager that temporarily masks the test runner's values for stdin and argv
38 """
39 real_stdin = sys.stdin
40 real_argv = sys.argv
41
42 if PY3:
43 fake_stream = StringIO(stdin_data)
44 fake_stream.buffer = BytesIO(to_bytes(stdin_data))
45 else:
46 fake_stream = BytesIO(to_bytes(stdin_data))
47
48 try:
49 sys.stdin = fake_stream
50 sys.argv = argv_data
51
52 yield
53 finally:
54 sys.stdin = real_stdin
55 sys.argv = real_argv
56
57
58 @contextmanager
59 def swap_stdout():
60 """
61 context manager that temporarily replaces stdout for tests that need to verify output
62 """
63 old_stdout = sys.stdout
64
65 if PY3:
66 fake_stream = StringIO()
67 else:
68 fake_stream = BytesIO()
69
70 try:
71 sys.stdout = fake_stream
72
73 yield fake_stream
74 finally:
75 sys.stdout = old_stdout
76
77
78 class ModuleTestCase(unittest.TestCase):
79 def setUp(self, module_args=None):
80 if module_args is None:
81 module_args = {"_ansible_remote_tmp": "/tmp", "_ansible_keep_remote_files": False}
82
83 args = json.dumps(dict(ANSIBLE_MODULE_ARGS=module_args))
84
85 # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
86 self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
87 self.stdin_swap.__enter__()
88
89 def tearDown(self):
90 # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
91 self.stdin_swap.__exit__(None, None, None)