Python断言assert处理

assert断言语句用来声明某个条件是真的,其作用是测试一个条件(condition)是否成立,如果不成立,则抛出异。

一般来说在做单元测试的时候用的比较多,在生产环境代码运行的情况下,不建议使用断言,会让程序abort掉。

什么时候使用断言

保护性的编程 正常情况下,并不是防范当前代码发生错误,而防范由于以后的代码变更发生错误。

运行时序逻辑的检查 这种情况一般都是很严重的,防止脏数据或者异常数据进入业务系统,主动进行中断处理

单元测试代码 开发或测试人员编写单元测试代码的时候,也会使用断言

Python中断言使用

test.py文件

def compare(a, b):
    assert a>b, 'error: b is bigger'
    print('compare: %d %d' %(a, b))

compare(1, 3)

输出:

Traceback (most recent call last):
  File "test8.py", line 5, in <module>
    compare(1, 3)
  File "test8.py", line 2, in compare
    assert a>b, 'error: b is bigger'
AssertionError: error: b is bigger

当然,我们也可以通过-O参数来忽略断言,运行python3 -O test.py
输出:

compare: 1 3

单元测试中常用断言

Python中的unittest框架用来进行单元测试非常方便

import unittest

class WidgetTestCase(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

unittest.main()

unittest中一些常用断言方法如下:

assertEqual(a, b)   a == b   
assertNotEqual(a, b)    a != b   
assertTrue(x)   bool(x) is True  
assertFalse(x)  bool(x) is False     
assertIs(a, b)  a is b  3.1
assertIsNot(a, b)   a is not b  3.1
assertIsNone(x) x is None   3.1
assertIsNotNone(x)  x is not None   3.1
assertIn(a, b)  a in b  3.1
assertNotIn(a, b)   a not in b  3.1
assertIsInstance(a, b)  isinstance(a, b)    3.2
assertNotIsInstance(a, b)   not isinstance(a, b)    3.2

小结

断言在软件系统中有非常重要的作用,写的好可以让你的系统更稳定,也可以让你有更多面对对象的时间,而不是在调试代码。

作者:田阅川
链接:https://www.jianshu.com/p/b70b3340e55f
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发布了16 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_38308549/article/details/103507629