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