Best Python code snippet using Testify_python
testpatch.py
Source:testpatch.py  
1# Copyright (C) 2007-2012 Michael Foord & the mock team2# E-mail: fuzzyman AT voidspace DOT org DOT uk3# http://www.voidspace.org.uk/python/mock/4import os5import sys6import unittest7from unittest.test.testmock import support8from unittest.test.testmock.support import SomeClass, is_instance9from unittest.mock import (10    NonCallableMock, CallableMixin, patch, sentinel,11    MagicMock, Mock, NonCallableMagicMock, patch, _patch,12    DEFAULT, call, _get_target13)14builtin_string = 'builtins'15PTModule = sys.modules[__name__]16MODNAME = '%s.PTModule' % __name__17def _get_proxy(obj, get_only=True):18    class Proxy(object):19        def __getattr__(self, name):20            return getattr(obj, name)21    if not get_only:22        def __setattr__(self, name, value):23            setattr(obj, name, value)24        def __delattr__(self, name):25            delattr(obj, name)26        Proxy.__setattr__ = __setattr__27        Proxy.__delattr__ = __delattr__28    return Proxy()29# for use in the test30something  = sentinel.Something31something_else  = sentinel.SomethingElse32class Foo(object):33    def __init__(self, a):34        pass35    def f(self, a):36        pass37    def g(self):38        pass39    foo = 'bar'40    class Bar(object):41        def a(self):42            pass43foo_name = '%s.Foo' % __name__44def function(a, b=Foo):45    pass46class Container(object):47    def __init__(self):48        self.values = {}49    def __getitem__(self, name):50        return self.values[name]51    def __setitem__(self, name, value):52        self.values[name] = value53    def __delitem__(self, name):54        del self.values[name]55    def __iter__(self):56        return iter(self.values)57class PatchTest(unittest.TestCase):58    def assertNotCallable(self, obj, magic=True):59        MockClass = NonCallableMagicMock60        if not magic:61            MockClass = NonCallableMock62        self.assertRaises(TypeError, obj)63        self.assertTrue(is_instance(obj, MockClass))64        self.assertFalse(is_instance(obj, CallableMixin))65    def test_single_patchobject(self):66        class Something(object):67            attribute = sentinel.Original68        @patch.object(Something, 'attribute', sentinel.Patched)69        def test():70            self.assertEqual(Something.attribute, sentinel.Patched, "unpatched")71        test()72        self.assertEqual(Something.attribute, sentinel.Original,73                         "patch not restored")74    def test_patchobject_with_none(self):75        class Something(object):76            attribute = sentinel.Original77        @patch.object(Something, 'attribute', None)78        def test():79            self.assertIsNone(Something.attribute, "unpatched")80        test()81        self.assertEqual(Something.attribute, sentinel.Original,82                         "patch not restored")83    def test_multiple_patchobject(self):84        class Something(object):85            attribute = sentinel.Original86            next_attribute = sentinel.Original287        @patch.object(Something, 'attribute', sentinel.Patched)88        @patch.object(Something, 'next_attribute', sentinel.Patched2)89        def test():90            self.assertEqual(Something.attribute, sentinel.Patched,91                             "unpatched")92            self.assertEqual(Something.next_attribute, sentinel.Patched2,93                             "unpatched")94        test()95        self.assertEqual(Something.attribute, sentinel.Original,96                         "patch not restored")97        self.assertEqual(Something.next_attribute, sentinel.Original2,98                         "patch not restored")99    def test_object_lookup_is_quite_lazy(self):100        global something101        original = something102        @patch('%s.something' % __name__, sentinel.Something2)103        def test():104            pass105        try:106            something = sentinel.replacement_value107            test()108            self.assertEqual(something, sentinel.replacement_value)109        finally:110            something = original111    def test_patch(self):112        @patch('%s.something' % __name__, sentinel.Something2)113        def test():114            self.assertEqual(PTModule.something, sentinel.Something2,115                             "unpatched")116        test()117        self.assertEqual(PTModule.something, sentinel.Something,118                         "patch not restored")119        @patch('%s.something' % __name__, sentinel.Something2)120        @patch('%s.something_else' % __name__, sentinel.SomethingElse)121        def test():122            self.assertEqual(PTModule.something, sentinel.Something2,123                             "unpatched")124            self.assertEqual(PTModule.something_else, sentinel.SomethingElse,125                             "unpatched")126        self.assertEqual(PTModule.something, sentinel.Something,127                         "patch not restored")128        self.assertEqual(PTModule.something_else, sentinel.SomethingElse,129                         "patch not restored")130        # Test the patching and restoring works a second time131        test()132        self.assertEqual(PTModule.something, sentinel.Something,133                         "patch not restored")134        self.assertEqual(PTModule.something_else, sentinel.SomethingElse,135                         "patch not restored")136        mock = Mock()137        mock.return_value = sentinel.Handle138        @patch('%s.open' % builtin_string, mock)139        def test():140            self.assertEqual(open('filename', 'r'), sentinel.Handle,141                             "open not patched")142        test()143        test()144        self.assertNotEqual(open, mock, "patch not restored")145    def test_patch_class_attribute(self):146        @patch('%s.SomeClass.class_attribute' % __name__,147               sentinel.ClassAttribute)148        def test():149            self.assertEqual(PTModule.SomeClass.class_attribute,150                             sentinel.ClassAttribute, "unpatched")151        test()152        self.assertIsNone(PTModule.SomeClass.class_attribute,153                          "patch not restored")154    def test_patchobject_with_default_mock(self):155        class Test(object):156            something = sentinel.Original157            something2 = sentinel.Original2158        @patch.object(Test, 'something')159        def test(mock):160            self.assertEqual(mock, Test.something,161                             "Mock not passed into test function")162            self.assertIsInstance(mock, MagicMock,163                            "patch with two arguments did not create a mock")164        test()165        @patch.object(Test, 'something')166        @patch.object(Test, 'something2')167        def test(this1, this2, mock1, mock2):168            self.assertEqual(this1, sentinel.this1,169                             "Patched function didn't receive initial argument")170            self.assertEqual(this2, sentinel.this2,171                             "Patched function didn't receive second argument")172            self.assertEqual(mock1, Test.something2,173                             "Mock not passed into test function")174            self.assertEqual(mock2, Test.something,175                             "Second Mock not passed into test function")176            self.assertIsInstance(mock2, MagicMock,177                            "patch with two arguments did not create a mock")178            self.assertIsInstance(mock2, MagicMock,179                            "patch with two arguments did not create a mock")180            # A hack to test that new mocks are passed the second time181            self.assertNotEqual(outerMock1, mock1, "unexpected value for mock1")182            self.assertNotEqual(outerMock2, mock2, "unexpected value for mock1")183            return mock1, mock2184        outerMock1 = outerMock2 = None185        outerMock1, outerMock2 = test(sentinel.this1, sentinel.this2)186        # Test that executing a second time creates new mocks187        test(sentinel.this1, sentinel.this2)188    def test_patch_with_spec(self):189        @patch('%s.SomeClass' % __name__, spec=SomeClass)190        def test(MockSomeClass):191            self.assertEqual(SomeClass, MockSomeClass)192            self.assertTrue(is_instance(SomeClass.wibble, MagicMock))193            self.assertRaises(AttributeError, lambda: SomeClass.not_wibble)194        test()195    def test_patchobject_with_spec(self):196        @patch.object(SomeClass, 'class_attribute', spec=SomeClass)197        def test(MockAttribute):198            self.assertEqual(SomeClass.class_attribute, MockAttribute)199            self.assertTrue(is_instance(SomeClass.class_attribute.wibble,200                                       MagicMock))201            self.assertRaises(AttributeError,202                              lambda: SomeClass.class_attribute.not_wibble)203        test()204    def test_patch_with_spec_as_list(self):205        @patch('%s.SomeClass' % __name__, spec=['wibble'])206        def test(MockSomeClass):207            self.assertEqual(SomeClass, MockSomeClass)208            self.assertTrue(is_instance(SomeClass.wibble, MagicMock))209            self.assertRaises(AttributeError, lambda: SomeClass.not_wibble)210        test()211    def test_patchobject_with_spec_as_list(self):212        @patch.object(SomeClass, 'class_attribute', spec=['wibble'])213        def test(MockAttribute):214            self.assertEqual(SomeClass.class_attribute, MockAttribute)215            self.assertTrue(is_instance(SomeClass.class_attribute.wibble,216                                       MagicMock))217            self.assertRaises(AttributeError,218                              lambda: SomeClass.class_attribute.not_wibble)219        test()220    def test_nested_patch_with_spec_as_list(self):221        # regression test for nested decorators222        @patch('%s.open' % builtin_string)223        @patch('%s.SomeClass' % __name__, spec=['wibble'])224        def test(MockSomeClass, MockOpen):225            self.assertEqual(SomeClass, MockSomeClass)226            self.assertTrue(is_instance(SomeClass.wibble, MagicMock))227            self.assertRaises(AttributeError, lambda: SomeClass.not_wibble)228        test()229    def test_patch_with_spec_as_boolean(self):230        @patch('%s.SomeClass' % __name__, spec=True)231        def test(MockSomeClass):232            self.assertEqual(SomeClass, MockSomeClass)233            # Should not raise attribute error234            MockSomeClass.wibble235            self.assertRaises(AttributeError, lambda: MockSomeClass.not_wibble)236        test()237    def test_patch_object_with_spec_as_boolean(self):238        @patch.object(PTModule, 'SomeClass', spec=True)239        def test(MockSomeClass):240            self.assertEqual(SomeClass, MockSomeClass)241            # Should not raise attribute error242            MockSomeClass.wibble243            self.assertRaises(AttributeError, lambda: MockSomeClass.not_wibble)244        test()245    def test_patch_class_acts_with_spec_is_inherited(self):246        @patch('%s.SomeClass' % __name__, spec=True)247        def test(MockSomeClass):248            self.assertTrue(is_instance(MockSomeClass, MagicMock))249            instance = MockSomeClass()250            self.assertNotCallable(instance)251            # Should not raise attribute error252            instance.wibble253            self.assertRaises(AttributeError, lambda: instance.not_wibble)254        test()255    def test_patch_with_create_mocks_non_existent_attributes(self):256        @patch('%s.frooble' % builtin_string, sentinel.Frooble, create=True)257        def test():258            self.assertEqual(frooble, sentinel.Frooble)259        test()260        self.assertRaises(NameError, lambda: frooble)261    def test_patchobject_with_create_mocks_non_existent_attributes(self):262        @patch.object(SomeClass, 'frooble', sentinel.Frooble, create=True)263        def test():264            self.assertEqual(SomeClass.frooble, sentinel.Frooble)265        test()266        self.assertFalse(hasattr(SomeClass, 'frooble'))267    def test_patch_wont_create_by_default(self):268        try:269            @patch('%s.frooble' % builtin_string, sentinel.Frooble)270            def test():271                self.assertEqual(frooble, sentinel.Frooble)272            test()273        except AttributeError:274            pass275        else:276            self.fail('Patching non existent attributes should fail')277        self.assertRaises(NameError, lambda: frooble)278    def test_patchobject_wont_create_by_default(self):279        try:280            @patch.object(SomeClass, 'frooble', sentinel.Frooble)281            def test():282                self.fail('Patching non existent attributes should fail')283            test()284        except AttributeError:285            pass286        else:287            self.fail('Patching non existent attributes should fail')288        self.assertFalse(hasattr(SomeClass, 'frooble'))289    def test_patch_with_static_methods(self):290        class Foo(object):291            @staticmethod292            def woot():293                return sentinel.Static294        @patch.object(Foo, 'woot', staticmethod(lambda: sentinel.Patched))295        def anonymous():296            self.assertEqual(Foo.woot(), sentinel.Patched)297        anonymous()298        self.assertEqual(Foo.woot(), sentinel.Static)299    def test_patch_local(self):300        foo = sentinel.Foo301        @patch.object(sentinel, 'Foo', 'Foo')302        def anonymous():303            self.assertEqual(sentinel.Foo, 'Foo')304        anonymous()305        self.assertEqual(sentinel.Foo, foo)306    def test_patch_slots(self):307        class Foo(object):308            __slots__ = ('Foo',)309        foo = Foo()310        foo.Foo = sentinel.Foo311        @patch.object(foo, 'Foo', 'Foo')312        def anonymous():313            self.assertEqual(foo.Foo, 'Foo')314        anonymous()315        self.assertEqual(foo.Foo, sentinel.Foo)316    def test_patchobject_class_decorator(self):317        class Something(object):318            attribute = sentinel.Original319        class Foo(object):320            def test_method(other_self):321                self.assertEqual(Something.attribute, sentinel.Patched,322                                 "unpatched")323            def not_test_method(other_self):324                self.assertEqual(Something.attribute, sentinel.Original,325                                 "non-test method patched")326        Foo = patch.object(Something, 'attribute', sentinel.Patched)(Foo)327        f = Foo()328        f.test_method()329        f.not_test_method()330        self.assertEqual(Something.attribute, sentinel.Original,331                         "patch not restored")332    def test_patch_class_decorator(self):333        class Something(object):334            attribute = sentinel.Original335        class Foo(object):336            def test_method(other_self, mock_something):337                self.assertEqual(PTModule.something, mock_something,338                                 "unpatched")339            def not_test_method(other_self):340                self.assertEqual(PTModule.something, sentinel.Something,341                                 "non-test method patched")342        Foo = patch('%s.something' % __name__)(Foo)343        f = Foo()344        f.test_method()345        f.not_test_method()346        self.assertEqual(Something.attribute, sentinel.Original,347                         "patch not restored")348        self.assertEqual(PTModule.something, sentinel.Something,349                         "patch not restored")350    def test_patchobject_twice(self):351        class Something(object):352            attribute = sentinel.Original353            next_attribute = sentinel.Original2354        @patch.object(Something, 'attribute', sentinel.Patched)355        @patch.object(Something, 'attribute', sentinel.Patched)356        def test():357            self.assertEqual(Something.attribute, sentinel.Patched, "unpatched")358        test()359        self.assertEqual(Something.attribute, sentinel.Original,360                         "patch not restored")361    def test_patch_dict(self):362        foo = {'initial': object(), 'other': 'something'}363        original = foo.copy()364        @patch.dict(foo)365        def test():366            foo['a'] = 3367            del foo['initial']368            foo['other'] = 'something else'369        test()370        self.assertEqual(foo, original)371        @patch.dict(foo, {'a': 'b'})372        def test():373            self.assertEqual(len(foo), 3)374            self.assertEqual(foo['a'], 'b')375        test()376        self.assertEqual(foo, original)377        @patch.dict(foo, [('a', 'b')])378        def test():379            self.assertEqual(len(foo), 3)380            self.assertEqual(foo['a'], 'b')381        test()382        self.assertEqual(foo, original)383    def test_patch_dict_with_container_object(self):384        foo = Container()385        foo['initial'] = object()386        foo['other'] =  'something'387        original = foo.values.copy()388        @patch.dict(foo)389        def test():390            foo['a'] = 3391            del foo['initial']392            foo['other'] = 'something else'393        test()394        self.assertEqual(foo.values, original)395        @patch.dict(foo, {'a': 'b'})396        def test():397            self.assertEqual(len(foo.values), 3)398            self.assertEqual(foo['a'], 'b')399        test()400        self.assertEqual(foo.values, original)401    def test_patch_dict_with_clear(self):402        foo = {'initial': object(), 'other': 'something'}403        original = foo.copy()404        @patch.dict(foo, clear=True)405        def test():406            self.assertEqual(foo, {})407            foo['a'] = 3408            foo['other'] = 'something else'409        test()410        self.assertEqual(foo, original)411        @patch.dict(foo, {'a': 'b'}, clear=True)412        def test():413            self.assertEqual(foo, {'a': 'b'})414        test()415        self.assertEqual(foo, original)416        @patch.dict(foo, [('a', 'b')], clear=True)417        def test():418            self.assertEqual(foo, {'a': 'b'})419        test()420        self.assertEqual(foo, original)421    def test_patch_dict_with_container_object_and_clear(self):422        foo = Container()423        foo['initial'] = object()424        foo['other'] =  'something'425        original = foo.values.copy()426        @patch.dict(foo, clear=True)427        def test():428            self.assertEqual(foo.values, {})429            foo['a'] = 3430            foo['other'] = 'something else'431        test()432        self.assertEqual(foo.values, original)433        @patch.dict(foo, {'a': 'b'}, clear=True)434        def test():435            self.assertEqual(foo.values, {'a': 'b'})436        test()437        self.assertEqual(foo.values, original)438    def test_name_preserved(self):439        foo = {}440        @patch('%s.SomeClass' % __name__, object())441        @patch('%s.SomeClass' % __name__, object(), autospec=True)442        @patch.object(SomeClass, object())443        @patch.dict(foo)444        def some_name():445            pass446        self.assertEqual(some_name.__name__, 'some_name')447    def test_patch_with_exception(self):448        foo = {}449        @patch.dict(foo, {'a': 'b'})450        def test():451            raise NameError('Konrad')452        try:453            test()454        except NameError:455            pass456        else:457            self.fail('NameError not raised by test')458        self.assertEqual(foo, {})459    def test_patch_dict_with_string(self):460        @patch.dict('os.environ', {'konrad_delong': 'some value'})461        def test():462            self.assertIn('konrad_delong', os.environ)463        test()464    def test_patch_descriptor(self):465        # would be some effort to fix this - we could special case the466        # builtin descriptors: classmethod, property, staticmethod467        return468        class Nothing(object):469            foo = None470        class Something(object):471            foo = {}472            @patch.object(Nothing, 'foo', 2)473            @classmethod474            def klass(cls):475                self.assertIs(cls, Something)476            @patch.object(Nothing, 'foo', 2)477            @staticmethod478            def static(arg):479                return arg480            @patch.dict(foo)481            @classmethod482            def klass_dict(cls):483                self.assertIs(cls, Something)484            @patch.dict(foo)485            @staticmethod486            def static_dict(arg):487                return arg488        # these will raise exceptions if patching descriptors is broken489        self.assertEqual(Something.static('f00'), 'f00')490        Something.klass()491        self.assertEqual(Something.static_dict('f00'), 'f00')492        Something.klass_dict()493        something = Something()494        self.assertEqual(something.static('f00'), 'f00')495        something.klass()496        self.assertEqual(something.static_dict('f00'), 'f00')497        something.klass_dict()498    def test_patch_spec_set(self):499        @patch('%s.SomeClass' % __name__, spec=SomeClass, spec_set=True)500        def test(MockClass):501            MockClass.z = 'foo'502        self.assertRaises(AttributeError, test)503        @patch.object(support, 'SomeClass', spec=SomeClass, spec_set=True)504        def test(MockClass):505            MockClass.z = 'foo'506        self.assertRaises(AttributeError, test)507        @patch('%s.SomeClass' % __name__, spec_set=True)508        def test(MockClass):509            MockClass.z = 'foo'510        self.assertRaises(AttributeError, test)511        @patch.object(support, 'SomeClass', spec_set=True)512        def test(MockClass):513            MockClass.z = 'foo'514        self.assertRaises(AttributeError, test)515    def test_spec_set_inherit(self):516        @patch('%s.SomeClass' % __name__, spec_set=True)517        def test(MockClass):518            instance = MockClass()519            instance.z = 'foo'520        self.assertRaises(AttributeError, test)521    def test_patch_start_stop(self):522        original = something523        patcher = patch('%s.something' % __name__)524        self.assertIs(something, original)525        mock = patcher.start()526        try:527            self.assertIsNot(mock, original)528            self.assertIs(something, mock)529        finally:530            patcher.stop()531        self.assertIs(something, original)532    def test_stop_without_start(self):533        patcher = patch(foo_name, 'bar', 3)534        # calling stop without start used to produce a very obscure error535        self.assertRaises(RuntimeError, patcher.stop)536    def test_patchobject_start_stop(self):537        original = something538        patcher = patch.object(PTModule, 'something', 'foo')539        self.assertIs(something, original)540        replaced = patcher.start()541        try:542            self.assertEqual(replaced, 'foo')543            self.assertIs(something, replaced)544        finally:545            patcher.stop()546        self.assertIs(something, original)547    def test_patch_dict_start_stop(self):548        d = {'foo': 'bar'}549        original = d.copy()550        patcher = patch.dict(d, [('spam', 'eggs')], clear=True)551        self.assertEqual(d, original)552        patcher.start()553        try:554            self.assertEqual(d, {'spam': 'eggs'})555        finally:556            patcher.stop()557        self.assertEqual(d, original)558    def test_patch_dict_class_decorator(self):559        this = self560        d = {'spam': 'eggs'}561        original = d.copy()562        class Test(object):563            def test_first(self):564                this.assertEqual(d, {'foo': 'bar'})565            def test_second(self):566                this.assertEqual(d, {'foo': 'bar'})567        Test = patch.dict(d, {'foo': 'bar'}, clear=True)(Test)568        self.assertEqual(d, original)569        test = Test()570        test.test_first()571        self.assertEqual(d, original)572        test.test_second()573        self.assertEqual(d, original)574        test = Test()575        test.test_first()576        self.assertEqual(d, original)577        test.test_second()578        self.assertEqual(d, original)579    def test_get_only_proxy(self):580        class Something(object):581            foo = 'foo'582        class SomethingElse:583            foo = 'foo'584        for thing in Something, SomethingElse, Something(), SomethingElse:585            proxy = _get_proxy(thing)586            @patch.object(proxy, 'foo', 'bar')587            def test():588                self.assertEqual(proxy.foo, 'bar')589            test()590            self.assertEqual(proxy.foo, 'foo')591            self.assertEqual(thing.foo, 'foo')592            self.assertNotIn('foo', proxy.__dict__)593    def test_get_set_delete_proxy(self):594        class Something(object):595            foo = 'foo'596        class SomethingElse:597            foo = 'foo'598        for thing in Something, SomethingElse, Something(), SomethingElse:599            proxy = _get_proxy(Something, get_only=False)600            @patch.object(proxy, 'foo', 'bar')601            def test():602                self.assertEqual(proxy.foo, 'bar')603            test()604            self.assertEqual(proxy.foo, 'foo')605            self.assertEqual(thing.foo, 'foo')606            self.assertNotIn('foo', proxy.__dict__)607    def test_patch_keyword_args(self):608        kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,609                  'foo': MagicMock()}610        patcher = patch(foo_name, **kwargs)611        mock = patcher.start()612        patcher.stop()613        self.assertRaises(KeyError, mock)614        self.assertEqual(mock.foo.bar(), 33)615        self.assertIsInstance(mock.foo, MagicMock)616    def test_patch_object_keyword_args(self):617        kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33,618                  'foo': MagicMock()}619        patcher = patch.object(Foo, 'f', **kwargs)620        mock = patcher.start()621        patcher.stop()622        self.assertRaises(KeyError, mock)623        self.assertEqual(mock.foo.bar(), 33)624        self.assertIsInstance(mock.foo, MagicMock)625    def test_patch_dict_keyword_args(self):626        original = {'foo': 'bar'}627        copy = original.copy()628        patcher = patch.dict(original, foo=3, bar=4, baz=5)629        patcher.start()630        try:631            self.assertEqual(original, dict(foo=3, bar=4, baz=5))632        finally:633            patcher.stop()634        self.assertEqual(original, copy)635    def test_autospec(self):636        class Boo(object):637            def __init__(self, a):638                pass639            def f(self, a):640                pass641            def g(self):642                pass643            foo = 'bar'644            class Bar(object):645                def a(self):646                    pass647        def _test(mock):648            mock(1)649            mock.assert_called_with(1)650            self.assertRaises(TypeError, mock)651        def _test2(mock):652            mock.f(1)653            mock.f.assert_called_with(1)654            self.assertRaises(TypeError, mock.f)655            mock.g()656            mock.g.assert_called_with()657            self.assertRaises(TypeError, mock.g, 1)658            self.assertRaises(AttributeError, getattr, mock, 'h')659            mock.foo.lower()660            mock.foo.lower.assert_called_with()661            self.assertRaises(AttributeError, getattr, mock.foo, 'bar')662            mock.Bar()663            mock.Bar.assert_called_with()664            mock.Bar.a()665            mock.Bar.a.assert_called_with()666            self.assertRaises(TypeError, mock.Bar.a, 1)667            mock.Bar().a()668            mock.Bar().a.assert_called_with()669            self.assertRaises(TypeError, mock.Bar().a, 1)670            self.assertRaises(AttributeError, getattr, mock.Bar, 'b')671            self.assertRaises(AttributeError, getattr, mock.Bar(), 'b')672        def function(mock):673            _test(mock)674            _test2(mock)675            _test2(mock(1))676            self.assertIs(mock, Foo)677            return mock678        test = patch(foo_name, autospec=True)(function)679        mock = test()680        self.assertIsNot(Foo, mock)681        # test patching a second time works682        test()683        module = sys.modules[__name__]684        test = patch.object(module, 'Foo', autospec=True)(function)685        mock = test()686        self.assertIsNot(Foo, mock)687        # test patching a second time works688        test()689    def test_autospec_function(self):690        @patch('%s.function' % __name__, autospec=True)691        def test(mock):692            function(1)693            function.assert_called_with(1)694            function(2, 3)695            function.assert_called_with(2, 3)696            self.assertRaises(TypeError, function)697            self.assertRaises(AttributeError, getattr, function, 'foo')698        test()699    def test_autospec_keywords(self):700        @patch('%s.function' % __name__, autospec=True,701               return_value=3)702        def test(mock_function):703            #self.assertEqual(function.abc, 'foo')704            return function(1, 2)705        result = test()706        self.assertEqual(result, 3)707    def test_autospec_with_new(self):708        patcher = patch('%s.function' % __name__, new=3, autospec=True)709        self.assertRaises(TypeError, patcher.start)710        module = sys.modules[__name__]711        patcher = patch.object(module, 'function', new=3, autospec=True)712        self.assertRaises(TypeError, patcher.start)713    def test_autospec_with_object(self):714        class Bar(Foo):715            extra = []716        patcher = patch(foo_name, autospec=Bar)717        mock = patcher.start()718        try:719            self.assertIsInstance(mock, Bar)720            self.assertIsInstance(mock.extra, list)721        finally:722            patcher.stop()723    def test_autospec_inherits(self):724        FooClass = Foo725        patcher = patch(foo_name, autospec=True)726        mock = patcher.start()727        try:728            self.assertIsInstance(mock, FooClass)729            self.assertIsInstance(mock(3), FooClass)730        finally:731            patcher.stop()732    def test_autospec_name(self):733        patcher = patch(foo_name, autospec=True)734        mock = patcher.start()735        try:736            self.assertIn(" name='Foo'", repr(mock))737            self.assertIn(" name='Foo.f'", repr(mock.f))738            self.assertIn(" name='Foo()'", repr(mock(None)))739            self.assertIn(" name='Foo().f'", repr(mock(None).f))740        finally:741            patcher.stop()742    def test_tracebacks(self):743        @patch.object(Foo, 'f', object())744        def test():745            raise AssertionError746        try:747            test()748        except:749            err = sys.exc_info()750        result = unittest.TextTestResult(None, None, 0)751        traceback = result._exc_info_to_string(err, self)752        self.assertIn('raise AssertionError', traceback)753    def test_new_callable_patch(self):754        patcher = patch(foo_name, new_callable=NonCallableMagicMock)755        m1 = patcher.start()756        patcher.stop()757        m2 = patcher.start()758        patcher.stop()759        self.assertIsNot(m1, m2)760        for mock in m1, m2:761            self.assertNotCallable(m1)762    def test_new_callable_patch_object(self):763        patcher = patch.object(Foo, 'f', new_callable=NonCallableMagicMock)764        m1 = patcher.start()765        patcher.stop()766        m2 = patcher.start()767        patcher.stop()768        self.assertIsNot(m1, m2)769        for mock in m1, m2:770            self.assertNotCallable(m1)771    def test_new_callable_keyword_arguments(self):772        class Bar(object):773            kwargs = None774            def __init__(self, **kwargs):775                Bar.kwargs = kwargs776        patcher = patch(foo_name, new_callable=Bar, arg1=1, arg2=2)777        m = patcher.start()778        try:779            self.assertIs(type(m), Bar)780            self.assertEqual(Bar.kwargs, dict(arg1=1, arg2=2))781        finally:782            patcher.stop()783    def test_new_callable_spec(self):784        class Bar(object):785            kwargs = None786            def __init__(self, **kwargs):787                Bar.kwargs = kwargs788        patcher = patch(foo_name, new_callable=Bar, spec=Bar)789        patcher.start()790        try:791            self.assertEqual(Bar.kwargs, dict(spec=Bar))792        finally:793            patcher.stop()794        patcher = patch(foo_name, new_callable=Bar, spec_set=Bar)795        patcher.start()796        try:797            self.assertEqual(Bar.kwargs, dict(spec_set=Bar))798        finally:799            patcher.stop()800    def test_new_callable_create(self):801        non_existent_attr = '%s.weeeee' % foo_name802        p = patch(non_existent_attr, new_callable=NonCallableMock)803        self.assertRaises(AttributeError, p.start)804        p = patch(non_existent_attr, new_callable=NonCallableMock,805                  create=True)806        m = p.start()807        try:808            self.assertNotCallable(m, magic=False)809        finally:810            p.stop()811    def test_new_callable_incompatible_with_new(self):812        self.assertRaises(813            ValueError, patch, foo_name, new=object(), new_callable=MagicMock814        )815        self.assertRaises(816            ValueError, patch.object, Foo, 'f', new=object(),817            new_callable=MagicMock818        )819    def test_new_callable_incompatible_with_autospec(self):820        self.assertRaises(821            ValueError, patch, foo_name, new_callable=MagicMock,822            autospec=True823        )824        self.assertRaises(825            ValueError, patch.object, Foo, 'f', new_callable=MagicMock,826            autospec=True827        )828    def test_new_callable_inherit_for_mocks(self):829        class MockSub(Mock):830            pass831        MockClasses = (832            NonCallableMock, NonCallableMagicMock, MagicMock, Mock, MockSub833        )834        for Klass in MockClasses:835            for arg in 'spec', 'spec_set':836                kwargs = {arg: True}837                p = patch(foo_name, new_callable=Klass, **kwargs)838                m = p.start()839                try:840                    instance = m.return_value841                    self.assertRaises(AttributeError, getattr, instance, 'x')842                finally:843                    p.stop()844    def test_new_callable_inherit_non_mock(self):845        class NotAMock(object):846            def __init__(self, spec):847                self.spec = spec848        p = patch(foo_name, new_callable=NotAMock, spec=True)849        m = p.start()850        try:851            self.assertTrue(is_instance(m, NotAMock))852            self.assertRaises(AttributeError, getattr, m, 'return_value')853        finally:854            p.stop()855        self.assertEqual(m.spec, Foo)856    def test_new_callable_class_decorating(self):857        test = self858        original = Foo859        class SomeTest(object):860            def _test(self, mock_foo):861                test.assertIsNot(Foo, original)862                test.assertIs(Foo, mock_foo)863                test.assertIsInstance(Foo, SomeClass)864            def test_two(self, mock_foo):865                self._test(mock_foo)866            def test_one(self, mock_foo):867                self._test(mock_foo)868        SomeTest = patch(foo_name, new_callable=SomeClass)(SomeTest)869        SomeTest().test_one()870        SomeTest().test_two()871        self.assertIs(Foo, original)872    def test_patch_multiple(self):873        original_foo = Foo874        original_f = Foo.f875        original_g = Foo.g876        patcher1 = patch.multiple(foo_name, f=1, g=2)877        patcher2 = patch.multiple(Foo, f=1, g=2)878        for patcher in patcher1, patcher2:879            patcher.start()880            try:881                self.assertIs(Foo, original_foo)882                self.assertEqual(Foo.f, 1)883                self.assertEqual(Foo.g, 2)884            finally:885                patcher.stop()886            self.assertIs(Foo, original_foo)887            self.assertEqual(Foo.f, original_f)888            self.assertEqual(Foo.g, original_g)889        @patch.multiple(foo_name, f=3, g=4)890        def test():891            self.assertIs(Foo, original_foo)892            self.assertEqual(Foo.f, 3)893            self.assertEqual(Foo.g, 4)894        test()895    def test_patch_multiple_no_kwargs(self):896        self.assertRaises(ValueError, patch.multiple, foo_name)897        self.assertRaises(ValueError, patch.multiple, Foo)898    def test_patch_multiple_create_mocks(self):899        original_foo = Foo900        original_f = Foo.f901        original_g = Foo.g902        @patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT)903        def test(f, foo):904            self.assertIs(Foo, original_foo)905            self.assertIs(Foo.f, f)906            self.assertEqual(Foo.g, 3)907            self.assertIs(Foo.foo, foo)908            self.assertTrue(is_instance(f, MagicMock))909            self.assertTrue(is_instance(foo, MagicMock))910        test()911        self.assertEqual(Foo.f, original_f)912        self.assertEqual(Foo.g, original_g)913    def test_patch_multiple_create_mocks_different_order(self):914        # bug revealed by Jython!915        original_f = Foo.f916        original_g = Foo.g917        patcher = patch.object(Foo, 'f', 3)918        patcher.attribute_name = 'f'919        other = patch.object(Foo, 'g', DEFAULT)920        other.attribute_name = 'g'921        patcher.additional_patchers = [other]922        @patcher923        def test(g):924            self.assertIs(Foo.g, g)925            self.assertEqual(Foo.f, 3)926        test()927        self.assertEqual(Foo.f, original_f)928        self.assertEqual(Foo.g, original_g)929    def test_patch_multiple_stacked_decorators(self):930        original_foo = Foo931        original_f = Foo.f932        original_g = Foo.g933        @patch.multiple(foo_name, f=DEFAULT)934        @patch.multiple(foo_name, foo=DEFAULT)935        @patch(foo_name + '.g')936        def test1(g, **kwargs):937            _test(g, **kwargs)938        @patch.multiple(foo_name, f=DEFAULT)939        @patch(foo_name + '.g')940        @patch.multiple(foo_name, foo=DEFAULT)941        def test2(g, **kwargs):942            _test(g, **kwargs)943        @patch(foo_name + '.g')944        @patch.multiple(foo_name, f=DEFAULT)945        @patch.multiple(foo_name, foo=DEFAULT)946        def test3(g, **kwargs):947            _test(g, **kwargs)948        def _test(g, **kwargs):949            f = kwargs.pop('f')950            foo = kwargs.pop('foo')951            self.assertFalse(kwargs)952            self.assertIs(Foo, original_foo)953            self.assertIs(Foo.f, f)954            self.assertIs(Foo.g, g)955            self.assertIs(Foo.foo, foo)956            self.assertTrue(is_instance(f, MagicMock))957            self.assertTrue(is_instance(g, MagicMock))958            self.assertTrue(is_instance(foo, MagicMock))959        test1()960        test2()961        test3()962        self.assertEqual(Foo.f, original_f)963        self.assertEqual(Foo.g, original_g)964    def test_patch_multiple_create_mocks_patcher(self):965        original_foo = Foo966        original_f = Foo.f967        original_g = Foo.g968        patcher = patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT)969        result = patcher.start()970        try:971            f = result['f']972            foo = result['foo']973            self.assertEqual(set(result), set(['f', 'foo']))974            self.assertIs(Foo, original_foo)975            self.assertIs(Foo.f, f)976            self.assertIs(Foo.foo, foo)977            self.assertTrue(is_instance(f, MagicMock))978            self.assertTrue(is_instance(foo, MagicMock))979        finally:980            patcher.stop()981        self.assertEqual(Foo.f, original_f)982        self.assertEqual(Foo.g, original_g)983    def test_patch_multiple_decorating_class(self):984        test = self985        original_foo = Foo986        original_f = Foo.f987        original_g = Foo.g988        class SomeTest(object):989            def _test(self, f, foo):990                test.assertIs(Foo, original_foo)991                test.assertIs(Foo.f, f)992                test.assertEqual(Foo.g, 3)993                test.assertIs(Foo.foo, foo)994                test.assertTrue(is_instance(f, MagicMock))995                test.assertTrue(is_instance(foo, MagicMock))996            def test_two(self, f, foo):997                self._test(f, foo)998            def test_one(self, f, foo):999                self._test(f, foo)1000        SomeTest = patch.multiple(1001            foo_name, f=DEFAULT, g=3, foo=DEFAULT1002        )(SomeTest)1003        thing = SomeTest()1004        thing.test_one()1005        thing.test_two()1006        self.assertEqual(Foo.f, original_f)1007        self.assertEqual(Foo.g, original_g)1008    def test_patch_multiple_create(self):1009        patcher = patch.multiple(Foo, blam='blam')1010        self.assertRaises(AttributeError, patcher.start)1011        patcher = patch.multiple(Foo, blam='blam', create=True)1012        patcher.start()1013        try:1014            self.assertEqual(Foo.blam, 'blam')1015        finally:1016            patcher.stop()1017        self.assertFalse(hasattr(Foo, 'blam'))1018    def test_patch_multiple_spec_set(self):1019        # if spec_set works then we can assume that spec and autospec also1020        # work as the underlying machinery is the same1021        patcher = patch.multiple(Foo, foo=DEFAULT, spec_set=['a', 'b'])1022        result = patcher.start()1023        try:1024            self.assertEqual(Foo.foo, result['foo'])1025            Foo.foo.a(1)1026            Foo.foo.b(2)1027            Foo.foo.a.assert_called_with(1)1028            Foo.foo.b.assert_called_with(2)1029            self.assertRaises(AttributeError, setattr, Foo.foo, 'c', None)1030        finally:1031            patcher.stop()1032    def test_patch_multiple_new_callable(self):1033        class Thing(object):1034            pass1035        patcher = patch.multiple(1036            Foo, f=DEFAULT, g=DEFAULT, new_callable=Thing1037        )1038        result = patcher.start()1039        try:1040            self.assertIs(Foo.f, result['f'])1041            self.assertIs(Foo.g, result['g'])1042            self.assertIsInstance(Foo.f, Thing)1043            self.assertIsInstance(Foo.g, Thing)1044            self.assertIsNot(Foo.f, Foo.g)1045        finally:1046            patcher.stop()1047    def test_nested_patch_failure(self):1048        original_f = Foo.f1049        original_g = Foo.g1050        @patch.object(Foo, 'g', 1)1051        @patch.object(Foo, 'missing', 1)1052        @patch.object(Foo, 'f', 1)1053        def thing1():1054            pass1055        @patch.object(Foo, 'missing', 1)1056        @patch.object(Foo, 'g', 1)1057        @patch.object(Foo, 'f', 1)1058        def thing2():1059            pass1060        @patch.object(Foo, 'g', 1)1061        @patch.object(Foo, 'f', 1)1062        @patch.object(Foo, 'missing', 1)1063        def thing3():1064            pass1065        for func in thing1, thing2, thing3:1066            self.assertRaises(AttributeError, func)1067            self.assertEqual(Foo.f, original_f)1068            self.assertEqual(Foo.g, original_g)1069    def test_new_callable_failure(self):1070        original_f = Foo.f1071        original_g = Foo.g1072        original_foo = Foo.foo1073        def crasher():1074            raise NameError('crasher')1075        @patch.object(Foo, 'g', 1)1076        @patch.object(Foo, 'foo', new_callable=crasher)1077        @patch.object(Foo, 'f', 1)1078        def thing1():1079            pass1080        @patch.object(Foo, 'foo', new_callable=crasher)1081        @patch.object(Foo, 'g', 1)1082        @patch.object(Foo, 'f', 1)1083        def thing2():1084            pass1085        @patch.object(Foo, 'g', 1)1086        @patch.object(Foo, 'f', 1)1087        @patch.object(Foo, 'foo', new_callable=crasher)1088        def thing3():1089            pass1090        for func in thing1, thing2, thing3:1091            self.assertRaises(NameError, func)1092            self.assertEqual(Foo.f, original_f)1093            self.assertEqual(Foo.g, original_g)1094            self.assertEqual(Foo.foo, original_foo)1095    def test_patch_multiple_failure(self):1096        original_f = Foo.f1097        original_g = Foo.g1098        patcher = patch.object(Foo, 'f', 1)1099        patcher.attribute_name = 'f'1100        good = patch.object(Foo, 'g', 1)1101        good.attribute_name = 'g'1102        bad = patch.object(Foo, 'missing', 1)1103        bad.attribute_name = 'missing'1104        for additionals in [good, bad], [bad, good]:1105            patcher.additional_patchers = additionals1106            @patcher1107            def func():1108                pass1109            self.assertRaises(AttributeError, func)1110            self.assertEqual(Foo.f, original_f)1111            self.assertEqual(Foo.g, original_g)1112    def test_patch_multiple_new_callable_failure(self):1113        original_f = Foo.f1114        original_g = Foo.g1115        original_foo = Foo.foo1116        def crasher():1117            raise NameError('crasher')1118        patcher = patch.object(Foo, 'f', 1)1119        patcher.attribute_name = 'f'1120        good = patch.object(Foo, 'g', 1)1121        good.attribute_name = 'g'1122        bad = patch.object(Foo, 'foo', new_callable=crasher)1123        bad.attribute_name = 'foo'1124        for additionals in [good, bad], [bad, good]:1125            patcher.additional_patchers = additionals1126            @patcher1127            def func():1128                pass1129            self.assertRaises(NameError, func)1130            self.assertEqual(Foo.f, original_f)1131            self.assertEqual(Foo.g, original_g)1132            self.assertEqual(Foo.foo, original_foo)1133    def test_patch_multiple_string_subclasses(self):1134        Foo = type('Foo', (str,), {'fish': 'tasty'})1135        foo = Foo()1136        @patch.multiple(foo, fish='nearly gone')1137        def test():1138            self.assertEqual(foo.fish, 'nearly gone')1139        test()1140        self.assertEqual(foo.fish, 'tasty')1141    @patch('unittest.mock.patch.TEST_PREFIX', 'foo')1142    def test_patch_test_prefix(self):1143        class Foo(object):1144            thing = 'original'1145            def foo_one(self):1146                return self.thing1147            def foo_two(self):1148                return self.thing1149            def test_one(self):1150                return self.thing1151            def test_two(self):1152                return self.thing1153        Foo = patch.object(Foo, 'thing', 'changed')(Foo)1154        foo = Foo()1155        self.assertEqual(foo.foo_one(), 'changed')1156        self.assertEqual(foo.foo_two(), 'changed')1157        self.assertEqual(foo.test_one(), 'original')1158        self.assertEqual(foo.test_two(), 'original')1159    @patch('unittest.mock.patch.TEST_PREFIX', 'bar')1160    def test_patch_dict_test_prefix(self):1161        class Foo(object):1162            def bar_one(self):1163                return dict(the_dict)1164            def bar_two(self):1165                return dict(the_dict)1166            def test_one(self):1167                return dict(the_dict)1168            def test_two(self):1169                return dict(the_dict)1170        the_dict = {'key': 'original'}1171        Foo = patch.dict(the_dict, key='changed')(Foo)1172        foo =Foo()1173        self.assertEqual(foo.bar_one(), {'key': 'changed'})1174        self.assertEqual(foo.bar_two(), {'key': 'changed'})1175        self.assertEqual(foo.test_one(), {'key': 'original'})1176        self.assertEqual(foo.test_two(), {'key': 'original'})1177    def test_patch_with_spec_mock_repr(self):1178        for arg in ('spec', 'autospec', 'spec_set'):1179            p = patch('%s.SomeClass' % __name__, **{arg: True})1180            m = p.start()1181            try:1182                self.assertIn(" name='SomeClass'", repr(m))1183                self.assertIn(" name='SomeClass.class_attribute'",1184                              repr(m.class_attribute))1185                self.assertIn(" name='SomeClass()'", repr(m()))1186                self.assertIn(" name='SomeClass().class_attribute'",1187                              repr(m().class_attribute))1188            finally:1189                p.stop()1190    def test_patch_nested_autospec_repr(self):1191        with patch('unittest.test.testmock.support', autospec=True) as m:1192            self.assertIn(" name='support.SomeClass.wibble()'",1193                          repr(m.SomeClass.wibble()))1194            self.assertIn(" name='support.SomeClass().wibble()'",1195                          repr(m.SomeClass().wibble()))1196    def test_mock_calls_with_patch(self):1197        for arg in ('spec', 'autospec', 'spec_set'):1198            p = patch('%s.SomeClass' % __name__, **{arg: True})1199            m = p.start()1200            try:1201                m.wibble()1202                kalls = [call.wibble()]1203                self.assertEqual(m.mock_calls, kalls)1204                self.assertEqual(m.method_calls, kalls)1205                self.assertEqual(m.wibble.mock_calls, [call()])1206                result = m()1207                kalls.append(call())1208                self.assertEqual(m.mock_calls, kalls)1209                result.wibble()1210                kalls.append(call().wibble())1211                self.assertEqual(m.mock_calls, kalls)1212                self.assertEqual(result.mock_calls, [call.wibble()])1213                self.assertEqual(result.wibble.mock_calls, [call()])1214                self.assertEqual(result.method_calls, [call.wibble()])1215            finally:1216                p.stop()1217    def test_patch_imports_lazily(self):1218        sys.modules.pop('squizz', None)1219        p1 = patch('squizz.squozz')1220        self.assertRaises(ImportError, p1.start)1221        squizz = Mock()1222        squizz.squozz = 61223        sys.modules['squizz'] = squizz1224        p1 = patch('squizz.squozz')1225        squizz.squozz = 31226        p1.start()1227        p1.stop()1228        self.assertEqual(squizz.squozz, 3)1229    def test_patch_propogrates_exc_on_exit(self):1230        class holder:1231            exc_info = None, None, None1232        class custom_patch(_patch):1233            def __exit__(self, etype=None, val=None, tb=None):1234                _patch.__exit__(self, etype, val, tb)1235                holder.exc_info = etype, val, tb1236            stop = __exit__1237        def with_custom_patch(target):1238            getter, attribute = _get_target(target)1239            return custom_patch(1240                getter, attribute, DEFAULT, None, False, None,1241                None, None, {}1242            )1243        @with_custom_patch('squizz.squozz')1244        def test(mock):1245            raise RuntimeError1246        self.assertRaises(RuntimeError, test)1247        self.assertIs(holder.exc_info[0], RuntimeError)1248        self.assertIsNotNone(holder.exc_info[1],1249                            'exception value not propgated')1250        self.assertIsNotNone(holder.exc_info[2],1251                            'exception traceback not propgated')1252    def test_create_and_specs(self):1253        for kwarg in ('spec', 'spec_set', 'autospec'):1254            p = patch('%s.doesnotexist' % __name__, create=True,1255                      **{kwarg: True})1256            self.assertRaises(TypeError, p.start)1257            self.assertRaises(NameError, lambda: doesnotexist)1258            # check that spec with create is innocuous if the original exists1259            p = patch(MODNAME, create=True, **{kwarg: True})1260            p.start()1261            p.stop()1262    def test_multiple_specs(self):1263        original = PTModule1264        for kwarg in ('spec', 'spec_set'):1265            p = patch(MODNAME, autospec=0, **{kwarg: 0})1266            self.assertRaises(TypeError, p.start)1267            self.assertIs(PTModule, original)1268        for kwarg in ('spec', 'autospec'):1269            p = patch(MODNAME, spec_set=0, **{kwarg: 0})1270            self.assertRaises(TypeError, p.start)1271            self.assertIs(PTModule, original)1272        for kwarg in ('spec_set', 'autospec'):1273            p = patch(MODNAME, spec=0, **{kwarg: 0})1274            self.assertRaises(TypeError, p.start)1275            self.assertIs(PTModule, original)1276    def test_specs_false_instead_of_none(self):1277        p = patch(MODNAME, spec=False, spec_set=False, autospec=False)1278        mock = p.start()1279        try:1280            # no spec should have been set, so attribute access should not fail1281            mock.does_not_exist1282            mock.does_not_exist = 31283        finally:1284            p.stop()1285    def test_falsey_spec(self):1286        for kwarg in ('spec', 'autospec', 'spec_set'):1287            p = patch(MODNAME, **{kwarg: 0})1288            m = p.start()1289            try:1290                self.assertRaises(AttributeError, getattr, m, 'doesnotexit')1291            finally:1292                p.stop()1293    def test_spec_set_true(self):1294        for kwarg in ('spec', 'autospec'):1295            p = patch(MODNAME, spec_set=True, **{kwarg: True})1296            m = p.start()1297            try:1298                self.assertRaises(AttributeError, setattr, m,1299                                  'doesnotexist', 'something')1300                self.assertRaises(AttributeError, getattr, m, 'doesnotexist')1301            finally:1302                p.stop()1303    def test_callable_spec_as_list(self):1304        spec = ('__call__',)1305        p = patch(MODNAME, spec=spec)1306        m = p.start()1307        try:1308            self.assertTrue(callable(m))1309        finally:1310            p.stop()1311    def test_not_callable_spec_as_list(self):1312        spec = ('foo', 'bar')1313        p = patch(MODNAME, spec=spec)1314        m = p.start()1315        try:1316            self.assertFalse(callable(m))1317        finally:1318            p.stop()1319    def test_patch_stopall(self):1320        unlink = os.unlink1321        chdir = os.chdir1322        path = os.path1323        patch('os.unlink', something).start()1324        patch('os.chdir', something_else).start()1325        @patch('os.path')1326        def patched(mock_path):1327            patch.stopall()1328            self.assertIs(os.path, mock_path)1329            self.assertIs(os.unlink, unlink)1330            self.assertIs(os.chdir, chdir)1331        patched()1332        self.assertIs(os.path, path)1333if __name__ == '__main__':...test_responses.py
Source:test_responses.py  
1import pytest2from origin.api import (3    BadRequest,4    MovedPermanently,5    TemporaryRedirect,6)7from .endpoints import (8    EndpointReturnsGeneric,9    EndpointRaisesGeneric,10    EndpointReturnsResponseModel,11    EndpointWithRequestAndResponseModels,12)13class TestEndpointResponse:14    """Testing different responses data types."""15    def test__health_check__should_return_status_200(16            self,17            client,18    ):19        """TODO."""20        # -- Act -------------------------------------------------------------21        r = client.get('/health')22        # -- Assert ----------------------------------------------------------23        assert r.status_code == 20024    @pytest.mark.parametrize('obj, response_body', [25        ('string-body', 'string-body'),26        (b'bytes-body', 'bytes-body'),27        # TODO ByteStream, more?28    ])29    def test__endpoint_returns_string_alike__should_return_string_as_body(30            self,31            obj,32            response_body,33            app,34            client,35    ):36        """TODO."""37        # -- Arrange ---------------------------------------------------------38        app.add_endpoint(39            method='POST',40            path='/something',41            endpoint=EndpointReturnsGeneric(obj),42        )43        # -- Act -------------------------------------------------------------44        r = client.post('/something')45        # -- Assert ----------------------------------------------------------46        assert r.get_data(as_text=True) == response_body47        assert r.headers['Content-Type'] == 'text/html; charset=utf-8'48    def test__endpoint_returns_dict__should_return_dict_as_body(49            self,50            app,51            client,52    ):53        """TODO."""54        # -- Arrange ---------------------------------------------------------55        response_data = {56            'foo': 'bar',57            'something': {58                'foo': 1,59                'bar': 22.2,60            },61        }62        app.add_endpoint(63            method='POST',64            path='/something',65            endpoint=EndpointReturnsGeneric(response_data),66        )67        # -- Act -------------------------------------------------------------68        r = client.post('/something')69        # -- Assert ----------------------------------------------------------70        assert r.json == response_data71        assert r.headers['Content-Type'] == 'application/json'72    @pytest.mark.parametrize('status_code, obj', [73        (301, MovedPermanently('http://something.com/')),74        (307, TemporaryRedirect('http://something.com/')),75        (400, BadRequest()),76    ])77    def test__endpoint_raises_http_response__should_format_response_appropriately(  # noqa: E50178            self,79            status_code,80            obj,81            app,82            client,83    ):84        """TODO."""85        # -- Arrange ---------------------------------------------------------86        app.add_endpoint(87            method='POST',88            path='/something',89            endpoint=EndpointRaisesGeneric(obj),90        )91        # -- Act -------------------------------------------------------------92        r = client.post('/something')93        # -- Assert ----------------------------------------------------------94        assert r.status_code == status_code95    def test__endpoint_raises_exception__should_return_status_500(96            self,97            app,98            client,99    ):100        """TODO."""101        # -- Arrange ---------------------------------------------------------102        app.add_endpoint(103            method='POST',104            path='/something',105            endpoint=EndpointRaisesGeneric(Exception('foo bar')),106        )107        # -- Act -------------------------------------------------------------108        r = client.post('/something')109        # -- Assert ----------------------------------------------------------110        assert r.status_code == 500111    def test__endpoint_returns_response_model__should_format_response_appropriately(  # noqa: E501112            self,113            app,114            client,115    ):116        """TODO."""117        # -- Arrange ---------------------------------------------------------118        app.add_endpoint(119            method='POST',120            path='/something',121            endpoint=EndpointReturnsResponseModel(),122        )123        # -- Act -------------------------------------------------------------124        r = client.post('/something')125        # -- Assert ----------------------------------------------------------126        assert r.headers['Content-Type'] == 'application/json'127        assert r.json == {128            'success': True,129            'something': 'something',130        }131    def test__endpoint_with_request_and_response_models(132            self,133            app,134            client,135    ):136        """TODO."""137        # -- Arrange ---------------------------------------------------------138        app.add_endpoint(139            method='POST',140            path='/something',141            endpoint=EndpointWithRequestAndResponseModels(),142        )143        # -- Act -------------------------------------------------------------144        r = client.post(145            path='/something',146            json={'something': 'Hello world'},147        )148        # -- Assert ----------------------------------------------------------149        assert r.headers['Content-Type'] == 'application/json'150        assert r.json == {151            'success': True,152            'something': 'Hello world',153        }154class TestEndpointRedirect:155    """TODO."""156    @pytest.mark.parametrize('status_code, response', [157        (301, MovedPermanently('http://something.com/')),158        (307, TemporaryRedirect('http://something.com/')),159    ])160    def test__endpoint_returns_redirect(161            self,162            status_code,163            response,164            app,165            client,166    ):167        """TODO."""168        # -- Arrange ---------------------------------------------------------169        app.add_endpoint(170            method='GET',171            path='/something',172            endpoint=EndpointReturnsGeneric(response),173        )174        # -- Act -------------------------------------------------------------175        r = client.get('/something')176        # -- Assert ----------------------------------------------------------177        assert r.status_code == status_code178        assert r.headers['Location'] == 'http://something.com/'179    @pytest.mark.parametrize('status_code, response', [180        (301, MovedPermanently('http://something.com/')),181        (307, TemporaryRedirect('http://something.com/')),182    ])183    def test__endpoint_raises_redirect(184            self,185            status_code,186            response,187            app,188            client,189    ):190        """TODO."""191        # -- Arrange ---------------------------------------------------------192        app.add_endpoint(193            method='POST',194            path='/something',195            endpoint=EndpointRaisesGeneric(response),196        )197        # -- Act -------------------------------------------------------------198        r = client.post('/something')199        # -- Assert ----------------------------------------------------------200        assert r.status_code == status_code..._testwith.py
Source:_testwith.py  
1# Copyright (C) 2007-2012 Michael Foord & the mock team2# E-mail: fuzzyman AT voidspace DOT org DOT uk3# http://www.voidspace.org.uk/python/mock/4from __future__ import with_statement5from tests.support import unittest2, is_instance6from mock import MagicMock, Mock, patch, sentinel, mock_open, call7from tests.support_with import catch_warnings, nested8something  = sentinel.Something9something_else  = sentinel.SomethingElse10class WithTest(unittest2.TestCase):11    def test_with_statement(self):12        with patch('tests._testwith.something', sentinel.Something2):13            self.assertEqual(something, sentinel.Something2, "unpatched")14        self.assertEqual(something, sentinel.Something)15    def test_with_statement_exception(self):16        try:17            with patch('tests._testwith.something', sentinel.Something2):18                self.assertEqual(something, sentinel.Something2, "unpatched")19                raise Exception('pow')20        except Exception:21            pass22        else:23            self.fail("patch swallowed exception")24        self.assertEqual(something, sentinel.Something)25    def test_with_statement_as(self):26        with patch('tests._testwith.something') as mock_something:27            self.assertEqual(something, mock_something, "unpatched")28            self.assertTrue(is_instance(mock_something, MagicMock),29                            "patching wrong type")30        self.assertEqual(something, sentinel.Something)31    def test_patch_object_with_statement(self):32        class Foo(object):33            something = 'foo'34        original = Foo.something35        with patch.object(Foo, 'something'):36            self.assertNotEqual(Foo.something, original, "unpatched")37        self.assertEqual(Foo.something, original)38    def test_with_statement_nested(self):39        with catch_warnings(record=True):40            # nested is deprecated in Python 2.741            with nested(patch('tests._testwith.something'),42                    patch('tests._testwith.something_else')) as (mock_something, mock_something_else):43                self.assertEqual(something, mock_something, "unpatched")44                self.assertEqual(something_else, mock_something_else,45                                 "unpatched")46        self.assertEqual(something, sentinel.Something)47        self.assertEqual(something_else, sentinel.SomethingElse)48    def test_with_statement_specified(self):49        with patch('tests._testwith.something', sentinel.Patched) as mock_something:50            self.assertEqual(something, mock_something, "unpatched")51            self.assertEqual(mock_something, sentinel.Patched, "wrong patch")52        self.assertEqual(something, sentinel.Something)53    def testContextManagerMocking(self):54        mock = Mock()55        mock.__enter__ = Mock()56        mock.__exit__ = Mock()57        mock.__exit__.return_value = False58        with mock as m:59            self.assertEqual(m, mock.__enter__.return_value)60        mock.__enter__.assert_called_with()61        mock.__exit__.assert_called_with(None, None, None)62    def test_context_manager_with_magic_mock(self):63        mock = MagicMock()64        with self.assertRaises(TypeError):65            with mock:66                'foo' + 367        mock.__enter__.assert_called_with()68        self.assertTrue(mock.__exit__.called)69    def test_with_statement_same_attribute(self):70        with patch('tests._testwith.something', sentinel.Patched) as mock_something:71            self.assertEqual(something, mock_something, "unpatched")72            with patch('tests._testwith.something') as mock_again:73                self.assertEqual(something, mock_again, "unpatched")74            self.assertEqual(something, mock_something,75                             "restored with wrong instance")76        self.assertEqual(something, sentinel.Something, "not restored")77    def test_with_statement_imbricated(self):78        with patch('tests._testwith.something') as mock_something:79            self.assertEqual(something, mock_something, "unpatched")80            with patch('tests._testwith.something_else') as mock_something_else:81                self.assertEqual(something_else, mock_something_else,82                                 "unpatched")83        self.assertEqual(something, sentinel.Something)84        self.assertEqual(something_else, sentinel.SomethingElse)85    def test_dict_context_manager(self):86        foo = {}87        with patch.dict(foo, {'a': 'b'}):88            self.assertEqual(foo, {'a': 'b'})89        self.assertEqual(foo, {})90        with self.assertRaises(NameError):91            with patch.dict(foo, {'a': 'b'}):92                self.assertEqual(foo, {'a': 'b'})93                raise NameError('Konrad')94        self.assertEqual(foo, {})95class TestMockOpen(unittest2.TestCase):96    def test_mock_open(self):97        mock = mock_open()98        with patch('%s.open' % __name__, mock, create=True) as patched:99            self.assertIs(patched, mock)100            open('foo')101        mock.assert_called_once_with('foo')102    def test_mock_open_context_manager(self):103        mock = mock_open()104        handle = mock.return_value105        with patch('%s.open' % __name__, mock, create=True):106            with open('foo') as f:107                f.read()108        expected_calls = [call('foo'), call().__enter__(), call().read(),109                          call().__exit__(None, None, None)]110        self.assertEqual(mock.mock_calls, expected_calls)111        self.assertIs(f, handle)112    def test_explicit_mock(self):113        mock = MagicMock()114        mock_open(mock)115        with patch('%s.open' % __name__, mock, create=True) as patched:116            self.assertIs(patched, mock)117            open('foo')118        mock.assert_called_once_with('foo')119    def test_read_data(self):120        mock = mock_open(read_data='foo')121        with patch('%s.open' % __name__, mock, create=True):122            h = open('bar')123            result = h.read()124        self.assertEqual(result, 'foo')125if __name__ == '__main__':...testwith.py
Source:testwith.py  
1import unittest2from warnings import catch_warnings3from unittest.test.testmock.support import is_instance4from unittest.mock import MagicMock, Mock, patch, sentinel, mock_open, call5something  = sentinel.Something6something_else  = sentinel.SomethingElse7class WithTest(unittest.TestCase):8    def test_with_statement(self):9        with patch('%s.something' % __name__, sentinel.Something2):10            self.assertEqual(something, sentinel.Something2, "unpatched")11        self.assertEqual(something, sentinel.Something)12    def test_with_statement_exception(self):13        try:14            with patch('%s.something' % __name__, sentinel.Something2):15                self.assertEqual(something, sentinel.Something2, "unpatched")16                raise Exception('pow')17        except Exception:18            pass19        else:20            self.fail("patch swallowed exception")21        self.assertEqual(something, sentinel.Something)22    def test_with_statement_as(self):23        with patch('%s.something' % __name__) as mock_something:24            self.assertEqual(something, mock_something, "unpatched")25            self.assertTrue(is_instance(mock_something, MagicMock),26                            "patching wrong type")27        self.assertEqual(something, sentinel.Something)28    def test_patch_object_with_statement(self):29        class Foo(object):30            something = 'foo'31        original = Foo.something32        with patch.object(Foo, 'something'):33            self.assertNotEqual(Foo.something, original, "unpatched")34        self.assertEqual(Foo.something, original)35    def test_with_statement_nested(self):36        with catch_warnings(record=True):37            with patch('%s.something' % __name__) as mock_something, patch('%s.something_else' % __name__) as mock_something_else:38                self.assertEqual(something, mock_something, "unpatched")39                self.assertEqual(something_else, mock_something_else,40                                 "unpatched")41        self.assertEqual(something, sentinel.Something)42        self.assertEqual(something_else, sentinel.SomethingElse)43    def test_with_statement_specified(self):44        with patch('%s.something' % __name__, sentinel.Patched) as mock_something:45            self.assertEqual(something, mock_something, "unpatched")46            self.assertEqual(mock_something, sentinel.Patched, "wrong patch")47        self.assertEqual(something, sentinel.Something)48    def testContextManagerMocking(self):49        mock = Mock()50        mock.__enter__ = Mock()51        mock.__exit__ = Mock()52        mock.__exit__.return_value = False53        with mock as m:54            self.assertEqual(m, mock.__enter__.return_value)55        mock.__enter__.assert_called_with()56        mock.__exit__.assert_called_with(None, None, None)57    def test_context_manager_with_magic_mock(self):58        mock = MagicMock()59        with self.assertRaises(TypeError):60            with mock:61                'foo' + 362        mock.__enter__.assert_called_with()63        self.assertTrue(mock.__exit__.called)64    def test_with_statement_same_attribute(self):65        with patch('%s.something' % __name__, sentinel.Patched) as mock_something:66            self.assertEqual(something, mock_something, "unpatched")67            with patch('%s.something' % __name__) as mock_again:68                self.assertEqual(something, mock_again, "unpatched")69            self.assertEqual(something, mock_something,70                             "restored with wrong instance")71        self.assertEqual(something, sentinel.Something, "not restored")72    def test_with_statement_imbricated(self):73        with patch('%s.something' % __name__) as mock_something:74            self.assertEqual(something, mock_something, "unpatched")75            with patch('%s.something_else' % __name__) as mock_something_else:76                self.assertEqual(something_else, mock_something_else,77                                 "unpatched")78        self.assertEqual(something, sentinel.Something)79        self.assertEqual(something_else, sentinel.SomethingElse)80    def test_dict_context_manager(self):81        foo = {}82        with patch.dict(foo, {'a': 'b'}):83            self.assertEqual(foo, {'a': 'b'})84        self.assertEqual(foo, {})85        with self.assertRaises(NameError):86            with patch.dict(foo, {'a': 'b'}):87                self.assertEqual(foo, {'a': 'b'})88                raise NameError('Konrad')89        self.assertEqual(foo, {})90class TestMockOpen(unittest.TestCase):91    def test_mock_open(self):92        mock = mock_open()93        with patch('%s.open' % __name__, mock, create=True) as patched:94            self.assertIs(patched, mock)95            open('foo')96        mock.assert_called_once_with('foo')97    def test_mock_open_context_manager(self):98        mock = mock_open()99        handle = mock.return_value100        with patch('%s.open' % __name__, mock, create=True):101            with open('foo') as f:102                f.read()103        expected_calls = [call('foo'), call().__enter__(), call().read(),104                          call().__exit__(None, None, None)]105        self.assertEqual(mock.mock_calls, expected_calls)106        self.assertIs(f, handle)107    def test_explicit_mock(self):108        mock = MagicMock()109        mock_open(mock)110        with patch('%s.open' % __name__, mock, create=True) as patched:111            self.assertIs(patched, mock)112            open('foo')113        mock.assert_called_once_with('foo')114    def test_read_data(self):115        mock = mock_open(read_data='foo')116        with patch('%s.open' % __name__, mock, create=True):117            h = open('bar')118            result = h.read()119        self.assertEqual(result, 'foo')120if __name__ == '__main__':...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
