unittest官方文档摘录 翻译 reffer to: https://docs.python.org/3/library/unittest.html#unittest.TextTestRunner
test fixture
测试固件:表示一个或多个测试用例需要的准备,以及关联的清理操作,例如:创建临时DB、目录或启动一个进程
test case
测试用例: 一个独立的测试单元,它校验一组输入得到的一个指定的响应,unittest提供一个基类TestCase,用来创建新的测试用例
test suite
测试套件: 一个测试用例的集合,用来集合应该被一起执行的测试用例
test runner
测试执行组件: 安排测试的执行并给用户提供结果
unittest库提供了一系列丰富的工具来构建和执行测试,下面讲一下可以满足大部分用户需求的一个小的工具子集
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
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)
if __name__ == '__main__':
unittest.main()
# 您可以像这样执行一个测试模块:
python -m unittest test_module1 test_module2
# 也可以执行一个测试类,如:
python -m unittest test_module.TestClass
# 或者单独执行一个测试方法
python -m unittest test_module.TestClass.test_method
自由组装测试套件
import unittest
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget('The widget')
def tearDown(self):
self.widget.dispose()
def suite():
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase('test_default_widget_size'))
suite.addTest(WidgetTestCase('test_widget_resize'))
return suite
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(suite())
5.1 跳过一个用例使用skip()装饰器就可以了,下面是几个实例
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 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
这个类代表一些单独测试用例或测试集的集合,TestSuite的对象有点像TestCase对象,除了它并不真正实现一个测试外,另外,它们用来集成需要一起运行的测试,下面是一些常用方法:
--
# 执行一个module中的所有用例
if __name__ == '__main__':
unittest.main()
unittest (python标准库-开发工具-单元测试框架)
原文:https://www.cnblogs.com/chengtch/p/10590936.html