简体   繁体   English

使用 pytest_generate_tests() 时如何在 pytest.param 中设置动态标记参数

[英]How to set dynamic marks parameter in pytest.param when using pytest_generate_tests()

I have a pytest setup where all of my tests are parameterized through data stored in a YAML file.我有一个 pytest 设置,其中我的所有测试都通过存储在 YAML 文件中的数据进行参数化。 Included in that YAML file are custom markers for various test instances.该 YAML 文件中包含各种测试实例的自定义标记。 I stripped out most of the code for simplicity.为简单起见,我去掉了大部分代码。 The problem is the variable marker below needs to be of type _pytest.mark.structures.MarkDecorator问题是下面的变量标记需要是 _pytest.mark.structures.MarkDecorator 类型

I can't seem to change the object type from string.我似乎无法从字符串更改对象类型。 I'm thinking there must be a simpler/different way for what I'm trying to do but I'm just not seeing it...我在想我正在尝试做的事情必须有一种更简单/不同的方式,但我只是没有看到......

def pytest_generate_tests(metafunc):

    ######################################################################
    # A bunch of code removed for simplicity but cm is defined in yaml file
    ######################################################################
    cm = "custom_marker"
    marker = f"pytest.mark.{cm}"
    final_str = pytest.param((1,2), marks=marker)

This doesn't directly answer your question, but I wrote a library called parametrize_from_file for the exact purpose parametrizing tests (in pytest) from YAML/TOML/JSON/NT files.这并不能直接回答您的问题,但我编写了一个名为parametrize_from_file的库,用于从 YAML/TOML/JSON/NT 文件进行参数化测试(在 pytest 中)的确切目的。 It supports custom marks, and might be a lot easier than writing your own parametrization code.它支持自定义标记,并且可能比编写自己的参数化代码容易得多。

Posting answer based on Kale's response.根据 Kale 的回复发布答案。 Thank you Kale I needed to change this:谢谢羽衣甘蓝我需要改变这个:

cm = "custom_marker"
    marker = f"pytest.mark.{cm}"
    final_str = pytest.param((1,2), marks=marker)

to this:对此:

cm = "custom_marker"
    marker = getattr(pytest.mark, cm)
    final_str = pytest.param((1,2), marks=marker)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM