Debian Codegraph @

ansible_collections/community/ciscosmb/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 __metaclass__ = type
21
22 '''
23 Compat module for Python3.x's unittest.mock module
24 '''
25 import sys
26
27 # Python 2.7
28
29 # Note: Could use the pypi mock library on python3.x as well as python2.x. It
30 # is the same as the python3 stdlib mock library
31
32 try:
33 # Allow wildcard import because we really do want to import all of mock's
34 # symbols into this compat shim
35 # pylint: disable=wildcard-import,unused-wildcard-import
36 from unittest.mock import *
37 except ImportError:
38 # Python 2
39 # pylint: disable=wildcard-import,unused-wildcard-import
40 try:
41 from mock import *
42 except ImportError:
43 print('You need the mock library installed on python2.x to run tests')
44
45
46 # Prior to 3.4.4, mock_open cannot handle binary read_data
47 if sys.version_info >= (3,) and sys.version_info < (3, 4, 4):
48 file_spec = None
49
50 def _iterate_read_data(read_data):
51 # Helper for mock_open:
52 # Retrieve lines from read_data via a generator so that separate calls to
53 # readline, read, and readlines are properly interleaved
54 sep = b'\n' if isinstance(read_data, bytes) else '\n'
55 data_as_list = [l + sep for l in read_data.split(sep)]
56
57 if data_as_list[-1] == sep:
58 # If the last line ended in a newline, the list comprehension will have an
59 # extra entry that's just a newline. Remove this.
60 data_as_list = data_as_list[:-1]
61 else:
62 # If there wasn't an extra newline by itself, then the file being
63 # emulated doesn't have a newline to end the last line remove the
64 # newline that our naive format() added
65 data_as_list[-1] = data_as_list[-1][:-1]
66
67 yield data_as_list
68
69 def mock_open(mock=None, read_data=''):
70 """
71 A helper function to create a mock to replace the use of `open`. It works
72 for `open` called directly or used as a context manager.
73
74 The `mock` argument is the mock object to configure. If `None` (the
75 default) then a `MagicMock` will be created for you, with the API limited
76 to methods or attributes available on standard file handles.
77
78 `read_data` is a string for the `read` methoddline`, and `readlines` of the
79 file handle to return. This is an empty string by default.
80 """
81 def _readlines_side_effect(*args, **kwargs):
82 if handle.readlines.return_value is not None:
83 return handle.readlines.return_value
84 return list(_data)
85
86 def _read_side_effect(*args, **kwargs):
87 if handle.read.return_value is not None:
88 return handle.read.return_value
89 return type(read_data)().join(_data)
90
91 def _readline_side_effect():
92 if handle.readline.return_value is not None:
93 while True:
94 yield handle.readline.return_value
95 yield _data
96
97 global file_spec
98 if file_spec is None:
99 import _io
100 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
101
102 if mock is None:
103 mock = MagicMock(name='open', spec=open)
104
105 handle = MagicMock(spec=file_spec)
106 handle.__enter__.return_value = handle
107
108 _data = _iterate_read_data(read_data)
109
110 handle.write.return_value = None
111 handle.read.return_value = None
112 handle.readline.return_value = None
113 handle.readlines.return_value = None
114
115 handle.read.side_effect = _read_side_effect
116 handle.readline.side_effect = _readline_side_effect()
117 handle.readlines.side_effect = _readlines_side_effect
118
119 mock.return_value = handle
120 return mock