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>

這是測試的函數中輸入的字符串中的元音輸出,正確的話,就通過測試。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章