Skip to content

Commit 48f52b1

Browse files
authored
Merge pull request #4279 from williamjamir/improve-warning-msg
Improve the warning message for the implicitly str conversion
2 parents a5b3ad2 + 948fd7b commit 48f52b1

File tree

3 files changed

+10
-5
lines changed

3 files changed

+10
-5
lines changed

changelog/4279.trivial.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve message and stack level of warnings issued by ``monkeypatch.setenv`` when the value of the environment variable is not a ``str``.

src/_pytest/monkeypatch.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,10 +230,12 @@ def setenv(self, name, value, prepend=None):
230230
if not isinstance(value, str):
231231
warnings.warn(
232232
pytest.PytestWarning(
233-
"Environment variable value {!r} should be str, converted to str implicitly".format(
234-
value
233+
"Value of environment variable {name} type should be str, but got "
234+
"{value!r} (type: {type}); converted to str implicitly".format(
235+
name=name, value=value, type=type(value).__name__
235236
)
236-
)
237+
),
238+
stacklevel=2,
237239
)
238240
value = str(value)
239241
if prepend and name in os.environ:

testing/test_monkeypatch.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from __future__ import print_function
44

55
import os
6+
import re
67
import sys
78
import textwrap
89

@@ -226,9 +227,10 @@ def test_delenv_unicode_key(self, monkeypatch):
226227
def test_setenv_non_str_warning(self, monkeypatch):
227228
value = 2
228229
msg = (
229-
"Environment variable value {!r} should be str, converted to str implicitly"
230+
"Value of environment variable PYTEST_INTERNAL_MY_VAR type should be str, "
231+
"but got 2 (type: int); converted to str implicitly"
230232
)
231-
with pytest.warns(pytest.PytestWarning, match=msg.format(value)):
233+
with pytest.warns(pytest.PytestWarning, match=re.escape(msg)):
232234
monkeypatch.setenv(str(self.VAR_NAME), value)
233235

234236

0 commit comments

Comments
 (0)