unittest中通过设置断言可以帮助我们不阻碍测试用例的执行,下面是整理的一些常用的断言,后续根据使用继续更新
assertEqual(a,b) 如果a!=b,运行之后控制台会报错:
AssertionError: 2 != 3
FAILED (failures=1)
但是程序会运行结束。
如果一次性运行两个或者多个test用例,即使前面的测试用例失败了,也不会影响后面case的运行。
代码中如果是多个测试用例的话,可以在后面添加,如下面代码:
suit.addTest(testFun("test1","test2"))
假如第一个运行失败,后面会继续运行,failure后面有一个数量,展示的是失败的用例个数。
这个是所有代码:
import unittest
from test.functions import fun_add,fun_minus,fun_multi,fun_div
class testFun(unittest.TestCase):
times = 0
@classmethod
def setUpClass(cls):
testFun.times += 1
print("setUpClass")
@classmethod
def tearDownClass(cls):
testFun.times += 1
print("tearDownClass")
def test1(self):
# self.assertEqual(2,fun_div(3))
self.assertEqual(2,3)
# self.failUnlessEqual(2,2)
# self.assertTrue(1<2)
# self.failUnless(2 ==2)
# self.assertNotEquals(2,1)
def test2(self):
self.assertEqual(3,5)
if __name__ == '__main__':
suit = unittest.TestCase()
suit.addTest(testFun("test1","test2"))
runner = unittest.TextTestRunner()
runner.run(suit)
下面是运行的结果图:
从运行结果我们可以总结出:
(1)测试用例的运行不管成功与否,都是互不影响的;
(2)不管测试用例有多少,setUpClass() 和 tearDownClass() 都是只运行一次。一般情况下,setUpClass()函数是测试之前的各种准备,比如:连接数据库,准备数据。tearDownClass()函数是测试结束后要进行的操作,比如:断开数据库连接,释放资源等等。
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 2.7
assertIsNot(a, b) a is not b 2.7
assertIsNone(x) x is None 2.7
assertIsNotNone(x) x is not None 2.7
assertIn(a, b) a in b 2.7
assertNotIn(a, b) a not in b 2.7
assertIsInstance(a, b) isinstance(a, b) 2.7
assertNotIsInstance(a, b) not isinstance(a, b) 2.7
assertAlmostEqual(a, b) round(a-b, 7) == 0
assertNotAlmostEqual(a, b) round(a-b, 7) != 0
assertGreater(a, b) a > b 2.7
assertGreaterEqual(a, b) a >= b 2.7
assertLess(a, b) a < b 2.7
assertLessEqual(a, b) a <= b 2.7
assertRegexpMatches(s, re) regex.search(s) 2.7
assertNotRegexpMatches(s, re) not regex.search(s) 2.7
assertItemsEqual(a, b) sorted(a) == sorted(b) and works with unhashable objs 2.7
assertDictContainsSubset(a, b) all the key/value pairs in a exist in b 2.7
assertMultiLineEqual(a, b) strings 2.7
assertSequenceEqual(a, b) sequences 2.7
assertListEqual(a, b) lists 2.7
assertTupleEqual(a, b) tuples 2.7
assertSetEqual(a, b) sets or frozensets 2.7
assertDictEqual(a, b) dicts 2.7
assertMultiLineEqual(a, b) strings 2.7
assertSequenceEqual(a, b) sequences 2.7
assertListEqual(a, b) lists 2.7
assertTupleEqual(a, b) tuples 2.7
assertSetEqual(a, b) sets or frozensets 2.7
assertDictEqual(a, b) dicts 2.7