Skip to content

Commit 3495a6e

Browse files
committed
cacheprovider: speed up NFPlugin when --nf is not enabled
The code used an O(n^2) loop. Replace list with set to make it O(n). For backward compatibility the filesystem cache still remains a list. On this test: import pytest @pytest.mark.parametrize("x", range(5000)) def test_foo(x): pass run with `pytest --collect-only`: Before: 0m1.251s After: 0m0.921s
1 parent cbca9f1 commit 3495a6e

File tree

2 files changed

+6
-8
lines changed

2 files changed

+6
-8
lines changed

src/_pytest/cacheprovider.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -332,13 +332,13 @@ class NFPlugin:
332332
def __init__(self, config):
333333
self.config = config
334334
self.active = config.option.newfirst
335-
self.cached_nodeids = config.cache.get("cache/nodeids", [])
335+
self.cached_nodeids = set(config.cache.get("cache/nodeids", []))
336336

337337
def pytest_collection_modifyitems(
338338
self, session: Session, config: Config, items: List[nodes.Item]
339339
) -> None:
340-
new_items = OrderedDict() # type: OrderedDict[str, nodes.Item]
341340
if self.active:
341+
new_items = OrderedDict() # type: OrderedDict[str, nodes.Item]
342342
other_items = OrderedDict() # type: OrderedDict[str, nodes.Item]
343343
for item in items:
344344
if item.nodeid not in self.cached_nodeids:
@@ -349,11 +349,9 @@ def pytest_collection_modifyitems(
349349
items[:] = self._get_increasing_order(
350350
new_items.values()
351351
) + self._get_increasing_order(other_items.values())
352+
self.cached_nodeids.update(new_items)
352353
else:
353-
for item in items:
354-
if item.nodeid not in self.cached_nodeids:
355-
new_items[item.nodeid] = item
356-
self.cached_nodeids.extend(new_items)
354+
self.cached_nodeids.update(item.nodeid for item in items)
357355

358356
def _get_increasing_order(self, items):
359357
return sorted(items, key=lambda item: item.fspath.mtime(), reverse=True)
@@ -363,7 +361,7 @@ def pytest_sessionfinish(self, session):
363361
if config.getoption("cacheshow") or hasattr(config, "slaveinput"):
364362
return
365363

366-
config.cache.set("cache/nodeids", self.cached_nodeids)
364+
config.cache.set("cache/nodeids", sorted(self.cached_nodeids))
367365

368366

369367
def pytest_addoption(parser):

testing/test_cacheprovider.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def test_cache_failure_warns(self, testdir, monkeypatch):
7474
"*/cacheprovider.py:*",
7575
" */cacheprovider.py:*: PytestCacheWarning: could not create cache path "
7676
"{}/v/cache/nodeids".format(cache_dir),
77-
' config.cache.set("cache/nodeids", self.cached_nodeids)',
77+
' config.cache.set("cache/nodeids", sorted(self.cached_nodeids))',
7878
"*1 failed, 3 warnings in*",
7979
]
8080
)

0 commit comments

Comments
 (0)