Skip to content

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

@Redoubts

Description

@Redoubts

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.

Metadata

Metadata

Assignees

Labels

topic: marksrelated to marks, either the general marks or builtintype: proposalproposal for a new feature, often to gather opinions or design the API around the new feature

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions