I have a method that accepts default arguments:
def build_url(endpoint, host=settings.DEFAULT_HOST):
return \'{}{}\'.format(host, endpoint)
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