Selenium with Pytest: Writing and Running Tests
๐งช Selenium with Pytest: Writing and Running Tests
๐ What Is Selenium?
Selenium is a tool for automating web browsers — great for testing web apps by simulating real user interactions.
๐ What Is Pytest?
Pytest is a powerful testing framework for Python. It’s clean, readable, and supports fixtures, assertions, and plugins.
๐งฐ What You Need to Get Started
✅ Install Required Packages
bash
Copy
Edit
pip install selenium pytest
Also install a web driver like ChromeDriver or GeckoDriver (for Firefox).
๐ Example: Basic Selenium Test with Pytest
Step 1: Create a Test File — test_google_search.py
python
Copy
Edit
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
import time
@pytest.fixture
def browser():
# Setup: Start the browser
driver = webdriver.Chrome()
yield driver
# Teardown: Close the browser
driver.quit()
def test_google_search(browser):
browser.get("https://www.google.com")
search_box = browser.find_element(By.NAME, "q")
search_box.send_keys("Selenium with Pytest")
search_box.submit()
time.sleep(2) # Wait for results to load (not ideal for real tests)
assert "Selenium with Pytest" in browser.title
๐ How to Run the Test
From the terminal:
bash
Copy
Edit
pytest test_google_search.py
Pytest will automatically:
Find the test
Launch the browser
Run the test
Show you the results
๐ Better Testing: Use Explicit Waits Instead of sleep
python
Copy
Edit
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_google_search(browser):
browser.get("https://www.google.com")
search_box = browser.find_element(By.NAME, "q")
search_box.send_keys("Selenium with Pytest")
search_box.submit()
WebDriverWait(browser, 10).until(
EC.title_contains("Selenium with Pytest")
)
assert "Selenium with Pytest" in browser.title
⚙️ Organizing Tests
Place all tests inside a folder like tests/
Use conftest.py for shared fixtures (e.g., browser setup)
Use --html=report.html for an HTML report (with pytest-html plugin)
๐ง Useful Pytest Commands
Command Description
pytest Run all tests
pytest -v Verbose mode
pytest -k "search" Run tests matching keyword
pytest --maxfail=1 Stop after first failure
pytest --html=report.html Generate test report (plugin needed)
๐ฆ Optional: Use pytest-selenium Plugin
Install:
bash
Copy
Edit
pip install pytest-selenium
It simplifies browser setup and allows command-line browser selection:
bash
Copy
Edit
pytest --driver Chrome
✅ Summary
Selenium handles browser automation
Pytest manages test execution and reporting
Together, they make writing UI tests simple, structured, and scalable
Learn Selenium Python Training in Hyderabad
Read More
Creating a Data-Driven Framework with Selenium and Python
Using unittest Framework with Selenium in Python
How to Read Data from Excel or CSV for Selenium Test Automation
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment