Skip to content

Commit ed83efa

Browse files
committed
testing/test_monkeypatch: fix some patches leaking into pytest code
The tests patch `os.path.abspath` which can break some pytest internal code since the patching is not undone immediately.
1 parent 0c98f19 commit ed83efa

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

testing/test_monkeypatch.py

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -50,21 +50,24 @@ class A:
5050

5151
class TestSetattrWithImportPath:
5252
def test_string_expression(self, monkeypatch: MonkeyPatch) -> None:
53-
monkeypatch.setattr("os.path.abspath", lambda x: "hello2")
54-
assert os.path.abspath("123") == "hello2"
53+
with monkeypatch.context() as mp:
54+
mp.setattr("os.path.abspath", lambda x: "hello2")
55+
assert os.path.abspath("123") == "hello2"
5556

5657
def test_string_expression_class(self, monkeypatch: MonkeyPatch) -> None:
57-
monkeypatch.setattr("_pytest.config.Config", 42)
58-
import _pytest
58+
with monkeypatch.context() as mp:
59+
mp.setattr("_pytest.config.Config", 42)
60+
import _pytest
5961

60-
assert _pytest.config.Config == 42 # type: ignore
62+
assert _pytest.config.Config == 42 # type: ignore
6163

6264
def test_unicode_string(self, monkeypatch: MonkeyPatch) -> None:
63-
monkeypatch.setattr("_pytest.config.Config", 42)
64-
import _pytest
65+
with monkeypatch.context() as mp:
66+
mp.setattr("_pytest.config.Config", 42)
67+
import _pytest
6568

66-
assert _pytest.config.Config == 42 # type: ignore
67-
monkeypatch.delattr("_pytest.config.Config")
69+
assert _pytest.config.Config == 42 # type: ignore
70+
mp.delattr("_pytest.config.Config")
6871

6972
def test_wrong_target(self, monkeypatch: MonkeyPatch) -> None:
7073
with pytest.raises(TypeError):
@@ -80,14 +83,16 @@ def test_unknown_attr(self, monkeypatch: MonkeyPatch) -> None:
8083

8184
def test_unknown_attr_non_raising(self, monkeypatch: MonkeyPatch) -> None:
8285
# https://github.com/pytest-dev/pytest/issues/746
83-
monkeypatch.setattr("os.path.qweqwe", 42, raising=False)
84-
assert os.path.qweqwe == 42 # type: ignore
86+
with monkeypatch.context() as mp:
87+
mp.setattr("os.path.qweqwe", 42, raising=False)
88+
assert os.path.qweqwe == 42 # type: ignore
8589

8690
def test_delattr(self, monkeypatch: MonkeyPatch) -> None:
87-
monkeypatch.delattr("os.path.abspath")
88-
assert not hasattr(os.path, "abspath")
89-
monkeypatch.undo()
90-
assert os.path.abspath
91+
with monkeypatch.context() as mp:
92+
mp.delattr("os.path.abspath")
93+
assert not hasattr(os.path, "abspath")
94+
mp.undo()
95+
assert os.path.abspath
9196

9297

9398
def test_delattr() -> None:

0 commit comments

Comments
 (0)