def add(x, y):
""" add two number or string
>>> add(1, 2)
3
>>> add("hello", " world")
'hello world'
>>> add(1, 2.0)
3
>>> add("hello", " python") # doctest: +ELLIPSIS
'hello ...'
"""
return x+y
if __name__ == '__main__':
import doctest
doctest.testmod()
执行它python doctest_sample.py -v得到结果如下(3个用例pass,1个用例fail):
Trying:
add(1, 2)
Expecting:
3
ok
Trying:
add("hello", " world")
Expecting:
'hello world'
ok
Trying:
add(1, 2.0)
Expecting:
3
**********************************************************************
File "doctest_sample.py", line 13, in __main__.add
Failed example:
add(1, 2.0)
Expected:
3
Got:
3.0
Trying:
add("hello", " python") # doctest: +ELLIPSIS
Expecting:
'hello ...'
ok
1 items had no tests:
__main__
**********************************************************************
1 items had failures:
1 of 4 in __main__.add
4 tests in 2 items.
3 passed and 1 failed.
***Test Failed*** 1 failures.
本文地址已经归档到github,您可以访问下面的链接获得。
代码地址