5👍
You should patch
objects in the module you’re testing, not in the module with tests.
Minimal working example based on your code:
app.py
from datetime import datetime
def my_great_func():
# do something
return datetime.now()
tests.py (notice how datetime
in app.py
is patched)
from datetime import datetime
from unittest import mock
from app import my_great_func
@mock.patch('app.datetime')
def test_my_great_func(mocked_datetime):
mocked_datetime.now.return_value = datetime(2010, 1, 1)
assert my_great_func() == datetime(2010, 1, 1)
Test execution results:
$ pytest -vvv tests.py
======================= test session starts =========================
platform linux -- Python 3.5.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
cachedir: .cache
rootdir: /home/xyz/projects/tmp, inifile:
plugins: mock-1.6.2, celery-4.1.0
collected 1 item
tests.py::test_my_great_func PASSED
==================== 1 passed in 0.00 seconds =======================
Source:stackexchange.com