用pytest测试日志输出 [英] Testing logging output with pytest

查看:1527
本文介绍了用pytest测试日志输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用pytest编写测试,该测试将检查特定功能是否在需要时将警告写到日志中.例如:

I am trying to write a test, using pytest, that would check that a specific function is writing out a warning to the log when needed. For example:

在module.py中:

In module.py:

import logging
LOGGER = logging.getLogger(__name__)

def run_function():
    if something_bad_happens:
        LOGGER.warning('Something bad happened!')

在test_module.py中:

In test_module.py:

import logging
from module import run_function

LOGGER = logging.getLogger(__name__)

def test_func():
    LOGGER.info('Testing now.')
    run_function()
    ~ somehow get the stdout/log of run_function() ~
    assert 'Something bad happened!' in output

我已经看到可以通过pytest获取日志或stdout/stderr,方法是将capsyscaplog作为测试的参数传递,然后使用capsus.readouterr()caplog.records来访问输出.

I have seen that you can supposedly get the log or the stdout/stderr with pytest by passing capsys or caplog as an argument to the test, and then using either capsus.readouterr() or caplog.records to access the output.

但是,当我尝试这些方法时,我只会看到立即测试.",而不会看到发生了什么不好的事情!".似乎无法从test_func()访问对run_function()的调用中发生的日志记录输出?

However, when I try those methods, I only see "Testing now.", and not "Something bad happened!". It seems like the logging output that is happening within the call to run_function() is not accessible from test_func()?

如果我尝试使用更直接的方法(例如sys.stdout.getvalue()),也会发生同样的事情.令人困惑的是,因为run_function()正在写入终端,所以我认为可以从stdout ...访问它?

The same thing happens if I try a more direct method, such as sys.stdout.getvalue(). Which is confusing, because run_function() is writing to the terminal, so I would think that would be accessible from stdout...?

基本上,没有人知道我如何访问发生了什么不好的事情!"从test_func()内部?

Basically, does anyone know how I can access that 'Something bad happened!' from within test_func()?

推荐答案

我不知道为什么以前尝试过这种方法不起作用,但是这种解决方案现在对我有用:

I don't know why this didn't work when I tried it before, but this solution works for me now:

在test_module.py中:

In test_module.py:

import logging
from module import run_function

LOGGER = logging.getLogger(__name__)

def test_func(caplog):
    LOGGER.info('Testing now.')
    run_function()
    assert 'Something bad happened!' in caplog.text

这篇关于用pytest测试日志输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆