The examples in this paper describe the usage of unittest in Python and share them for your reference. The specific usage analysis is as follows:
1. The UnitTest module includes the ability to write run UnitTest, and the custom test class integrates unitest. TestCase class, test method begins with test, and the run order is sorted by the name of the test method, with a special method:
①setup (): Run before each test function runs
②teardown (): Executes after each test function finishes running
③setupclass (): Must use @classmethod adorner, all test runs before run
④teardownclass (): Must use @classmethod adorner, run once after all test runs
2. Sample code:
#文件名runtest. Pyimport randomimport unittestclass testsequencefunctions (unittest. TestCase): def setUp (self): self.seq = list (range) def test_shuffle (self): # Make sure the Shuffled sequence does not lose any elements random.shuffle (SELF.SEQ) self.seq.sort () self.assertequal ( SELF.SEQ, List (range)) # should raise an exception for an immutable sequence self.assertraises (TypeError, Random.shuffle, (+/-)) def test_choice (self): element = Random.choice (self.seq) self.asserttrue ( element in Self.seq) def test_sample (self): with self.assertraises (valueerror): random.sample ( SELF.SEQ) for element in Random.sample (SELF.SEQ, 5): self.asserttrue (element in self.seq) if __name__ = = ' _ _main__ ': unittest.main ()
3. Operating mode: Run this runtest.py directly at the command line
You can use the Unitest.skip decorator family to skip the test method or test class, which includes:
① @unittest. Skip (reason): Skip test unconditionally, reason describe why you skipped the test
② @unittest. SKIPIF (Conditition,reason): Skip Test when Condititon is True
③ @unittest. Skipunless (Condition,reason): Skip test when condition is not true
You can customize the skip decorator
#这是一个自定义的skip decorratordef skipunlesshasattr (obj, attr): if hasattr (obj, attr): return lambda Func:func Return Unittest.skip ("{!r} doesn ' t has {!r}". Format (obj, attr))
Skip Decorator Sample code:
Class Mytestcase (UnitTest. TestCase): @unittest. Skip ("Demonstrating skipping") def test_nothing (self): self.fail ("shouldn ' t Happen ") @unittest. SkipIf (Mylib.__version__ < (1, 3), " not supported in this library version ") def test_ Format (self): # Tests This work for only a certain version of the library. Pass @unittest. Skipunless (Sys.platform.startswith ("Win"), "requires Windows") def test_windows_support ( Self): # Windows Specific testing code Pass@unittest.skip ("showing class skipping") class Myskippedtestcase ( UnitTest. TestCase): def test_not_run (self): Pass
4.expected failure: Using the @unittest.expectedfailure adorner, if test fails, this test does not count toward the number of failed case
I hope this article is helpful to the study of Python program design.