一、摘要

单元测试里很重要的一个部分就是断言,unittest为我们提供了很多断言方法

  • assertEqual(a, b, msg=None)断言 a == b
  • assertNotEqual(a, b, msg=None)断言  a != b
  • assertTrue(expr, msg=None)断言  bool(expr) is True
  • assertFalse(expr, msg=None)断言  bool(expr) is False
  • assertIs(a, b, msg=None)断言  a is b
  • assertIsNot(a, b, msg=None)断言  a is not b
  • assertIsNone(expr, msg=None)断言  expr is None
  • assertIsNotNone(expr, msg=None)断言  expr is not None
  • assertIn(a, b, msg=None)断言  a in b
  • assertNotIn(a, b, msg=None)断言  a not in b
  • assertIsInstance(obj, cls, msg=None)断言 obj  is cls instance
  • assertNotIsInstance(obj, cls, msg=None)断言 obj is not cls instance
  • assertRaises(exc, fun, *args, **kwds)断言  fun(*args, **kwds) raises exc 否则抛出断言异常
  • assertRaisesRegex(exc, r, fun, *args, **kwds) 断言  fun(*args, **kwds) raises exc and the exc message matches regex r 否则抛出断言异常

二、代码实例

# encoding = utf-8
import unittest
import random


#  被测试类
class ToBeTest(object):
    @classmethod
    def sum(cls, a, b):
        return a + b

    @classmethod
    def div(cls, a, b):
        return a/b

    @classmethod
    def return_none(cls):
        return None


#  单元测试类
class TestToBeTest(unittest.TestCase):

    # assertEqual()方法实例
    def test_assertequal(self):
        try:
            a, b = 100, 200
            sum = 300
            # 断言a+b等于sum
            self.assertEqual(a + b, sum, '断言失败,%s+%s != %s ' %(a, b, sum))
        except AssertionError as e:
            print(e)

    # assertNotEqual()方法实例
    def test_assertnotequal(self):
        try:
            a, b = 100, 200
            res = -1000
            # 断言a-b不等于res
            self.assertNotEqual(a - b, res, '断言失败,%s-%s != %s ' %(a, b, res))
        except AssertionError as e:
            print(e)

    # assertTure()方法实例
    def test_asserttrue(self):
        list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        list2 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
        list3 = list1[::-1]
        print(list3)
        try:
            # 断言表达式为真
            self.assertTrue(list3 == list2, "表达式为假")
        except AssertionError as e:
            print(e)

    # assertFalse()方法实例
    def test_assertfalse(self):
        list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        list2 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
        list3 = list1[::-1]
        try:
            #  断言表达式为假
            self.assertFalse(list3 == list1, "表达式为真")
        except AssertionError as e:
            print(e)

    # assertIs()方法实例
    def test_assertis(self):
        list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        list2 = list1
        try:
            # 断言list2和list1属于同一个对象
            self.assertIs(list1, list2, "%s 与 %s 不属于同一对象" % (list1, list2))
        except AssertionError as e:
            print(e)

    # assertIsNot()方法实例
    def test_assertisnot(self):
        list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        list2 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
        try:
            # 断言list2和list1不属于同一个对象
            self.assertIsNot(list2, list1, "%s 与 %s 属于同一对象" % (list1, list2))
        except AssertionError as e:
            print(e)

    # assertIsNone()方法实例
    def test_assertisnone(self):
        try:
            results = ToBeTest.return_none()
            # 断言表达式结果是none
            self.assertIsNone(results, "is not none")
        except AssertionError as e:
            print(e)

    # assertIsNotNone()方法实例
    def test_assertisnotnone(self):
        try:
            results = ToBeTest.sum(4, 5)
            # 断言表达式结果不是none
            self.assertIsNotNone(results, "is none")
        except AssertionError as e:
            print(e)

    # assertIn()方法实例
    def test_assertin(self):
        try:
            str1 = "this is unit test demo"
            str2 = "demo"
            # 断言str2包含在str1中
            self.assertIn(str2, str1, "%s 不被包含在 %s中" %(str2, str1))
        except AssertionError as e:
            print(e)

    # assertNotIn()方法实例
    def test_assertnotin(self):
        try:
            str1 = "this is unit test demo"
            str2 = "ABC"
            # 断言str2不包含在str1中
            self.assertNotIn(str2, str1, "%s 包含在 %s 中" % (str2, str1))
        except AssertionError as e:
            print(e)

    # assertIsInstance()方法实例
    def test_assertisinstance(self):
        try:
            o = ToBeTest
            k = object
            # 断言测试对象o是k的类型
            self.assertIsInstance(o, k, "%s的类型不是%s" % (o, k))
        except AssertionError as e:
            print(e)

    # assertNotIsInstance()方法实例
    def test_assertnotisinstance(self):
        try:
            o = ToBeTest
            k = int
            # 断言测试对象o不是k的类型
            self.assertNotIsInstance(o, k, "%s 的类型是%s" % (o, k))
        except AssertionError as e:
            print(e)

    # assertRaises()方法实例
    def test_assertraises(self):
        # 测试抛出指定的异常类型
        # assertRaises(exception)
        with self.assertRaises(TypeError) as exc:
            random.sample([1, 2, 3, 4, 5, 6], "j")
        # 打印详细的异常信息
        print(exc.exception)
        # assertRaises(exception, callable, *args, **kwds)
        try:
            self.assertRaises(ZeroDivisionError, ToBeTest.div, 3, 0)
        except ZeroDivisionError as e:
            print(e)

    # assertRaisesRegexp()方法实例
    def test_assertraisesregex(self):
        # 测试抛出指定的异常类型,并用正则表达式去匹配异常信息
        # assertRaisesRegex(exception, regexp)
        with self.assertRaisesRegex(ValueError, "literal") as exc:
            int("abc")
        # 打印详细的异常信息
        print(exc.exception)

        # assertRaisesRegex(exception, regexp, callable, *args, **kwds)
        try:
            self.assertRaisesRegex(ValueError, 'invalid literal for.*\'abc\'$', int, 'abc')
        except AssertionError as e:
            print(e)


if __name__ == '__main__':
    unittest.main()
12-27 06:28