Introduction
Writing Selenium tests that simply pass is not enough. A well-designed automation framework should also be easy to maintain, reliable, readable, and scalable. Following PyTest best practices helps reduce flaky tests, simplify debugging, and improve long-term project maintenance.
In this tutorial, you’ll learn the recommended best practices for writing Selenium tests with PyTest, along with practical examples, real-world scenarios, common mistakes, and best practices followed in modern automation frameworks.
What are PyTest Best Practices?
PyTest Best Practices are guidelines that help you write clean, reusable, and stable test cases.
Some important practices include:
Writing independent test cases.
Using clear assertions.
Properly closing the browser after each test.
Avoiding unnecessary hard-coded waits.
Keeping tests simple and readable.
Following these practices makes automation projects easier to maintain and less prone to failures.
Why Follow PyTest Best Practices?
Following best practices helps you:
Create reliable automation tests.
Improve code readability.
Reduce flaky test failures.
Simplify maintenance.
Build scalable automation frameworks.
Example
from selenium import webdriver
from selenium.webdriver.common.by import By
# Topic: 42. Parallel Execution - PyTest Best Practices
# Practice site: https://www.testmuai.com/selenium-playground/simple-form-demo
# Run: pytest -s 42_examples/test_03_pytest_best_practices.py
#
# Best practices: independent tests, clear assertions, quit the browser in
# finally/yield teardown, and avoid hard-coded sleeps.
def test_pytest_best_practices():
driver = webdriver.Chrome()
try:
driver.get("https://www.testmuai.com/selenium-playground/simple-form-demo")
driver.find_element(By.ID, "user-message").send_keys("Best Practice")
driver.find_element(By.ID, "showInput").click()
assert driver.find_element(By.ID, "message").text == "Best Practice"
finally:
driver.quit()
Understanding the Code
Import Required Libraries
from selenium import webdriver
from selenium.webdriver.common.by import By
These modules are required to launch the browser and locate web elements.
Create a Chrome Browser Instance
driver = webdriver.Chrome()
Starts a new Chrome browser session.
Each test creates its own browser instance, keeping the test independent from others.
Open the Practice Website
driver.get(
"https://www.testmuai.com/selenium-playground/simple-form-demo"
)
Navigates to the Simple Form Demo page.
Enter a Message
driver.find_element(
By.ID,
"user-message"
).send_keys("Best Practice")
Locates the message input field and enters the text “Best Practice”.
Click the Show Message Button
driver.find_element(
By.ID,
"showInput"
).click()
Clicks the Show Message button to display the entered message.
Verify the Result
assert driver.find_element(
By.ID,
"message"
).text == "Best Practice"
Checks that the displayed message exactly matches the expected value.
Using a clear and meaningful assert statement makes test failures easier to understand.
Close the Browser
driver.quit()
Closes all browser windows and ends the WebDriver session.
Using driver.quit() inside a finally block ensures that the browser is always closed, even if the test fails.
Important PyTest Best Practices
Some commonly followed best practices include:
Write independent test cases.
Use meaningful assertions.
Always close the browser using driver.quit().
Prefer explicit waits instead of hard-coded time.sleep().
Keep each test focused on a single scenario.
Use fixtures to reuse setup and teardown code.
Store reusable test data separately.
Give test functions descriptive names.
Practical Example
Suppose an online banking application has separate tests for:
User Login
Fund Transfer
Bill Payment
Each test should launch its own browser, perform only its assigned task, verify the expected result, and close the browser without affecting other tests.
Automation Testing Example
Consider an e-commerce application.
Instead of writing one large test that covers login, search, cart, checkout, and payment, create separate test cases for each feature.
This makes failures easier to identify and simplifies maintenance.
Real-World Example
PyTest best practices are commonly followed in:
Selenium automation frameworks
Banking applications
E-commerce platforms
Healthcare systems
Enterprise web applications
CI/CD pipelines
Large regression test suites
Following these practices helps teams maintain reliable and scalable automation projects.
Advantages of Following PyTest Best Practices
Produces stable automation tests.
Improves code readability.
Simplifies maintenance.
Reduces flaky test failures.
Supports reusable automation frameworks.
Makes debugging easier.
Common Mistakes Beginners Make
Writing Dependent Test Cases
Avoid creating tests that rely on the execution of previous tests.
Each test should run successfully on its own.
Using Hard-Coded Sleeps
Avoid:
time.sleep(5)
Instead, use Selenium’s explicit waits whenever synchronization is required.
Forgetting to Close the Browser
Always call:
driver.quit()
This prevents browser sessions from remaining open after test execution.
Writing Multiple Scenarios in One Test
Keep every test focused on one specific feature or workflow.
Smaller tests are easier to maintain and debug.
Using Unclear Assertions
Avoid generic assertions that provide little information.
Write assertions that clearly verify the expected application behavior.
Best Practices
Write independent test cases.
Use clear and meaningful assertions.
Always close the browser using driver.quit().
Prefer explicit waits over time.sleep().
Reuse setup and teardown using PyTest fixtures.
Keep test methods short, readable, and focused on a single scenario.
Use descriptive test names and organize tests logically.
Conclusion
Following PyTest best practices helps create automation tests that are reliable, maintainable, and scalable. Writing independent tests, using meaningful assertions, managing browser sessions correctly, and avoiding unnecessary waits results in cleaner automation code that performs well in both local execution and CI/CD environments.
Frequently Asked Questions (FAQs)
Why are PyTest best practices important?
They improve the reliability, readability, and maintainability of automation test suites.
Why should each Selenium test be independent?
Independent tests can run in any order and do not rely on the results of other tests.
Why should I avoid time.sleep()?
Hard-coded sleeps slow down test execution and can make tests unreliable.
Use Selenium’s explicit waits whenever possible.
Why should I use driver.quit()?
driver.quit() closes all browser windows and properly ends the WebDriver session, preventing resource leaks.
Should one test contain multiple scenarios?
No.
Each test should verify only one specific feature or workflow for easier debugging and maintenance.
Key Takeaways
Write independent Selenium test cases.
Use clear and meaningful assertions.
Always close the browser using driver.quit().
Prefer explicit waits over hard-coded sleeps.
Reuse setup and teardown using PyTest fixtures.
Keep tests small, readable, and focused on a single scenario.
Following best practices improves the stability and maintainability of Selenium automation projects.
