pytest icon indicating copy to clipboard operation
pytest copied to clipboard

Generalize `PYTEST_CURRENT_TEST` for multiple threads

Open Liam-DeVoe opened this issue 1 month ago • 9 comments

Part of https://github.com/pytest-dev/pytest/issues/13768. See also discussion in https://github.com/pytest-dev/pytest/pull/13837.

The PYTEST_CURRENT_TEST envvar stores the node id and phase of the current test. When multiple threads are running, we'll need to generalize this, so that each thread shows the current test being run.

Based on @RonnyPfannschmidt's comments in https://github.com/pytest-dev/pytest/pull/13837, one option is that pytest makes it a requirement that whoever spawns the threads* sets each thread name to a scheme recognized by pytest, like pytest-thread-{n}. Pytest would check threading.current_thread().name in runtestprotocol, and then if it matches pytest-thread-{n}, use n to set the PYTEST_CURRENT_TEST_THREAD_{n} envvar.

* this responsibility might fall to pytest, or to the user, depending on TBD details about how a user invokes pytest multithreading. Eg, it might be invoked with a high-level + pytest-managed --threads arg, or a user-managed override of pytest_runtestloop and spawning a thread pool, or an alternative mechanism.

Main thread considerations

@RonnyPfannschmidt mentions that PYTEST_CURRENT_TEST should be reserved for the main thread. If we check this with threading.main_thread(), then we'll mistake cases where pytest is run inside of a thread:

import threading
import pytest

thread = threading.Thread(target=pytest.main)
thread.start()

We could:

  1. Accept this as a possibility and don't worry about it
  2. Treat the threading.current_thread() when pytest.main is called as "this pytest session's main thread", even if it's not truly the main thread
  3. Forgo PYTEST_CURRENT_TEST entirely under threading, and just use PYTEST_CURRENT_TEST_THREAD_{n}

Liam-DeVoe avatar Oct 24 '25 15:10 Liam-DeVoe