pytest icon indicating copy to clipboard operation
pytest copied to clipboard

Public way to test if a matchexpr will match a marker string or Item

Open Redoubts opened this issue 2 months ago • 2 comments

I have a handful of tools in and outside of a pytest run that care about whether the matchexpr (i.e. what gets passed to pytest -m ...) will match a specific marker (i.e. the string representation of a mark, a la @pytest.mark.my_mark) or an Item decorated with such a marker.

Currently I've solved this problem with something like

def matchmark(markexpr: str, markers: str | Sequence[str] | pytest.Item) -> bool:
    from pytest import Item
    from _pytest.mark import Expression, MarkMatcher

    expression = Expression.compile(markexpr)

    if isinstance(markers, Item):
        matcher = MarkMatcher.from_item(markers)
    elif isinstance(markers, str):
        matcher = MarkMatcher([markers])
    else:
        matcher = MarkMatcher(set(markers))

    return expression.evaluate(matcher)

But this is reaching in to private stuff you can and will break at any time (I think this code breaks after pytest 8.2). It would be nice if there were a supported public method to answer this question.

Redoubts avatar Sep 27 '25 21:09 Redoubts