mercredi 23 septembre 2020

Parametrize pytest test function based on output of setup_module or other function dynamically

I have a pytest code in I have a setup_module in which I do some code processing which modifies a list of lists named testdata which is declared globally. I need to pass that list of lists to my test case dynamically based on what I receive from the setup_module.

testdata = [['servername_1', 'servermac_1', 'vlans'],['servername_2', 'servermac_2', 'vlans']]
 
def setup_module(module):
    #global testdata
    #do some steps
    #based on if the server has issues or server mac is different, 
    # return testdata which may or may not remove one or both list from test data(modified testdata)

def teardown_module(module):
    #close ssh connection

@pytest.mark.parametrize('servername, servermac, vlan', testdata)
def test_function(servername, servermac, vlans):
    for vlans in vlans:
       do ssh to servername:
          #do things

Anyway to dynamically parametrize the testdata in the test_function.

I have tried :

a) With the current code, even if setup_module removes one list from the testdata, since my test case is parametrized with testdata globally, which has two lists, the test cases runs twice for one list in testdata. I read from other questions that this is not possible as per pytest structure.

b) If i try the fixture by doing something like :

testdata = [['servername_1', 'servermac_1', 'vlans'],['servername_2', 'servermac_2', 'vlans']]

@pytest.fixture
def setup():
    #do some steps
    #based on if the server has issues or server mac is different, 
    # return testdata which may or may not remove one or both list from test data

def teardown_module(module):
    #close ssh connection


def test_function(setup):
    testdata = setup 

    for test in testdata:
        servername = test[0]
        servermac = test[1]
        vlans = test[2]

    for vlans in vlans:
       do ssh to servername:
          #do things

With this code structure, pytest doesn't consider it was two set of test cases but only one only set of case. Also, I can't use assert here, since if something fails for 1st servername and if i assert it to false, code won't run for 2nd servername at all.

Can somebody please suggest if I am doing something wrong here. Apologies if didn't follow the question guidelines, since posting a question for the first time here.

Aucun commentaire:

Enregistrer un commentaire