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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)