testhelpers.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. import unittest
  2. from unittest.mock import (
  3. call, _Call, create_autospec, MagicMock,
  4. Mock, ANY, _CallList, patch, PropertyMock
  5. )
  6. from datetime import datetime
  7. class SomeClass(object):
  8. def one(self, a, b):
  9. pass
  10. def two(self):
  11. pass
  12. def three(self, a=None):
  13. pass
  14. class AnyTest(unittest.TestCase):
  15. def test_any(self):
  16. self.assertEqual(ANY, object())
  17. mock = Mock()
  18. mock(ANY)
  19. mock.assert_called_with(ANY)
  20. mock = Mock()
  21. mock(foo=ANY)
  22. mock.assert_called_with(foo=ANY)
  23. def test_repr(self):
  24. self.assertEqual(repr(ANY), '<ANY>')
  25. self.assertEqual(str(ANY), '<ANY>')
  26. def test_any_and_datetime(self):
  27. mock = Mock()
  28. mock(datetime.now(), foo=datetime.now())
  29. mock.assert_called_with(ANY, foo=ANY)
  30. def test_any_mock_calls_comparison_order(self):
  31. mock = Mock()
  32. d = datetime.now()
  33. class Foo(object):
  34. def __eq__(self, other):
  35. return False
  36. def __ne__(self, other):
  37. return True
  38. for d in datetime.now(), Foo():
  39. mock.reset_mock()
  40. mock(d, foo=d, bar=d)
  41. mock.method(d, zinga=d, alpha=d)
  42. mock().method(a1=d, z99=d)
  43. expected = [
  44. call(ANY, foo=ANY, bar=ANY),
  45. call.method(ANY, zinga=ANY, alpha=ANY),
  46. call(), call().method(a1=ANY, z99=ANY)
  47. ]
  48. self.assertEqual(expected, mock.mock_calls)
  49. self.assertEqual(mock.mock_calls, expected)
  50. class CallTest(unittest.TestCase):
  51. def test_call_with_call(self):
  52. kall = _Call()
  53. self.assertEqual(kall, _Call())
  54. self.assertEqual(kall, _Call(('',)))
  55. self.assertEqual(kall, _Call(((),)))
  56. self.assertEqual(kall, _Call(({},)))
  57. self.assertEqual(kall, _Call(('', ())))
  58. self.assertEqual(kall, _Call(('', {})))
  59. self.assertEqual(kall, _Call(('', (), {})))
  60. self.assertEqual(kall, _Call(('foo',)))
  61. self.assertEqual(kall, _Call(('bar', ())))
  62. self.assertEqual(kall, _Call(('baz', {})))
  63. self.assertEqual(kall, _Call(('spam', (), {})))
  64. kall = _Call(((1, 2, 3),))
  65. self.assertEqual(kall, _Call(((1, 2, 3),)))
  66. self.assertEqual(kall, _Call(('', (1, 2, 3))))
  67. self.assertEqual(kall, _Call(((1, 2, 3), {})))
  68. self.assertEqual(kall, _Call(('', (1, 2, 3), {})))
  69. kall = _Call(((1, 2, 4),))
  70. self.assertNotEqual(kall, _Call(('', (1, 2, 3))))
  71. self.assertNotEqual(kall, _Call(('', (1, 2, 3), {})))
  72. kall = _Call(('foo', (1, 2, 4),))
  73. self.assertNotEqual(kall, _Call(('', (1, 2, 4))))
  74. self.assertNotEqual(kall, _Call(('', (1, 2, 4), {})))
  75. self.assertNotEqual(kall, _Call(('bar', (1, 2, 4))))
  76. self.assertNotEqual(kall, _Call(('bar', (1, 2, 4), {})))
  77. kall = _Call(({'a': 3},))
  78. self.assertEqual(kall, _Call(('', (), {'a': 3})))
  79. self.assertEqual(kall, _Call(('', {'a': 3})))
  80. self.assertEqual(kall, _Call(((), {'a': 3})))
  81. self.assertEqual(kall, _Call(({'a': 3},)))
  82. def test_empty__Call(self):
  83. args = _Call()
  84. self.assertEqual(args, ())
  85. self.assertEqual(args, ('foo',))
  86. self.assertEqual(args, ((),))
  87. self.assertEqual(args, ('foo', ()))
  88. self.assertEqual(args, ('foo',(), {}))
  89. self.assertEqual(args, ('foo', {}))
  90. self.assertEqual(args, ({},))
  91. def test_named_empty_call(self):
  92. args = _Call(('foo', (), {}))
  93. self.assertEqual(args, ('foo',))
  94. self.assertEqual(args, ('foo', ()))
  95. self.assertEqual(args, ('foo',(), {}))
  96. self.assertEqual(args, ('foo', {}))
  97. self.assertNotEqual(args, ((),))
  98. self.assertNotEqual(args, ())
  99. self.assertNotEqual(args, ({},))
  100. self.assertNotEqual(args, ('bar',))
  101. self.assertNotEqual(args, ('bar', ()))
  102. self.assertNotEqual(args, ('bar', {}))
  103. def test_call_with_args(self):
  104. args = _Call(((1, 2, 3), {}))
  105. self.assertEqual(args, ((1, 2, 3),))
  106. self.assertEqual(args, ('foo', (1, 2, 3)))
  107. self.assertEqual(args, ('foo', (1, 2, 3), {}))
  108. self.assertEqual(args, ((1, 2, 3), {}))
  109. def test_named_call_with_args(self):
  110. args = _Call(('foo', (1, 2, 3), {}))
  111. self.assertEqual(args, ('foo', (1, 2, 3)))
  112. self.assertEqual(args, ('foo', (1, 2, 3), {}))
  113. self.assertNotEqual(args, ((1, 2, 3),))
  114. self.assertNotEqual(args, ((1, 2, 3), {}))
  115. def test_call_with_kwargs(self):
  116. args = _Call(((), dict(a=3, b=4)))
  117. self.assertEqual(args, (dict(a=3, b=4),))
  118. self.assertEqual(args, ('foo', dict(a=3, b=4)))
  119. self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
  120. self.assertEqual(args, ((), dict(a=3, b=4)))
  121. def test_named_call_with_kwargs(self):
  122. args = _Call(('foo', (), dict(a=3, b=4)))
  123. self.assertEqual(args, ('foo', dict(a=3, b=4)))
  124. self.assertEqual(args, ('foo', (), dict(a=3, b=4)))
  125. self.assertNotEqual(args, (dict(a=3, b=4),))
  126. self.assertNotEqual(args, ((), dict(a=3, b=4)))
  127. def test_call_with_args_call_empty_name(self):
  128. args = _Call(((1, 2, 3), {}))
  129. self.assertEqual(args, call(1, 2, 3))
  130. self.assertEqual(call(1, 2, 3), args)
  131. self.assertIn(call(1, 2, 3), [args])
  132. def test_call_ne(self):
  133. self.assertNotEqual(_Call(((1, 2, 3),)), call(1, 2))
  134. self.assertFalse(_Call(((1, 2, 3),)) != call(1, 2, 3))
  135. self.assertTrue(_Call(((1, 2), {})) != call(1, 2, 3))
  136. def test_call_non_tuples(self):
  137. kall = _Call(((1, 2, 3),))
  138. for value in 1, None, self, int:
  139. self.assertNotEqual(kall, value)
  140. self.assertFalse(kall == value)
  141. def test_repr(self):
  142. self.assertEqual(repr(_Call()), 'call()')
  143. self.assertEqual(repr(_Call(('foo',))), 'call.foo()')
  144. self.assertEqual(repr(_Call(((1, 2, 3), {'a': 'b'}))),
  145. "call(1, 2, 3, a='b')")
  146. self.assertEqual(repr(_Call(('bar', (1, 2, 3), {'a': 'b'}))),
  147. "call.bar(1, 2, 3, a='b')")
  148. self.assertEqual(repr(call), 'call')
  149. self.assertEqual(str(call), 'call')
  150. self.assertEqual(repr(call()), 'call()')
  151. self.assertEqual(repr(call(1)), 'call(1)')
  152. self.assertEqual(repr(call(zz='thing')), "call(zz='thing')")
  153. self.assertEqual(repr(call().foo), 'call().foo')
  154. self.assertEqual(repr(call(1).foo.bar(a=3).bing),
  155. 'call().foo.bar().bing')
  156. self.assertEqual(
  157. repr(call().foo(1, 2, a=3)),
  158. "call().foo(1, 2, a=3)"
  159. )
  160. self.assertEqual(repr(call()()), "call()()")
  161. self.assertEqual(repr(call(1)(2)), "call()(2)")
  162. self.assertEqual(
  163. repr(call()().bar().baz.beep(1)),
  164. "call()().bar().baz.beep(1)"
  165. )
  166. def test_call(self):
  167. self.assertEqual(call(), ('', (), {}))
  168. self.assertEqual(call('foo', 'bar', one=3, two=4),
  169. ('', ('foo', 'bar'), {'one': 3, 'two': 4}))
  170. mock = Mock()
  171. mock(1, 2, 3)
  172. mock(a=3, b=6)
  173. self.assertEqual(mock.call_args_list,
  174. [call(1, 2, 3), call(a=3, b=6)])
  175. def test_attribute_call(self):
  176. self.assertEqual(call.foo(1), ('foo', (1,), {}))
  177. self.assertEqual(call.bar.baz(fish='eggs'),
  178. ('bar.baz', (), {'fish': 'eggs'}))
  179. mock = Mock()
  180. mock.foo(1, 2 ,3)
  181. mock.bar.baz(a=3, b=6)
  182. self.assertEqual(mock.method_calls,
  183. [call.foo(1, 2, 3), call.bar.baz(a=3, b=6)])
  184. def test_extended_call(self):
  185. result = call(1).foo(2).bar(3, a=4)
  186. self.assertEqual(result, ('().foo().bar', (3,), dict(a=4)))
  187. mock = MagicMock()
  188. mock(1, 2, a=3, b=4)
  189. self.assertEqual(mock.call_args, call(1, 2, a=3, b=4))
  190. self.assertNotEqual(mock.call_args, call(1, 2, 3))
  191. self.assertEqual(mock.call_args_list, [call(1, 2, a=3, b=4)])
  192. self.assertEqual(mock.mock_calls, [call(1, 2, a=3, b=4)])
  193. mock = MagicMock()
  194. mock.foo(1).bar()().baz.beep(a=6)
  195. last_call = call.foo(1).bar()().baz.beep(a=6)
  196. self.assertEqual(mock.mock_calls[-1], last_call)
  197. self.assertEqual(mock.mock_calls, last_call.call_list())
  198. def test_call_list(self):
  199. mock = MagicMock()
  200. mock(1)
  201. self.assertEqual(call(1).call_list(), mock.mock_calls)
  202. mock = MagicMock()
  203. mock(1).method(2)
  204. self.assertEqual(call(1).method(2).call_list(),
  205. mock.mock_calls)
  206. mock = MagicMock()
  207. mock(1).method(2)(3)
  208. self.assertEqual(call(1).method(2)(3).call_list(),
  209. mock.mock_calls)
  210. mock = MagicMock()
  211. int(mock(1).method(2)(3).foo.bar.baz(4)(5))
  212. kall = call(1).method(2)(3).foo.bar.baz(4)(5).__int__()
  213. self.assertEqual(kall.call_list(), mock.mock_calls)
  214. def test_call_any(self):
  215. self.assertEqual(call, ANY)
  216. m = MagicMock()
  217. int(m)
  218. self.assertEqual(m.mock_calls, [ANY])
  219. self.assertEqual([ANY], m.mock_calls)
  220. def test_two_args_call(self):
  221. args = _Call(((1, 2), {'a': 3}), two=True)
  222. self.assertEqual(len(args), 2)
  223. self.assertEqual(args[0], (1, 2))
  224. self.assertEqual(args[1], {'a': 3})
  225. other_args = _Call(((1, 2), {'a': 3}))
  226. self.assertEqual(args, other_args)
  227. class SpecSignatureTest(unittest.TestCase):
  228. def _check_someclass_mock(self, mock):
  229. self.assertRaises(AttributeError, getattr, mock, 'foo')
  230. mock.one(1, 2)
  231. mock.one.assert_called_with(1, 2)
  232. self.assertRaises(AssertionError,
  233. mock.one.assert_called_with, 3, 4)
  234. self.assertRaises(TypeError, mock.one, 1)
  235. mock.two()
  236. mock.two.assert_called_with()
  237. self.assertRaises(AssertionError,
  238. mock.two.assert_called_with, 3)
  239. self.assertRaises(TypeError, mock.two, 1)
  240. mock.three()
  241. mock.three.assert_called_with()
  242. self.assertRaises(AssertionError,
  243. mock.three.assert_called_with, 3)
  244. self.assertRaises(TypeError, mock.three, 3, 2)
  245. mock.three(1)
  246. mock.three.assert_called_with(1)
  247. mock.three(a=1)
  248. mock.three.assert_called_with(a=1)
  249. def test_basic(self):
  250. mock = create_autospec(SomeClass)
  251. self._check_someclass_mock(mock)
  252. mock = create_autospec(SomeClass())
  253. self._check_someclass_mock(mock)
  254. def test_create_autospec_return_value(self):
  255. def f():
  256. pass
  257. mock = create_autospec(f, return_value='foo')
  258. self.assertEqual(mock(), 'foo')
  259. class Foo(object):
  260. pass
  261. mock = create_autospec(Foo, return_value='foo')
  262. self.assertEqual(mock(), 'foo')
  263. def test_autospec_reset_mock(self):
  264. m = create_autospec(int)
  265. int(m)
  266. m.reset_mock()
  267. self.assertEqual(m.__int__.call_count, 0)
  268. def test_mocking_unbound_methods(self):
  269. class Foo(object):
  270. def foo(self, foo):
  271. pass
  272. p = patch.object(Foo, 'foo')
  273. mock_foo = p.start()
  274. Foo().foo(1)
  275. mock_foo.assert_called_with(1)
  276. def test_create_autospec_unbound_methods(self):
  277. # see mock issue 128
  278. # this is expected to fail until the issue is fixed
  279. return
  280. class Foo(object):
  281. def foo(self):
  282. pass
  283. klass = create_autospec(Foo)
  284. instance = klass()
  285. self.assertRaises(TypeError, instance.foo, 1)
  286. # Note: no type checking on the "self" parameter
  287. klass.foo(1)
  288. klass.foo.assert_called_with(1)
  289. self.assertRaises(TypeError, klass.foo)
  290. def test_create_autospec_keyword_arguments(self):
  291. class Foo(object):
  292. a = 3
  293. m = create_autospec(Foo, a='3')
  294. self.assertEqual(m.a, '3')
  295. def test_create_autospec_keyword_only_arguments(self):
  296. def foo(a, *, b=None):
  297. pass
  298. m = create_autospec(foo)
  299. m(1)
  300. m.assert_called_with(1)
  301. self.assertRaises(TypeError, m, 1, 2)
  302. m(2, b=3)
  303. m.assert_called_with(2, b=3)
  304. def test_function_as_instance_attribute(self):
  305. obj = SomeClass()
  306. def f(a):
  307. pass
  308. obj.f = f
  309. mock = create_autospec(obj)
  310. mock.f('bing')
  311. mock.f.assert_called_with('bing')
  312. def test_spec_as_list(self):
  313. # because spec as a list of strings in the mock constructor means
  314. # something very different we treat a list instance as the type.
  315. mock = create_autospec([])
  316. mock.append('foo')
  317. mock.append.assert_called_with('foo')
  318. self.assertRaises(AttributeError, getattr, mock, 'foo')
  319. class Foo(object):
  320. foo = []
  321. mock = create_autospec(Foo)
  322. mock.foo.append(3)
  323. mock.foo.append.assert_called_with(3)
  324. self.assertRaises(AttributeError, getattr, mock.foo, 'foo')
  325. def test_attributes(self):
  326. class Sub(SomeClass):
  327. attr = SomeClass()
  328. sub_mock = create_autospec(Sub)
  329. for mock in (sub_mock, sub_mock.attr):
  330. self._check_someclass_mock(mock)
  331. def test_builtin_functions_types(self):
  332. # we could replace builtin functions / methods with a function
  333. # with *args / **kwargs signature. Using the builtin method type
  334. # as a spec seems to work fairly well though.
  335. class BuiltinSubclass(list):
  336. def bar(self, arg):
  337. pass
  338. sorted = sorted
  339. attr = {}
  340. mock = create_autospec(BuiltinSubclass)
  341. mock.append(3)
  342. mock.append.assert_called_with(3)
  343. self.assertRaises(AttributeError, getattr, mock.append, 'foo')
  344. mock.bar('foo')
  345. mock.bar.assert_called_with('foo')
  346. self.assertRaises(TypeError, mock.bar, 'foo', 'bar')
  347. self.assertRaises(AttributeError, getattr, mock.bar, 'foo')
  348. mock.sorted([1, 2])
  349. mock.sorted.assert_called_with([1, 2])
  350. self.assertRaises(AttributeError, getattr, mock.sorted, 'foo')
  351. mock.attr.pop(3)
  352. mock.attr.pop.assert_called_with(3)
  353. self.assertRaises(AttributeError, getattr, mock.attr, 'foo')
  354. def test_method_calls(self):
  355. class Sub(SomeClass):
  356. attr = SomeClass()
  357. mock = create_autospec(Sub)
  358. mock.one(1, 2)
  359. mock.two()
  360. mock.three(3)
  361. expected = [call.one(1, 2), call.two(), call.three(3)]
  362. self.assertEqual(mock.method_calls, expected)
  363. mock.attr.one(1, 2)
  364. mock.attr.two()
  365. mock.attr.three(3)
  366. expected.extend(
  367. [call.attr.one(1, 2), call.attr.two(), call.attr.three(3)]
  368. )
  369. self.assertEqual(mock.method_calls, expected)
  370. def test_magic_methods(self):
  371. class BuiltinSubclass(list):
  372. attr = {}
  373. mock = create_autospec(BuiltinSubclass)
  374. self.assertEqual(list(mock), [])
  375. self.assertRaises(TypeError, int, mock)
  376. self.assertRaises(TypeError, int, mock.attr)
  377. self.assertEqual(list(mock), [])
  378. self.assertIsInstance(mock['foo'], MagicMock)
  379. self.assertIsInstance(mock.attr['foo'], MagicMock)
  380. def test_spec_set(self):
  381. class Sub(SomeClass):
  382. attr = SomeClass()
  383. for spec in (Sub, Sub()):
  384. mock = create_autospec(spec, spec_set=True)
  385. self._check_someclass_mock(mock)
  386. self.assertRaises(AttributeError, setattr, mock, 'foo', 'bar')
  387. self.assertRaises(AttributeError, setattr, mock.attr, 'foo', 'bar')
  388. def test_descriptors(self):
  389. class Foo(object):
  390. @classmethod
  391. def f(cls, a, b):
  392. pass
  393. @staticmethod
  394. def g(a, b):
  395. pass
  396. class Bar(Foo):
  397. pass
  398. class Baz(SomeClass, Bar):
  399. pass
  400. for spec in (Foo, Foo(), Bar, Bar(), Baz, Baz()):
  401. mock = create_autospec(spec)
  402. mock.f(1, 2)
  403. mock.f.assert_called_once_with(1, 2)
  404. mock.g(3, 4)
  405. mock.g.assert_called_once_with(3, 4)
  406. def test_recursive(self):
  407. class A(object):
  408. def a(self):
  409. pass
  410. foo = 'foo bar baz'
  411. bar = foo
  412. A.B = A
  413. mock = create_autospec(A)
  414. mock()
  415. self.assertFalse(mock.B.called)
  416. mock.a()
  417. mock.B.a()
  418. self.assertEqual(mock.method_calls, [call.a(), call.B.a()])
  419. self.assertIs(A.foo, A.bar)
  420. self.assertIsNot(mock.foo, mock.bar)
  421. mock.foo.lower()
  422. self.assertRaises(AssertionError, mock.bar.lower.assert_called_with)
  423. def test_spec_inheritance_for_classes(self):
  424. class Foo(object):
  425. def a(self, x):
  426. pass
  427. class Bar(object):
  428. def f(self, y):
  429. pass
  430. class_mock = create_autospec(Foo)
  431. self.assertIsNot(class_mock, class_mock())
  432. for this_mock in class_mock, class_mock():
  433. this_mock.a(x=5)
  434. this_mock.a.assert_called_with(x=5)
  435. this_mock.a.assert_called_with(5)
  436. self.assertRaises(TypeError, this_mock.a, 'foo', 'bar')
  437. self.assertRaises(AttributeError, getattr, this_mock, 'b')
  438. instance_mock = create_autospec(Foo())
  439. instance_mock.a(5)
  440. instance_mock.a.assert_called_with(5)
  441. instance_mock.a.assert_called_with(x=5)
  442. self.assertRaises(TypeError, instance_mock.a, 'foo', 'bar')
  443. self.assertRaises(AttributeError, getattr, instance_mock, 'b')
  444. # The return value isn't isn't callable
  445. self.assertRaises(TypeError, instance_mock)
  446. instance_mock.Bar.f(6)
  447. instance_mock.Bar.f.assert_called_with(6)
  448. instance_mock.Bar.f.assert_called_with(y=6)
  449. self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')
  450. instance_mock.Bar().f(6)
  451. instance_mock.Bar().f.assert_called_with(6)
  452. instance_mock.Bar().f.assert_called_with(y=6)
  453. self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
  454. def test_inherit(self):
  455. class Foo(object):
  456. a = 3
  457. Foo.Foo = Foo
  458. # class
  459. mock = create_autospec(Foo)
  460. instance = mock()
  461. self.assertRaises(AttributeError, getattr, instance, 'b')
  462. attr_instance = mock.Foo()
  463. self.assertRaises(AttributeError, getattr, attr_instance, 'b')
  464. # instance
  465. mock = create_autospec(Foo())
  466. self.assertRaises(AttributeError, getattr, mock, 'b')
  467. self.assertRaises(TypeError, mock)
  468. # attribute instance
  469. call_result = mock.Foo()
  470. self.assertRaises(AttributeError, getattr, call_result, 'b')
  471. def test_builtins(self):
  472. # used to fail with infinite recursion
  473. create_autospec(1)
  474. create_autospec(int)
  475. create_autospec('foo')
  476. create_autospec(str)
  477. create_autospec({})
  478. create_autospec(dict)
  479. create_autospec([])
  480. create_autospec(list)
  481. create_autospec(set())
  482. create_autospec(set)
  483. create_autospec(1.0)
  484. create_autospec(float)
  485. create_autospec(1j)
  486. create_autospec(complex)
  487. create_autospec(False)
  488. create_autospec(True)
  489. def test_function(self):
  490. def f(a, b):
  491. pass
  492. mock = create_autospec(f)
  493. self.assertRaises(TypeError, mock)
  494. mock(1, 2)
  495. mock.assert_called_with(1, 2)
  496. mock.assert_called_with(1, b=2)
  497. mock.assert_called_with(a=1, b=2)
  498. f.f = f
  499. mock = create_autospec(f)
  500. self.assertRaises(TypeError, mock.f)
  501. mock.f(3, 4)
  502. mock.f.assert_called_with(3, 4)
  503. mock.f.assert_called_with(a=3, b=4)
  504. def test_skip_attributeerrors(self):
  505. class Raiser(object):
  506. def __get__(self, obj, type=None):
  507. if obj is None:
  508. raise AttributeError('Can only be accessed via an instance')
  509. class RaiserClass(object):
  510. raiser = Raiser()
  511. @staticmethod
  512. def existing(a, b):
  513. return a + b
  514. s = create_autospec(RaiserClass)
  515. self.assertRaises(TypeError, lambda x: s.existing(1, 2, 3))
  516. s.existing(1, 2)
  517. self.assertRaises(AttributeError, lambda: s.nonexisting)
  518. # check we can fetch the raiser attribute and it has no spec
  519. obj = s.raiser
  520. obj.foo, obj.bar
  521. def test_signature_class(self):
  522. class Foo(object):
  523. def __init__(self, a, b=3):
  524. pass
  525. mock = create_autospec(Foo)
  526. self.assertRaises(TypeError, mock)
  527. mock(1)
  528. mock.assert_called_once_with(1)
  529. mock.assert_called_once_with(a=1)
  530. self.assertRaises(AssertionError, mock.assert_called_once_with, 2)
  531. mock(4, 5)
  532. mock.assert_called_with(4, 5)
  533. mock.assert_called_with(a=4, b=5)
  534. self.assertRaises(AssertionError, mock.assert_called_with, a=5, b=4)
  535. def test_class_with_no_init(self):
  536. # this used to raise an exception
  537. # due to trying to get a signature from object.__init__
  538. class Foo(object):
  539. pass
  540. create_autospec(Foo)
  541. def test_signature_callable(self):
  542. class Callable(object):
  543. def __init__(self, x, y):
  544. pass
  545. def __call__(self, a):
  546. pass
  547. mock = create_autospec(Callable)
  548. mock(1, 2)
  549. mock.assert_called_once_with(1, 2)
  550. mock.assert_called_once_with(x=1, y=2)
  551. self.assertRaises(TypeError, mock, 'a')
  552. instance = mock(1, 2)
  553. self.assertRaises(TypeError, instance)
  554. instance(a='a')
  555. instance.assert_called_once_with('a')
  556. instance.assert_called_once_with(a='a')
  557. instance('a')
  558. instance.assert_called_with('a')
  559. instance.assert_called_with(a='a')
  560. mock = create_autospec(Callable(1, 2))
  561. mock(a='a')
  562. mock.assert_called_once_with(a='a')
  563. self.assertRaises(TypeError, mock)
  564. mock('a')
  565. mock.assert_called_with('a')
  566. def test_signature_noncallable(self):
  567. class NonCallable(object):
  568. def __init__(self):
  569. pass
  570. mock = create_autospec(NonCallable)
  571. instance = mock()
  572. mock.assert_called_once_with()
  573. self.assertRaises(TypeError, mock, 'a')
  574. self.assertRaises(TypeError, instance)
  575. self.assertRaises(TypeError, instance, 'a')
  576. mock = create_autospec(NonCallable())
  577. self.assertRaises(TypeError, mock)
  578. self.assertRaises(TypeError, mock, 'a')
  579. def test_create_autospec_none(self):
  580. class Foo(object):
  581. bar = None
  582. mock = create_autospec(Foo)
  583. none = mock.bar
  584. self.assertNotIsInstance(none, type(None))
  585. none.foo()
  586. none.foo.assert_called_once_with()
  587. def test_autospec_functions_with_self_in_odd_place(self):
  588. class Foo(object):
  589. def f(a, self):
  590. pass
  591. a = create_autospec(Foo)
  592. a.f(10)
  593. a.f.assert_called_with(10)
  594. a.f.assert_called_with(self=10)
  595. a.f(self=10)
  596. a.f.assert_called_with(10)
  597. a.f.assert_called_with(self=10)
  598. def test_autospec_property(self):
  599. class Foo(object):
  600. @property
  601. def foo(self):
  602. return 3
  603. foo = create_autospec(Foo)
  604. mock_property = foo.foo
  605. # no spec on properties
  606. self.assertIsInstance(mock_property, MagicMock)
  607. mock_property(1, 2, 3)
  608. mock_property.abc(4, 5, 6)
  609. mock_property.assert_called_once_with(1, 2, 3)
  610. mock_property.abc.assert_called_once_with(4, 5, 6)
  611. def test_autospec_slots(self):
  612. class Foo(object):
  613. __slots__ = ['a']
  614. foo = create_autospec(Foo)
  615. mock_slot = foo.a
  616. # no spec on slots
  617. mock_slot(1, 2, 3)
  618. mock_slot.abc(4, 5, 6)
  619. mock_slot.assert_called_once_with(1, 2, 3)
  620. mock_slot.abc.assert_called_once_with(4, 5, 6)
  621. class TestCallList(unittest.TestCase):
  622. def test_args_list_contains_call_list(self):
  623. mock = Mock()
  624. self.assertIsInstance(mock.call_args_list, _CallList)
  625. mock(1, 2)
  626. mock(a=3)
  627. mock(3, 4)
  628. mock(b=6)
  629. for kall in call(1, 2), call(a=3), call(3, 4), call(b=6):
  630. self.assertIn(kall, mock.call_args_list)
  631. calls = [call(a=3), call(3, 4)]
  632. self.assertIn(calls, mock.call_args_list)
  633. calls = [call(1, 2), call(a=3)]
  634. self.assertIn(calls, mock.call_args_list)
  635. calls = [call(3, 4), call(b=6)]
  636. self.assertIn(calls, mock.call_args_list)
  637. calls = [call(3, 4)]
  638. self.assertIn(calls, mock.call_args_list)
  639. self.assertNotIn(call('fish'), mock.call_args_list)
  640. self.assertNotIn([call('fish')], mock.call_args_list)
  641. def test_call_list_str(self):
  642. mock = Mock()
  643. mock(1, 2)
  644. mock.foo(a=3)
  645. mock.foo.bar().baz('fish', cat='dog')
  646. expected = (
  647. "[call(1, 2),\n"
  648. " call.foo(a=3),\n"
  649. " call.foo.bar(),\n"
  650. " call.foo.bar().baz('fish', cat='dog')]"
  651. )
  652. self.assertEqual(str(mock.mock_calls), expected)
  653. def test_propertymock(self):
  654. p = patch('%s.SomeClass.one' % __name__, new_callable=PropertyMock)
  655. mock = p.start()
  656. try:
  657. SomeClass.one
  658. mock.assert_called_once_with()
  659. s = SomeClass()
  660. s.one
  661. mock.assert_called_with()
  662. self.assertEqual(mock.mock_calls, [call(), call()])
  663. s.one = 3
  664. self.assertEqual(mock.mock_calls, [call(), call(), call(3)])
  665. finally:
  666. p.stop()
  667. def test_propertymock_returnvalue(self):
  668. m = MagicMock()
  669. p = PropertyMock()
  670. type(m).foo = p
  671. returned = m.foo
  672. p.assert_called_once_with()
  673. self.assertIsInstance(returned, MagicMock)
  674. self.assertNotIsInstance(returned, PropertyMock)
  675. if __name__ == '__main__':
  676. unittest.main()