rahul knair
rahul knair

Reputation: 113

Parameterizing pytest function with different tests

I have a scenario where there are 1000's of test cases in excel.
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:

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.

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. How do I customize the params in pytest fixture so that I will be able to run all the cases?
Will I be able to pass a range inside getCases as parameter?

Upvotes: 1

Views: 615

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16855

To be able to return the control to the function you have to use yield instead of 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)

Upvotes: 2

Related Questions