[英]Using pytest, can I get fixture values outside test function?
I am using parametrizing tests, to test 2 different data sets. 我正在使用参数化测试来测试2个不同的数据集。 For example like this. 例如这样。 some_data()
functions return test data. some_data()
函数返回测试数据。
test_data = [
(some_data1_v1(), some_data2_v2()),
(some_data1_v2(), some_data2_v2())
]
@pytest.mark.parametrize('a,b', test_data)
def test_fn(a,b):
pass
But for some tests, that checks only general behavior, I don't need to test 2 data sets, because both sets have appropriate general data. 但是对于某些仅检查常规行为的测试,我不需要测试2个数据集,因为这两个数据集都有适当的常规数据。 I want to convert some_data1_v1()
function to fixture and use it in test, like this 我想将some_data1_v1()
函数转换为some_data1_v1()
并在测试中使用它,像这样
def test_fn2(some_data1_v1):
pass
If I will do it, then call some_data1_v1()
during test_data
list construction raise exception Fixtures are not meant to be called directly...
如果我愿意的话,那么在test_data
列表构建过程中调用some_data1_v1()
引发异常Fixtures are not meant to be called directly...
So instead this 所以这个
def test_fn2(some_data1_v1):
pass
I do like this 我喜欢这样
@pytest.mark.parametrize('some_data1_v1', [some_data1_v1()])
def test_fn2(some_data1_v1):
pass
This allow me to have one source of test data - "fake fixtures" (usual functions that return data), and pass test data in test_data
list (first example or last example). 这使我拥有一个测试数据源-“假装”(通常是返回数据的函数),并在test_data
列表中传递测试数据(第一个示例或最后一个示例)。 But I think my approach to store data in usual functions is break "fixture abstraction". 但是我认为我将数据存储在常规功能中的方法是打破“夹具抽象”。
Is there a better approach, to do what I do? 是否有更好的方法来做我想做的事?
You can use a parametrized fixture . 您可以使用参数化夹具 。 request.param
refers to the specific entry in the params
sequence request.param
引用params
序列中的特定条目
For example: 例如:
@pytest.fixture(params=(1, 2, 3))
def fix1(request):
return request.param
@pytest.fixture(params=(4, 5, 6))
def fix2(request):
return request.param
def test1(fix1, fix2):
print(fix1, fix2)
def test2(fix1):
print(fix1)
And execution: 并执行:
$ pytest t.py
...
collected 12 items
t.py::test1[1-4] 1 4
PASSED
t.py::test1[1-5] 1 5
PASSED
t.py::test1[1-6] 1 6
PASSED
t.py::test1[2-4] 2 4
PASSED
t.py::test1[2-5] 2 5
PASSED
t.py::test1[2-6] 2 6
PASSED
t.py::test1[3-4] 3 4
PASSED
t.py::test1[3-5] 3 5
PASSED
t.py::test1[3-6] 3 6
PASSED
t.py::test2[1] 1
PASSED
t.py::test2[2] 2
PASSED
t.py::test2[3] 3
PASSED
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.