Can I fake/mock the type of my mock objects in python unittests(我可以在 python 单元测试中伪造/模拟我的模拟对象的类型吗)
问题描述
在我的 python 代码中,我检查其中一个参数的类型以确保它是我期望的类型.例如:
In my python code I check the type of one of the parameters to make sure it is of the type I expect. For instance:
def myfunction(dbConnection):
if (type(dbConnection)<>bpgsql.Connection):
r['error'] += ' invalid database connection'
我想传递一个模拟连接以进行测试.有没有办法让模拟对象伪装成正确的类型?
I want to pass a mock connection for testing purposes. Is there a way to make the mock object pretend to be of the correct type?
推荐答案
恕我直言,看来你们不太对劲!
With all due respect, It looks like you guys are not quite right!
如上所述,我可以使用鸭子打字,但有一种方法可以做我最初打算做的事情:
I can use duck typing as said, but there is a way to do what I intended to do in the first place:
来自 http://docs.python.org/dev/library/unittest.mock.html
使用类或实例作为 spec
或 spec_set
的模拟对象能够通过 isintance 测试:
Mock objects that use a class or an instance as a spec
or spec_set
are able to pass isintance tests:
>>>
>>> mock = Mock(spec=SomeClass)
>>> isinstance(mock, SomeClass)
True
>>> mock = Mock(spec_set=SomeClass())
>>> isinstance(mock, SomeClass)
True
所以我的示例代码如下:
so my example code would be like:
m = mock.MagicMock(spec=bpgsql.Connection)
isinstance(m, bpgsql.Connection)
返回真
话虽如此,我并不是在争论在 python 中进行严格的类型检查,我说如果你需要检查它你可以做到,它也适用于测试和模拟.
All that said, I am not arguing for strict type checking in python, I say if you need to check it you can do it and it works with testing and mocking too.
这篇关于我可以在 python 单元测试中伪造/模拟我的模拟对象的类型吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以在 python 单元测试中伪造/模拟我的模拟对


基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01