How to ignore structlog debug/info/etc generated during pytest on doctests?

363 Views Asked by At

I'm trying to figure out how to ignore logging output from structlog in my doctests. It seems that pytest is capable of ignoring logs from logging, but not from structlog (at least not natively).

An example follows:

import logging
import structlog


LOGGING_LOGGER = logging.getLogger(__name__)
STRUCTLOG_LOGGER = structlog.getLogger(__name__)


def func_with_logging():
    """
    >>> func_with_logging()
    1
    """
    LOGGING_LOGGER.debug("ABC")
    return 1


def func_with_structlog():
    """
    >>> func_with_structlog()
    1
    """
    STRUCTLOG_LOGGER.debug("ABC")
    return 1

The above fails the structlog doctest only.

========================================= test session starts =========================================
platform linux -- Python 3.9.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /home/bbeattie/test
collected 2 items

myfile.py .F                                                                                    [100%]

============================================== FAILURES ===============================================
________________________________ [doctest] myfile.func_with_structlog _________________________________
019
020     >>> func_with_structlog()
Expected:
    1
Got:
    2022-05-07 18:32.13 [debug    ] ABC
    1

/home/bbeattie/test/myfile.py:20: DocTestFailure
======================================= short test summary info =======================================
FAILED myfile.py::myfile.func_with_structlog
===================================== 1 failed, 1 passed in 0.03s =====================================

Am I missing some obvious flag to pytest?

1

There are 1 best solutions below

1
On BEST ANSWER

You can either configure structlog to not log to stdout, or configure it to log using standard library logging such that pytest's logging helpers work.

The autouse fixture in https://www.structlog.org/en/stable/testing.html should be the simplest way to achieve the first approach, for the latter the "Rendering Within structlog" approach should work. Add your own autouse fixture that configures structlog for that (session scope should be fine, no need to re-configure for each test).