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 相关文章推荐
Flask框架使用DBUtils模块连接数据库操作示例
Jul 20 Python
Django中的ajax请求
Oct 19 Python
Python实现的ftp服务器功能详解【附源码下载】
Jun 26 Python
Python实现蒙特卡洛算法小实验过程详解
Jul 12 Python
Python Numpy 自然数填充数组的实现
Nov 28 Python
python实现五子棋游戏(pygame版)
Jan 19 Python
多个python文件调用logging模块报错误
Feb 12 Python
Python3 selenium 实现QQ群接龙自动化功能
Apr 17 Python
详解python中groupby函数通俗易懂
May 14 Python
完美解决python针对hdfs上传和下载的问题
Jun 05 Python
利用Python实现自动扫雷小脚本
Dec 17 Python
python中的被动信息搜集
Apr 29 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 Ajax实现页面无刷新发表评论
2007/01/02 PHP
PHP提取中文首字母
2008/04/09 PHP
PHP 数据库树的遍历方法
2009/02/06 PHP
PHP中常用的转义函数
2014/02/28 PHP
Linux下PHP连接Oracle数据库
2014/08/20 PHP
CL vs ForZe BO5 第一场 2.13
2021/03/10 DOTA
不错的新闻标题颜色效果
2006/12/10 Javascript
对YUI扩展的Gird组件 Part-2
2007/03/10 Javascript
ajax中get和post的说明及使用与区别
2012/12/23 Javascript
jQuery点击弹出下拉菜单的小例子
2013/08/01 Javascript
黑帽seo劫持程序,js劫持搜索引擎代码
2015/09/15 Javascript
JQuery+EasyUI轻松实现步骤条效果
2016/02/22 Javascript
Bootstrap每天必学之折叠(Collapse)插件
2016/04/25 Javascript
微信小程序模板之分页滑动栏
2017/02/10 Javascript
nodejs前端自动化构建环境的搭建
2017/07/26 NodeJs
node中实现删除目录的几种方法
2019/06/24 Javascript
jQuery实现form表单基于ajax无刷新提交方法实例代码
2019/11/04 jQuery
openlayers实现图标拖动获取坐标
2020/09/25 Javascript
[04:19]完美世界携手游戏风云打造 卡尔工作室模型介绍篇
2013/04/24 DOTA
python实现数据预处理之填充缺失值的示例
2017/12/22 Python
浅谈python中requests模块导入的问题
2018/05/18 Python
python实现人人自动回复、抢沙发功能
2018/06/08 Python
Python函数的参数常见分类与用法实例详解
2019/03/30 Python
pyqt5 QProgressBar清空进度条的实例
2019/06/21 Python
在python image 中安装中文字体的实现方法
2019/08/22 Python
pip install python 快速安装模块的教程图解
2019/10/08 Python
Python hashlib加密模块常用方法解析
2019/12/18 Python
关于Pytorch的MLP模块实现方式
2020/01/07 Python
天逸系统(武汉)有限公司Java笔试题
2015/12/29 面试题
为什么需要版本控制?
2013/08/08 面试题
关于成绩下滑的自我检讨书
2014/09/20 职场文书
故意伤害人身损害赔偿协议书
2014/11/19 职场文书
平安家庭事迹材料
2014/12/20 职场文书
优秀团员事迹材料
2014/12/25 职场文书
2015入党自传格式范文
2015/06/26 职场文书
python爬取网页版QQ空间,生成各类图表
2021/06/02 Python