testhelpers.py 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. import inspect
  2. import time
  3. import types
  4. import unittest
  5. from unittest.mock import (
  6. call, _Call, create_autospec, MagicMock,
  7. Mock, ANY, _CallList, patch, PropertyMock, _callable
  8. )
  9. from datetime import datetime
  10. from functools import partial
  11. class SomeClass(object):
  12. def one(self, a, b): pass
  13. def two(self): pass
  14. def three(self, a=None): pass
  15. class AnyTest(unittest.TestCase):
  16. def test_any(self):
  17. self.assertEqual(ANY, object())
  18. mock = Mock()
  19. mock(ANY)
  20. mock.assert_called_with(ANY)
  21. mock = Mock()
  22. mock(foo=ANY)
  23. mock.assert_called_with(foo=ANY)
  24. def test_repr(self):
  25. self.assertEqual(repr(ANY), '<ANY>')
  26. self.assertEqual(str(ANY), '<ANY>')
  27. def test_any_and_datetime(self):
  28. mock = Mock()
  29. mock(datetime.now(), foo=datetime.now())
  30. mock.assert_called_with(ANY, foo=ANY)
  31. def test_any_mock_calls_comparison_order(self):
  32. mock = Mock()
  33. class Foo(object):
  34. def __eq__(self, other): pass
  35. def __ne__(self, other): pass
  36. for d in datetime.now(), Foo():
  37. mock.reset_mock()
  38. mock(d, foo=d, bar=d)
  39. mock.method(d, zinga=d, alpha=d)
  40. mock().method(a1=d, z99=d)
  41. expected = [
  42. call(ANY, foo=ANY, bar=ANY),
  43. call.method(ANY, zinga=ANY, alpha=ANY),
  44. call(), call().method(a1=ANY, z99=ANY)
  45. ]
  46. self.assertEqual(expected, mock.mock_calls)
  47. self.assertEqual(mock.mock_calls, expected)
  48. def test_any_no_spec(self):
  49. # This is a regression test for bpo-37555
  50. class Foo:
  51. def __eq__(self, other): pass
  52. mock = Mock()
  53. mock(Foo(), 1)
  54. mock.assert_has_calls([call(ANY, 1)])
  55. mock.assert_called_with(ANY, 1)
  56. mock.assert_any_call(ANY, 1)
  57. def test_any_and_spec_set(self):
  58. # This is a regression test for bpo-37555
  59. class Foo:
  60. def __eq__(self, other): pass
  61. mock = Mock(spec=Foo)
  62. mock(Foo(), 1)
  63. mock.assert_has_calls([call(ANY, 1)])
  64. mock.assert_called_with(ANY, 1)
  65. mock.assert_any_call(ANY, 1)
  66. class CallTest(unittest.TestCase):
  67. def test_call_with_call(self):
  68. kall = _Call()
  69. self.assertEqual(kall, _Call())
  70. self.assertEqual(kall, _Call(('',)))
  71. self.assertEqual(kall, _Call(((),)))
  72. self.assertEqual(kall, _Call(({},)))
  73. self.assertEqual(kall, _Call(('', ())))
  74. self.assertEqual(kall, _Call(('', {})))
  75. self.assertEqual(kall, _Call(('', (), {})))
  76. self.assertEqual(kall, _Call(('foo',)))
  77. self.assertEqual(kall, _Call(('bar', ())))
  78. self.assertEqual(kall, _Call(('baz', {})))
  79. self.assertEqual(kall, _Call(('spam', (), {})))
  80. kall = _Call(((1, 2, 3),))
  81. self.assertEqual(kall, _Call(((1, 2, 3),)))
  82. self.assertEqual(kall, _Call(('', (1, 2, 3))))
  83. self.assertEqual(kall, _Call(((1, 2, 3), {})))
  84. self.assertEqual(kall, _Call(('', (1, 2, 3), {})))
  85. kall = _Call(((1, 2, 4),))
  86. self.assertNotEqual(kall, _Call(('', (1, 2, 3))))
  87. self.assertNotEqual(kall, _Call(('', (1, 2, 3), {})))
  88. kall = _Call(('foo', (1, 2, 4),))
  89. self.assertNotEqual(kall, _Call(('', (1, 2, 4))))
  90. self.assertNotEqual(kall, _Call(('', (1, 2, 4), {})))
  91. self.assertNotEqual(kall, _Call(('bar', (1, 2, 4))))
  92. self.assertNotEqual(kall, _Call(('bar', (1, 2, 4), {})))
  93. kall = _Call(({'a': 3},))
  94. self.assertEqual(kall, _Call(('', (), {'a': 3})))
  95. self.assertEqual(kall, _Call(('', {'a': 3})))
  96. self.assertEqual(kall, _Call(((), {'a': 3})))
  97. self.assertEqual(kall, _Call(({'a': 3},)))
  98. def test_empty__Call(self):
  99. args = _Call()
  100. self.assertEqual(args, ())
  101. self.assertEqual(args, ('foo',))
  102. self.assertEqual(args, ((),))
  103. self.assertEqual(args, ('foo', ()))
  104. self.assertEqual(args, ('foo',(), {}))
  105. self.assertEqual(args, ('foo', {}))
  106. self.assertEqual(args, ({},))
  107. def test_named_empty_call(self):
  108. args = _Call(('foo', (), {}))
  109. self.assertEqual(args, ('foo',))
  110. self.assertEqual(args, ('foo', ()))
  111. self.assertEqual(args, ('foo',(), {}))
  112. self.assertEqual(args, ('foo', {}))
  113. self.assertNotEqual(args, ((),))
  114. self.assertNotEqual(args, ())
  115. self.assertNotEqual(args, ({},))
  116. self.assertNotEqual(args, ('bar',))
  117. self.assertNotEqual(args, ('bar', ()))
  118. self.assertNotEqual(args, ('bar', {}))
  119. def test_call_with_args(self):
  120. args = _Call(((1, 2, 3), {}))
  121. self.assertEqual(args, ((1, 2, 3),))
  122. self.assertEqual(args, ('foo', (1, 2, 3)))
  123. self.assertEqual(args, ('foo', (1, 2, 3), {}))
  124. self.assertEqual(args, ((1, 2, 3), {}))
  125. self.assertEqual(args.args, (1, 2, 3))
  126. self.assertEqual(args.kwargs, {})
  127. def test_named_call_with_args(self):
  128. args = _Call(('foo', (1, 2, 3), {}))
  129. self.assertEqual(args, ('foo', (1, 2, 3)))
  130. self.assertEqual(args, ('foo', (1, 2, 3), {}))
  131. self.assertEqual(args.args, (1, 2, 3))
  132. self.assertEqual(args.kwargs, {})
  133. self.assertNotEqual(args, ((1, 2, 3),))
  134. self.assertNotEqual(args, ((1, 2, 3), {}))
  135. def test_call_with_kwargs(self):
  136. args = _Call(((), dict(a=3, b=4)))
  137. self.assertEqual(args, (dict(a=3, b=4),))
  138. self.assertEqual(args, ('foo', dict(a=3, b=4)))
  139. self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
  140. self.assertEqual(args, ((), dict(a=3, b=4)))
  141. self.assertEqual(args.args, ())
  142. self.assertEqual(args.kwargs, dict(a=3, b=4))
  143. def test_named_call_with_kwargs(self):
  144. args = _Call(('foo', (), dict(a=3, b=4)))
  145. self.assertEqual(args, ('foo', dict(a=3, b=4)))
  146. self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
  147. self.assertEqual(args.args, ())
  148. self.assertEqual(args.kwargs, dict(a=3, b=4))
  149. self.assertNotEqual(args, (dict(a=3, b=4),))
  150. self.assertNotEqual(args, ((), dict(a=3, b=4)))
  151. def test_call_with_args_call_empty_name(self):
  152. args = _Call(((1, 2, 3), {}))
  153. self.assertEqual(args, call(1, 2, 3))
  154. self.assertEqual(call(1, 2, 3), args)
  155. self.assertIn(call(1, 2, 3), [args])
  156. def test_call_ne(self):
  157. self.assertNotEqual(_Call(((1, 2, 3),)), call(1, 2))
  158. self.assertFalse(_Call(((1, 2, 3),)) != call(1, 2, 3))
  159. self.assertTrue(_Call(((1, 2), {})) != call(1, 2, 3))
  160. def test_call_non_tuples(self):
  161. kall = _Call(((1, 2, 3),))
  162. for value in 1, None, self, int:
  163. self.assertNotEqual(kall, value)
  164. self.assertFalse(kall == value)
  165. def test_repr(self):
  166. self.assertEqual(repr(_Call()), 'call()')
  167. self.assertEqual(repr(_Call(('foo',))), 'call.foo()')
  168. self.assertEqual(repr(_Call(((1, 2, 3), {'a': 'b'}))),
  169. "call(1, 2, 3, a='b')")
  170. self.assertEqual(repr(_Call(('bar', (1, 2, 3), {'a': 'b'}))),
  171. "call.bar(1, 2, 3, a='b')")
  172. self.assertEqual(repr(call), 'call')
  173. self.assertEqual(str(call), 'call')
  174. self.assertEqual(repr(call()), 'call()')
  175. self.assertEqual(repr(call(1)), 'call(1)')
  176. self.assertEqual(repr(call(zz='thing')), "call(zz='thing')")
  177. self.assertEqual(repr(call().foo), 'call().foo')
  178. self.assertEqual(repr(call(1).foo.bar(a=3).bing),
  179. 'call().foo.bar().bing')
  180. self.assertEqual(
  181. repr(call().foo(1, 2, a=3)),
  182. "call().foo(1, 2, a=3)"
  183. )
  184. self.assertEqual(repr(call()()), "call()()")
  185. self.assertEqual(repr(call(1)(2)), "call()(2)")
  186. self.assertEqual(
  187. repr(call()().bar().baz.beep(1)),
  188. "call()().bar().baz.beep(1)"
  189. )
  190. def test_call(self):
  191. self.assertEqual(call(), ('', (), {}))
  192. self.assertEqual(call('foo', 'bar', one=3, two=4),
  193. ('', ('foo', 'bar'), {'one': 3, 'two': 4}))
  194. mock = Mock()
  195. mock(1, 2, 3)
  196. mock(a=3, b=6)
  197. self.assertEqual(mock.call_args_list,
  198. [call(1, 2, 3), call(a=3, b=6)])
  199. def test_attribute_call(self):
  200. self.assertEqual(call.foo(1), ('foo', (1,), {}))
  201. self.assertEqual(call.bar.baz(fish='eggs'),
  202. ('bar.baz', (), {'fish': 'eggs'}))
  203. mock = Mock()
  204. mock.foo(1, 2 ,3)
  205. mock.bar.baz(a=3, b=6)
  206. self.assertEqual(mock.method_calls,
  207. [call.foo(1, 2, 3), call.bar.baz(a=3, b=6)])
  208. def test_extended_call(self):
  209. result = call(1).foo(2).bar(3, a=4)
  210. self.assertEqual(result, ('().foo().bar', (3,), dict(a=4)))
  211. mock = MagicMock()
  212. mock(1, 2, a=3, b=4)
  213. self.assertEqual(mock.call_args, call(1, 2, a=3, b=4))
  214. self.assertNotEqual(mock.call_args, call(1, 2, 3))
  215. self.assertEqual(mock.call_args_list, [call(1, 2, a=3, b=4)])
  216. self.assertEqual(mock.mock_calls, [call(1, 2, a=3, b=4)])
  217. mock = MagicMock()
  218. mock.foo(1).bar()().baz.beep(a=6)
  219. last_call = call.foo(1).bar()().baz.beep(a=6)
  220. self.assertEqual(mock.mock_calls[-1], last_call)
  221. self.assertEqual(mock.mock_calls, last_call.call_list())
  222. def test_extended_not_equal(self):
  223. a = call(x=1).foo
  224. b = call(x=2).foo
  225. self.assertEqual(a, a)
  226. self.assertEqual(b, b)
  227. self.assertNotEqual(a, b)
  228. def test_nested_calls_not_equal(self):
  229. a = call(x=1).foo().bar
  230. b = call(x=2).foo().bar
  231. self.assertEqual(a, a)
  232. self.assertEqual(b, b)
  233. self.assertNotEqual(a, b)
  234. def test_call_list(self):
  235. mock = MagicMock()
  236. mock(1)
  237. self.assertEqual(call(1).call_list(), mock.mock_calls)
  238. mock = MagicMock()
  239. mock(1).method(2)
  240. self.assertEqual(call(1).method(2).call_list(),
  241. mock.mock_calls)
  242. mock = MagicMock()
  243. mock(1).method(2)(3)
  244. self.assertEqual(call(1).method(2)(3).call_list(),
  245. mock.mock_calls)
  246. mock = MagicMock()
  247. int(mock(1).method(2)(3).foo.bar.baz(4)(5))
  248. kall = call(1).method(2)(3).foo.bar.baz(4)(5).__int__()
  249. self.assertEqual(kall.call_list(), mock.mock_calls)
  250. def test_call_any(self):
  251. self.assertEqual(call, ANY)
  252. m = MagicMock()
  253. int(m)
  254. self.assertEqual(m.mock_calls, [ANY])
  255. self.assertEqual([ANY], m.mock_calls)
  256. def test_two_args_call(self):
  257. args = _Call(((1, 2), {'a': 3}), two=True)
  258. self.assertEqual(len(args), 2)
  259. self.assertEqual(args[0], (1, 2))
  260. self.assertEqual(args[1], {'a': 3})
  261. other_args = _Call(((1, 2), {'a': 3}))
  262. self.assertEqual(args, other_args)
  263. def test_call_with_name(self):
  264. self.assertEqual(_Call((), 'foo')[0], 'foo')
  265. self.assertEqual(_Call((('bar', 'barz'),),)[0], '')
  266. self.assertEqual(_Call((('bar', 'barz'), {'hello': 'world'}),)[0], '')
  267. def test_dunder_call(self):
  268. m = MagicMock()
  269. m().foo()['bar']()
  270. self.assertEqual(
  271. m.mock_calls,
  272. [call(), call().foo(), call().foo().__getitem__('bar'), call().foo().__getitem__()()]
  273. )
  274. m = MagicMock()
  275. m().foo()['bar'] = 1
  276. self.assertEqual(
  277. m.mock_calls,
  278. [call(), call().foo(), call().foo().__setitem__('bar', 1)]
  279. )
  280. m = MagicMock()
  281. iter(m().foo())
  282. self.assertEqual(
  283. m.mock_calls,
  284. [call(), call().foo(), call().foo().__iter__()]
  285. )
  286. class SpecSignatureTest(unittest.TestCase):
  287. def _check_someclass_mock(self, mock):
  288. self.assertRaises(AttributeError, getattr, mock, 'foo')
  289. mock.one(1, 2)
  290. mock.one.assert_called_with(1, 2)
  291. self.assertRaises(AssertionError,
  292. mock.one.assert_called_with, 3, 4)
  293. self.assertRaises(TypeError, mock.one, 1)
  294. mock.two()
  295. mock.two.assert_called_with()
  296. self.assertRaises(AssertionError,
  297. mock.two.assert_called_with, 3)
  298. self.assertRaises(TypeError, mock.two, 1)
  299. mock.three()
  300. mock.three.assert_called_with()
  301. self.assertRaises(AssertionError,
  302. mock.three.assert_called_with, 3)
  303. self.assertRaises(TypeError, mock.three, 3, 2)
  304. mock.three(1)
  305. mock.three.assert_called_with(1)
  306. mock.three(a=1)
  307. mock.three.assert_called_with(a=1)
  308. def test_basic(self):
  309. mock = create_autospec(SomeClass)
  310. self._check_someclass_mock(mock)
  311. mock = create_autospec(SomeClass())
  312. self._check_someclass_mock(mock)
  313. def test_create_autospec_return_value(self):
  314. def f(): pass
  315. mock = create_autospec(f, return_value='foo')
  316. self.assertEqual(mock(), 'foo')
  317. class Foo(object):
  318. pass
  319. mock = create_autospec(Foo, return_value='foo')
  320. self.assertEqual(mock(), 'foo')
  321. def test_autospec_reset_mock(self):
  322. m = create_autospec(int)
  323. int(m)
  324. m.reset_mock()
  325. self.assertEqual(m.__int__.call_count, 0)
  326. def test_mocking_unbound_methods(self):
  327. class Foo(object):
  328. def foo(self, foo): pass
  329. p = patch.object(Foo, 'foo')
  330. mock_foo = p.start()
  331. Foo().foo(1)
  332. mock_foo.assert_called_with(1)
  333. def test_create_autospec_keyword_arguments(self):
  334. class Foo(object):
  335. a = 3
  336. m = create_autospec(Foo, a='3')
  337. self.assertEqual(m.a, '3')
  338. def test_create_autospec_keyword_only_arguments(self):
  339. def foo(a, *, b=None): pass
  340. m = create_autospec(foo)
  341. m(1)
  342. m.assert_called_with(1)
  343. self.assertRaises(TypeError, m, 1, 2)
  344. m(2, b=3)
  345. m.assert_called_with(2, b=3)
  346. def test_function_as_instance_attribute(self):
  347. obj = SomeClass()
  348. def f(a): pass
  349. obj.f = f
  350. mock = create_autospec(obj)
  351. mock.f('bing')
  352. mock.f.assert_called_with('bing')
  353. def test_spec_as_list(self):
  354. # because spec as a list of strings in the mock constructor means
  355. # something very different we treat a list instance as the type.
  356. mock = create_autospec([])
  357. mock.append('foo')
  358. mock.append.assert_called_with('foo')
  359. self.assertRaises(AttributeError, getattr, mock, 'foo')
  360. class Foo(object):
  361. foo = []
  362. mock = create_autospec(Foo)
  363. mock.foo.append(3)
  364. mock.foo.append.assert_called_with(3)
  365. self.assertRaises(AttributeError, getattr, mock.foo, 'foo')
  366. def test_attributes(self):
  367. class Sub(SomeClass):
  368. attr = SomeClass()
  369. sub_mock = create_autospec(Sub)
  370. for mock in (sub_mock, sub_mock.attr):
  371. self._check_someclass_mock(mock)
  372. def test_spec_has_descriptor_returning_function(self):
  373. class CrazyDescriptor(object):
  374. def __get__(self, obj, type_):
  375. if obj is None:
  376. return lambda x: None
  377. class MyClass(object):
  378. some_attr = CrazyDescriptor()
  379. mock = create_autospec(MyClass)
  380. mock.some_attr(1)
  381. with self.assertRaises(TypeError):
  382. mock.some_attr()
  383. with self.assertRaises(TypeError):
  384. mock.some_attr(1, 2)
  385. def test_spec_has_function_not_in_bases(self):
  386. class CrazyClass(object):
  387. def __dir__(self):
  388. return super(CrazyClass, self).__dir__()+['crazy']
  389. def __getattr__(self, item):
  390. if item == 'crazy':
  391. return lambda x: x
  392. raise AttributeError(item)
  393. inst = CrazyClass()
  394. with self.assertRaises(AttributeError):
  395. inst.other
  396. self.assertEqual(inst.crazy(42), 42)
  397. mock = create_autospec(inst)
  398. mock.crazy(42)
  399. with self.assertRaises(TypeError):
  400. mock.crazy()
  401. with self.assertRaises(TypeError):
  402. mock.crazy(1, 2)
  403. def test_builtin_functions_types(self):
  404. # we could replace builtin functions / methods with a function
  405. # with *args / **kwargs signature. Using the builtin method type
  406. # as a spec seems to work fairly well though.
  407. class BuiltinSubclass(list):
  408. def bar(self, arg): pass
  409. sorted = sorted
  410. attr = {}
  411. mock = create_autospec(BuiltinSubclass)
  412. mock.append(3)
  413. mock.append.assert_called_with(3)
  414. self.assertRaises(AttributeError, getattr, mock.append, 'foo')
  415. mock.bar('foo')
  416. mock.bar.assert_called_with('foo')
  417. self.assertRaises(TypeError, mock.bar, 'foo', 'bar')
  418. self.assertRaises(AttributeError, getattr, mock.bar, 'foo')
  419. mock.sorted([1, 2])
  420. mock.sorted.assert_called_with([1, 2])
  421. self.assertRaises(AttributeError, getattr, mock.sorted, 'foo')
  422. mock.attr.pop(3)
  423. mock.attr.pop.assert_called_with(3)
  424. self.assertRaises(AttributeError, getattr, mock.attr, 'foo')
  425. def test_method_calls(self):
  426. class Sub(SomeClass):
  427. attr = SomeClass()
  428. mock = create_autospec(Sub)
  429. mock.one(1, 2)
  430. mock.two()
  431. mock.three(3)
  432. expected = [call.one(1, 2), call.two(), call.three(3)]
  433. self.assertEqual(mock.method_calls, expected)
  434. mock.attr.one(1, 2)
  435. mock.attr.two()
  436. mock.attr.three(3)
  437. expected.extend(
  438. [call.attr.one(1, 2), call.attr.two(), call.attr.three(3)]
  439. )
  440. self.assertEqual(mock.method_calls, expected)
  441. def test_magic_methods(self):
  442. class BuiltinSubclass(list):
  443. attr = {}
  444. mock = create_autospec(BuiltinSubclass)
  445. self.assertEqual(list(mock), [])
  446. self.assertRaises(TypeError, int, mock)
  447. self.assertRaises(TypeError, int, mock.attr)
  448. self.assertEqual(list(mock), [])
  449. self.assertIsInstance(mock['foo'], MagicMock)
  450. self.assertIsInstance(mock.attr['foo'], MagicMock)
  451. def test_spec_set(self):
  452. class Sub(SomeClass):
  453. attr = SomeClass()
  454. for spec in (Sub, Sub()):
  455. mock = create_autospec(spec, spec_set=True)
  456. self._check_someclass_mock(mock)
  457. self.assertRaises(AttributeError, setattr, mock, 'foo', 'bar')
  458. self.assertRaises(AttributeError, setattr, mock.attr, 'foo', 'bar')
  459. def test_descriptors(self):
  460. class Foo(object):
  461. @classmethod
  462. def f(cls, a, b): pass
  463. @staticmethod
  464. def g(a, b): pass
  465. class Bar(Foo): pass
  466. class Baz(SomeClass, Bar): pass
  467. for spec in (Foo, Foo(), Bar, Bar(), Baz, Baz()):
  468. mock = create_autospec(spec)
  469. mock.f(1, 2)
  470. mock.f.assert_called_once_with(1, 2)
  471. mock.g(3, 4)
  472. mock.g.assert_called_once_with(3, 4)
  473. def test_recursive(self):
  474. class A(object):
  475. def a(self): pass
  476. foo = 'foo bar baz'
  477. bar = foo
  478. A.B = A
  479. mock = create_autospec(A)
  480. mock()
  481. self.assertFalse(mock.B.called)
  482. mock.a()
  483. mock.B.a()
  484. self.assertEqual(mock.method_calls, [call.a(), call.B.a()])
  485. self.assertIs(A.foo, A.bar)
  486. self.assertIsNot(mock.foo, mock.bar)
  487. mock.foo.lower()
  488. self.assertRaises(AssertionError, mock.bar.lower.assert_called_with)
  489. def test_spec_inheritance_for_classes(self):
  490. class Foo(object):
  491. def a(self, x): pass
  492. class Bar(object):
  493. def f(self, y): pass
  494. class_mock = create_autospec(Foo)
  495. self.assertIsNot(class_mock, class_mock())
  496. for this_mock in class_mock, class_mock():
  497. this_mock.a(x=5)
  498. this_mock.a.assert_called_with(x=5)
  499. this_mock.a.assert_called_with(5)
  500. self.assertRaises(TypeError, this_mock.a, 'foo', 'bar')
  501. self.assertRaises(AttributeError, getattr, this_mock, 'b')
  502. instance_mock = create_autospec(Foo())
  503. instance_mock.a(5)
  504. instance_mock.a.assert_called_with(5)
  505. instance_mock.a.assert_called_with(x=5)
  506. self.assertRaises(TypeError, instance_mock.a, 'foo', 'bar')
  507. self.assertRaises(AttributeError, getattr, instance_mock, 'b')
  508. # The return value isn't isn't callable
  509. self.assertRaises(TypeError, instance_mock)
  510. instance_mock.Bar.f(6)
  511. instance_mock.Bar.f.assert_called_with(6)
  512. instance_mock.Bar.f.assert_called_with(y=6)
  513. self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')
  514. instance_mock.Bar().f(6)
  515. instance_mock.Bar().f.assert_called_with(6)
  516. instance_mock.Bar().f.assert_called_with(y=6)
  517. self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
  518. def test_inherit(self):
  519. class Foo(object):
  520. a = 3
  521. Foo.Foo = Foo
  522. # class
  523. mock = create_autospec(Foo)
  524. instance = mock()
  525. self.assertRaises(AttributeError, getattr, instance, 'b')
  526. attr_instance = mock.Foo()
  527. self.assertRaises(AttributeError, getattr, attr_instance, 'b')
  528. # instance
  529. mock = create_autospec(Foo())
  530. self.assertRaises(AttributeError, getattr, mock, 'b')
  531. self.assertRaises(TypeError, mock)
  532. # attribute instance
  533. call_result = mock.Foo()
  534. self.assertRaises(AttributeError, getattr, call_result, 'b')
  535. def test_builtins(self):
  536. # used to fail with infinite recursion
  537. create_autospec(1)
  538. create_autospec(int)
  539. create_autospec('foo')
  540. create_autospec(str)
  541. create_autospec({})
  542. create_autospec(dict)
  543. create_autospec([])
  544. create_autospec(list)
  545. create_autospec(set())
  546. create_autospec(set)
  547. create_autospec(1.0)
  548. create_autospec(float)
  549. create_autospec(1j)
  550. create_autospec(complex)
  551. create_autospec(False)
  552. create_autospec(True)
  553. def test_function(self):
  554. def f(a, b): pass
  555. mock = create_autospec(f)
  556. self.assertRaises(TypeError, mock)
  557. mock(1, 2)
  558. mock.assert_called_with(1, 2)
  559. mock.assert_called_with(1, b=2)
  560. mock.assert_called_with(a=1, b=2)
  561. f.f = f
  562. mock = create_autospec(f)
  563. self.assertRaises(TypeError, mock.f)
  564. mock.f(3, 4)
  565. mock.f.assert_called_with(3, 4)
  566. mock.f.assert_called_with(a=3, b=4)
  567. def test_skip_attributeerrors(self):
  568. class Raiser(object):
  569. def __get__(self, obj, type=None):
  570. if obj is None:
  571. raise AttributeError('Can only be accessed via an instance')
  572. class RaiserClass(object):
  573. raiser = Raiser()
  574. @staticmethod
  575. def existing(a, b):
  576. return a + b
  577. self.assertEqual(RaiserClass.existing(1, 2), 3)
  578. s = create_autospec(RaiserClass)
  579. self.assertRaises(TypeError, lambda x: s.existing(1, 2, 3))
  580. self.assertEqual(s.existing(1, 2), s.existing.return_value)
  581. self.assertRaises(AttributeError, lambda: s.nonexisting)
  582. # check we can fetch the raiser attribute and it has no spec
  583. obj = s.raiser
  584. obj.foo, obj.bar
  585. def test_signature_class(self):
  586. class Foo(object):
  587. def __init__(self, a, b=3): pass
  588. mock = create_autospec(Foo)
  589. self.assertRaises(TypeError, mock)
  590. mock(1)
  591. mock.assert_called_once_with(1)
  592. mock.assert_called_once_with(a=1)
  593. self.assertRaises(AssertionError, mock.assert_called_once_with, 2)
  594. mock(4, 5)
  595. mock.assert_called_with(4, 5)
  596. mock.assert_called_with(a=4, b=5)
  597. self.assertRaises(AssertionError, mock.assert_called_with, a=5, b=4)
  598. def test_class_with_no_init(self):
  599. # this used to raise an exception
  600. # due to trying to get a signature from object.__init__
  601. class Foo(object):
  602. pass
  603. create_autospec(Foo)
  604. def test_signature_callable(self):
  605. class Callable(object):
  606. def __init__(self, x, y): pass
  607. def __call__(self, a): pass
  608. mock = create_autospec(Callable)
  609. mock(1, 2)
  610. mock.assert_called_once_with(1, 2)
  611. mock.assert_called_once_with(x=1, y=2)
  612. self.assertRaises(TypeError, mock, 'a')
  613. instance = mock(1, 2)
  614. self.assertRaises(TypeError, instance)
  615. instance(a='a')
  616. instance.assert_called_once_with('a')
  617. instance.assert_called_once_with(a='a')
  618. instance('a')
  619. instance.assert_called_with('a')
  620. instance.assert_called_with(a='a')
  621. mock = create_autospec(Callable(1, 2))
  622. mock(a='a')
  623. mock.assert_called_once_with(a='a')
  624. self.assertRaises(TypeError, mock)
  625. mock('a')
  626. mock.assert_called_with('a')
  627. def test_signature_noncallable(self):
  628. class NonCallable(object):
  629. def __init__(self):
  630. pass
  631. mock = create_autospec(NonCallable)
  632. instance = mock()
  633. mock.assert_called_once_with()
  634. self.assertRaises(TypeError, mock, 'a')
  635. self.assertRaises(TypeError, instance)
  636. self.assertRaises(TypeError, instance, 'a')
  637. mock = create_autospec(NonCallable())
  638. self.assertRaises(TypeError, mock)
  639. self.assertRaises(TypeError, mock, 'a')
  640. def test_create_autospec_none(self):
  641. class Foo(object):
  642. bar = None
  643. mock = create_autospec(Foo)
  644. none = mock.bar
  645. self.assertNotIsInstance(none, type(None))
  646. none.foo()
  647. none.foo.assert_called_once_with()
  648. def test_autospec_functions_with_self_in_odd_place(self):
  649. class Foo(object):
  650. def f(a, self): pass
  651. a = create_autospec(Foo)
  652. a.f(10)
  653. a.f.assert_called_with(10)
  654. a.f.assert_called_with(self=10)
  655. a.f(self=10)
  656. a.f.assert_called_with(10)
  657. a.f.assert_called_with(self=10)
  658. def test_autospec_data_descriptor(self):
  659. class Descriptor(object):
  660. def __init__(self, value):
  661. self.value = value
  662. def __get__(self, obj, cls=None):
  663. return self
  664. def __set__(self, obj, value): pass
  665. class MyProperty(property):
  666. pass
  667. class Foo(object):
  668. __slots__ = ['slot']
  669. @property
  670. def prop(self): pass
  671. @MyProperty
  672. def subprop(self): pass
  673. desc = Descriptor(42)
  674. foo = create_autospec(Foo)
  675. def check_data_descriptor(mock_attr):
  676. # Data descriptors don't have a spec.
  677. self.assertIsInstance(mock_attr, MagicMock)
  678. mock_attr(1, 2, 3)
  679. mock_attr.abc(4, 5, 6)
  680. mock_attr.assert_called_once_with(1, 2, 3)
  681. mock_attr.abc.assert_called_once_with(4, 5, 6)
  682. # property
  683. check_data_descriptor(foo.prop)
  684. # property subclass
  685. check_data_descriptor(foo.subprop)
  686. # class __slot__
  687. check_data_descriptor(foo.slot)
  688. # plain data descriptor
  689. check_data_descriptor(foo.desc)
  690. def test_autospec_on_bound_builtin_function(self):
  691. meth = types.MethodType(time.ctime, time.time())
  692. self.assertIsInstance(meth(), str)
  693. mocked = create_autospec(meth)
  694. # no signature, so no spec to check against
  695. mocked()
  696. mocked.assert_called_once_with()
  697. mocked.reset_mock()
  698. mocked(4, 5, 6)
  699. mocked.assert_called_once_with(4, 5, 6)
  700. def test_autospec_getattr_partial_function(self):
  701. # bpo-32153 : getattr returning partial functions without
  702. # __name__ should not create AttributeError in create_autospec
  703. class Foo:
  704. def __getattr__(self, attribute):
  705. return partial(lambda name: name, attribute)
  706. proxy = Foo()
  707. autospec = create_autospec(proxy)
  708. self.assertFalse(hasattr(autospec, '__name__'))
  709. def test_spec_inspect_signature(self):
  710. def myfunc(x, y): pass
  711. mock = create_autospec(myfunc)
  712. mock(1, 2)
  713. mock(x=1, y=2)
  714. self.assertEqual(inspect.signature(mock), inspect.signature(myfunc))
  715. self.assertEqual(mock.mock_calls, [call(1, 2), call(x=1, y=2)])
  716. self.assertRaises(TypeError, mock, 1)
  717. def test_spec_inspect_signature_annotations(self):
  718. def foo(a: int, b: int=10, *, c:int) -> int:
  719. return a + b + c
  720. self.assertEqual(foo(1, 2 , c=3), 6)
  721. mock = create_autospec(foo)
  722. mock(1, 2, c=3)
  723. mock(1, c=3)
  724. self.assertEqual(inspect.signature(mock), inspect.signature(foo))
  725. self.assertEqual(mock.mock_calls, [call(1, 2, c=3), call(1, c=3)])
  726. self.assertRaises(TypeError, mock, 1)
  727. self.assertRaises(TypeError, mock, 1, 2, 3, c=4)
  728. def test_spec_function_no_name(self):
  729. func = lambda: 'nope'
  730. mock = create_autospec(func)
  731. self.assertEqual(mock.__name__, 'funcopy')
  732. def test_spec_function_assert_has_calls(self):
  733. def f(a): pass
  734. mock = create_autospec(f)
  735. mock(1)
  736. mock.assert_has_calls([call(1)])
  737. with self.assertRaises(AssertionError):
  738. mock.assert_has_calls([call(2)])
  739. def test_spec_function_assert_any_call(self):
  740. def f(a): pass
  741. mock = create_autospec(f)
  742. mock(1)
  743. mock.assert_any_call(1)
  744. with self.assertRaises(AssertionError):
  745. mock.assert_any_call(2)
  746. def test_spec_function_reset_mock(self):
  747. def f(a): pass
  748. rv = Mock()
  749. mock = create_autospec(f, return_value=rv)
  750. mock(1)(2)
  751. self.assertEqual(mock.mock_calls, [call(1)])
  752. self.assertEqual(rv.mock_calls, [call(2)])
  753. mock.reset_mock()
  754. self.assertEqual(mock.mock_calls, [])
  755. self.assertEqual(rv.mock_calls, [])
  756. class TestCallList(unittest.TestCase):
  757. def test_args_list_contains_call_list(self):
  758. mock = Mock()
  759. self.assertIsInstance(mock.call_args_list, _CallList)
  760. mock(1, 2)
  761. mock(a=3)
  762. mock(3, 4)
  763. mock(b=6)
  764. for kall in call(1, 2), call(a=3), call(3, 4), call(b=6):
  765. self.assertIn(kall, mock.call_args_list)
  766. calls = [call(a=3), call(3, 4)]
  767. self.assertIn(calls, mock.call_args_list)
  768. calls = [call(1, 2), call(a=3)]
  769. self.assertIn(calls, mock.call_args_list)
  770. calls = [call(3, 4), call(b=6)]
  771. self.assertIn(calls, mock.call_args_list)
  772. calls = [call(3, 4)]
  773. self.assertIn(calls, mock.call_args_list)
  774. self.assertNotIn(call('fish'), mock.call_args_list)
  775. self.assertNotIn([call('fish')], mock.call_args_list)
  776. def test_call_list_str(self):
  777. mock = Mock()
  778. mock(1, 2)
  779. mock.foo(a=3)
  780. mock.foo.bar().baz('fish', cat='dog')
  781. expected = (
  782. "[call(1, 2),\n"
  783. " call.foo(a=3),\n"
  784. " call.foo.bar(),\n"
  785. " call.foo.bar().baz('fish', cat='dog')]"
  786. )
  787. self.assertEqual(str(mock.mock_calls), expected)
  788. def test_propertymock(self):
  789. p = patch('%s.SomeClass.one' % __name__, new_callable=PropertyMock)
  790. mock = p.start()
  791. try:
  792. SomeClass.one
  793. mock.assert_called_once_with()
  794. s = SomeClass()
  795. s.one
  796. mock.assert_called_with()
  797. self.assertEqual(mock.mock_calls, [call(), call()])
  798. s.one = 3
  799. self.assertEqual(mock.mock_calls, [call(), call(), call(3)])
  800. finally:
  801. p.stop()
  802. def test_propertymock_returnvalue(self):
  803. m = MagicMock()
  804. p = PropertyMock()
  805. type(m).foo = p
  806. returned = m.foo
  807. p.assert_called_once_with()
  808. self.assertIsInstance(returned, MagicMock)
  809. self.assertNotIsInstance(returned, PropertyMock)
  810. class TestCallablePredicate(unittest.TestCase):
  811. def test_type(self):
  812. for obj in [str, bytes, int, list, tuple, SomeClass]:
  813. self.assertTrue(_callable(obj))
  814. def test_call_magic_method(self):
  815. class Callable:
  816. def __call__(self): pass
  817. instance = Callable()
  818. self.assertTrue(_callable(instance))
  819. def test_staticmethod(self):
  820. class WithStaticMethod:
  821. @staticmethod
  822. def staticfunc(): pass
  823. self.assertTrue(_callable(WithStaticMethod.staticfunc))
  824. def test_non_callable_staticmethod(self):
  825. class BadStaticMethod:
  826. not_callable = staticmethod(None)
  827. self.assertFalse(_callable(BadStaticMethod.not_callable))
  828. def test_classmethod(self):
  829. class WithClassMethod:
  830. @classmethod
  831. def classfunc(cls): pass
  832. self.assertTrue(_callable(WithClassMethod.classfunc))
  833. def test_non_callable_classmethod(self):
  834. class BadClassMethod:
  835. not_callable = classmethod(None)
  836. self.assertFalse(_callable(BadClassMethod.not_callable))
  837. if __name__ == '__main__':
  838. unittest.main()