Overriding decorator during unit test in python

后端 未结 1 1104
深忆病人
深忆病人 2020-12-16 21:19

I have a django class based view that I\'m decorating. Unfortunately that decorator makes outside calls to do status checks which is outside the scope of what the unit test

相关标签:
1条回答
  • 2020-12-16 22:03

    I think your gonna have to get into the dark underworld of Mock, but once you get your head around it (if you haven't already) the dark underworld turns into a bright blue heavenly sky of mockiness.

    You could use the patch module of Mock to to patch this decorator so your views using it can become more testable: http://www.voidspace.org.uk/python/mock/patch.html. Personally I have not tried mocking a decorator before but it should work...

    @patch('python.path.to.decorator', new_callable=PropertyMock)
    def my_test(self, decorator_mock):
        # your test code
    

    Give that a whirl.

    You can read about the patch module in Mock here: http://www.voidspace.org.uk/python/mock/patch.html

    edit

    new_callable=PropertyMock is probably not the right thing to do for patching a decorator.

    Perhaps try:

    @patch('python.path.to.decorator', lambda: func: func)
    def my_test(self):
        # your test code
    

    This should in theory patch the decorator so it just returns the function back rather than does all the stuff you have in wrapped.

    0 讨论(0)
提交回复
热议问题