python unittest 快速入门
import unittest
def add(x, y):
return x + y
class TestLearning(unittest.TestCase):
def setUp(self):
a = 0
a += 1
print('a:' + str(a))
def test_demo(self):
# a=1/0
self.assertEqual('foo'.upper(), 'FOO')
def test_next(self):
self.assertTrue(1 == 1)
在命令行运行的结果:
(venvtest) rabbit:testframe rabbit$ python -m unittest discover -v qiuzhouxin
test_demo (tests.TestLearning) ... a:1
ok
test_next (tests.TestLearning) ... a:1
ok
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
解析:每次运行一个testcase都会先运行setUp()
若运行testcase过程中有异常,为测试失败(errors=xx)
若assert断言失败,为测试失败(failures=xx)
tearDown()类似setUp,在每个test方法结束后调用,无论测试结果是fail还是error都会调用
assert断言方法:
方法 | 检查一下 | 新的 |
---|---|---|
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 |