testmock.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. import copy
  2. import sys
  3. import tempfile
  4. import unittest
  5. from unittest.test.testmock.support import is_instance
  6. from unittest import mock
  7. from unittest.mock import (
  8. call, DEFAULT, patch, sentinel,
  9. MagicMock, Mock, NonCallableMock,
  10. NonCallableMagicMock, _CallList,
  11. create_autospec
  12. )
  13. class Iter(object):
  14. def __init__(self):
  15. self.thing = iter(['this', 'is', 'an', 'iter'])
  16. def __iter__(self):
  17. return self
  18. def next(self):
  19. return next(self.thing)
  20. __next__ = next
  21. class Something(object):
  22. def meth(self, a, b, c, d=None):
  23. pass
  24. @classmethod
  25. def cmeth(cls, a, b, c, d=None):
  26. pass
  27. @staticmethod
  28. def smeth(a, b, c, d=None):
  29. pass
  30. class MockTest(unittest.TestCase):
  31. def test_all(self):
  32. # if __all__ is badly defined then import * will raise an error
  33. # We have to exec it because you can't import * inside a method
  34. # in Python 3
  35. exec("from unittest.mock import *")
  36. def test_constructor(self):
  37. mock = Mock()
  38. self.assertFalse(mock.called, "called not initialised correctly")
  39. self.assertEqual(mock.call_count, 0,
  40. "call_count not initialised correctly")
  41. self.assertTrue(is_instance(mock.return_value, Mock),
  42. "return_value not initialised correctly")
  43. self.assertEqual(mock.call_args, None,
  44. "call_args not initialised correctly")
  45. self.assertEqual(mock.call_args_list, [],
  46. "call_args_list not initialised correctly")
  47. self.assertEqual(mock.method_calls, [],
  48. "method_calls not initialised correctly")
  49. # Can't use hasattr for this test as it always returns True on a mock
  50. self.assertNotIn('_items', mock.__dict__,
  51. "default mock should not have '_items' attribute")
  52. self.assertIsNone(mock._mock_parent,
  53. "parent not initialised correctly")
  54. self.assertIsNone(mock._mock_methods,
  55. "methods not initialised correctly")
  56. self.assertEqual(mock._mock_children, {},
  57. "children not initialised incorrectly")
  58. def test_return_value_in_constructor(self):
  59. mock = Mock(return_value=None)
  60. self.assertIsNone(mock.return_value,
  61. "return value in constructor not honoured")
  62. def test_repr(self):
  63. mock = Mock(name='foo')
  64. self.assertIn('foo', repr(mock))
  65. self.assertIn("'%s'" % id(mock), repr(mock))
  66. mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
  67. for mock, name in mocks:
  68. self.assertIn('%s.bar' % name, repr(mock.bar))
  69. self.assertIn('%s.foo()' % name, repr(mock.foo()))
  70. self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
  71. self.assertIn('%s()' % name, repr(mock()))
  72. self.assertIn('%s()()' % name, repr(mock()()))
  73. self.assertIn('%s()().foo.bar.baz().bing' % name,
  74. repr(mock()().foo.bar.baz().bing))
  75. def test_repr_with_spec(self):
  76. class X(object):
  77. pass
  78. mock = Mock(spec=X)
  79. self.assertIn(" spec='X' ", repr(mock))
  80. mock = Mock(spec=X())
  81. self.assertIn(" spec='X' ", repr(mock))
  82. mock = Mock(spec_set=X)
  83. self.assertIn(" spec_set='X' ", repr(mock))
  84. mock = Mock(spec_set=X())
  85. self.assertIn(" spec_set='X' ", repr(mock))
  86. mock = Mock(spec=X, name='foo')
  87. self.assertIn(" spec='X' ", repr(mock))
  88. self.assertIn(" name='foo' ", repr(mock))
  89. mock = Mock(name='foo')
  90. self.assertNotIn("spec", repr(mock))
  91. mock = Mock()
  92. self.assertNotIn("spec", repr(mock))
  93. mock = Mock(spec=['foo'])
  94. self.assertNotIn("spec", repr(mock))
  95. def test_side_effect(self):
  96. mock = Mock()
  97. def effect(*args, **kwargs):
  98. raise SystemError('kablooie')
  99. mock.side_effect = effect
  100. self.assertRaises(SystemError, mock, 1, 2, fish=3)
  101. mock.assert_called_with(1, 2, fish=3)
  102. results = [1, 2, 3]
  103. def effect():
  104. return results.pop()
  105. mock.side_effect = effect
  106. self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
  107. "side effect not used correctly")
  108. mock = Mock(side_effect=sentinel.SideEffect)
  109. self.assertEqual(mock.side_effect, sentinel.SideEffect,
  110. "side effect in constructor not used")
  111. def side_effect():
  112. return DEFAULT
  113. mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
  114. self.assertEqual(mock(), sentinel.RETURN)
  115. def test_autospec_side_effect(self):
  116. # Test for issue17826
  117. results = [1, 2, 3]
  118. def effect():
  119. return results.pop()
  120. def f():
  121. pass
  122. mock = create_autospec(f)
  123. mock.side_effect = [1, 2, 3]
  124. self.assertEqual([mock(), mock(), mock()], [1, 2, 3],
  125. "side effect not used correctly in create_autospec")
  126. # Test where side effect is a callable
  127. results = [1, 2, 3]
  128. mock = create_autospec(f)
  129. mock.side_effect = effect
  130. self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
  131. "callable side effect not used correctly")
  132. def test_autospec_side_effect_exception(self):
  133. # Test for issue 23661
  134. def f():
  135. pass
  136. mock = create_autospec(f)
  137. mock.side_effect = ValueError('Bazinga!')
  138. self.assertRaisesRegex(ValueError, 'Bazinga!', mock)
  139. @unittest.skipUnless('java' in sys.platform,
  140. 'This test only applies to Jython')
  141. def test_java_exception_side_effect(self):
  142. import java
  143. mock = Mock(side_effect=java.lang.RuntimeException("Boom!"))
  144. # can't use assertRaises with java exceptions
  145. try:
  146. mock(1, 2, fish=3)
  147. except java.lang.RuntimeException:
  148. pass
  149. else:
  150. self.fail('java exception not raised')
  151. mock.assert_called_with(1,2, fish=3)
  152. def test_reset_mock(self):
  153. parent = Mock()
  154. spec = ["something"]
  155. mock = Mock(name="child", parent=parent, spec=spec)
  156. mock(sentinel.Something, something=sentinel.SomethingElse)
  157. something = mock.something
  158. mock.something()
  159. mock.side_effect = sentinel.SideEffect
  160. return_value = mock.return_value
  161. return_value()
  162. mock.reset_mock()
  163. self.assertEqual(mock._mock_name, "child",
  164. "name incorrectly reset")
  165. self.assertEqual(mock._mock_parent, parent,
  166. "parent incorrectly reset")
  167. self.assertEqual(mock._mock_methods, spec,
  168. "methods incorrectly reset")
  169. self.assertFalse(mock.called, "called not reset")
  170. self.assertEqual(mock.call_count, 0, "call_count not reset")
  171. self.assertEqual(mock.call_args, None, "call_args not reset")
  172. self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
  173. self.assertEqual(mock.method_calls, [],
  174. "method_calls not initialised correctly: %r != %r" %
  175. (mock.method_calls, []))
  176. self.assertEqual(mock.mock_calls, [])
  177. self.assertEqual(mock.side_effect, sentinel.SideEffect,
  178. "side_effect incorrectly reset")
  179. self.assertEqual(mock.return_value, return_value,
  180. "return_value incorrectly reset")
  181. self.assertFalse(return_value.called, "return value mock not reset")
  182. self.assertEqual(mock._mock_children, {'something': something},
  183. "children reset incorrectly")
  184. self.assertEqual(mock.something, something,
  185. "children incorrectly cleared")
  186. self.assertFalse(mock.something.called, "child not reset")
  187. def test_reset_mock_recursion(self):
  188. mock = Mock()
  189. mock.return_value = mock
  190. # used to cause recursion
  191. mock.reset_mock()
  192. def test_reset_mock_on_mock_open_issue_18622(self):
  193. a = mock.mock_open()
  194. a.reset_mock()
  195. def test_call(self):
  196. mock = Mock()
  197. self.assertTrue(is_instance(mock.return_value, Mock),
  198. "Default return_value should be a Mock")
  199. result = mock()
  200. self.assertEqual(mock(), result,
  201. "different result from consecutive calls")
  202. mock.reset_mock()
  203. ret_val = mock(sentinel.Arg)
  204. self.assertTrue(mock.called, "called not set")
  205. self.assertEqual(mock.call_count, 1, "call_count incoreect")
  206. self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
  207. "call_args not set")
  208. self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
  209. "call_args_list not initialised correctly")
  210. mock.return_value = sentinel.ReturnValue
  211. ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
  212. self.assertEqual(ret_val, sentinel.ReturnValue,
  213. "incorrect return value")
  214. self.assertEqual(mock.call_count, 2, "call_count incorrect")
  215. self.assertEqual(mock.call_args,
  216. ((sentinel.Arg,), {'key': sentinel.KeyArg}),
  217. "call_args not set")
  218. self.assertEqual(mock.call_args_list, [
  219. ((sentinel.Arg,), {}),
  220. ((sentinel.Arg,), {'key': sentinel.KeyArg})
  221. ],
  222. "call_args_list not set")
  223. def test_call_args_comparison(self):
  224. mock = Mock()
  225. mock()
  226. mock(sentinel.Arg)
  227. mock(kw=sentinel.Kwarg)
  228. mock(sentinel.Arg, kw=sentinel.Kwarg)
  229. self.assertEqual(mock.call_args_list, [
  230. (),
  231. ((sentinel.Arg,),),
  232. ({"kw": sentinel.Kwarg},),
  233. ((sentinel.Arg,), {"kw": sentinel.Kwarg})
  234. ])
  235. self.assertEqual(mock.call_args,
  236. ((sentinel.Arg,), {"kw": sentinel.Kwarg}))
  237. # Comparing call_args to a long sequence should not raise
  238. # an exception. See issue 24857.
  239. self.assertFalse(mock.call_args == "a long sequence")
  240. def test_calls_equal_with_any(self):
  241. call1 = mock.call(mock.MagicMock())
  242. call2 = mock.call(mock.ANY)
  243. # Check that equality and non-equality is consistent even when
  244. # comparing with mock.ANY
  245. self.assertTrue(call1 == call2)
  246. self.assertFalse(call1 != call2)
  247. def test_assert_called_with(self):
  248. mock = Mock()
  249. mock()
  250. # Will raise an exception if it fails
  251. mock.assert_called_with()
  252. self.assertRaises(AssertionError, mock.assert_called_with, 1)
  253. mock.reset_mock()
  254. self.assertRaises(AssertionError, mock.assert_called_with)
  255. mock(1, 2, 3, a='fish', b='nothing')
  256. mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
  257. def test_assert_called_with_any(self):
  258. m = MagicMock()
  259. m(MagicMock())
  260. m.assert_called_with(mock.ANY)
  261. def test_assert_called_with_function_spec(self):
  262. def f(a, b, c, d=None):
  263. pass
  264. mock = Mock(spec=f)
  265. mock(1, b=2, c=3)
  266. mock.assert_called_with(1, 2, 3)
  267. mock.assert_called_with(a=1, b=2, c=3)
  268. self.assertRaises(AssertionError, mock.assert_called_with,
  269. 1, b=3, c=2)
  270. # Expected call doesn't match the spec's signature
  271. with self.assertRaises(AssertionError) as cm:
  272. mock.assert_called_with(e=8)
  273. self.assertIsInstance(cm.exception.__cause__, TypeError)
  274. def test_assert_called_with_method_spec(self):
  275. def _check(mock):
  276. mock(1, b=2, c=3)
  277. mock.assert_called_with(1, 2, 3)
  278. mock.assert_called_with(a=1, b=2, c=3)
  279. self.assertRaises(AssertionError, mock.assert_called_with,
  280. 1, b=3, c=2)
  281. mock = Mock(spec=Something().meth)
  282. _check(mock)
  283. mock = Mock(spec=Something.cmeth)
  284. _check(mock)
  285. mock = Mock(spec=Something().cmeth)
  286. _check(mock)
  287. mock = Mock(spec=Something.smeth)
  288. _check(mock)
  289. mock = Mock(spec=Something().smeth)
  290. _check(mock)
  291. def test_assert_called_once_with(self):
  292. mock = Mock()
  293. mock()
  294. # Will raise an exception if it fails
  295. mock.assert_called_once_with()
  296. mock()
  297. self.assertRaises(AssertionError, mock.assert_called_once_with)
  298. mock.reset_mock()
  299. self.assertRaises(AssertionError, mock.assert_called_once_with)
  300. mock('foo', 'bar', baz=2)
  301. mock.assert_called_once_with('foo', 'bar', baz=2)
  302. mock.reset_mock()
  303. mock('foo', 'bar', baz=2)
  304. self.assertRaises(
  305. AssertionError,
  306. lambda: mock.assert_called_once_with('bob', 'bar', baz=2)
  307. )
  308. def test_assert_called_once_with_function_spec(self):
  309. def f(a, b, c, d=None):
  310. pass
  311. mock = Mock(spec=f)
  312. mock(1, b=2, c=3)
  313. mock.assert_called_once_with(1, 2, 3)
  314. mock.assert_called_once_with(a=1, b=2, c=3)
  315. self.assertRaises(AssertionError, mock.assert_called_once_with,
  316. 1, b=3, c=2)
  317. # Expected call doesn't match the spec's signature
  318. with self.assertRaises(AssertionError) as cm:
  319. mock.assert_called_once_with(e=8)
  320. self.assertIsInstance(cm.exception.__cause__, TypeError)
  321. # Mock called more than once => always fails
  322. mock(4, 5, 6)
  323. self.assertRaises(AssertionError, mock.assert_called_once_with,
  324. 1, 2, 3)
  325. self.assertRaises(AssertionError, mock.assert_called_once_with,
  326. 4, 5, 6)
  327. def test_attribute_access_returns_mocks(self):
  328. mock = Mock()
  329. something = mock.something
  330. self.assertTrue(is_instance(something, Mock), "attribute isn't a mock")
  331. self.assertEqual(mock.something, something,
  332. "different attributes returned for same name")
  333. # Usage example
  334. mock = Mock()
  335. mock.something.return_value = 3
  336. self.assertEqual(mock.something(), 3, "method returned wrong value")
  337. self.assertTrue(mock.something.called,
  338. "method didn't record being called")
  339. def test_attributes_have_name_and_parent_set(self):
  340. mock = Mock()
  341. something = mock.something
  342. self.assertEqual(something._mock_name, "something",
  343. "attribute name not set correctly")
  344. self.assertEqual(something._mock_parent, mock,
  345. "attribute parent not set correctly")
  346. def test_method_calls_recorded(self):
  347. mock = Mock()
  348. mock.something(3, fish=None)
  349. mock.something_else.something(6, cake=sentinel.Cake)
  350. self.assertEqual(mock.something_else.method_calls,
  351. [("something", (6,), {'cake': sentinel.Cake})],
  352. "method calls not recorded correctly")
  353. self.assertEqual(mock.method_calls, [
  354. ("something", (3,), {'fish': None}),
  355. ("something_else.something", (6,), {'cake': sentinel.Cake})
  356. ],
  357. "method calls not recorded correctly")
  358. def test_method_calls_compare_easily(self):
  359. mock = Mock()
  360. mock.something()
  361. self.assertEqual(mock.method_calls, [('something',)])
  362. self.assertEqual(mock.method_calls, [('something', (), {})])
  363. mock = Mock()
  364. mock.something('different')
  365. self.assertEqual(mock.method_calls, [('something', ('different',))])
  366. self.assertEqual(mock.method_calls,
  367. [('something', ('different',), {})])
  368. mock = Mock()
  369. mock.something(x=1)
  370. self.assertEqual(mock.method_calls, [('something', {'x': 1})])
  371. self.assertEqual(mock.method_calls, [('something', (), {'x': 1})])
  372. mock = Mock()
  373. mock.something('different', some='more')
  374. self.assertEqual(mock.method_calls, [
  375. ('something', ('different',), {'some': 'more'})
  376. ])
  377. def test_only_allowed_methods_exist(self):
  378. for spec in ['something'], ('something',):
  379. for arg in 'spec', 'spec_set':
  380. mock = Mock(**{arg: spec})
  381. # this should be allowed
  382. mock.something
  383. self.assertRaisesRegex(
  384. AttributeError,
  385. "Mock object has no attribute 'something_else'",
  386. getattr, mock, 'something_else'
  387. )
  388. def test_from_spec(self):
  389. class Something(object):
  390. x = 3
  391. __something__ = None
  392. def y(self):
  393. pass
  394. def test_attributes(mock):
  395. # should work
  396. mock.x
  397. mock.y
  398. mock.__something__
  399. self.assertRaisesRegex(
  400. AttributeError,
  401. "Mock object has no attribute 'z'",
  402. getattr, mock, 'z'
  403. )
  404. self.assertRaisesRegex(
  405. AttributeError,
  406. "Mock object has no attribute '__foobar__'",
  407. getattr, mock, '__foobar__'
  408. )
  409. test_attributes(Mock(spec=Something))
  410. test_attributes(Mock(spec=Something()))
  411. def test_wraps_calls(self):
  412. real = Mock()
  413. mock = Mock(wraps=real)
  414. self.assertEqual(mock(), real())
  415. real.reset_mock()
  416. mock(1, 2, fish=3)
  417. real.assert_called_with(1, 2, fish=3)
  418. def test_wraps_call_with_nondefault_return_value(self):
  419. real = Mock()
  420. mock = Mock(wraps=real)
  421. mock.return_value = 3
  422. self.assertEqual(mock(), 3)
  423. self.assertFalse(real.called)
  424. def test_wraps_attributes(self):
  425. class Real(object):
  426. attribute = Mock()
  427. real = Real()
  428. mock = Mock(wraps=real)
  429. self.assertEqual(mock.attribute(), real.attribute())
  430. self.assertRaises(AttributeError, lambda: mock.fish)
  431. self.assertNotEqual(mock.attribute, real.attribute)
  432. result = mock.attribute.frog(1, 2, fish=3)
  433. Real.attribute.frog.assert_called_with(1, 2, fish=3)
  434. self.assertEqual(result, Real.attribute.frog())
  435. def test_exceptional_side_effect(self):
  436. mock = Mock(side_effect=AttributeError)
  437. self.assertRaises(AttributeError, mock)
  438. mock = Mock(side_effect=AttributeError('foo'))
  439. self.assertRaises(AttributeError, mock)
  440. def test_baseexceptional_side_effect(self):
  441. mock = Mock(side_effect=KeyboardInterrupt)
  442. self.assertRaises(KeyboardInterrupt, mock)
  443. mock = Mock(side_effect=KeyboardInterrupt('foo'))
  444. self.assertRaises(KeyboardInterrupt, mock)
  445. def test_assert_called_with_message(self):
  446. mock = Mock()
  447. self.assertRaisesRegex(AssertionError, 'Not called',
  448. mock.assert_called_with)
  449. def test_assert_called_once_with_message(self):
  450. mock = Mock(name='geoffrey')
  451. self.assertRaisesRegex(AssertionError,
  452. r"Expected 'geoffrey' to be called once\.",
  453. mock.assert_called_once_with)
  454. def test__name__(self):
  455. mock = Mock()
  456. self.assertRaises(AttributeError, lambda: mock.__name__)
  457. mock.__name__ = 'foo'
  458. self.assertEqual(mock.__name__, 'foo')
  459. def test_spec_list_subclass(self):
  460. class Sub(list):
  461. pass
  462. mock = Mock(spec=Sub(['foo']))
  463. mock.append(3)
  464. mock.append.assert_called_with(3)
  465. self.assertRaises(AttributeError, getattr, mock, 'foo')
  466. def test_spec_class(self):
  467. class X(object):
  468. pass
  469. mock = Mock(spec=X)
  470. self.assertIsInstance(mock, X)
  471. mock = Mock(spec=X())
  472. self.assertIsInstance(mock, X)
  473. self.assertIs(mock.__class__, X)
  474. self.assertEqual(Mock().__class__.__name__, 'Mock')
  475. mock = Mock(spec_set=X)
  476. self.assertIsInstance(mock, X)
  477. mock = Mock(spec_set=X())
  478. self.assertIsInstance(mock, X)
  479. def test_setting_attribute_with_spec_set(self):
  480. class X(object):
  481. y = 3
  482. mock = Mock(spec=X)
  483. mock.x = 'foo'
  484. mock = Mock(spec_set=X)
  485. def set_attr():
  486. mock.x = 'foo'
  487. mock.y = 'foo'
  488. self.assertRaises(AttributeError, set_attr)
  489. def test_copy(self):
  490. current = sys.getrecursionlimit()
  491. self.addCleanup(sys.setrecursionlimit, current)
  492. # can't use sys.maxint as this doesn't exist in Python 3
  493. sys.setrecursionlimit(int(10e8))
  494. # this segfaults without the fix in place
  495. copy.copy(Mock())
  496. def test_subclass_with_properties(self):
  497. class SubClass(Mock):
  498. def _get(self):
  499. return 3
  500. def _set(self, value):
  501. raise NameError('strange error')
  502. some_attribute = property(_get, _set)
  503. s = SubClass(spec_set=SubClass)
  504. self.assertEqual(s.some_attribute, 3)
  505. def test():
  506. s.some_attribute = 3
  507. self.assertRaises(NameError, test)
  508. def test():
  509. s.foo = 'bar'
  510. self.assertRaises(AttributeError, test)
  511. def test_setting_call(self):
  512. mock = Mock()
  513. def __call__(self, a):
  514. return self._mock_call(a)
  515. type(mock).__call__ = __call__
  516. mock('one')
  517. mock.assert_called_with('one')
  518. self.assertRaises(TypeError, mock, 'one', 'two')
  519. def test_dir(self):
  520. mock = Mock()
  521. attrs = set(dir(mock))
  522. type_attrs = set([m for m in dir(Mock) if not m.startswith('_')])
  523. # all public attributes from the type are included
  524. self.assertEqual(set(), type_attrs - attrs)
  525. # creates these attributes
  526. mock.a, mock.b
  527. self.assertIn('a', dir(mock))
  528. self.assertIn('b', dir(mock))
  529. # instance attributes
  530. mock.c = mock.d = None
  531. self.assertIn('c', dir(mock))
  532. self.assertIn('d', dir(mock))
  533. # magic methods
  534. mock.__iter__ = lambda s: iter([])
  535. self.assertIn('__iter__', dir(mock))
  536. def test_dir_from_spec(self):
  537. mock = Mock(spec=unittest.TestCase)
  538. testcase_attrs = set(dir(unittest.TestCase))
  539. attrs = set(dir(mock))
  540. # all attributes from the spec are included
  541. self.assertEqual(set(), testcase_attrs - attrs)
  542. # shadow a sys attribute
  543. mock.version = 3
  544. self.assertEqual(dir(mock).count('version'), 1)
  545. def test_filter_dir(self):
  546. patcher = patch.object(mock, 'FILTER_DIR', False)
  547. patcher.start()
  548. try:
  549. attrs = set(dir(Mock()))
  550. type_attrs = set(dir(Mock))
  551. # ALL attributes from the type are included
  552. self.assertEqual(set(), type_attrs - attrs)
  553. finally:
  554. patcher.stop()
  555. def test_configure_mock(self):
  556. mock = Mock(foo='bar')
  557. self.assertEqual(mock.foo, 'bar')
  558. mock = MagicMock(foo='bar')
  559. self.assertEqual(mock.foo, 'bar')
  560. kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
  561. 'foo': MagicMock()}
  562. mock = Mock(**kwargs)
  563. self.assertRaises(KeyError, mock)
  564. self.assertEqual(mock.foo.bar(), 33)
  565. self.assertIsInstance(mock.foo, MagicMock)
  566. mock = Mock()
  567. mock.configure_mock(**kwargs)
  568. self.assertRaises(KeyError, mock)
  569. self.assertEqual(mock.foo.bar(), 33)
  570. self.assertIsInstance(mock.foo, MagicMock)
  571. def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs):
  572. # needed because assertRaisesRegex doesn't work easily with newlines
  573. try:
  574. func(*args, **kwargs)
  575. except:
  576. instance = sys.exc_info()[1]
  577. self.assertIsInstance(instance, exception)
  578. else:
  579. self.fail('Exception %r not raised' % (exception,))
  580. msg = str(instance)
  581. self.assertEqual(msg, message)
  582. def test_assert_called_with_failure_message(self):
  583. mock = NonCallableMock()
  584. expected = "mock(1, '2', 3, bar='foo')"
  585. message = 'Expected call: %s\nNot called'
  586. self.assertRaisesWithMsg(
  587. AssertionError, message % (expected,),
  588. mock.assert_called_with, 1, '2', 3, bar='foo'
  589. )
  590. mock.foo(1, '2', 3, foo='foo')
  591. asserters = [
  592. mock.foo.assert_called_with, mock.foo.assert_called_once_with
  593. ]
  594. for meth in asserters:
  595. actual = "foo(1, '2', 3, foo='foo')"
  596. expected = "foo(1, '2', 3, bar='foo')"
  597. message = 'Expected call: %s\nActual call: %s'
  598. self.assertRaisesWithMsg(
  599. AssertionError, message % (expected, actual),
  600. meth, 1, '2', 3, bar='foo'
  601. )
  602. # just kwargs
  603. for meth in asserters:
  604. actual = "foo(1, '2', 3, foo='foo')"
  605. expected = "foo(bar='foo')"
  606. message = 'Expected call: %s\nActual call: %s'
  607. self.assertRaisesWithMsg(
  608. AssertionError, message % (expected, actual),
  609. meth, bar='foo'
  610. )
  611. # just args
  612. for meth in asserters:
  613. actual = "foo(1, '2', 3, foo='foo')"
  614. expected = "foo(1, 2, 3)"
  615. message = 'Expected call: %s\nActual call: %s'
  616. self.assertRaisesWithMsg(
  617. AssertionError, message % (expected, actual),
  618. meth, 1, 2, 3
  619. )
  620. # empty
  621. for meth in asserters:
  622. actual = "foo(1, '2', 3, foo='foo')"
  623. expected = "foo()"
  624. message = 'Expected call: %s\nActual call: %s'
  625. self.assertRaisesWithMsg(
  626. AssertionError, message % (expected, actual), meth
  627. )
  628. def test_mock_calls(self):
  629. mock = MagicMock()
  630. # need to do this because MagicMock.mock_calls used to just return
  631. # a MagicMock which also returned a MagicMock when __eq__ was called
  632. self.assertIs(mock.mock_calls == [], True)
  633. mock = MagicMock()
  634. mock()
  635. expected = [('', (), {})]
  636. self.assertEqual(mock.mock_calls, expected)
  637. mock.foo()
  638. expected.append(call.foo())
  639. self.assertEqual(mock.mock_calls, expected)
  640. # intermediate mock_calls work too
  641. self.assertEqual(mock.foo.mock_calls, [('', (), {})])
  642. mock = MagicMock()
  643. mock().foo(1, 2, 3, a=4, b=5)
  644. expected = [
  645. ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5))
  646. ]
  647. self.assertEqual(mock.mock_calls, expected)
  648. self.assertEqual(mock.return_value.foo.mock_calls,
  649. [('', (1, 2, 3), dict(a=4, b=5))])
  650. self.assertEqual(mock.return_value.mock_calls,
  651. [('foo', (1, 2, 3), dict(a=4, b=5))])
  652. mock = MagicMock()
  653. mock().foo.bar().baz()
  654. expected = [
  655. ('', (), {}), ('().foo.bar', (), {}),
  656. ('().foo.bar().baz', (), {})
  657. ]
  658. self.assertEqual(mock.mock_calls, expected)
  659. self.assertEqual(mock().mock_calls,
  660. call.foo.bar().baz().call_list())
  661. for kwargs in dict(), dict(name='bar'):
  662. mock = MagicMock(**kwargs)
  663. int(mock.foo)
  664. expected = [('foo.__int__', (), {})]
  665. self.assertEqual(mock.mock_calls, expected)
  666. mock = MagicMock(**kwargs)
  667. mock.a()()
  668. expected = [('a', (), {}), ('a()', (), {})]
  669. self.assertEqual(mock.mock_calls, expected)
  670. self.assertEqual(mock.a().mock_calls, [call()])
  671. mock = MagicMock(**kwargs)
  672. mock(1)(2)(3)
  673. self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list())
  674. self.assertEqual(mock().mock_calls, call(2)(3).call_list())
  675. self.assertEqual(mock()().mock_calls, call(3).call_list())
  676. mock = MagicMock(**kwargs)
  677. mock(1)(2)(3).a.b.c(4)
  678. self.assertEqual(mock.mock_calls,
  679. call(1)(2)(3).a.b.c(4).call_list())
  680. self.assertEqual(mock().mock_calls,
  681. call(2)(3).a.b.c(4).call_list())
  682. self.assertEqual(mock()().mock_calls,
  683. call(3).a.b.c(4).call_list())
  684. mock = MagicMock(**kwargs)
  685. int(mock().foo.bar().baz())
  686. last_call = ('().foo.bar().baz().__int__', (), {})
  687. self.assertEqual(mock.mock_calls[-1], last_call)
  688. self.assertEqual(mock().mock_calls,
  689. call.foo.bar().baz().__int__().call_list())
  690. self.assertEqual(mock().foo.bar().mock_calls,
  691. call.baz().__int__().call_list())
  692. self.assertEqual(mock().foo.bar().baz.mock_calls,
  693. call().__int__().call_list())
  694. def test_subclassing(self):
  695. class Subclass(Mock):
  696. pass
  697. mock = Subclass()
  698. self.assertIsInstance(mock.foo, Subclass)
  699. self.assertIsInstance(mock(), Subclass)
  700. class Subclass(Mock):
  701. def _get_child_mock(self, **kwargs):
  702. return Mock(**kwargs)
  703. mock = Subclass()
  704. self.assertNotIsInstance(mock.foo, Subclass)
  705. self.assertNotIsInstance(mock(), Subclass)
  706. def test_arg_lists(self):
  707. mocks = [
  708. Mock(),
  709. MagicMock(),
  710. NonCallableMock(),
  711. NonCallableMagicMock()
  712. ]
  713. def assert_attrs(mock):
  714. names = 'call_args_list', 'method_calls', 'mock_calls'
  715. for name in names:
  716. attr = getattr(mock, name)
  717. self.assertIsInstance(attr, _CallList)
  718. self.assertIsInstance(attr, list)
  719. self.assertEqual(attr, [])
  720. for mock in mocks:
  721. assert_attrs(mock)
  722. if callable(mock):
  723. mock()
  724. mock(1, 2)
  725. mock(a=3)
  726. mock.reset_mock()
  727. assert_attrs(mock)
  728. mock.foo()
  729. mock.foo.bar(1, a=3)
  730. mock.foo(1).bar().baz(3)
  731. mock.reset_mock()
  732. assert_attrs(mock)
  733. def test_call_args_two_tuple(self):
  734. mock = Mock()
  735. mock(1, a=3)
  736. mock(2, b=4)
  737. self.assertEqual(len(mock.call_args), 2)
  738. args, kwargs = mock.call_args
  739. self.assertEqual(args, (2,))
  740. self.assertEqual(kwargs, dict(b=4))
  741. expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
  742. for expected, call_args in zip(expected_list, mock.call_args_list):
  743. self.assertEqual(len(call_args), 2)
  744. self.assertEqual(expected[0], call_args[0])
  745. self.assertEqual(expected[1], call_args[1])
  746. def test_side_effect_iterator(self):
  747. mock = Mock(side_effect=iter([1, 2, 3]))
  748. self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
  749. self.assertRaises(StopIteration, mock)
  750. mock = MagicMock(side_effect=['a', 'b', 'c'])
  751. self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
  752. self.assertRaises(StopIteration, mock)
  753. mock = Mock(side_effect='ghi')
  754. self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i'])
  755. self.assertRaises(StopIteration, mock)
  756. class Foo(object):
  757. pass
  758. mock = MagicMock(side_effect=Foo)
  759. self.assertIsInstance(mock(), Foo)
  760. mock = Mock(side_effect=Iter())
  761. self.assertEqual([mock(), mock(), mock(), mock()],
  762. ['this', 'is', 'an', 'iter'])
  763. self.assertRaises(StopIteration, mock)
  764. def test_side_effect_iterator_exceptions(self):
  765. for Klass in Mock, MagicMock:
  766. iterable = (ValueError, 3, KeyError, 6)
  767. m = Klass(side_effect=iterable)
  768. self.assertRaises(ValueError, m)
  769. self.assertEqual(m(), 3)
  770. self.assertRaises(KeyError, m)
  771. self.assertEqual(m(), 6)
  772. def test_side_effect_setting_iterator(self):
  773. mock = Mock()
  774. mock.side_effect = iter([1, 2, 3])
  775. self.assertEqual([mock(), mock(), mock()], [1, 2, 3])
  776. self.assertRaises(StopIteration, mock)
  777. side_effect = mock.side_effect
  778. self.assertIsInstance(side_effect, type(iter([])))
  779. mock.side_effect = ['a', 'b', 'c']
  780. self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c'])
  781. self.assertRaises(StopIteration, mock)
  782. side_effect = mock.side_effect
  783. self.assertIsInstance(side_effect, type(iter([])))
  784. this_iter = Iter()
  785. mock.side_effect = this_iter
  786. self.assertEqual([mock(), mock(), mock(), mock()],
  787. ['this', 'is', 'an', 'iter'])
  788. self.assertRaises(StopIteration, mock)
  789. self.assertIs(mock.side_effect, this_iter)
  790. def test_side_effect_iterator_default(self):
  791. mock = Mock(return_value=2)
  792. mock.side_effect = iter([1, DEFAULT])
  793. self.assertEqual([mock(), mock()], [1, 2])
  794. def test_assert_has_calls_any_order(self):
  795. mock = Mock()
  796. mock(1, 2)
  797. mock(a=3)
  798. mock(3, 4)
  799. mock(b=6)
  800. mock(b=6)
  801. kalls = [
  802. call(1, 2), ({'a': 3},),
  803. ((3, 4),), ((), {'a': 3}),
  804. ('', (1, 2)), ('', {'a': 3}),
  805. ('', (1, 2), {}), ('', (), {'a': 3})
  806. ]
  807. for kall in kalls:
  808. mock.assert_has_calls([kall], any_order=True)
  809. for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo':
  810. self.assertRaises(
  811. AssertionError, mock.assert_has_calls,
  812. [kall], any_order=True
  813. )
  814. kall_lists = [
  815. [call(1, 2), call(b=6)],
  816. [call(3, 4), call(1, 2)],
  817. [call(b=6), call(b=6)],
  818. ]
  819. for kall_list in kall_lists:
  820. mock.assert_has_calls(kall_list, any_order=True)
  821. kall_lists = [
  822. [call(b=6), call(b=6), call(b=6)],
  823. [call(1, 2), call(1, 2)],
  824. [call(3, 4), call(1, 2), call(5, 7)],
  825. [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)],
  826. ]
  827. for kall_list in kall_lists:
  828. self.assertRaises(
  829. AssertionError, mock.assert_has_calls,
  830. kall_list, any_order=True
  831. )
  832. def test_assert_has_calls(self):
  833. kalls1 = [
  834. call(1, 2), ({'a': 3},),
  835. ((3, 4),), call(b=6),
  836. ('', (1,), {'b': 6}),
  837. ]
  838. kalls2 = [call.foo(), call.bar(1)]
  839. kalls2.extend(call.spam().baz(a=3).call_list())
  840. kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
  841. mocks = []
  842. for mock in Mock(), MagicMock():
  843. mock(1, 2)
  844. mock(a=3)
  845. mock(3, 4)
  846. mock(b=6)
  847. mock(1, b=6)
  848. mocks.append((mock, kalls1))
  849. mock = Mock()
  850. mock.foo()
  851. mock.bar(1)
  852. mock.spam().baz(a=3)
  853. mock.bam(set(), foo={}).fish([1])
  854. mocks.append((mock, kalls2))
  855. for mock, kalls in mocks:
  856. for i in range(len(kalls)):
  857. for step in 1, 2, 3:
  858. these = kalls[i:i+step]
  859. mock.assert_has_calls(these)
  860. if len(these) > 1:
  861. self.assertRaises(
  862. AssertionError,
  863. mock.assert_has_calls,
  864. list(reversed(these))
  865. )
  866. def test_assert_has_calls_with_function_spec(self):
  867. def f(a, b, c, d=None):
  868. pass
  869. mock = Mock(spec=f)
  870. mock(1, b=2, c=3)
  871. mock(4, 5, c=6, d=7)
  872. mock(10, 11, c=12)
  873. calls = [
  874. ('', (1, 2, 3), {}),
  875. ('', (4, 5, 6), {'d': 7}),
  876. ((10, 11, 12), {}),
  877. ]
  878. mock.assert_has_calls(calls)
  879. mock.assert_has_calls(calls, any_order=True)
  880. mock.assert_has_calls(calls[1:])
  881. mock.assert_has_calls(calls[1:], any_order=True)
  882. mock.assert_has_calls(calls[:-1])
  883. mock.assert_has_calls(calls[:-1], any_order=True)
  884. # Reversed order
  885. calls = list(reversed(calls))
  886. with self.assertRaises(AssertionError):
  887. mock.assert_has_calls(calls)
  888. mock.assert_has_calls(calls, any_order=True)
  889. with self.assertRaises(AssertionError):
  890. mock.assert_has_calls(calls[1:])
  891. mock.assert_has_calls(calls[1:], any_order=True)
  892. with self.assertRaises(AssertionError):
  893. mock.assert_has_calls(calls[:-1])
  894. mock.assert_has_calls(calls[:-1], any_order=True)
  895. def test_assert_any_call(self):
  896. mock = Mock()
  897. mock(1, 2)
  898. mock(a=3)
  899. mock(1, b=6)
  900. mock.assert_any_call(1, 2)
  901. mock.assert_any_call(a=3)
  902. mock.assert_any_call(1, b=6)
  903. self.assertRaises(
  904. AssertionError,
  905. mock.assert_any_call
  906. )
  907. self.assertRaises(
  908. AssertionError,
  909. mock.assert_any_call,
  910. 1, 3
  911. )
  912. self.assertRaises(
  913. AssertionError,
  914. mock.assert_any_call,
  915. a=4
  916. )
  917. def test_assert_any_call_with_function_spec(self):
  918. def f(a, b, c, d=None):
  919. pass
  920. mock = Mock(spec=f)
  921. mock(1, b=2, c=3)
  922. mock(4, 5, c=6, d=7)
  923. mock.assert_any_call(1, 2, 3)
  924. mock.assert_any_call(a=1, b=2, c=3)
  925. mock.assert_any_call(4, 5, 6, 7)
  926. mock.assert_any_call(a=4, b=5, c=6, d=7)
  927. self.assertRaises(AssertionError, mock.assert_any_call,
  928. 1, b=3, c=2)
  929. # Expected call doesn't match the spec's signature
  930. with self.assertRaises(AssertionError) as cm:
  931. mock.assert_any_call(e=8)
  932. self.assertIsInstance(cm.exception.__cause__, TypeError)
  933. def test_mock_calls_create_autospec(self):
  934. def f(a, b):
  935. pass
  936. obj = Iter()
  937. obj.f = f
  938. funcs = [
  939. create_autospec(f),
  940. create_autospec(obj).f
  941. ]
  942. for func in funcs:
  943. func(1, 2)
  944. func(3, 4)
  945. self.assertEqual(
  946. func.mock_calls, [call(1, 2), call(3, 4)]
  947. )
  948. #Issue21222
  949. def test_create_autospec_with_name(self):
  950. m = mock.create_autospec(object(), name='sweet_func')
  951. self.assertIn('sweet_func', repr(m))
  952. #Issue21238
  953. def test_mock_unsafe(self):
  954. m = Mock()
  955. with self.assertRaises(AttributeError):
  956. m.assert_foo_call()
  957. with self.assertRaises(AttributeError):
  958. m.assret_foo_call()
  959. m = Mock(unsafe=True)
  960. m.assert_foo_call()
  961. m.assret_foo_call()
  962. #Issue21262
  963. def test_assert_not_called(self):
  964. m = Mock()
  965. m.hello.assert_not_called()
  966. m.hello()
  967. with self.assertRaises(AssertionError):
  968. m.hello.assert_not_called()
  969. #Issue21256 printout of keyword args should be in deterministic order
  970. def test_sorted_call_signature(self):
  971. m = Mock()
  972. m.hello(name='hello', daddy='hero')
  973. text = "call(daddy='hero', name='hello')"
  974. self.assertEqual(repr(m.hello.call_args), text)
  975. #Issue21270 overrides tuple methods for mock.call objects
  976. def test_override_tuple_methods(self):
  977. c = call.count()
  978. i = call.index(132,'hello')
  979. m = Mock()
  980. m.count()
  981. m.index(132,"hello")
  982. self.assertEqual(m.method_calls[0], c)
  983. self.assertEqual(m.method_calls[1], i)
  984. def test_mock_add_spec(self):
  985. class _One(object):
  986. one = 1
  987. class _Two(object):
  988. two = 2
  989. class Anything(object):
  990. one = two = three = 'four'
  991. klasses = [
  992. Mock, MagicMock, NonCallableMock, NonCallableMagicMock
  993. ]
  994. for Klass in list(klasses):
  995. klasses.append(lambda K=Klass: K(spec=Anything))
  996. klasses.append(lambda K=Klass: K(spec_set=Anything))
  997. for Klass in klasses:
  998. for kwargs in dict(), dict(spec_set=True):
  999. mock = Klass()
  1000. #no error
  1001. mock.one, mock.two, mock.three
  1002. for One, Two in [(_One, _Two), (['one'], ['two'])]:
  1003. for kwargs in dict(), dict(spec_set=True):
  1004. mock.mock_add_spec(One, **kwargs)
  1005. mock.one
  1006. self.assertRaises(
  1007. AttributeError, getattr, mock, 'two'
  1008. )
  1009. self.assertRaises(
  1010. AttributeError, getattr, mock, 'three'
  1011. )
  1012. if 'spec_set' in kwargs:
  1013. self.assertRaises(
  1014. AttributeError, setattr, mock, 'three', None
  1015. )
  1016. mock.mock_add_spec(Two, **kwargs)
  1017. self.assertRaises(
  1018. AttributeError, getattr, mock, 'one'
  1019. )
  1020. mock.two
  1021. self.assertRaises(
  1022. AttributeError, getattr, mock, 'three'
  1023. )
  1024. if 'spec_set' in kwargs:
  1025. self.assertRaises(
  1026. AttributeError, setattr, mock, 'three', None
  1027. )
  1028. # note that creating a mock, setting an instance attribute, and
  1029. # *then* setting a spec doesn't work. Not the intended use case
  1030. def test_mock_add_spec_magic_methods(self):
  1031. for Klass in MagicMock, NonCallableMagicMock:
  1032. mock = Klass()
  1033. int(mock)
  1034. mock.mock_add_spec(object)
  1035. self.assertRaises(TypeError, int, mock)
  1036. mock = Klass()
  1037. mock['foo']
  1038. mock.__int__.return_value =4
  1039. mock.mock_add_spec(int)
  1040. self.assertEqual(int(mock), 4)
  1041. self.assertRaises(TypeError, lambda: mock['foo'])
  1042. def test_adding_child_mock(self):
  1043. for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock:
  1044. mock = Klass()
  1045. mock.foo = Mock()
  1046. mock.foo()
  1047. self.assertEqual(mock.method_calls, [call.foo()])
  1048. self.assertEqual(mock.mock_calls, [call.foo()])
  1049. mock = Klass()
  1050. mock.bar = Mock(name='name')
  1051. mock.bar()
  1052. self.assertEqual(mock.method_calls, [])
  1053. self.assertEqual(mock.mock_calls, [])
  1054. # mock with an existing _new_parent but no name
  1055. mock = Klass()
  1056. mock.baz = MagicMock()()
  1057. mock.baz()
  1058. self.assertEqual(mock.method_calls, [])
  1059. self.assertEqual(mock.mock_calls, [])
  1060. def test_adding_return_value_mock(self):
  1061. for Klass in Mock, MagicMock:
  1062. mock = Klass()
  1063. mock.return_value = MagicMock()
  1064. mock()()
  1065. self.assertEqual(mock.mock_calls, [call(), call()()])
  1066. def test_manager_mock(self):
  1067. class Foo(object):
  1068. one = 'one'
  1069. two = 'two'
  1070. manager = Mock()
  1071. p1 = patch.object(Foo, 'one')
  1072. p2 = patch.object(Foo, 'two')
  1073. mock_one = p1.start()
  1074. self.addCleanup(p1.stop)
  1075. mock_two = p2.start()
  1076. self.addCleanup(p2.stop)
  1077. manager.attach_mock(mock_one, 'one')
  1078. manager.attach_mock(mock_two, 'two')
  1079. Foo.two()
  1080. Foo.one()
  1081. self.assertEqual(manager.mock_calls, [call.two(), call.one()])
  1082. def test_magic_methods_mock_calls(self):
  1083. for Klass in Mock, MagicMock:
  1084. m = Klass()
  1085. m.__int__ = Mock(return_value=3)
  1086. m.__float__ = MagicMock(return_value=3.0)
  1087. int(m)
  1088. float(m)
  1089. self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()])
  1090. self.assertEqual(m.method_calls, [])
  1091. def test_mock_open_reuse_issue_21750(self):
  1092. mocked_open = mock.mock_open(read_data='data')
  1093. f1 = mocked_open('a-name')
  1094. f1_data = f1.read()
  1095. f2 = mocked_open('another-name')
  1096. f2_data = f2.read()
  1097. self.assertEqual(f1_data, f2_data)
  1098. def test_mock_open_write(self):
  1099. # Test exception in file writing write()
  1100. mock_namedtemp = mock.mock_open(mock.MagicMock(name='JLV'))
  1101. with mock.patch('tempfile.NamedTemporaryFile', mock_namedtemp):
  1102. mock_filehandle = mock_namedtemp.return_value
  1103. mock_write = mock_filehandle.write
  1104. mock_write.side_effect = OSError('Test 2 Error')
  1105. def attempt():
  1106. tempfile.NamedTemporaryFile().write('asd')
  1107. self.assertRaises(OSError, attempt)
  1108. def test_mock_open_alter_readline(self):
  1109. mopen = mock.mock_open(read_data='foo\nbarn')
  1110. mopen.return_value.readline.side_effect = lambda *args:'abc'
  1111. first = mopen().readline()
  1112. second = mopen().readline()
  1113. self.assertEqual('abc', first)
  1114. self.assertEqual('abc', second)
  1115. def test_mock_open_after_eof(self):
  1116. # read, readline and readlines should work after end of file.
  1117. _open = mock.mock_open(read_data='foo')
  1118. h = _open('bar')
  1119. h.read()
  1120. self.assertEqual('', h.read())
  1121. self.assertEqual('', h.read())
  1122. self.assertEqual('', h.readline())
  1123. self.assertEqual('', h.readline())
  1124. self.assertEqual([], h.readlines())
  1125. self.assertEqual([], h.readlines())
  1126. def test_mock_parents(self):
  1127. for Klass in Mock, MagicMock:
  1128. m = Klass()
  1129. original_repr = repr(m)
  1130. m.return_value = m
  1131. self.assertIs(m(), m)
  1132. self.assertEqual(repr(m), original_repr)
  1133. m.reset_mock()
  1134. self.assertIs(m(), m)
  1135. self.assertEqual(repr(m), original_repr)
  1136. m = Klass()
  1137. m.b = m.a
  1138. self.assertIn("name='mock.a'", repr(m.b))
  1139. self.assertIn("name='mock.a'", repr(m.a))
  1140. m.reset_mock()
  1141. self.assertIn("name='mock.a'", repr(m.b))
  1142. self.assertIn("name='mock.a'", repr(m.a))
  1143. m = Klass()
  1144. original_repr = repr(m)
  1145. m.a = m()
  1146. m.a.return_value = m
  1147. self.assertEqual(repr(m), original_repr)
  1148. self.assertEqual(repr(m.a()), original_repr)
  1149. def test_attach_mock(self):
  1150. classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
  1151. for Klass in classes:
  1152. for Klass2 in classes:
  1153. m = Klass()
  1154. m2 = Klass2(name='foo')
  1155. m.attach_mock(m2, 'bar')
  1156. self.assertIs(m.bar, m2)
  1157. self.assertIn("name='mock.bar'", repr(m2))
  1158. m.bar.baz(1)
  1159. self.assertEqual(m.mock_calls, [call.bar.baz(1)])
  1160. self.assertEqual(m.method_calls, [call.bar.baz(1)])
  1161. def test_attach_mock_return_value(self):
  1162. classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock
  1163. for Klass in Mock, MagicMock:
  1164. for Klass2 in classes:
  1165. m = Klass()
  1166. m2 = Klass2(name='foo')
  1167. m.attach_mock(m2, 'return_value')
  1168. self.assertIs(m(), m2)
  1169. self.assertIn("name='mock()'", repr(m2))
  1170. m2.foo()
  1171. self.assertEqual(m.mock_calls, call().foo().call_list())
  1172. def test_attribute_deletion(self):
  1173. for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
  1174. NonCallableMock()):
  1175. self.assertTrue(hasattr(mock, 'm'))
  1176. del mock.m
  1177. self.assertFalse(hasattr(mock, 'm'))
  1178. del mock.f
  1179. self.assertFalse(hasattr(mock, 'f'))
  1180. self.assertRaises(AttributeError, getattr, mock, 'f')
  1181. def test_class_assignable(self):
  1182. for mock in Mock(), MagicMock():
  1183. self.assertNotIsInstance(mock, int)
  1184. mock.__class__ = int
  1185. self.assertIsInstance(mock, int)
  1186. mock.foo
  1187. if __name__ == '__main__':
  1188. unittest.main()