【问题标题】:how to use class variable on @pytest.mark.parametrize如何在@pytest.mark.parametrize 上使用类变量
【发布时间】:2018-05-22 20:58:50
【问题描述】:

我有一个名为test_case_params 的测试用例。需要将一些参数(从class Mock_data 获取模拟数据)传递给夹具并检查测试用例中的返回值。我还有其他选择在@pytest.mark.parametrize 和测试用例中使用Mock_data.get_mock_data 吗?目的是确保所有测试用例都使用相同的模拟数据。到目前为止,我所做的是创建一个 mock_data 变量,以便我可以在所有测试用例中使用它,因为整个 Testsuit 都是从 TestFixure 继承的。但我不确定如何编写pytest.mark.parametrize 部分。

import pytest
class Mock_data:
    @staticmethod
    def get_mock_data():
        return [1,2,3,4,5]

class TestFixure(object):
    @pytest.fixture(scope='function')
    def func_fixture(self, request):
        print('#do something in fixure{}'.format(request.param))
        return request.param

        def fin():
            print('#do something on finalizer')
        request.addfinalizer(fin)

    @classmethod
    def setup_class(cls):
        super(TestFixure, cls).setup_class()
        cls.mock_data = Mock_data.get_mock_data()

    @classmethod
    def teardown_class(cls):
        super(TestMember, cls).teardown_class()


class TestSuite(TestFixure):
    @pytest.mark.parametrize('func_fixture', [Mock_data.get_mock_data()[1], Mock_data.get_mock_data()[2], Mock_data.get_mock_data()[3]], indirect=['func_fixture'])
    def test_case_params(self, func_fixture):
        print(func_fixture)
        assert func_fixture in self.mock_data

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    在我看来,您的整个班级 TestFixure 看起来很糟糕。像super(TestFixure, cls).setup_class() 这样的行表明你打算从某事物中派生它...?

    我自己第一次很难弄清楚这样的事情,所以我重写了你的代码示例。我相信它可以满足您的需求,我希望它可以帮助您理解夹具和参数化的概念是如何工作的:

    import pytest
    
    class __mock_data_class__:
    
        def __init__(self):
            self.vector = [2, 3, 4, 5, 6]
    
        def do_something(self, parameter):
            return self.vector[parameter] - 2
    
        def fin(self):
            self.vector.clear() # demo action at the end ...
    
    @pytest.fixture(scope = 'function')
    def mock_data(request):
    
        mock_data_object = __mock_data_class__()
    
        def __finalizer__():
            mock_data_object.fin()
    
        request.addfinalizer(__finalizer__)
    
        return mock_data_object
    
    class TestSuite():
    
        @pytest.mark.parametrize('some_parameter', range(0, 5))
        def test_case_params(self, mock_data, some_parameter):
            print(some_parameter)
            assert some_parameter == mock_data.do_something(some_parameter)
    

    您的模拟数据由名为__mock_data_class__ 的类生成(或获取或...)。感谢scope = 'function',我将在每个测试用例中初始化一次mock_data(您的示例中只有一个test_case_params)。该对象会将您的数据保存在名为vector 的“字段”中。 mock_data 对象一直存在,直到为传递给它的每个参数调用了测试用例(range(0, 5) 等于 [0, 1, 2, 3, 4] 的生成器)。在其生命结束时,它会在类方法fin 中使用self.vector.clear()“销毁”数据(仅作为示例)。您的测试用例可以通过调用do_something 直接在mock_data 对象中执行某些操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 2017-04-10
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多