2013-05-30 25 views

回答

1

您的doctest可以使用模塊StringIO從字符串中提供文件對象。

0

您可以擁有一個參數,該參數採用路徑,用下劃線標記以表示僅供內部使用。該參數應該默認爲非測試模式下的絕對路徑。命名臨時文件是解決方案,並且使用with語句應該是失敗的。

#!/usr/bin/env python3 
import doctest 
import json 
import tempfile 

def read_config(_file_path='/etc/myservice.conf'): 
    """ 
    >>> with tempfile.NamedTemporaryFile() as tmpfile: 
    ...  tmpfile.write(b'{"myconfig": "myvalue"}') and True 
    ...  tmpfile.flush() 
    ...  read_config(_file_path=tmpfile.name) 
    True 
    {'myconfig': 'myvalue'} 
    """ 
    with open(_file_path, 'r') as f: 
     return json.load(f) 

# Self-test 
if doctest.testmod()[0]: 
    exit(1) 

對於Python 2.x中的文檔測試會有所不同:

#!/usr/bin/env python2 
import doctest 
import json 
import tempfile 

def read_config(_file_path='/etc/myservice.conf'): 
    """ 
    >>> with tempfile.NamedTemporaryFile() as tmpfile: 
    ...  tmpfile.write(b'{"myconfig": "myvalue"}') and True 
    ...  tmpfile.flush() 
    ...  read_config(_file_path=tmpfile.name) 
    {u'myconfig': u'myvalue'} 
    """ 
    with open(_file_path, 'r') as f: 
     return json.load(f) 

# Self-test 
if doctest.testmod()[0]: 
    exit(1) 
相關問題