EX.
NO:05
DATE:14-07-2025
SELENIUM ECOMMERCE PLATFORM TESTING
AIM:
To automate the testing of the Sauce Demo website's login, purchase, and logout
functionalities using Selenium and Pytest, while generating a detailed test report to track the
success or failure of each test step.
ALGORITHM:
1) Set up WebDriver: Initialize a Chrome WebDriver session with specified options and
yield it for tests, ensuring proper cleanup afterward.
2) Execute login test: Navigate to the Sauce Demo login page, input credentials, and
verify successful login by checking for the inventory list.
3) Perform purchase test: Add specified items to the cart, proceed through checkout
steps, and confirm purchase completion.
4) Execute logout test: Access the menu, click the logout link, and verify return to the
login page.
5) Generate test report: Log each test step’s status (Passed/Failed) with timestamps and
errors, then print a summarized report at the end.
CODE:
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from datetime import datetime
@pytest.fixture(scope="session")
def driver():
"""Set up and tear down Chrome WebDriver."""
chrome_options = Options()
chrome_options.add_argument("--disable-features=PasswordCheck") # Disable Google
data breach pop-up
driver = webdriver.Chrome(
service=Service(ChromeDriverManager(driver_version="138.0.7204.101").install()),
options=chrome_options
)
yield driver
driver.quit()
@pytest.fixture
def test_report():
"""Fixture to store test report entries."""
return []
def add_to_report(test_report, step, status, error=None):
"""Add a test step result to the report."""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
report_entry = {
"step": step,
"status": status,
"timestamp": timestamp,
"error": str(error) if error else "None"
}
test_report.append(report_entry)
def print_report(test_report):
"""Print the test report summary."""
print("\n=== Test Report Summary ===")
print(f"{'Step':<20} {'Status':<10} {'Timestamp':<20} {'Error':<50}")
print("-" * 100)
for entry in test_report:
print(f"{entry['step']:<20} {entry['status']:<10} {entry['timestamp']:<20}
{entry['error']:<50}")
print(f"\nTotal Steps: {len(test_report)}")
passed = sum(1 for entry in test_report if entry['status'] == "Passed")
print(f"Passed: {passed}, Failed: {len(test_report) - passed}")
print("==========================")
@pytest.mark.usefixtures("driver", "test_report")
def test_login(driver, test_report):
"""Test login functionality on Sauce Demo."""
base_url = "https://www.saucedemo.com/"
username = "standard_user"
password = "secret_sauce"
wait = WebDriverWait(driver, 20)
try:
print("Navigating to Sauce Demo login page...")
driver.get(base_url)
username_field = wait.until(EC.presence_of_element_located((By.ID, "user-name")))
username_field.send_keys(username)
print("Username entered")
password_field = wait.until(EC.presence_of_element_located((By.ID, "password")))
password_field.send_keys(password)
print("Password entered")
login_button = wait.until(EC.element_to_be_clickable((By.ID, "login-button")))
login_button.click()
print("Login button clicked")
wait.until(EC.presence_of_element_located((By.CLASS_NAME, "inventory_list")))
print("Login successful")
add_to_report(test_report, "Login", "Passed")
except Exception as e:
print(f"Login failed: {str(e)}")
add_to_report(test_report, "Login", "Failed", e)
pytest.fail(f"Login test failed: {str(e)}")
@pytest.mark.usefixtures("driver", "test_report")
def test_search_and_purchase(driver, test_report):
"""Test adding items to cart and completing purchase."""
items = ["Sauce Labs Backpack", "Sauce Labs Bike Light"]
wait = WebDriverWait(driver, 20)
try:
print("Starting purchase process...")
for item in items:
print(f"Attempting to add '{item}' to cart...")
item_button_id = f"add-to-cart-{item.lower().replace(' ', '-')}"
item_button = wait.until(EC.element_to_be_clickable((By.ID, item_button_id)))
item_button.click()
print(f"'{item}' successfully added to cart")
print("Navigating to shopping cart...")
cart_button = wait.until(EC.element_to_be_clickable((By.CLASS_NAME,
"shopping_cart_link")))
cart_button.click()
print("Cart page loaded")
print("Proceeding to checkout page...")
checkout_button = wait.until(EC.element_to_be_clickable((By.ID, "checkout")))
checkout_button.click()
print("Checkout page reached")
print("Entering checkout information...")
first_name_field = wait.until(EC.presence_of_element_located((By.ID, "first-name")))
first_name_field.send_keys("Test")
last_name_field = wait.until(EC.presence_of_element_located((By.ID, "last-name")))
last_name_field.send_keys("User")
zip_code_field = wait.until(EC.presence_of_element_located((By.ID, "postal-code")))
zip_code_field.send_keys("12345")
print("Checkout information submitted")
print("Continuing to payment overview...")
continue_button = wait.until(EC.element_to_be_clickable((By.ID, "continue")))
continue_button.click()
print("Payment overview page loaded")
print("Finalizing purchase...")
finish_button = wait.until(EC.element_to_be_clickable((By.ID, "finish")))
finish_button.click()
print("Purchase submitted")
wait.until(EC.presence_of_element_located((By.CLASS_NAME, "complete-header")))
print("Purchase completed successfully! All items purchased.")
add_to_report(test_report, "Purchase", "Passed")
except Exception as e:
print(f"Purchase failed: {str(e)}")
add_to_report(test_report, "Purchase", "Failed", e)
pytest.fail(f"Purchase test failed: {str(e)}")
@pytest.mark.usefixtures("driver", "test_report")
def test_logout(driver, test_report):
"""Test logout functionality on Sauce Demo."""
wait = WebDriverWait(driver, 20)
try:
print("Opening menu...")
menu_button = wait.until(EC.element_to_be_clickable((By.ID, "react-burger-menu-
btn")))
menu_button.click()
print("Menu opened")
print("Clicking logout link...")
logout_link = wait.until(EC.element_to_be_clickable((By.ID, "logout_sidebar_link")))
logout_link.click()
print("Logout link clicked")
wait.until(EC.presence_of_element_located((By.ID, "login-button")))
print("Logout successful")
add_to_report(test_report, "Logout", "Passed")
except Exception as e:
print(f"Logout failed: {str(e)}")
add_to_report(test_report, "Logout", "Failed", e)
pytest.fail(f"Logout test failed: {str(e)}")
def test_print_report(test_report):
"""Print the test report at the end of the session."""
print_report(test_report)
PARAMETERS USED:
Parameter
Description Value/Example
Name
Chrome WebDriver instance for
WebDriver instance with chrome_options
driver browser automation with
(disables password check pop-ups).
specified options.
List to store test step results (step Empty list initialized as [] for storing report
test_report
name, status, timestamp, error). entries.
URL of the Sauce Demo website
base_url https://www.saucedemo.com/
for navigation.
Username credential for logging
username standard_user
into the Sauce Demo website.
Password credential for logging
password secret_sauce
into the Sauce Demo website.
List of items to be added to the ["Sauce Labs Backpack", "Sauce Labs
items
cart during the purchase test. Bike Light"]
WebDriverWait instance for
WebDriverWait(driver, 20) (20-second
wait handling dynamic page elements
timeout).
with a timeout.
TEST CASES:
Test
Test Expected
Case Description Precondition Steps Postcondition
Scenario Outcome
ID
1. Enter
username.
Verify that a
User is on 2. Enter Inventory
Test Login user can log User is logged
TC_01 the login password. list is
Functionality in with valid in.
page. 3. Click displayed.
credentials.
login
button.
Verify that 1. Add
items can be items to Purchase
cart. 2. Items are
Test Search added to the User is confirmation
TC_02 Navigate to purchased,
and Purchase cart and logged in. page is
cart. 3. cart is empty.
purchased displayed.
successfully. Proceed to
checkout.
Test
Test Expected
Case Description Precondition Steps Postcondition
Scenario Outcome
ID
4. Enter
checkout
info. 5.
Complete
purchase.
Verify that a 1. Open
Test Logout user can log User is menu. 2. Login page User is logged
TC_03
Functionality out logged in. Click is displayed. out.
successfully. logout link.
1. Collect
Verify that a test results.
Report is
test report is Tests have 2. Print Report is
Test Report printed with
TC_04 generated been report with available for
Generation correct
summarizing executed. step, status, review.
details.
all test steps. timestamp,
and errors.
OUTPUT: