Python单元测试工具:doctest的使用方法

doctest本身是一个为检查文档而设计的,但非常适合用来编写单元测试。

  • 新建一个名为 my_math.py 的文件,并编写以下代码:
def square(x):
    '''
	计算平方并返回结果
	>>> square(2)
	4
	>>> square(3)
	9
	'''
    return x * x


if __name__ == '__main__':
    import doctest, my_math

    doctest.testmod(my_math)

从代码中可以看到,注释的部分,是直接从交互式解释器中直接复制出来的。实际上,交互式会话是一种很有用的文档,可将其放在文档字符串中,作为单元测试的代码。

  • 执行代码
~ python3 my_math.py
~

看似什么都没输出,其实已经测试通过了,可以通过下述命令看一下实际情况

~ python3 my_math.py -v
~ Trying:
    square(2)
Expecting:
    4
ok
Trying:
    square(3)
Expecting:
    9
ok
1 items had no tests:
    my_math
1 items passed all tests:
   2 tests in my_math.square
2 tests in 2 items.
2 passed and 0 failed.
Test passed.

  • 再示范一个fail的情况,将代码注释中square(3)的结果改成8,再执行以下脚本:
~ python3 my_math.py -v
~**********************************************************************
File "my_math.py", line 6, in my_math.square
Failed example:
    square(3)
Expected:
    8
Got:
    9
**********************************************************************
1 items had failures:
   1 of   2 in my_math.square
***Test Failed*** 1 failures.

从执行结果来看,已经清楚的指出了错误在什么地方。

发布了102 篇原创文章 · 获赞 6 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/tt75281920/article/details/104130937