NOh*_*Ohs 6 python subprocess pytest
我写我需要从外部调用一个包pytest从内pytest通过运行subprocess。很明显,从子进程捕获的输出正是我想要显示的错误,因为它具有 pytest 提供的所有漂亮的格式和信息。不幸的是,目前主要的 pytest 调用只显示我的包装器的内部代码,而不是漂亮的子进程输出,在我打印它之后,只显示在 pytest 的捕获标准输出部分。我想格式化失败和错误的输出,就好像直接调用代码一样,并隐藏进行了子进程调用。因此,我基本上想用不同的字符串完全替换一个测试函数的输出。这可能吗?
让我们看一个简单包装函数的 MWE(没有做任何有用的事情,但是我能想到的最短的 MWE):
import functools
from subprocess import Popen, PIPE
import sys
def call_something(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# for the sake of simplicity, a dummy call
p = Popen([sys.executable, '-c', 'import numby'], stderr=PIPE, stdout=PIPE)
# let's imagine this is the perfect string output we want
# to print instead of the actual output generated from...
error = p.communicate()[1].decode("utf-8")
if p.returncode != 0:
# ... this line
raise AssertionError(f'{error}')
return wrapper
@call_something
def test_something():
assert 1 == 2
Run Code Online (Sandbox Code Playgroud)
如您所见,我的test_something()函数在子进程中会失败。
如果我pytest使用这个文件运行,我会得到:
================================== FAILURES ===================================
_______________________________ test_something ________________________________
func = <function test_something at 0x000001EA414F1400>, args = (), kwargs = {}
p = <subprocess.Popen object at 0x000001EA414A67B8>
error = 'Traceback (most recent call last):\r\n File "<string>", line 1, in <module>\r\nModuleNotFoundError: No module named \'numby\'\r\n'
def wrapper(*args, **kwargs):
# for the sake of simplicity, a dummy call
p = Popen([sys.executable, '-c', 'import numby'], stderr=PIPE, stdout=PIPE)
# let's imagine this is the perfect string output we want
# to print instead of the actual output generated from...
error = p.communicate()[1].decode("utf-8")
if p.returncode != 0:
# ... this line
> raise AssertionError(f'{error}')
E AssertionError: Traceback (most recent call last):
E File "<string>", line 1, in <module>
E ModuleNotFoundError: No module named 'numby'
test_me.py:18: AssertionError
========================== 1 failed in 0.18 seconds ===========================
Run Code Online (Sandbox Code Playgroud)
显然,我不想展示包装函数的细节。反而
我想展示子流程中发生的事情。所以它应该看起来像这样(或类似)。
================================== FAILURES ===================================
_______________________________ test_something ________________________________
<string captured from subprocess>
========================== 1 failed in 0.11 seconds ===========================
Run Code Online (Sandbox Code Playgroud)
所以我的问题更小:
引发错误时,您可以使用from语法来抑制或更改异常的链接方式。例如,请考虑以下情况:
try:
a / b
except ZeroDivisionError:
raise ValueError('Invalid b value')
Run Code Online (Sandbox Code Playgroud)
ZeroDivisionError如果b == 0后面跟着 a ,这将显示 a ValueError,但您可能想要抑制 the ZeroDivisionError,因为唯一相关的部分是 the ValueError。所以你应该写:
try:
a / b
except ZeroDivisionError:
raise ValueError('Invalid b value') from None
Run Code Online (Sandbox Code Playgroud)
这只会显示ValueError, 告诉你这b是错误的
您还可以使用from此处相关的语法执行其他操作,请参阅此线程了解详细信息。
我做了一些与您尝试的非常相似的事情,通过抑制奇怪的管道错误并改为引发ModuleNotFoundError:
# Test if <module> is callable
try:
sp.run('<run some module>', shell=True, check=True, stdout=sp.PIPE)
except sp.CalledProcessError as exc:
raise ModuleNotFoundError(
'<some module> not working. Please ensure it is installed and can be called with the command: <command>'
) from exc
Run Code Online (Sandbox Code Playgroud)
注意这里的使用from exc。