【问题标题】:How to pass complex class members to pytest parametrize decorator如何将复杂的类成员传递给pytest参数化装饰器
【发布时间】:2018-07-24 20:10:22
【问题描述】:

我需要将类成员作为参数传递给pytest.mark.parametrize。 以下代码不起作用(我使用了简单的成员字符串,但在我的情况下,它们是复杂且构造的):

import pytest
class TestSmth(object):
     def setup_class(cls):
         cls.a = "a"
         cls.b = "b"
         cls.c = "c"

     @pytest.mark.parametrize("test_input,expected", [
     (self.a, "a"),
     (self.b, "b"),
     (self.c, "c")
     ])
     def test_members(test_input, expected):
         assert test_input == expected

有可能达到这样的结果吗? 还是类似的?

【问题讨论】:

    标签: python class pytest


    【解决方案1】:

    此代码不起作用,因为 Python 装饰器 don't work that way。它与测试参数中的实际数据无关。如果你是编写装饰器的人,你可以solve it by manually passing the instance,但这取决于装饰器本身是否做正确的事情。

    就目前而言,pytest 装饰器只是存储要验证的测试数据 - 因此您需要提供在运行脱糖代码时可访问的数据,如下所示:

    o = TestSmth()
    o.setup_class()
    
    @pytest.mark.parametrize("test_input,expected", [
    (o.a, "a"),
    (o.b, "b"),
    (o.c, "c")
    ])
    def test_members(test_input, expected):
        assert test_input == expected
    

    我认为传递给这些函数的数据类型没有任何固有限制。如果您仍然觉得限制太大,pytest 有一个 substantial support 用于自定义参数化方案。如果没有您实际使用的详细信息(而不是模拟示例),很难说出最适合问题的方法。

    【讨论】:

    • 我也必须为 test_inputexpected 传递一些复杂的参数,就像你的例子一样。一种选择是将其写在参数中以进行参数化..或定义一个包含 test_data 的类。正如OP指出的那样,在一个类中定义测试数据是最佳实践吗?
    【解决方案2】:

    在 pytest 文档中找到解决方案 -> “通过每个类配置参数化测试方法¶”

    #!/usr/bin/env python
    
    import pytest
    
    
    def pytest_generate_tests(metafunc):
        # called once per each test function
        funcarglist = metafunc.cls.params[metafunc.function.__name__]
        argnames = sorted(funcarglist[0])
        metafunc.parametrize(argnames, [[funcargs[name] for name in argnames]
                for funcargs in funcarglist])
    
    class Complex(object):
        def __init__(self):
            self.a = "a"
    
    class TestBase(object):
        A = Complex()
        params = {
            'test_a' : [dict (test_input=A)]
        }
    
        def test_a(self, test_input):
            assert test_input.a == "a"
    

    它很丑,但它达到了它的目的。

    【讨论】:

      猜你喜欢
      • 2018-08-24
      • 2021-01-19
      • 2020-04-13
      • 2014-11-17
      • 2013-03-10
      • 1970-01-01
      • 2016-02-14
      • 2021-11-21
      • 2014-10-01
      相关资源
      最近更新 更多