Monday, 30 November 2015

Selenium Python Real-Time Automation Project: Complete E-Commerce Testing Example



Introduction

Learning Selenium Python through individual examples is useful, but developing a complete automation project provides a much better understanding of real-world software testing.

In professional projects, automation testers are expected to understand application workflows, identify test scenarios, design reusable scripts, validate business requirements and report defects.

An e-commerce website is an excellent example for learning these skills because it contains multiple functionalities, including login, product search, shopping cart, checkout and order confirmation.

In this tutorial, we will develop a practical e-commerce automation testing project using Selenium WebDriver, Python, PyTest and Page Object Model (POM).

The project will demonstrate how to organise test cases, automate user journeys and validate application behaviour.

1. Project Overview: E-Commerce Website Automation

Our sample project will cover the following application modules:

ModuleTest Scenarios
LoginValid and invalid login
Product listingVerify product availability
Product detailsCheck product information
Shopping cartAdd and remove products
CheckoutEnter customer information
Order summaryVerify order details
LogoutVerify user logout

These scenarios represent common workflows found in online shopping applications.

For practice, testers can use a dedicated demo application such as <Entity value="SauceDemo" category="software" disambig="E-commerce demo application for software testing"/>. Confirm the demo application's current availability and test credentials before running the scripts.

2. Project Requirements and Tools

The following tools will be used:

  • Python 3.

  • Selenium WebDriver.

  • PyTest.

  • VS Code or PyCharm.

  • Chrome browser.

  • Git and GitHub.

  • PyTest HTML reporting plugin.

Install the required packages:

python -m pip install selenium pytest pytest-html

Create a project directory:

mkdir ecommerce_automation
cd ecommerce_automation

Create a virtual environment:

python -m venv venv

Activate it on Windows:

venv\Scripts\activate

Selenium Manager can automatically manage compatible browser drivers in many current Selenium setups.

3. Designing the Automation Framework

We will use Page Object Model to separate application page interactions from test execution.

Recommended project structure:

ecommerce_automation/
│
├── pages/
│   ├── __init__.py
│   ├── login_page.py
│   ├── inventory_page.py
│   ├── cart_page.py
│   └── checkout_page.py
│
├── tests/
│   ├── test_login.py
│   ├── test_inventory.py
│   ├── test_cart.py
│   └── test_checkout.py
│
├── conftest.py
├── pytest.ini
├── requirements.txt
└── reports/

This structure helps organise page objects, test scripts, configuration and reporting.

4. Creating the Browser Fixture

Create conftest.py:

import pytest
from selenium import webdriver

@pytest.fixture
def driver():
    browser = webdriver.Chrome()
    browser.maximize_window()

    yield browser

    browser.quit()

This fixture starts a new browser session for each test and closes it during teardown.

Independent test sessions reduce the possibility of one test affecting another.

5. Automating the Login Page

The first step is to automate user authentication.

Create pages/login_page.py:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class LoginPage:

    USERNAME = (By.ID, "user-name")
    PASSWORD = (By.ID, "password")
    LOGIN_BUTTON = (By.ID, "login-button")
    ERROR_MESSAGE = (
        By.CSS_SELECTOR,
        "[data-test='error']"
    )

    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)

    def enter_username(self, username):
        element = self.wait.until(
            EC.visibility_of_element_located(
                self.USERNAME
            )
        )
        element.send_keys(username)

    def enter_password(self, password):
        element = self.wait.until(
            EC.visibility_of_element_located(
                self.PASSWORD
            )
        )
        element.send_keys(password)

    def click_login(self):
        self.wait.until(
            EC.element_to_be_clickable(
                self.LOGIN_BUTTON
            )
        ).click()

    def login(self, username, password):
        self.enter_username(username)
        self.enter_password(password)
        self.click_login()

    def get_error_message(self):
        return self.wait.until(
            EC.visibility_of_element_located(
                self.ERROR_MESSAGE
            )
        ).text

The page class contains reusable login operations and the relevant element locators.

6. Writing Login Test Cases

Create tests/test_login.py:

from pages.login_page import LoginPage

BASE_URL = "https://www.saucedemo.com/"

def test_valid_login(driver):

    driver.get(BASE_URL)

    login = LoginPage(driver)

    login.login(
        "standard_user",
        "secret_sauce"
    )

    assert "inventory" in driver.current_url


def test_invalid_login(driver):

    driver.get(BASE_URL)

    login = LoginPage(driver)

    login.login(
        "invalid_user",
        "wrong_password"
    )

    error = login.get_error_message()

    assert error != ""

The example uses commonly documented SauceDemo sample credentials. Verify that they remain valid before executing the tests.

The first test verifies successful navigation. The second checks that an error message is displayed for invalid credentials.

7. Automating the Product Listing Page

After login, the user should be able to view available products and add selected items to the shopping cart.

Create pages/inventory_page.py:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class InventoryPage:

    PRODUCTS = (
        By.CLASS_NAME,
        "inventory_item"
    )

    ADD_TO_CART = (
        By.CSS_SELECTOR,
        "button[data-test^='add-to-cart']"
    )

    CART_LINK = (By.CLASS_NAME, "shopping_cart_link")

    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)

    def get_product_count(self):
        products = self.wait.until(
            EC.presence_of_all_elements_located(
                self.PRODUCTS
            )
        )
        return len(products)

    def add_first_product(self):
        button = self.wait.until(
            EC.element_to_be_clickable(
                self.ADD_TO_CART
            )
        )
        button.click()

    def open_cart(self):
        self.driver.find_element(
            *self.CART_LINK
        ).click()

This page object provides methods to count available products, add the first product and open the shopping cart.

8. Writing Product Listing Test Cases

Create tests/test_inventory.py:

from pages.login_page import LoginPage
from pages.inventory_page import InventoryPage

BASE_URL = "https://www.saucedemo.com/"

def test_product_listing(driver):

    driver.get(BASE_URL)

    LoginPage(driver).login(
        "standard_user",
        "secret_sauce"
    )

    inventory = InventoryPage(driver)

    assert inventory.get_product_count() > 0


def test_add_product_to_cart(driver):

    driver.get(BASE_URL)

    LoginPage(driver).login(
        "standard_user",
        "secret_sauce"
    )

    inventory = InventoryPage(driver)

    inventory.add_first_product()
    inventory.open_cart()

    assert "cart" in driver.current_url

These tests validate product availability and the ability to add a product to the shopping cart.

9. Automating the Shopping Cart

The shopping cart allows users to review selected products and proceed to checkout.

Create pages/cart_page.py:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class CartPage:

    CART_ITEMS = (
        By.CLASS_NAME,
        "cart_item"
    )

    CHECKOUT_BUTTON = (
        By.ID,
        "checkout"
    )

    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)

    def get_cart_count(self):
        items = self.driver.find_elements(
            *self.CART_ITEMS
        )
        return len(items)

    def click_checkout(self):
        self.wait.until(
            EC.element_to_be_clickable(
                self.CHECKOUT_BUTTON
            )
        ).click()

Create a test to verify the shopping cart:

from pages.login_page import LoginPage
from pages.inventory_page import InventoryPage
from pages.cart_page import CartPage

def test_cart_contents(driver):

    driver.get("https://www.saucedemo.com/")

    LoginPage(driver).login(
        "standard_user",
        "secret_sauce"
    )

    inventory = InventoryPage(driver)
    inventory.add_first_product()
    inventory.open_cart()

    cart = CartPage(driver)

    assert cart.get_cart_count() == 1

This test verifies that the selected product appears in the cart.

10. Automating the Checkout Process

Checkout is an important e-commerce workflow because it involves customer information and order processing.

Create pages/checkout_page.py:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class CheckoutPage:

    FIRST_NAME = (By.ID, "first-name")
    LAST_NAME = (By.ID, "last-name")
    POSTAL_CODE = (By.ID, "postal-code")
    CONTINUE = (By.ID, "continue")
    FINISH = (By.ID, "finish")
    COMPLETE = (
        By.CLASS_NAME,
        "complete-header"
    )

    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)

    def enter_customer_details(
        self, first, last, postal
    ):
        self.driver.find_element(
            *self.FIRST_NAME
        ).send_keys(first)

        self.driver.find_element(
            *self.LAST_NAME
        ).send_keys(last)

        self.driver.find_element(
            *self.POSTAL_CODE
        ).send_keys(postal)

    def continue_checkout(self):
        self.wait.until(
            EC.element_to_be_clickable(
                self.CONTINUE
            )
        ).click()

    def finish_order(self):
        self.wait.until(
            EC.element_to_be_clickable(
                self.FINISH
            )
        ).click()

    def get_confirmation(self):
        return self.wait.until(
            EC.visibility_of_element_located(
                self.COMPLETE
            )
        ).text

The locators correspond to the sample application's checkout workflow. Verify them against the current demo page.

11. Creating an End-to-End Purchase Test

Now combine login, product selection, cart and checkout into one complete workflow.

Create tests/test_checkout.py:

from pages.login_page import LoginPage
from pages.inventory_page import InventoryPage
from pages.cart_page import CartPage
from pages.checkout_page import CheckoutPage

def test_complete_purchase(driver):

    driver.get("https://www.saucedemo.com/")

    # Login
    LoginPage(driver).login(
        "standard_user",
        "secret_sauce"
    )

    # Add product
    inventory = InventoryPage(driver)
    inventory.add_first_product()
    inventory.open_cart()

    # Open checkout
    cart = CartPage(driver)

    assert cart.get_cart_count() == 1

    cart.click_checkout()

    # Enter customer details
    checkout = CheckoutPage(driver)

    checkout.enter_customer_details(
        "Test",
        "Customer",
        "700001"
    )

    checkout.continue_checkout()
    checkout.finish_order()

    # Verify order confirmation
    confirmation = checkout.get_confirmation()

    assert "Thank you" in confirmation

This is an end-to-end test of the sample shopping workflow. It demonstrates how multiple page objects can work together to automate a business process.

Use non-sensitive test information and confirm that the demo environment supports order completion before running this test.

12. Running the Automation Project

From the project root directory, execute:

pytest -v

Run a specific module:

pytest tests/test_login.py -v

Generate an HTML report:

pytest --html=reports/report.html --self-contained-html

For larger suites, you can add smoke and regression markers and execute selected groups of tests.

13. Test Scenarios to Include in a Real-Time Project

A professional e-commerce automation project should cover more than successful purchases.

Login testing

  • Valid credentials.

  • Invalid username.

  • Invalid password.

  • Empty fields.

  • Locked or inactive account.

  • Logout behaviour.

Product testing

  • Product listing.

  • Product details.

  • Sorting products.

  • Price verification.

  • Product availability.

Cart testing

  • Add product.

  • Remove product.

  • Update quantity, where supported.

  • Verify cart total.

  • Verify selected product details.

Checkout testing

  • Valid customer details.

  • Missing mandatory fields.

  • Invalid postal code.

  • Order summary.

  • Successful order confirmation.

Non-functional considerations

  • Browser compatibility.

  • Page loading behaviour.

  • Accessibility checks.

  • Basic performance observations.

These scenarios help build a more comprehensive automation test suite.

14. Best Practices for Real-Time Selenium Python Projects

  1. Use Page Object Model for reusable page interactions.

  2. Keep test cases independent.

  3. Use explicit waits for dynamic elements.

  4. Maintain separate test data.

  5. Avoid hardcoding credentials in scripts.

  6. Use meaningful assertions.

  7. Generate execution reports.

  8. Maintain logs and useful failure diagnostics.

  9. Use Git for version control.

  10. Integrate the suite with Jenkins or GitHub Actions.

  11. Validate application behaviour rather than only checking URL changes.

  12. Review failed tests to distinguish application defects from automation issues.

A real-time automation project should demonstrate not only browser interaction but also good testing strategy and framework design.

15. How This Project Helps in Automation Testing Interviews

Interviewers frequently ask candidates to explain projects they have developed or worked on.

This e-commerce project provides opportunities to discuss:

  • Selenium WebDriver architecture.

  • Python programming.

  • PyTest fixtures and assertions.

  • Page Object Model.

  • Explicit waits.

  • Data-driven testing.

  • Test case design.

  • Test reporting.

  • Framework architecture.

  • CI/CD integration.

  • Debugging and defect analysis.

Candidates should be able to explain why they selected particular locators, how they handled dynamic elements and how they ensured test independence.

Learn Practical Selenium Python Automation Testing with Palium Skills

Palium Skills offers practical Automation Testing training for freshers, graduates, manual testers and working professionals.

The Selenium Python learning pathway can include:

  • Python programming fundamentals.

  • Selenium WebDriver.

  • Locators and web element handling.

  • PyTest framework.

  • Page Object Model.

  • Data-driven automation.

  • Framework development.

  • End-to-end e-commerce automation projects.

  • API testing fundamentals.

  • Git, Jenkins and CI/CD.

  • Interview preparation.

Training is available through classroom sessions at South Kolkata and Salt Lake, Kolkata, and instructor-led live online sessions for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar, Near South City Mall, Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Frequently Asked Questions

1. What is a real-time Selenium Python project?

It is an automation testing project that simulates practical application workflows, such as login, shopping cart operations and checkout.

2. Which website can beginners use for Selenium practice?

SauceDemo is a commonly used sample e-commerce application for practising browser automation. Verify its current availability and credentials before using it.

3. Which framework is suitable for Selenium Python projects?

PyTest is a popular choice because it supports fixtures, assertions, parameterization and plugins.

4. Why is Page Object Model used in real-time projects?

POM separates page interactions from test logic, improving reusability and maintainability.

5. Can Selenium Python automate an entire shopping workflow?

Yes. Selenium can automate browser-based workflows such as login, product selection, cart management and checkout.

6. Can this project be added to a GitHub portfolio?

Yes. A well-documented project with test cases, framework structure, execution instructions and sample reports can demonstrate practical automation skills.

7. What should I learn after completing this project?

You can progress to API testing, advanced PyTest, Playwright, CI/CD integration, Docker and more advanced automation framework design.

No comments:

Post a Comment

TDS on Salary: A Practical Guide for HR and Payroll Professionals

  TDS on Salary: A Complete Guide for HR and Payroll Professionals Learn how TDS on salary works in India , the role of employers, employee...