Plugin which implements the --nf (run new-first) option.
| 388 | |
| 389 | |
| 390 | class NFPlugin: |
| 391 | """Plugin which implements the --nf (run new-first) option.""" |
| 392 | |
| 393 | def __init__(self, config: Config) -> None: |
| 394 | self.config = config |
| 395 | self.active = config.option.newfirst |
| 396 | assert config.cache is not None |
| 397 | self.cached_nodeids = set(config.cache.get("cache/nodeids", [])) |
| 398 | |
| 399 | @hookimpl(hookwrapper=True, tryfirst=True) |
| 400 | def pytest_collection_modifyitems( |
| 401 | self, items: List[nodes.Item] |
| 402 | ) -> Generator[None, None, None]: |
| 403 | yield |
| 404 | |
| 405 | if self.active: |
| 406 | new_items: Dict[str, nodes.Item] = {} |
| 407 | other_items: Dict[str, nodes.Item] = {} |
| 408 | for item in items: |
| 409 | if item.nodeid not in self.cached_nodeids: |
| 410 | new_items[item.nodeid] = item |
| 411 | else: |
| 412 | other_items[item.nodeid] = item |
| 413 | |
| 414 | items[:] = self._get_increasing_order( |
| 415 | new_items.values() |
| 416 | ) + self._get_increasing_order(other_items.values()) |
| 417 | self.cached_nodeids.update(new_items) |
| 418 | else: |
| 419 | self.cached_nodeids.update(item.nodeid for item in items) |
| 420 | |
| 421 | def _get_increasing_order(self, items: Iterable[nodes.Item]) -> List[nodes.Item]: |
| 422 | return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True) # type: ignore[no-any-return] |
| 423 | |
| 424 | def pytest_sessionfinish(self) -> None: |
| 425 | config = self.config |
| 426 | if config.getoption("cacheshow") or hasattr(config, "workerinput"): |
| 427 | return |
| 428 | |
| 429 | if config.getoption("collectonly"): |
| 430 | return |
| 431 | |
| 432 | assert config.cache is not None |
| 433 | config.cache.set("cache/nodeids", sorted(self.cached_nodeids)) |
| 434 | |
| 435 | |
| 436 | def pytest_addoption(parser: Parser) -> None: |