pytest 未看到模拟
Mock not seen by pytest
我得到了一个描述实体的 class,我正在尝试编写单元测试来检查某些字段是否默认为正确的值。其中一个字段使用 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
、classes
和 pytests
目录中有 __init__.py 个文件;
- 移除
sys.path.append(r'C:\python-projects\test\src')
- 在@mock.patch中,将
classes.MyClass.datetime.now
替换为src.classes.MyClass.datetime.now
- 使
C:\python-projects\test\
成为当前工作目录并且运行pytest ./pytests
否则,使用像 freezegun
这样的包模拟 datetime 模块会更容易:https://github.com/spulec/freezegun
我得到了一个描述实体的 class,我正在尝试编写单元测试来检查某些字段是否默认为正确的值。其中一个字段使用 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
、classes
和pytests
目录中有 __init__.py 个文件; - 移除
sys.path.append(r'C:\python-projects\test\src')
- 在@mock.patch中,将
classes.MyClass.datetime.now
替换为src.classes.MyClass.datetime.now
- 使
C:\python-projects\test\
成为当前工作目录并且运行pytest ./pytests
否则,使用像 freezegun
这样的包模拟 datetime 模块会更容易:https://github.com/spulec/freezegun