Skip to content

Commit eb79fa7

Browse files
authored
Merge pull request #2590 from nicoddemus/current-test-var
Introduce new PYTEST_CURRENT_TEST environment variable
2 parents 2c03000 + d7f182a commit eb79fa7

File tree

7 files changed

+163
-24
lines changed

7 files changed

+163
-24
lines changed

_pytest/runner.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from __future__ import absolute_import, division, print_function
33

44
import bdb
5+
import os
56
import sys
67
from time import time
78

@@ -91,9 +92,11 @@ def show_test_item(item):
9192
tw.write(' (fixtures used: {0})'.format(', '.join(used_fixtures)))
9293

9394
def pytest_runtest_setup(item):
95+
_update_current_test_var(item, 'setup')
9496
item.session._setupstate.prepare(item)
9597

9698
def pytest_runtest_call(item):
99+
_update_current_test_var(item, 'call')
97100
try:
98101
item.runtest()
99102
except Exception:
@@ -107,7 +110,23 @@ def pytest_runtest_call(item):
107110
raise
108111

109112
def pytest_runtest_teardown(item, nextitem):
113+
_update_current_test_var(item, 'teardown')
110114
item.session._setupstate.teardown_exact(item, nextitem)
115+
_update_current_test_var(item, None)
116+
117+
118+
def _update_current_test_var(item, when):
119+
"""
120+
Update PYTEST_CURRENT_TEST to reflect the current item and stage.
121+
122+
If ``when`` is None, delete PYTEST_CURRENT_TEST from the environment.
123+
"""
124+
var_name = 'PYTEST_CURRENT_TEST'
125+
if when:
126+
os.environ[var_name] = '{0} ({1})'.format(item.nodeid, when)
127+
else:
128+
os.environ.pop(var_name)
129+
111130

112131
def pytest_report_teststatus(report):
113132
if report.when in ("setup", "teardown"):

changelog/2583.feature

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Introduce the ``PYTEST_CURRENT_TEST`` environment variable that is set with the ``nodeid`` and stage (``setup``, ``call`` and
2+
``teardown``) of the test being currently executed. See the `documentation <https://docs.pytest.org/en/latest/example/simple.html#pytest-current-test-environment-variable>`_ for more info.

doc/en/customize.rst

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,15 +112,27 @@ progress output, you can write it into a configuration file:
112112
# content of pytest.ini
113113
# (or tox.ini or setup.cfg)
114114
[pytest]
115-
addopts = -rsxX -q
115+
addopts = -ra -q
116116
117-
Alternatively, you can set a PYTEST_ADDOPTS environment variable to add command
117+
Alternatively, you can set a ``PYTEST_ADDOPTS`` environment variable to add command
118118
line options while the environment is in use::
119119

120-
export PYTEST_ADDOPTS="-rsxX -q"
120+
export PYTEST_ADDOPTS="-v"
121121

122-
From now on, running ``pytest`` will add the specified options.
122+
Here's how the command-line is built in the presence of ``addopts`` or the environment variable::
123123

124+
<pytest.ini:addopts> $PYTEST_ADDOTPS <extra command-line arguments>
125+
126+
So if the user executes in the command-line::
127+
128+
pytest -m slow
129+
130+
The actual command line executed is::
131+
132+
pytest -ra -q -v -m slow
133+
134+
Note that as usual for other command-line applications, in case of conflicting options the last one wins, so the example
135+
above will show verbose output because ``-v`` overwrites ``-q``.
124136

125137

126138
Builtin configuration file options

doc/en/example/simple.rst

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,47 @@ and run it::
761761
You'll see that the fixture finalizers could use the precise reporting
762762
information.
763763

764+
``PYTEST_CURRENT_TEST`` environment variable
765+
--------------------------------------------
766+
767+
.. versionadded:: 3.2
768+
769+
Sometimes a test session might get stuck and there might be no easy way to figure out
770+
which test got stuck, for example if pytest was run in quiet mode (``-q``) or you don't have access to the console
771+
output. This is particularly a problem if the problem helps only sporadically, the famous "flaky" kind of tests.
772+
773+
``pytest`` sets a ``PYTEST_CURRENT_TEST`` environment variable when running tests, which can be inspected
774+
by process monitoring utilities or libraries like `psutil <https://pypi.python.org/pypi/psutil>`_ to discover which
775+
test got stuck if necessary:
776+
777+
.. code-block:: python
778+
779+
import psutil
780+
781+
for pid in psutil.pids():
782+
environ = psutil.Process(pid).environ()
783+
if 'PYTEST_CURRENT_TEST' in environ:
784+
print(f'pytest process {pid} running: {environ["PYTEST_CURRENT_TEST"]}')
785+
786+
During the test session pytest will set ``PYTEST_CURRENT_TEST`` to the current test
787+
:ref:`nodeid <nodeids>` and the current stage, which can be ``setup``, ``call``
788+
and ``teardown``.
789+
790+
For example, when running a single test function named ``test_foo`` from ``foo_module.py``,
791+
``PYTEST_CURRENT_TEST`` will be set to:
792+
793+
#. ``foo_module.py::test_foo (setup)``
794+
#. ``foo_module.py::test_foo (call)``
795+
#. ``foo_module.py::test_foo (teardown)``
796+
797+
In that order.
798+
799+
.. note::
800+
801+
The contents of ``PYTEST_CURRENT_TEST`` is meant to be human readable and the actual format
802+
can be changed between releases (even bug fixes) so it shouldn't be relied on for scripting
803+
or automation.
804+
764805
Freezing pytest
765806
---------------
766807

doc/en/usage.rst

Lines changed: 58 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -52,23 +52,64 @@ To stop the testing process after the first (N) failures::
5252
Specifying tests / selecting tests
5353
---------------------------------------------------
5454

55-
Several test run options::
56-
57-
pytest test_mod.py # run tests in module
58-
pytest somepath # run all tests below somepath
59-
pytest -k stringexpr # only run tests with names that match the
60-
# "string expression", e.g. "MyClass and not method"
61-
# will select TestMyClass.test_something
62-
# but not TestMyClass.test_method_simple
63-
pytest test_mod.py::test_func # only run tests that match the "node ID",
64-
# e.g. "test_mod.py::test_func" will select
65-
# only test_func in test_mod.py
66-
pytest test_mod.py::TestClass::test_method # run a single method in
67-
# a single class
68-
69-
Import 'pkg' and use its filesystem location to find and run tests::
70-
71-
pytest --pyargs pkg # run all tests found below directory of pkg
55+
Pytest supports several ways to run and select tests from the command-line.
56+
57+
**Run tests in a module**
58+
59+
::
60+
61+
pytest test_mod.py
62+
63+
**Run tests in a directory**
64+
65+
::
66+
67+
pytest testing/
68+
69+
**Run tests by keyword expressions**
70+
71+
::
72+
73+
pytest -k "MyClass and not method"
74+
75+
This will run tests which contain names that match the given *string expression*, which can
76+
include Python operators that use filenames, class names and function names as variables.
77+
The example above will run ``TestMyClass.test_something`` but not ``TestMyClass.test_method_simple``.
78+
79+
.. _nodeids:
80+
81+
**Run tests by node ids**
82+
83+
Each collected test is assigned a unique ``nodeid`` which consist of the module filename followed
84+
by specifiers like class names, function names and parameters from parametrization, separated by ``::`` characters.
85+
86+
To run a specific test within a module::
87+
88+
pytest test_mod.py::test_func
89+
90+
91+
Another example specifying a test method in the command line::
92+
93+
pytest test_mod.py::TestClass::test_method
94+
95+
**Run tests by marker expressions**
96+
97+
::
98+
99+
pytest -m slow
100+
101+
Will run all tests which are decorated with the ``@pytest.mark.slow`` decorator.
102+
103+
For more information see :ref:`marks <mark>`.
104+
105+
**Run tests from packages**
106+
107+
::
108+
109+
pytest --pyargs pkg.testing
110+
111+
This will import ``pkg.testing`` and use its filesystem location to find and run tests from.
112+
72113

73114
Modifying Python traceback printing
74115
----------------------------------------------

testing/test_runner.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,8 @@ def test_store_except_info_on_eror():
681681
"""
682682
# Simulate item that raises a specific exception
683683
class ItemThatRaises(object):
684+
nodeid = 'item_that_raises'
685+
684686
def runtest(self):
685687
raise IndexError('TEST')
686688
try:
@@ -693,6 +695,31 @@ def runtest(self):
693695
assert sys.last_traceback
694696

695697

698+
def test_current_test_env_var(testdir, monkeypatch):
699+
pytest_current_test_vars = []
700+
monkeypatch.setattr(sys, 'pytest_current_test_vars', pytest_current_test_vars, raising=False)
701+
testdir.makepyfile('''
702+
import pytest
703+
import sys
704+
import os
705+
706+
@pytest.fixture
707+
def fix():
708+
sys.pytest_current_test_vars.append(('setup', os.environ['PYTEST_CURRENT_TEST']))
709+
yield
710+
sys.pytest_current_test_vars.append(('teardown', os.environ['PYTEST_CURRENT_TEST']))
711+
712+
def test(fix):
713+
sys.pytest_current_test_vars.append(('call', os.environ['PYTEST_CURRENT_TEST']))
714+
''')
715+
result = testdir.runpytest_inprocess()
716+
assert result.ret == 0
717+
test_id = 'test_current_test_env_var.py::test'
718+
assert pytest_current_test_vars == [
719+
('setup', test_id + ' (setup)'), ('call', test_id + ' (call)'), ('teardown', test_id + ' (teardown)')]
720+
assert 'PYTEST_CURRENT_TEST' not in os.environ
721+
722+
696723
class TestReportContents(object):
697724
"""
698725
Test user-level API of ``TestReport`` objects.

tox.ini

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,6 @@ commands=
4949
skipsdist=True
5050
usedevelop=True
5151
basepython = python2.7
52-
# needed to keep check-manifest working
53-
setenv =
54-
SETUPTOOLS_SCM_PRETEND_VERSION=2.0.1
5552
deps =
5653
flake8
5754
# pygments required by rst-lint

0 commit comments

Comments
 (0)