[英]Python test run under Pytest does not catch CalledProcessError exceptions correctly
我目前在Pytest( py.test
)中運行Python doctests時遇到一種奇怪的行為。 以下代碼片段突出顯示了該行為。
python2.7 ./weirdpytestbehaviour_test.py
調用腳本時,doctest 確實通過了。 py.test ./weirdpytestbehaviour_test.py --doctest-modules --tb=short
調用腳本時,doctest 不會通過 。 except CalledProcessError as e:
的語句except CalledProcessError as e:
except Exception as e:
更改except Exception as e:
則將doctests除外,然后還將py.test
傳遞。 似乎py.test對CalledProcessError
異常類型有一些特殊處理。 在py.test
執行時,代碼采用不同的評估路徑是非常不直觀的。 如何控制或調整該行為?
#!/usr/bin/python
# coding=utf-8
# file: 'weirdpytestbehaviour_test.py'
from subprocess import check_output, CalledProcessError
def func(success):
"""The worker function.
>>> func(success=True)
>>> func(success=False)
Ouch!
Special treatment of this particular failure...
"""
try:
# Now invoke a subprocess
if success:
# Will always succeed and return with an exit code of 0
check_output('echo "Hello!"; exit 0', shell=True)
else:
# Will always succeed and return with an exit code of 1
check_output('echo "Ouch!"; exit 1', shell=True)
# Does not catch the exception under pytest
# 'except Exception as e:' would work as expected
except CalledProcessError as e:
print(e.output),
if "Ouch!" in e.output:
print("Special treatment of this particular failure...")
else:
raise
if __name__ == '__main__':
import doctest
doctest.testmod()
失敗情況下py.test的輸出(嘗試捕獲上述CalledProcessError)如下:
$ py.test ./weirdpytestbehaviour_test.py --doctest-modules --tb=short
Test session starts (platform: linux2, Python 2.7.6, pytest 3.4.2, pytest-sugar 0.9.1)
[...]
007 The worker function.
008
009 >>> func(success=True)
010
011 >>> func(success=False)
UNEXPECTED EXCEPTION: CalledProcessError()
Traceback (most recent call last):
File "/usr/lib/python2.7/doctest.py", line 1315, in __run
compileflags, 1) in test.globs
File "<doctest experiments.weirdpytestbehaviour_test.func[1]>", line 1, in <module>
File "weirdpytestbehaviour_test.py", line 22, in func
check_output('echo "Ouch!"; exit 1', shell=True)
File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
CalledProcessError: Command 'echo "Ouch!"; exit 1' returned non-zero exit status 1
weirdpytestbehaviour_test.py:11: UnexpectedException
weirdpytestbehaviour_test.py ⨯ 100% ██████████
Results (0.19s):
1 failed
- weirdpytestbehaviour_test.py:11 [doctest] weirdpytestbehaviour_test.func
經過一番嘗試和錯誤之后,我不僅卸載並重新安裝了pytest,還卸載並重新安裝了我使用的插件,從而解決了此問題。 之后,它又開始工作了。
清理緩存( __pycache__
)無效。 顯然pytest及其插件的安裝有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.