Unit testing 如何使用pytest对多个数据结构运行相同的测试?
我有一个具有相同抽象基类的各种实现的模块。例如,假设我想用基类Unit testing 如何使用pytest对多个数据结构运行相同的测试?,unit-testing,pytest,Unit Testing,Pytest,我有一个具有相同抽象基类的各种实现的模块。例如,假设我想用基类collections.abc.Collection测试类,这些基类都有append(element)和\uuuu包含
collections.abc.Collection
测试类,这些基类都有append(element)
和\uuuu包含
。我想要这样的东西:
import collections
collection_classes = [list, collections.deque]
@pytest.parameter_values(collection_classes) # what I'm looking for
def test_contains(CollectionClass):
collection = CollectionClass()
words = ["foo", "bar", "baz"]
for word in words:
collection.append(word)
for word in words:
assert word in collection
然后我希望pytest使用所有给定的值执行测试,如果一个(或多个)参数失败,则显示一条可理解的错误消息。基本上就像我将有一个自己的参数测试,只是没有测试代码的重复
我现在在做什么
我有3个类实现了相同的接口。作为一种解决方法,我将测试代码复制到3个不同的文件中,这些文件看起来几乎相同,除了顶部的导入:
# speicific_collection is different for the 3 classes
from foo.module import specific_collection as CollectionClass
因为我是唯一的开发人员,而且我不经常为此添加测试,所以这不是什么大问题。我仍然想知道如何避免这种代码重复。只需在类中使用
pytest.mark.parametize
:
导入pytest
集合\u类=(
第一类,
类别2
)
@pytest.mark.parametize('cls',集合类)
def测试单元包含(cls):
collection=cls()
单词=[“foo”,“bar”,“baz”]
用文字表示:
collection.append(word)
用文字表示:
集合中的断言词
只需在类中使用pytest.mark.parametize
:
导入pytest
集合\u类=(
第一类,
类别2
)
@pytest.mark.parametize('cls',集合类)
def测试单元包含(cls):
collection=cls()
单词=[“foo”,“bar”,“baz”]
用文字表示:
collection.append(word)
用文字表示:
集合中的断言词