Skip to content

Commit c629f6b

Browse files
author
Daniel Hahler
committed
Fix reload() with modules handled via python_files
If a module exists in `sys.modules` already, `load_module` has to return it. Fixes https://bitbucket.org/pytest-dev/pytest/issue/435 --HG-- branch : fix-reload
1 parent 41e6b04 commit c629f6b

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

_pytest/assertion/rewrite.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,12 @@ def find_module(self, name, path=None):
146146
return self
147147

148148
def load_module(self, name):
149+
# If there is an existing module object named 'fullname' in
150+
# sys.modules, the loader must use that existing module. (Otherwise,
151+
# the reload() builtin will not work correctly.)
152+
if name in sys.modules:
153+
return sys.modules[name]
154+
149155
co, pyc = self.modules.pop(name)
150156
# I wish I could just call imp.load_compiled here, but __file__ has to
151157
# be set properly. In Python 3.2+, this all would be handled correctly

testing/test_assertrewrite.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,3 +641,27 @@ def test_read_pyc(self, tmpdir):
641641
pyc.write(contents[:strip_bytes], mode='wb')
642642

643643
assert _read_pyc(source, str(pyc)) is None # no error
644+
645+
def test_reload_is_same(self, testdir):
646+
# A file that will be picked up during collecting.
647+
testdir.tmpdir.join("file.py").ensure()
648+
testdir.tmpdir.join("pytest.ini").write(py.std.textwrap.dedent("""
649+
[pytest]
650+
python_files = *.py
651+
"""))
652+
653+
testdir.makepyfile(test_fun="""
654+
import sys
655+
try:
656+
from imp import reload
657+
except ImportError:
658+
pass
659+
660+
def test_loader():
661+
import file
662+
assert sys.modules["file"] is reload(file)
663+
""")
664+
result = testdir.runpytest('-s')
665+
result.stdout.fnmatch_lines([
666+
"* 1 passed*",
667+
])

0 commit comments

Comments
 (0)