简体   繁体   English

用不同的测试参数化 pytest function

[英]Parameterizing pytest function with different tests

I have a scenario where there are 1000's of test cases in excel.我有一个场景,excel 中有 1000 个测试用例。
Is there a way to parameterize the test so that all the test cases run?有没有办法对测试进行参数化,以便所有测试用例都运行?

I have used pandas and I am getting all the test cases while iterating through:我使用pandas并且在迭代时获得了所有测试用例:

def getCases():
    excel_file = 'path of excel'
    result = pd.read_excel(excel_file)
    count_row = result.shape[0]
    for i in range(count_row):
        r = result.iloc[i]
        return [r]

Each row in the excel table is a test case and the result returned is in the form of dictionary, which I want to pass as input to my test case. excel 表中的每一行都是一个测试用例,返回的结果是字典的形式,我想将它作为输入传递给我的测试用例。

I use the following fixture to pass these parameters to my test functions:我使用以下夹具将这些参数传递给我的测试函数:

@pytest.fixture(params=PWC.getCases())
def getData(self, request):
    return request.param 

The problem is that after the first iteration, it is not reaching this code and my test case does not return to the getCases() function.问题是在第一次迭代之后,它没有到达这个代码,我的测试用例没有返回到getCases() function。 How do I customize the params in pytest fixture so that I will be able to run all the cases?如何自定义pytest 夹具中的参数,以便能够运行所有案例?
Will I be able to pass a range inside getCases as parameter?我可以将getCases中的范围作为参数传递吗?

To be able to return the control to the function you have to use yield instead of return .为了能够将控制权返回给 function,您必须使用yield而不是return Assuming each row contains both the input and the result data for the test, this would look something like this:假设每一行都包含测试的输入和结果数据,这看起来像这样:

def getCases():
    excel_file = 'path of excel'
    result = pd.read_excel(excel_file)
    count_row = result.shape[0]
    for i in range(count_row):
        yield result.iloc[i]

@pytest.fixture(params=getCases())
def data(self, request):
    return request.param

def test_data(data):
    assert my_fct(data['input']) == data['result']

(assuming that there is only one input parameter in your tested function) (假设您测试的函数中只有一个输入参数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM