dimanche 25 septembre 2016

Dynamically parametrizing class-level fixtures with pytest

It is possible to parametrize test functions from command-line arguments. It is possible to have a fixture scoped to a class. I want to combine those two things, so that each class receives parametrized arguments that are given to the fixture within the class.

(essentially, per command-line argument I need to run one very expensive operation and then do a variety of cheap, speedy tests against the results of that operation, and I'd prefer not to have to rerun the expensive operation for each cheap test, so I'd like a way to save it)

In other words, I'm looking for an equivalent to pytest_generate_tests(metafunc), that would work for dynamically parametrizing a fixture, not a test function.

One thing I have already tried unusccessfully is reading the request parameters and setting those via the pytest_generate_tests hook.

conftest.py:
    def pytest_generate_tests(metafunc):
        metafunc.parametrize("result", [
                (1,0),(1,2)
            ])

test_thing.py:
    class TestThingy:
        @pytest.fixture(scope="class")
        def result(self, request):
            a,b=request.param
            return a+b

    #@pytest.mark.parametrize("result", [(0, 1), (1, 2)])
    def test_one(self, result):
        assert result!=2

Running this test causes the following error to be raised (note that the test ran fine when I tried it without the conftest hook and with the commented line uncommented):

@pytest.fixture(scope="class") def result(self, request): a,b=request.param AttributeError: 'SubRequest' object has no attribute 'param'

I'd also be interested in any other alternate way to achive the same result.

Aucun commentaire:

Enregistrer un commentaire