Skip to content

Referencing a specific case function within a class #159

@plammens

Description

@plammens

What is the correct way to reference a specific case function that is part of a class (for case grouping)?

For example, this

import pytest_cases


class CaseGroup:
    def case_x(self):
        return 1


@pytest_cases.parametrize_with_cases("x", cases=CaseGroup.case_x)
def test_spam(x):
    pass

doesn't work because CaseGroup.case_x is an unbound method and there's nothing to fill the self parameter with (pytest complains that there is no fixture named self).

One way maybe would be to instantiate the case group before referencing the method:

@pytest_cases.parametrize_with_cases("x", cases=CaseGroup().case_x)
def test_spam(x):
    pass

although this looks quite ugly.

Another would be to use @staticmethod:

class CaseGroup:
    @staticmethod
    def case_x1():
        return 1

    @staticmethod
    def case_x2():
        return 2


@pytest_cases.parametrize_with_cases("x", cases=CaseGroup.case_x1)
def test_specific_x(x):
    pass

Is this supported? If so, should the staticmethod decorator always be the topmost?

In any case, if we have to do this for every case function, it becomes cumbersome. Perhaps it would be useful to have a metaclass in pytest-cases that automatically makes every function in the class definition body a static method, since case classes are essentially just a namespace. This could also be useful in the future to add any other features to case classes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions