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