python - 如何禁止猴子修补不存在的模拟方法?

标签 python unit-testing python-2.7 monkeypatching python-unittest

我想编写一个测试来帮助我确定我正在使用的库的 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 a TypeError 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/

相关文章:

python - 电子商务应用程序中的 Django 用户模型扩展

python - 如何在不同的输入上使用经过训练的模型

javascript - 具有隔离范围的单元测试 AngularJS 指令 - 如何获取输出的绑定(bind)?

javascript - AngularJS:测试外部脚本是否有效加载

python - 删除 python Barcode.py 库中条形码下方的文本

python - 同一向量的归一化在两种情况下给出不同的值?

python - 如何使用python获取纬度和经度

python - 如何处理utf-8编码的String和BeautifulSoup?

python - 为什么我不能通过 Python 中的键访问列表?

c# - 如何在github仓库中找到文件路径?