Skip to content

WarningsRecorder.pop() improperly matches warning #10701

@groutr

Description

@groutr

When trying to pop a specific warning from a WarningsRecorder instance, the wrong warning is returned. I believe the issue is that pop uses issubclass

if issubclass(w.category, cls):

I believe the correct comparison should be:

if w.category is cls:

Here is a minimum working example that triggers the buggy behavior:

import pytest
import warnings

class RWarning(Warning):
    pass
    
class SWarning(RWarning):
    pass

def raise_warnings():
    warnings.warn("Warning 1", SWarning)
    warnings.warn("Warning 2", RWarning)
    
def test_pop():
    with pytest.warns((RWarning, SWarning)) as record:
        raise_warnings()
        
    assert len(record) == 2
    _warn = record.pop(RWarning)
    assert _warn.category is RWarning  # This fails because _warn.category is SWarning

The test output is

========================================================================================= FAILURES ==========================================================================================
_________________________________________________________________________________________ test_pop __________________________________________________________________________________________

    def test_pop():
        with pytest.warns((RWarning, SWarning)) as record:
            raise_warnings()

        assert len(record) == 2
        _warn = record.pop(RWarning)
>       assert _warn.category is RWarning
E       AssertionError: assert <class 'pytest_bug.SWarning'> is RWarning
E        +  where <class 'pytest_bug.SWarning'> = <warnings.WarningMessage object at 0x7fea08a72010>.category

pytest_bug.py:24: AssertionError

pytest 7.2.1 on archlinux.
virtual environment is a clean conda environment with only python and pytest (and their dependencies installed from conda-forge).

If this is indeed a bug, I'm happy to open a PR with my proposed solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueeasy issue that is friendly to new contributorplugin: warningsrelated to the warnings builtin plugintype: enhancementnew feature or API change, should be merged into features branch

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions