gpt4 book ai didi

python - 如何在 pytest 钩子(Hook)中捕获打印语句

转载 作者:行者123 更新时间:2023-12-04 09:30:52 25 4
gpt4 key购买 nike

我是 pytest 框架工作的新手,并试图了解 pytest 钩子(Hook)。我在 pytest 钩子(Hook)中放置了一些打印语句,但不确定如何在控制台上打印语句。
这是我尝试过的示例

# content of conftest.py
import pytest
import sys

def pytest_load_initial_conftests(args):
print ("Hello")
if 'xdist' in sys.modules: # pytest-xdist plugin
import multiprocessing

num = max(multiprocessing.cpu_count() / 2, 1)
args[:] = ["-n", str(num)] + args
print ("args: ", args)
# content of the test_sample.py
def test_answer():
# assert 0
print ("test function")
pass
我试过使用 pytest test_sample.py -s , pytest --capture=sys/fd/no .我只能从 test_answer 函数获取控制台上的打印语句,但不能从 pytest 钩子(Hook)获取。
谢谢

最佳答案

引用 pytest_load_initial_conftests 的文档钩,

Note:

This hook will not be called for conftest.py files, only for setuptools plugins.


所以把它放到 conftest.py没有效果。您需要通过 pytest 调用钩子(Hook)插件系统。按照文档中的建议,将钩子(Hook) impl 移动到单独的包中:
# myplugin.py

def pytest_load_initial_conftests(args):
...

# setup.py
from setuptools import setup

setup(
name='myplugin',
py_modules=['myplugin'],
entry_points={'pytest11': ['myplugin = myplugin']}
)
并像往常一样通过 pip install 安装它/ python setup.py install .
或保留 myplugin.py使用其余代码并通过 -p 传递自定义插件参数:
$ pytest -p myplugin
您可能需要更新 PYTHONPATH对于 myplugin.py成为可进口的。自定义插件 arg 可以移动到 pytest.ini简化调用:
[pytest]
addopts = -p myplugin

关于python - 如何在 pytest 钩子(Hook)中捕获打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com