Debian Codegraph @

Lib/test/test_unittest/testmock/testpatch.py

raw
1 # Copyright (C) 2007-2012 Michael Foord & the mock team
2 # E-mail: fuzzyman AT voidspace DOT org DOT uk
3 # http://www.voidspace.org.uk/python/mock/
4
5 import os
6 import sys
7 from collections import OrderedDict
8
9 import unittest
10 import test
11 from test.test_unittest.testmock import support
12 from test.test_unittest.testmock.support import SomeClass, is_instance
13
14 from test.support.import_helper import DirsOnSysPath
15 from test.test_importlib.util import uncache
16 from unittest.mock import (
17 NonCallableMock, CallableMixin, sentinel,
18 MagicMock, Mock, NonCallableMagicMock, patch, _patch,
19 DEFAULT, call, _get_target
20 )
21
22
23 builtin_string = 'builtins'
24
25 PTModule = sys.modules[__name__]
26 MODNAME = '%s.PTModule' % __name__
27
28
29 def _get_proxy(obj, get_only=True):
30 class Proxy(object):
31 def __getattr__(self, name):
32 return getattr(obj, name)
33 if not get_only:
34 def __setattr__(self, name, value):
35 setattr(obj, name, value)
36 def __delattr__(self, name):
37 delattr(obj, name)
38 Proxy.__setattr__ = __setattr__
39 Proxy.__delattr__ = __delattr__
40 return Proxy()
41
42
43 # for use in the test
44 something = sentinel.Something
45 something_else = sentinel.SomethingElse
46
47
48 class Foo(object):
49 def __init__(self, a): pass
50 def f(self, a): pass
51 def g(self): pass
52 foo = 'bar'
53
54 @staticmethod
55 def static_method(): pass
56
57 @classmethod
58 def class_method(cls): pass
59
60 class Bar(object):
61 def a(self): pass
62
63 foo_name = '%s.Foo' % __name__
64
65
66 def function(a, b=Foo): pass
67
68
69 class Container(object):
70 def __init__(self):
71 self.values = {}
72
73 def __getitem__(self, name):
74 return self.values[name]
75
76 def __setitem__(self, name, value):
77 self.values[name] = value
78
79 def __delitem__(self, name):
80 del self.values[name]
81
82 def __iter__(self):
83 return iter(self.values)
84
85
86
87 class PatchTest(unittest.TestCase):
88
89 def assertNotCallable(self, obj, magic=True):
90 MockClass = NonCallableMagicMock
91 if not magic:
92 MockClass = NonCallableMock
93
94 self.assertRaises(TypeError, obj)
95 self.assertTrue(is_instance(obj, MockClass))
96 self.assertFalse(is_instance(obj, CallableMixin))
97
98
99 def test_single_patchobject(self):
100 class Something(object):
101 attribute = sentinel.Original
102
103 @patch.object(Something, 'attribute', sentinel.Patched)
104 def test():
105 self.assertEqual(Something.attribute, sentinel.Patched, "unpatched")
106
107 test()
108 self.assertEqual(Something.attribute, sentinel.Original,
109 "patch not restored")
110
111 def test_patchobject_with_string_as_target(self):
112 msg = "'Something' must be the actual object to be patched, not a str"
113 with self.assertRaisesRegex(TypeError, msg):
114 patch.object('Something', 'do_something')
115
116 def test_patchobject_with_none(self):
117 class Something(object):
118 attribute = sentinel.Original
119
120 @patch.object(Something, 'attribute', None)
121 def test():
122 self.assertIsNone(Something.attribute, "unpatched")
123
124 test()
125 self.assertEqual(Something.attribute, sentinel.Original,
126 "patch not restored")
127
128
129 def test_multiple_patchobject(self):
130 class Something(object):
131 attribute = sentinel.Original
132 next_attribute = sentinel.Original2
133
134 @patch.object(Something, 'attribute', sentinel.Patched)
135 @patch.object(Something, 'next_attribute', sentinel.Patched2)
136 def test():
137 self.assertEqual(Something.attribute, sentinel.Patched,
138 "unpatched")
139 self.assertEqual(Something.next_attribute, sentinel.Patched2,
140 "unpatched")
141
142 test()
143 self.assertEqual(Something.attribute, sentinel.Original,
144 "patch not restored")
145 self.assertEqual(Something.next_attribute, sentinel.Original2,
146 "patch not restored")
147
148
149 def test_object_lookup_is_quite_lazy(self):
150 global something
151 original = something
152 @patch('%s.something' % __name__, sentinel.Something2)
153 def test():
154 pass
155
156 try:
157 something = sentinel.replacement_value
158 test()
159 self.assertEqual(something, sentinel.replacement_value)
160 finally:
161 something = original
162
163
164 def test_patch(self):
165 @patch('%s.something' % __name__, sentinel.Something2)
166 def test():
167 self.assertEqual(PTModule.something, sentinel.Something2,
168 "unpatched")
169
170 test()
171 self.assertEqual(PTModule.something, sentinel.Something,
172 "patch not restored")
173
174 @patch('%s.something' % __name__, sentinel.Something2)
175 @patch('%s.something_else' % __name__, sentinel.SomethingElse)
176 def test():
177 self.assertEqual(PTModule.something, sentinel.Something2,
178 "unpatched")
179 self.assertEqual(PTModule.something_else, sentinel.SomethingElse,
180 "unpatched")
181
182 self.assertEqual(PTModule.something, sentinel.Something,
183 "patch not restored")
184 self.assertEqual(PTModule.something_else, sentinel.SomethingElse,
185 "patch not restored")
186
187 # Test the patching and restoring works a second time
188 test()
189
190 self.assertEqual(PTModule.something, sentinel.Something,
191 "patch not restored")
192 self.assertEqual(PTModule.something_else, sentinel.SomethingElse,
193 "patch not restored")
194
195 mock = Mock()
196 mock.return_value = sentinel.Handle
197 @patch('%s.open' % builtin_string, mock)
198 def test():
199 self.assertEqual(open('filename', 'r'), sentinel.Handle,
200 "open not patched")
201 test()
202 test()
203
204 self.assertNotEqual(open, mock, "patch not restored")
205
206
207 def test_patch_class_attribute(self):
208 @patch('%s.SomeClass.class_attribute' % __name__,
209 sentinel.ClassAttribute)
210 def test():
211 self.assertEqual(PTModule.SomeClass.class_attribute,
212 sentinel.ClassAttribute, "unpatched")
213 test()
214
215 self.assertIsNone(PTModule.SomeClass.class_attribute,
216 "patch not restored")
217
218
219 def test_patchobject_with_default_mock(self):
220 class Test(object):
221 something = sentinel.Original
222 something2 = sentinel.Original2
223
224 @patch.object(Test, 'something')
225 def test(mock):
226 self.assertEqual(mock, Test.something,
227 "Mock not passed into test function")
228 self.assertIsInstance(mock, MagicMock,
229 "patch with two arguments did not create a mock")
230
231 test()
232
233 @patch.object(Test, 'something')
234 @patch.object(Test, 'something2')
235 def test(this1, this2, mock1, mock2):
236 self.assertEqual(this1, sentinel.this1,
237 "Patched function didn't receive initial argument")
238 self.assertEqual(this2, sentinel.this2,
239 "Patched function didn't receive second argument")
240 self.assertEqual(mock1, Test.something2,
241 "Mock not passed into test function")
242 self.assertEqual(mock2, Test.something,
243 "Second Mock not passed into test function")
244 self.assertIsInstance(mock2, MagicMock,
245 "patch with two arguments did not create a mock")
246 self.assertIsInstance(mock2, MagicMock,
247 "patch with two arguments did not create a mock")
248
249 # A hack to test that new mocks are passed the second time
250 self.assertNotEqual(outerMock1, mock1, "unexpected value for mock1")
251 self.assertNotEqual(outerMock2, mock2, "unexpected value for mock1")
252 return mock1, mock2
253
254 outerMock1 = outerMock2 = None
255 outerMock1, outerMock2 = test(sentinel.this1, sentinel.this2)
256
257 # Test that executing a second time creates new mocks
258 test(sentinel.this1, sentinel.this2)
259
260
261 def test_patch_with_spec(self):
262 @patch('%s.SomeClass' % __name__, spec=SomeClass)
263 def test(MockSomeClass):
264 self.assertEqual(SomeClass, MockSomeClass)
265 self.assertTrue(is_instance(SomeClass.wibble, MagicMock))
266 self.assertRaises(AttributeError, lambda: SomeClass.not_wibble)
267
268 test()
269
270
271 def test_patchobject_with_spec(self):
272 @patch.object(SomeClass, 'class_attribute', spec=SomeClass)
273 def test(MockAttribute):
274 self.assertEqual(SomeClass.class_attribute, MockAttribute)
275 self.assertTrue(is_instance(SomeClass.class_attribute.wibble,
276 MagicMock))
277 self.assertRaises(AttributeError,
278 lambda: SomeClass.class_attribute.not_wibble)
279
280 test()
281
282
283 def test_patch_with_spec_as_list(self):
284 @patch('%s.SomeClass' % __name__, spec=['wibble'])
285 def test(MockSomeClass):
286 self.assertEqual(SomeClass, MockSomeClass)
287 self.assertTrue(is_instance(SomeClass.wibble, MagicMock))
288 self.assertRaises(AttributeError, lambda: SomeClass.not_wibble)
289
290 test()
291
292
293 def test_patchobject_with_spec_as_list(self):
294 @patch.object(SomeClass, 'class_attribute', spec=['wibble'])
295 def test(MockAttribute):
296 self.assertEqual(SomeClass.class_attribute, MockAttribute)
297 self.assertTrue(is_instance(SomeClass.class_attribute.wibble,
298 MagicMock))
299 self.assertRaises(AttributeError,
300 lambda: SomeClass.class_attribute.not_wibble)
301
302 test()
303
304
305 def test_nested_patch_with_spec_as_list(self):
306 # regression test for nested decorators
307 @patch('%s.open' % builtin_string)
308 @patch('%s.SomeClass' % __name__, spec=['wibble'])
309 def test(MockSomeClass, MockOpen):
310 self.assertEqual(SomeClass, MockSomeClass)
311 self.assertTrue(is_instance(SomeClass.wibble, MagicMock))
312 self.assertRaises(AttributeError, lambda: SomeClass.not_wibble)
313 test()
314
315
316 def test_patch_with_spec_as_boolean(self):
317 @patch('%s.SomeClass' % __name__, spec=True)
318 def test(MockSomeClass):
319 self.assertEqual(SomeClass, MockSomeClass)
320 # Should not raise attribute error
321 MockSomeClass.wibble
322
323 self.assertRaises(AttributeError, lambda: MockSomeClass.not_wibble)
324
325 test()
326
327
328 def test_patch_object_with_spec_as_boolean(self):
329 @patch.object(PTModule, 'SomeClass', spec=True)
330 def test(MockSomeClass):
331 self.assertEqual(SomeClass, MockSomeClass)
332 # Should not raise attribute error
333 MockSomeClass.wibble
334
335 self.assertRaises(AttributeError, lambda: MockSomeClass.not_wibble)
336
337 test()
338
339
340 def test_patch_class_acts_with_spec_is_inherited(self):
341 @patch('%s.SomeClass' % __name__, spec=True)
342 def test(MockSomeClass):
343 self.assertTrue(is_instance(MockSomeClass, MagicMock))
344 instance = MockSomeClass()
345 self.assertNotCallable(instance)
346 # Should not raise attribute error
347 instance.wibble
348
349 self.assertRaises(AttributeError, lambda: instance.not_wibble)
350
351 test()
352
353
354 def test_patch_with_create_mocks_non_existent_attributes(self):
355 @patch('%s.frooble' % builtin_string, sentinel.Frooble, create=True)
356 def test():
357 self.assertEqual(frooble, sentinel.Frooble)
358
359 test()
360 self.assertRaises(NameError, lambda: frooble)
361
362
363 def test_patchobject_with_create_mocks_non_existent_attributes(self):
364 @patch.object(SomeClass, 'frooble', sentinel.Frooble, create=True)
365 def test():
366 self.assertEqual(SomeClass.frooble, sentinel.Frooble)
367
368 test()
369 self.assertNotHasAttr(SomeClass, 'frooble')
370
371
372 def test_patch_wont_create_by_default(self):
373 with self.assertRaises(AttributeError):
374 @patch('%s.frooble' % builtin_string, sentinel.Frooble)
375 def test(): pass
376
377 test()
378 self.assertRaises(NameError, lambda: frooble)
379
380
381 def test_patchobject_wont_create_by_default(self):
382 with self.assertRaises(AttributeError):
383 @patch.object(SomeClass, 'ord', sentinel.Frooble)
384 def test(): pass
385 test()
386 self.assertNotHasAttr(SomeClass, 'ord')
387
388
389 def test_patch_builtins_without_create(self):
390 @patch(__name__+'.ord')
391 def test_ord(mock_ord):
392 mock_ord.return_value = 101
393 return ord('c')
394
395 @patch(__name__+'.open')
396 def test_open(mock_open):
397 m = mock_open.return_value
398 m.read.return_value = 'abcd'
399
400 fobj = open('doesnotexists.txt')
401 data = fobj.read()
402 fobj.close()
403 return data
404
405 self.assertEqual(test_ord(), 101)
406 self.assertEqual(test_open(), 'abcd')
407
408
409 def test_patch_with_static_methods(self):
410 class Foo(object):
411 @staticmethod
412 def woot():
413 return sentinel.Static
414
415 @patch.object(Foo, 'woot', staticmethod(lambda: sentinel.Patched))
416 def anonymous():
417 self.assertEqual(Foo.woot(), sentinel.Patched)
418 anonymous()
419
420 self.assertEqual(Foo.woot(), sentinel.Static)
421
422
423 def test_patch_local(self):
424 foo = sentinel.Foo
425 @patch.object(sentinel, 'Foo', 'Foo')
426 def anonymous():
427 self.assertEqual(sentinel.Foo, 'Foo')
428 anonymous()
429
430 self.assertEqual(sentinel.Foo, foo)
431
432
433 def test_patch_slots(self):
434 class Foo(object):
435 __slots__ = ('Foo',)
436
437 foo = Foo()
438 foo.Foo = sentinel.Foo
439
440 @patch.object(foo, 'Foo', 'Foo')
441 def anonymous():
442 self.assertEqual(foo.Foo, 'Foo')
443 anonymous()
444
445 self.assertEqual(foo.Foo, sentinel.Foo)
446
447
448 def test_patchobject_class_decorator(self):
449 class Something(object):
450 attribute = sentinel.Original
451
452 class Foo(object):
453 def test_method(other_self):
454 self.assertEqual(Something.attribute, sentinel.Patched,
455 "unpatched")
456 def not_test_method(other_self):
457 self.assertEqual(Something.attribute, sentinel.Original,
458 "non-test method patched")
459
460 Foo = patch.object(Something, 'attribute', sentinel.Patched)(Foo)
461
462 f = Foo()
463 f.test_method()
464 f.not_test_method()
465
466 self.assertEqual(Something.attribute, sentinel.Original,
467 "patch not restored")
468
469
470 def test_patch_class_decorator(self):
471 class Something(object):
472 attribute = sentinel.Original
473
474 class Foo(object):
475
476 test_class_attr = 'whatever'
477
478 def test_method(other_self, mock_something):
479 self.assertEqual(PTModule.something, mock_something,
480 "unpatched")
481 def not_test_method(other_self):
482 self.assertEqual(PTModule.something, sentinel.Something,
483 "non-test method patched")
484 Foo = patch('%s.something' % __name__)(Foo)
485
486 f = Foo()
487 f.test_method()
488 f.not_test_method()
489
490 self.assertEqual(Something.attribute, sentinel.Original,
491 "patch not restored")
492 self.assertEqual(PTModule.something, sentinel.Something,
493 "patch not restored")
494
495
496 def test_patchobject_twice(self):
497 class Something(object):
498 attribute = sentinel.Original
499 next_attribute = sentinel.Original2
500
501 @patch.object(Something, 'attribute', sentinel.Patched)
502 @patch.object(Something, 'attribute', sentinel.Patched)
503 def test():
504 self.assertEqual(Something.attribute, sentinel.Patched, "unpatched")
505
506 test()
507
508 self.assertEqual(Something.attribute, sentinel.Original,
509 "patch not restored")
510
511
512 def test_patch_dict(self):
513 foo = {'initial': object(), 'other': 'something'}
514 original = foo.copy()
515
516 @patch.dict(foo)
517 def test():
518 foo['a'] = 3
519 del foo['initial']
520 foo['other'] = 'something else'
521
522 test()
523
524 self.assertEqual(foo, original)
525
526 @patch.dict(foo, {'a': 'b'})
527 def test():
528 self.assertEqual(len(foo), 3)
529 self.assertEqual(foo['a'], 'b')
530
531 test()
532
533 self.assertEqual(foo, original)
534
535 @patch.dict(foo, [('a', 'b')])
536 def test():
537 self.assertEqual(len(foo), 3)
538 self.assertEqual(foo['a'], 'b')
539
540 test()
541
542 self.assertEqual(foo, original)
543
544
545 def test_patch_dict_with_container_object(self):
546 foo = Container()
547 foo['initial'] = object()
548 foo['other'] = 'something'
549
550 original = foo.values.copy()
551
552 @patch.dict(foo)
553 def test():
554 foo['a'] = 3
555 del foo['initial']
556 foo['other'] = 'something else'
557
558 test()
559
560 self.assertEqual(foo.values, original)
561
562 @patch.dict(foo, {'a': 'b'})
563 def test():
564 self.assertEqual(len(foo.values), 3)
565 self.assertEqual(foo['a'], 'b')
566
567 test()
568
569 self.assertEqual(foo.values, original)
570
571
572 def test_patch_dict_with_clear(self):
573 foo = {'initial': object(), 'other': 'something'}
574 original = foo.copy()
575
576 @patch.dict(foo, clear=True)
577 def test():
578 self.assertEqual(foo, {})
579 foo['a'] = 3
580 foo['other'] = 'something else'
581
582 test()
583
584 self.assertEqual(foo, original)
585
586 @patch.dict(foo, {'a': 'b'}, clear=True)
587 def test():
588 self.assertEqual(foo, {'a': 'b'})
589
590 test()
591
592 self.assertEqual(foo, original)
593
594 @patch.dict(foo, [('a', 'b')], clear=True)
595 def test():
596 self.assertEqual(foo, {'a': 'b'})
597
598 test()
599
600 self.assertEqual(foo, original)
601
602
603 def test_patch_dict_with_container_object_and_clear(self):
604 foo = Container()
605 foo['initial'] = object()
606 foo['other'] = 'something'
607
608 original = foo.values.copy()
609
610 @patch.dict(foo, clear=True)
611 def test():
612 self.assertEqual(foo.values, {})
613 foo['a'] = 3
614 foo['other'] = 'something else'
615
616 test()
617
618 self.assertEqual(foo.values, original)
619
620 @patch.dict(foo, {'a': 'b'}, clear=True)
621 def test():
622 self.assertEqual(foo.values, {'a': 'b'})
623
624 test()
625
626 self.assertEqual(foo.values, original)
627
628
629 def test_patch_dict_as_context_manager(self):
630 foo = {'a': 'b'}
631 with patch.dict(foo, a='c') as patched:
632 self.assertEqual(patched, {'a': 'c'})
633 self.assertEqual(foo, {'a': 'b'})
634
635
636 def test_name_preserved(self):
637 foo = {}
638
639 @patch('%s.SomeClass' % __name__, object())
640 @patch('%s.SomeClass' % __name__, object(), autospec=True)
641 @patch.object(SomeClass, object())
642 @patch.dict(foo)
643 def some_name(): pass
644
645 self.assertEqual(some_name.__name__, 'some_name')
646
647
648 def test_patch_with_exception(self):
649 foo = {}
650
651 @patch.dict(foo, {'a': 'b'})
652 def test():
653 raise NameError('Konrad')
654
655 with self.assertRaises(NameError):
656 test()
657
658 self.assertEqual(foo, {})
659
660
661 def test_patch_dict_with_string(self):
662 @patch.dict('os.environ', {'konrad_delong': 'some value'})
663 def test():
664 self.assertIn('konrad_delong', os.environ)
665
666 test()
667
668
669 def test_patch_dict_decorator_resolution(self):
670 # bpo-35512: Ensure that patch with a string target resolves to
671 # the new dictionary during function call
672 original = support.target.copy()
673
674 @patch.dict('test.test_unittest.testmock.support.target', {'bar': 'BAR'})
675 def test():
676 self.assertEqual(support.target, {'foo': 'BAZ', 'bar': 'BAR'})
677
678 try:
679 support.target = {'foo': 'BAZ'}
680 test()
681 self.assertEqual(support.target, {'foo': 'BAZ'})
682 finally:
683 support.target = original
684
685
686 def test_patch_spec_set(self):
687 @patch('%s.SomeClass' % __name__, spec=SomeClass, spec_set=True)
688 def test(MockClass):
689 MockClass.z = 'foo'
690
691 self.assertRaises(AttributeError, test)
692
693 @patch.object(support, 'SomeClass', spec=SomeClass, spec_set=True)
694 def test(MockClass):
695 MockClass.z = 'foo'
696
697 self.assertRaises(AttributeError, test)
698 @patch('%s.SomeClass' % __name__, spec_set=True)
699 def test(MockClass):
700 MockClass.z = 'foo'
701
702 self.assertRaises(AttributeError, test)
703
704 @patch.object(support, 'SomeClass', spec_set=True)
705 def test(MockClass):
706 MockClass.z = 'foo'
707
708 self.assertRaises(AttributeError, test)
709
710
711 def test_spec_set_inherit(self):
712 @patch('%s.SomeClass' % __name__, spec_set=True)
713 def test(MockClass):
714 instance = MockClass()
715 instance.z = 'foo'
716
717 self.assertRaises(AttributeError, test)
718
719
720 def test_patch_start_stop(self):
721 original = something
722 patcher = patch('%s.something' % __name__)
723 self.assertIs(something, original)
724 mock = patcher.start()
725 try:
726 self.assertIsNot(mock, original)
727 self.assertIs(something, mock)
728 finally:
729 patcher.stop()
730 self.assertIs(something, original)
731
732
733 def test_stop_without_start(self):
734 # bpo-36366: calling stop without start will return None.
735 patcher = patch(foo_name, 'bar', 3)
736 self.assertIsNone(patcher.stop())
737
738
739 def test_stop_idempotent(self):
740 # bpo-36366: calling stop on an already stopped patch will return None.
741 patcher = patch(foo_name, 'bar', 3)
742
743 patcher.start()
744 patcher.stop()
745 self.assertIsNone(patcher.stop())
746
747
748 def test_exit_idempotent(self):
749 patcher = patch(foo_name, 'bar', 3)
750 with patcher:
751 patcher.__exit__(None, None, None)
752
753
754 def test_second_start_failure(self):
755 patcher = patch(foo_name, 'bar', 3)
756 patcher.start()
757 try:
758 self.assertRaises(RuntimeError, patcher.start)
759 finally:
760 patcher.stop()
761
762
763 def test_second_enter_failure(self):
764 patcher = patch(foo_name, 'bar', 3)
765 with patcher:
766 self.assertRaises(RuntimeError, patcher.start)
767
768
769 def test_second_start_after_stop(self):
770 patcher = patch(foo_name, 'bar', 3)
771 patcher.start()
772 patcher.stop()
773 patcher.start()
774 patcher.stop()
775
776
777 def test_property_setters(self):
778 mock_object = Mock()
779 mock_bar = mock_object.bar
780 patcher = patch.object(mock_object, 'bar', 'x')
781 with patcher:
782 self.assertEqual(patcher.is_local, False)
783 self.assertIs(patcher.target, mock_object)
784 self.assertEqual(patcher.temp_original, mock_bar)
785 patcher.is_local = True
786 patcher.target = mock_bar
787 patcher.temp_original = mock_object
788 self.assertEqual(patcher.is_local, True)
789 self.assertIs(patcher.target, mock_bar)
790 self.assertEqual(patcher.temp_original, mock_object)
791 # if changes are left intact, they may lead to disruption as shown below (it might be what someone needs though)
792 self.assertEqual(mock_bar.bar, mock_object)
793 self.assertEqual(mock_object.bar, 'x')
794
795
796 def test_patchobject_start_stop(self):
797 original = something
798 patcher = patch.object(PTModule, 'something', 'foo')
799 self.assertIs(something, original)
800 replaced = patcher.start()
801 try:
802 self.assertEqual(replaced, 'foo')
803 self.assertIs(something, replaced)
804 finally:
805 patcher.stop()
806 self.assertIs(something, original)
807
808
809 def test_patch_dict_start_stop(self):
810 d = {'foo': 'bar'}
811 original = d.copy()
812 patcher = patch.dict(d, [('spam', 'eggs')], clear=True)
813 self.assertEqual(d, original)
814
815 patcher.start()
816 try:
817 self.assertEqual(d, {'spam': 'eggs'})
818 finally:
819 patcher.stop()
820 self.assertEqual(d, original)
821
822
823 def test_patch_dict_stop_without_start(self):
824 d = {'foo': 'bar'}
825 original = d.copy()
826 patcher = patch.dict(d, [('spam', 'eggs')], clear=True)
827 self.assertFalse(patcher.stop())
828 self.assertEqual(d, original)
829
830
831 def test_patch_dict_class_decorator(self):
832 this = self
833 d = {'spam': 'eggs'}
834 original = d.copy()
835
836 class Test(object):
837 def test_first(self):
838 this.assertEqual(d, {'foo': 'bar'})
839 def test_second(self):
840 this.assertEqual(d, {'foo': 'bar'})
841
842 Test = patch.dict(d, {'foo': 'bar'}, clear=True)(Test)
843 self.assertEqual(d, original)
844
845 test = Test()
846
847 test.test_first()
848 self.assertEqual(d, original)
849
850 test.test_second()
851 self.assertEqual(d, original)
852
853 test = Test()
854
855 test.test_first()
856 self.assertEqual(d, original)
857
858 test.test_second()
859 self.assertEqual(d, original)
860
861
862 def test_get_only_proxy(self):
863 class Something(object):
864 foo = 'foo'
865 class SomethingElse:
866 foo = 'foo'
867
868 for thing in Something, SomethingElse, Something(), SomethingElse:
869 proxy = _get_proxy(thing)
870
871 @patch.object(proxy, 'foo', 'bar')
872 def test():
873 self.assertEqual(proxy.foo, 'bar')
874 test()
875 self.assertEqual(proxy.foo, 'foo')
876 self.assertEqual(thing.foo, 'foo')
877 self.assertNotIn('foo', proxy.__dict__)
878
879
880 def test_get_set_delete_proxy(self):
881 class Something(object):
882 foo = 'foo'
883 class SomethingElse:
884 foo = 'foo'
885
886 for thing in Something, SomethingElse, Something(), SomethingElse:
887 proxy = _get_proxy(Something, get_only=False)
888
889 @patch.object(proxy, 'foo', 'bar')
890 def test():
891 self.assertEqual(proxy.foo, 'bar')
892 test()
893 self.assertEqual(proxy.foo, 'foo')
894 self.assertEqual(thing.foo, 'foo')
895 self.assertNotIn('foo', proxy.__dict__)
896
897
898 def test_patch_keyword_args(self):
899 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
900 'foo': MagicMock()}
901
902 patcher = patch(foo_name, **kwargs)
903 mock = patcher.start()
904 patcher.stop()
905
906 self.assertRaises(KeyError, mock)
907 self.assertEqual(mock.foo.bar(), 33)
908 self.assertIsInstance(mock.foo, MagicMock)
909
910
911 def test_patch_object_keyword_args(self):
912 kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,
913 'foo': MagicMock()}
914
915 patcher = patch.object(Foo, 'f', **kwargs)
916 mock = patcher.start()
917 patcher.stop()
918
919 self.assertRaises(KeyError, mock)
920 self.assertEqual(mock.foo.bar(), 33)
921 self.assertIsInstance(mock.foo, MagicMock)
922
923
924 def test_patch_dict_keyword_args(self):
925 original = {'foo': 'bar'}
926 copy = original.copy()
927
928 patcher = patch.dict(original, foo=3, bar=4, baz=5)
929 patcher.start()
930
931 try:
932 self.assertEqual(original, dict(foo=3, bar=4, baz=5))
933 finally:
934 patcher.stop()
935
936 self.assertEqual(original, copy)
937
938
939 def test_autospec(self):
940 class Boo(object):
941 def __init__(self, a): pass
942 def f(self, a): pass
943 def g(self): pass
944 foo = 'bar'
945
946 class Bar(object):
947 def a(self): pass
948
949 def _test(mock):
950 mock(1)
951 mock.assert_called_with(1)
952 self.assertRaises(TypeError, mock)
953
954 def _test2(mock):
955 mock.f(1)
956 mock.f.assert_called_with(1)
957 self.assertRaises(TypeError, mock.f)
958
959 mock.g()
960 mock.g.assert_called_with()
961 self.assertRaises(TypeError, mock.g, 1)
962
963 self.assertRaises(AttributeError, getattr, mock, 'h')
964
965 mock.foo.lower()
966 mock.foo.lower.assert_called_with()
967 self.assertRaises(AttributeError, getattr, mock.foo, 'bar')
968
969 mock.Bar()
970 mock.Bar.assert_called_with()
971
972 mock.Bar.a()
973 mock.Bar.a.assert_called_with()
974 self.assertRaises(TypeError, mock.Bar.a, 1)
975
976 mock.Bar().a()
977 mock.Bar().a.assert_called_with()
978 self.assertRaises(TypeError, mock.Bar().a, 1)
979
980 self.assertRaises(AttributeError, getattr, mock.Bar, 'b')
981 self.assertRaises(AttributeError, getattr, mock.Bar(), 'b')
982
983 def function(mock):
984 _test(mock)
985 _test2(mock)
986 _test2(mock(1))
987 self.assertIs(mock, Foo)
988 return mock
989
990 test = patch(foo_name, autospec=True)(function)
991
992 mock = test()
993 self.assertIsNot(Foo, mock)
994 # test patching a second time works
995 test()
996
997 module = sys.modules[__name__]
998 test = patch.object(module, 'Foo', autospec=True)(function)
999
1000 mock = test()
1001 self.assertIsNot(Foo, mock)
1002 # test patching a second time works
1003 test()
1004
1005
1006 def test_autospec_function(self):
1007 @patch('%s.function' % __name__, autospec=True)
1008 def test(mock):
1009 function.assert_not_called()
1010 self.assertRaises(AssertionError, function.assert_called)
1011 self.assertRaises(AssertionError, function.assert_called_once)
1012 function(1)
1013 self.assertRaises(AssertionError, function.assert_not_called)
1014 function.assert_called_with(1)
1015 function.assert_called()
1016 function.assert_called_once()
1017 function(2, 3)
1018 function.assert_called_with(2, 3)
1019
1020 self.assertRaises(TypeError, function)
1021 self.assertRaises(AttributeError, getattr, function, 'foo')
1022
1023 test()
1024
1025
1026 def test_autospec_keywords(self):
1027 @patch('%s.function' % __name__, autospec=True,
1028 return_value=3)
1029 def test(mock_function):
1030 #self.assertEqual(function.abc, 'foo')
1031 return function(1, 2)
1032
1033 result = test()
1034 self.assertEqual(result, 3)
1035
1036
1037 def test_autospec_staticmethod(self):
1038 with patch('%s.Foo.static_method' % __name__, autospec=True) as method:
1039 Foo.static_method()
1040 method.assert_called_once_with()
1041
1042
1043 def test_autospec_classmethod(self):
1044 with patch('%s.Foo.class_method' % __name__, autospec=True) as method:
1045 Foo.class_method()
1046 method.assert_called_once_with()
1047
1048
1049 def test_autospec_staticmethod_signature(self):
1050 # Patched methods which are decorated with @staticmethod should have the same signature
1051 class Foo:
1052 @staticmethod
1053 def static_method(a, b=10, *, c): pass
1054
1055 Foo.static_method(1, 2, c=3)
1056
1057 with patch.object(Foo, 'static_method', autospec=True) as method:
1058 method(1, 2, c=3)
1059 self.assertRaises(TypeError, method)
1060 self.assertRaises(TypeError, method, 1)
1061 self.assertRaises(TypeError, method, 1, 2, 3, c=4)
1062
1063
1064 def test_autospec_classmethod_signature(self):
1065 # Patched methods which are decorated with @classmethod should have the same signature
1066 class Foo:
1067 @classmethod
1068 def class_method(cls, a, b=10, *, c): pass
1069
1070 Foo.class_method(1, 2, c=3)
1071
1072 with patch.object(Foo, 'class_method', autospec=True) as method:
1073 method(1, 2, c=3)
1074 self.assertRaises(TypeError, method)
1075 self.assertRaises(TypeError, method, 1)
1076 self.assertRaises(TypeError, method, 1, 2, 3, c=4)
1077
1078
1079 def test_autospec_with_new(self):
1080 patcher = patch('%s.function' % __name__, new=3, autospec=True)
1081 self.assertRaises(TypeError, patcher.start)
1082
1083 module = sys.modules[__name__]
1084 patcher = patch.object(module, 'function', new=3, autospec=True)
1085 self.assertRaises(TypeError, patcher.start)
1086
1087
1088 def test_autospec_with_object(self):
1089 class Bar(Foo):
1090 extra = []
1091
1092 patcher = patch(foo_name, autospec=Bar)
1093 mock = patcher.start()
1094 try:
1095 self.assertIsInstance(mock, Bar)
1096 self.assertIsInstance(mock.extra, list)
1097 finally:
1098 patcher.stop()
1099
1100
1101 def test_autospec_inherits(self):
1102 FooClass = Foo
1103 patcher = patch(foo_name, autospec=True)
1104 mock = patcher.start()
1105 try:
1106 self.assertIsInstance(mock, FooClass)
1107 self.assertIsInstance(mock(3), FooClass)
1108 finally:
1109 patcher.stop()
1110
1111
1112 def test_autospec_name(self):
1113 patcher = patch(foo_name, autospec=True)
1114 mock = patcher.start()
1115
1116 try:
1117 self.assertIn(" name='Foo'", repr(mock))
1118 self.assertIn(" name='Foo.f'", repr(mock.f))
1119 self.assertIn(" name='Foo()'", repr(mock(None)))
1120 self.assertIn(" name='Foo().f'", repr(mock(None).f))
1121 finally:
1122 patcher.stop()
1123
1124
1125 def test_tracebacks(self):
1126 @patch.object(Foo, 'f', object())
1127 def test():
1128 raise AssertionError
1129 try:
1130 test()
1131 except:
1132 err = sys.exc_info()
1133
1134 result = unittest.TextTestResult(None, None, 0)
1135 traceback = result._exc_info_to_string(err, self)
1136 self.assertIn('raise AssertionError', traceback)
1137
1138
1139 def test_new_callable_patch(self):
1140 patcher = patch(foo_name, new_callable=NonCallableMagicMock)
1141
1142 m1 = patcher.start()
1143 patcher.stop()
1144 m2 = patcher.start()
1145 patcher.stop()
1146
1147 self.assertIsNot(m1, m2)
1148 for mock in m1, m2:
1149 self.assertNotCallable(mock)
1150
1151
1152 def test_new_callable_patch_object(self):
1153 patcher = patch.object(Foo, 'f', new_callable=NonCallableMagicMock)
1154
1155 m1 = patcher.start()
1156 patcher.stop()
1157 m2 = patcher.start()
1158 patcher.stop()
1159
1160 self.assertIsNot(m1, m2)
1161 for mock in m1, m2:
1162 self.assertNotCallable(mock)
1163
1164
1165 def test_new_callable_keyword_arguments(self):
1166 class Bar(object):
1167 kwargs = None
1168 def __init__(self, **kwargs):
1169 Bar.kwargs = kwargs
1170
1171 patcher = patch(foo_name, new_callable=Bar, arg1=1, arg2=2)
1172 m = patcher.start()
1173 try:
1174 self.assertIs(type(m), Bar)
1175 self.assertEqual(Bar.kwargs, dict(arg1=1, arg2=2))
1176 finally:
1177 patcher.stop()
1178
1179
1180 def test_new_callable_spec(self):
1181 class Bar(object):
1182 kwargs = None
1183 def __init__(self, **kwargs):
1184 Bar.kwargs = kwargs
1185
1186 patcher = patch(foo_name, new_callable=Bar, spec=Bar)
1187 patcher.start()
1188 try:
1189 self.assertEqual(Bar.kwargs, dict(spec=Bar))
1190 finally:
1191 patcher.stop()
1192
1193 patcher = patch(foo_name, new_callable=Bar, spec_set=Bar)
1194 patcher.start()
1195 try:
1196 self.assertEqual(Bar.kwargs, dict(spec_set=Bar))
1197 finally:
1198 patcher.stop()
1199
1200
1201 def test_new_callable_create(self):
1202 non_existent_attr = '%s.weeeee' % foo_name
1203 p = patch(non_existent_attr, new_callable=NonCallableMock)
1204 self.assertRaises(AttributeError, p.start)
1205
1206 p = patch(non_existent_attr, new_callable=NonCallableMock,
1207 create=True)
1208 m = p.start()
1209 try:
1210 self.assertNotCallable(m, magic=False)
1211 finally:
1212 p.stop()
1213
1214
1215 def test_new_callable_incompatible_with_new(self):
1216 self.assertRaises(
1217 ValueError, patch, foo_name, new=object(), new_callable=MagicMock
1218 )
1219 self.assertRaises(
1220 ValueError, patch.object, Foo, 'f', new=object(),
1221 new_callable=MagicMock
1222 )
1223
1224
1225 def test_new_callable_incompatible_with_autospec(self):
1226 self.assertRaises(
1227 ValueError, patch, foo_name, new_callable=MagicMock,
1228 autospec=True
1229 )
1230 self.assertRaises(
1231 ValueError, patch.object, Foo, 'f', new_callable=MagicMock,
1232 autospec=True
1233 )
1234
1235
1236 def test_new_callable_inherit_for_mocks(self):
1237 class MockSub(Mock):
1238 pass
1239
1240 MockClasses = (
1241 NonCallableMock, NonCallableMagicMock, MagicMock, Mock, MockSub
1242 )
1243 for Klass in MockClasses:
1244 for arg in 'spec', 'spec_set':
1245 kwargs = {arg: True}
1246 p = patch(foo_name, new_callable=Klass, **kwargs)
1247 m = p.start()
1248 try:
1249 instance = m.return_value
1250 self.assertRaises(AttributeError, getattr, instance, 'x')
1251 finally:
1252 p.stop()
1253
1254
1255 def test_new_callable_inherit_non_mock(self):
1256 class NotAMock(object):
1257 def __init__(self, spec):
1258 self.spec = spec
1259
1260 p = patch(foo_name, new_callable=NotAMock, spec=True)
1261 m = p.start()
1262 try:
1263 self.assertTrue(is_instance(m, NotAMock))
1264 self.assertRaises(AttributeError, getattr, m, 'return_value')
1265 finally:
1266 p.stop()
1267
1268 self.assertEqual(m.spec, Foo)
1269
1270
1271 def test_new_callable_class_decorating(self):
1272 test = self
1273 original = Foo
1274 class SomeTest(object):
1275
1276 def _test(self, mock_foo):
1277 test.assertIsNot(Foo, original)
1278 test.assertIs(Foo, mock_foo)
1279 test.assertIsInstance(Foo, SomeClass)
1280
1281 def test_two(self, mock_foo):
1282 self._test(mock_foo)
1283 def test_one(self, mock_foo):
1284 self._test(mock_foo)
1285
1286 SomeTest = patch(foo_name, new_callable=SomeClass)(SomeTest)
1287 SomeTest().test_one()
1288 SomeTest().test_two()
1289 self.assertIs(Foo, original)
1290
1291
1292 def test_patch_multiple(self):
1293 original_foo = Foo
1294 original_f = Foo.f
1295 original_g = Foo.g
1296
1297 patcher1 = patch.multiple(foo_name, f=1, g=2)
1298 patcher2 = patch.multiple(Foo, f=1, g=2)
1299
1300 for patcher in patcher1, patcher2:
1301 patcher.start()
1302 try:
1303 self.assertIs(Foo, original_foo)
1304 self.assertEqual(Foo.f, 1)
1305 self.assertEqual(Foo.g, 2)
1306 finally:
1307 patcher.stop()
1308
1309 self.assertIs(Foo, original_foo)
1310 self.assertEqual(Foo.f, original_f)
1311 self.assertEqual(Foo.g, original_g)
1312
1313
1314 @patch.multiple(foo_name, f=3, g=4)
1315 def test():
1316 self.assertIs(Foo, original_foo)
1317 self.assertEqual(Foo.f, 3)
1318 self.assertEqual(Foo.g, 4)
1319
1320 test()
1321
1322
1323 def test_patch_multiple_no_kwargs(self):
1324 self.assertRaises(ValueError, patch.multiple, foo_name)
1325 self.assertRaises(ValueError, patch.multiple, Foo)
1326
1327
1328 def test_patch_multiple_create_mocks(self):
1329 original_foo = Foo
1330 original_f = Foo.f
1331 original_g = Foo.g
1332
1333 @patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT)
1334 def test(f, foo):
1335 self.assertIs(Foo, original_foo)
1336 self.assertIs(Foo.f, f)
1337 self.assertEqual(Foo.g, 3)
1338 self.assertIs(Foo.foo, foo)
1339 self.assertTrue(is_instance(f, MagicMock))
1340 self.assertTrue(is_instance(foo, MagicMock))
1341
1342 test()
1343 self.assertEqual(Foo.f, original_f)
1344 self.assertEqual(Foo.g, original_g)
1345
1346
1347 def test_patch_multiple_create_mocks_different_order(self):
1348 original_f = Foo.f
1349 original_g = Foo.g
1350
1351 patcher = patch.object(Foo, 'f', 3)
1352 patcher.attribute_name = 'f'
1353
1354 other = patch.object(Foo, 'g', DEFAULT)
1355 other.attribute_name = 'g'
1356 patcher.additional_patchers = [other]
1357
1358 @patcher
1359 def test(g):
1360 self.assertIs(Foo.g, g)
1361 self.assertEqual(Foo.f, 3)
1362
1363 test()
1364 self.assertEqual(Foo.f, original_f)
1365 self.assertEqual(Foo.g, original_g)
1366
1367
1368 def test_patch_multiple_stacked_decorators(self):
1369 original_foo = Foo
1370 original_f = Foo.f
1371 original_g = Foo.g
1372
1373 @patch.multiple(foo_name, f=DEFAULT)
1374 @patch.multiple(foo_name, foo=DEFAULT)
1375 @patch(foo_name + '.g')
1376 def test1(g, **kwargs):
1377 _test(g, **kwargs)
1378
1379 @patch.multiple(foo_name, f=DEFAULT)
1380 @patch(foo_name + '.g')
1381 @patch.multiple(foo_name, foo=DEFAULT)
1382 def test2(g, **kwargs):
1383 _test(g, **kwargs)
1384
1385 @patch(foo_name + '.g')
1386 @patch.multiple(foo_name, f=DEFAULT)
1387 @patch.multiple(foo_name, foo=DEFAULT)
1388 def test3(g, **kwargs):
1389 _test(g, **kwargs)
1390
1391 def _test(g, **kwargs):
1392 f = kwargs.pop('f')
1393 foo = kwargs.pop('foo')
1394 self.assertFalse(kwargs)
1395
1396 self.assertIs(Foo, original_foo)
1397 self.assertIs(Foo.f, f)
1398 self.assertIs(Foo.g, g)
1399 self.assertIs(Foo.foo, foo)
1400 self.assertTrue(is_instance(f, MagicMock))
1401 self.assertTrue(is_instance(g, MagicMock))
1402 self.assertTrue(is_instance(foo, MagicMock))
1403
1404 test1()
1405 test2()
1406 test3()
1407 self.assertEqual(Foo.f, original_f)
1408 self.assertEqual(Foo.g, original_g)
1409
1410
1411 def test_patch_multiple_create_mocks_patcher(self):
1412 original_foo = Foo
1413 original_f = Foo.f
1414 original_g = Foo.g
1415
1416 patcher = patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT)
1417
1418 result = patcher.start()
1419 try:
1420 f = result['f']
1421 foo = result['foo']
1422 self.assertEqual(set(result), set(['f', 'foo']))
1423
1424 self.assertIs(Foo, original_foo)
1425 self.assertIs(Foo.f, f)
1426 self.assertIs(Foo.foo, foo)
1427 self.assertTrue(is_instance(f, MagicMock))
1428 self.assertTrue(is_instance(foo, MagicMock))
1429 finally:
1430 patcher.stop()
1431
1432 self.assertEqual(Foo.f, original_f)
1433 self.assertEqual(Foo.g, original_g)
1434
1435
1436 def test_patch_multiple_decorating_class(self):
1437 test = self
1438 original_foo = Foo
1439 original_f = Foo.f
1440 original_g = Foo.g
1441
1442 class SomeTest(object):
1443
1444 def _test(self, f, foo):
1445 test.assertIs(Foo, original_foo)
1446 test.assertIs(Foo.f, f)
1447 test.assertEqual(Foo.g, 3)
1448 test.assertIs(Foo.foo, foo)
1449 test.assertTrue(is_instance(f, MagicMock))
1450 test.assertTrue(is_instance(foo, MagicMock))
1451
1452 def test_two(self, f, foo):
1453 self._test(f, foo)
1454 def test_one(self, f, foo):
1455 self._test(f, foo)
1456
1457 SomeTest = patch.multiple(
1458 foo_name, f=DEFAULT, g=3, foo=DEFAULT
1459 )(SomeTest)
1460
1461 thing = SomeTest()
1462 thing.test_one()
1463 thing.test_two()
1464
1465 self.assertEqual(Foo.f, original_f)
1466 self.assertEqual(Foo.g, original_g)
1467
1468
1469 def test_patch_multiple_create(self):
1470 patcher = patch.multiple(Foo, blam='blam')
1471 self.assertRaises(AttributeError, patcher.start)
1472
1473 patcher = patch.multiple(Foo, blam='blam', create=True)
1474 patcher.start()
1475 try:
1476 self.assertEqual(Foo.blam, 'blam')
1477 finally:
1478 patcher.stop()
1479
1480 self.assertNotHasAttr(Foo, 'blam')
1481
1482
1483 def test_patch_multiple_spec_set(self):
1484 # if spec_set works then we can assume that spec and autospec also
1485 # work as the underlying machinery is the same
1486 patcher = patch.multiple(Foo, foo=DEFAULT, spec_set=['a', 'b'])
1487 result = patcher.start()
1488 try:
1489 self.assertEqual(Foo.foo, result['foo'])
1490 Foo.foo.a(1)
1491 Foo.foo.b(2)
1492 Foo.foo.a.assert_called_with(1)
1493 Foo.foo.b.assert_called_with(2)
1494 self.assertRaises(AttributeError, setattr, Foo.foo, 'c', None)
1495 finally:
1496 patcher.stop()
1497
1498
1499 def test_patch_multiple_new_callable(self):
1500 class Thing(object):
1501 pass
1502
1503 patcher = patch.multiple(
1504 Foo, f=DEFAULT, g=DEFAULT, new_callable=Thing
1505 )
1506 result = patcher.start()
1507 try:
1508 self.assertIs(Foo.f, result['f'])
1509 self.assertIs(Foo.g, result['g'])
1510 self.assertIsInstance(Foo.f, Thing)
1511 self.assertIsInstance(Foo.g, Thing)
1512 self.assertIsNot(Foo.f, Foo.g)
1513 finally:
1514 patcher.stop()
1515
1516
1517 def test_nested_patch_failure(self):
1518 original_f = Foo.f
1519 original_g = Foo.g
1520
1521 @patch.object(Foo, 'g', 1)
1522 @patch.object(Foo, 'missing', 1)
1523 @patch.object(Foo, 'f', 1)
1524 def thing1(): pass
1525
1526 @patch.object(Foo, 'missing', 1)
1527 @patch.object(Foo, 'g', 1)
1528 @patch.object(Foo, 'f', 1)
1529 def thing2(): pass
1530
1531 @patch.object(Foo, 'g', 1)
1532 @patch.object(Foo, 'f', 1)
1533 @patch.object(Foo, 'missing', 1)
1534 def thing3(): pass
1535
1536 for func in thing1, thing2, thing3:
1537 self.assertRaises(AttributeError, func)
1538 self.assertEqual(Foo.f, original_f)
1539 self.assertEqual(Foo.g, original_g)
1540
1541
1542 def test_new_callable_failure(self):
1543 original_f = Foo.f
1544 original_g = Foo.g
1545 original_foo = Foo.foo
1546
1547 def crasher():
1548 raise NameError('crasher')
1549
1550 @patch.object(Foo, 'g', 1)
1551 @patch.object(Foo, 'foo', new_callable=crasher)
1552 @patch.object(Foo, 'f', 1)
1553 def thing1(): pass
1554
1555 @patch.object(Foo, 'foo', new_callable=crasher)
1556 @patch.object(Foo, 'g', 1)
1557 @patch.object(Foo, 'f', 1)
1558 def thing2(): pass
1559
1560 @patch.object(Foo, 'g', 1)
1561 @patch.object(Foo, 'f', 1)
1562 @patch.object(Foo, 'foo', new_callable=crasher)
1563 def thing3(): pass
1564
1565 for func in thing1, thing2, thing3:
1566 self.assertRaises(NameError, func)
1567 self.assertEqual(Foo.f, original_f)
1568 self.assertEqual(Foo.g, original_g)
1569 self.assertEqual(Foo.foo, original_foo)
1570
1571
1572 def test_patch_multiple_failure(self):
1573 original_f = Foo.f
1574 original_g = Foo.g
1575
1576 patcher = patch.object(Foo, 'f', 1)
1577 patcher.attribute_name = 'f'
1578
1579 good = patch.object(Foo, 'g', 1)
1580 good.attribute_name = 'g'
1581
1582 bad = patch.object(Foo, 'missing', 1)
1583 bad.attribute_name = 'missing'
1584
1585 for additionals in [good, bad], [bad, good]:
1586 patcher.additional_patchers = additionals
1587
1588 @patcher
1589 def func(): pass
1590
1591 self.assertRaises(AttributeError, func)
1592 self.assertEqual(Foo.f, original_f)
1593 self.assertEqual(Foo.g, original_g)
1594
1595
1596 def test_patch_multiple_new_callable_failure(self):
1597 original_f = Foo.f
1598 original_g = Foo.g
1599 original_foo = Foo.foo
1600
1601 def crasher():
1602 raise NameError('crasher')
1603
1604 patcher = patch.object(Foo, 'f', 1)
1605 patcher.attribute_name = 'f'
1606
1607 good = patch.object(Foo, 'g', 1)
1608 good.attribute_name = 'g'
1609
1610 bad = patch.object(Foo, 'foo', new_callable=crasher)
1611 bad.attribute_name = 'foo'
1612
1613 for additionals in [good, bad], [bad, good]:
1614 patcher.additional_patchers = additionals
1615
1616 @patcher
1617 def func(): pass
1618
1619 self.assertRaises(NameError, func)
1620 self.assertEqual(Foo.f, original_f)
1621 self.assertEqual(Foo.g, original_g)
1622 self.assertEqual(Foo.foo, original_foo)
1623
1624
1625 def test_patch_multiple_string_subclasses(self):
1626 Foo = type('Foo', (str,), {'fish': 'tasty'})
1627 foo = Foo()
1628 @patch.multiple(foo, fish='nearly gone')
1629 def test():
1630 self.assertEqual(foo.fish, 'nearly gone')
1631
1632 test()
1633 self.assertEqual(foo.fish, 'tasty')
1634
1635
1636 @patch('unittest.mock.patch.TEST_PREFIX', 'foo')
1637 def test_patch_test_prefix(self):
1638 class Foo(object):
1639 thing = 'original'
1640
1641 def foo_one(self):
1642 return self.thing
1643 def foo_two(self):
1644 return self.thing
1645 def test_one(self):
1646 return self.thing
1647 def test_two(self):
1648 return self.thing
1649
1650 Foo = patch.object(Foo, 'thing', 'changed')(Foo)
1651
1652 foo = Foo()
1653 self.assertEqual(foo.foo_one(), 'changed')
1654 self.assertEqual(foo.foo_two(), 'changed')
1655 self.assertEqual(foo.test_one(), 'original')
1656 self.assertEqual(foo.test_two(), 'original')
1657
1658
1659 @patch('unittest.mock.patch.TEST_PREFIX', 'bar')
1660 def test_patch_dict_test_prefix(self):
1661 class Foo(object):
1662 def bar_one(self):
1663 return dict(the_dict)
1664 def bar_two(self):
1665 return dict(the_dict)
1666 def test_one(self):
1667 return dict(the_dict)
1668 def test_two(self):
1669 return dict(the_dict)
1670
1671 the_dict = {'key': 'original'}
1672 Foo = patch.dict(the_dict, key='changed')(Foo)
1673
1674 foo =Foo()
1675 self.assertEqual(foo.bar_one(), {'key': 'changed'})
1676 self.assertEqual(foo.bar_two(), {'key': 'changed'})
1677 self.assertEqual(foo.test_one(), {'key': 'original'})
1678 self.assertEqual(foo.test_two(), {'key': 'original'})
1679
1680
1681 def test_patch_with_spec_mock_repr(self):
1682 for arg in ('spec', 'autospec', 'spec_set'):
1683 p = patch('%s.SomeClass' % __name__, **{arg: True})
1684 m = p.start()
1685 try:
1686 self.assertIn(" name='SomeClass'", repr(m))
1687 self.assertIn(" name='SomeClass.class_attribute'",
1688 repr(m.class_attribute))
1689 self.assertIn(" name='SomeClass()'", repr(m()))
1690 self.assertIn(" name='SomeClass().class_attribute'",
1691 repr(m().class_attribute))
1692 finally:
1693 p.stop()
1694
1695
1696 def test_patch_nested_autospec_repr(self):
1697 with patch('test.test_unittest.testmock.support', autospec=True) as m:
1698 self.assertIn(" name='support.SomeClass.wibble()'",
1699 repr(m.SomeClass.wibble()))
1700 self.assertIn(" name='support.SomeClass().wibble()'",
1701 repr(m.SomeClass().wibble()))
1702
1703
1704
1705 def test_mock_calls_with_patch(self):
1706 for arg in ('spec', 'autospec', 'spec_set'):
1707 p = patch('%s.SomeClass' % __name__, **{arg: True})
1708 m = p.start()
1709 try:
1710 m.wibble()
1711
1712 kalls = [call.wibble()]
1713 self.assertEqual(m.mock_calls, kalls)
1714 self.assertEqual(m.method_calls, kalls)
1715 self.assertEqual(m.wibble.mock_calls, [call()])
1716
1717 result = m()
1718 kalls.append(call())
1719 self.assertEqual(m.mock_calls, kalls)
1720
1721 result.wibble()
1722 kalls.append(call().wibble())
1723 self.assertEqual(m.mock_calls, kalls)
1724
1725 self.assertEqual(result.mock_calls, [call.wibble()])
1726 self.assertEqual(result.wibble.mock_calls, [call()])
1727 self.assertEqual(result.method_calls, [call.wibble()])
1728 finally:
1729 p.stop()
1730
1731
1732 def test_patch_imports_lazily(self):
1733 p1 = patch('squizz.squozz')
1734 self.assertRaises(ImportError, p1.start)
1735
1736 with uncache('squizz'):
1737 squizz = Mock()
1738 sys.modules['squizz'] = squizz
1739
1740 squizz.squozz = 6
1741 p1 = patch('squizz.squozz')
1742 squizz.squozz = 3
1743 p1.start()
1744 p1.stop()
1745 self.assertEqual(squizz.squozz, 3)
1746
1747 def test_patch_propagates_exc_on_exit(self):
1748 class holder:
1749 exc_info = None, None, None
1750
1751 class custom_patch(_patch):
1752 def __exit__(self, etype=None, val=None, tb=None):
1753 _patch.__exit__(self, etype, val, tb)
1754 holder.exc_info = etype, val, tb
1755 stop = __exit__
1756
1757 def with_custom_patch(target):
1758 getter, attribute = _get_target(target)
1759 return custom_patch(
1760 getter, attribute, DEFAULT, None, False, None,
1761 None, None, {}
1762 )
1763
1764 @with_custom_patch('squizz.squozz')
1765 def test(mock):
1766 raise RuntimeError
1767
1768 with uncache('squizz'):
1769 squizz = Mock()
1770 sys.modules['squizz'] = squizz
1771
1772 self.assertRaises(RuntimeError, test)
1773
1774 self.assertIs(holder.exc_info[0], RuntimeError)
1775 self.assertIsNotNone(holder.exc_info[1],
1776 'exception value not propagated')
1777 self.assertIsNotNone(holder.exc_info[2],
1778 'exception traceback not propagated')
1779
1780
1781 def test_name_resolution_import_rebinding(self):
1782 # Currently mock.patch uses pkgutil.resolve_name(), but repeat
1783 # similar tests just for the case.
1784 # The same data is also used for testing import in test_import and
1785 # pkgutil.resolve_name() in test_pkgutil.
1786 path = os.path.join(os.path.dirname(test.__file__), 'test_import', 'data')
1787 def check(name):
1788 p = patch(name)
1789 p.start()
1790 p.stop()
1791 def check_error(name):
1792 p = patch(name)
1793 self.assertRaises(AttributeError, p.start)
1794 with uncache('package3', 'package3.submodule'), DirsOnSysPath(path):
1795 check('package3.submodule.A.attr')
1796 check_error('package3.submodule.B.attr')
1797 with uncache('package3', 'package3.submodule'), DirsOnSysPath(path):
1798 check('package3.submodule:A.attr')
1799 check_error('package3.submodule:B.attr')
1800 with uncache('package3', 'package3.submodule'), DirsOnSysPath(path):
1801 check('package3:submodule.B.attr')
1802 check_error('package3:submodule.A.attr')
1803 check('package3.submodule.A.attr')
1804 check_error('package3.submodule.B.attr')
1805 check('package3:submodule.B.attr')
1806 check_error('package3:submodule.A.attr')
1807 with uncache('package3', 'package3.submodule'), DirsOnSysPath(path):
1808 check('package3:submodule.B.attr')
1809 check_error('package3:submodule.A.attr')
1810 check('package3.submodule:A.attr')
1811 check_error('package3.submodule:B.attr')
1812 check('package3:submodule.B.attr')
1813 check_error('package3:submodule.A.attr')
1814
1815 def test_name_resolution_import_rebinding2(self):
1816 path = os.path.join(os.path.dirname(test.__file__), 'test_import', 'data')
1817 def check(name):
1818 p = patch(name)
1819 p.start()
1820 p.stop()
1821 def check_error(name):
1822 p = patch(name)
1823 self.assertRaises(AttributeError, p.start)
1824 with uncache('package4', 'package4.submodule'), DirsOnSysPath(path):
1825 check('package4.submodule.A.attr')
1826 check_error('package4.submodule.B.attr')
1827 with uncache('package4', 'package4.submodule'), DirsOnSysPath(path):
1828 check('package4.submodule:A.attr')
1829 check_error('package4.submodule:B.attr')
1830 with uncache('package4', 'package4.submodule'), DirsOnSysPath(path):
1831 check('package4:submodule.B.attr')
1832 check_error('package4:submodule.A.attr')
1833 check('package4.submodule.A.attr')
1834 check_error('package4.submodule.B.attr')
1835 check('package4:submodule.A.attr')
1836 check_error('package4:submodule.B.attr')
1837 with uncache('package4', 'package4.submodule'), DirsOnSysPath(path):
1838 check('package4:submodule.B.attr')
1839 check_error('package4:submodule.A.attr')
1840 check('package4.submodule:A.attr')
1841 check_error('package4.submodule:B.attr')
1842 check('package4:submodule.A.attr')
1843 check_error('package4:submodule.B.attr')
1844
1845
1846 def test_create_and_specs(self):
1847 for kwarg in ('spec', 'spec_set', 'autospec'):
1848 p = patch('%s.doesnotexist' % __name__, create=True,
1849 **{kwarg: True})
1850 self.assertRaises(TypeError, p.start)
1851 self.assertRaises(NameError, lambda: doesnotexist)
1852
1853 # check that spec with create is innocuous if the original exists
1854 p = patch(MODNAME, create=True, **{kwarg: True})
1855 p.start()
1856 p.stop()
1857
1858
1859 def test_multiple_specs(self):
1860 original = PTModule
1861 for kwarg in ('spec', 'spec_set'):
1862 p = patch(MODNAME, autospec=0, **{kwarg: 0})
1863 self.assertRaises(TypeError, p.start)
1864 self.assertIs(PTModule, original)
1865
1866 for kwarg in ('spec', 'autospec'):
1867 p = patch(MODNAME, spec_set=0, **{kwarg: 0})
1868 self.assertRaises(TypeError, p.start)
1869 self.assertIs(PTModule, original)
1870
1871 for kwarg in ('spec_set', 'autospec'):
1872 p = patch(MODNAME, spec=0, **{kwarg: 0})
1873 self.assertRaises(TypeError, p.start)
1874 self.assertIs(PTModule, original)
1875
1876
1877 def test_specs_false_instead_of_none(self):
1878 p = patch(MODNAME, spec=False, spec_set=False, autospec=False)
1879 mock = p.start()
1880 try:
1881 # no spec should have been set, so attribute access should not fail
1882 mock.does_not_exist
1883 mock.does_not_exist = 3
1884 finally:
1885 p.stop()
1886
1887
1888 def test_falsey_spec(self):
1889 for kwarg in ('spec', 'autospec', 'spec_set'):
1890 p = patch(MODNAME, **{kwarg: 0})
1891 m = p.start()
1892 try:
1893 self.assertRaises(AttributeError, getattr, m, 'doesnotexit')
1894 finally:
1895 p.stop()
1896
1897
1898 def test_spec_set_true(self):
1899 for kwarg in ('spec', 'autospec'):
1900 p = patch(MODNAME, spec_set=True, **{kwarg: True})
1901 m = p.start()
1902 try:
1903 self.assertRaises(AttributeError, setattr, m,
1904 'doesnotexist', 'something')
1905 self.assertRaises(AttributeError, getattr, m, 'doesnotexist')
1906 finally:
1907 p.stop()
1908
1909
1910 def test_callable_spec_as_list(self):
1911 spec = ('__call__',)
1912 p = patch(MODNAME, spec=spec)
1913 m = p.start()
1914 try:
1915 self.assertTrue(callable(m))
1916 finally:
1917 p.stop()
1918
1919
1920 def test_not_callable_spec_as_list(self):
1921 spec = ('foo', 'bar')
1922 p = patch(MODNAME, spec=spec)
1923 m = p.start()
1924 try:
1925 self.assertFalse(callable(m))
1926 finally:
1927 p.stop()
1928
1929
1930 def test_patch_stopall(self):
1931 unlink = os.unlink
1932 chdir = os.chdir
1933 path = os.path
1934 patch('os.unlink', something).start()
1935 patch('os.chdir', something_else).start()
1936
1937 @patch('os.path')
1938 def patched(mock_path):
1939 patch.stopall()
1940 self.assertIs(os.path, mock_path)
1941 self.assertIs(os.unlink, unlink)
1942 self.assertIs(os.chdir, chdir)
1943
1944 patched()
1945 self.assertIs(os.path, path)
1946
1947 def test_stopall_lifo(self):
1948 stopped = []
1949 class thing(object):
1950 one = two = three = None
1951
1952 def get_patch(attribute):
1953 class mypatch(_patch):
1954 def stop(self):
1955 stopped.append(attribute)
1956 return super(mypatch, self).stop()
1957 return mypatch(lambda: thing, attribute, None, None,
1958 False, None, None, None, {})
1959 [get_patch(val).start() for val in ("one", "two", "three")]
1960 patch.stopall()
1961
1962 self.assertEqual(stopped, ["three", "two", "one"])
1963
1964 def test_patch_dict_stopall(self):
1965 dic1 = {}
1966 dic2 = {1: 'a'}
1967 dic3 = {1: 'A', 2: 'B'}
1968 origdic1 = dic1.copy()
1969 origdic2 = dic2.copy()
1970 origdic3 = dic3.copy()
1971 patch.dict(dic1, {1: 'I', 2: 'II'}).start()
1972 patch.dict(dic2, {2: 'b'}).start()
1973
1974 @patch.dict(dic3)
1975 def patched():
1976 del dic3[1]
1977
1978 patched()
1979 self.assertNotEqual(dic1, origdic1)
1980 self.assertNotEqual(dic2, origdic2)
1981 self.assertEqual(dic3, origdic3)
1982
1983 patch.stopall()
1984
1985 self.assertEqual(dic1, origdic1)
1986 self.assertEqual(dic2, origdic2)
1987 self.assertEqual(dic3, origdic3)
1988
1989
1990 def test_patch_and_patch_dict_stopall(self):
1991 original_unlink = os.unlink
1992 original_chdir = os.chdir
1993 dic1 = {}
1994 dic2 = {1: 'A', 2: 'B'}
1995 origdic1 = dic1.copy()
1996 origdic2 = dic2.copy()
1997
1998 patch('os.unlink', something).start()
1999 patch('os.chdir', something_else).start()
2000 patch.dict(dic1, {1: 'I', 2: 'II'}).start()
2001 patch.dict(dic2).start()
2002 del dic2[1]
2003
2004 self.assertIsNot(os.unlink, original_unlink)
2005 self.assertIsNot(os.chdir, original_chdir)
2006 self.assertNotEqual(dic1, origdic1)
2007 self.assertNotEqual(dic2, origdic2)
2008 patch.stopall()
2009 self.assertIs(os.unlink, original_unlink)
2010 self.assertIs(os.chdir, original_chdir)
2011 self.assertEqual(dic1, origdic1)
2012 self.assertEqual(dic2, origdic2)
2013
2014
2015 def test_special_attrs(self):
2016 def foo(x=0):
2017 """TEST"""
2018 return x
2019 with patch.object(foo, '__defaults__', (1, )):
2020 self.assertEqual(foo(), 1)
2021 self.assertEqual(foo(), 0)
2022
2023 orig_doc = foo.__doc__
2024 with patch.object(foo, '__doc__', "FUN"):
2025 self.assertEqual(foo.__doc__, "FUN")
2026 self.assertEqual(foo.__doc__, orig_doc)
2027
2028 with patch.object(foo, '__module__', "testpatch2"):
2029 self.assertEqual(foo.__module__, "testpatch2")
2030 self.assertEqual(foo.__module__, __name__)
2031
2032 with patch.object(foo, '__annotations__', dict([('s', 1, )])):
2033 self.assertEqual(foo.__annotations__, dict([('s', 1, )]))
2034 self.assertEqual(foo.__annotations__, dict())
2035
2036 def foo(*a, x=0):
2037 return x
2038 with patch.object(foo, '__kwdefaults__', dict([('x', 1, )])):
2039 self.assertEqual(foo(), 1)
2040 self.assertEqual(foo(), 0)
2041
2042 def test_patch_orderdict(self):
2043 foo = OrderedDict()
2044 foo['a'] = object()
2045 foo['b'] = 'python'
2046
2047 original = foo.copy()
2048 update_values = list(zip('cdefghijklmnopqrstuvwxyz', range(26)))
2049 patched_values = list(foo.items()) + update_values
2050
2051 with patch.dict(foo, OrderedDict(update_values)):
2052 self.assertEqual(list(foo.items()), patched_values)
2053
2054 self.assertEqual(foo, original)
2055
2056 with patch.dict(foo, update_values):
2057 self.assertEqual(list(foo.items()), patched_values)
2058
2059 self.assertEqual(foo, original)
2060
2061 def test_dotted_but_module_not_loaded(self):
2062 # This exercises the AttributeError branch of _dot_lookup.
2063
2064 # make sure it's there
2065 import test.test_unittest.testmock.support
2066 # now make sure it's not:
2067 with patch.dict('sys.modules'):
2068 del sys.modules['test.test_unittest.testmock.support']
2069 del sys.modules['test.test_unittest.testmock']
2070 del sys.modules['test.test_unittest']
2071 del sys.modules['test']
2072
2073 # now make sure we can patch based on a dotted path:
2074 @patch('test.test_unittest.testmock.support.X')
2075 def test(mock):
2076 pass
2077 test()
2078
2079
2080 def test_invalid_target(self):
2081 class Foo:
2082 pass
2083
2084 for target in ['', 12, Foo()]:
2085 with self.subTest(target=target):
2086 with self.assertRaises(TypeError):
2087 patch(target)
2088
2089
2090 def test_cant_set_kwargs_when_passing_a_mock(self):
2091 @patch('test.test_unittest.testmock.support.X', new=object(), x=1)
2092 def test(): pass
2093 with self.assertRaises(TypeError):
2094 test()
2095
2096 def test_patch_proxy_object(self):
2097 @patch("test.test_unittest.testmock.support.g", new_callable=MagicMock())
2098 def test(_):
2099 pass
2100
2101 test()
2102
2103
2104 if __name__ == '__main__':
2105 unittest.main()