pytest中参数的笛卡尔乘积的参数化测试 [英] parameterized test with cartesian product of arguments in pytest
问题描述
只是想知道,有没有(更)优雅的笛卡尔积参数化方法?这是我目前想到的:
Just wondering, is there any (more) elegant way of parameterizing with the cartesian product? This is what I figured out so far:
numbers = [1,2,3,4,5]
vowels = ['a','e','i','o','u']
consonants = ['x','y','z']
cartesian = [elem for elem in itertools.product(*[numbers,vowels,consonants])]
@pytest.fixture(params=cartesian)
def someparams(request):
return request.param
def test_something(someparams):
pass
至少我想在fixture函数中封装数字、元音、辅音和笛卡尔.
At least I'd like to encapsulate numbers, vowels, consonants and cartesian in the fixture function.
推荐答案
我可以想到两种方法来做到这一点.一种使用参数化的装置,一种参数化测试函数.由您决定哪一种更优雅.
I can think of two ways to do this. One uses parametrized fixtures, and one parametrizes the test function. It's up to you which one you find more elegant.
这是参数化的测试函数:
Here is the test function parametrized:
import itertools
import pytest
numbers = [1,2,3,4,5]
vowels = ['a','e','i','o','u']
consonants = ['x','y','z']
@pytest.mark.parametrize('number,vowel,consonant',
itertools.product(numbers, vowels, consonants)
)
def test(number, vowel, consonant):
pass
值得注意的是,parametrize 装饰器的第二个参数可以是一个可迭代对象,而不仅仅是一个列表.
Of note, the second argument to the parametrize decorator can be an iterable, not just a list.
这是通过参数化每个灯具来实现的:
Here is how you do it by parametrizing each fixture:
import pytest
numbers = [1,2,3,4,5]
vowels = ['a','e','i','o','u']
consonants = ['x','y','z']
@pytest.fixture(params=numbers)
def number(request):
return request.param
@pytest.fixture(params=vowels)
def vowel(request):
return request.param
@pytest.fixture(params=consonants)
def consonant(request):
return request.param
def test(number, vowel, consonant):
pass
你的直觉是对的.通过参数化多个装置中的每一个,pytest 负责创建所有出现的排列.
Your intuition was correct. By parametrizing each of multiple fixtures, pytest takes care of creating all the permutations that arise.
测试输出是相同的.这是一个示例(我使用 -vv 选项运行 py.test):
The test output is identical. Here is a sample (I ran py.test with the -vv option):
test_bar.py:22: test[1-a-x] PASSED
test_bar.py:22: test[1-a-y] PASSED
test_bar.py:22: test[1-a-z] PASSED
test_bar.py:22: test[1-e-x] PASSED
test_bar.py:22: test[1-e-y] PASSED
test_bar.py:22: test[1-e-z] PASSED
test_bar.py:22: test[1-i-x] PASSED
这篇关于pytest中参数的笛卡尔乘积的参数化测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!