实践是检验真理的唯一标准
写程序是检验理论和理解理论的必要途径
- 一个基本的单元测试
下面代码存放的文件名为test.py
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 test.py
#使用-v 会详细输出每个测试函数的结果,没有-v的话就用一个.显示
$ python test.py -v
也可以这样运行:
#运行整个模块
$ python -m unittest test
#测试test模块的TestStringMethods类的test_upper方法
$ python -m unittest test.TestStringMethods.test_upper
帮助命令
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
-f, --failfast Stop on first failure
-c, --catch Catch control-C and display results
-b, --buffer Buffer stdout and stderr during test runs
#在测试类中用来做初始化的,一般用来打开资源
def setUp(self):
self.widget = Widget('The widget')
#在测试类中用来做初始化的,一般用来关闭资源 setUp不论执行成功或失败tearDown都会执行
def tearDown(self):
self.widget.dispose()
Method | Checks that | New in |
---|---|---|
assertEqual(a, b) | a == b | |
assertNotEqual(a, b) | a != b | |
assertTrue(x) | bool(x) is True | |
assertFalse(x) | bool(x) is False | |
assertIs(a, b) | a is b 3.1 | |
assertIsNot(a, b) | a is not b | 3.1 |
assertIsNone(x) | x is None | 3.1 |
assertIsNotNone(x) | x is not None | 3.1 |
assertIn(a, b) | a in b | 3.1 |
assertNotIn(a, b) | a not in b | 3.1 |
assertIsInstance(a, b) | isinstance(a, b) | 3.2 |
assertNotIsInstance(a, b) | not isinstance(a, b) | 3.2 |