Skip to content

Catching both warning and error, message of warning is ignored #11032

@MarcoGorelli

Description

@MarcoGorelli
  • a detailed description of the bug or problem you are having
  • output of pip list from the virtual environment you are using
  • pytest and operating system versions
  • minimal example if possible

Here's a reproducible example:
t.py:

import warnings

def foo():
    warnings.warn('my warning message', FutureWarning)
    raise ValueError('my error message')

test_t.py:

import pytest

from t import foo

def test_foo():
    with (
        pytest.raises(ValueError, match='my error message'),
        pytest.warns(FutureWarning, match='definitely not my warning message'),
    ):
        foo()

Then:

(.venv) marcogorelli@DESKTOP-U8OKFP3:~/tmp$ pytest test_t.py
================================================= test session starts ==================================================
platform linux -- Python 3.10.6, pytest-7.3.1, pluggy-1.0.0
rootdir: /home/marcogorelli/tmp
plugins: anyio-3.6.2
collected 1 item

test_t.py .                                                                                                      [100%]

================================================== 1 passed in 0.00s ===================================================

I'd have expected it to error with something like

E       Failed: DID NOT WARN. No warnings of type (<class 'FutureWarning'>,) matching the regex were emitted.
E        Regex: definitely not my warning message
E        Emitted warnings: [FutureWarning('my warning message')]

other info:

(.venv) marcogorelli@DESKTOP-U8OKFP3:~/tmp$ pip list | grep pytest
pytest                   7.3.1
(.venv) marcogorelli@DESKTOP-U8OKFP3:~/tmp$ uname -a
Linux DESKTOP-U8OKFP3 5.10.102.1-microsoft-standard-WSL2 #1 SMP Wed Mar 2 00:30:59 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
(.venv) marcogorelli@DESKTOP-U8OKFP3:~/tmp$ python --version
Python 3.10.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    plugin: warningsrelated to the warnings builtin plugintype: bugproblem that needs to be addressed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions