本文介绍了参数化测试取决于pytest中的参数化值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个测试,其中有一个设置方法,应接收一个 dataset ,一个测试函数,该函数应针对 dataset中的每个 data 运行

I have a test where I have a setup method, that should receive a dataset, and a test function, that should run for each data in dataset

基本上,我需要类似的东西:

Basically I would need something like:

datasetA = [data1_a, data2_a, data3_a]
datasetB = [data1_b, data2_b, data3_b]

@pytest.fixture(autouse=True, scope="module", params=[datasetA, datasetB])
def setup(dataset):
    #do setup
    yield
    #finalize

#dataset should be the same instantiated for the setup
@pytest.mark.parametrize('data', [data for data in dataset])
def test_data(data):
    #do test

它应该像这样运行:

  • setup(datasetA)
  • test(data1_a)
  • test(data2_a)
  • test(data3_a)
  • setup(datasetB)
  • test(data1_b)
  • test(data2_b)
  • test(data3_b)

但是,正如我在示例中所希望的那样,似乎无法对由灯具获得的变量进行参数化.

However it does not seem to be possible to parametrize over a variable obtained by a fixture, as I wanted to in the example.

我可以让我的函数使用固定装置并在测试方法中进行迭代:

I could have my function use a fixture and iterate inside the test method:

def test_data(dataset):
    for data in dataset:
        #do test

但是然后我会针对每个案例进行一个大型测试,而不是单独的测试,这是我不希望的.

But then I would have one large test instead of a separate test for each case, which I would not like to have.

有什么办法可以做到这一点?

Is there any way of accomplishing this?

谢谢!

推荐答案

答案#1:如果严格按照设计进行测试,那么它应该看起来像这样:

Answer #1: If strictly following you test design, then it should look like this:

import pytest

datasetA = [10, 20, 30]
datasetB = [100, 200, 300]

@pytest.fixture
def dataset(request):
    #do setup
    items = request.param
    yield items
    #finalize

@pytest.fixture
def item(request, dataset):
    index = request.param
    yield dataset[index]

#dataset should be the same instantiated for the setup
@pytest.mark.parametrize('dataset', [datasetA, datasetB], indirect=True)
@pytest.mark.parametrize('item', [0, 1, 2], indirect=True)
def test_data(dataset, item):
    print(item)
    #do test

请注意,对于item& dataset.参数值将被传递到与request.param相同名称的灯具.在这种情况下,我们在假设数据集具有3个项目的相同长度的情况下使用索引.

Note the indirect parametrization for both item & dataset. The parameter values will be passed to the same-named fixture as request.param. In this case, we use the index in the assumption that the datasets are of the same length of 3 items.

这是它的执行方式:

$ pytest -s -v -ra test_me.py
test_me.py::test_data[0-dataset0] 10
PASSED
test_me.py::test_data[0-dataset1] 100
PASSED
test_me.py::test_data[1-dataset0] 20
PASSED
test_me.py::test_data[1-dataset1] 200
PASSED
test_me.py::test_data[2-dataset0] 30
PASSED
test_me.py::test_data[2-dataset1] 300
PASSED

这篇关于参数化测试取决于pytest中的参数化值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:52