Python unittest mock: Is it possible to mock the value of a method's default arguments at test time?

前端 未结 3 1509
梦毁少年i
梦毁少年i 2020-12-20 12:09

I have a method that accepts default arguments:

def build_url(endpoint, host=settings.DEFAULT_HOST):
    return \'{}{}\'.format(host, endpoint)
3条回答
  •  再見小時候
    2020-12-20 12:43

    An alternate way to do this: Use functools.partial to provide the "default" args you want. This isn't technically the same thing as overriding them; the call-ee sees an explicit arg, but the call-er doesn't have to provide it. That's close enough most of the time, and it does the Right Thing after the context manager exits:

    # mymodule.py
    def myfunction(arg=17):
        return arg
    
    # test_mymodule.py
    from functools import partial
    from mock import patch
    
    import mymodule
    
    class TestMyModule(TestCase):
        def test_myfunc(self):
            patched = partial(mymodule.myfunction, arg=23)
            with patch('mymodule.myfunction', patched):
                self.assertEqual(23, mymodule.myfunction())  # Passes; default overridden
            self.assertEqual(17, mymodule.myfunction()) # Also passes; original default restored
    

    I use this for overriding default config file locations when testing. Credit where due, I got the idea from Danilo Bargen here

提交回复
热议问题