Define a pytest fixture providing multiple arguments to test function

后端 未结 2 1445
猫巷女王i
猫巷女王i 2020-12-19 17:38

With pytest, I can define a fixture like so:

@pytest.fixture
def foo():
    return \"blah\"

And use it in a test like so:

d         


        
相关标签:
2条回答
  • 2020-12-19 17:59

    You can now do this using pytest-cases:

    from pytest_cases import fixture
    
    @fixture(unpack_into="foo,bar")
    def foobar():
        return "blah", "whatever"
    
    def test_stuff(foo, bar):
        assert foo == "blah" and bar == "whatever"
    

    See the documentation for more details (I'm the author by the way)

    0 讨论(0)
  • 2020-12-19 18:20

    note: this solution not working if your fixture depends on another fixtures with parameters

    Don't really know if there are any default solution in pytest package, but you can make a custom one:

    import pytest
    from _pytest.mark import MarkInfo
    
    
    def pytest_generate_tests(metafunc):
        test_func = metafunc.function
        if 'use_multifixture' in [name for name, ob in vars(test_func).items() if isinstance(ob, MarkInfo)]:
            result, func = test_func.use_multifixture.args
            params_names = result.split(',')
            params_values = list(func())
            metafunc.parametrize(params_names, [params_values])
    
    
    def foobar():
        return "blah", "whatever"
    
    
    @pytest.mark.use_multifixture("foo,bar", foobar)
    def test_stuff(foo, bar):
        assert foo == "blah" and bar == "whatever"
    
    
    def test_stuff2():
        assert 'blah' == "blah"
    

    So we defined pytest_generate_tests metafunction. This function

    1. checks if multifixture mark is on the test
    2. if the mark is on - it takes variables names "foo,bar" and fucntion foobar that will be executed on generation

      @pytest.mark.multifixture("foo,bar", foobar)

    0 讨论(0)
提交回复
热议问题