Pytest: Use Console values with “conftest.py”

Murat Feyzioğlu
Beyn Technology
Published in
5 min readNov 29, 2023

In the realm of software testing having an efficient testing suite is crucial to ensure the quality of your software applications. Pytest, an used testing framework, in the Python ecosystem has established itself as a reliable tool for creating and running tests. However, within Pytest there is a treasure called the conftest.py file. It is an asset that is often overlooked but can significantly transform your approach to test automation.

Whether you are a Quality Assurance Test Engineer, developer, or anyone involved in the testing process understanding and harnessing the potential of conftest.py can greatly enhance your testing workflow. This document aims to demystify the conftest.py file by exploring its capabilities and demonstrating how it can be leveraged to optimize your testing suite.

Together we will embark on a journey through the world of conftest.py. We will unravel its mysteries. Showcase its applications. From configuration management to fixture generation from customizing fixture behavior to integrating with third-party plugins and automating testing, in your CI/CD pipeline — conftest.py offers versatility that becomes invaluable once you comprehend its true potential. It can become your trusted ally in pursuit of top-notch software quality.
Whether you have been using Pytest for a while or are new, to the world of software testing this guide is here to help you make the most out of conftest.py. So let’s jump in and explore how we can utilize this tool to improve our testing efforts.

How to Create and Use?

Select or create a Directory. You should place your “conftest.py” file in the corresponding field of the test classes you intend to use. The “conftest.py” file applies to all test files within its own subdirectories. I choose “testCases” directory.

Inside the conftest.py file, you can define fixtures using the @pytest.fixture decorator. For example:

import pytest

@pytest.fixture
def my_fixture():
# Fixture setup code here
yield
# Fixture teardown code here (optional)

This example defines a fixture named my_fixture. You can include setup and teardown code as needed within the fixture. You can also include other configurations or settings in the conftest.py file. For example, you are setting global test parameters, configuring logging, or defining hooks.

I want to show you an example. You can use this example exactly. In the example, there will be configuring logging, and defining hooks. This code gives that you can choose your explorer with your parameter afteryou can change as regarding your project.

import pytest

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService


@pytest.fixture()
def setup(browser):
if browser == "firefox":
driver = webdriver.Firefox()
print("Launching Chrome browser")
return driver
elif browser == "edge":
driver = webdriver.Edge()
print("Launching Firefox browser")
return driver
# if the user doesn't give any parameter.
else:

CHROMEDRIVER_PATH = 'C:/Users/Name/Desktop/chromedriver-win64/chromedriver.exe'
service = ChromeService(executable_path=CHROMEDRIVER_PATH)
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
return driver

# hooks, terminal info,
# get the value from CLI/hooks
def pytest_addoption(parser):
parser.addoption("--browser")

# return the Browser value to setup method
@pytest.fixture()
def browser(request):
return request.config.getoption("--browser")

I added some comment lines for these functions but i would to explain some important parts.

def pytest_addoption(parser):
parser.addoption("--browser")

pytest_addoptions(parser):

When you use this method, you can add an option on your console line. The pytest sees the “ — browser” option and it waits for a parameter after this.

— browser chrome

— browser edge etc.

@pytest.fixture()
def browser(request):
return request.config.getoption("--browser")

browser(request):

This method takes your option from the console and returns.

chrome, edge, etc.

The main method is “def setup(browser)”. You need to define your fixture to your test method. As you see the method waits a parameter “browser”. browser(request) method gives the option to this parameter.

def test_login(self, setup):

Now you can use driver on your test method. There is a simple example. You will see there is no difference from the normal way to use “driver”. (My chrome driver is a little bit different. That’s why i am using some different libraries and third party plugins. )

    def test_login(self, setup):
self.driver = setup

self.driver.get(self.baseURL)

self.login_page = LoginPage(self.driver)
print(self.driver)

self.login_page.setUserName(self.username)
print(self.driver)
self.login_page.setPassword(self.password)
self.login_page.clickLogin()
act_title = self.driver.title

if act_title == "Dashboard / nopCommerce administration":
assert True
else:
assert False

self.driver.close()

You can give a parameter from the console before the test run. And your driver is preparedaccording your parameter.

“pytest -v -s testCases/test_login.py — browser chrome

First example, take a parameter from the console. It was a great feature. Now I want to show you how that add information to the console. It will be more useful if you use this feature.

For example, we have many engineers, project modules, etc and we want to separate or cluster. You can add information with “conftest.py”. These informations are readable from third-party pluggins. This is the biggest differences from the logs.

We are going to add this information with key and value.

def pytest_configure(config):
config._metadata['Project Name'] = 'nop Commerce'
config._metadata['Module Name'] = 'Customers'
config._metadata['Tester'] = 'Murat_test'

when the conftest.py is worked, this method will be triggered. You can add what you want below your console lines.

I hope these two exapmles will improve your automation. You will add information to the console and you will take parameters from the console. Don’t underestimatethe power of using a console. Your outputs and inputs will become more professional.

--

--