Skip to content Skip to sidebar Skip to footer

Pytest Fixture With Scope “class” Doesn't Works With "setup_class" Method

I'm currently using pytest_addoption to run my API tests, so the tests should run against the environment the user uses on the command line. In my test file, I'm trying to instanti

Solution 1:

If you use a fixture with class scope, the self parameter does not refer to the class instance. You can, however, still access the class itself by using self.__class__, so you can make class variables from your instance variables.

Your code could look like this:

import pytest
from faker import Faker
from projects import UsersSupport
from projects import users_payload


class TestCreateUser:

    @pytest.fixture(autouse=True, scope='class')
    def setup_class(self, env):
        self.__class__.users_support = UsersSupport(env)
        self.__class__.fake = Faker()
        self.__class__.create_user_payload = users_payload.create_user_payload

    def test_create_user(self):
        created_user_res = self.users_support.create_user(
            payload=self.create_user_payload
        ).json()  # now you access the class variable
        print(created_user_res)

During the test, a new test instance is created for each test.
If you have a default function scoped fixture, it will be called within the same instance of the test, so that the self arguments of the fixture and the current test refer to the same instance.

In the case of a class scoped fixture, the setup code is run in a separate instance before the test instances are created - this instance has to live until the end of all tests to be able to execute teardown code, so it is different to all test instances. As it is still an instance of the same test class, you can store your variables in the test class in this case.


Post a Comment for "Pytest Fixture With Scope “class” Doesn't Works With "setup_class" Method"