'Pytest logging ignores dependency warnings

I have a simple python script that leads to a pandas SettingsWithCopyWarning:

import logging

import pandas as pd


def method():
    logging.info("info")
    logging.warning("warning1")
    logging.warning("warning2")
    df = pd.DataFrame({"1": [1, 0], "2": [3, 4]})
    df[df["1"] == 1]["2"] = 100


if __name__ == "__main__":
    method()

When I run the script, I get what I expect

WARNING:root:warning1
WARNING:root:warning2
main.py:11: SettingWithCopyWarning:  ...

Now I write a pytest unit test for it:

from src.main import method


def test_main():
    method()

and activate the logging in my pytest.ini

[pytest]
log_cli = true
log_cli_level = DEBUG
========================= 1 passed, 1 warning in 0.27s =========================

Process finished with exit code 0

-------------------------------- live log call ---------------------------------
INFO     root:main.py:7 info
WARNING  root:main.py:8 warning1
WARNING  root:main.py:9 warning2
PASSED                                                                   [100%]
  1. The SettingsWithCopyWarning is counted while my logging warnings are not. Why is that? How do I control that? Via a configuration in the pytest.ini?
  2. Even worse: The SettingsWithCopyWarning is not printed. I want to see it and perhaps even test on it? How can I see warnings that are generated by dependent packages? Via a configuration in the pytest.ini?

Thank you!



Solution 1:[1]

All log warnings logged using the pytest live logs feature are done with the standard logging facility.

Warnings done with the warnings facility are captured separately in pytest by default and logged in the warnings summary after the live log messages.

To log warnings done through warnings.warn function immediately they are emitted, you need to inform pytest not to capture them.

In your pytest.ini, add

[pytest]
log_cli = true
log_level = DEBUG
log_cli_level = DEBUG
addopts=--disable-warnings

Then in your tests/conftest.py, write a hook to capture warnings in the tests using the standard logging facility.

import logging

def pytest_runtest_call(item):
    logging.captureWarnings(True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1