###unittest 支持的重要的 工具
####example:
import unittest
class TestSrtingMethod(unittest.TestCase):
def setUp(self):
print("prepare for test\n")
def test_upper(self):
print("executing test_upper\n")
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
print("executing test_isupper\n")
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
print("executing test_split\n")
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
def tearDown(self):
print("do something after test\n")
if __name__ == "__main__":
unittest.main()
setUp 和 tearDown 在每一个测试执行前后自动调用这两个方法。如果setUp()方法在测试运行时引发异常,框架将认为测试发生了错误,并且测试方法将不会被执行。如果setUp()成功,无论测试方法是否成功,都将运行tearDown()。
测试用例执行的顺序是测试方法名称相对于字符串的内置顺序的排序
console:
python3 ut.py -v
test_isupper (__main__.TestSrtingMethod) ... prepare for test
executing test_isupper
do something after test
ok
test_split (__main__.TestSrtingMethod) ... prepare for test
executing test_split
do something after test
ok
test_upper (__main__.TestSrtingMethod) ... prepare for test
executing test_upper
do something after test
ok
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
支持的参数
python3 -m unittest -h
usage: python3 -m unittest [-h] [-v] [-q] [--locals] [-f] [-c] [-b]
[tests [tests ...]]
positional arguments:
tests a list of any number of test modules, classes and test
methods.
optional arguments:
-h, --help show this help message and exit
-v, --verbose Verbose output
-q, --quiet Quiet output
--locals Show local variables in tracebacks
-f, --failfast Stop on first fail or error
-c, --catch Catch Ctrl-C and display results so far
-b, --buffer Buffer stdout and stderr during tests
Examples:
python3 -m unittest test_module - run tests from test_module
python3 -m unittest module.TestClass - run tests from module.TestClass
python3 -m unittest module.Class.test_method - run specified test method
python3 -m unittest path/to/test_file.py - run tests from test_file.py
usage: python3 -m unittest discover [-h] [-v] [-q] [--locals] [-f] [-c] [-b] 测试 用例的搜索, 是通过TestLoader.discover() 实现的
[-s START] [-p PATTERN] [-t TOP]
Example:python3 -m unittest discover -p ut*
optional arguments:
-h, --help show this help message and exit
-v, --verbose Verbose output
-q, --quiet Quiet output
--locals Show local variables in tracebacks
-f, --failfast Stop on first fail or error
-c, --catch Catch Ctrl-C and display results so far
-b, --buffer Buffer stdout and stderr during tests
-s START, --start-directory START
Directory to start discovery ('.' default)
-p PATTERN, --pattern PATTERN
Pattern to match tests ('test*.py' default)
-t TOP, --top-level-directory TOP
Top level directory of project (defaults to start
directory)
For test discovery all test modules must be importable from the top level
directory of the project