Debian Codegraph @

ansible_collections/cisco/aci/tests/unit/compat/mock.py

raw
1 # (c) 2014, Toshio Kuratomi <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 # Make coding more python3-ish
19 from __future__ import absolute_import, division, print_function
20
21 __metaclass__ = type
22
23 """
24 Compat module for Python3.x's unittest.mock module
25 """
26 import sys
27
28 # Python 2.7
29
30 # Note: Could use the pypi mock library on python3.x as well as python2.x. It
31 # is the same as the python3 stdlib mock library
32
33 try:
34 # Allow wildcard import because we really do want to import all of mock's
35 # symbols into this compat shim
36 # pylint: disable=wildcard-import,unused-wildcard-import
37 from unittest.mock import *
38 except ImportError:
39 # Python 2
40 # pylint: disable=wildcard-import,unused-wildcard-import
41 try:
42 from mock import *
43 except ImportError:
44 print("You need the mock library installed on python2.x to run tests")
45
46
47 # Prior to 3.4.4, mock_open cannot handle binary read_data
48 if sys.version_info >= (3,) and sys.version_info < (3, 4, 4):
49 file_spec = None
50
51 def _iterate_read_data(read_data):
52 # Helper for mock_open:
53 # Retrieve lines from read_data via a generator so that separate calls to
54 # readline, read, and readlines are properly interleaved
55 sep = b"\n" if isinstance(read_data, bytes) else "\n"
56 data_as_list = [l + sep for l in read_data.split(sep)]
57
58 if data_as_list[-1] == sep:
59 # If the last line ended in a newline, the list comprehension will have an
60 # extra entry that's just a newline. Remove this.
61 data_as_list = data_as_list[:-1]
62 else:
63 # If there wasn't an extra newline by itself, then the file being
64 # emulated doesn't have a newline to end the last line remove the
65 # newline that our naive format() added
66 data_as_list[-1] = data_as_list[-1][:-1]
67
68 yield from data_as_list
69
70 def mock_open(mock=None, read_data=""):
71 """
72 A helper function to create a mock to replace the use of `open`. It works
73 for `open` called directly or used as a context manager.
74
75 The `mock` argument is the mock object to configure. If `None` (the
76 default) then a `MagicMock` will be created for you, with the API limited
77 to methods or attributes available on standard file handles.
78
79 `read_data` is a string for the `read` methoddline`, and `readlines` of the
80 file handle to return. This is an empty string by default.
81 """
82
83 def _readlines_side_effect(*args, **kwargs):
84 if handle.readlines.return_value is not None:
85 return handle.readlines.return_value
86 return list(_data)
87
88 def _read_side_effect(*args, **kwargs):
89 if handle.read.return_value is not None:
90 return handle.read.return_value
91 return type(read_data)().join(_data)
92
93 def _readline_side_effect():
94 if handle.readline.return_value is not None:
95 while True:
96 yield handle.readline.return_value
97 yield from _data
98
99 global file_spec
100 if file_spec is None:
101 import _io
102
103 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
104
105 if mock is None:
106 mock = MagicMock(name="open", spec=open)
107
108 handle = MagicMock(spec=file_spec)
109 handle.__enter__.return_value = handle
110
111 _data = _iterate_read_data(read_data)
112
113 handle.write.return_value = None
114 handle.read.return_value = None
115 handle.readline.return_value = None
116 handle.readlines.return_value = None
117
118 handle.read.side_effect = _read_side_effect
119 handle.readline.side_effect = _readline_side_effect()
120 handle.readlines.side_effect = _readlines_side_effect
121
122 mock.return_value = handle
123 return mock