For testing I want to monkeypatch some modules, in particular os
and datetime
. I am successful in monkeypatching os
but not datetime
:
TypeError: can't set attributes of built-in/extension type 'datetime.datetime'
My setup is:
file_to_test.py
import os
import datetime
def os_function():
return os.path.exists('some_path')
def datetime_function():
return datetime.datetime.now()
test_file.py:
import file_to_test
import datetime
mockdate = datetime.datetime(2000, 1, 1, 0, 0, 0)
def test_function_to_test(monkeypatch):
monkeypatch.setattr(file_to_test.os.path, 'exists', (lambda x: True))
monkeypatch.setattr(file_to_test.datetime.datetime, 'now', (lambda x: mockdate))
file_exists = file_to_test.os_function()
date = file_to_test.datetime_function()
assert file_exists
assert date == mockdate
Thanks!!