diff --git a/src/_pytest/main.py b/src/_pytest/main.py index 105891e4686..eae0bb25548 100644 --- a/src/_pytest/main.py +++ b/src/_pytest/main.py @@ -505,8 +505,9 @@ def _collect(self, arg): root = self._node_cache[pkginit] else: col = root._collectfile(pkginit) - if col and isinstance(col, Package): - root = col[0] + if col: + if isinstance(col[0], Package): + root = col[0] self._node_cache[root.fspath] = root # If it's a directory argument, recurse and look for any Subpackages. diff --git a/testing/test_collection.py b/testing/test_collection.py index 23d82cb141b..5b494ba31af 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -638,6 +638,10 @@ def test_global_file(self, testdir, tmpdir): assert col.config is config def test_pkgfile(self, testdir): + """Verify nesting when a module is within a package. + The parent chain should match: Module -> Package -> Session. + Session's parent should always be None. + """ tmpdir = testdir.tmpdir subdir = tmpdir.join("subdir") x = subdir.ensure("x.py") @@ -645,9 +649,12 @@ def test_pkgfile(self, testdir): with subdir.as_cwd(): config = testdir.parseconfigure(x) col = testdir.getnode(config, x) - assert isinstance(col, pytest.Module) assert col.name == "x.py" - assert col.parent.parent is None + assert isinstance(col, pytest.Module) + assert isinstance(col.parent, pytest.Package) + assert isinstance(col.parent.parent, pytest.Session) + # session is batman (has no parents) + assert col.parent.parent.parent is None for col in col.listchain(): assert col.config is config