1
0

mock.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. # -*- coding: utf-8 -*-
  2. '''
  3. :codeauthor: Pedro Algarvio (pedro@algarvio.me)
  4. tests.support.mock
  5. ~~~~~~~~~~~~~~~~~~
  6. Helper module that wraps `mock` and provides some fake objects in order to
  7. properly set the function/class decorators and yet skip the test case's
  8. execution.
  9. Note: mock >= 2.0.0 required since unittest.mock does not have
  10. MagicMock.assert_called in Python < 3.6.
  11. '''
  12. # pylint: disable=unused-import,function-redefined,blacklisted-module,blacklisted-external-module
  13. from __future__ import absolute_import
  14. import collections
  15. import copy
  16. import errno
  17. import fnmatch
  18. import sys
  19. # Import salt libs
  20. from salt.ext import six
  21. import salt.utils.stringutils
  22. # By these days, we should blowup if mock is not available
  23. import mock # pylint: disable=blacklisted-external-import
  24. __mock_version = tuple([int(part) for part in mock.__version__.split('.') if part.isdigit()]) # pylint: disable=no-member
  25. if sys.version_info < (3, 6) and __mock_version < (2,):
  26. # We need mock >= 2.0.0 before Py3.6
  27. raise ImportError('Please install mock>=2.0.0')
  28. from mock import (Mock, # pylint: disable=no-name-in-module,no-member
  29. MagicMock,
  30. patch,
  31. sentinel,
  32. DEFAULT,
  33. create_autospec,
  34. FILTER_DIR,
  35. NonCallableMock,
  36. NonCallableMagicMock,
  37. PropertyMock,
  38. __version__,
  39. ANY,
  40. call)
  41. class MockFH(object):
  42. def __init__(self, filename, read_data, *args, **kwargs):
  43. self.filename = filename
  44. self.read_data = read_data
  45. try:
  46. self.mode = args[0]
  47. except IndexError:
  48. self.mode = kwargs.get('mode', 'r')
  49. self.binary_mode = 'b' in self.mode
  50. self.read_mode = any(x in self.mode for x in ('r', '+'))
  51. self.write_mode = any(x in self.mode for x in ('w', 'a', '+'))
  52. self.empty_string = b'' if self.binary_mode else ''
  53. self.call = MockCall(filename, *args, **kwargs)
  54. self.read_data_iter = self._iterate_read_data(read_data)
  55. self.read = Mock(side_effect=self._read)
  56. self.readlines = Mock(side_effect=self._readlines)
  57. self.readline = Mock(side_effect=self._readline)
  58. self.write = Mock(side_effect=self._write)
  59. self.writelines = Mock(side_effect=self._writelines)
  60. self.close = Mock()
  61. self.seek = Mock()
  62. self.__loc = 0
  63. self.__read_data_ok = False
  64. def _iterate_read_data(self, read_data):
  65. '''
  66. Helper for mock_open:
  67. Retrieve lines from read_data via a generator so that separate calls to
  68. readline, read, and readlines are properly interleaved
  69. '''
  70. # Newline will always be a bytestring on PY2 because mock_open will have
  71. # normalized it to one.
  72. newline = b'\n' if isinstance(read_data, six.binary_type) else '\n'
  73. read_data = [line + newline for line in read_data.split(newline)]
  74. if read_data[-1] == newline:
  75. # If the last line ended in a newline, the list comprehension will have an
  76. # extra entry that's just a newline. Remove this.
  77. read_data = read_data[:-1]
  78. else:
  79. # If there wasn't an extra newline by itself, then the file being
  80. # emulated doesn't have a newline to end the last line, so remove the
  81. # newline that we added in the list comprehension.
  82. read_data[-1] = read_data[-1][:-1]
  83. for line in read_data:
  84. yield line
  85. @property
  86. def write_calls(self):
  87. '''
  88. Return a list of all calls to the .write() mock
  89. '''
  90. return [x[1][0] for x in self.write.mock_calls]
  91. @property
  92. def writelines_calls(self):
  93. '''
  94. Return a list of all calls to the .writelines() mock
  95. '''
  96. return [x[1][0] for x in self.writelines.mock_calls]
  97. def tell(self):
  98. return self.__loc
  99. def __check_read_data(self):
  100. if not self.__read_data_ok:
  101. if self.binary_mode:
  102. if not isinstance(self.read_data, six.binary_type):
  103. raise TypeError(
  104. '{0} opened in binary mode, expected read_data to be '
  105. 'bytes, not {1}'.format(
  106. self.filename,
  107. type(self.read_data).__name__
  108. )
  109. )
  110. else:
  111. if not isinstance(self.read_data, str):
  112. raise TypeError(
  113. '{0} opened in non-binary mode, expected read_data to '
  114. 'be str, not {1}'.format(
  115. self.filename,
  116. type(self.read_data).__name__
  117. )
  118. )
  119. # No need to repeat this the next time we check
  120. self.__read_data_ok = True
  121. def _read(self, size=0):
  122. self.__check_read_data()
  123. if not self.read_mode:
  124. raise IOError('File not open for reading')
  125. if not isinstance(size, six.integer_types) or size < 0:
  126. raise TypeError('a positive integer is required')
  127. joined = self.empty_string.join(self.read_data_iter)
  128. if not size:
  129. # read() called with no args, return everything
  130. self.__loc += len(joined)
  131. return joined
  132. else:
  133. # read() called with an explicit size. Return a slice matching the
  134. # requested size, but before doing so, reset read_data to reflect
  135. # what we read.
  136. self.read_data_iter = self._iterate_read_data(joined[size:])
  137. ret = joined[:size]
  138. self.__loc += len(ret)
  139. return ret
  140. def _readlines(self, size=None): # pylint: disable=unused-argument
  141. # TODO: Implement "size" argument
  142. self.__check_read_data()
  143. if not self.read_mode:
  144. raise IOError('File not open for reading')
  145. ret = list(self.read_data_iter)
  146. self.__loc += sum(len(x) for x in ret)
  147. return ret
  148. def _readline(self, size=None): # pylint: disable=unused-argument
  149. # TODO: Implement "size" argument
  150. self.__check_read_data()
  151. if not self.read_mode:
  152. raise IOError('File not open for reading')
  153. try:
  154. ret = next(self.read_data_iter)
  155. self.__loc += len(ret)
  156. return ret
  157. except StopIteration:
  158. return self.empty_string
  159. def __iter__(self):
  160. self.__check_read_data()
  161. if not self.read_mode:
  162. raise IOError('File not open for reading')
  163. while True:
  164. try:
  165. ret = next(self.read_data_iter)
  166. self.__loc += len(ret)
  167. yield ret
  168. except StopIteration:
  169. break
  170. def _write(self, content):
  171. if not self.write_mode:
  172. raise IOError('File not open for writing')
  173. if six.PY2:
  174. if isinstance(content, six.text_type):
  175. # encoding intentionally not specified to force a
  176. # UnicodeEncodeError when non-ascii unicode type is passed
  177. content.encode()
  178. else:
  179. content_type = type(content)
  180. if self.binary_mode and content_type is not bytes:
  181. raise TypeError(
  182. 'a bytes-like object is required, not \'{0}\''.format(
  183. content_type.__name__
  184. )
  185. )
  186. elif not self.binary_mode and content_type is not str:
  187. raise TypeError(
  188. 'write() argument must be str, not {0}'.format(
  189. content_type.__name__
  190. )
  191. )
  192. def _writelines(self, lines):
  193. if not self.write_mode:
  194. raise IOError('File not open for writing')
  195. for line in lines:
  196. self._write(line)
  197. def __enter__(self):
  198. return self
  199. def __exit__(self, exc_type, exc_val, exc_tb): # pylint: disable=unused-argument
  200. pass
  201. class MockCall(object):
  202. def __init__(self, *args, **kwargs):
  203. self.args = args
  204. self.kwargs = kwargs
  205. def __repr__(self):
  206. # future lint: disable=blacklisted-function
  207. ret = str('MockCall(')
  208. for arg in self.args:
  209. ret += repr(arg) + str(', ')
  210. if not self.kwargs:
  211. if self.args:
  212. # Remove trailing ', '
  213. ret = ret[:-2]
  214. else:
  215. for key, val in six.iteritems(self.kwargs):
  216. ret += str('{0}={1}').format(
  217. salt.utils.stringutils.to_str(key),
  218. repr(val)
  219. )
  220. ret += str(')')
  221. return ret
  222. # future lint: enable=blacklisted-function
  223. def __str__(self):
  224. return self.__repr__()
  225. def __eq__(self, other):
  226. return self.args == other.args and self.kwargs == other.kwargs
  227. class MockOpen(object):
  228. r'''
  229. This class can be used to mock the use of ``open()``.
  230. ``read_data`` is a string representing the contents of the file to be read.
  231. By default, this is an empty string.
  232. Optionally, ``read_data`` can be a dictionary mapping ``fnmatch.fnmatch()``
  233. patterns to strings (or optionally, exceptions). This allows the mocked
  234. filehandle to serve content for more than one file path.
  235. .. code-block:: python
  236. data = {
  237. '/etc/foo.conf': textwrap.dedent("""\
  238. Foo
  239. Bar
  240. Baz
  241. """),
  242. '/etc/bar.conf': textwrap.dedent("""\
  243. A
  244. B
  245. C
  246. """),
  247. }
  248. with patch('salt.utils.files.fopen', mock_open(read_data=data):
  249. do stuff
  250. If the file path being opened does not match any of the glob expressions,
  251. an IOError will be raised to simulate the file not existing.
  252. Passing ``read_data`` as a string is equivalent to passing it with a glob
  253. expression of "*". That is to say, the below two invocations are
  254. equivalent:
  255. .. code-block:: python
  256. mock_open(read_data='foo\n')
  257. mock_open(read_data={'*': 'foo\n'})
  258. Instead of a string representing file contents, ``read_data`` can map to an
  259. exception, and that exception will be raised if a file matching that
  260. pattern is opened:
  261. .. code-block:: python
  262. data = {
  263. '/etc/*': IOError(errno.EACCES, 'Permission denied'),
  264. '*': 'Hello world!\n',
  265. }
  266. with patch('salt.utils.files.fopen', mock_open(read_data=data)):
  267. do stuff
  268. The above would raise an exception if any files within /etc are opened, but
  269. would produce a mocked filehandle if any other file is opened.
  270. To simulate file contents changing upon subsequent opens, the file contents
  271. can be a list of strings/exceptions. For example:
  272. .. code-block:: python
  273. data = {
  274. '/etc/foo.conf': [
  275. 'before\n',
  276. 'after\n',
  277. ],
  278. '/etc/bar.conf': [
  279. IOError(errno.ENOENT, 'No such file or directory', '/etc/bar.conf'),
  280. 'Hey, the file exists now!',
  281. ],
  282. }
  283. with patch('salt.utils.files.fopen', mock_open(read_data=data):
  284. do stuff
  285. The first open of ``/etc/foo.conf`` would return "before\n" when read,
  286. while the second would return "after\n" when read. For ``/etc/bar.conf``,
  287. the first read would raise an exception, while the second would open
  288. successfully and read the specified string.
  289. Expressions will be attempted in dictionary iteration order (the exception
  290. being ``*`` which is tried last), so if a file path matches more than one
  291. fnmatch expression then the first match "wins". If your use case calls for
  292. overlapping expressions, then an OrderedDict can be used to ensure that the
  293. desired matching behavior occurs:
  294. .. code-block:: python
  295. data = OrderedDict()
  296. data['/etc/foo.conf'] = 'Permission granted!'
  297. data['/etc/*'] = IOError(errno.EACCES, 'Permission denied')
  298. data['*'] = '*': 'Hello world!\n'
  299. with patch('salt.utils.files.fopen', mock_open(read_data=data):
  300. do stuff
  301. The following attributes are tracked for the life of a mock object:
  302. * call_count - Tracks how many fopen calls were attempted
  303. * filehandles - This is a dictionary mapping filenames to lists of MockFH
  304. objects, representing the individual times that a given file was opened.
  305. '''
  306. def __init__(self, read_data=''):
  307. # If the read_data contains lists, we will be popping it. So, don't
  308. # modify the original value passed.
  309. read_data = copy.copy(read_data)
  310. # Normalize read_data, Python 2 filehandles should never produce unicode
  311. # types on read.
  312. if not isinstance(read_data, dict):
  313. read_data = {'*': read_data}
  314. if six.PY2:
  315. # .__class__() used here to preserve the dict class in the event that
  316. # an OrderedDict was used.
  317. new_read_data = read_data.__class__()
  318. for key, val in six.iteritems(read_data):
  319. try:
  320. val = salt.utils.data.decode(val, to_str=True)
  321. except TypeError:
  322. if not isinstance(val, BaseException):
  323. raise
  324. new_read_data[key] = val
  325. read_data = new_read_data
  326. del new_read_data
  327. self.read_data = read_data
  328. self.filehandles = {}
  329. self.calls = []
  330. self.call_count = 0
  331. def __call__(self, name, *args, **kwargs):
  332. '''
  333. Match the file being opened to the patterns in the read_data and spawn
  334. a mocked filehandle with the corresponding file contents.
  335. '''
  336. call = MockCall(name, *args, **kwargs)
  337. self.calls.append(call)
  338. self.call_count += 1
  339. for pat in self.read_data:
  340. if pat == '*':
  341. continue
  342. if fnmatch.fnmatch(name, pat):
  343. matched_pattern = pat
  344. break
  345. else:
  346. # No non-glob match in read_data, fall back to '*'
  347. matched_pattern = '*'
  348. try:
  349. matched_contents = self.read_data[matched_pattern]
  350. try:
  351. # Assuming that the value for the matching expression is a
  352. # list, pop the first element off of it.
  353. file_contents = matched_contents.pop(0)
  354. except AttributeError:
  355. # The value for the matching expression is a string (or exception)
  356. file_contents = matched_contents
  357. except IndexError:
  358. # We've run out of file contents, abort!
  359. raise RuntimeError(
  360. 'File matching expression \'{0}\' opened more times than '
  361. 'expected'.format(matched_pattern)
  362. )
  363. try:
  364. # Raise the exception if the matched file contents are an
  365. # instance of an exception class.
  366. raise file_contents
  367. except TypeError:
  368. # Contents were not an exception, so proceed with creating the
  369. # mocked filehandle.
  370. pass
  371. ret = MockFH(name, file_contents, *args, **kwargs)
  372. self.filehandles.setdefault(name, []).append(ret)
  373. return ret
  374. except KeyError:
  375. # No matching glob in read_data, treat this as a file that does
  376. # not exist and raise the appropriate exception.
  377. raise IOError(errno.ENOENT, 'No such file or directory', name)
  378. def write_calls(self, path=None):
  379. '''
  380. Returns the contents passed to all .write() calls. Use `path` to narrow
  381. the results to files matching a given pattern.
  382. '''
  383. ret = []
  384. for filename, handles in six.iteritems(self.filehandles):
  385. if path is None or fnmatch.fnmatch(filename, path):
  386. for fh_ in handles:
  387. ret.extend(fh_.write_calls)
  388. return ret
  389. def writelines_calls(self, path=None):
  390. '''
  391. Returns the contents passed to all .writelines() calls. Use `path` to
  392. narrow the results to files matching a given pattern.
  393. '''
  394. ret = []
  395. for filename, handles in six.iteritems(self.filehandles):
  396. if path is None or fnmatch.fnmatch(filename, path):
  397. for fh_ in handles:
  398. ret.extend(fh_.writelines_calls)
  399. return ret
  400. # reimplement mock_open to support multiple filehandles
  401. mock_open = MockOpen