mock.py 17 KB

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