Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest generate tests in derived classes

I need to generate some similar tests according with different data. I tried

import pytest


class BaseClass(object):
    data = [1]

    @pytest.mark.parametrize("param1", data)
    def test_something(self, param1):
        assert param1


class Test1(BaseClass):
    data = [2, 3]


class Test2(BaseClass):
    data = [0]

but result is

collected 2 items

test_of_pytest.py::Test1::test_something[1] PASSED                       [ 50%]
test_of_pytest.py::Test2::test_something[1] PASSED                       [100%]

instead of expected something like:

collected 3 items

test_of_pytest.py::Test1::test_something[2] PASSED                       [ 33%]
test_of_pytest.py::Test1::test_something[3] PASSED                       [ 66%]
test_of_pytest.py::Test2::test_something[0] FAIL                       [100%]

So @pytest.mark.parametrize runs only once while reading BaseClass. How to deal with parametrize(or some other generator) to behave as i expected?

like image 853
Opostol Avatar asked Nov 24 '25 19:11

Opostol


1 Answers

Try with pytest_generate_tests

def pytest_generate_tests(metafunc):
    # called once per each test function
    funcarglist = metafunc.cls.params[metafunc.function.__name__]
    argnames = sorted(funcarglist[0])
    metafunc.parametrize(
    argnames, [[funcargs[name] for name in argnames] for funcargs in funcarglist]
)


class BaseClass(object):
    params = None

    def test_something(self, param):
        assert param


class Test1(BaseClass):
    params = {
        "test_something": [dict(param=2), dict(param=3)]
    }


class Test2(BaseClass):
    params = {
        "test_something": [dict(param=0)]
    }
like image 183
Rubén Pozo Avatar answered Nov 26 '25 12:11

Rubén Pozo