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