我有一个描述实体的类,我正在尝试编写单元测试来检查某些字段是否默认为正确的值。其中一个字段使用 datetime.now()
设置默认状态。
我在尝试模拟对 now()
的调用时遇到问题在我的测试中。我猜这与我的文件夹结构有关。
src
classes
MyClass.py
pytests
test_MyClass.py
MyClass 定义:from datetime import datetime
class MyClass:
def __init__(self):
self.mom = datetime.now()
我使用@mock.patch 如下(在 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'
测试忽略补丁。
最佳答案
尝试这个:
src
中有 __init__.py 文件, classes
和 pytests
目录; sys.path.append(r'C:\python-projects\test\src')
classes.MyClass.datetime.now
与 src.classes.MyClass.datetime.now
C:\python-projects\test\
当前工作目录并运行 pytest ./pytests
否则,使用
freezegun
之类的包可以更轻松地模拟 datetime 模块。 :https://github.com/spulec/freezegun
关于python - pytest 没有看到模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66853066/