【问题标题】:Pytest: Paramatrizing test data with mark.paramatrize vs fixture(params=[])Pytest:使用 mark.parametrize 和 fixture(params=[]) 参数化测试数据
【发布时间】:2020-09-20 21:38:00
【问题描述】:

我正在尝试自学 Pytest,并尝试了解使用 @pytest.fixture(params=[]) 和 @pytest.mark.parametrization() 参数化测试数据之间的区别。我已经设置了下面的代码来查看两者是如何工作的并且它们都返回相同的结果。但是,我不确定是否存在一种方法优于另一种方法的用例。使用其中一个有什么好处吗?

import pytest

@pytest.fixture(params=["first parameter", "second parameter", "third parameter"])
def param_fixture(request):
    return request.param

def parametrize_list():
    return ["first parameter", "second parameter", "third parameter"]

def test_using_fixture_params(param_fixture):
    """Tests parametrization with fixture(params=[])"""
    assert "parameter" in param_fixture

@pytest.mark.parametrize("param", parametrize_list())
def test_using_mark_parametrize(param):
    """Tests parametrization with mark.parametrize()"""
    assert "parameter" in param

以上代码有如下结果。

test_parametrization.py::test_using_fixture_params[first parameter] PASSED
test_parametrization.py::test_using_fixture_params[second parameter] PASSED
test_parametrization.py::test_using_fixture_params[third parameter] PASSED
test_parametrization.py::test_using_mark_parametrize[first parameter] PASSED
test_parametrization.py::test_using_mark_parametrize[second parameter] PASSED
test_parametrization.py::test_using_mark_parametrize[third parameter] PASSED

【问题讨论】:

    标签: python parameters pytest fixtures


    【解决方案1】:

    夹具通常用于将数据结构加载到测试中并传递给测试函数。 @pytest.mark.parametrize 是使用不同输入测试大量迭代的首选方法(如上所述)。

    在开始时这是一个方便的资源:@​​987654321@

    from data_module import Data
    
    class TestData:
        """
        Load and Test data
    """
        @pytest.fixture(autouse=True)
        def data(test):
            return Data()
    
    
        def test_fixture(data):
            result = do_test(data)
            assert result
    
        @pytest.mark.parametrize('options', ['option1', 'option2', 'option3'])
        def test_with_parameterisation(data, options)
            result_with_paramaterisation(data, options)
            assert result_with_paramaterisation
    
    ``
    

    【讨论】:

    • 这完美地回答了我的问题!因此,fixture 非常适合加载测试数据和依赖项,而 mark.parametrize 非常适合使用不同选项重复测试。该链接也很有帮助。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2018-02-24
    相关资源
    最近更新 更多