diff --git a/changelog/4279.trivial.rst b/changelog/4279.trivial.rst new file mode 100644 index 000000000..9f4c4c473 --- /dev/null +++ b/changelog/4279.trivial.rst @@ -0,0 +1 @@ +Improve message and stack level of warnings issued by ``monkeypatch.setenv`` when the value of the environment variable is not a ``str``. diff --git a/src/_pytest/monkeypatch.py b/src/_pytest/monkeypatch.py index 2efdb73ae..d536b7746 100644 --- a/src/_pytest/monkeypatch.py +++ b/src/_pytest/monkeypatch.py @@ -230,10 +230,12 @@ class MonkeyPatch(object): if not isinstance(value, str): warnings.warn( pytest.PytestWarning( - "Environment variable value {!r} should be str, converted to str implicitly".format( - value + "Value of environment variable {name} type should be str, but got " + "{value!r} (type: {type}); converted to str implicitly".format( + name=name, value=value, type=type(value).__name__ ) - ) + ), + stacklevel=2, ) value = str(value) if prepend and name in os.environ: diff --git a/testing/test_monkeypatch.py b/testing/test_monkeypatch.py index d250d24e7..ebc233fbf 100644 --- a/testing/test_monkeypatch.py +++ b/testing/test_monkeypatch.py @@ -3,6 +3,7 @@ from __future__ import division from __future__ import print_function import os +import re import sys import textwrap @@ -226,9 +227,10 @@ class TestEnvironWarnings(object): def test_setenv_non_str_warning(self, monkeypatch): value = 2 msg = ( - "Environment variable value {!r} should be str, converted to str implicitly" + "Value of environment variable PYTEST_INTERNAL_MY_VAR type should be str, " + "but got 2 (type: int); converted to str implicitly" ) - with pytest.warns(pytest.PytestWarning, match=msg.format(value)): + with pytest.warns(pytest.PytestWarning, match=re.escape(msg)): monkeypatch.setenv(str(self.VAR_NAME), value)