(点击
上方蓝字
,快速关注我们)
来源:cicaday
segmentfault.com/a/1190000007248161
如有好文章投稿,请点击 → 这里了解详情
Python中的断言用起来非常简单,你可以在assert后面跟上任意判断条件,如果断言失败则会抛出异常。
>>>
assert
1
+
1
==
2
>>>
assert
isinstance
(
'Hello'
,
str
)
>>>
assert
isinstance
(
'Hello'
,
int
)
Traceback
(
most recent call
last
)
:
File
""
,
line
1
,
in
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
"
"
,
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