Cleaning up Pytest Fixtures

In one of our previous tutorials, we added some fixtures to handle the inclusion of parameter handling via a config file and also, the manipulation of the different variables to get the driver working.

In this tutorial, we'll learn how to handle the same variables through parameters in a different way, by using a special class. This way we don't need fixtures to load in memory to access some basic info.

Pre-conditions:

  1. You should have been working on the series where the project has been built structured for POM.

Step-by-step guide:

  1. Create a new folder called generics.
  2. Initialize the folder as a python package by creating an __init__.py file in it (this file goes empty).
  3. Now let's create a new file called config.py that will serve to store our variables.
  4. In this file we'll create a TestData class and will add our variables like below:
    class TestData:
     BROWSER = "chrome'"
     WAIT_TIME = 10
     APP_URL = ""
    
  5. Now let's go to our conftest.py file in our tests directory and update it so that we don't use the fixtures to load the JSON file and read the different variables. Instead, we'll be using our static TestData class.
import pytest
from selenium.webdriver import Chrome, Firefox
from generics.config import TestData

@pytest.fixture(scope='class')
def init_driver(request):
    # Initialize WebDriver
    if TestData.BROWSER == "chrome":
        web_driver = Chrome()
    elif TestData.BROWSER == "firefox":
        web_driver = Firefox()
    else:
        raise Exception(f'"{TestData.BROWSER}" is not supported browser')

    # Create a global instance of the driver for every execution
    request.cls.driver = web_driver

    # Maximize the window
    web_driver.maximize_window()

    # Open the URL
    web_driver.get(TestData.APP_URL)

    # Return the driver object at the end of the setup
    yield web_driver

    # For cleanup quit the driver
    web_driver.quit()

Some additional notes: We removed some fixtures that are not needed due to our way of setting up the framework but were needed for you to understand how they work. We also created a global instance of the WebDriver object to share in the whole session.

Almost there. The next step is to update our test to use the new fixture and clean up the way the initialization of the pages. To do so, continue to the Including BaseTest tutorial.

Note: If you try to run the project now, it's likely that it will fail.