Plugin which implements the --nf (run new-first) option.
| 424 | |
| 425 | |
| 426 | class NFPlugin: |
| 427 | """Plugin which implements the --nf (run new-first) option.""" |
| 428 | |
| 429 | def __init__(self, config: Config) -> None: |
| 430 | self.config = config |
| 431 | self.active = config.option.newfirst |
| 432 | assert config.cache is not None |
| 433 | self.cached_nodeids = set(config.cache.get("cache/nodeids", [])) |
| 434 | |
| 435 | @hookimpl(wrapper=True, tryfirst=True) |
| 436 | def pytest_collection_modifyitems(self, items: list[nodes.Item]) -> Generator[None]: |
| 437 | res = yield |
| 438 | |
| 439 | if self.active: |
| 440 | new_items: dict[str, nodes.Item] = {} |
| 441 | other_items: dict[str, nodes.Item] = {} |
| 442 | for item in items: |
| 443 | if item.nodeid not in self.cached_nodeids: |
| 444 | new_items[item.nodeid] = item |
| 445 | else: |
| 446 | other_items[item.nodeid] = item |
| 447 | |
| 448 | items[:] = self._get_increasing_order( |
| 449 | new_items.values() |
| 450 | ) + self._get_increasing_order(other_items.values()) |
| 451 | self.cached_nodeids.update(new_items) |
| 452 | else: |
| 453 | self.cached_nodeids.update(item.nodeid for item in items) |
| 454 | |
| 455 | return res |
| 456 | |
| 457 | def _get_increasing_order(self, items: Iterable[nodes.Item]) -> list[nodes.Item]: |
| 458 | return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True) |
| 459 | |
| 460 | def pytest_sessionfinish(self) -> None: |
| 461 | config = self.config |
| 462 | if config.getoption("cacheshow") or hasattr(config, "workerinput"): |
| 463 | return |
| 464 | |
| 465 | if config.getoption("collectonly"): |
| 466 | return |
| 467 | |
| 468 | assert config.cache is not None |
| 469 | config.cache.set("cache/nodeids", sorted(self.cached_nodeids)) |
| 470 | |
| 471 | |
| 472 | def pytest_addoption(parser: Parser) -> None: |