六:Python断言方法:assert

前言

在测试用例中,执行完测试用例后,最后一步是判断测试结果是pass还是fail,自动化测试脚本里面一般把这种生成测试结果的方法称为断言(assert)。

用unittest组件测试用例的时候,断言的方法还是很多的,下面介绍几种常用的断言方法:assertEqual、assertIn、assertTrue

基本断言方法

基本的断言方法提供了测试结果是True还是False。所有的断言方法都有一个msg参数,如果指定msg参数的值,则将该信息作为失败的错误信息返回。

序号断言方法断言描述
1assertEqual(arg1, arg2, msg=None)验证arg1=arg2,不等则fail
2assertNotEqual(arg1, arg2, msg=None)验证arg1 != arg2, 相等则fail
3assertTrue(expr, msg=None)验证expr是true,如果为false,则fail
4assertFalse(expr,msg=None)验证expr是false,如果为true,则fail
5assertIs(arg1, arg2, msg=None)验证arg1、arg2是同一个对象,不是则fail
6assertIsNot(arg1, arg2, msg=None)验证arg1、arg2不是同一个对象,是则fail
7assertIsNone(expr, msg=None)验证expr是None,不是则fail
8assertIsNotNone(expr, msg=None)验证expr不是None,是则fail
9assertIn(arg1, arg2, msg=None)验证arg1是arg2的子串,不是则fail
10assertNotIn(arg1, arg2, msg=None)验证arg1不是arg2的子串,是则fail
11assertIsInstance(obj, cls, msg=None)验证obj是cls的实例,不是则fail
12assertNotIsInstance(obj, cls, msg=None)验证obj不是cls的实例,是则fail

 

一、简单案例

1.下面写了4个case,其中第四个是执行失败的

# coding:utf-8
import unittest
class Test(unittest.TestCase):
    def test01(self):
        '''判断 a == b '''
        a = 1
        b = 1
        self.assertEqual(a, b)

    def test02(self):
        '''判断 a in b '''
        a = "hello"
        b = "hello world!"
        self.assertIn(a, b)

    def test03(self):
        '''判断 a is True '''
        a = True
        self.assertTrue(a)

    def test04(self):
        '''失败案例'''
        a = "上海-悠悠"
        b = "yoyo"
        self.assertEqual(a, b)

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

2.执行结果如下

Failure
Expected :'\xe4\xb8\x8a\xe6\xb5\xb7-\xe6\x82\xa0\xe6\x82\xa0'
Actual   :'yoyo'
 <Click to see difference>

Traceback (most recent call last):
  File "D:\test\yoyotest\kecheng\test12.py", line 27, in test04
    self.assertEqual(a, b)
AssertionError: '\xe4\xb8\x8a\xe6\xb5\xb7-\xe6\x82\xa0\xe6\x82\xa0' != 'yoyo'
3.执行的结果,中文编码不对,没正常显示中文,遇到这种情况,可以自定义异常输出

二、自定义异常

1.以assertEqual为例分析:

assertEqual(self, first, second, msg=None)
    Fail if the two objects are unequal as determined by the '=='
    operator.

2.翻译:如果两个对象不能相等,就返回失败,相当于return: first==second

3.这里除了相比较的两个参数first和second,还有第三个参数msg=None,这个msg参数就是遇到异常后自定义输出信息

 

三、unittest常用的断言方法

1.assertEqual(self, first, second, msg=None)

--判断两个参数相等:first == second

2.assertNotEqual(self, first, second, msg=None)

--判断两个参数不相等:first != second

3.assertIn(self, member, container, msg=None)

--判断是字符串是否包含:member in container

4.assertNotIn(self, member, container, msg=None)

--判断是字符串是否不包含:member not in container

5.assertTrue(self, expr, msg=None)

--判断是否为真:expr is True

6.assertFalse(self, expr, msg=None)

--判断是否为假:expr is False

7.assertIsNone(self, obj, msg=None)

--判断是否为None:obj is None

8.assertIsNotNone(self, obj, msg=None)
--判断是否不为None:obj is not None



四、unittest所有断言方法

1.下面是unittest框架支持的所有断言方法,有兴趣的同学可以慢慢看。

|  assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)
|      Fail if the two objects are unequal as determined by their
|      difference rounded to the given number of decimal places
|      (default 7) and comparing to zero, or by comparing that the
|      between the two objects is more than the given delta.
|      
|      Note that decimal places (from zero) are usually not the same
|      as significant digits (measured from the most signficant digit).
|      
|      If the two objects compare equal then they will automatically
|      compare almost equal.
|  
|  assertAlmostEquals = assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)
|  
|  assertDictContainsSubset(self, expected, actual, msg=None)
|      Checks whether actual is a superset of expected.
|  
|  assertDictEqual(self, d1, d2, msg=None)
|  
|  assertEqual(self, first, second, msg=None)
|      Fail if the two objects are unequal as determined by the '=='
|      operator.
|  
|  assertEquals = assertEqual(self, first, second, msg=None)
|  
|  assertFalse(self, expr, msg=None)
|      Check that the expression is false.
|  
|  assertGreater(self, a, b, msg=None)
|      Just like self.assertTrue(a > b), but with a nicer default message.
|  
|  assertGreaterEqual(self, a, b, msg=None)
|      Just like self.assertTrue(a >= b), but with a nicer default message.
|  
|  assertIn(self, member, container, msg=None)
|      Just like self.assertTrue(a in b), but with a nicer default message.
|  
|  assertIs(self, expr1, expr2, msg=None)
|      Just like self.assertTrue(a is b), but with a nicer default message.
|  
|  assertIsInstance(self, obj, cls, msg=None)
|      Same as self.assertTrue(isinstance(obj, cls)), with a nicer
|      default message.
|  
|  assertIsNone(self, obj, msg=None)
|      Same as self.assertTrue(obj is None), with a nicer default message.
|  
|  assertIsNot(self, expr1, expr2, msg=None)
|      Just like self.assertTrue(a is not b), but with a nicer default message.
|  
|  assertIsNotNone(self, obj, msg=None)
|      Included for symmetry with assertIsNone.
|  
|  assertItemsEqual(self, expected_seq, actual_seq, msg=None)
|      An unordered sequence specific comparison. It asserts that
|      actual_seq and expected_seq have the same element counts.
|      Equivalent to::
|      
|          self.assertEqual(Counter(iter(actual_seq)),
|                           Counter(iter(expected_seq)))
|      
|      Asserts that each element has the same count in both sequences.
|      Example:
|          - [0, 1, 1] and [1, 0, 1] compare equal.
|          - [0, 0, 1] and [0, 1] compare unequal.
|  
|  assertLess(self, a, b, msg=None)
|      Just like self.assertTrue(a < b), but with a nicer default message.
|  
|  assertLessEqual(self, a, b, msg=None)
|      Just like self.assertTrue(a <= b), but with a nicer default message.
|  
|  assertListEqual(self, list1, list2, 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.
|  
|  assertMultiLineEqual(self, first, second, msg=None)
|      Assert that two multi-line strings are equal.
|  
|  assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)
|      Fail if the two objects are equal as determined by their
|      difference rounded to the given number of decimal places
|      (default 7) and comparing to zero, or by comparing that the
|      between the two objects is less than the given delta.
|      
|      Note that decimal places (from zero) are usually not the same
|      as significant digits (measured from the most signficant digit).
|      
|      Objects that are equal automatically fail.
|  
|  assertNotAlmostEquals = assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)
|  
|  assertNotEqual(self, first, second, msg=None)
|      Fail if the two objects are equal as determined by the '!='
|      operator.
|  
|  assertNotEquals = assertNotEqual(self, first, second, msg=None)
|  
|  assertNotIn(self, member, container, msg=None)
|      Just like self.assertTrue(a not in b), but with a nicer default message.
|  
|  assertNotIsInstance(self, obj, cls, msg=None)
|      Included for symmetry with assertIsInstance.
|  
|  assertNotRegexpMatches(self, text, unexpected_regexp, msg=None)
|      Fail the test if the text matches the regular expression.
|  
|  assertRaises(self, excClass, callableObj=None, *args, **kwargs)
|      Fail unless an exception of class excClass is raised
|      by callableObj when invoked with arguments args and keyword
|      arguments kwargs. If a different type of exception is
|      raised, it will not be caught, and the test case will be
|      deemed to have suffered an error, exactly as for an
|      unexpected exception.
|      
|      If called with callableObj omitted or None, will return a
|      context object used like this::
|      
|           with self.assertRaises(SomeException):
|               do_something()
|      
|      The context manager keeps a reference to the exception as
|      the 'exception' attribute. This allows you to inspect the
|      exception after the assertion::
|      
|          with self.assertRaises(SomeException) as cm:
|              do_something()
|          the_exception = cm.exception
|          self.assertEqual(the_exception.error_code, 3)
|  
|  assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs)
|      Asserts that the message in a raised exception matches a regexp.
|      
|      Args:
|          expected_exception: Exception class expected to be raised.
|          expected_regexp: Regexp (re pattern object or string) expected
|                  to be found in error message.
|          callable_obj: Function to be called.
|          args: Extra args.
|          kwargs: Extra kwargs.
|  
|  assertRegexpMatches(self, text, expected_regexp, msg=None)
|      Fail the test unless the text matches the regular expression.
|  
|  assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None)
|      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.
|  
|  assertSetEqual(self, set1, set2, msg=None)
|      A set-specific equality assertion.
|      
|      Args:
|          set1: The first set to compare.
|          set2: The second set to compare.
|          msg: Optional message to use on failure instead of a list of
|                  differences.
|      
|      assertSetEqual uses ducktyping to support different types of sets, and
|      is optimized for sets specifically (parameters must support a
|      difference method).
|  
|  assertTrue(self, expr, msg=None)
|      Check that the expression is true.
|  
|  assertTupleEqual(self, tuple1, tuple2, 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.

转:https://www.cnblogs.com/yoyoketang/p/6691270.html

  • 50
    点赞
  • 291
    收藏
    觉得还不错? 一键收藏
  • 18
    评论
Python中的assert是用来检查一个条件的语句。如果条件为真,则不执行任何操作。如果条件为假,则会抛出AssertError并包含错误信息。它的语法为: assert expression [, arguments]。例如,在下面的代码中,如果x不是一个偶数,则会抛出一个错误。 x = 23 assert x%2 == 0, "x is not an even number" 输出为: AssertionError: x is not an even number 这个语句等价于: if not expression: raise AssertionError(arguments) 可以将assert理解为一个断言,它用于在程序执行之前或之后对结果进行断定。如果结果与预期不符,assert会抛出一个错误。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [【Python断言(assert)的用法,你真的懂吗?](https://blog.csdn.net/qq_46092061/article/details/121735843)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Python中的assert(断言)](https://blog.csdn.net/m0_60152377/article/details/125045399)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [python 错误处理 assert详解](https://download.csdn.net/download/weixin_38504417/14910453)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值