plugin.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import asyncio
  2. import builtins
  3. import functools
  4. import inspect
  5. import sys
  6. import unittest.mock
  7. import warnings
  8. from typing import Any
  9. from typing import Callable
  10. from typing import cast
  11. from typing import Dict
  12. from typing import Generator
  13. from typing import Iterable
  14. from typing import List
  15. from typing import Mapping
  16. from typing import Optional
  17. from typing import overload
  18. from typing import Tuple
  19. from typing import Type
  20. from typing import TypeVar
  21. from typing import Union
  22. import pytest
  23. from ._util import get_mock_module
  24. from ._util import parse_ini_boolean
  25. _T = TypeVar("_T")
  26. if sys.version_info >= (3, 8):
  27. AsyncMockType = unittest.mock.AsyncMock
  28. MockType = Union[
  29. unittest.mock.MagicMock,
  30. unittest.mock.AsyncMock,
  31. unittest.mock.NonCallableMagicMock,
  32. ]
  33. else:
  34. AsyncMockType = Any
  35. MockType = Union[unittest.mock.MagicMock, unittest.mock.NonCallableMagicMock]
  36. class PytestMockWarning(UserWarning):
  37. """Base class for all warnings emitted by pytest-mock."""
  38. class MockerFixture:
  39. """
  40. Fixture that provides the same interface to functions in the mock module,
  41. ensuring that they are uninstalled at the end of each test.
  42. """
  43. def __init__(self, config: Any) -> None:
  44. self._patches_and_mocks: List[Tuple[Any, unittest.mock.MagicMock]] = []
  45. self.mock_module = mock_module = get_mock_module(config)
  46. self.patch = self._Patcher(
  47. self._patches_and_mocks, mock_module
  48. ) # type: MockerFixture._Patcher
  49. # aliases for convenience
  50. self.Mock = mock_module.Mock
  51. self.MagicMock = mock_module.MagicMock
  52. self.NonCallableMock = mock_module.NonCallableMock
  53. self.NonCallableMagicMock = mock_module.NonCallableMagicMock
  54. self.PropertyMock = mock_module.PropertyMock
  55. if hasattr(mock_module, "AsyncMock"):
  56. self.AsyncMock = mock_module.AsyncMock
  57. self.call = mock_module.call
  58. self.ANY = mock_module.ANY
  59. self.DEFAULT = mock_module.DEFAULT
  60. self.sentinel = mock_module.sentinel
  61. self.mock_open = mock_module.mock_open
  62. if hasattr(mock_module, "seal"):
  63. self.seal = mock_module.seal
  64. def create_autospec(
  65. self, spec: Any, spec_set: bool = False, instance: bool = False, **kwargs: Any
  66. ) -> MockType:
  67. m: MockType = self.mock_module.create_autospec(
  68. spec, spec_set, instance, **kwargs
  69. )
  70. self._patches_and_mocks.append((None, m))
  71. return m
  72. def resetall(
  73. self, *, return_value: bool = False, side_effect: bool = False
  74. ) -> None:
  75. """
  76. Call reset_mock() on all patchers started by this fixture.
  77. :param bool return_value: Reset the return_value of mocks.
  78. :param bool side_effect: Reset the side_effect of mocks.
  79. """
  80. supports_reset_mock_with_args: Tuple[Type[Any], ...]
  81. if hasattr(self, "AsyncMock"):
  82. supports_reset_mock_with_args = (self.Mock, self.AsyncMock)
  83. else:
  84. supports_reset_mock_with_args = (self.Mock,)
  85. for p, m in self._patches_and_mocks:
  86. # See issue #237.
  87. if not hasattr(m, "reset_mock"):
  88. continue
  89. if isinstance(m, supports_reset_mock_with_args):
  90. m.reset_mock(return_value=return_value, side_effect=side_effect)
  91. else:
  92. m.reset_mock()
  93. def stopall(self) -> None:
  94. """
  95. Stop all patchers started by this fixture. Can be safely called multiple
  96. times.
  97. """
  98. for p, m in reversed(self._patches_and_mocks):
  99. if p is not None:
  100. p.stop()
  101. self._patches_and_mocks.clear()
  102. def stop(self, mock: unittest.mock.MagicMock) -> None:
  103. """
  104. Stops a previous patch or spy call by passing the ``MagicMock`` object
  105. returned by it.
  106. """
  107. for index, (p, m) in enumerate(self._patches_and_mocks):
  108. if mock is m:
  109. p.stop()
  110. del self._patches_and_mocks[index]
  111. break
  112. else:
  113. raise ValueError("This mock object is not registered")
  114. def spy(self, obj: object, name: str) -> MockType:
  115. """
  116. Create a spy of method. It will run method normally, but it is now
  117. possible to use `mock` call features with it, like call count.
  118. :param obj: An object.
  119. :param name: A method in object.
  120. :return: Spy object.
  121. """
  122. method = getattr(obj, name)
  123. if inspect.isclass(obj) and isinstance(
  124. inspect.getattr_static(obj, name), (classmethod, staticmethod)
  125. ):
  126. # Can't use autospec classmethod or staticmethod objects before 3.7
  127. # see: https://bugs.python.org/issue23078
  128. autospec = False
  129. else:
  130. autospec = inspect.ismethod(method) or inspect.isfunction(method)
  131. def wrapper(*args, **kwargs):
  132. spy_obj.spy_return = None
  133. spy_obj.spy_exception = None
  134. try:
  135. r = method(*args, **kwargs)
  136. except BaseException as e:
  137. spy_obj.spy_exception = e
  138. raise
  139. else:
  140. spy_obj.spy_return = r
  141. return r
  142. async def async_wrapper(*args, **kwargs):
  143. spy_obj.spy_return = None
  144. spy_obj.spy_exception = None
  145. try:
  146. r = await method(*args, **kwargs)
  147. except BaseException as e:
  148. spy_obj.spy_exception = e
  149. raise
  150. else:
  151. spy_obj.spy_return = r
  152. return r
  153. if asyncio.iscoroutinefunction(method):
  154. wrapped = functools.update_wrapper(async_wrapper, method)
  155. else:
  156. wrapped = functools.update_wrapper(wrapper, method)
  157. spy_obj = self.patch.object(obj, name, side_effect=wrapped, autospec=autospec)
  158. spy_obj.spy_return = None
  159. spy_obj.spy_exception = None
  160. return spy_obj
  161. def stub(self, name: Optional[str] = None) -> unittest.mock.MagicMock:
  162. """
  163. Create a stub method. It accepts any arguments. Ideal to register to
  164. callbacks in tests.
  165. :param name: the constructed stub's name as used in repr
  166. :return: Stub object.
  167. """
  168. return cast(
  169. unittest.mock.MagicMock,
  170. self.mock_module.MagicMock(spec=lambda *args, **kwargs: None, name=name),
  171. )
  172. def async_stub(self, name: Optional[str] = None) -> AsyncMockType:
  173. """
  174. Create a async stub method. It accepts any arguments. Ideal to register to
  175. callbacks in tests.
  176. :param name: the constructed stub's name as used in repr
  177. :return: Stub object.
  178. """
  179. return cast(
  180. AsyncMockType,
  181. self.mock_module.AsyncMock(spec=lambda *args, **kwargs: None, name=name),
  182. )
  183. class _Patcher:
  184. """
  185. Object to provide the same interface as mock.patch, mock.patch.object,
  186. etc. We need this indirection to keep the same API of the mock package.
  187. """
  188. DEFAULT = object()
  189. def __init__(self, patches_and_mocks, mock_module):
  190. self.__patches_and_mocks = patches_and_mocks
  191. self.mock_module = mock_module
  192. def _start_patch(
  193. self, mock_func: Any, warn_on_mock_enter: bool, *args: Any, **kwargs: Any
  194. ) -> MockType:
  195. """Patches something by calling the given function from the mock
  196. module, registering the patch to stop it later and returns the
  197. mock object resulting from the mock call.
  198. """
  199. p = mock_func(*args, **kwargs)
  200. mocked: MockType = p.start()
  201. self.__patches_and_mocks.append((p, mocked))
  202. if hasattr(mocked, "reset_mock"):
  203. # check if `mocked` is actually a mock object, as depending on autospec or target
  204. # parameters `mocked` can be anything
  205. if hasattr(mocked, "__enter__") and warn_on_mock_enter:
  206. if sys.version_info >= (3, 8):
  207. depth = 5
  208. else:
  209. depth = 4
  210. mocked.__enter__.side_effect = lambda: warnings.warn(
  211. "Mocks returned by pytest-mock do not need to be used as context managers. "
  212. "The mocker fixture automatically undoes mocking at the end of a test. "
  213. "This warning can be ignored if it was triggered by mocking a context manager. "
  214. "https://pytest-mock.readthedocs.io/en/latest/remarks.html#usage-as-context-manager",
  215. PytestMockWarning,
  216. stacklevel=depth,
  217. )
  218. return mocked
  219. def object(
  220. self,
  221. target: object,
  222. attribute: str,
  223. new: object = DEFAULT,
  224. spec: Optional[object] = None,
  225. create: bool = False,
  226. spec_set: Optional[object] = None,
  227. autospec: Optional[object] = None,
  228. new_callable: object = None,
  229. **kwargs: Any
  230. ) -> MockType:
  231. """API to mock.patch.object"""
  232. if new is self.DEFAULT:
  233. new = self.mock_module.DEFAULT
  234. return self._start_patch(
  235. self.mock_module.patch.object,
  236. True,
  237. target,
  238. attribute,
  239. new=new,
  240. spec=spec,
  241. create=create,
  242. spec_set=spec_set,
  243. autospec=autospec,
  244. new_callable=new_callable,
  245. **kwargs
  246. )
  247. def context_manager(
  248. self,
  249. target: builtins.object,
  250. attribute: str,
  251. new: builtins.object = DEFAULT,
  252. spec: Optional[builtins.object] = None,
  253. create: bool = False,
  254. spec_set: Optional[builtins.object] = None,
  255. autospec: Optional[builtins.object] = None,
  256. new_callable: builtins.object = None,
  257. **kwargs: Any
  258. ) -> MockType:
  259. """This is equivalent to mock.patch.object except that the returned mock
  260. does not issue a warning when used as a context manager."""
  261. if new is self.DEFAULT:
  262. new = self.mock_module.DEFAULT
  263. return self._start_patch(
  264. self.mock_module.patch.object,
  265. False,
  266. target,
  267. attribute,
  268. new=new,
  269. spec=spec,
  270. create=create,
  271. spec_set=spec_set,
  272. autospec=autospec,
  273. new_callable=new_callable,
  274. **kwargs
  275. )
  276. def multiple(
  277. self,
  278. target: builtins.object,
  279. spec: Optional[builtins.object] = None,
  280. create: bool = False,
  281. spec_set: Optional[builtins.object] = None,
  282. autospec: Optional[builtins.object] = None,
  283. new_callable: Optional[builtins.object] = None,
  284. **kwargs: Any
  285. ) -> Dict[str, MockType]:
  286. """API to mock.patch.multiple"""
  287. return self._start_patch(
  288. self.mock_module.patch.multiple,
  289. True,
  290. target,
  291. spec=spec,
  292. create=create,
  293. spec_set=spec_set,
  294. autospec=autospec,
  295. new_callable=new_callable,
  296. **kwargs
  297. )
  298. def dict(
  299. self,
  300. in_dict: Union[Mapping[Any, Any], str],
  301. values: Union[Mapping[Any, Any], Iterable[Tuple[Any, Any]]] = (),
  302. clear: bool = False,
  303. **kwargs: Any
  304. ) -> Any:
  305. """API to mock.patch.dict"""
  306. return self._start_patch(
  307. self.mock_module.patch.dict,
  308. True,
  309. in_dict,
  310. values=values,
  311. clear=clear,
  312. **kwargs
  313. )
  314. @overload
  315. def __call__(
  316. self,
  317. target: str,
  318. new: None = ...,
  319. spec: Optional[builtins.object] = ...,
  320. create: bool = ...,
  321. spec_set: Optional[builtins.object] = ...,
  322. autospec: Optional[builtins.object] = ...,
  323. new_callable: None = ...,
  324. **kwargs: Any
  325. ) -> MockType:
  326. ...
  327. @overload
  328. def __call__(
  329. self,
  330. target: str,
  331. new: _T,
  332. spec: Optional[builtins.object] = ...,
  333. create: bool = ...,
  334. spec_set: Optional[builtins.object] = ...,
  335. autospec: Optional[builtins.object] = ...,
  336. new_callable: None = ...,
  337. **kwargs: Any
  338. ) -> _T:
  339. ...
  340. @overload
  341. def __call__(
  342. self,
  343. target: str,
  344. new: None,
  345. spec: Optional[builtins.object],
  346. create: bool,
  347. spec_set: Optional[builtins.object],
  348. autospec: Optional[builtins.object],
  349. new_callable: Callable[[], _T],
  350. **kwargs: Any
  351. ) -> _T:
  352. ...
  353. @overload
  354. def __call__(
  355. self,
  356. target: str,
  357. new: None = ...,
  358. spec: Optional[builtins.object] = ...,
  359. create: bool = ...,
  360. spec_set: Optional[builtins.object] = ...,
  361. autospec: Optional[builtins.object] = ...,
  362. *,
  363. new_callable: Callable[[], _T],
  364. **kwargs: Any
  365. ) -> _T:
  366. ...
  367. def __call__(
  368. self,
  369. target: str,
  370. new: builtins.object = DEFAULT,
  371. spec: Optional[builtins.object] = None,
  372. create: bool = False,
  373. spec_set: Optional[builtins.object] = None,
  374. autospec: Optional[builtins.object] = None,
  375. new_callable: Optional[Callable[[], Any]] = None,
  376. **kwargs: Any
  377. ) -> Any:
  378. """API to mock.patch"""
  379. if new is self.DEFAULT:
  380. new = self.mock_module.DEFAULT
  381. return self._start_patch(
  382. self.mock_module.patch,
  383. True,
  384. target,
  385. new=new,
  386. spec=spec,
  387. create=create,
  388. spec_set=spec_set,
  389. autospec=autospec,
  390. new_callable=new_callable,
  391. **kwargs
  392. )
  393. def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]:
  394. """
  395. Return an object that has the same interface to the `mock` module, but
  396. takes care of automatically undoing all patches after each test method.
  397. """
  398. result = MockerFixture(pytestconfig)
  399. yield result
  400. result.stopall()
  401. mocker = pytest.fixture()(_mocker) # default scope is function
  402. class_mocker = pytest.fixture(scope="class")(_mocker)
  403. module_mocker = pytest.fixture(scope="module")(_mocker)
  404. package_mocker = pytest.fixture(scope="package")(_mocker)
  405. session_mocker = pytest.fixture(scope="session")(_mocker)
  406. _mock_module_patches = [] # type: List[Any]
  407. _mock_module_originals = {} # type: Dict[str, Any]
  408. def assert_wrapper(
  409. __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any
  410. ) -> None:
  411. __tracebackhide__ = True
  412. try:
  413. __wrapped_mock_method__(*args, **kwargs)
  414. return
  415. except AssertionError as e:
  416. if getattr(e, "_mock_introspection_applied", 0):
  417. msg = str(e)
  418. else:
  419. __mock_self = args[0]
  420. msg = str(e)
  421. if __mock_self.call_args is not None:
  422. actual_args, actual_kwargs = __mock_self.call_args
  423. introspection = ""
  424. try:
  425. assert actual_args == args[1:]
  426. except AssertionError as e_args:
  427. introspection += "\nArgs:\n" + str(e_args)
  428. try:
  429. assert actual_kwargs == kwargs
  430. except AssertionError as e_kwargs:
  431. introspection += "\nKwargs:\n" + str(e_kwargs)
  432. if introspection:
  433. msg += "\n\npytest introspection follows:\n" + introspection
  434. e = AssertionError(msg)
  435. e._mock_introspection_applied = True # type:ignore[attr-defined]
  436. raise e
  437. def assert_has_calls_wrapper(
  438. __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any
  439. ) -> None:
  440. __tracebackhide__ = True
  441. try:
  442. __wrapped_mock_method__(*args, **kwargs)
  443. return
  444. except AssertionError as e:
  445. any_order = kwargs.get("any_order", False)
  446. if getattr(e, "_mock_introspection_applied", 0) or any_order:
  447. msg = str(e)
  448. else:
  449. __mock_self = args[0]
  450. msg = str(e)
  451. if __mock_self.call_args_list is not None:
  452. actual_calls = list(__mock_self.call_args_list)
  453. expect_calls = args[1]
  454. introspection = ""
  455. from itertools import zip_longest
  456. for actual_call, expect_call in zip_longest(actual_calls, expect_calls):
  457. if actual_call is not None:
  458. actual_args, actual_kwargs = actual_call
  459. else:
  460. actual_args = tuple()
  461. actual_kwargs = {}
  462. if expect_call is not None:
  463. _, expect_args, expect_kwargs = expect_call
  464. else:
  465. expect_args = tuple()
  466. expect_kwargs = {}
  467. try:
  468. assert actual_args == expect_args
  469. except AssertionError as e_args:
  470. introspection += "\nArgs:\n" + str(e_args)
  471. try:
  472. assert actual_kwargs == expect_kwargs
  473. except AssertionError as e_kwargs:
  474. introspection += "\nKwargs:\n" + str(e_kwargs)
  475. if introspection:
  476. msg += "\n\npytest introspection follows:\n" + introspection
  477. e = AssertionError(msg)
  478. e._mock_introspection_applied = True # type:ignore[attr-defined]
  479. raise e
  480. def wrap_assert_not_called(*args: Any, **kwargs: Any) -> None:
  481. __tracebackhide__ = True
  482. assert_wrapper(_mock_module_originals["assert_not_called"], *args, **kwargs)
  483. def wrap_assert_called_with(*args: Any, **kwargs: Any) -> None:
  484. __tracebackhide__ = True
  485. assert_wrapper(_mock_module_originals["assert_called_with"], *args, **kwargs)
  486. def wrap_assert_called_once(*args: Any, **kwargs: Any) -> None:
  487. __tracebackhide__ = True
  488. assert_wrapper(_mock_module_originals["assert_called_once"], *args, **kwargs)
  489. def wrap_assert_called_once_with(*args: Any, **kwargs: Any) -> None:
  490. __tracebackhide__ = True
  491. assert_wrapper(_mock_module_originals["assert_called_once_with"], *args, **kwargs)
  492. def wrap_assert_has_calls(*args: Any, **kwargs: Any) -> None:
  493. __tracebackhide__ = True
  494. assert_has_calls_wrapper(
  495. _mock_module_originals["assert_has_calls"], *args, **kwargs
  496. )
  497. def wrap_assert_any_call(*args: Any, **kwargs: Any) -> None:
  498. __tracebackhide__ = True
  499. assert_wrapper(_mock_module_originals["assert_any_call"], *args, **kwargs)
  500. def wrap_assert_called(*args: Any, **kwargs: Any) -> None:
  501. __tracebackhide__ = True
  502. assert_wrapper(_mock_module_originals["assert_called"], *args, **kwargs)
  503. def wrap_assert_not_awaited(*args: Any, **kwargs: Any) -> None:
  504. __tracebackhide__ = True
  505. assert_wrapper(_mock_module_originals["assert_not_awaited"], *args, **kwargs)
  506. def wrap_assert_awaited_with(*args: Any, **kwargs: Any) -> None:
  507. __tracebackhide__ = True
  508. assert_wrapper(_mock_module_originals["assert_awaited_with"], *args, **kwargs)
  509. def wrap_assert_awaited_once(*args: Any, **kwargs: Any) -> None:
  510. __tracebackhide__ = True
  511. assert_wrapper(_mock_module_originals["assert_awaited_once"], *args, **kwargs)
  512. def wrap_assert_awaited_once_with(*args: Any, **kwargs: Any) -> None:
  513. __tracebackhide__ = True
  514. assert_wrapper(_mock_module_originals["assert_awaited_once_with"], *args, **kwargs)
  515. def wrap_assert_has_awaits(*args: Any, **kwargs: Any) -> None:
  516. __tracebackhide__ = True
  517. assert_wrapper(_mock_module_originals["assert_has_awaits"], *args, **kwargs)
  518. def wrap_assert_any_await(*args: Any, **kwargs: Any) -> None:
  519. __tracebackhide__ = True
  520. assert_wrapper(_mock_module_originals["assert_any_await"], *args, **kwargs)
  521. def wrap_assert_awaited(*args: Any, **kwargs: Any) -> None:
  522. __tracebackhide__ = True
  523. assert_wrapper(_mock_module_originals["assert_awaited"], *args, **kwargs)
  524. def wrap_assert_methods(config: Any) -> None:
  525. """
  526. Wrap assert methods of mock module so we can hide their traceback and
  527. add introspection information to specified argument asserts.
  528. """
  529. # Make sure we only do this once
  530. if _mock_module_originals:
  531. return
  532. mock_module = get_mock_module(config)
  533. wrappers = {
  534. "assert_called": wrap_assert_called,
  535. "assert_called_once": wrap_assert_called_once,
  536. "assert_called_with": wrap_assert_called_with,
  537. "assert_called_once_with": wrap_assert_called_once_with,
  538. "assert_any_call": wrap_assert_any_call,
  539. "assert_has_calls": wrap_assert_has_calls,
  540. "assert_not_called": wrap_assert_not_called,
  541. }
  542. for method, wrapper in wrappers.items():
  543. try:
  544. original = getattr(mock_module.NonCallableMock, method)
  545. except AttributeError: # pragma: no cover
  546. continue
  547. _mock_module_originals[method] = original
  548. patcher = mock_module.patch.object(mock_module.NonCallableMock, method, wrapper)
  549. patcher.start()
  550. _mock_module_patches.append(patcher)
  551. if hasattr(mock_module, "AsyncMock"):
  552. async_wrappers = {
  553. "assert_awaited": wrap_assert_awaited,
  554. "assert_awaited_once": wrap_assert_awaited_once,
  555. "assert_awaited_with": wrap_assert_awaited_with,
  556. "assert_awaited_once_with": wrap_assert_awaited_once_with,
  557. "assert_any_await": wrap_assert_any_await,
  558. "assert_has_awaits": wrap_assert_has_awaits,
  559. "assert_not_awaited": wrap_assert_not_awaited,
  560. }
  561. for method, wrapper in async_wrappers.items():
  562. try:
  563. original = getattr(mock_module.AsyncMock, method)
  564. except AttributeError: # pragma: no cover
  565. continue
  566. _mock_module_originals[method] = original
  567. patcher = mock_module.patch.object(mock_module.AsyncMock, method, wrapper)
  568. patcher.start()
  569. _mock_module_patches.append(patcher)
  570. config.add_cleanup(unwrap_assert_methods)
  571. def unwrap_assert_methods() -> None:
  572. for patcher in _mock_module_patches:
  573. try:
  574. patcher.stop()
  575. except RuntimeError as e:
  576. # a patcher might have been stopped by user code (#137)
  577. # so we need to catch this error here and ignore it;
  578. # unfortunately there's no public API to check if a patch
  579. # has been started, so catching the error it is
  580. if str(e) == "stop called on unstarted patcher":
  581. pass
  582. else:
  583. raise
  584. _mock_module_patches[:] = []
  585. _mock_module_originals.clear()
  586. def pytest_addoption(parser: Any) -> None:
  587. parser.addini(
  588. "mock_traceback_monkeypatch",
  589. "Monkeypatch the mock library to improve reporting of the "
  590. "assert_called_... methods",
  591. default=True,
  592. )
  593. parser.addini(
  594. "mock_use_standalone_module",
  595. 'Use standalone "mock" (from PyPI) instead of builtin "unittest.mock" '
  596. "on Python 3",
  597. default=False,
  598. )
  599. def pytest_configure(config: Any) -> None:
  600. tb = config.getoption("--tb", default="auto")
  601. if (
  602. parse_ini_boolean(config.getini("mock_traceback_monkeypatch"))
  603. and tb != "native"
  604. ):
  605. wrap_assert_methods(config)