如何使用pytest对多个数据结构运行相同的测试



我有一个模块,它具有同一抽象基类的各种实现。举个例子,假设我想用基类collections.abc.Collection测试类,它们都有append(element)__contains__。我想要这样的东西:

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个不同的文件中,这些文件看起来几乎相同,除了最上面的导入:

# speicific_collection is different for the 3 classes
from foo.module import specific_collection as CollectionClass

由于我是唯一的开发人员,而且我不经常为此添加测试,所以这没什么大不了的。我仍然想知道如何避免这种代码重复。

只需将pytest.mark.parametrize与类一起使用即可:

import pytest
collection_classes = (
class1,
class2
)
@pytest.mark.parametrize('cls', collection_classes)
def test_contains(cls):
collection = cls()
words = ["foo", "bar", "baz"]
for word in words:
collection.append(word)
for word in words:
assert word in collection        

最新更新