Access Pytest marks from parametrize in the test

339 Views Asked by At

I have a very large of set tests that use @pytest.mark.parametrize with a fairly large set of custom marks. I can't figure out a way to access those marks from within the test. The documentation explains how to do this from a conftest.py file, but not from the test function.

I don't really need to operate on the marks, all I need is to register them.

pytest.ini:

[pytest]
markers =
    MarkFoo
    MarkBar

test.py:

import pytest

from typing import Any
from dataclasses import dataclass

@dataclass(frozen=True)
class FooTest:
    name: str                           # Unique test name
    param: int                          # A parameter
    marks: Any = ()                     # Marks for this test


test_list = [
    FooTest(name='Foo', param=1, marks=(pytest.mark.MarkFoo)),
    FooTest(name='Bar', param=2, marks=(pytest.mark.MarkBar)),
]

@pytest.mark.parametrize( "name, param, ",
    [ pytest.param(t.name, t.param, marks=t.marks) for t in test_list ]
)

def test_run_foo_bar(name, param, record_property):
    # How to read the marks here?
    # record_property("marks:", ???)
    print(name, param)    

How can I access the marks from the test? Thanks!

1

There are 1 best solutions below

0
On

Turns out it's super simple if you use a fixture:

@pytest.fixture()
def test_marks(request):
    marks = ["MarkFoo", "MarkBar"]
    return [m for m in request.node.own_markers if m.name in marks]

def test_run_foo_bar(name, param, record_property, test_marks):
    record_property("Test Marks:", test_marks)
    print(name, param, test_marks)