使用 Pytest,我想编写一个测试函数,该函数接受多个装置作为参数。每个灯具都有几个参数。
例如,test_demo.py 中是一个函数test_squared_is_less_than_10
需要固定装置,negative_integer
and positive_integer
作为参数,然后检查夹具参数的平方是否小于 10。
import pytest
@pytest.fixture(params=[-1, -2, -3])
def negative_integer(request):
return request.param
@pytest.fixture(params=[1, 2, 3])
def positive_integer(request):
return request.param
def test_squared_is_less_than_10(negative_integer, positive_integer):
assert negative_integer ** 2 < 10
assert positive_integer ** 2 < 10
我预计当我在终端中运行 pytest 命令时,总共应执行 6 个测试,即[-1, -2, -3]
for positive_integer
and [1, 2, 3]
for negative_integer
.
然而,pytest 似乎执行嵌套循环类型的迭代,以便执行 9 个测试
IE。[(-1, 1), (-1, 2), (-1, 3), (-2, 1), (-2, 2), (-2, 3), (-3, 1), (-3, 2), (-3, 3)]
.
这是我运行时的输出pytest -v -k "test_squared_is_less"
:
test_squared_is_less_than_10[-1-1] PASSED
test_squared_is_less_than_10[-1-2] PASSED
test_squared_is_less_than_10[-1-3] PASSED
test_squared_is_less_than_10[-2-1] PASSED
test_squared_is_less_than_10[-2-2] PASSED
test_squared_is_less_than_10[-2-3] PASSED
test_squared_is_less_than_10[-3-1] PASSED
test_squared_is_less_than_10[-3-2] PASSED
test_squared_is_less_than_10[-3-3] PASSED
这是不可取的,因为我只想执行 6 个测试,而不是 9 个。如果参数数量较多(例如 20 个),pytest 将执行 400 个测试,而不是所需的 40 个测试,这浪费了计算时间。
我该如何处理这个问题。
P.S:我想避免编写两个单独的测试,例如
test_negative_squared_is_less_than_10(negative_integer)
and test_positive_squared_is_less_than_10(positive_integer)