7

I've got a pytest test that's parametrized with a @pytest.mark.parametrize decorator using a custom function load_test_cases() that loads the test cases from a yaml file.

class SelectTestCase:
    def __init__(self, test_case):
        self.select = test_case['select']
        self.expect = test_case['expect']

    def __str__(self):        # also tried __repr__()
        # Attempt to print the 'select' attribute in "pytest -v" output
        return self.select


def load_test_cases(path):
    with open(path, "rt") as f:
        test_cases = yaml.safe_load_all(f)
        return [ SelectTestCase(test_case) for test_case in test_cases ]


@pytest.mark.parametrize("test_case", load_test_cases("tests/select-test-cases.yaml"))
def test_select_prefixes(test_case):
    # .. run the test

It works well except that the tests when run with pytest -v are displayed with test_case0, test_case1, etc parameters.

tests/test_resolver.py::test_select_prefixes[test_case0] PASSED  [ 40%]
tests/test_resolver.py::test_select_prefixes[test_case1] PASSED  [ 60%]
tests/test_resolver.py::test_select_prefixes[test_case2] PASSED  [ 80%]
tests/test_resolver.py::test_select_prefixes[test_case3] PASSED  [100%]

I would love to see the select attribute displayed instead, e.g.

tests/test_resolver.py::test_select_prefixes["some query"] PASSED  [ 40%]
tests/test_resolver.py::test_select_prefixes["another query"] PASSED  [ 60%]

I tried to add __str__() and __repr__() methods to the SelectTestCase class but it didn't make any difference.

Any idea how to do it?

0

1 Answer 1

10

You can define how your parametrized test names look using the ids parameter. This can be a list of strings, or a function that takes the current parameter as argument and returns the ID to be shown in the test name.

So, in your case it is sufficient to use str as that function, as you have already implemented __str__ for the parameters (which are of type SelectTestCase). If you just write:

@pytest.mark.parametrize("test_case", load_test_cases("tests/select-test-cases.yaml"),
                         ids=str)
def test_select_prefixes(test_case):
    # .. run the test

you will get the desired behavior, e.g.

tests/test_resolver.py::test_select_prefixes[some query] PASSED  [ 40%]
tests/test_resolver.py::test_select_prefixes[another query] PASSED  [ 60%]

apart from the apostrophes (which you can add by adapting __str__ accordingly).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.