📜  单元测试框架-断言

📅  最后修改于: 2020-12-03 05:28:10             🧑  作者: Mango


Python测试框架使用Python的内置assert()函数来测试特定条件。如果断言失败,将引发AssertionError。然后,测试框架会将测试标识为“失败”。其他异常被视为错误。

在unittest模块中定义了以下三组断言函数-

  • 基本布尔断言
  • 比较断言
  • 集合断言

基本的断言函数评估操作的结果是True还是False。所有的assert方法都接受一个msg参数,如果指定该参数,该参数将用作失败时的错误消息。

Sr.No. Method & Description
1

assertEqual(arg1, arg2, msg = None)

Test that arg1 and arg2 are equal. If the values do not compare equal, the test will fail.

2

assertNotEqual(arg1, arg2, msg = None)

Test that arg1 and arg2 are not equal. If the values do compare equal, the test will fail.

3

assertTrue(expr, msg = None)

Test that expr is true. If false, test fails

4

assertFalse(expr, msg = None)

Test that expr is false. If true, test fails

5

assertIs(arg1, arg2, msg = None)

Test that arg1 and arg2 evaluate to the same object.

6

assertIsNot(arg1, arg2, msg = None)

Test that arg1 and arg2 don’t evaluate to the same object.

7

assertIsNone(expr, msg = None)

Test that expr is None. If not None, test fails

8

assertIsNotNone(expr, msg = None)

Test that expr is not None. If None, test fails

9

assertIn(arg1, arg2, msg = None)

Test that arg1 is in arg2.

10

assertNotIn(arg1, arg2, msg = None)

Test that arg1 is not in arg2.

11

assertIsInstance(obj, cls, msg = None)

Test that obj is an instance of cls

12

assertNotIsInstance(obj, cls, msg = None)

Test that obj is not an instance of cls

上面的一些断言功能在以下代码中实现-

import unittest

class SimpleTest(unittest.TestCase):
   def test1(self):
      self.assertEqual(4 + 5,9)
   def test2(self):
      self.assertNotEqual(5 * 2,10)
   def test3(self):
      self.assertTrue(4 + 5 == 9,"The result is False")
   def test4(self):
      self.assertTrue(4 + 5 == 10,"assertion fails")
   def test5(self):
      self.assertIn(3,[1,2,3])
   def test6(self):
      self.assertNotIn(3, range(5))

if __name__ == '__main__':
   unittest.main()

当运行上述脚本时,test2,test4和test6将显示失败,其他脚本将成功运行。

FAIL: test2 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "C:\Python27\SimpleTest.py", line 9, in test2
      self.assertNotEqual(5*2,10)
AssertionError: 10 == 10

FAIL: test4 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "C:\Python27\SimpleTest.py", line 13, in test4
      self.assertTrue(4+5==10,"assertion fails")
AssertionError: assertion fails

FAIL: test6 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "C:\Python27\SimpleTest.py", line 17, in test6
      self.assertNotIn(3, range(5))
AssertionError: 3 unexpectedly found in [0, 1, 2, 3, 4]

----------------------------------------------------------------------            
Ran 6 tests in 0.001s                                                             
                                                                                  
FAILED (failures = 3)

第二组断言函数是比较断言-

  • assertAlmostEqual (第一,第二,位= 7,味精=无,增量=无)

    测试的第一第二大致的(或不近似)通过计算差,四舍五入到小数点的给定数量(默认7)相等,

  • assertNotAlmostEqual (第一,第二,位置,味精,增量)

    通过计算差值,四舍五入到给定的小数位数(默认为7),然后与零进行比较,测试第一和第二个近似不相等。

    在以上两个函数中,如果提供了增量而不是位置,则第一和第二之间的差必须小于或等于(或大于)增量。

    同时提供delta和place会引发TypeError。

  • assertGreater (first,second,msg = None)

    测试第一个大于第二个,具体取决于方法名称。否则,测试将失败。

  • assertGreaterEqual (first,second,msg = None)

    根据方法名称测试第一个大于或等于第二个。否则,测试将失败

  • assertLess (第一,第二,msg =无)

    根据方法名称,测试第一个小于第二个。否则,测试将失败

  • assertLessEqual (第一,第二,味精=无)

    根据方法名称,测试第一个小于或等于第二个。否则,测试将失败。

  • assertRegexpMatches (text,regexp,msg = None)

    测试正则表达式搜索是否与文本匹配。如果失败,错误消息将包括模式和文本。 regexp可以是正则表达式对象,也可以是包含适合re.search()使用的正则表达式的字符串。

  • assertNotRegexpMatches (text,regexp,msg = None)

    验证正则表达式搜索与text不匹配。失败,并显示错误消息,包括模式和匹配的文本部分。 regexp可以是正则表达式对象,也可以是包含适合re.search()使用的正则表达式的字符串。

断言功能在以下示例中实现-

import unittest
import math
import re

class SimpleTest(unittest.TestCase):
   def test1(self):
      self.assertAlmostEqual(22.0/7,3.14)
   def test2(self):
      self.assertNotAlmostEqual(10.0/3,3)
   def test3(self):
      self.assertGreater(math.pi,3)
   def test4(self):
      self.assertNotRegexpMatches("Tutorials Point (I) Private Limited","Point")

if __name__ == '__main__':
   unittest.main()

上面的脚本将test1和test4报告为Failure。在test1中,22/7的除法不在3.14的7个小数位之内。同样,由于第二个参数与第一个参数中的文本匹配,因此test4会导致AssertionError。

=====================================================FAIL: test1 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "asserttest.py", line 7, in test1
      self.assertAlmostEqual(22.0/7,3.14)
AssertionError: 3.142857142857143 != 3.14 within 7 places
================================================================
FAIL: test4 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "asserttest.py", line 13, in test4
      self.assertNotRegexpMatches("Tutorials Point (I) Private Limited","Point")
AssertionError: Regexp matched: 'Point' matches 'Point' in 'Tutorials Point (I)
Private Limited'
----------------------------------------------------------------------

Ran 4 tests in 0.001s                                                             
                                                                                  
FAILED (failures = 2)

声明收藏

这组断言函数旨在与Python的集合数据类型一起使用,例如List,Tuple,Dictionary和Set。

Sr.No. Method & Description
1

assertListEqual (list1, list2, msg = None)

Tests that two lists are equal. If not, an error message is constructed that shows only the differences between the two.

2

assertTupleEqual (tuple1, tuple2, msg = None)

Tests that two tuples are equal. If not, an error message is constructed that shows only the differences between the two.

3

assertSetEqual (set1, set2, msg = None)

Tests that two sets are equal. If not, an error message is constructed that lists the differences between the sets.

4

assertDictEqual (expected, actual, msg = None)

Test that two dictionaries are equal. If not, an error message is constructed that shows the differences in the dictionaries.

以下示例实现上述方法-

import unittest

class SimpleTest(unittest.TestCase):
   def test1(self):
      self.assertListEqual([2,3,4], [1,2,3,4,5])
   def test2(self):
      self.assertTupleEqual((1*2,2*2,3*2), (2,4,6))
   def test3(self):
      self.assertDictEqual({1:11,2:22},{3:33,2:22,1:11})

if __name__ == '__main__':
   unittest.main()

在上面的示例中,test1和test3显示AssertionError。错误消息显示列表和字典对象中的差异。

FAIL: test1 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "asserttest.py", line 5, in test1
      self.assertListEqual([2,3,4], [1,2,3,4,5])
AssertionError: Lists differ: [2, 3, 4] != [1, 2, 3, 4, 5]

First differing element 0:
2
1

Second list contains 2 additional elements.
First extra element 3:
4

- [2, 3, 4]
+ [1, 2, 3, 4, 5]
? +++       +++

FAIL: test3 (__main__.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "asserttest.py", line 9, in test3
      self.assertDictEqual({1:11,2:22},{3:33,2:22,1:11})
AssertionError: {1: 11, 2: 22} != {1: 11, 2: 22, 3: 33}
- {1: 11, 2: 22}
+ {1: 11, 2: 22, 3: 33}
?              +++++++
                                                                                  
----------------------------------------------------------------------            
Ran 3 tests in 0.001s                                                             
                                                                                  
FAILED (failures = 2)