I have a method that accepts default arguments:
def build_url(endpoint, host=settings.DEFAULT_HOST):
return '{}{}'.format(host, endpoint)
I have a test case that exercises this method:
class BuildUrlTestCase(TestCase):
def test_build_url(self):
""" If host and endpoint are supplied result should be 'host/endpoint' """
result = build_url('/end', 'host')
expected = 'host/end'
self.assertEqual(result,expected)
@patch('myapp.settings')
def test_build_url_with_default(self, mock_settings):
""" If only endpoint is supplied should default to settings"""
mock_settings.DEFAULT_HOST = 'domain'
result = build_url('/end')
expected = 'domain/end'
self.assertEqual(result,expected)
If I drop a debug point in build_url
and inspect this attribute settings.DEFAULT_HOST
returns the mocked value. However the test continues to fail and the assertion indicates host
is assigned the value from my actual settings.py
. I know this is because the host
keyword argument is set at import time and my mock is not considered.
debugger
(Pdb) settings
<MagicMock name='settings' id='85761744'>
(Pdb) settings.DEFAULT_HOST
'domain'
(Pdb) host
'host-from-settings.com'
Is there a way to override this value at test time so that I can exercise the default path with a mocked settings
object?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…