我想编写一个测试来帮助我确定我正在使用的库的 API 是否没有改变,例如升级后。
如果我创建一个“盲模拟”对象,那么模拟将始终使用一种方法并且测试将通过,但我的应用程序将与实际库中断。
我知道有一种修补现有对象的方法:
@patch.object(ZipFile, 'namelist')
def test_my_method(self, mocked_zipfile):
这至少会检查 namelist
方法是否确实存在于原始对象上,但它仍然允许我在模拟内部对象时打错字:
@patch.object(ZipFile, 'namelist')
def test_my_method(self, mocked_zipfile):
mocked_zipfile.namlist.return_value = [ 'one.txt', 'two.txt' ]
当我在测试和测试代码中输入错误 (namlist
) 时,测试会默默地通过。
有什么方法可以防止猴子修补模拟对象的不存在的方法,除了每次编写测试时都要牢记这一点(当你有一个团队并且你想自动检查这些方法时,这不是最好的方法东西)?
最佳答案
您可以使用 autospec=True
修补 zipfile.Zipfile
:
If you set
autospec=True
then the mock with be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise aTypeError
if they are called with the wrong signature. For mocks replacing a class, their return value (the ‘instance’) will have the same spec as the class.
以下测试将因 AttributeError: Mock object has no attribute 'namlist'
而失败:
from unittest import TestCase
from mock import patch
class MyTestCase(TestCase):
@patch.object(ZipFile, 'namelist', autospec=True)
def test_my_method(self, mocked_zipfile):
mocked_zipfile.namlist.return_value = [ 'one.txt', 'two.txt' ]
希望对您有所帮助。
关于python - 如何禁止猴子修补不存在的模拟方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23291841/