Python中断言Assertion的一些改进方案


Posted in Python onOctober 27, 2016

Python Assert 为何不尽如人意?

Python中的断言用起来非常简单,你可以在assert后面跟上任意判断条件,如果断言失败则会抛出异常。

>>> assert 1 + 1 == 2
>>> assert isinstance('Hello', str)
>>> assert isinstance('Hello', int)

Traceback (most recent call last):
 File "<input>", line 1, in <module>
AssertionError

其实assert看上去不错,然而用起来并不爽。就比如有人告诉你程序错了,但是不告诉哪里错了。很多时候这样的assert还不如不写,写了我就想骂娘。直接抛一个异常来得更痛快一些。

改进方案 #1

一个稍微改进一丢丢的方案就是把必要的信息也放到assert语句后面,比如这样。

>>> s = "nothin is impossible."
>>> key = "nothing"
>>> assert key in s, "Key: '{}' is not in Target: '{}'".format(key, s)

Traceback (most recent call last):
 File "<input>", line 1, in <module>
AssertionError: Key: 'nothing' is not in Target: 'nothin is impossible.'

看上去还行吧,但是其实写的很蛋疼。假如你是一名测试汪,有成千上万的测试案例需要做断言做验证,相信你面对以上做法,心中一定有千万只那种马奔腾而过。

改进方案 #2

不管你是你是搞测试还是开发的,想必听过不少测试框架。你猜到我要说什么了吧?对,不用测试框架里的断言机制,你是不是洒。

py.test

py.test 是一个轻量级的测试框架,所以它压根就没写自己的断言系统,但是它对Python自带的断言做了强化处理,如果断言失败,那么框架本身会尽可能多地提供断言失败的原因。那么也就意味着,用py.test实现测试,你一行代码都不用改。

import pytest

def test_case():
  expected = "Hello"
  actual = "hello"
  assert expected == actual

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

"""
================================== FAILURES ===================================
__________________________________ test_case __________________________________

  def test_case():
    expected = "Hello"
    actual = "hello"
>    assert expected == actual
E    assert 'Hello' == 'hello'
E     - Hello
E     ? ^
E     + hello
E     ? ^

assertion_in_python.py:7: AssertionError
========================== 1 failed in 0.05 seconds ===========================
""""

unittest

Python自带的unittest单元测试框架就有了自己的断言方法self.assertXXX() ,而且不推荐使用assert XXX语句。

import unittest

class TestStringMethods(unittest.TestCase):

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

if __name__ == '__main__':
  unittest.main()
  
"""
Failure
Expected :'FOO'
Actual  :'FoO'

Traceback (most recent call last):
 File "assertion_in_python.py", line 6, in test_upper
  self.assertEqual('foo'.upper(), 'FoO')
AssertionError: 'FOO' != 'FoO'
"""

ptest

我非常喜欢ptest,感谢Karl大神写了这么一个测试框架。ptest中的断言可读性很好,而且通过IDE的智能提示你能轻松完成各种断言语句。

from ptest.decorator import *
from ptest.assertion import *

@TestClass()
class TestCases:
  @Test()
  def test1(self):
    actual = 'foo'
    expected = 'bar'
    assert_that(expected).is_equal_to(actual)

"""
Start to run following 1 tests:
------------------------------
...
[demo.assertion_in_python.TestCases.test1@Test] Failed with following message:
...
AssertionError: Unexpectedly that the str <bar> is not equal to str <foo>.
"""

改进方案 #3

不仅仅是你和我对Python中的断言表示不满足,所以大家都争相发明自己的assert包。在这里我强烈推荐assertpy 这个包,它异常强大而且好评如潮。

pip install assertpy

看例子:

from assertpy import assert_that

def test_something():
  assert_that(1 + 2).is_equal_to(3)
  assert_that('foobar')\
    .is_length(6)\
    .starts_with('foo')\
    .ends_with('bar')
  assert_that(['a', 'b', 'c'])\
    .contains('a')\
    .does_not_contain('x')

从它的主页文档上你会发现它支持了几乎你能想到的所有测试场景,包括但不限于以下列表。

      Strings

      Numbers

      Lists

      Tuples

      Dicts

      Sets

      Booleans

      Dates

      Files

      Objects

而且它的断言信息简洁明了,不多不少。

Expected <foo> to be of length <4>, but was <3>.
Expected <foo> to be empty string, but was not.
Expected <False>, but was not.
Expected <foo> to contain only digits, but did not.
Expected <123> to contain only alphabetic chars, but did not.
Expected <foo> to contain only uppercase chars, but did not.
Expected <FOO> to contain only lowercase chars, but did not.
Expected <foo> to be equal to <bar>, but was not.
Expected <foo> to be not equal to <foo>, but was.
Expected <foo> to be case-insensitive equal to <BAR>, but was not.

在发现assertpy之前我也想写一个类似的包,尽可能通用一些。但是现在,我为毛要重新去造轮子?完全没必要!

总结

断言在软件系统中有非常重要的作用,写的好可以让你的系统更稳定。Python中默认的断言语句其实还有一个作用,如果你写了一个类型相关的断言,IDE会把这个对象当成这种类型,这时候智能提示就有如神助。

要不要把内置的断言语句换成可读性更好功能更强大的第三方断言,完全取决于实际情况。比如你真的需要验证某个东西并且很关心验证结果,那么必须不能用简单的assert;如果你只是担心某个点可能有坑或者让IDE认识某个对象,用内置的assert既简单又方便。

所以说,项目经验还是蛮重要的。以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能有所帮助,如果有疑问大家可以留言交流。

Python 相关文章推荐
在Django的模型中添加自定义方法的示例
Jul 21 Python
python中pandas.DataFrame的简单操作方法(创建、索引、增添与删除)
Mar 12 Python
python实现发送邮件功能
Jul 22 Python
python多线程之事件Event的使用详解
Apr 27 Python
Python实现绘制双柱状图并显示数值功能示例
Jun 23 Python
python 去除二维数组/二维列表中的重复行方法
Jan 23 Python
python中数组和矩阵乘法及使用总结(推荐)
May 18 Python
Mac在python3环境下安装virtualwrapper遇到的问题及解决方法
Jul 09 Python
python用类实现文章敏感词的过滤方法示例
Oct 27 Python
浅谈tensorflow中张量的提取值和赋值
Jan 19 Python
Python3.7在anaconda里面使用IDLE编译器的步骤详解
Apr 29 Python
Selenium webdriver添加cookie实现过程详解
Aug 12 Python
利用Python实现颜色色值转换的小工具
Oct 27 #Python
Python实现批量检测HTTP服务的状态
Oct 27 #Python
python解决网站的反爬虫策略总结
Oct 26 #Python
Python控制多进程与多线程并发数总结
Oct 26 #Python
Python网络爬虫项目:内容提取器的定义
Oct 25 #Python
Python实现ssh批量登录并执行命令
Oct 25 #Python
详解Python的Lambda函数与排序
Oct 25 #Python
You might like
php 运行效率总结(提示程序速度)
2009/11/26 PHP
php中通过curl检测页面是否被百度收录
2013/09/27 PHP
linux下使用crontab实现定时PHP计划任务失败的原因分析
2014/07/05 PHP
thinkphp中session和cookie无效的解决方法
2014/12/19 PHP
golang实现php里的serialize()和unserialize()序列和反序列方法详解
2018/10/30 PHP
Laravel6.2中用于用户登录的新密码确认流程详解
2019/10/16 PHP
php设计模式之模板模式实例分析【星际争霸游戏案例】
2020/03/24 PHP
jquery 学习之二 属性(类)
2010/11/25 Javascript
在IE和VB中支持png图片透明效果的实现方法(vb源码打包)
2011/04/01 Javascript
javascript中验证大写字母、数字和中文
2014/01/15 Javascript
使用node.js半年来总结的 10 条经验
2014/08/18 Javascript
详解JavaScript中常用的函数类型
2015/11/18 Javascript
详解js中的apply与call的用法
2016/07/30 Javascript
jquery 中toggle的2种用法详解(推荐)
2016/09/02 Javascript
jQuery的extend方法【三种】
2016/12/14 Javascript
JS日程管理插件FullCalendar简单实例
2017/02/07 Javascript
用vue构建多页面应用的示例代码
2017/09/20 Javascript
jQuery简单实现对数组去重及排序操作实例
2017/10/31 jQuery
Angularjs实现多图片上传预览功能
2018/07/18 Javascript
vue实现搜索过滤效果
2019/05/28 Javascript
webpack常用构建优化策略小结
2019/11/21 Javascript
JS面向对象实现飞机大战
2020/08/26 Javascript
Python入门篇之编程习惯与特点
2014/10/17 Python
python实现单链表的方法示例
2019/09/03 Python
利用python中的matplotlib打印混淆矩阵实例
2020/06/16 Python
Hotels.com越南:酒店预订
2019/10/29 全球购物
新西兰Bookabach:查找全球度假屋
2020/12/03 全球购物
linux面试题参考答案(7)
2012/10/29 面试题
党的群众路线教育实践活动个人对照检查材料范文
2014/09/25 职场文书
高中生旷课检讨书
2014/10/08 职场文书
党的群众路线教育实践活动制度建设计划方案
2014/10/31 职场文书
拾金不昧表扬稿
2015/01/16 职场文书
保护环境建议书作文300字
2015/09/14 职场文书
在CSS中使用when/else的方法
2022/01/18 HTML / CSS
深入理解go缓存库freecache的使用
2022/02/15 Golang
Mysql 8.x 创建用户以及授予权限的操作记录
2022/04/18 MySQL