【问题标题】:Access Pytest marks from parametrize in the test在测试中通过参数化访问 Pytest 标记
【发布时间】:2022-06-27 23:23:06
【问题描述】:

我有大量使用@pytest.mark.parametrize 和大量自定义标记的集合测试。我想不出一种从测试中访问这些标记的方法。 documentation 解释了如何从 conftest.py 文件中执行此操作,而不是从测试函数中。

我真的不需要对标记进行操作,我只需要注册它们。

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)    

我如何从测试中获取分数?谢谢!

【问题讨论】:

    标签: python pytest pytest-markers


    【解决方案1】:

    事实证明,如果您使用固定装置,这将非常简单:

    @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)
    

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多