Sateeshkumar Varma
Sateeshkumar Varma

Reputation: 21

How to pass parameter to fixture from tests in pytest

I want to create a solution where i can create a login logout fixture where the login will be based on test cases.

For example

@pytest.mark.usefixtures("setup_driver")
class TestSmoke:

    def test_smoke_test1_login(self,login_logout):
        print("test1")

    def test_smoke_test2_login(self,login_logout):
        print("test2")`

In above code there are 2 tests and i have conftest.py with 2 fixtures.

def setup_driver(request):
// setting up driver

@pytest.fixture(scope='function', autouse=True)
def login_logout(driver,usernam,password):
// Login ang logout.

The setup_driver i am using at class level and login logout i want to use it at each test level.

Challenge here is the login is not constant with users it gets changed as per the tests .. So have to pass user name and password specific to tests.

Can anybody suggest me how i can achieve this by passing the required parameters to login_logout fixture through tests.

Upvotes: 2

Views: 2416

Answers (1)

Andrei Evtikheev
Andrei Evtikheev

Reputation: 329

You can use indirect parametrization

test_*.py

@pytest.mark.usefixtures("setup_driver")
class TestSmoke:

    @pytest.mark.parametrize(
        "login_logout", [("login1", "password1")], indirect=True
    )
    def test_smoke_test1_login(self, login_logout):
        print("test1")

    @pytest.mark.parametrize(
        "login_logout", [("login2", "password2")], indirect=True
    )
    def test_smoke_test2_login(self, login_logout):
        print("test2")

conftest.py

@pytest.fixture(scope='function')
def login_logout(request):
    login, password = request.param
    ...

Read more at https://docs.pytest.org/en/7.1.x/example/parametrize.html#indirect-parametrization

Upvotes: 0

Related Questions