Search code examples
pythonmockingpython-unittesttestcase

Is it available to patch function of function in python testcase?


This is an example.

main/something.py

from example.something import get_utc_time, get_jst_time

print(get_utc_time())
print(get_jst_time())

example/something.py

from django.utils import timezone

def get_utc_time():
    return timezone.now()

def get_jst_time():
    return timezone.now() + timezone.timedelta(hours=9)

I want to do like following testcase. But, this is not available.
Does anyone have any ideas?

testcase

@patch('main.something.example.something.timezone.now')
def test_execute(mock_now):
    ....

Do I have to set both functions as patch like:

@patch('main.something.get_utc_time') and @patch('main.something.get_jst_time')?


Solution

  • You need to patch in the namespace of the thing whose behavior you want to change. In this case you likely need:

    @patch('example.something.timezone.now')
    def test_execute(mock_now):
        mock_now.return_value = 'a mock time'  # probably want to return a time not a string