Skip to content

Commit a75b3fa

Browse files
committed
monkeypatch.syspath_prepend: call fixup_namespace_packages
Without the patch the test fails as follows: # Prepending should call fixup_namespace_packages. monkeypatch.syspath_prepend("world") > import ns_pkg.world E ModuleNotFoundError: No module named 'ns_pkg.world'
1 parent 15d6088 commit a75b3fa

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/_pytest/monkeypatch.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,10 +262,15 @@ def delenv(self, name, raising=True):
262262

263263
def syspath_prepend(self, path):
264264
""" Prepend ``path`` to ``sys.path`` list of import locations. """
265+
from pkg_resources import fixup_namespace_packages
266+
265267
if self._savesyspath is None:
266268
self._savesyspath = sys.path[:]
267269
sys.path.insert(0, str(path))
268270

271+
# https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171
272+
fixup_namespace_packages(str(path))
273+
269274
def chdir(self, path):
270275
""" Change the current working directory to the specified path.
271276
Path can be a string or a py.path.local object.

testing/test_monkeypatch.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,3 +437,25 @@ def test_context():
437437
m.setattr(functools, "partial", 3)
438438
assert not inspect.isclass(functools.partial)
439439
assert inspect.isclass(functools.partial)
440+
441+
442+
def test_syspath_prepend_with_namespace_packages(testdir, monkeypatch):
443+
for dirname in "hello", "world":
444+
d = testdir.mkdir(dirname)
445+
ns = d.mkdir("ns_pkg")
446+
ns.join("__init__.py").write(
447+
"__import__('pkg_resources').declare_namespace(__name__)"
448+
)
449+
lib = ns.mkdir(dirname)
450+
lib.join("__init__.py").write("def check(): return %r" % dirname)
451+
452+
monkeypatch.syspath_prepend("hello")
453+
import ns_pkg.hello
454+
455+
assert ns_pkg.hello.check() == "hello"
456+
457+
# Prepending should call fixup_namespace_packages.
458+
monkeypatch.syspath_prepend("world")
459+
import ns_pkg.world
460+
461+
assert ns_pkg.world.check() == "world"

0 commit comments

Comments
 (0)