Skip to content

Commit 0a09833

Browse files
committed
Simplify reload_module fixture.
1 parent d8d5a56 commit 0a09833

File tree

1 file changed

+15
-23
lines changed

1 file changed

+15
-23
lines changed

tests/utils.py

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -55,35 +55,27 @@ def wrapper(**kwargs):
5555
return decorator
5656

5757

58-
class Reloader:
59-
def __init__(self, monkeypatch):
60-
self.modules = []
61-
self.monkeypatch = monkeypatch
58+
@pytest.fixture
59+
def reload_module(monkeypatch, request):
60+
modules = []
6261

63-
def __call__(self, module):
64-
self.modules.append((module, module.__dict__.copy()))
62+
def reload_module(module):
63+
modules.append((module, module.__dict__.copy()))
6564
return importlib.reload(module)
6665

67-
def undo(self):
68-
self.monkeypatch.undo()
69-
70-
# previously, this would reload the module again,
71-
# creating *new* versions of the old classes,
72-
# which breaks some modules (e.g. pathlib).
73-
# restoring the original attributes seems to work better.
74-
while self.modules:
75-
module, module_dict = self.modules.pop()
66+
def undo():
67+
monkeypatch.undo()
68+
# we don't reload the module again,
69+
# because it creates *new* versions of the old classes,
70+
# which breaks some modules (e.g. pathlib)
71+
while modules:
72+
module, module_dict = modules.pop()
7673
module.__dict__.clear()
7774
module.__dict__.update(module_dict)
7875

79-
80-
@pytest.fixture
81-
def reload_module(monkeypatch):
82-
reloader = Reloader(monkeypatch)
83-
try:
84-
yield reloader
85-
finally:
86-
reloader.undo()
76+
request.addfinalizer(undo)
77+
with monkeypatch.context() as monkeypatch:
78+
yield reload_module
8779

8880

8981
@pytest.fixture

0 commit comments

Comments
 (0)