SecretIndividual
SecretIndividual

Reputation: 2519

Mock not seen by pytest

I got a class that describes an entity and am trying to write unit tests that should check if certain fields are defaulted to the correct value. One of those fields uses datetime.now() to set the default state.

I am having trouble trying to mock this call to now() in my test. I am guessing it has to do with my folder structure.

src
    classes
        MyClass.py
pytests
    test_MyClass.py

The MyClass definition:

from datetime import datetime
class MyClass:
    def __init__(self):
        self.mom = datetime.now()

I am using @mock.patch as follows (inside test_MyClass.py):

import pytest
import sys

from unittest import mock    
sys.path.append(r'C:\python-projects\test\src')
from classes.MyClass import MyClass
@mock.patch('classes.MyClass.datetime.now', return_value = 'timestamp', autospec = True)
@pytest.fixture
def myclass():
    myclass = MyClass()
    yield myclass
    
def test_has_datetime(myclass):
    assert myclass.mom == 'timestamp'

The test ignores the patch.

Upvotes: 2

Views: 1131

Answers (1)

Laurent
Laurent

Reputation: 13458

Try this:

  • make sure you have __init__.py files in src, classesand pytests directories;
  • remove sys.path.append(r'C:\python-projects\test\src')
  • in @mock.patch, replace classes.MyClass.datetime.now with src.classes.MyClass.datetime.now
  • make C:\python-projects\test\ the current working directory and run pytest ./pytests

Otherwise, mocking the datetime module can be easier with packages like freezegun: https://github.com/spulec/freezegun

Upvotes: 1

Related Questions