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

前端 未结 3 1514
梦毁少年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:42

    Functions store their parameter default values in the func_defaults attribute when the function is defined, so you can patch that. Something like

    def test_build_url(self):
        """ If only endpoint is supplied should default to settings"""
    
        # Use `func_defaults` in Python2.x and `__defaults__` in Python3.x.
        with patch.object(build_url, 'func_defaults', ('domain',)):
          result = build_url('/end')
          expected = 'domain/end'
    
        self.assertEqual(result,expected)
    

    I use patch.object as a context manager rather than a decorator to avoid the unnecessary patch object being passed as an argument to test_build_url.

提交回复
热议问题