testmock.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034
  1. import copy
  2. import re
  3. import sys
  4. import tempfile
  5. import unittest
  6. from unittest.test.testmock.support import is_instance
  7. from unittest import mock
  8. from unittest.mock import (
  9. call, DEFAULT, patch, sentinel,
  10. MagicMock, Mock, NonCallableMock,
  11. NonCallableMagicMock, _Call, _CallList,
  12. create_autospec
  13. )
  14. class Iter(object):
  15. def __init__(self):
  16. self.thing = iter(['this', 'is', 'an', 'iter'])
  17. def __iter__(self):
  18. return self
  19. def next(self):
  20. return next(self.thing)
  21. __next__ = next
  22. class Something(object):
  23. def meth(self, a, b, c, d=None):
  24. pass
  25. @classmethod
  26. def cmeth(cls, a, b, c, d=None):
  27. pass
  28. @staticmethod
  29. def smeth(a, b, c, d=None):
  30. pass
  31. def something(a): pass
  32. class MockTest(unittest.TestCase):
  33. def test_all(self):
  34. # if __all__ is badly defined then import * will raise an error
  35. # We have to exec it because you can't import * inside a method
  36. # in Python 3
  37. exec("from unittest.mock import *")
  38. def test_constructor(self):
  39. mock = Mock()
  40. self.assertFalse(mock.called, "called not initialised correctly")
  41. self.assertEqual(mock.call_count, 0,
  42. "call_count not initialised correctly")
  43. self.assertTrue(is_instance(mock.return_value, Mock),
  44. "return_value not initialised correctly")
  45. self.assertEqual(mock.call_args, None,
  46. "call_args not initialised correctly")
  47. self.assertEqual(mock.call_args_list, [],
  48. "call_args_list not initialised correctly")
  49. self.assertEqual(mock.method_calls, [],
  50. "method_calls not initialised correctly")
  51. # Can't use hasattr for this test as it always returns True on a mock
  52. self.assertNotIn('_items', mock.__dict__,
  53. "default mock should not have '_items' attribute")
  54. self.assertIsNone(mock._mock_parent,
  55. "parent not initialised correctly")
  56. self.assertIsNone(mock._mock_methods,
  57. "methods not initialised correctly")
  58. self.assertEqual(mock._mock_children, {},
  59. "children not initialised incorrectly")
  60. def test_return_value_in_constructor(self):
  61. mock = Mock(return_value=None)
  62. self.assertIsNone(mock.return_value,
  63. "return value in constructor not honoured")
  64. def test_repr(self):
  65. mock = Mock(name='foo')
  66. self.assertIn('foo', repr(mock))
  67. self.assertIn("'%s'" % id(mock), repr(mock))
  68. mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
  69. for mock, name in mocks:
  70. self.assertIn('%s.bar' % name, repr(mock.bar))
  71. self.assertIn('%s.foo()' % name, repr(mock.foo()))
  72. self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
  73. self.assertIn('%s()' % name, repr(mock()))
  74. self.assertIn('%s()()' % name, repr(mock()()))
  75. self.assertIn('%s()().foo.bar.baz().bing' % name,
  76. repr(mock()().foo.bar.baz().bing))
  77. def test_repr_with_spec(self):
  78. class X(object):
  79. pass
  80. mock = Mock(spec=X)
  81. self.assertIn(" spec='X' ", repr(mock))
  82. mock = Mock(spec=X())
  83. self.assertIn(" spec='X' ", repr(mock))
  84. mock = Mock(spec_set=X)
  85. self.assertIn(" spec_set='X' ", repr(mock))
  86. mock = Mock(spec_set=X())
  87. self.assertIn(" spec_set='X' ", repr(mock))
  88. mock = Mock(spec=X, name='foo')
  89. self.assertIn(" spec='X' ", repr(mock))
  90. self.assertIn(" name='foo' ", repr(mock))
  91. mock = Mock(name='foo')
  92. self.assertNotIn("spec", repr(mock))
  93. mock = Mock()
  94. self.assertNotIn("spec", repr(mock))
  95. mock = Mock(spec=['foo'])
  96. self.assertNotIn("spec", repr(mock))
  97. def test_side_effect(self):
  98. mock = Mock()
  99. def effect(*args, **kwargs):
  100. raise SystemError('kablooie')
  101. mock.side_effect = effect
  102. self.assertRaises(SystemError, mock, 1, 2, fish=3)
  103. mock.assert_called_with(1, 2, fish=3)
  104. results = [1, 2, 3]
  105. def effect():
  106. return results.pop()
  107. mock.side_effect = effect
  108. self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
  109. "side effect not used correctly")
  110. mock = Mock(side_effect=sentinel.SideEffect)
  111. self.assertEqual(mock.side_effect, sentinel.SideEffect,
  112. "side effect in constructor not used")
  113. def side_effect():
  114. return DEFAULT
  115. mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
  116. self.assertEqual(mock(), sentinel.RETURN)
  117. def test_autospec_side_effect(self):
  118. # Test for issue17826
  119. results = [1, 2, 3]
  120. def effect():
  121. return results.pop()
  122. def f():
  123. pass
  124. mock = create_autospec(f)
  125. mock.side_effect = [1, 2, 3]
  126. self.assertEqual([mock(), mock(), mock()], [1, 2, 3],
  127. "side effect not used correctly in create_autospec")
  128. # Test where side effect is a callable
  129. results = [1, 2, 3]
  130. mock = create_autospec(f)
  131. mock.side_effect = effect
  132. self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
  133. "callable side effect not used correctly")
  134. def test_autospec_side_effect_exception(self):
  135. # Test for issue 23661
  136. def f():
  137. pass
  138. mock = create_autospec(f)
  139. mock.side_effect = ValueError('Bazinga!')
  140. self.assertRaisesRegex(ValueError, 'Bazinga!', mock)
  141. @unittest.skipUnless('java' in sys.platform,
  142. 'This test only applies to Jython')
  143. def test_java_exception_side_effect(self):
  144. import java
  145. mock = Mock(side_effect=java.lang.RuntimeException("Boom!"))
  146. # can't use assertRaises with java exceptions
  147. try:
  148. mock(1, 2, fish=3)
  149. except java.lang.RuntimeException:
  150. pass
  151. else:
  152. self.fail('java exception not raised')
  153. mock.assert_called_with(1,2, fish=3)
  154. def test_reset_mock(self):
  155. parent = Mock()
  156. spec = ["something"]
  157. mock = Mock(name="child", parent=parent, spec=spec)
  158. mock(sentinel.Something, something=sentinel.SomethingElse)
  159. something = mock.something
  160. mock.something()
  161. mock.side_effect = sentinel.SideEffect
  162. return_value = mock.return_value
  163. return_value()
  164. mock.reset_mock()
  165. self.assertEqual(mock._mock_name, "child",
  166. "name incorrectly reset")
  167. self.assertEqual(mock._mock_parent, parent,
  168. "parent incorrectly reset")
  169. self.assertEqual(mock._mock_methods, spec,
  170. "methods incorrectly reset")
  171. self.assertFalse(mock.called, "called not reset")
  172. self.assertEqual(mock.call_count, 0, "call_count not reset")
  173. self.assertEqual(mock.call_args, None, "call_args not reset")
  174. self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
  175. self.assertEqual(mock.method_calls, [],
  176. "method_calls not initialised correctly: %r != %r" %
  177. (mock.method_calls, []))
  178. self.assertEqual(mock.mock_calls, [])
  179. self.assertEqual(mock.side_effect, sentinel.SideEffect,
  180. "side_effect incorrectly reset")
  181. self.assertEqual(mock.return_value, return_value,
  182. "return_value incorrectly reset")
  183. self.assertFalse(return_value.called, "return value mock not reset")
  184. self.assertEqual(mock._mock_children, {'something': something},
  185. "children reset incorrectly")
  186. self.assertEqual(mock.something, something,
  187. "children incorrectly cleared")
  188. self.assertFalse(mock.something.called, "child not reset")
  189. def test_reset_mock_recursion(self):
  190. mock = Mock()
  191. mock.return_value = mock
  192. # used to cause recursion
  193. mock.reset_mock()
  194. def test_reset_mock_on_mock_open_issue_18622(self):
  195. a = mock.mock_open()
  196. a.reset_mock()
  197. def test_call(self):
  198. mock = Mock()
  199. self.assertTrue(is_instance(mock.return_value, Mock),
  200. "Default return_value should be a Mock")
  201. result = mock()
  202. self.assertEqual(mock(), result,
  203. "different result from consecutive calls")
  204. mock.reset_mock()
  205. ret_val = mock(sentinel.Arg)
  206. self.assertTrue(mock.called, "called not set")
  207. self.assertEqual(mock.call_count, 1, "call_count incoreect")
  208. self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
  209. "call_args not set")
  210. self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
  211. "call_args_list not initialised correctly")
  212. mock.return_value = sentinel.ReturnValue
  213. ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
  214. self.assertEqual(ret_val, sentinel.ReturnValue,
  215. "incorrect return value")
  216. self.assertEqual(mock.call_count, 2, "call_count incorrect")
  217. self.assertEqual(mock.call_args,
  218. ((sentinel.Arg,), {'key': sentinel.KeyArg}),
  219. "call_args not set")
  220. self.assertEqual(mock.call_args_list, [
  221. ((sentinel.Arg,), {}),
  222. ((sentinel.Arg,), {'key': sentinel.KeyArg})
  223. ],
  224. "call_args_list not set")
  225. def test_call_args_comparison(self):
  226. mock = Mock()
  227. mock()
  228. mock(sentinel.Arg)
  229. mock(kw=sentinel.Kwarg)
  230. mock(sentinel.Arg, kw=sentinel.Kwarg)
  231. self.assertEqual(mock.call_args_list, [
  232. (),
  233. ((sentinel.Arg,),),
  234. ({"kw": sentinel.Kwarg},),
  235. ((sentinel.Arg,), {"kw": sentinel.Kwarg})
  236. ])
  237. self.assertEqual(mock.call_args,
  238. ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
  239. # Comparing call_args to a long sequence should not raise
  240. # an exception. See issue 24857.
  241. self.assertFalse(mock.call_args == "a long sequence")
  242. def test_calls_equal_with_any(self):
  243. # Check that equality and non-equality is consistent even when
  244. # comparing with mock.ANY
  245. mm = mock.MagicMock()
  246. self.assertTrue(mm == mm)
  247. self.assertFalse(mm != mm)
  248. self.assertFalse(mm == mock.MagicMock())
  249. self.assertTrue(mm != mock.MagicMock())
  250. self.assertTrue(mm == mock.ANY)
  251. self.assertFalse(mm != mock.ANY)
  252. self.assertTrue(mock.ANY == mm)
  253. self.assertFalse(mock.ANY != mm)
  254. call1 = mock.call(mock.MagicMock())
  255. call2 = mock.call(mock.ANY)
  256. self.assertTrue(call1 == call2)
  257. self.assertFalse(call1 != call2)
  258. self.assertTrue(call2 == call1)
  259. self.assertFalse(call2 != call1)
  260. def test_assert_called_with(self):
  261. mock = Mock()
  262. mock()
  263. # Will raise an exception if it fails
  264. mock.assert_called_with()
  265. self.assertRaises(AssertionError, mock.assert_called_with, 1)
  266. mock.reset_mock()
  267. self.assertRaises(AssertionError, mock.assert_called_with)
  268. mock(1, 2, 3, a='fish', b='nothing')
  269. mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
  270. def test_assert_called_with_any(self):
  271. m = MagicMock()
  272. m(MagicMock())
  273. m.assert_called_with(mock.ANY)
  274. def test_assert_called_with_function_spec(self):
  275. def f(a, b, c, d=None):
  276. pass
  277. mock = Mock(spec=f)
  278. mock(1, b=2, c=3)
  279. mock.assert_called_with(1, 2, 3)
  280. mock.assert_called_with(a=1, b=2, c=3)
  281. self.assertRaises(AssertionError, mock.assert_called_with,
  282. 1, b=3, c=2)
  283. # Expected call doesn't match the spec's signature
  284. with self.assertRaises(AssertionError) as cm:
  285. mock.assert_called_with(e=8)
  286. self.assertIsInstance(cm.exception.__cause__, TypeError)
  287. def test_assert_called_with_method_spec(self):
  288. def _check(mock):
  289. mock(1, b=2, c=3)
  290. mock.assert_called_with(1, 2, 3)
  291. mock.assert_called_with(a=1, b=2, c=3)
  292. self.assertRaises(AssertionError, mock.assert_called_with,
  293. 1, b=3, c=2)
  294. mock = Mock(spec=Something().meth)
  295. _check(mock)
  296. mock = Mock(spec=Something.cmeth)
  297. _check(mock)
  298. mock = Mock(spec=Something().cmeth)
  299. _check(mock)
  300. mock = Mock(spec=Something.smeth)
  301. _check(mock)
  302. mock = Mock(spec=Something().smeth)
  303. _check(mock)
  304. def test_assert_called_once_with(self):
  305. mock = Mock()
  306. mock()
  307. # Will raise an exception if it fails
  308. mock.assert_called_once_with()
  309. mock()
  310. self.assertRaises(AssertionError, mock.assert_called_once_with)
  311. mock.reset_mock()
  312. self.assertRaises(AssertionError, mock.assert_called_once_with)
  313. mock('foo', 'bar', baz=2)
  314. mock.assert_called_once_with('foo', 'bar', baz=2)
  315. mock.reset_mock()
  316. mock('foo', 'bar', baz=2)
  317. self.assertRaises(
  318. AssertionError,
  319. lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
  320. )
  321. def test_assert_called_once_with_function_spec(self):
  322. def f(a, b, c, d=None):
  323. pass
  324. mock = Mock(spec=f)
  325. mock(1, b=2, c=3)
  326. mock.assert_called_once_with(1, 2, 3)
  327. mock.assert_called_once_with(a=1, b=2, c=3)
  328. self.assertRaises(AssertionError, mock.assert_called_once_with,
  329. 1, b=3, c=2)
  330. # Expected call doesn't match the spec's signature
  331. with self.assertRaises(AssertionError) as cm:
  332. mock.assert_called_once_with(e=8)
  333. self.assertIsInstance(cm.exception.__cause__, TypeError)
  334. # Mock called more than once => always fails
  335. mock(4, 5, 6)
  336. self.assertRaises(AssertionError, mock.assert_called_once_with,
  337. 1, 2, 3)
  338. self.assertRaises(AssertionError, mock.assert_called_once_with,
  339. 4, 5, 6)
  340. def test_attribute_access_returns_mocks(self):
  341. mock = Mock()
  342. something = mock.something
  343. self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
  344. self.assertEqual(mock.something, something,
  345. "different attributes returned for same name")
  346. # Usage example
  347. mock = Mock()
  348. mock.something.return_value = 3
  349. self.assertEqual(mock.something(), 3, "method returned wrong value")
  350. self.assertTrue(mock.something.called,
  351. "method didn't record being called")
  352. def test_attributes_have_name_and_parent_set(self):
  353. mock = Mock()
  354. something = mock.something
  355. self.assertEqual(something._mock_name, "something",
  356. "attribute name not set correctly")
  357. self.assertEqual(something._mock_parent, mock,
  358. "attribute parent not set correctly")
  359. def test_method_calls_recorded(self):
  360. mock = Mock()
  361. mock.something(3, fish=None)
  362. mock.something_else.something(6, cake=sentinel.Cake)
  363. self.assertEqual(mock.something_else.method_calls,
  364. [("something", (6,), {'cake': sentinel.Cake})],
  365. "method calls not recorded correctly")
  366. self.assertEqual(mock.method_calls, [
  367. ("something", (3,), {'fish': None}),
  368. ("something_else.something", (6,), {'cake': sentinel.Cake})
  369. ],
  370. "method calls not recorded correctly")
  371. def test_method_calls_compare_easily(self):
  372. mock = Mock()
  373. mock.something()
  374. self.assertEqual(mock.method_calls, [('something',)])
  375. self.assertEqual(mock.method_calls, [('something', (), {})])
  376. mock = Mock()
  377. mock.something('different')
  378. self.assertEqual(mock.method_calls, [('something', ('different',))])
  379. self.assertEqual(mock.method_calls,
  380. [('something', ('different',), {})])
  381. mock = Mock()
  382. mock.something(x=1)
  383. self.assertEqual(mock.method_calls, [('something', {'x': 1})])
  384. self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
  385. mock = Mock()
  386. mock.something('different', some='more')
  387. self.assertEqual(mock.method_calls, [
  388. ('something', ('different',), {'some': 'more'})
  389. ])
  390. def test_only_allowed_methods_exist(self):
  391. for spec in ['something'], ('something',):
  392. for arg in 'spec', 'spec_set':
  393. mock = Mock(**{arg: spec})
  394. # this should be allowed
  395. mock.something
  396. self.assertRaisesRegex(
  397. AttributeError,
  398. "Mock object has no attribute 'something_else'",
  399. getattr, mock, 'something_else'
  400. )
  401. def test_from_spec(self):
  402. class Something(object):
  403. x = 3
  404. __something__ = None
  405. def y(self):
  406. pass
  407. def test_attributes(mock):
  408. # should work
  409. mock.x
  410. mock.y
  411. mock.__something__
  412. self.assertRaisesRegex(
  413. AttributeError,
  414. "Mock object has no attribute 'z'",
  415. getattr, mock, 'z'
  416. )
  417. self.assertRaisesRegex(
  418. AttributeError,
  419. "Mock object has no attribute '__foobar__'",
  420. getattr, mock, '__foobar__'
  421. )
  422. test_attributes(Mock(spec=Something))
  423. test_attributes(Mock(spec=Something()))
  424. def test_wraps_calls(self):
  425. real = Mock()
  426. mock = Mock(wraps=real)
  427. self.assertEqual(mock(), real())
  428. real.reset_mock()
  429. mock(1, 2, fish=3)
  430. real.assert_called_with(1, 2, fish=3)
  431. def test_wraps_prevents_automatic_creation_of_mocks(self):
  432. class Real(object):
  433. pass
  434. real = Real()
  435. mock = Mock(wraps=real)
  436. self.assertRaises(AttributeError, lambda: mock.new_attr())
  437. def test_wraps_call_with_nondefault_return_value(self):
  438. real = Mock()
  439. mock = Mock(wraps=real)
  440. mock.return_value = 3
  441. self.assertEqual(mock(), 3)
  442. self.assertFalse(real.called)
  443. def test_wraps_attributes(self):
  444. class Real(object):
  445. attribute = Mock()
  446. real = Real()
  447. mock = Mock(wraps=real)
  448. self.assertEqual(mock.attribute(), real.attribute())
  449. self.assertRaises(AttributeError, lambda: mock.fish)
  450. self.assertNotEqual(mock.attribute, real.attribute)
  451. result = mock.attribute.frog(1, 2, fish=3)
  452. Real.attribute.frog.assert_called_with(1, 2, fish=3)
  453. self.assertEqual(result, Real.attribute.frog())
  454. def test_customize_wrapped_object_with_side_effect_iterable_with_default(self):
  455. class Real(object):
  456. def method(self):
  457. return sentinel.ORIGINAL_VALUE
  458. real = Real()
  459. mock = Mock(wraps=real)
  460. mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
  461. self.assertEqual(mock.method(), sentinel.VALUE1)
  462. self.assertEqual(mock.method(), sentinel.ORIGINAL_VALUE)
  463. self.assertRaises(StopIteration, mock.method)
  464. def test_customize_wrapped_object_with_side_effect_iterable(self):
  465. class Real(object):
  466. def method(self):
  467. raise NotImplementedError()
  468. real = Real()
  469. mock = Mock(wraps=real)
  470. mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
  471. self.assertEqual(mock.method(), sentinel.VALUE1)
  472. self.assertEqual(mock.method(), sentinel.VALUE2)
  473. self.assertRaises(StopIteration, mock.method)
  474. def test_customize_wrapped_object_with_side_effect_exception(self):
  475. class Real(object):
  476. def method(self):
  477. raise NotImplementedError()
  478. real = Real()
  479. mock = Mock(wraps=real)
  480. mock.method.side_effect = RuntimeError
  481. self.assertRaises(RuntimeError, mock.method)
  482. def test_customize_wrapped_object_with_side_effect_function(self):
  483. class Real(object):
  484. def method(self):
  485. raise NotImplementedError()
  486. def side_effect():
  487. return sentinel.VALUE
  488. real = Real()
  489. mock = Mock(wraps=real)
  490. mock.method.side_effect = side_effect
  491. self.assertEqual(mock.method(), sentinel.VALUE)
  492. def test_customize_wrapped_object_with_return_value(self):
  493. class Real(object):
  494. def method(self):
  495. raise NotImplementedError()
  496. real = Real()
  497. mock = Mock(wraps=real)
  498. mock.method.return_value = sentinel.VALUE
  499. self.assertEqual(mock.method(), sentinel.VALUE)
  500. def test_customize_wrapped_object_with_return_value_and_side_effect(self):
  501. # side_effect should always take precedence over return_value.
  502. class Real(object):
  503. def method(self):
  504. raise NotImplementedError()
  505. real = Real()
  506. mock = Mock(wraps=real)
  507. mock.method.side_effect = [sentinel.VALUE1, sentinel.VALUE2]
  508. mock.method.return_value = sentinel.WRONG_VALUE
  509. self.assertEqual(mock.method(), sentinel.VALUE1)
  510. self.assertEqual(mock.method(), sentinel.VALUE2)
  511. self.assertRaises(StopIteration, mock.method)
  512. def test_customize_wrapped_object_with_return_value_and_side_effect2(self):
  513. # side_effect can return DEFAULT to default to return_value
  514. class Real(object):
  515. def method(self):
  516. raise NotImplementedError()
  517. real = Real()
  518. mock = Mock(wraps=real)
  519. mock.method.side_effect = lambda: DEFAULT
  520. mock.method.return_value = sentinel.VALUE
  521. self.assertEqual(mock.method(), sentinel.VALUE)
  522. def test_customize_wrapped_object_with_return_value_and_side_effect_default(self):
  523. class Real(object):
  524. def method(self):
  525. raise NotImplementedError()
  526. real = Real()
  527. mock = Mock(wraps=real)
  528. mock.method.side_effect = [sentinel.VALUE1, DEFAULT]
  529. mock.method.return_value = sentinel.RETURN
  530. self.assertEqual(mock.method(), sentinel.VALUE1)
  531. self.assertEqual(mock.method(), sentinel.RETURN)
  532. self.assertRaises(StopIteration, mock.method)
  533. def test_exceptional_side_effect(self):
  534. mock = Mock(side_effect=AttributeError)
  535. self.assertRaises(AttributeError, mock)
  536. mock = Mock(side_effect=AttributeError('foo'))
  537. self.assertRaises(AttributeError, mock)
  538. def test_baseexceptional_side_effect(self):
  539. mock = Mock(side_effect=KeyboardInterrupt)
  540. self.assertRaises(KeyboardInterrupt, mock)
  541. mock = Mock(side_effect=KeyboardInterrupt('foo'))
  542. self.assertRaises(KeyboardInterrupt, mock)
  543. def test_assert_called_with_message(self):
  544. mock = Mock()
  545. self.assertRaisesRegex(AssertionError, 'Not called',
  546. mock.assert_called_with)
  547. def test_assert_called_once_with_message(self):
  548. mock = Mock(name='geoffrey')
  549. self.assertRaisesRegex(AssertionError,
  550. r"Expected 'geoffrey' to be called once\.",
  551. mock.assert_called_once_with)
  552. def test__name__(self):
  553. mock = Mock()
  554. self.assertRaises(AttributeError, lambda: mock.__name__)
  555. mock.__name__ = 'foo'
  556. self.assertEqual(mock.__name__, 'foo')
  557. def test_spec_list_subclass(self):
  558. class Sub(list):
  559. pass
  560. mock = Mock(spec=Sub(['foo']))
  561. mock.append(3)
  562. mock.append.assert_called_with(3)
  563. self.assertRaises(AttributeError, getattr, mock, 'foo')
  564. def test_spec_class(self):
  565. class X(object):
  566. pass
  567. mock = Mock(spec=X)
  568. self.assertIsInstance(mock, X)
  569. mock = Mock(spec=X())
  570. self.assertIsInstance(mock, X)
  571. self.assertIs(mock.__class__, X)
  572. self.assertEqual(Mock().__class__.__name__, 'Mock')
  573. mock = Mock(spec_set=X)
  574. self.assertIsInstance(mock, X)
  575. mock = Mock(spec_set=X())
  576. self.assertIsInstance(mock, X)
  577. def test_setting_attribute_with_spec_set(self):
  578. class X(object):
  579. y = 3
  580. mock = Mock(spec=X)
  581. mock.x = 'foo'
  582. mock = Mock(spec_set=X)
  583. def set_attr():
  584. mock.x = 'foo'
  585. mock.y = 'foo'
  586. self.assertRaises(AttributeError, set_attr)
  587. def test_copy(self):
  588. current = sys.getrecursionlimit()
  589. self.addCleanup(sys.setrecursionlimit, current)
  590. # can't use sys.maxint as this doesn't exist in Python 3
  591. sys.setrecursionlimit(int(10e8))
  592. # this segfaults without the fix in place
  593. copy.copy(Mock())
  594. def test_subclass_with_properties(self):
  595. class SubClass(Mock):
  596. def _get(self):
  597. return 3
  598. def _set(self, value):
  599. raise NameError('strange error')
  600. some_attribute = property(_get, _set)
  601. s = SubClass(spec_set=SubClass)
  602. self.assertEqual(s.some_attribute, 3)
  603. def test():
  604. s.some_attribute = 3
  605. self.assertRaises(NameError, test)
  606. def test():
  607. s.foo = 'bar'
  608. self.assertRaises(AttributeError, test)
  609. def test_setting_call(self):
  610. mock = Mock()
  611. def __call__(self, a):
  612. return self._mock_call(a)
  613. type(mock).__call__ = __call__
  614. mock('one')
  615. mock.assert_called_with('one')
  616. self.assertRaises(TypeError, mock, 'one', 'two')
  617. def test_dir(self):
  618. mock = Mock()
  619. attrs = set(dir(mock))
  620. type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
  621. # all public attributes from the type are included
  622. self.assertEqual(set(), type_attrs - attrs)
  623. # creates these attributes
  624. mock.a, mock.b
  625. self.assertIn('a', dir(mock))
  626. self.assertIn('b', dir(mock))
  627. # instance attributes
  628. mock.c = mock.d = None
  629. self.assertIn('c', dir(mock))
  630. self.assertIn('d', dir(mock))
  631. # magic methods
  632. mock.__iter__ = lambda s: iter([])
  633. self.assertIn('__iter__', dir(mock))
  634. def test_dir_from_spec(self):
  635. mock = Mock(spec=unittest.TestCase)
  636. testcase_attrs = set(dir(unittest.TestCase))
  637. attrs = set(dir(mock))
  638. # all attributes from the spec are included
  639. self.assertEqual(set(), testcase_attrs - attrs)
  640. # shadow a sys attribute
  641. mock.version = 3
  642. self.assertEqual(dir(mock).count('version'), 1)
  643. def test_filter_dir(self):
  644. patcher = patch.object(mock, 'FILTER_DIR', False)
  645. patcher.start()
  646. try:
  647. attrs = set(dir(Mock()))
  648. type_attrs = set(dir(Mock))
  649. # ALL attributes from the type are included
  650. self.assertEqual(set(), type_attrs - attrs)
  651. finally:
  652. patcher.stop()
  653. def test_dir_does_not_include_deleted_attributes(self):
  654. mock = Mock()
  655. mock.child.return_value = 1
  656. self.assertIn('child', dir(mock))
  657. del mock.child
  658. self.assertNotIn('child', dir(mock))
  659. def test_configure_mock(self):
  660. mock = Mock(foo='bar')
  661. self.assertEqual(mock.foo, 'bar')
  662. mock = MagicMock(foo='bar')
  663. self.assertEqual(mock.foo, 'bar')
  664. kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
  665. 'foo': MagicMock()}
  666. mock = Mock(**kwargs)
  667. self.assertRaises(KeyError, mock)
  668. self.assertEqual(mock.foo.bar(), 33)
  669. self.assertIsInstance(mock.foo, MagicMock)
  670. mock = Mock()
  671. mock.configure_mock(**kwargs)
  672. self.assertRaises(KeyError, mock)
  673. self.assertEqual(mock.foo.bar(), 33)
  674. self.assertIsInstance(mock.foo, MagicMock)
  675. def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
  676. # needed because assertRaisesRegex doesn't work easily with newlines
  677. try:
  678. func(*args, **kwargs)
  679. except:
  680. instance = sys.exc_info()[1]
  681. self.assertIsInstance(instance, exception)
  682. else:
  683. self.fail('Exception %r not raised' % (exception,))
  684. msg = str(instance)
  685. self.assertEqual(msg, message)
  686. def test_assert_called_with_failure_message(self):
  687. mock = NonCallableMock()
  688. expected = "mock(1, '2', 3, bar='foo')"
  689. message = 'Expected call: %s\nNot called'
  690. self.assertRaisesWithMsg(
  691. AssertionError, message % (expected,),
  692. mock.assert_called_with, 1, '2', 3, bar='foo'
  693. )
  694. mock.foo(1, '2', 3, foo='foo')
  695. asserters = [
  696. mock.foo.assert_called_with, mock.foo.assert_called_once_with
  697. ]
  698. for meth in asserters:
  699. actual = "foo(1, '2', 3, foo='foo')"
  700. expected = "foo(1, '2', 3, bar='foo')"
  701. message = 'Expected call: %s\nActual call: %s'
  702. self.assertRaisesWithMsg(
  703. AssertionError, message % (expected, actual),
  704. meth, 1, '2', 3, bar='foo'
  705. )
  706. # just kwargs
  707. for meth in asserters:
  708. actual = "foo(1, '2', 3, foo='foo')"
  709. expected = "foo(bar='foo')"
  710. message = 'Expected call: %s\nActual call: %s'
  711. self.assertRaisesWithMsg(
  712. AssertionError, message % (expected, actual),
  713. meth, bar='foo'
  714. )
  715. # just args
  716. for meth in asserters:
  717. actual = "foo(1, '2', 3, foo='foo')"
  718. expected = "foo(1, 2, 3)"
  719. message = 'Expected call: %s\nActual call: %s'
  720. self.assertRaisesWithMsg(
  721. AssertionError, message % (expected, actual),
  722. meth, 1, 2, 3
  723. )
  724. # empty
  725. for meth in asserters:
  726. actual = "foo(1, '2', 3, foo='foo')"
  727. expected = "foo()"
  728. message = 'Expected call: %s\nActual call: %s'
  729. self.assertRaisesWithMsg(
  730. AssertionError, message % (expected, actual), meth
  731. )
  732. def test_mock_calls(self):
  733. mock = MagicMock()
  734. # need to do this because MagicMock.mock_calls used to just return
  735. # a MagicMock which also returned a MagicMock when __eq__ was called
  736. self.assertIs(mock.mock_calls == [], True)
  737. mock = MagicMock()
  738. mock()
  739. expected = [('', (), {})]
  740. self.assertEqual(mock.mock_calls, expected)
  741. mock.foo()
  742. expected.append(call.foo())
  743. self.assertEqual(mock.mock_calls, expected)
  744. # intermediate mock_calls work too
  745. self.assertEqual(mock.foo.mock_calls, [('', (), {})])
  746. mock = MagicMock()
  747. mock().foo(1, 2, 3, a=4, b=5)
  748. expected = [
  749. ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
  750. ]
  751. self.assertEqual(mock.mock_calls, expected)
  752. self.assertEqual(mock.return_value.foo.mock_calls,
  753. [('', (1, 2, 3), dict(a=4, b=5))])
  754. self.assertEqual(mock.return_value.mock_calls,
  755. [('foo', (1, 2, 3), dict(a=4, b=5))])
  756. mock = MagicMock()
  757. mock().foo.bar().baz()
  758. expected = [
  759. ('', (), {}), ('().foo.bar', (), {}),
  760. ('().foo.bar().baz', (), {})
  761. ]
  762. self.assertEqual(mock.mock_calls, expected)
  763. self.assertEqual(mock().mock_calls,
  764. call.foo.bar().baz().call_list())
  765. for kwargs in dict(), dict(name='bar'):
  766. mock = MagicMock(**kwargs)
  767. int(mock.foo)
  768. expected = [('foo.__int__', (), {})]
  769. self.assertEqual(mock.mock_calls, expected)
  770. mock = MagicMock(**kwargs)
  771. mock.a()()
  772. expected = [('a', (), {}), ('a()', (), {})]
  773. self.assertEqual(mock.mock_calls, expected)
  774. self.assertEqual(mock.a().mock_calls, [call()])
  775. mock = MagicMock(**kwargs)
  776. mock(1)(2)(3)
  777. self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
  778. self.assertEqual(mock().mock_calls, call(2)(3).call_list())
  779. self.assertEqual(mock()().mock_calls, call(3).call_list())
  780. mock = MagicMock(**kwargs)
  781. mock(1)(2)(3).a.b.c(4)
  782. self.assertEqual(mock.mock_calls,
  783. call(1)(2)(3).a.b.c(4).call_list())
  784. self.assertEqual(mock().mock_calls,
  785. call(2)(3).a.b.c(4).call_list())
  786. self.assertEqual(mock()().mock_calls,
  787. call(3).a.b.c(4).call_list())
  788. mock = MagicMock(**kwargs)
  789. int(mock().foo.bar().baz())
  790. last_call = ('().foo.bar().baz().__int__', (), {})
  791. self.assertEqual(mock.mock_calls[-1], last_call)
  792. self.assertEqual(mock().mock_calls,
  793. call.foo.bar().baz().__int__().call_list())
  794. self.assertEqual(mock().foo.bar().mock_calls,
  795. call.baz().__int__().call_list())
  796. self.assertEqual(mock().foo.bar().baz.mock_calls,
  797. call().__int__().call_list())
  798. def test_child_mock_call_equal(self):
  799. m = Mock()
  800. result = m()
  801. result.wibble()
  802. # parent looks like this:
  803. self.assertEqual(m.mock_calls, [call(), call().wibble()])
  804. # but child should look like this:
  805. self.assertEqual(result.mock_calls, [call.wibble()])
  806. def test_mock_call_not_equal_leaf(self):
  807. m = Mock()
  808. m.foo().something()
  809. self.assertNotEqual(m.mock_calls[1], call.foo().different())
  810. self.assertEqual(m.mock_calls[0], call.foo())
  811. def test_mock_call_not_equal_non_leaf(self):
  812. m = Mock()
  813. m.foo().bar()
  814. self.assertNotEqual(m.mock_calls[1], call.baz().bar())
  815. self.assertNotEqual(m.mock_calls[0], call.baz())
  816. def test_mock_call_not_equal_non_leaf_params_different(self):
  817. m = Mock()
  818. m.foo(x=1).bar()
  819. # This isn't ideal, but there's no way to fix it without breaking backwards compatibility:
  820. self.assertEqual(m.mock_calls[1], call.foo(x=2).bar())
  821. def test_mock_call_not_equal_non_leaf_attr(self):
  822. m = Mock()
  823. m.foo.bar()
  824. self.assertNotEqual(m.mock_calls[0], call.baz.bar())
  825. def test_mock_call_not_equal_non_leaf_call_versus_attr(self):
  826. m = Mock()
  827. m.foo.bar()
  828. self.assertNotEqual(m.mock_calls[0], call.foo().bar())
  829. def test_mock_call_repr(self):
  830. m = Mock()
  831. m.foo().bar().baz.bob()
  832. self.assertEqual(repr(m.mock_calls[0]), 'call.foo()')
  833. self.assertEqual(repr(m.mock_calls[1]), 'call.foo().bar()')
  834. self.assertEqual(repr(m.mock_calls[2]), 'call.foo().bar().baz.bob()')
  835. def test_subclassing(self):
  836. class Subclass(Mock):
  837. pass
  838. mock = Subclass()
  839. self.assertIsInstance(mock.foo, Subclass)
  840. self.assertIsInstance(mock(), Subclass)
  841. class Subclass(Mock):
  842. def _get_child_mock(self, **kwargs):
  843. return Mock(**kwargs)
  844. mock = Subclass()
  845. self.assertNotIsInstance(mock.foo, Subclass)
  846. self.assertNotIsInstance(mock(), Subclass)
  847. def test_arg_lists(self):
  848. mocks = [
  849. Mock(),
  850. MagicMock(),
  851. NonCallableMock(),
  852. NonCallableMagicMock()
  853. ]
  854. def assert_attrs(mock):
  855. names = 'call_args_list', 'method_calls', 'mock_calls'
  856. for name in names:
  857. attr = getattr(mock, name)
  858. self.assertIsInstance(attr, _CallList)
  859. self.assertIsInstance(attr, list)
  860. self.assertEqual(attr, [])
  861. for mock in mocks:
  862. assert_attrs(mock)
  863. if callable(mock):
  864. mock()
  865. mock(1, 2)
  866. mock(a=3)
  867. mock.reset_mock()
  868. assert_attrs(mock)
  869. mock.foo()
  870. mock.foo.bar(1, a=3)
  871. mock.foo(1).bar().baz(3)
  872. mock.reset_mock()
  873. assert_attrs(mock)
  874. def test_call_args_two_tuple(self):
  875. mock = Mock()
  876. mock(1, a=3)
  877. mock(2, b=4)
  878. self.assertEqual(len(mock.call_args), 2)
  879. args, kwargs = mock.call_args
  880. self.assertEqual(args, (2,))
  881. self.assertEqual(kwargs, dict(b=4))
  882. expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
  883. for expected, call_args in zip(expected_list, mock.call_args_list):
  884. self.assertEqual(len(call_args), 2)
  885. self.assertEqual(expected[0], call_args[0])
  886. self.assertEqual(expected[1], call_args[1])
  887. def test_side_effect_iterator(self):
  888. mock = Mock(side_effect=iter([1, 2, 3]))
  889. self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
  890. self.assertRaises(StopIteration, mock)
  891. mock = MagicMock(side_effect=['a', 'b', 'c'])
  892. self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
  893. self.assertRaises(StopIteration, mock)
  894. mock = Mock(side_effect='ghi')
  895. self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
  896. self.assertRaises(StopIteration, mock)
  897. class Foo(object):
  898. pass
  899. mock = MagicMock(side_effect=Foo)
  900. self.assertIsInstance(mock(), Foo)
  901. mock = Mock(side_effect=Iter())
  902. self.assertEqual([mock(), mock(), mock(), mock()],
  903. ['this', 'is', 'an', 'iter'])
  904. self.assertRaises(StopIteration, mock)
  905. def test_side_effect_iterator_exceptions(self):
  906. for Klass in Mock, MagicMock:
  907. iterable = (ValueError, 3, KeyError, 6)
  908. m = Klass(side_effect=iterable)
  909. self.assertRaises(ValueError, m)
  910. self.assertEqual(m(), 3)
  911. self.assertRaises(KeyError, m)
  912. self.assertEqual(m(), 6)
  913. def test_side_effect_setting_iterator(self):
  914. mock = Mock()
  915. mock.side_effect = iter([1, 2, 3])
  916. self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
  917. self.assertRaises(StopIteration, mock)
  918. side_effect = mock.side_effect
  919. self.assertIsInstance(side_effect, type(iter([])))
  920. mock.side_effect = ['a', 'b', 'c']
  921. self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
  922. self.assertRaises(StopIteration, mock)
  923. side_effect = mock.side_effect
  924. self.assertIsInstance(side_effect, type(iter([])))
  925. this_iter = Iter()
  926. mock.side_effect = this_iter
  927. self.assertEqual([mock(), mock(), mock(), mock()],
  928. ['this', 'is', 'an', 'iter'])
  929. self.assertRaises(StopIteration, mock)
  930. self.assertIs(mock.side_effect, this_iter)
  931. def test_side_effect_iterator_default(self):
  932. mock = Mock(return_value=2)
  933. mock.side_effect = iter([1, DEFAULT])
  934. self.assertEqual([mock(), mock()], [1, 2])
  935. def test_assert_has_calls_any_order(self):
  936. mock = Mock()
  937. mock(1, 2)
  938. mock(a=3)
  939. mock(3, 4)
  940. mock(b=6)
  941. mock(b=6)
  942. kalls = [
  943. call(1, 2), ({'a': 3},),
  944. ((3, 4),), ((), {'a': 3}),
  945. ('', (1, 2)), ('', {'a': 3}),
  946. ('', (1, 2), {}), ('', (), {'a': 3})
  947. ]
  948. for kall in kalls:
  949. mock.assert_has_calls([kall], any_order=True)
  950. for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
  951. self.assertRaises(
  952. AssertionError, mock.assert_has_calls,
  953. [kall], any_order=True
  954. )
  955. kall_lists = [
  956. [call(1, 2), call(b=6)],
  957. [call(3, 4), call(1, 2)],
  958. [call(b=6), call(b=6)],
  959. ]
  960. for kall_list in kall_lists:
  961. mock.assert_has_calls(kall_list, any_order=True)
  962. kall_lists = [
  963. [call(b=6), call(b=6), call(b=6)],
  964. [call(1, 2), call(1, 2)],
  965. [call(3, 4), call(1, 2), call(5, 7)],
  966. [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
  967. ]
  968. for kall_list in kall_lists:
  969. self.assertRaises(
  970. AssertionError, mock.assert_has_calls,
  971. kall_list, any_order=True
  972. )
  973. def test_assert_has_calls(self):
  974. kalls1 = [
  975. call(1, 2), ({'a': 3},),
  976. ((3, 4),), call(b=6),
  977. ('', (1,), {'b': 6}),
  978. ]
  979. kalls2 = [call.foo(), call.bar(1)]
  980. kalls2.extend(call.spam().baz(a=3).call_list())
  981. kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
  982. mocks = []
  983. for mock in Mock(), MagicMock():
  984. mock(1, 2)
  985. mock(a=3)
  986. mock(3, 4)
  987. mock(b=6)
  988. mock(1, b=6)
  989. mocks.append((mock, kalls1))
  990. mock = Mock()
  991. mock.foo()
  992. mock.bar(1)
  993. mock.spam().baz(a=3)
  994. mock.bam(set(), foo={}).fish([1])
  995. mocks.append((mock, kalls2))
  996. for mock, kalls in mocks:
  997. for i in range(len(kalls)):
  998. for step in 1, 2, 3:
  999. these = kalls[i:i+step]
  1000. mock.assert_has_calls(these)
  1001. if len(these) > 1:
  1002. self.assertRaises(
  1003. AssertionError,
  1004. mock.assert_has_calls,
  1005. list(reversed(these))
  1006. )
  1007. def test_assert_has_calls_nested_spec(self):
  1008. class Something:
  1009. def __init__(self): pass
  1010. def meth(self, a, b, c, d=None): pass
  1011. class Foo:
  1012. def __init__(self, a): pass
  1013. def meth1(self, a, b): pass
  1014. mock_class = create_autospec(Something)
  1015. for m in [mock_class, mock_class()]:
  1016. m.meth(1, 2, 3, d=1)
  1017. m.assert_has_calls([call.meth(1, 2, 3, d=1)])
  1018. m.assert_has_calls([call.meth(1, 2, 3, 1)])
  1019. mock_class.reset_mock()
  1020. for m in [mock_class, mock_class()]:
  1021. self.assertRaises(AssertionError, m.assert_has_calls, [call.Foo()])
  1022. m.Foo(1).meth1(1, 2)
  1023. m.assert_has_calls([call.Foo(1), call.Foo(1).meth1(1, 2)])
  1024. m.Foo.assert_has_calls([call(1), call().meth1(1, 2)])
  1025. mock_class.reset_mock()
  1026. invalid_calls = [call.meth(1),
  1027. call.non_existent(1),
  1028. call.Foo().non_existent(1),
  1029. call.Foo().meth(1, 2, 3, 4)]
  1030. for kall in invalid_calls:
  1031. self.assertRaises(AssertionError,
  1032. mock_class.assert_has_calls,
  1033. [kall]
  1034. )
  1035. def test_assert_has_calls_nested_without_spec(self):
  1036. m = MagicMock()
  1037. m().foo().bar().baz()
  1038. m.one().two().three()
  1039. calls = call.one().two().three().call_list()
  1040. m.assert_has_calls(calls)
  1041. def test_assert_has_calls_with_function_spec(self):
  1042. def f(a, b, c, d=None):
  1043. pass
  1044. mock = Mock(spec=f)
  1045. mock(1, b=2, c=3)
  1046. mock(4, 5, c=6, d=7)
  1047. mock(10, 11, c=12)
  1048. calls = [
  1049. ('', (1, 2, 3), {}),
  1050. ('', (4, 5, 6), {'d': 7}),
  1051. ((10, 11, 12), {}),
  1052. ]
  1053. mock.assert_has_calls(calls)
  1054. mock.assert_has_calls(calls, any_order=True)
  1055. mock.assert_has_calls(calls[1:])
  1056. mock.assert_has_calls(calls[1:], any_order=True)
  1057. mock.assert_has_calls(calls[:-1])
  1058. mock.assert_has_calls(calls[:-1], any_order=True)
  1059. # Reversed order
  1060. calls = list(reversed(calls))
  1061. with self.assertRaises(AssertionError):
  1062. mock.assert_has_calls(calls)
  1063. mock.assert_has_calls(calls, any_order=True)
  1064. with self.assertRaises(AssertionError):
  1065. mock.assert_has_calls(calls[1:])
  1066. mock.assert_has_calls(calls[1:], any_order=True)
  1067. with self.assertRaises(AssertionError):
  1068. mock.assert_has_calls(calls[:-1])
  1069. mock.assert_has_calls(calls[:-1], any_order=True)
  1070. def test_assert_has_calls_not_matching_spec_error(self):
  1071. def f(x=None): pass
  1072. mock = Mock(spec=f)
  1073. mock(1)
  1074. with self.assertRaisesRegex(
  1075. AssertionError,
  1076. '^{}$'.format(
  1077. re.escape('Calls not found.\n'
  1078. 'Expected: [call()]\n'
  1079. 'Actual: [call(1)]'))) as cm:
  1080. mock.assert_has_calls([call()])
  1081. self.assertIsNone(cm.exception.__cause__)
  1082. with self.assertRaisesRegex(
  1083. AssertionError,
  1084. '^{}$'.format(
  1085. re.escape(
  1086. 'Error processing expected calls.\n'
  1087. "Errors: [None, TypeError('too many positional arguments')]\n"
  1088. "Expected: [call(), call(1, 2)]\n"
  1089. 'Actual: [call(1)]'))) as cm:
  1090. mock.assert_has_calls([call(), call(1, 2)])
  1091. self.assertIsInstance(cm.exception.__cause__, TypeError)
  1092. def test_assert_any_call(self):
  1093. mock = Mock()
  1094. mock(1, 2)
  1095. mock(a=3)
  1096. mock(1, b=6)
  1097. mock.assert_any_call(1, 2)
  1098. mock.assert_any_call(a=3)
  1099. mock.assert_any_call(1, b=6)
  1100. self.assertRaises(
  1101. AssertionError,
  1102. mock.assert_any_call
  1103. )
  1104. self.assertRaises(
  1105. AssertionError,
  1106. mock.assert_any_call,
  1107. 1, 3
  1108. )
  1109. self.assertRaises(
  1110. AssertionError,
  1111. mock.assert_any_call,
  1112. a=4
  1113. )
  1114. def test_assert_any_call_with_function_spec(self):
  1115. def f(a, b, c, d=None):
  1116. pass
  1117. mock = Mock(spec=f)
  1118. mock(1, b=2, c=3)
  1119. mock(4, 5, c=6, d=7)
  1120. mock.assert_any_call(1, 2, 3)
  1121. mock.assert_any_call(a=1, b=2, c=3)
  1122. mock.assert_any_call(4, 5, 6, 7)
  1123. mock.assert_any_call(a=4, b=5, c=6, d=7)
  1124. self.assertRaises(AssertionError, mock.assert_any_call,
  1125. 1, b=3, c=2)
  1126. # Expected call doesn't match the spec's signature
  1127. with self.assertRaises(AssertionError) as cm:
  1128. mock.assert_any_call(e=8)
  1129. self.assertIsInstance(cm.exception.__cause__, TypeError)
  1130. def test_mock_calls_create_autospec(self):
  1131. def f(a, b):
  1132. pass
  1133. obj = Iter()
  1134. obj.f = f
  1135. funcs = [
  1136. create_autospec(f),
  1137. create_autospec(obj).f
  1138. ]
  1139. for func in funcs:
  1140. func(1, 2)
  1141. func(3, 4)
  1142. self.assertEqual(
  1143. func.mock_calls, [call(1, 2), call(3, 4)]
  1144. )
  1145. #Issue21222
  1146. def test_create_autospec_with_name(self):
  1147. m = mock.create_autospec(object(), name='sweet_func')
  1148. self.assertIn('sweet_func', repr(m))
  1149. #Issue23078
  1150. def test_create_autospec_classmethod_and_staticmethod(self):
  1151. class TestClass:
  1152. @classmethod
  1153. def class_method(cls):
  1154. pass
  1155. @staticmethod
  1156. def static_method():
  1157. pass
  1158. for method in ('class_method', 'static_method'):
  1159. with self.subTest(method=method):
  1160. mock_method = mock.create_autospec(getattr(TestClass, method))
  1161. mock_method()
  1162. mock_method.assert_called_once_with()
  1163. self.assertRaises(TypeError, mock_method, 'extra_arg')
  1164. #Issue21238
  1165. def test_mock_unsafe(self):
  1166. m = Mock()
  1167. with self.assertRaises(AttributeError):
  1168. m.assert_foo_call()
  1169. with self.assertRaises(AttributeError):
  1170. m.assret_foo_call()
  1171. m = Mock(unsafe=True)
  1172. m.assert_foo_call()
  1173. m.assret_foo_call()
  1174. #Issue21262
  1175. def test_assert_not_called(self):
  1176. m = Mock()
  1177. m.hello.assert_not_called()
  1178. m.hello()
  1179. with self.assertRaises(AssertionError):
  1180. m.hello.assert_not_called()
  1181. def test_assert_called(self):
  1182. m = Mock()
  1183. with self.assertRaises(AssertionError):
  1184. m.hello.assert_called()
  1185. m.hello()
  1186. m.hello.assert_called()
  1187. m.hello()
  1188. m.hello.assert_called()
  1189. def test_assert_called_once(self):
  1190. m = Mock()
  1191. with self.assertRaises(AssertionError):
  1192. m.hello.assert_called_once()
  1193. m.hello()
  1194. m.hello.assert_called_once()
  1195. m.hello()
  1196. with self.assertRaises(AssertionError):
  1197. m.hello.assert_called_once()
  1198. #Issue21256 printout of keyword args should be in deterministic order
  1199. def test_sorted_call_signature(self):
  1200. m = Mock()
  1201. m.hello(name='hello', daddy='hero')
  1202. text = "call(daddy='hero', name='hello')"
  1203. self.assertEqual(repr(m.hello.call_args), text)
  1204. #Issue21270 overrides tuple methods for mock.call objects
  1205. def test_override_tuple_methods(self):
  1206. c = call.count()
  1207. i = call.index(132,'hello')
  1208. m = Mock()
  1209. m.count()
  1210. m.index(132,"hello")
  1211. self.assertEqual(m.method_calls[0], c)
  1212. self.assertEqual(m.method_calls[1], i)
  1213. def test_reset_return_sideeffect(self):
  1214. m = Mock(return_value=10, side_effect=[2,3])
  1215. m.reset_mock(return_value=True, side_effect=True)
  1216. self.assertIsInstance(m.return_value, Mock)
  1217. self.assertEqual(m.side_effect, None)
  1218. def test_reset_return(self):
  1219. m = Mock(return_value=10, side_effect=[2,3])
  1220. m.reset_mock(return_value=True)
  1221. self.assertIsInstance(m.return_value, Mock)
  1222. self.assertNotEqual(m.side_effect, None)
  1223. def test_reset_sideeffect(self):
  1224. m = Mock(return_value=10, side_effect=[2,3])
  1225. m.reset_mock(side_effect=True)
  1226. self.assertEqual(m.return_value, 10)
  1227. self.assertEqual(m.side_effect, None)
  1228. def test_mock_add_spec(self):
  1229. class _One(object):
  1230. one = 1
  1231. class _Two(object):
  1232. two = 2
  1233. class Anything(object):
  1234. one = two = three = 'four'
  1235. klasses = [
  1236. Mock, MagicMock, NonCallableMock, NonCallableMagicMock
  1237. ]
  1238. for Klass in list(klasses):
  1239. klasses.append(lambda K=Klass: K(spec=Anything))
  1240. klasses.append(lambda K=Klass: K(spec_set=Anything))
  1241. for Klass in klasses:
  1242. for kwargs in dict(), dict(spec_set=True):
  1243. mock = Klass()
  1244. #no error
  1245. mock.one, mock.two, mock.three
  1246. for One, Two in [(_One, _Two), (['one'], ['two'])]:
  1247. for kwargs in dict(), dict(spec_set=True):
  1248. mock.mock_add_spec(One, **kwargs)
  1249. mock.one
  1250. self.assertRaises(
  1251. AttributeError, getattr, mock, 'two'
  1252. )
  1253. self.assertRaises(
  1254. AttributeError, getattr, mock, 'three'
  1255. )
  1256. if 'spec_set' in kwargs:
  1257. self.assertRaises(
  1258. AttributeError, setattr, mock, 'three', None
  1259. )
  1260. mock.mock_add_spec(Two, **kwargs)
  1261. self.assertRaises(
  1262. AttributeError, getattr, mock, 'one'
  1263. )
  1264. mock.two
  1265. self.assertRaises(
  1266. AttributeError, getattr, mock, 'three'
  1267. )
  1268. if 'spec_set' in kwargs:
  1269. self.assertRaises(
  1270. AttributeError, setattr, mock, 'three', None
  1271. )
  1272. # note that creating a mock, setting an instance attribute, and
  1273. # *then* setting a spec doesn't work. Not the intended use case
  1274. def test_mock_add_spec_magic_methods(self):
  1275. for Klass in MagicMock, NonCallableMagicMock:
  1276. mock = Klass()
  1277. int(mock)
  1278. mock.mock_add_spec(object)
  1279. self.assertRaises(TypeError, int, mock)
  1280. mock = Klass()
  1281. mock['foo']
  1282. mock.__int__.return_value =4
  1283. mock.mock_add_spec(int)
  1284. self.assertEqual(int(mock), 4)
  1285. self.assertRaises(TypeError, lambda: mock['foo'])
  1286. def test_adding_child_mock(self):
  1287. for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
  1288. mock = Klass()
  1289. mock.foo = Mock()
  1290. mock.foo()
  1291. self.assertEqual(mock.method_calls, [call.foo()])
  1292. self.assertEqual(mock.mock_calls, [call.foo()])
  1293. mock = Klass()
  1294. mock.bar = Mock(name='name')
  1295. mock.bar()
  1296. self.assertEqual(mock.method_calls, [])
  1297. self.assertEqual(mock.mock_calls, [])
  1298. # mock with an existing _new_parent but no name
  1299. mock = Klass()
  1300. mock.baz = MagicMock()()
  1301. mock.baz()
  1302. self.assertEqual(mock.method_calls, [])
  1303. self.assertEqual(mock.mock_calls, [])
  1304. def test_adding_return_value_mock(self):
  1305. for Klass in Mock, MagicMock:
  1306. mock = Klass()
  1307. mock.return_value = MagicMock()
  1308. mock()()
  1309. self.assertEqual(mock.mock_calls, [call(), call()()])
  1310. def test_manager_mock(self):
  1311. class Foo(object):
  1312. one = 'one'
  1313. two = 'two'
  1314. manager = Mock()
  1315. p1 = patch.object(Foo, 'one')
  1316. p2 = patch.object(Foo, 'two')
  1317. mock_one = p1.start()
  1318. self.addCleanup(p1.stop)
  1319. mock_two = p2.start()
  1320. self.addCleanup(p2.stop)
  1321. manager.attach_mock(mock_one, 'one')
  1322. manager.attach_mock(mock_two, 'two')
  1323. Foo.two()
  1324. Foo.one()
  1325. self.assertEqual(manager.mock_calls, [call.two(), call.one()])
  1326. def test_magic_methods_mock_calls(self):
  1327. for Klass in Mock, MagicMock:
  1328. m = Klass()
  1329. m.__int__ = Mock(return_value=3)
  1330. m.__float__ = MagicMock(return_value=3.0)
  1331. int(m)
  1332. float(m)
  1333. self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
  1334. self.assertEqual(m.method_calls, [])
  1335. def test_mock_open_reuse_issue_21750(self):
  1336. mocked_open = mock.mock_open(read_data='data')
  1337. f1 = mocked_open('a-name')
  1338. f1_data = f1.read()
  1339. f2 = mocked_open('another-name')
  1340. f2_data = f2.read()
  1341. self.assertEqual(f1_data, f2_data)
  1342. def test_mock_open_dunder_iter_issue(self):
  1343. # Test dunder_iter method generates the expected result and
  1344. # consumes the iterator.
  1345. mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
  1346. f1 = mocked_open('a-name')
  1347. lines = [line for line in f1]
  1348. self.assertEqual(lines[0], 'Remarkable\n')
  1349. self.assertEqual(lines[1], 'Norwegian Blue')
  1350. self.assertEqual(list(f1), [])
  1351. def test_mock_open_using_next(self):
  1352. mocked_open = mock.mock_open(read_data='1st line\n2nd line\n3rd line')
  1353. f1 = mocked_open('a-name')
  1354. line1 = next(f1)
  1355. line2 = f1.__next__()
  1356. lines = [line for line in f1]
  1357. self.assertEqual(line1, '1st line\n')
  1358. self.assertEqual(line2, '2nd line\n')
  1359. self.assertEqual(lines[0], '3rd line')
  1360. self.assertEqual(list(f1), [])
  1361. with self.assertRaises(StopIteration):
  1362. next(f1)
  1363. def test_mock_open_write(self):
  1364. # Test exception in file writing write()
  1365. mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
  1366. with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
  1367. mock_filehandle = mock_namedtemp.return_value
  1368. mock_write = mock_filehandle.write
  1369. mock_write.side_effect = OSError('Test 2 Error')
  1370. def attempt():
  1371. tempfile.NamedTemporaryFile().write('asd')
  1372. self.assertRaises(OSError, attempt)
  1373. def test_mock_open_alter_readline(self):
  1374. mopen = mock.mock_open(read_data='foo\nbarn')
  1375. mopen.return_value.readline.side_effect = lambda *args:'abc'
  1376. first = mopen().readline()
  1377. second = mopen().readline()
  1378. self.assertEqual('abc', first)
  1379. self.assertEqual('abc', second)
  1380. def test_mock_open_after_eof(self):
  1381. # read, readline and readlines should work after end of file.
  1382. _open = mock.mock_open(read_data='foo')
  1383. h = _open('bar')
  1384. h.read()
  1385. self.assertEqual('', h.read())
  1386. self.assertEqual('', h.read())
  1387. self.assertEqual('', h.readline())
  1388. self.assertEqual('', h.readline())
  1389. self.assertEqual([], h.readlines())
  1390. self.assertEqual([], h.readlines())
  1391. def test_mock_parents(self):
  1392. for Klass in Mock, MagicMock:
  1393. m = Klass()
  1394. original_repr = repr(m)
  1395. m.return_value = m
  1396. self.assertIs(m(), m)
  1397. self.assertEqual(repr(m), original_repr)
  1398. m.reset_mock()
  1399. self.assertIs(m(), m)
  1400. self.assertEqual(repr(m), original_repr)
  1401. m = Klass()
  1402. m.b = m.a
  1403. self.assertIn("name='mock.a'", repr(m.b))
  1404. self.assertIn("name='mock.a'", repr(m.a))
  1405. m.reset_mock()
  1406. self.assertIn("name='mock.a'", repr(m.b))
  1407. self.assertIn("name='mock.a'", repr(m.a))
  1408. m = Klass()
  1409. original_repr = repr(m)
  1410. m.a = m()
  1411. m.a.return_value = m
  1412. self.assertEqual(repr(m), original_repr)
  1413. self.assertEqual(repr(m.a()), original_repr)
  1414. def test_attach_mock(self):
  1415. classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
  1416. for Klass in classes:
  1417. for Klass2 in classes:
  1418. m = Klass()
  1419. m2 = Klass2(name='foo')
  1420. m.attach_mock(m2, 'bar')
  1421. self.assertIs(m.bar, m2)
  1422. self.assertIn("name='mock.bar'", repr(m2))
  1423. m.bar.baz(1)
  1424. self.assertEqual(m.mock_calls, [call.bar.baz(1)])
  1425. self.assertEqual(m.method_calls, [call.bar.baz(1)])
  1426. def test_attach_mock_return_value(self):
  1427. classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
  1428. for Klass in Mock, MagicMock:
  1429. for Klass2 in classes:
  1430. m = Klass()
  1431. m2 = Klass2(name='foo')
  1432. m.attach_mock(m2, 'return_value')
  1433. self.assertIs(m(), m2)
  1434. self.assertIn("name='mock()'", repr(m2))
  1435. m2.foo()
  1436. self.assertEqual(m.mock_calls, call().foo().call_list())
  1437. def test_attach_mock_patch_autospec(self):
  1438. parent = Mock()
  1439. with mock.patch(f'{__name__}.something', autospec=True) as mock_func:
  1440. self.assertEqual(mock_func.mock._extract_mock_name(), 'something')
  1441. parent.attach_mock(mock_func, 'child')
  1442. parent.child(1)
  1443. something(2)
  1444. mock_func(3)
  1445. parent_calls = [call.child(1), call.child(2), call.child(3)]
  1446. child_calls = [call(1), call(2), call(3)]
  1447. self.assertEqual(parent.mock_calls, parent_calls)
  1448. self.assertEqual(parent.child.mock_calls, child_calls)
  1449. self.assertEqual(something.mock_calls, child_calls)
  1450. self.assertEqual(mock_func.mock_calls, child_calls)
  1451. self.assertIn('mock.child', repr(parent.child.mock))
  1452. self.assertEqual(mock_func.mock._extract_mock_name(), 'mock.child')
  1453. def test_attach_mock_patch_autospec_signature(self):
  1454. with mock.patch(f'{__name__}.Something.meth', autospec=True) as mocked:
  1455. manager = Mock()
  1456. manager.attach_mock(mocked, 'attach_meth')
  1457. obj = Something()
  1458. obj.meth(1, 2, 3, d=4)
  1459. manager.assert_has_calls([call.attach_meth(mock.ANY, 1, 2, 3, d=4)])
  1460. obj.meth.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)])
  1461. mocked.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)])
  1462. with mock.patch(f'{__name__}.something', autospec=True) as mocked:
  1463. manager = Mock()
  1464. manager.attach_mock(mocked, 'attach_func')
  1465. something(1)
  1466. manager.assert_has_calls([call.attach_func(1)])
  1467. something.assert_has_calls([call(1)])
  1468. mocked.assert_has_calls([call(1)])
  1469. with mock.patch(f'{__name__}.Something', autospec=True) as mocked:
  1470. manager = Mock()
  1471. manager.attach_mock(mocked, 'attach_obj')
  1472. obj = Something()
  1473. obj.meth(1, 2, 3, d=4)
  1474. manager.assert_has_calls([call.attach_obj(),
  1475. call.attach_obj().meth(1, 2, 3, d=4)])
  1476. obj.meth.assert_has_calls([call(1, 2, 3, d=4)])
  1477. mocked.assert_has_calls([call(), call().meth(1, 2, 3, d=4)])
  1478. def test_attribute_deletion(self):
  1479. for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
  1480. NonCallableMock()):
  1481. self.assertTrue(hasattr(mock, 'm'))
  1482. del mock.m
  1483. self.assertFalse(hasattr(mock, 'm'))
  1484. del mock.f
  1485. self.assertFalse(hasattr(mock, 'f'))
  1486. self.assertRaises(AttributeError, getattr, mock, 'f')
  1487. def test_mock_does_not_raise_on_repeated_attribute_deletion(self):
  1488. # bpo-20239: Assigning and deleting twice an attribute raises.
  1489. for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
  1490. NonCallableMock()):
  1491. mock.foo = 3
  1492. self.assertTrue(hasattr(mock, 'foo'))
  1493. self.assertEqual(mock.foo, 3)
  1494. del mock.foo
  1495. self.assertFalse(hasattr(mock, 'foo'))
  1496. mock.foo = 4
  1497. self.assertTrue(hasattr(mock, 'foo'))
  1498. self.assertEqual(mock.foo, 4)
  1499. del mock.foo
  1500. self.assertFalse(hasattr(mock, 'foo'))
  1501. def test_mock_raises_when_deleting_nonexistent_attribute(self):
  1502. for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
  1503. NonCallableMock()):
  1504. del mock.foo
  1505. with self.assertRaises(AttributeError):
  1506. del mock.foo
  1507. def test_reset_mock_does_not_raise_on_attr_deletion(self):
  1508. # bpo-31177: reset_mock should not raise AttributeError when attributes
  1509. # were deleted in a mock instance
  1510. mock = Mock()
  1511. mock.child = True
  1512. del mock.child
  1513. mock.reset_mock()
  1514. self.assertFalse(hasattr(mock, 'child'))
  1515. def test_class_assignable(self):
  1516. for mock in Mock(), MagicMock():
  1517. self.assertNotIsInstance(mock, int)
  1518. mock.__class__ = int
  1519. self.assertIsInstance(mock, int)
  1520. mock.foo
  1521. def test_name_attribute_of_call(self):
  1522. # bpo-35357: _Call should not disclose any attributes whose names
  1523. # may clash with popular ones (such as ".name")
  1524. self.assertIsNotNone(call.name)
  1525. self.assertEqual(type(call.name), _Call)
  1526. self.assertEqual(type(call.name().name), _Call)
  1527. def test_parent_attribute_of_call(self):
  1528. # bpo-35357: _Call should not disclose any attributes whose names
  1529. # may clash with popular ones (such as ".parent")
  1530. self.assertIsNotNone(call.parent)
  1531. self.assertEqual(type(call.parent), _Call)
  1532. self.assertEqual(type(call.parent().parent), _Call)
  1533. def test_parent_propagation_with_create_autospec(self):
  1534. def foo(a, b):
  1535. pass
  1536. mock = Mock()
  1537. mock.child = create_autospec(foo)
  1538. mock.child(1, 2)
  1539. self.assertRaises(TypeError, mock.child, 1)
  1540. self.assertEqual(mock.mock_calls, [call.child(1, 2)])
  1541. self.assertIn('mock.child', repr(mock.child.mock))
  1542. def test_parent_propagation_with_autospec_attach_mock(self):
  1543. def foo(a, b): pass
  1544. parent = Mock()
  1545. parent.attach_mock(create_autospec(foo, name='bar'), 'child')
  1546. parent.child(1, 2)
  1547. self.assertRaises(TypeError, parent.child, 1)
  1548. self.assertEqual(parent.child.mock_calls, [call.child(1, 2)])
  1549. self.assertIn('mock.child', repr(parent.child.mock))
  1550. def test_isinstance_under_settrace(self):
  1551. # bpo-36593 : __class__ is not set for a class that has __class__
  1552. # property defined when it's used with sys.settrace(trace) set.
  1553. # Delete the module to force reimport with tracing function set
  1554. # restore the old reference later since there are other tests that are
  1555. # dependent on unittest.mock.patch. In testpatch.PatchTest
  1556. # test_patch_dict_test_prefix and test_patch_test_prefix not restoring
  1557. # causes the objects patched to go out of sync
  1558. old_patch = unittest.mock.patch
  1559. # Directly using __setattr__ on unittest.mock causes current imported
  1560. # reference to be updated. Use a lambda so that during cleanup the
  1561. # re-imported new reference is updated.
  1562. self.addCleanup(lambda patch: setattr(unittest.mock, 'patch', patch),
  1563. old_patch)
  1564. with patch.dict('sys.modules'):
  1565. del sys.modules['unittest.mock']
  1566. def trace(frame, event, arg):
  1567. return trace
  1568. sys.settrace(trace)
  1569. self.addCleanup(sys.settrace, None)
  1570. from unittest.mock import (
  1571. Mock, MagicMock, NonCallableMock, NonCallableMagicMock
  1572. )
  1573. mocks = [
  1574. Mock, MagicMock, NonCallableMock, NonCallableMagicMock
  1575. ]
  1576. for mock in mocks:
  1577. obj = mock(spec=Something)
  1578. self.assertIsInstance(obj, Something)
  1579. if __name__ == '__main__':
  1580. unittest.main()