Skip to content
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### New features
- added `--order-include-dependencies` to include collected prerequisites when
selecting tests with `-k` and `--order-dependencies`

### Changes
- added official support for Python 3.15

Expand Down
36 changes: 36 additions & 0 deletions docs/source/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,42 @@ adds ordering to the existing functionality if needed.
detected at collection time and therefore are not included in ordering.
The same is true for the `dynamic compilation of marked parameters`_.

.. _order-include-dependencies:

``--order-include-dependencies``
--------------------------------
Normally, ``-k`` selects tests independently of their dependencies. For example,
``pytest -k test_a --order-dependencies`` selects only ``test_a`` in the example
above, so ``pytest-dependency`` skips it because ``test_b`` did not run.

Use ``--order-include-dependencies`` together with ``--order-dependencies`` to
also select its collected prerequisites::

$ pytest tests -vv -k test_a --order-dependencies --order-include-dependencies
...
test_dep.py::test_b PASSED
test_dep.py::test_a PASSED

Dependencies declared by ``dependency`` markers are followed transitively.
Their names and module, class, package or session scopes are interpreted as in
``pytest-dependency``. Parameterized dependencies can be named explicitly or
referred to by their full parameterized test name. The prerequisite does not
need to match ``-k`` itself, even if the expression explicitly excludes its name.

This option only expands keyword selection. It does not collect tests outside
the paths given on the command line, override ``-m`` or ``--deselect``, or undo
another plugin's deselection. Dependencies added at runtime cannot be included.
Unknown dependencies and dependency cycles retain the usual ordering warnings
and ``pytest-dependency`` skip behavior. An ``order(before=...)`` or
``order(after=...)`` marker alone specifies order, not a prerequisite, and does
not select additional tests.

On pytest 6, the deprecated ``-k '-expr'`` syntax still works. The deprecated
``-k 'expr:'`` syntax, which selects a suffix of the collection order, cannot be
combined with this option: adding an earlier prerequisite could change that
suffix and select unrelated tests. Use a standard ``-k`` expression instead.
Without this option, pytest 6's existing keyword behavior is unchanged.

.. _order-marker-prefix:

``--order-marker-prefix``
Expand Down
18 changes: 18 additions & 0 deletions src/pytest_order/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from _pytest.mark import Mark
from pytest import Function

from .selection import DependencySelectionPlugin
from .sorter import Sorter


Expand Down Expand Up @@ -46,6 +47,14 @@ def pytest_configure(config: Config) -> None:
hook_function
)
config.pluginmanager.register(OrderingPlugin(), "orderingplugin")
if config.getoption("order_include_dependencies"):
if not config.getoption("order_dependencies"):
raise pytest.UsageError(
"--order-include-dependencies requires --order-dependencies"
)
config.pluginmanager.register(
DependencySelectionPlugin(), "order_dependency_selection"
)


def pytest_addoption(parser: Parser) -> None:
Expand Down Expand Up @@ -108,6 +117,15 @@ def pytest_addoption(parser: Parser) -> None:
"If set, dependencies added by pytest-dependency will be ordered if needed."
),
)
group.addoption(
"--order-include-dependencies",
action="store_true",
dest="order_include_dependencies",
help=(
"Include collected prerequisites of tests selected by -k. "
"Requires --order-dependencies."
),
)
group.addoption(
"--order-marker-prefix",
action="store",
Expand Down
143 changes: 143 additions & 0 deletions src/pytest_order/selection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
from collections import defaultdict
from collections.abc import Generator
from warnings import warn

import pytest
from _pytest.config import Config
from _pytest.mark import KeywordMatcher, MarkMatcher
from _pytest.mark import expression as expression_module
from _pytest.mark.expression import Expression
from _pytest.nodes import Item, Node

PARSE_ERRORS = (SyntaxError, getattr(expression_module, "ParseError", SyntaxError))


class DependencySelectionPlugin:
"""Expand keyword selection without bypassing pytest's deselection hooks."""

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_collection_modifyitems(
self, config: Config, items: list[Item]
) -> Generator[None]:
keyword = config.option.keyword
dependencies: set[Item] = set()
token = f"pytest_order_dependency_{id(self)}"
if keyword.lstrip():
normalized_keyword, legacy_negative = normalize_keyword(keyword)
expression = parse_expression(normalized_keyword, "-k")
selected = {
item
for item in items
if expression.evaluate(KeywordMatcher.from_item(item))
}
if config.option.markexpr:
mark_expression = parse_expression(config.option.markexpr, "-m")
selected = {
item
for item in selected
if mark_expression.evaluate(marker_matcher(item))
}
dependencies = dependency_closure(config, items, selected) - selected
if dependencies:
if legacy_negative:
# The rewritten expression no longer reaches pytest 6's legacy-syntax check.
warn(
"The `-k '-expr'` syntax to -k is deprecated.\n"
"Use `-k 'not expr'` instead.",
pytest.PytestDeprecationWarning,
stacklevel=2,
)
# Avoid colliding with a real keyword, even one supplied by another plugin.
while any(KeywordMatcher.from_item(item)(token) for item in items):
token += "_"
for item in dependencies:
item.extra_keyword_matches.add(token)
config.option.keyword = f"({normalized_keyword}) or {token}"
try:
yield
finally:
config.option.keyword = keyword
for item in dependencies:
item.extra_keyword_matches.discard(token)


def normalize_keyword(keyword: str) -> tuple[str, bool]:
"""Preserve pytest 6's negative syntax; suffix selection cannot be safely expanded."""
keyword = keyword.lstrip()
legacy = pytest.__version__.split(".", 1)[0] == "6"
if legacy and keyword.endswith(":"):
raise pytest.UsageError(
"--order-include-dependencies does not support pytest 6's deprecated "
"'-k expr:' suffix selection; use a standard -k expression"
)
negative = legacy and keyword.startswith("-")
return (f"not {keyword[1:]}" if negative else keyword), negative


def parse_expression(expression: str, option: str) -> Expression:
"""Use the expression parser shared by the supported pytest versions."""
try:
return Expression.compile(expression)
except PARSE_ERRORS as error:
raise pytest.UsageError(
f"Wrong expression passed to '{option}': {expression}: {error}"
) from None


def marker_matcher(item: Item):
"""Support marker arguments where pytest supports them."""
from_markers = getattr(MarkMatcher, "from_markers", None)
if from_markers is not None:
return from_markers(item.iter_markers())
from_item = getattr(MarkMatcher, "from_item", None)
assert from_item is not None
return from_item(item)


def dependency_closure(
config: Config, items: list[Item], selected: set[Item]
) -> set[Item]:
"""Find statically declared prerequisites using pytest-dependency's names and scopes."""
scopes: dict[str, type[Node]] = {
"session": pytest.Session,
"package": pytest.Package,
"module": pytest.Module,
"class": pytest.Class,
}
aliases: dict[tuple[Node | None, str], list[Item]] = defaultdict(list)
try:
automark = config.getini("automark_dependency")
except ValueError:
automark = False
for item in items:
mark = item.get_closest_marker("dependency")
if mark is None and not automark:
continue
explicit_name = mark.kwargs.get("name") if mark else None
for scope, cls in scopes.items():
node = item.getparent(cls)
if node is None:
continue
name = explicit_name or item.nodeid
if not explicit_name:
if scope == "module":
name = item.nodeid.split("::", 1)[1]
elif scope == "class":
name = item.nodeid.split("::", 2)[2]
aliases[node, name].append(item)

included = set(selected)
pending = list(selected)
while pending:
item = pending.pop()
mark = item.get_closest_marker("dependency")
if mark is None:
continue
scope_class = scopes[mark.kwargs.get("scope", "module")]
node = item.getparent(scope_class)
for name in mark.kwargs.get("depends", []):
for dependency in aliases.get((node, name), []):
if dependency not in included:
included.add(dependency)
pending.append(dependency)
return included
Loading