Home > Blockchain >  Pytest using a fixture to return value instead of function location
Pytest using a fixture to return value instead of function location

Time:03-24

I want to perform pytest for the tenth_standard method inside HighSchool class:

Class HighSchool():
    ...

    def tenth_standard(self):
        return f"I-am-studying-in-{self.school}-at-{self.country}"

I want to use @pytest.fixture and @pytest.mark.parametrize to perform the pytest and my code is as below:

@pytest.fixture(scope="function")
def expected(request):
    return f"I-am-studying-in-{school}-at-{country}"

@pytest.fixture(scope="function")
def school(request):
    return request.param

@pytest.fixture(scope="function")
def country(request):
    return request.param





@pytest.mark.parametrize("school", ["abcd", "efgh"], indirect=True)
@pytest.mark.parametrize("country", ["India", "Japan"], indirect=True)

def test_tenthstandard(school, country, expected):

    b = HighSchool(school=school, country=country)
    assert expected == b.tenth_standard()

When I run this, I get an AssertionError as below:

AssertionError: assert ('I-am-studying-in-<function school at 0x7f6b858a63a0>-at-<function country at '0x7f6b858a6280>) == 'I-am-studying-in-abcd-at-India'

I want to fix the expected fixture to return the values instead of function at XXX location. Could someone help me how to fix this?

CodePudding user response:

Your expected fixture is not taking the parameters from the other fixtures, but just the fixture function, which is of course not what you want. You can just "derive" the expected fixture from the other fixtures, so it will be automatically parametrized with the same parameters:

@pytest.fixture
def school(request):
    return request.param

@pytest.fixture
def country(request):
    return request.param

@pytest.fixture
def expected(school, country):
    return f"I-am-studying-in-{school}-at-{country}"

@pytest.mark.parametrize("school", ["abcd", "efgh"])
@pytest.mark.parametrize("country", ["India", "Japan"])
def test_tenthstandard(school, country, expected):
    b = HighSchool(school=school, country=country)
    assert expected == b.tenth_standard()

Note that it this case you can even skip the indirect=True part, as the expected fixture will already get the correct values.

As a side note: It is usually not a good idea to duplicate the application logic in the test, as is done here. This way bugs can easily propagate to the tests and not be found.
(though in this case it may only be due to a dumbed down example)

  • Related