0

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..) ?

  • Your decorator is incorrect, the argument should be strings, so it should be: `@pytest.mark.usefixtures("client")` as explained [here](https://docs.pytest.org/en/6.2.x/fixture.html#usefixtures) – RufusVS Jul 15 '21 at 20:26

1 Answers1

1

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)
tmt
  • 7,611
  • 4
  • 32
  • 46
  • This does not actually answer the problem the OP had. The op had incorrectly used the decorator (Interesting that they didn't get a type error) – RufusVS Jul 15 '21 at 20:29
  • @RufusVS OP demonstrated that he/she knows how to use a fixture in a test function but wanted to use it within a test class method instead. `@pytest.mark.usefixtures()` wouldn't allow OP to easily access `client` fixture/object inside the method. – tmt Aug 10 '21 at 13:29