Skip to content

pytest.mark.filterwarnings doesn't work if warning already shown on python2.7 #3954

@duncanmmacleod

Description

@duncanmmacleod

It looks like pytest.mark.filterwarnings doesn't work properly if a warning has already been shown only on python2.7. See the following example:

import pytest
import warnings


def func():
    warnings.warn('test warning')


def test_1():
    func()


@pytest.mark.filterwarnings('always:test warning')
def test_2():
    with pytest.warns(UserWarning):
        func()

This gives the following result:

============================= test session starts ==============================
platform darwin -- Python 2.7.15, pytest-3.8.0, py-1.5.3, pluggy-0.7.1
rootdir: /Users/duncan/tmp, inifile:
collected 2 items

test-pytest.py .F                                                        [100%]

=================================== FAILURES ===================================
____________________________________ test_2 ____________________________________

    @pytest.mark.filterwarnings('always:test warning')
    def test_2():
        with pytest.warns(UserWarning):
>           func()
E           Failed: DID NOT WARN. No warnings of type (<type 'exceptions.UserWarning'>,) was emitted. The list of emitted warnings is: [].

test-pytest.py:16: Failed
=============================== warnings summary ===============================
/Users/duncan/tmp/test-pytest.py:6: UserWarning: test warning
  warnings.warn('test warning')

-- Docs: https://docs.pytest.org/en/latest/warnings.html
================ 1 failed, 1 passed, 1 warnings in 0.05 seconds ================

On python 3.x this works fine. If I reverse the order of the tests, it works fine. Is there a workaround for this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: 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