Skip to content

Fix 'Package has no len()' error during collection #4010

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog/3749.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix the following error during collection of tests inside packages::

TypeError: object of type 'Package' has no len()
7 changes: 4 additions & 3 deletions src/_pytest/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,13 +504,14 @@ def _collect(self, arg):
pkginit = parent.join("__init__.py")
if pkginit.isfile():
if pkginit in self._node_cache:
root = self._node_cache[pkginit]
root = self._node_cache[pkginit][0]
else:
col = root._collectfile(pkginit)
if col:
if isinstance(col[0], Package):
root = col[0]
self._node_cache[root.fspath] = root
# always store a list in the cache, matchnodes expects it
self._node_cache[root.fspath] = [root]

# If it's a directory argument, recurse and look for any Subpackages.
# Let the Package collector deal with subnodes, don't collect here.
Expand All @@ -530,8 +531,8 @@ def _collect(self, arg):
if (type(x), x.fspath) in self._node_cache:
yield self._node_cache[(type(x), x.fspath)]
else:
yield x
self._node_cache[(type(x), x.fspath)] = x
yield x
else:
assert argpath.check(file=1)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def test():
pass
7 changes: 7 additions & 0 deletions testing/python/collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1591,6 +1591,13 @@ def test_package_collection_infinite_recursion(testdir):
result.stdout.fnmatch_lines("*1 passed*")


def test_package_collection_init_given_as_argument(testdir):
"""Regression test for #3749"""
p = testdir.copy_example("collect/package_init_given_as_arg")
result = testdir.runpytest(p / "pkg" / "__init__.py")
result.stdout.fnmatch_lines("*1 passed*")


def test_package_with_modules(testdir):
"""
.
Expand Down