ยปCore Development>Code coverage>Lib/unittest/test/testmock/testpatch.py

Python code coverage for Lib/unittest/test/testmock/testpatch.py

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