Dow*_*wie 1 python testing mocking pytest
我正在使用py.test和模拟。我无法模拟常量。我的测试修改了分配给常量的dict值。这应该在我的测试中引发一个Exception,但到目前为止还没有。我不确定问题出在什么地方,不胜感激可以帮助您查明问题所在。谢谢。
the_module.py
MY_DICT = {'one': 1, 'two': 2, 'three': 3}
class OneMissingException(Exception):
pass
class Test1(object):
def __init__(self):
self.mydict = MY_DICT
@property
def mydict(self):
return self._mydict
@mydict.setter
def mydict(self, mydict):
if 'one' not in mydict:
raise OneMissingException
self._mydict = mydict
Run Code Online (Sandbox Code Playgroud)
test_themodule.py
import pytest
from unittest import mock
from the_module import Test1, OneMissingException
@pytest.fixture(scope='function')
def my_dict():
return {'one': 1, 'two': 2, 'three': 3}
def test_verify_test1_exception(my_dict):
my_dict.pop('one') # comment this out and test still passes
with mock.patch("the_module.MY_DICT") as mydict:
mydict.return_value.return_value = my_dict
with pytest.raises(OneMissingException):
Test1()
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您不需要模拟(并且您尝试以错误的方式使用它,因为没有人调用MY_DICT并尝试了return_value)
仅使用pytest的Monkeypatch固定装置:
import pytest
from unittest import mock
from the_module import Test1, OneMissingException
@pytest.fixture
def patched_my_dict(monkeypatch):
patched = {'one': 1, 'two': 2, 'three': 3}
monkeypatch.setattr("the_module.MY_DICT", patched)
return patched
def test_verify_test1_exception(patched_my_dict):
patched_my_dict.pop('one') # comment this out and test will not pass
with pytest.raises(OneMissingException):
Test1()
Run Code Online (Sandbox Code Playgroud)