Pytest dynamically generates a test method

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

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

I use the following command to run py.test to generate html and junit reports

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

I am currently manually defining methods as shown 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 tell py test to dynamically generate the test_came method when reporting.

I definitely expect what is mentioned in this blog http://eli.thegreenplace.net/2014/04/02/dynamically-generating-python-test-cases "

But unittest is used above the block, and if I use this, I cannot generate an html and junit report

When we use devices as shown below, I get an error, for example, 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 do the above, I get the following error:

  > testMethod() E TypeError: test_eval() takes exactly 2 arguments (1 given) 
+5
source share
1 answer

This can help you with this.

Then your test class will look like

 class Test_File(): @pytest.mark.parametrize( 'file', [ (lease_file,), (string_file,), (data_file,) ] ) def test_file(self, file): assert validate_data(file) 
+6
source

Source: https://habr.com/ru/post/1243672/


All Articles