python 學習彙總31:doctest - 文件測試簡述( tcy)
阿新 • • 發佈:2018-11-19
doctest - 文件測試: 2018/11/15
用途:
掃描模組並驗證程式文件中嵌入的測試。主要用來測試函式(在文件中)
測試的結構就像將一個典型的呼叫和結果切入並貼上到文件字串一樣簡單。
使用方式:
是嵌入到python源中
放到一個獨立檔案
1.嵌入到python源中
位置: 函式開頭和模組開頭;上面能加一條註釋說明函式或模組用途。 例程: def add0(a, b): """ This is test add0. >>> add0(4, 3) 7 """ return a +b if __name__=='__main__': import doctest doctest.testmod(verbose=True)#True顯示詳細資訊 #預設正確什麼也不顯示,錯誤則顯示錯誤。
輸出:
C:\python37\python.exe C:/Users/Administrator/.PyCharmCE2018.2/config/scratches/multiply_tcy.py Trying: add0(4, 3) Expecting: 7 ok 1 items had no tests: __main__ 1 items passed all tests: 1 tests in __main__.add0 1 tests in 2 items. 1 passed and 0 failed. Test passed. Process finished with exit code 0
2.放到一個獨立檔案
步驟1:
寫模組檔案,並存放的當前工作目錄下:c:\python37\lib\add0_module.py
#模組內容如下:
def add0(a, b):
"""
This is test add0.
>>> add0(4, 3)
7
"""
return a + b
if __name__=='__main__':
import doctest
doctest.testmod(verbose=True)
步驟2: 寫文字執行檔案*.txt(ANI編碼),並存放的當前工作目錄下:c:\python37\lib\test_add0.txt
#文件內容如下
This is test add0.
>>> from add0_module import add0
>>> add0(3,4)
7
步驟3:
dos環境下執行:
--- >cmd
C:\Users\Administrator> cd C:\python37\lib
c:\python37\Lib>python -m doctest -v test_add0.txt
步驟4:
執行結果顯示 :
Trying:
from add0_module import add0
Expecting nothing
ok
Trying:
add0(3,4)
Expecting:
7
ok
1 items passed all tests:
2 tests in test_add0.txt
2 tests in 1 items.
2 passed and 0 failed.
Test passed.
c:\python37\Lib>
3.類中測試
class Dict(dict):
"""
simple dict but also support access as x.y style.
>>> d1 = dict()
>>> d1['x'] = 100
>>> d1.x
100
>>> d1.y = 200
>>> d1['y']
200
>>> d2 = Dict(a=1, b=2, c='3')
>>> d2.c
'3'
>>> d2['empty']
Traceback(most recent call last):
...
KeyError: 'empty'
>>> d2.empty
Traceback(most recent call last):
...
AttributeError: 'Dict' object has no attribute 'empty'
"""
def __init__(self,**kwargs):
super(Dict,self).__init__(**kwargs)
def _getattr_(self,key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'"%key)
def _setattr_(self,key,value):
self[key] = value
測試
if __name__=='_main_':
import doctest
doctest.testmod(verbose=True)