当前位置: 首页 > 工具软件 > doctest > 使用案例 >

python中doctest_理解Python的doctest

云宏儒
2023-12-01

Python的doctest是一个标准模块,而且跟docstring有很大的关系。

Python的docstring是一段特别的注释,可以通过内置的help函数来提取,形成对模块,函数,类定义的解释文档,当然也有一些其它的工具来提取docstring。编写python程序,同时也编写文档,代码和文档同时写。而doctest要编写的内容就是docstring中的一部分,或者说,doctest要编写的内容,就属于docstring的一部分。

doctest模块的作用是,在函数的docstring区域,以注释的形式,写出这个函数的测试用例,即这个函数的调用方式以及返回。这样起到两个作用:

(1)编写函数的测试用例,测试用例同时也作为docstring中的函数使用介绍用例;

(2)实现测试的自动化单元测试。

官方的一个doctest的例子:

"""

This is the "test.py" module.

The test module supplies one function, factorial(). For example,

>>> factorial(5)

120

"""

def factorial(n):

"""Return the factorial of n, an exact integer >= 0.

>>> [factorial(n) for n in range(6)]

[1, 1, 2, 6, 24, 120]

>>> factorial(30)

265252859812191058636308480000000

>>> factorial(-1)

Traceback (most recent call last):

...

ValueError: n must be >= 0

Factorials of floats are OK, but the float must be an exact integer:

>>> factorial(30.1)

Traceback (most recent call last):

...

ValueError: n must be exact integer

>>> factorial(30.0)

265252859812191058636308480000000

It must also not be ridiculously large:

>>> factorial(1e100)

Traceback (most recent call last):

...

OverflowError: n too large

"""

import math

if not n >= 0:

raise ValueError("n must be >= 0")

if math.floor(n) != n:

raise ValueError("n must be exact integer")

if n+1 == n: # catch a value like 1e300

raise OverflowError("n too large")

result = 1

factor = 2

while factor <= n:

result *= factor

factor += 1

return result

if __name__ == "__main__":

import doctest

doctest.testmod()

下面是执行:

默认一切OK就没有输出,加“-v”可强制输出。

D:\pytest>python test.py

D:\pytest>python test.py -v

Trying:

factorial(5)

Expecting:

120

ok

Trying:

[factorial(n) for n in range(6)]

Expecting:

[1, 1, 2, 6, 24, 120]

ok

Trying:

factorial(30)

Expecting:

265252859812191058636308480000000

ok

Trying:

factorial(-1)

Expecting:

Traceback (most recent call last):

...

ValueError: n must be >= 0

ok

Trying:

factorial(30.1)

Expecting:

Traceback (most recent call last):

...

ValueError: n must be exact integer

ok

Trying:

factorial(30.0)

Expecting:

265252859812191058636308480000000

ok

Trying:

factorial(1e100)

Expecting:

Traceback (most recent call last):

...

OverflowError: n too large

ok

2 items passed all tests:

1 tests in __main__

6 tests in __main__.factorial

7 tests in 2 items.

7 passed and 0 failed.

Test passed.

D:\pytest>

这就是Python的doctest。

我们用Python编程,在写代码的时候,不仅同时完成了文档docstring,还同时完成了单元测试。

doctest还有更多更详细的用法,还可以增加一些可选参数来对返回的内容进行适配(毕竟是手写返回内容,而且有些返回内容在程序运行前不得而知,只知道格式和大概),请参考python官方介绍:https://docs.python.org/3/library/doctest.html

 类似资料: