【问题标题】:py.test parameterized fixturespy.test 参数化夹具
【发布时间】:2019-02-02 10:56:45
【问题描述】:

我目前正在使用py.test 处理一些单元测试用例和测试装置

我有一些代码可以做到这一点:

# my py.test file
import pytest

@pytest.fixture
def fixture_1():
    f = open("file_one.txt", 'rb')
    f_str = f.read()
    yield f_str
    f.close()

def test_function_1(fixture_1):
    assert fixture_1.startswith("some_test_data") # example test

这一切都很好,工作正常。

现在假设我编写了另一个测试函数,该函数使用存储在另一个文件中的输入(假设file_two.txt,我的函数是这样的:

# in same py file as above
def test_function_2(fixture_1):
     #some test with data from file_two.txt
     assert something_for_fun

在上面的test_function_2 中,我想fixture_1 执行与以前相同的操作,但在file_two.txt 而不是file_one.txt

编辑:我也玩过parametrizing fixtures,但它调用我的 test_function_* 的次数与夹具参数的数量一样多,这不起作用,因为 test_functions 是特定于输入的来自一个文件。

我了解了request 夹具,但不确定如何使用它来检查测试函数的上下文。

如果有人知道,请告诉我。同时,我会尽快发布!

编辑 2:我也知道 inspectintrospect 但我正在寻找一种更清洁的方法来做到这一点,最好是使用一些 pytest 魔法~

谢谢!

【问题讨论】:

    标签: python-3.x pytest


    【解决方案1】:

    您可以从测试中参数化夹具并通过request.param读取传递的参数:

    import pytest
    
    @pytest.fixture
    def fixture_1(request):
        filename = request.param
        with open(filename) as f:
            f_str = f.read()
        yield f_str
    
    
    @pytest.mark.parametrize('fixture_1', ['file_one.txt'], indirect=True)
    def test_function_1(fixture_1):
        assert fixture_1.startswith("some_test_data") # example test
    
    
    @pytest.mark.parametrize('fixture_1', ['file_two.txt'], indirect=True)
    def test_function_2(fixture_1):
        assert something_for_fun
    

    测试运行应该产生:

    test_module.py::test_function_1[file_one.txt] PASSED
    test_module.py::test_function_2[file_two.txt] PASSED
    

    您还可以为文件名设置默认夹具值并按需参数化:

    @pytest.fixture
    def fixture_1(request):
        filename = getattr(request, 'param', 'file_one.txt')
        with open(filename) as f:
            f_str = f.read()
        yield f_str
    
    
    def test_function_1(fixture_1):
        assert fixture_1.startswith("some_test_data") # example test
    
    
    @pytest.mark.parametrize('fixture_1', ['file_two.txt'], indirect=True)
    def test_function_2(fixture_1):
        assert fixture_1.startswith('bar')
    

    现在test_function_1 保持未参数化:

    test_module.py::test_function_1 PASSED
    test_module.py::test_function_2[file_two.txt] PASSED
    

    【讨论】:

    • 很高兴能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多