Day 10: Python Programming for SQA Engineers - Your Step-by-
Step Guide
Morning Session (9AM - 1PM) - 4 hours
Step 1: Python Environment Setup (9:00-10:30 AM)
Phase 1: Python Installation (30 minutes)
1. Download Python 3.11+
Visit python.org
Download Windows installer
Critical: Check "Add Python to PATH" during installation
Verify: Open Command Prompt, type python --version
Phase 2: IDE Setup (45 minutes)
Option A: PyCharm Community (Recommended)
Download from jetbrains.com/pycharm
Create new project "SQA-Python-Automation"
Configure Python interpreter
Option B: VS Code (Lightweight)
Install VS Code + Python extension
Configure Python environment
Phase 3: Essential Libraries (15 minutes)
bash
pip install selenium
pip install pytest
pip install requests
pip install pandas
pip install openpyxl
pip install allure-pytest
pip install webdriver-manager
Step 2: Python Fundamentals Review (10:30 AM - 12:00 PM)
Variables & Data Types for Testing (15 minutes)
python
# Basic data types for testing
test_name = "Login Test"
test_id = 101
is_passed = True
test_data = ["user1", "user2", "user3"]
user_info = {"name": "John", "age": 25, "role": "tester"}
# Testing-specific variables
base_url = "https://demo.opencart.com"
timeout = 10
expected_title = "Your Store"
Control Structures Practice (30 minutes)
python
# Conditional testing logic
def validate_login(username, password):
if username == "admin" and password == "admin123":
return "Login Successful"
elif username == "" or password == "":
return "Fields cannot be empty"
else:
return "Invalid credentials"
# Loop through test data
test_users = ["user1", "user2", "user3"]
for user in test_users:
result = validate_login(user, "password123")
print(f"Test for {user}: {result}")
Functions for Test Automation (30 minutes)
python
def setup_browser(browser_name="chrome"):
"""Setup browser for testing"""
print(f"Launching {browser_name} browser")
return f"{browser_name}_driver"
def log_test_result(test_name, status):
"""Log test execution results"""
timestamp = "2024-01-10 10:30:00"
print(f"[{timestamp}] {test_name}: {status}")
Exception Handling (15 minutes)
python
def safe_element_click(element_locator):
"""Safely click element with error handling"""
try:
print(f"Clicking element: {element_locator}")
return True
except Exception as e:
print(f"Unexpected error: {str(e)}")
return False
finally:
print("Click operation completed")
Step 3: File Handling for Test Data (12:00 PM - 1:00 PM)
Excel Operations (30 minutes)
python
import pandas as pd
from openpyxl import Workbook, load_workbook
def create_test_data_excel():
wb = Workbook()
ws = wb.active
ws.title = "Login Test Data"
# Headers
ws['A1'] = "Test_ID"
ws['B1'] = "Username"
ws['C1'] = "Password"
ws['D1'] = "Expected_Result"
# Sample data
test_data = [
[1, "admin", "admin123", "Success"],
[2, "user1", "wrongpass", "Failed"]
]
for i, row in enumerate(test_data, 2):
for j, value in enumerate(row, 1):
ws.cell(row=i, column=j).value = value
wb.save("test_data.xlsx")
print("Test data Excel created!")
JSON Configuration (30 minutes)
python
import json
config_data = {
"browser_settings": {
"default_browser": "chrome",
"headless": False,
"timeout": 10
},
"test_urls": {
"base_url": "https://demo.opencart.com"
}
}
# Save configuration
with open('config.json', 'w') as f:
json.dump(config_data, f, indent=4)
Afternoon Session (2PM - 6PM) - 4 hours
Step 4: Object-Oriented Programming (2:00-3:30 PM)
Page Object Model Classes (45 minutes)
python
class LoginPage:
"""Page Object Model for Login Page"""
def __init__(self, driver):
self.driver = driver
self.url = "https://demo.opencart.com/index.php?route=account/login"
# Locators
self.email_field = "#input-email"
self.password_field = "#input-password"
self.login_button = "input[value='Login']"
def navigate_to_page(self):
"""Navigate to login page"""
print(f"Navigating to: {self.url}")
def enter_credentials(self, email, password):
"""Enter login credentials"""
print(f"Entering email: {email}")
print(f"Entering password: {'*' * len(password)}")
def click_login(self):
"""Click login button"""
print("Clicking login button")
return HomePage(self.driver)
Base Test Classes (45 minutes)
python
class BaseTest:
"""Base class for all test classes"""
def __init__(self):
self.driver = None
self.test_results = []
def setup(self):
"""Common setup for all tests"""
print("Setting up test environment")
def teardown(self):
"""Common cleanup for all tests"""
print("Cleaning up test environment")
def log_result(self, test_name, status, details=""):
"""Log test execution results"""
result = {
"test_name": test_name,
"status": status,
"details": details
}
self.test_results.append(result)
print(f"Test {test_name}: {status}")
Step 5: Libraries for Test Automation (3:30-5:00 PM)
Requests Library for API Testing (45 minutes)
python
import requests
import json
class APITestHelper:
"""Helper class for API testing"""
def __init__(self, base_url):
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({'Content-Type': 'application/json'})
def get_request(self, endpoint, params=None):
"""Send GET request"""
url = f"{self.base_url}{endpoint}"
try:
response = self.session.get(url, params=params)
return {
'status_code': response.status_code,
'response_time': response.elapsed.total_seconds(),
'data': response.json() if response.text else None
}
except Exception as e:
return {'error': str(e)}
Pytest Framework Introduction (45 minutes)
python
import pytest
class TestCalculator:
"""Sample test class using pytest"""
def setup_method(self):
"""Setup before each test method"""
print("Setting up test")
def test_addition(self):
"""Test addition operation"""
result = 2 + 3
assert result == 5, f"Expected 5, got {result}"
@pytest.mark.parametrize("a, b, expected", [
(2, 3, 5),
(10, 5, 15),
(-1, 1, 0)
])
def test_addition_multiple_values(self, a, b, expected):
"""Test addition with multiple test data"""
result = a + b
assert result == expected
Step 6: Selenium WebDriver Setup (5:00-6:00 PM)
WebDriver Setup (30 minutes)
python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
class BrowserManager:
"""Manage browser instances"""
@staticmethod
def get_chrome_driver():
"""Get Chrome WebDriver"""
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
return driver
First Selenium Script (30 minutes)
python
def test_google_search():
"""Complete Google search automation test"""
driver = BrowserManager.get_chrome_driver()
try:
# Navigate to Google
driver.get("https://www.google.com")
# Find search box and search
search_box = driver.find_element(By.NAME, "q")
search_box.send_keys("Selenium Python")
search_box.submit()
# Wait and verify results
import time
time.sleep(2)
if "search" in driver.current_url:
print("✅ Google search test PASSED")
else:
print("❌ Google search test FAILED")
except Exception as e:
print(f"❌ Test failed: {str(e)}")
finally:
driver.quit()
if __name__ == "__main__":
test_google_search()
Evening Session (7PM - 10PM) - 3 hours
Step 7: Complete Framework Setup (7:00-8:30 PM)
Project Structure Creation
Create folders and files:
SQA-Python-Automation/
├── config/
│ ├── config.json
│ └── test_data.xlsx
├── pages/
│ ├── __init__.py
│ ├── base_page.py
│ └── login_page.py
├── tests/
│ ├── __init__.py
│ ├── conftest.py
│ └── test_login.py
├── utils/
│ ├── __init__.py
│ └── browser_manager.py
├── requirements.txt
└── pytest.ini
Requirements.txt
selenium==4.15.2
pytest==7.4.3
requests==2.31.0
pandas==2.1.3
openpyxl==3.1.2
webdriver-manager==4.0.1
Step 8: Write Complete Test Suite (8:30-9:30 PM)
Complete Test Implementation
python
# test_login.py
import pytest
from pages.login_page import LoginPage
class TestLogin:
"""Complete login functionality test suite"""
@pytest.mark.smoke
def test_valid_login(self, browser_setup):
"""Test login with valid credentials"""
driver = browser_setup
login_page = LoginPage(driver)
login_page.navigate_to_page()
home_page = login_page.login("demo", "demo")
assert home_page.is_user_logged_in(), "User should be logged in"
print("✅ Valid login test passed")
def test_invalid_login(self, browser_setup):
"""Test login with invalid credentials"""
driver = browser_setup
login_page = LoginPage(driver)
login_page.navigate_to_page()
login_page.attempt_login("invalid", "invalid")
error_message = login_page.get_error_message()
assert "No match" in error_message, "Error message should be displayed"
print("✅ Invalid login test passed")
Step 9: GitHub Portfolio Update (9:30-10:00 PM)
Portfolio Structure Update
03-Automation-Testing/
├── Python-Selenium-Framework/
│ ├── Complete-Framework/
│ └── Learning-Examples/
└── Test-Reports/
Commit Message
"Day 10: Python automation framework complete + Selenium integration + Pytest setup"
Success Checklist for Day 10
Environment Setup ✅
Python 3.11+ installed and PATH configured
PyCharm/VS Code setup complete
All essential libraries installed
WebDriver manager working
Python Fundamentals ✅
Variables and data types practiced
Control structures implemented
Functions written for testing
Exception handling understood
File operations (Excel, JSON) working
OOP for Testing ✅
Page Object Model classes created
Base test classes implemented
Inheritance concepts applied
Test Framework ✅
Complete framework structure ready
Selenium integration working
Pytest configuration done
First automation test successful
Portfolio Enhancement ✅
Python section added to GitHub
Framework uploaded with documentation
Learning examples committed
Pro Tips for Success
1. Take Breaks: Every 2 hours, take 15-minute breaks
2. Practice First: Don't just read code, type it yourself
3. Debug Errors: When you get errors, use them as learning opportunities
4. Ask AI: Use ChatGPT/Claude when stuck: "Help me debug this Python error"
5. Document: Add comments to your code for future reference
If You Get Stuck
Common Issues & Solutions:
Python not recognized: Check PATH installation
Import errors: Verify library installation with pip list
WebDriver issues: Use WebDriver Manager (already included)
Selenium errors: Check Chrome version compatibility
Tomorrow's Preview (Day 11)
Advanced Python programming
Exception handling mastery
Collections framework
File I/O operations
Python utilities for testing
Logging integration
You're doing great! Day 10 is a foundation day - take your time to understand each concept. The
framework you build today will be the base for advanced automation in coming days.