Python中的文檔測試模組

來源:互聯網
上載者:User

Python中的文檔測試模組

   這篇文章主要介紹了Python中的文檔測試模組,代碼基於Python2.x版本,需要的朋友可以參考下

  如果你經常閱讀Python的官方文檔,可以看到很多文檔都有範例程式碼。比如re模組就帶了很多範例程式碼:

  ?

1

2

3

4

>>> import re

>>> m = re.search('(?<=abc)def', 'abcdef')

>>> m.group(0)

'def'

  可以把這些範例程式碼在Python的互動式環境下輸入並執行,結果與文檔中的範例程式碼顯示的一致。

  這些代碼與其他說明可以寫在注釋中,然後,由一些工具來自動產生文檔。既然這些代碼本身就可以粘貼出來直接運行,那麼,可不可以自動執行寫在注釋中的這些代碼呢?

  答案是肯定的。

  當我們編寫注釋時,如果寫上這樣的注釋:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

def abs(n):

'''

Function to get absolute value of number.

 

Example:

 

>>> abs(1)

1

>>> abs(-1)

1

>>> abs(0)

0

'''

return n if n >= 0 else (-n)

  無疑更明確地告訴函數的調用者該函數的期望輸入和輸出。

  並且,Python內建的“文檔測試”(doctest)模組可以直接提取注釋中的代碼並執行測試。

  doctest嚴格按照Python互動式命令列的輸入和輸出來判斷測試結果是否正確。只有測試異常的時候,可以用...表示中間一大段煩人的輸出。

  讓我們用doctest來測試上次編寫的Dict類:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

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, **kw):

super(Dict, self).__init__(**kw)

 

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()

  運行python mydict.py:

  ?

1

$ python mydict.py

  什麼輸出也沒有。這說明我們編寫的doctest運行都是正確的。如果程式有問題,比如把__getattr__()方法注釋掉,再運行就會報錯:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

$ python mydict.py

**********************************************************************

File "mydict.py", line 7, in __main__.Dict

Failed example:

d1.x

Exception raised:

Traceback (most recent call last):

...

AttributeError: 'Dict' object has no attribute 'x'

**********************************************************************

File "mydict.py", line 13, in __main__.Dict

Failed example:

d2.c

Exception raised:

Traceback (most recent call last):

...

AttributeError: 'Dict' object has no attribute 'c'

**********************************************************************

  注意到最後兩行代碼。當模組正常匯入時,doctest不會被執行。只有在命令列運行時,才執行doctest。所以,不必擔心doctest會在非測試環境下執行。

  小結

  doctest非常有用,不但可以用來測試,還可以直接作為範例程式碼。通過某些文檔產生工具,就可以自動把包含doctest的注釋提取出來。使用者看文檔的時候,同時也看到了doctest。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.