pythonunit-testingpytestfixtures

Pytest: associate parameterized fixtures with expected results


Say I have the following test:

@pytest.fixture(params=['a'])
def ascii(request):
    return ord(request.param)

def test_ascii(ascii):
    assert ascii == 97

This works great. Now say I'd like to add 'b' as a parameter. Ideally I could just decorate the test with something like @pytest.mark.parametrize('ascii_val', [97, 98]), add ascii_val as an agrument to the test and assert ascii == ascii_val. Pytest, however, would also assert 'a' against 98 and 'b' against 97.

Is there any way for me to associate 'a' with 97 and 'b' with 98? I'm asking because I'm going to have a lot of tests like test_ascii where I'll be checking that some input consistently outputs the same output given different analysis techniques.


Solution

  • At least for the simple example you're giving, why use a parametrized fixture instead of parametrizing your test?

    Something like this should work:

    @pytest.mark.parametrize('char, expected', [('a', 97), ('b', 98)])
    def test_ascii(char, expected):
        assert ord(char) == expected
    

    If you really wanted to use a fixture, you could always return a (char, expected) tuple from it and work with that.