我可以在 python 单元测试中伪造/模拟我的模拟对象的类型吗

Can I fake/mock the type of my mock objects in python unittests(我可以在 python 单元测试中伪造/模拟我的模拟对象的类型吗)
本文介绍了我可以在 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

使用类或实例作为 specspec_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 单元测试中伪造/模拟我的模拟对象的类型吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)