Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest dynamically generate test method

Hi How can i generate test method dynamically for a list or for number of files. Say I have file1,file2 and filen with input value in json. Now I need to run the same test for multiple values like below,

class Test_File(unittest.TestCase):
    def test_$FILE_NAME(self):
        return_val = validate_data($FILE_NAME)
        assert return_val

I am using the following command to run the py.test to generate html and junit report

py.test test_rotate.py --tb=long --junit-xml=results.xml --html=results.html -vv

At present I am manually defining the methods as below,

def test_lease_file(self):
    return_val = validate_data(lease_file)
    assert return_val

def test_string_file(self):
    return_val = validate_data(string_file)
    assert return_val

 def test_data_file(self):
    return_val = validate_data(data_file)
    assert return_val

Please let me know how I can specify py test to dynamically generate test_came method while giving reports.

I am expecting exactly which is mentioned in this blog "http://eli.thegreenplace.net/2014/04/02/dynamically-generating-python-test-cases"

But above blog uses unittest and if I use that I am not able to generate html and junit report

When we use fixtures as below I get error like its requiring 2 parameters,

test_case = []
class Memory_utlization(unittest.TestCase):
@classmethod
def setup_class(cls):
    fname = "test_order.txt"
    with open(fname) as f:
        content = f.readlines()
    file_names = []
    for i in content:
        file_names.append(i.strip())
    data = tuple(file_names)
    test_case.append(data)
    logging.info(test_case) # here test_case=[('dhcp_lease.json'),('dns_rpz.json'),]

@pytest.mark.parametrize("test_file",test_case)
def test_eval(self,test_file):
    logging.info(test_case) 

When I execute the above I get the following error,

 >               testMethod()
 E               TypeError: test_eval() takes exactly 2 arguments (1 given)
like image 557
Naggappan Ramukannan Avatar asked Feb 23 '16 14:02

Naggappan Ramukannan


1 Answers

This might help you with this.

Your test class would then look like

class Test_File():
    @pytest.mark.parametrize(
        'file', [
            (lease_file,),
            (string_file,),
            (data_file,)
        ]
    )
    def test_file(self, file):
        assert validate_data(file)
like image 166
adarsh Avatar answered Nov 17 '22 03:11

adarsh