From 5404246e64aa61f0f61e4825fe1cd3de963d4262 Mon Sep 17 00:00:00 2001 From: William Jamir Silva Date: Wed, 31 Oct 2018 14:22:42 -0300 Subject: [PATCH] Improve the warning message for the implicitly str conversion Signed-off-by: William Jamir Silva --- src/_pytest/monkeypatch.py | 8 +++++--- testing/test_monkeypatch.py | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) 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..b81a656ea 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) @@ -337,7 +339,7 @@ def test_importerror(testdir): ) testdir.tmpdir.join("test_importerror.py").write( textwrap.dedent( - """\ + r"""\ def test_importerror(monkeypatch): monkeypatch.setattr('package.a.x', 2) """