Skip to content

pytest thread safety should be better documented #12356

@ngoldbaum

Description

@ngoldbaum
  • 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

pytest.warns is a subclass of the standard library warnings.catch_warnings context manager, which is not thread safe (this is noted in the docs).

If it's not possible for pytest to have a thread-safe version, it would be nice if the docs for pytest.warns could note that it's implemented using warnings.catch_warnings and is not thread safe for the same reason.

pytest 8.2.1 on MacOS Sonoma.

Fails about 10-20% of the time on my machine:

import warnings
import threading


def raise_warning():
    warnings.warn(RuntimeWarning())


def test_pytest_warns():
    b = threading.Barrier(2)

    def catch_warning():
        b.wait()
        with pytest.warns(RuntimeWarning):
            raise_warning()

    task1 = threading.Thread(target=catch_warning)
    task2 = threading.Thread(target=catch_warning)

    task1.start()
    task2.start()
    task1.join()
    task2.join()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions