unittest中包含了很多断言内容,实际用到的断言内容也就比对值是否相同,下面是unittest中的断言内容
#encoding=utf-8 import unittest import random # 被测试类 class MyClass(object): @classmethod def sum(self, a, b): return a + b @classmethod def div(self, a, b): return a / b @classmethod def retrun_None(self): return None # 单元测试类 class MyTest(unittest.TestCase): # assertEqual()方法实例 def test_assertEqual(self): # 断言两数之和的结果 a, b = 1, 2 sum = 4 self.assertEqual(a + b, sum, '断言失败,%s + %s != %s' %(a, b, sum)) # assertNotEqual()方法实例 def test_assertNotEqual(self): # 断言两数之差的结果 a, b = 5, 2 res = 1 self.assertNotEqual(a - b, res, '断言失败,%s - %s != %s' %(a, b, res)) # assertTrue()方法实例 def test_assertTrue(self): # 断言表达式的为真 self.assertTrue(1 == 1, "表达式为假") # assertFalse()方法实例 def test_assertFalse(self): self.assertFalse(3 == 2, "表达式为真") # assertIs()方法实例 def test_assertIs(self): # 断言两变量类型属于同一对象,这事对比的地址,查看地址使用id(变量) a = 12 b = a self.assertIs(a, b, "%s与%s不属于同一对象" %(a, b)) # test_assertIsNot()方法实例 def test_assertIsNot(self): # 断言两变量类型不属于同一对象 a = 12 b = "test" self.assertIsNot(a, b, "%s与%s属于同一对象" %(a, b)) # assertIsNone()方法实例 def test_assertIsNone(self): # 断言表达式结果为None result = MyClass.retrun_None() self.assertIsNone(result, "not is None") # assertIsNotNone()方法实例 def test_assertIsNotNone(self): result = MyClass.sum(2, 5) self.assertIsNotNone(result, "is None") # assertIn()方法实例 def test_assertIn(self): # 断言对象A是否包含在对象B中 ,这就是in的一个用法 strA = "this is a test" strB = "is" self.assertIn(strB, strA, "%s不包含在%s中" %(strB, strA)) # assertNotIn()方法实例 def test_assertNotIn(self): strA = "this is a test" strB = "Selenium" self.assertNotIn(strB, strA, "%s包含在%s中" %(strB, strA)) # assertIsInstance()方法实例 def test_assertIsInstance(self): # 测试对象A的类型是否值指定的类型 x = MyClass y = object self.assertIsInstance(x, y, "%s的类型不是%s" %(x, y)) # assertNotIsInstance()方法实例 def test_assertNotIsInstance(self): # 测试对象A的类型不是指定的类型 a = 123 b = str self.assertNotIsInstance(a, b, "%s的类型是%s" %(a, b)) # assertRaises()方法实例 def test_assertRaises(self): # 测试抛出的指定的异常类型 # assertRaises(exception) with self.assertRaises(TypeError) as cm: random.sample([1,2,3,4,5], "j") # 打印详细的异常信息 self.assertRaises(ZeroDivisionError, MyClass.div, 3, 0) # assertRaisesRegexp()方法实例 def test_assertRaisesRegexp(self): # 测试抛出的指定异常类型,并用正则表达式具体验证 with self.assertRaisesRegex(ValueError, 'literal') as ar: int("xyz") # assertRaisesRegexp(exception, regexp, callable, *args, **kwds) self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$", int, 'XYZ') if __name__ == '__main__': # 执行单元测试 unittest.main()
测试结果,运行14个,失败了1个,失败的结果显示