debugging - pytest:如何在测试的函数中显示来自logging.debug的消息

标签 debugging logging pytest

''' func.py '''
import logging

def func():
    ''' func '''
    logging.basicConfig(
        format="\t %(filename)s"
        " %(funcName)s"
        "-ln%(lineno)d"
        " %(levelname)s \n%(message)s",
        level=logging.DEBUG,
        # stream=sys.stdout,
    )
    logger = logging.getLogger()
    logger.info(" >>> logger func info")
    logger.warning(" >>> logger func warning")
    print(" >>> print func info")


def test_func():
    ''' test func '''
    # caplog.set_level(logging.DEBUG)
    func()


if __name__ == "__main__":
    test_func()

假设我将上面的代码保存为 func.py。当我运行时

pytest -s func.py

我得到了

" >>> print func info".

如何获得

" >>> logger func info" 

">>> 记录器功能警告"

当我运行时

pytest -s func.py

我希望我能这样做,原因如下。我通常在我的代码中插入logging.debug/info等。有时,我想在运行 pytest 时查看logging.debug/info 发出的消息。我在网上搜索了很长一段时间但找不到方法。预先感谢您的帮助。

最佳答案

要在每次运行时默认执行此操作,请添加到 pytest.ini:

[pytest]
log_cli = true
log_cli_level = DEBUG

注意:如果使用非常旧的 pytest(3.5 之前的版本),您需要在 pytest.ini 中设置 log_cli = true 才能使用以下命令。

否则,对于 3.5 及更高版本,您可以根据具体情况仅使用命令行:

pytest --log-cli-level=10 func.py

或更清楚地说:

pytest --log-cli-level=DEBUG func.py

命令行将始终覆盖 pytest.ini 设置。

关于debugging - pytest:如何在测试的函数中显示来自logging.debug的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51466586/

相关文章:

c++ - 按位运算截断数字的最后两位

linux - 无法在linux中的eclipse中调试java代码

pytest - pytest生成报告后如何执行代码(使用pytest)?

python pytest 用于测试请求和响应

python - 嵌套生成器到嵌套列表

mysql - 配置 Root MySQL 访问 - MySQL Logrotate

java - 无法将值放入 M​​DC

java - 何时为捕获的异常记录堆栈跟踪

python-3.x - 使用 "@pytest.mark.parametrize"fixture 调用类级变量

c++ - 我可以在 Visual Studio 2017 调试器中查看未处理的异常吗?