Plex plugin to to play various online streams (mostly Latvian).

testmock.py 49KB

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