0

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!!

Carsten
  • 2,765
  • 1
  • 13
  • 28
  • Does this answer your question? [How to monkeypatch python's datetime.datetime.now with py.test?](https://stackoverflow.com/questions/20503373/how-to-monkeypatch-pythons-datetime-datetime-now-with-py-test) – MrBean Bremen Jan 20 '21 at 19:05
  • Thanks, but I was looking for a more fundamental answer why these modules behave so differently – Carsten Jan 21 '21 at 05:39
  • [Here](https://stackoverflow.com/questions/4481954/trying-to-mock-datetime-date-today-but-not-working) is another similar question. The modules behave differently, because they are implemented in C, so you can't set attributes there the Python way (as shown by the error message). – MrBean Bremen Jan 21 '21 at 18:03

0 Answers0