Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share parametrized arguments across multiple test functions?

Tags:

pytest

I have many test functions in the same file that share a common set of parametrized arguments, as shown in the code snippets below. When the number of test functions increases (>100), repeating those parameters for each test function doesn't seem to be efficient and can be error prone. Is there any way in pytest to define one set of common parametrized arguments and share it across all tests? Fixture is used to inject common data dependency. I wonder if there is any similar tool to inject common arguments.

import pytest

@pytest.mark.parametrize('common_arg1', [0, 1])
@pytest.mark.parametrize('common_arg2', [2, 3])
@pytest.mark.parametrize('a', [0, 1])
def test_1(common_arg1, common_arg2, a):
    pass
    
@pytest.mark.parametrize('common_arg1', [0, 1])  # repetition
@pytest.mark.parametrize('common_arg2', [2, 3])  # repetition
@pytest.mark.parametrize('b', [0, 1])
def test_2(common_arg1, common_arg2, b):
    pass
    
...

@pytest.mark.parametrize('common_arg1', [0, 1])  # more repetition!
@pytest.mark.parametrize('common_arg2', [2, 3])  # more repetition!
@pytest.mark.parametrize('x', [0, 1])
def test_100(common_arg1, common_arg2, x):
    pass  
like image 231
cuhor Avatar asked Aug 08 '18 06:08

cuhor


1 Answers

You could move all test cases into one helper class and put common decorators on top of that class. Decorators that are specific to some tests (methods) can be applied directly on them. Check the example below.

import pytest


@pytest.mark.parametrize('common_arg1', [0, 1])
@pytest.mark.parametrize('common_arg2', [2, 3])
class TestParametrized:

    @pytest.mark.parametrize('a', [0, 1])
    def test_1(self, common_arg1, common_arg2, a):
        pass

    @pytest.mark.parametrize('b', [0, 1])
    def test_2(self, common_arg1, common_arg2, b):
        pass

    @pytest.mark.parametrize('x', [0, 1])
    def test_100(self, common_arg1, common_arg2, x):
        pass
like image 157
Kamil Avatar answered Jan 02 '23 02:01

Kamil