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