testmock.py 75 KB

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