Python 测试(一)—— doctest

测试的基本手段即使,保证和测试足够多的 case 。

交互式解释器的会话可以以文档字符串(docstring,在该文档字符串内部测试一些基本案例)的形式写入文档。如下:

def square(x):
    '''
    squares a number and returns the result.
    >>> square(2)
    4
    >>> square(3)
    9
    '''
    return x**2

文档字符串也可以包含一些文本(squares a number and returns the result.)。然而这与测试又有什么关系?假如 square 定义在 my_math 模块(也就是叫做 my_math.py 的文件)。我们可在该文件的末尾添加如下的代码:

if __name__ == '__main__':
    import doctest, my_math
    doctest.testmod(my_math)

在命令行界面,为该脚本(script)设定 -v (verbose,详述)选项开关:

$ python my_math.py -v

将会得到如下的输出:

Trying:
    square(2)
Expecting:
    4
ok
Trying:
    square(3)
Expecting:
    9
ok
1 items had no tests:
    demo
1 items passed all tests:
   2 tests in demo.square
2 tests in 2 items.
2 passed and 0 failed.
Test passed.

如果在 square 函数的内部,我们定义了错误的实现,比如将return x**2 写作 return x**x,再次运行,将得到如下的结果:

Failed example:
    square(3)
Expected:
    9
Got:
    27
1 items had no tests:
    demo
**********************************************************************
1 items had failures:
   1 of   2 in demo.square
2 tests in 2 items.
1 passed and 1 failed.
***Test Failed*** 1 failures.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值