捕获类fixtu的pytest日志

2024-05-23 16:34:49 发布

您现在位置:Python中文网/ 问答频道 /正文

通常您会使用caplog来断言测试中的日志消息,但是我感兴趣的是检查来自外部函数的日志消息,该函数在类作用域fixture中调用(然后传递到测试)。你知道吗

文件说明

import logging


def func_under_test():
    logging.critical('wally')

class MyTestClass:
    def test_baz(self, caplog):
        func_under_test()
        assert 'wally' in caplog.text

然而,我的实际用例如下

import logging
import pytest


def func_under_test():
    logging.critical('wally')

class MyTestClass:

    @pytest.fixture('class')
    def my_fixture(self):
        func_under_test()

    def test_baz(self, my_fixture, caplog):
        assert 'wally' in caplog.text

这当然不起作用,因为测试中没有发布日志。你知道吗

如果我把caplog传递到my_fixture,我得到ScopeMismatch: You tried to access the 'function' scoped fixture 'caplog' with a 'class' scoped request object。你知道吗

有必要在“class”范围内重新定义caplog,还是有更简单的方法?你知道吗


Tags: 函数testimportself消息myloggingdef