This article is an example of the use of unittest in Python, shared for everyone to reference. The specific usage analysis is as follows:
1. The UnitTest module contains the ability to write running UnitTest, and the custom test class is integrated unitest. TestCase class, test method begins with test, and the order of execution is sorted according to the name of test methods:
①setup (): Run before each test function runs
②teardown (): After each test function finishes running
③setupclass (): The @classmethod adorner must be used, and all test runs once before running
④teardownclass (): You must use the @classmethod adorner to run once after all test runs
2. Sample code:
#文件名runtest. py
Import random
import UnitTest
class 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 a exception for a immutable sequence self.assertraises
(TypeError, Random.shuffle, (1,2,3))
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. Operation mode: Run this runtest.py directly on the command line
You can use the Unitest.skip adorner family to skip test method or test class, which includes:
① @unittest. Skip (reason): unconditional skip test, reason describe why skipped test
② @unittest. SKIPIF (Conditition,reason): Condititon skipped test for true
③ @unittest. Skipunless (Condition,reason): condition skipped test if not true
You can customize the skip decorator
#这是一个自定义的skip decorrator
def skipunlesshasattr (obj, attr):
if hasattr (obj, attr): return
Lambda Func:func return
Unittest.skip ("{!r} doesn ' t have {!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 that work to 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 into the number of failed cases
I hope this article will help you with your study of Python programming.