美文网首页
1. unittest中断言,值得拥有

1. unittest中断言,值得拥有

作者: _百草_ | 来源:发表于2020-11-14 09:16 被阅读0次
# -*- coding:utf-8 -*-
"""
=============================
@author:_百草_
@file:test_unittest_assert_1106.py
@time:2020/11/06
=============================
"""

import unittest


class TestAssert(unittest.TestCase):
    """
    断言练习
    """
    def test_01(self):
        """
        基本布尔断言,要么正确,要么错误,msg用于指定失败返回的错误信息
        :return:
        """
        # # 1.assertTrue(expr, msg=None)  # 验证expr是True,若是False则fail
        self.assertTrue(1)
        self.assertFalse(0)

    def test_02(self):
        # 2. assertEqual(arg1,arg2,msg=None) 验证arg1=arg2,不等则fail
        self.assertEqual('1', '1')
        self.assertNotEqual(1, 2)

    def test_03(self):
        # # 3. assertIs(arg1, arg2, msg=None) 验证arg1、arg2是否是同一对象
        self.assertIs('1', '1', msg="fail")  # AssertionError: 1 is not 2 : fail
        self.assertIsNot(1, 2)

    def test_04(self):
        # # 4. assertIsNone(arg1, msg=None) 验证expr1是否是None,不是返回fail
        self.assertIsNone(None)
        self.assertIsNotNone([])

    def test_05(self):
        # # 5. assertIn(agr1, arg2, msg=None) 验证arg1是不是arg2的字串,不是则fail
        self.assertIn(1, [1, 2, 3])  # AssertionError: [1, 3, 2] not found in [1, 2, 3]
        self.assertNotIn(12, [1, 2, 3])  # AssertionError: 1 unexpectedly found in [1, 2, 3]

    def test_06(self):
        # # 6. assertIsInstance(obj, cls, msg=None) 验证obj是否是cls的实例,不是则fail
        self.assertIsInstance(1, int)  # , msg='不是')
        # # AssertionError: '1' is not an instance of <class 'int'> : 不是
        self.assertNotIsInstance(obj='1', cls=list, msg=None)

    def test_07(self):
        """
        比较断言
        :return:
        """
        # 7. assertAlmostEqual(self, first, second, places=7, msg=None,
        #                           delta=None)
        # 验证first约等于second(数据类型)。palces指定精确到小数点后多少位
        self.assertAlmostEqual(1235.12345678, 1235.12345679)  # 精确到小数点后第几位
        # self.assertNotAlmostEqual(1234, 1235, places=-1)  # AssertionError: 1234 == 1235 within -1 places

        # 8.
        self.assertLess(1, 2)  # Just like self.assertTrue(a < b), but with a nicer default message.
        self.assertLessEqual(1, 1)  # Just like self.assertTrue(a <= b), but with a nicer default message.
        self.assertGreater(2, 1)  # Just like self.assertTrue(a > b), but with a nicer default message.
        self.assertGreaterEqual(2, 2)  # Just like self.assertTrue(a >= b), but with a nicer default message.

        # # 9.assertRegex(text, expected_regex, msg=None)  # Fail the test unless the text matches the regular expression.
        # self.assertRegex('12', '.(1-9+).', msg='不匹配')
        # # AssertionError: Regex didn't match: '.(1-9+).' not found in '12' : 不匹配
        # # self.assertNotRegex(12, '1-9+')  # text : TypeError: expected string or bytes-like object

    def test_08(self):
        """
        :return:
        """
        self.assertSequenceEqual([1, 2], [1, 2])
        """An equality assertion for ordered sequences (like lists and tuples).

        For the purposes of this function, a valid ordered sequence type is one
        which can be indexed, has a length, and has an equality operator.

        Args:
            seq1: The first sequence to compare.
            seq2: The second sequence to compare.
            seq_type: The expected datatype of the sequences, or None if no
                    datatype should be enforced.
            msg: Optional message to use on failure instead of a list of
                    differences.
        """
        self.assertListEqual(list1=[1, 2, 1], list2=[1, 2, 1], msg=None)
        """A list-specific equality assertion.

        Args:
            list1: The first list to compare.
            list2: The second list to compare.
            msg: Optional message to use on failure instead of a list of
                    differences.
        """
        self.assertTupleEqual(tuple1=(1, 2), tuple2=(1, 2), msg=None)
        """A tuple-specific equality assertion.

        Args:
            tuple1: The first tuple to compare.
            tuple2: The second tuple to compare.
            msg: Optional message to use on failure instead of a list of
                    differences.
        """
        self.assertSetEqual(set1=set([1, 2, 3]), set2=set([2, 3, 1]), msg=None)
        self.assertDictEqual(d1={1: 2}, d2={2: 1}, msg=None)

    def test_09(self):
        """

        :return:
        """
        self.assertCountEqual(first=[1, 1, 2], second=[1, 2, 1], msg=None)
        """An unordered sequence comparison asserting that the same elements,
            regardless of order.  If the same element occurs more than once,
            it verifies that the elements occur the same number of times.

                self.assertEqual(Counter(list(first)),
                                 Counter(list(second)))

             Example:
                - [0, 1, 1] and [1, 0, 1] compare equal.
                - [0, 0, 1] and [0, 1] compare unequal.

        """
        self.assertMultiLineEqual(first='12345', second='12345', msg=None)
        """Assert that two multi-line strings are equal.
        multi- 多种多样的"""


if __name__ == '__main__':
    # suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestAssert)
    # runner = unittest.TextTestRunner(verbosity=2)
    # runner.run(suite)
    unittest.main(verbosity=2)  # verbosity=2默认1,2:详细信息;

相关文章

网友评论

      本文标题:1. unittest中断言,值得拥有

      本文链接:https://www.haomeiwen.com/subject/vrmibktx.html