我有這個 MRE:
.
└── tests
└── notest.py
notest.py只是做sys.exit(1)一個:
當我運行時,pytest --doctest-modules我收到此錯誤:
ERROR collecting tests/notest.py
tests/notest.py:4: in <module>
sys.exit(1)
E SystemExit: 1
所以--doctest-modules會嘗試執行我的腳本,這不是測驗。這是正常行為嗎?如何預防?
uj5u.com熱心網友回復:
這是正常的行為嗎?
是的。通過--doctest-modules將激活一個特殊的 doctest 收集器,該收集器不限于python_files(test_*.py并且*_test.py默認情況下) 指定的 glob。相反,它會查找并收集任何不是__init__.py或__main__.py. 之后,doctest將匯入它們以收集檔案字串并從每個模塊執行檔案測驗。
如何防止?
如果您notest要運行 doctest,則必須防止在notest模塊匯入時執行代碼。將導致過早退出的代碼放入if __name__ == '__main__'塊中:
# notest.py
import sys
if __name__ == '__main__':
sys.exit(1)
現在常規匯入(例如python -c 'import tests.notest')將以 0 退出,因為未執行主塊,而運行模塊(例如python tests/notest.py或python -m tests.notest)仍將以 1 退出。
如果您在模塊中沒有測驗notest或者您無法編輯其代碼,您可以指示pytest完全忽略該模塊:
$ pytest --doctest-modules --ignore=tests/notest.py
或堅持該選項pyproject.toml或pytest.ini避免每次都輸入該選項。示例pyproject.toml:
[tool.pytest.ini_options]
addopts = "--ignore=tests/notest.py"
或者,這也可以在conftest模塊中完成。例子:
# tests/conftest.py
collect_ignore = ["notest.py"]
注意collect_ignore接收與當前conftest模塊相關的檔案。因此,如果您conftest在專案根目錄(與目錄相同級別tests)中使用 a,則必須指定正確的相對路徑:
# conftest.py
collect_ignore = ["tests/notest.py"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/531975.html
上一篇:如何處理物件內的行內函式的錯誤
下一篇:Pytest試圖收集錯誤的類
