【发布时间】:2015-04-04 12:03:22
【问题描述】:
我正在使用 py.test 和 mock。我无法模拟一个常数。我的测试修改了分配给常量的 dict 值。这应该在我的测试中引发异常,但到目前为止还没有。我不确定问题出在哪里,如果能帮助您找出问题所在,我将不胜感激。谢谢。
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
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()
【问题讨论】:
标签: python testing mocking pytest