python-3.xpytestfixturestest-class

Tests with test fixtures as class methods (PyTest)


In organising tests in PyTest, I have seen that the test methods can be defined within a test class, like so:

class TestBasicEquality:
    def test_a_equals_b(self):
        assert 'a' == 'b'

If we want to write a test (test_client) that has to use a PyTest fixture client we do something like this:

def test_client(client):
    # assert client.something == something

But how can we organise the test_client within a test class? I have tried using @pytest.mark.usefixtures(client) as a decorator for the test class with no success.

Can someone show how and/or point to a guide/documentation for me to understand?

And perhaps a question hidden behind all this: when should we (or shouldn't) put pytest tests within a class? (only now starting to learn PyTest..) ?


Solution

  • In your given case you would simply include the fixture as another method argument:

    class TestSomething:
        def test_client(self, client):
            assert client.something == "something"
    

    So what are the classes good for? Personally, I rarely have a need to use them with pytest but you can for example use them to:

    1. Make groups of tests within one file and be able to run only one group: pytest ./tests/test.py::TestSomething
    2. Execute a fixture for each test method while the methods don't necessarily need to access the fixture itself. An example from the documentation is an automatic clean-up before each method. That is the @pytest.mark.usefixtures() that you have discovered.
    3. Have a fixture that is automatically run once for every test class by defining a fixture's scope to class: @pytest.fixture(scope="class", autouse=True)