Skip to content

piyu4591/Python-Selenium-Pyunit-Web

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ§ͺ PyUnit (unittest) + Selenium Framework

Professional Test Automation Framework using Python's unittest (PyUnit) and Selenium WebDriver.

✨ Features

  • 🎯 PyUnit (unittest) - Python's built-in testing framework
  • 🌐 Selenium WebDriver - Multi-browser automation
  • πŸ“Š HTML Reports - Beautiful test execution reports
  • πŸ“ Loguru Logging - Professional logging system
  • πŸ”„ CI/CD Ready - Jenkins & GitHub Actions support
  • πŸ“Έ Screenshots - Auto-capture on failures
  • 🎨 Page Object Model - Clean, maintainable architecture
  • βœ… 10 Test Cases - Comprehensive coverage

πŸ“¦ Installation

Prerequisites

  • Python 3.8 or higher
  • pip (Python package manager)

Setup

# Clone or extract the framework
cd pyunit-selenium-framework

# Create virtual environment (recommended)
python3 -m venv venv

# Activate virtual environment
# On macOS/Linux:
source venv/bin/activate
# On Windows:
venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

πŸš€ Quick Start

1. Configure Environment

# Copy example environment file
cp .env.example .env

# Edit .env with your settings (optional)
nano .env

2. Run Tests

# Run all tests with HTML report
python3 run_tests.py

# Or use the bash script
./run_tests.sh

# Run specific browser
./run_tests.sh chrome
./run_tests.sh firefox
./run_tests.sh edge

# Run in headed mode (see browser)
./run_tests.sh headed

# Run in headless mode (no UI)
./run_tests.sh headless

3. View Reports

# HTML report will be in reports/ directory
open reports/PyUnit_Selenium_Test_Report.html

πŸ“ Project Structure

pyunit-selenium-framework/
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ config.py              # Configuration management
β”‚   └── logger.py              # Logging configuration
β”œβ”€β”€ helpers/
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── api_helper.py          # API integration helper
β”œβ”€β”€ pages/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ base_page.py           # Base page object
β”‚   └── login_page.py          # Login page object
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ base_test.py           # Base test class
β”‚   └── test_login.py          # Login test cases
β”œβ”€β”€ screenshots/               # Test screenshots
β”œβ”€β”€ logs/                     # Execution logs
β”œβ”€β”€ reports/                  # HTML test reports
β”œβ”€β”€ requirements.txt          # Python dependencies
β”œβ”€β”€ run_tests.py             # Test runner script
β”œβ”€β”€ run_tests.sh             # Bash test runner
β”œβ”€β”€ .env.example             # Environment variables template
β”œβ”€β”€ .gitignore              # Git ignore file
└── README.md               # This file

πŸ§ͺ Test Cases

All test cases are based on https://the-internet.herokuapp.com/login

Login Tests (10 test cases)

  1. βœ… test_01_successful_login - Verify successful login with valid credentials
  2. βœ… test_02_invalid_username - Verify login fails with invalid username
  3. βœ… test_03_invalid_password - Verify login fails with invalid password
  4. βœ… test_04_empty_credentials - Verify login fails with empty credentials
  5. βœ… test_05_successful_logout - Verify successful logout after login
  6. βœ… test_06_login_page_elements - Verify login page elements validation
  7. βœ… test_07_special_characters - Verify login with special characters
  8. βœ… test_08_case_sensitivity - Verify username case sensitivity
  9. βœ… test_09_clear_form - Verify clear login form functionality
  10. βœ… test_10_page_title - Verify page title

🎯 Running Specific Tests

# Run specific test file
python3 -m unittest tests.test_login

# Run specific test class
python3 -m unittest tests.test_login.LoginTests

# Run specific test method
python3 -m unittest tests.test_login.LoginTests.test_01_successful_login

# Run with verbose output
python3 -m unittest tests.test_login -v

πŸ”§ Configuration

Environment Variables (.env)

# Browser Configuration
BROWSER=chrome                    # chrome, firefox, edge
HEADLESS=true                     # true or false

# Base URL
BASE_URL=https://the-internet.herokuapp.com

# Timeouts (seconds)
IMPLICIT_WAIT=10
EXPLICIT_WAIT=30
PAGE_LOAD_TIMEOUT=30

# Screenshots
SCREENSHOT_ON_FAILURE=true

# Test Data
VALID_USERNAME=tomsmith
VALID_PASSWORD=SuperSecretPassword!

Runtime Configuration

# Set browser
export BROWSER=firefox
python3 run_tests.py

# Set headless mode
export HEADLESS=false
python3 run_tests.py

# Set base URL
export BASE_URL=https://your-app.com
python3 run_tests.py

πŸ“Š Reports & Logging

HTML Reports

  • Location: reports/
  • Auto-generated after each test run
  • Includes test results, screenshots, and execution time
  • Open in browser: open reports/PyUnit_Selenium_Test_Report.html

Logs

  • Location: logs/test_execution.log
  • Rotating logs (max 10MB)
  • 30-day retention
  • Automatic compression

Screenshots

  • Location: screenshots/
  • Auto-captured on test failures
  • Named with test name and timestamp
  • Example: test_01_successful_login_20231215_143022.png

🎨 Page Object Model

Base Page

from pages.base_page import BasePage

class MyPage(BasePage):
    # Locators
    ELEMENT = (By.ID, 'element-id')
    
    def __init__(self, driver):
        super().__init__(driver)
    
    def click_element(self):
        self.click(self.ELEMENT)

Page Methods Available

# Navigation
navigate_to(url)

# Element Interaction
click(locator)
type(locator, text)
get_text(locator)

# Waits
wait_for_element(locator)
wait_for_element_clickable(locator)

# Visibility
is_visible(locator)
is_element_present(locator)

# Utilities
take_screenshot(name)
get_current_url()
get_title()
execute_script(script)

πŸ§ͺ Writing Tests

Test Template

import unittest
from tests.base_test import BaseTest
from pages.your_page import YourPage
from config.logger import test_start, test_end

class YourTests(BaseTest):
    
    def setUp(self):
        super().setUp()
        self.page = YourPage(self.driver)
    
    def test_something(self):
        test_start("TC-001: Test description")
        
        # Test steps
        self.page.do_something()
        
        # Assertions
        self.assertTrue(condition, "Error message")
        
        test_end("TC-001", "PASSED")

if __name__ == '__main__':
    unittest.main()

Assertions

PyUnit provides rich assertion methods:

# Equality
self.assertEqual(a, b)
self.assertNotEqual(a, b)

# Boolean
self.assertTrue(condition)
self.assertFalse(condition)

# Containment
self.assertIn(item, container)
self.assertNotIn(item, container)

# Null checks
self.assertIsNone(value)
self.assertIsNotNone(value)

# Exceptions
self.assertRaises(Exception, callable)

πŸ”„ CI/CD Integration

Jenkins

pipeline {
    agent any
    
    stages {
        stage('Setup') {
            steps {
                sh 'python3 -m venv venv'
                sh 'source venv/bin/activate && pip install -r requirements.txt'
            }
        }
        
        stage('Test') {
            steps {
                sh 'source venv/bin/activate && python3 run_tests.py'
            }
        }
        
        stage('Report') {
            steps {
                publishHTML([
                    reportDir: 'reports',
                    reportFiles: 'PyUnit_Selenium_Test_Report.html',
                    reportName: 'Test Report'
                ])
            }
        }
    }
}

GitHub Actions

name: PyUnit Tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v2
    
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: '3.9'
    
    - name: Install dependencies
      run: |
        pip install -r requirements.txt
    
    - name: Run tests
      run: |
        python3 run_tests.py
    
    - name: Upload report
      uses: actions/upload-artifact@v2
      with:
        name: test-report
        path: reports/

πŸ› Troubleshooting

Issue 1: WebDriver not found

# The framework uses webdriver-manager which auto-downloads drivers
# If issues persist, update webdriver-manager:
pip install --upgrade webdriver-manager

Issue 2: Import errors

# Ensure you're in the project root
cd pyunit-selenium-framework

# Verify Python path
export PYTHONPATH="${PYTHONPATH}:$(pwd)"

Issue 3: Browser not launching

# Check browser is installed
google-chrome --version  # Chrome
firefox --version        # Firefox
msedge --version        # Edge

# Try headed mode to see errors
export HEADLESS=false
python3 run_tests.py

Issue 4: Tests hanging

# Increase timeouts in .env
EXPLICIT_WAIT=60
PAGE_LOAD_TIMEOUT=60

πŸ“š Dependencies

Key dependencies and their purposes:

Package Version Purpose
selenium 4.15.2 Browser automation
webdriver-manager 4.0.1 Auto driver management
loguru 0.7.2 Professional logging
html-testRunner 1.2.1 HTML report generation
requests 2.31.0 API integration
python-dotenv 1.0.0 Environment variables

πŸ’‘ Best Practices

βœ… Use Page Object Model - Keep tests clean and maintainable
βœ… Explicit Waits - Wait for elements, don't use sleep
βœ… Descriptive Test Names - Use test_01_description format
βœ… Independent Tests - Each test should run standalone
βœ… Logging - Use logger for important actions
βœ… Screenshots - Capture on failures for debugging
βœ… Configuration - Use .env for environment-specific settings
βœ… Assertions - Use meaningful assertion messages

πŸŽ“ Learning Resources

πŸ‘¨β€πŸ’» Author

Pravin Gamit

  • Senior QA Automation Engineer
  • 5+ years experience in test automation

πŸ“„ License

ISC License - Free to use and modify


πŸš€ Quick Commands Reference

# Setup
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# Run all tests
python3 run_tests.py

# Run specific browser
./run_tests.sh chrome

# Run in headed mode
./run_tests.sh headed

# Run specific test
python3 -m unittest tests.test_login.LoginTests.test_01_successful_login

# View report
open reports/PyUnit_Selenium_Test_Report.html

# View logs
tail -f logs/test_execution.log

⭐ Happy Testing with PyUnit + Selenium! πŸš€

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors