How can I extract a TestCase list from TestSuite?

I am using Python unittest with simple code:

suite = unittest.TestSuite() suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module1)) suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module2)) 

However, I want to do some custom stuff for each test after they have been packaged. I thought I could do something similar to iterate over test cases in a package:

 print suite.countTestCases() for test in suite: # Also tried with suite.__iter__() # Do something with test print test.__class__ 

However, since there are as many test cases as I download, it only prints

 3 <class 'unittest.suite.TestSuite'> 

Is there a way to get all objects of class TestCase from a package? Is there any other way that I should download test cases to facilitate this?

+6
source share
3 answers

Try

  for test in suite: print test._tests 
+5
source

I use this function because some of the elements in suite._tests are the sets themselves:

 def list_of_tests_gen(s): """ a generator of tests from a suite """ for test in s: if unittest.suite._isnotsuite(test): yield test else: for t in list_of_tests_gen(test): yield t 
+1
source

The best way to get a list of tests is to use a plug-in for nose collection.

 $ nose2 -s <testdir> -v --plugin nose2.plugins.collect --collect-only test_1 (test_test.TestClass1) Test Desc 1 ... ok test_2 (test_test.TestClass1) Test Desc 2 ... ok test_3 (test_test.TestClass1) Test Desc 3 ... ok test_2_1 (test_test.TestClass2) Test Desc 2_1 ... ok test_2_2 (test_test.TestClass2) Test Desc 2_2 ... ok ---------------------------------------------------------------------- Ran 5 tests in 0.001s OK 

In fact, it does not run tests.

You can install nose2 (and its plugins) as follows:

 $ pip install nose2 

And of course, you can use nose2 to run unit tests, for example. eg:

 # run tests from testfile.py $ nose2 -v -s . testfile # generate junit xml results: $ nose2 -v --plugin nose2.plugins.junitxml -X testfile --junit-xml $ mv nose2-junit.xml results_testfile.xml 
0
source

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


All Articles