Skip to content

Added an environment variable which helps to check if a code is running from within a pytest run, Fixes #9502 #12190

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 18, 2024
Merged
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ Daw-Ran Liou
Debi Mishra
Denis Kirisov
Denivy Braiam Rück
Dheeraj C K
Dhiren Serai
Diego Russo
Dmitry Dygalo
Expand Down
1 change: 1 addition & 0 deletions changelog/9502.improvement.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added an environment variable which helps to check if a code is running from within a pytest run
4 changes: 4 additions & 0 deletions src/_pytest/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
from .exceptions import PrintHelp as PrintHelp
from .exceptions import UsageError as UsageError
from .findpaths import determine_setup
from _pytest import __version__
import _pytest._code
from _pytest._code import ExceptionInfo
from _pytest._code import filter_traceback
Expand Down Expand Up @@ -152,6 +153,7 @@ def main(
:returns: An exit code.
"""
try:
os.environ["PYTEST_VERSION"] = __version__
try:
config = _prepareconfig(args, plugins)
except ConftestImportFailure as e:
Expand Down Expand Up @@ -186,6 +188,8 @@ def main(
for msg in e.args:
tw.line(f"ERROR: {msg}\n", red=True)
return ExitCode.USAGE_ERROR
finally:
os.environ.pop("PYTEST_VERSION", None)


def console_main() -> int:
Expand Down
17 changes: 17 additions & 0 deletions testing/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -1094,3 +1094,20 @@ def func() -> None:
with pytest.raises(TypeError) as excinfo:
OutcomeException(func) # type: ignore
assert str(excinfo.value) == expected


def test_pytest_version(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
pytester.makepyfile(
"""
import pytest
import os


def test():
assert os.environ.get("PYTEST_VERSION") == pytest.__version__
"""
)
result = pytester.runpytest_inprocess()
# assert result.ret == 0
assert result.ret == ExitCode.OK
assert "PYTEST_VERSION" not in os.environ