Pytest下的Python测试运行没有正确捕获CalledProcessError异常

时间:2018-03-09 09:13:13

标签: python exception subprocess pytest doctest

在Pytest(py.test)中运行Python doctests时,我正面临一种奇怪的行为。以下片段突出了bevaviour。

  • 当通过python2.7 ./weirdpytestbehaviour_test.py调用脚本时,doctests 传递
  • 通过py.test ./weirdpytestbehaviour_test.py --doctest-modules --tb=short调用脚本时,doctests 不会传递
  • 如果我将语句except CalledProcessError 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

1 个答案:

答案 0 :(得分:0)

经过一些反复试验后,我解决了这个问题,不仅卸载并重新安装了pytest,还重新安装了我使用过的插件。之后它又恢复了工作。

清理缓存(__pycache__)没有效果。显然,pytest及其插件的安装有问题。