如何让pytest忽略返回非零代码并写入stderr的特定子进程调用?

问题描述 投票:1回答:1

我的代码(在pytest中)是:

    try:
        proc = subprocess.check_output(['somedaemon', '-v'], stderr=subprocess.STDERR)
        assert str(proc) is False, 'somedaemon returned a version number, should be uninstalled'
    except subprocess.CalledProcessError:
        # There was an error - command exited with non-zero code                                                                                                                            
        pass

我的愿望是传递测试对somedaemon的子进程调用返回非零返回代码并在stderr上输出并仍然传递。在这种情况下,我似乎无法让pytest忽略错误。换句话说,没有除外的尝试是失败。期望子进程失败。

Pytest的更多全局错误捕获正在打败我,我还没有找到一种压倒它的方法。

操作系统是CentOS 7。

在下面应用Branden的解决方案之后,我得到了以下结果(这些是来自pytest错误报告的片段):

答:这是通过子进程调用的下一个pdb:

- > proc = subprocess.Popen(['cbdaemon',' - v'],stdout = subprocess.PIPE,stderr = subprocess.PIPE)(Pdb)n FileNotFoundError:[Errno 2]没有这样的文件或目录:'cbdaemon'

B.在错误报告中,我们进入subprocess.py:

/root/.pyenv/versions/3.6.0/lib/python3.6/subprocess.py:707:在init restore_signals,start_new_session中)

C. subprocess.py有一个引发child_exception_type,引发错误:

            if errno_num != 0:
                err_msg = os.strerror(errno_num)
                if errno_num == errno.ENOENT:
                    if child_exec_never_called:
                        # The error must be from chdir(cwd).
                        err_msg += ': ' + repr(cwd)
                    else:
                        err_msg += ': ' + repr(orig_executable)
          raise child_exception_type(errno_num, err_msg)

E FileNotFoundError:[Errno 2]没有这样的文件或目录:'cbdaemon'

/root/.pyenv/versions/3.6.0/lib/python3.6/subprocess.py:1326:FileNotFoundError

这可能是一个棘手的问题。我浏览了很多pytest文档,找不到从整体测试失败中排除这个失败的方法。该错误被编码到subprocess.py中。

python pytest stderr
1个回答
1
投票

您可以只使用Popen并断言返回代码和错误消息。

proc = subprocess.Popen(['somedaemon', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
assert proc.returncode and err 
© www.soinside.com 2019 - 2024. All rights reserved.