Python中关于doctest的使用

doctest是python自带的一个模块,你可以把它叫做“文档测试”(doctest)模块。

我在认识这个模块时,总是不会写,发现格式总是找不对,现在做一下总结。
官方文件描述是:

 In simplest use, end each module M to be tested with:

    def _test():
        import doctest
        doctest.testmod()

    if __name__ == "__main__":
        _test()

    Then running the module as a script will cause the examples in the
    docstrings to get executed and verified:

    python M.py

    This won't display anything unless an example fails, in which case the
    failing example(s) and the cause(s) of the failure(s) are printed to stdout
    (why not stderr? because stderr is a lame hack <0.2 wink>), and the final
    line of output is "Test failed.".

大体意思就是引入这个模块就能对我们编写的程序进行测试。
简单的测试:

def collect_vowels(s):
    """ (str) -> str

    Return the vowels (a, e, i, o, and u) from s.

    >>> collect_vowels('Happy Anniversary!')
    'aAiea'
    >>> collect_vowels('xyz')
    ''
    """

    vowels = ''
    for char in s:
        if char in 'aeiouAEIOU':
            vowels = vowels + char
    return vowels

if __name__ == "__main__":
	import doctest
	doctest.testmod(verbose=True)

运行结果:

PS C:\Users\15222\lpthw> python ex471.py
Trying:
    collect_vowels('Happy Anniversary!')
Expecting:
    'aAiea'
ok
Trying:
    collect_vowels('xyz')
Expecting:
    ''
ok
1 items had no tests:
    __main__
1 items passed all tests:
   2 tests in __main__.collect_vowels
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
PS C:\Users\15222\lpthw>

由于加上了语句`verbose=True``强制将详细信息显示出来,否则就是什么都不输出;去掉那个语句后的运行结果是:

PS C:\Users\15222\lpthw> python ex471.py
PS C:\Users\15222\lpthw>

这是测试的函数中输入的字符串中的元音输出,正确的话,就通过测试。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值