Quick Learning guide: Python (Pytest) with Selenium Automation
1. Introduction to pytest and Selenium
What is pytest?
What is Selenium?
Why pytest + Selenium?
2. Environment Setup
Install Required Libraries
pip install selenium pytest pytest-html
pip install webdriver-manager
Install WebDriver
Use webdriver-manager to simplify driver management.
Example for ChromeDriver:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://example.com")
driver.quit()
3. Pytest Basics
Writing a Basic Test
File: test_example.py
def test_example():
assert 1 + 1 == 2
Run the test:
pytest test_example.py
Key pytest Features:
Assertions: Use Python’s assert statement.
4. Selenium with pytest
Example Test Case: Open a Website
File: test_google.py
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
def test_open_google():
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.google.com")
assert "Google" in driver.title
driver.quit()
5. Pytest Fixtures
What are Fixtures?
Fixtures help manage setup and teardown logic for tests.
Example: Browser Fixture
File: conftest.py
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
@pytest.fixture
def browser():
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
yield driver
driver.quit()
Use the fixture in your test:
def test_open_google(browser):
browser.get("https://www.google.com")
assert "Google" in browser.title
6. Locators in Selenium
Example
from selenium.webdriver.common.by import By
def test_google_search(browser):
browser.get("https://www.google.com")
search_box = browser.find_element(By.NAME, "q")
search_box.send_keys("pytest with Selenium")
search_box.submit()
assert "pytest" in browser.page_source
7. Assertions in pytest
assert "Google" in driver.title
8. Parameterized Testing
Run tests with multiple sets of data.
Example
import pytest
@pytest.mark.parametrize("query", ["pytest", "Selenium", "Python"])
def test_search(browser, query):
browser.get("https://www.google.com")
search_box = browser.find_element(By.NAME, "q")
search_box.send_keys(query)
search_box.submit()
assert query in browser.page_source
9. Reports with pytest-html
Generate HTML reports for better insights.
Recommended by LinkedIn
Install pytest-html
pip install pytest-html
Run Tests with HTML Report
pytest --html=report.html
10. Common Use Cases
Login Test
def test_login(browser):
browser.get("https://example.com/login")
browser.find_element(By.ID, "username").send_keys("test_user")
browser.find_element(By.ID, "password").send_keys("password123")
browser.find_element(By.ID, "login_button").click()
assert "Welcome" in browser.page_source
Form Submission
def test_form_submission(browser):
browser.get("https://example.com/form")
browser.find_element(By.NAME, "first_name").send_keys("John")
browser.find_element(By.NAME, "last_name").send_keys("Doe")
browser.find_element(By.NAME, "submit").click()
assert "Thank you" in browser.page_source
11. Handling Dynamic Waits
Implicit Waits
Sets a default wait time for all elements.
browser.implicitly_wait(10) # Wait up to 10 seconds
Explicit Waits
Waits for a specific condition to be met before proceeding.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_explicit_wait(browser):
browser.get("https://example.com")
element = WebDriverWait(browser, 10).until(
EC.presence_of_element_located((By.ID, "dynamic_element"))
)
assert element is not None
Fluent Waits
Checks for a condition at regular intervals until a timeout occurs.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_fluent_wait(browser):
wait = WebDriverWait(browser, timeout=10, poll_frequency=1)
element = wait.until(EC.presence_of_element_located((By.ID, "dynamic_element")))
assert element.is_displayed()
12. Handling Alerts
Simple Alerts
alert = browser.switch_to.alert
assert alert.text == "This is a simple alert"
alert.accept()
Confirmation Alerts
alert = browser.switch_to.alert
alert.dismiss() # Click 'Cancel'
Prompt Alerts
alert = browser.switch_to.alert
alert.send_keys("Test Input")
alert.accept()
13. Types of Exceptions and Handling
Common Selenium Exceptions
Handling Exceptions
Use try-except blocks to handle exceptions gracefully.
from selenium.common.exceptions import NoSuchElementException
def test_exception_handling(browser):
try:
browser.get("https://example.com")
browser.find_element(By.ID, "non_existent_element")
except NoSuchElementException:
print("Element not found")
14. Parallel Execution in pytest
Install pytest-xdist
pip install pytest-xdist
Run Tests in Parallel
pytest -n 4 # Runs tests in 4 parallel threads
Example
If you have multiple test files, they will run concurrently:
pytest tests/ -n auto # Automatically detect the number of available CPU cores
15. Multi-Tab Handling
Automating scenarios involving multiple browser tabs.
Example
from selenium.webdriver.common.by import By
def test_multi_tab_handling(browser):
browser.get("https://example.com")
browser.execute_script("window.open('https://google.com', '_blank');")
# Get all window handles
tabs = browser.window_handles
# Switch to the new tab
browser.switch_to.window(tabs[1])
assert "Google" in browser.title
# Switch back
16. Best Practices
"Fantastic guide! Selenium paired with Python and Pytest is a powerful combination for test automation. Santhanakumar S