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