|
3 | 3 | import sys |
4 | 4 | import textwrap |
5 | 5 |
|
| 6 | +import six |
| 7 | + |
6 | 8 | import pytest |
7 | 9 | from _pytest.monkeypatch import MonkeyPatch |
8 | 10 |
|
@@ -163,7 +165,8 @@ def test_delitem(): |
163 | 165 |
|
164 | 166 | def test_setenv(): |
165 | 167 | monkeypatch = MonkeyPatch() |
166 | | - monkeypatch.setenv("XYZ123", 2) |
| 168 | + with pytest.warns(pytest.PytestWarning): |
| 169 | + monkeypatch.setenv("XYZ123", 2) |
167 | 170 | import os |
168 | 171 |
|
169 | 172 | assert os.environ["XYZ123"] == "2" |
@@ -192,13 +195,49 @@ def test_delenv(): |
192 | 195 | del os.environ[name] |
193 | 196 |
|
194 | 197 |
|
| 198 | +class TestEnvironWarnings(object): |
| 199 | + """ |
| 200 | + os.environ keys and values should be native strings, otherwise it will cause problems with other modules (notably |
| 201 | + subprocess). On Python 2 os.environ accepts anything without complaining, while Python 3 does the right thing |
| 202 | + and raises an error. |
| 203 | + """ |
| 204 | + |
| 205 | + VAR_NAME = u"PYTEST_INTERNAL_MY_VAR" |
| 206 | + |
| 207 | + @pytest.mark.skipif(six.PY3, reason="Python 2 only test") |
| 208 | + def test_setenv_unicode_key(self, monkeypatch): |
| 209 | + with pytest.warns( |
| 210 | + pytest.PytestWarning, |
| 211 | + match="Environment variable name {!r} should be str".format(self.VAR_NAME), |
| 212 | + ): |
| 213 | + monkeypatch.setenv(self.VAR_NAME, "2") |
| 214 | + |
| 215 | + @pytest.mark.skipif(six.PY3, reason="Python 2 only test") |
| 216 | + def test_delenv_unicode_key(self, monkeypatch): |
| 217 | + with pytest.warns( |
| 218 | + pytest.PytestWarning, |
| 219 | + match="Environment variable name {!r} should be str".format(self.VAR_NAME), |
| 220 | + ): |
| 221 | + monkeypatch.delenv(self.VAR_NAME, raising=False) |
| 222 | + |
| 223 | + def test_setenv_non_str_warning(self, monkeypatch): |
| 224 | + value = 2 |
| 225 | + msg = ( |
| 226 | + "Environment variable value {!r} should be str, converted to str implicitly" |
| 227 | + ) |
| 228 | + with pytest.warns(pytest.PytestWarning, match=msg.format(value)): |
| 229 | + monkeypatch.setenv(str(self.VAR_NAME), value) |
| 230 | + |
| 231 | + |
195 | 232 | def test_setenv_prepend(): |
196 | 233 | import os |
197 | 234 |
|
198 | 235 | monkeypatch = MonkeyPatch() |
199 | | - monkeypatch.setenv("XYZ123", 2, prepend="-") |
| 236 | + with pytest.warns(pytest.PytestWarning): |
| 237 | + monkeypatch.setenv("XYZ123", 2, prepend="-") |
200 | 238 | assert os.environ["XYZ123"] == "2" |
201 | | - monkeypatch.setenv("XYZ123", 3, prepend="-") |
| 239 | + with pytest.warns(pytest.PytestWarning): |
| 240 | + monkeypatch.setenv("XYZ123", 3, prepend="-") |
202 | 241 | assert os.environ["XYZ123"] == "3-2" |
203 | 242 | monkeypatch.undo() |
204 | 243 | assert "XYZ123" not in os.environ |
|
0 commit comments