Skip to content

Commit 877c621

Browse files
authored
Merge pull request #7699 from bluetech/optimize-makeitem
python: small optimization in PyCollector.collect()
2 parents 21aa6c4 + daca174 commit 877c621

File tree

2 files changed

+8
-24
lines changed

2 files changed

+8
-24
lines changed

src/_pytest/python.py

+8-15
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,7 @@ def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
421421
dicts.append(basecls.__dict__)
422422
seen = set() # type: Set[str]
423423
values = [] # type: List[Union[nodes.Item, nodes.Collector]]
424+
ihook = self.ihook
424425
for dic in dicts:
425426
# Note: seems like the dict can change during iteration -
426427
# be careful not to remove the list() without consideration.
@@ -430,12 +431,15 @@ def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
430431
if name in seen:
431432
continue
432433
seen.add(name)
433-
res = self._makeitem(name, obj)
434+
res = ihook.pytest_pycollect_makeitem(
435+
collector=self, name=name, obj=obj
436+
)
434437
if res is None:
435438
continue
436-
if not isinstance(res, list):
437-
res = [res]
438-
values.extend(res)
439+
elif isinstance(res, list):
440+
values.extend(res)
441+
else:
442+
values.append(res)
439443

440444
def sort_key(item):
441445
fspath, lineno, _ = item.reportinfo()
@@ -444,17 +448,6 @@ def sort_key(item):
444448
values.sort(key=sort_key)
445449
return values
446450

447-
def _makeitem(
448-
self, name: str, obj: object
449-
) -> Union[
450-
None, nodes.Item, nodes.Collector, List[Union[nodes.Item, nodes.Collector]]
451-
]:
452-
# assert self.ihook.fspath == self.fspath, self
453-
item = self.ihook.pytest_pycollect_makeitem(
454-
collector=self, name=name, obj=obj
455-
) # type: Union[None, nodes.Item, nodes.Collector, List[Union[nodes.Item, nodes.Collector]]]
456-
return item
457-
458451
def _genfunctions(self, name: str, funcobj) -> Iterator["Function"]:
459452
modulecol = self.getparent(Module)
460453
assert modulecol is not None

testing/python/collect.py

-9
Original file line numberDiff line numberDiff line change
@@ -843,15 +843,6 @@ def pytest_pycollect_makeitem(collector, name, obj):
843843
result = testdir.runpytest("--collect-only")
844844
result.stdout.fnmatch_lines(["*MyFunction*some*"])
845845

846-
def test_makeitem_non_underscore(self, testdir, monkeypatch):
847-
modcol = testdir.getmodulecol("def _hello(): pass")
848-
values = []
849-
monkeypatch.setattr(
850-
pytest.Module, "_makeitem", lambda self, name, obj: values.append(name)
851-
)
852-
values = modcol.collect()
853-
assert "_hello" not in values
854-
855846
def test_issue2369_collect_module_fileext(self, testdir):
856847
"""Ensure we can collect files with weird file extensions as Python
857848
modules (#2369)"""

0 commit comments

Comments
 (0)