python PyTest lask for login page for each Test module

325 Views Asked by At

I am new to python. I have requirement that login must be done before running the all the test. i.e. on class level. if i have two test file TEST_F1 , TEST_F2 then when i run the test the login page popup and after successful login it must run all the test in TEST_F1 . When it start to run TEST_F2 then login page must popup again to validate. I am using python , Pytest ,slenumnbase lib

I was not able to archive this in python. It works for me in C# selenium.

1

There are 1 best solutions below

2
On

You can create a fixture to handle the login logic and use it in your test classes.

Here's an example:

Create a fixture for login in conftest.py:

# conftest.py

import pytest

@pytest.fixture(scope="class")
def login(request):

    username = request.cls.username
    password = request.cls.password
    print(f"Logging in with username: {username} and password: {password}")

    def logout():
        print("Logging out...")
    request.addfinalizer(logout)

Use the login fixture in your test classes:

# test_module.py

import pytest

@pytest.mark.usefixtures("login")
class TestF1:
    username = "user1"
    password = "pass1"

    def test_f1_1(self):
        # Your test logic for TEST_F1_1(using self.username and self.password)

    def test_f1_2(self):
        # Your test logic for TEST_F1_2

@pytest.mark.usefixtures("login")
class TestF2:
    username = "user2"
    password = "pass2"

    def test_f2_1(self):
        # Your test logic for TEST_F2_1 
    def test_f2_2(self):
        # Your test logic for TEST_F2_2