In the previous section, we shared principles, assertions, and implementations. This time we share the test suite.
Test suites, which we use to organize test runs. So how do you do that
def suite():
suite = unittest.TestSuite()
suite.addTest(TestDemo('testone'))
suite.addTest(TestDemo('testtwo'))
return suite
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(suite())
So, we’ve organized our test suite, and we’ve added two use cases. Then we use textTestRunner to execute the use case, and we look at the result
In fact, we can also organize our test suites by folders. We can duplicate the previous test case.
Then we have two test case files, so how do we organize our test suite by folder loading?
def suite():
import os
path=os.getcwd()
suite=unittest.TestLoader().discover(path, pattern='test*.py', top_level_dir=None)
return suite
if __name__=="__main__":
runner = unittest.TextTestRunner()
runner.run(suite())
It’s really simple, we just need to load from TestLoader. Matches the py file starting with test and assembles the test suite. We then instantiate the TextTestRunner to execute the test suite, and let’s look at the results
If we need to get the number of test cases for the suite during testing, we can do this directly:
Print (suit.countTestCases ())
In addition to the way the test suite is loaded above, we can also load it as follows.
def suite():
suit=unittest.TestSuite()
suit.addTests([TestDemo('testone'),TestDemo('testtwo')])
return suit
if __name__=="__main__":
runner = unittest.TextTestRunner()
runner.run(suite())
The result of execution is the same
There are other ways:
def suite(): suite = unittest.TestSuite() suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestDemo)) return suite if __name__=="__main__": suitone=suite() name= unittest.textTestRunner () name.run(suitone) def suite(): suite = unittest.TestSuite() suite.addTests(unittest.TestLoader().loadTestsFromName("testdemoone.TestDemo")) return suite if __name__=="__main__": suitone=suite() name=unittest.TextTestRunner() name.run(suitone)
The results of both of the above methods are as follows
We can also configure the presentation details at execution time.
suitone=suite()
name=unittest.TextTestRunner(verbosity=2)
name.run(suitone)
The result shows detailed information
If you have a question you can leave a comment or add me at WeChat: 952943386. 2021, with cattle to money kun, with cattle force.
Welcome to scan the code concern, the article first in the public number