Search code examples
pythondjangomockingpytestfixtures

Mocking some fixtures inside a test


I want to mock timezone.now in test AND in fixtures which test retrieve.

def time_to_test():
    return datetime(year=2019, month=4, day=30, hour=6, minute=2, second=3)

I try:

with patch('django.utils.timezone.now', side_effect=time_to_test):
    @pytest.mark.django_db
    def test_only_one(user_helpers, user):
        print(django.utils.timezone.now()) # Here is mocked timezone
        print(user_helpers.created_time) # Here is real time
        assert user_helpers.count == 4

and

@patch('django.utils.timezone.now', side_effect=time_to_test):
@pytest.mark.django_db
def test_only_one(user_helpers, user):
    print(django.utils.timezone.now()) # Here is mocked timezone
    print(user_helpers.created_time) # Here is real time
    assert user_helpers.count == 4

Mocked value not applied in fixtures, because they called before start a test, but I would like have patched this fixtures in this test only.

I don't want to create distinguish fixture or fabric for test.


Solution

  • There are no simple way to resolve it! For example how it works you can see on freezegun and pytest-freezegun Freezegun use sqlite db for save current context and restore it after decorator or context-manager is done.

    Simple answer is:

    @pytest.mark.freeze_time('2019-04-18')
    @pytest.mark.django_db
    def test_only_one(user_helpers, user):
        print(django.utils.timezone.now()) # Here is mocked timezone
        print(user_helpers.created_time) # Here is real time
        assert user_helpers.count == 4