I am new to pytest, i want to create a test for a method called inside a library. So following is my sample usecase.
I have a python library called core:
def get_timestamp(input_example):
# I have an import statement in this file that is, import time
timestamp = time.time()
return f'{input_example}-{timestamp}'
So I want to mock the time.time(), because every time I don't want to get a different timestamp.
following is my pytest code
import time
from core.p_core.common import CommonBase
def test_get_timestamp(mocker):
mock_now = mocker.patch("core.p_core.common.CommonBase.time.time",
return_value=1680087494.2400253)
assert CommonBase.get_timestamp('TEST') == "TEST1680087494.2400253"
But I am getting an error ModuleNotFoundError: No module named core.p_core.common.CommonBase
Please ignore my get_timestamp methods logic, this is just an example.
Thank you.
The issue is solved by updating the test_get_timestamp method as follows.
def test_get_timestamp(mocker):
mock_now = mocker.patch("core.p_core.common.time.time",
return_value=1680087494.2400253)
assert CommonBase.get_timestamp('TEST') == "TEST1680087494.2400253"
mock_now = mocker.patch("core.p_core.common.time.time", return_value=1680087494.2400253) This was the change. Before I was patching core.p_core.common.CommonBase.time.time. But if we need to mock a method(in my example time.time()) that is imported in common.py(common.py is the file in the above example), then I have to pass this core.p_core.common.time.time for mocker.patch