我的函數從文件中讀取,並且doctest需要以獨立於絕對路徑的方式寫入。什麼是編寫文檔測試的最佳方式?編寫臨時文件非常昂貴,而且不會失敗。如何爲從文件中讀取的函數編寫doctest?
2
A
回答
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)
相關問題
- 1. 從文件中讀取並寫入新文件的函數
- 2. 用C++編寫/從文件讀取
- 3. 如何在文件夾中編寫和讀取文本文件?
- 4. 如何編寫能夠讀取和覆蓋文本文件的Python函數?
- 5. 如何從C++中的數據文件讀取/寫入
- 6. 如何單元測試讀取或寫入文件的函數?
- 7. 如何編寫從單獨的python文件中讀取數據的三角函數?
- 8. Python - 從正在Windows中編寫的文本文件讀取
- 9. 如何從C編程的文件中讀取數據?
- 10. 從文件中讀取數據並寫入perl中的文件
- 11. C++:如何編寫一個程序從文件中讀取整數?
- 12. 在Firefox OS中編寫/讀取文件
- 13. 如何從文件中讀取幻數?
- 14. C++:從txt文件讀取和寫入的成員函數
- 15. 如何從函數中編寫.csv文件?
- 16. 如何寫.js文件從XML文件中讀取
- 17. 如何編寫C++ dll函數來獲取com端口讀取
- 18. 如何在Fortran中讀取Matlab編寫的二進制文件?
- 19. 從文件中讀取並作爲字典返回的函數?
- 20. 從函數讀取文件中的意外行爲C
- 21. 使用java編寫和讀取文本文件中的數字
- 22. 如何讀取文件,存儲數據然後編寫它
- 23. 從文本中讀取數字值已經在Android中編寫的文件
- 24. 如何從文件函數中進行工作讀取?
- 25. 如何使Jar exe文件從文本文件中讀取/寫入數據
- 26. Android - 寫入/讀取文件的編碼
- 27. 從用.net編寫的文件中讀取字符
- 28. 寫入和從文件中讀取
- 29. NSDocumentDirectory - 寫入並從文件中讀取
- 30. 從python中讀取和寫入文件