Operations 9 min read

10 Essential Python Automation Scripts for API, UI, and Performance Testing

This guide presents ten ready‑to‑use Python scripts covering API testing with Requests, data‑driven tests using DDT, Selenium UI automation, Locust performance testing, unified logging, pytest‑Allure reporting, CSV data handling, SMTP email alerts, Git automation, and coverage measurement, each with installation tips.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
10 Essential Python Automation Scripts for API, UI, and Performance Testing

1. Interface Testing Script (Requests + JSON)

Use

requests

to send HTTP requests and verify status codes and response content.

import requests
import json

def test_api(url, method='get', headers=None, params=None, payload=None):
    try:
        if method.lower() == 'get':
            response = requests.get(url, params=params, headers=headers)
        elif method.lower() == 'post':
            response = requests.post(url, json=payload, headers=headers)
        else:
            raise ValueError("Unsupported request method")
        print(f"Request URL: {response.url}")
        print(f"Status code: {response.status_code}")
        print(f"Response content: {json.dumps(response.json(), indent=2)}")
        return response
    except Exception as e:
        print(f"Request failed: {e}")
        return None

# Example call
if __name__ == "__main__":
    url = "https://jsonplaceholder.typicode.com/posts"
    res = test_api(url, method='get')

2. Data‑Driven Testing Script (DDT)

Leverage the

ddt

module to parameterize tests, suitable for multiple data sets.

import unittest
from ddt import ddt, data, unpack

@ddt
class TestLogin(unittest.TestCase):
    @data(
        ("admin", "123456", True),
        ("guest", "wrongpass", False),
        ("", "", False)
    )
    @unpack
    def test_login(self, username, password, expected):
        result = self.login(username, password)
        self.assertEqual(result, expected)

    def login(self, username, password):
        # Simulated login logic
        return username == "admin" and password == "123456"

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

Install dependency:

pip install ddt

3. UI Automation Script (Selenium)

Use Selenium for browser automation, ideal for web page testing.

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
try:
    driver.get("https://www.example.com/login")
    driver.find_element(By.ID, "username").send_keys("testuser")
    driver.find_element(By.ID, "password").send_keys("password123")
    driver.find_element(By.ID, "login-btn").click()
    time.sleep(2)  # Wait for page load
    assert "Welcome" in driver.title
    print("Login test passed")
finally:
    driver.quit()

Install dependency:

pip install selenium

Note: Install the appropriate browser driver (e.g., ChromeDriver) and add it to the system PATH.

4. Performance Testing Script (Locust)

Write a Locust script to simulate concurrent users accessing endpoints.

from locust import HttpUser, task, between

class WebsiteUser(HttpUser):
    wait_time = between(1, 3)

    @task
    def load_homepage(self):
        self.client.get("/")

    @task(3)
    def get_posts(self):
        self.client.get("/posts")

Run with:

locust -f locustfile.py

Install dependency:

pip install locust

5. Logging Module (logging)

Unified logging format for easier debugging and analysis.

import logging
import os

# Create logs directory
os.makedirs("logs", exist_ok=True)

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    handlers=[
        logging.FileHandler("logs/test.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# Example usage
logger.info("Starting test execution...")
logger.warning("This is a warning message")
logger.error("This is an error message")

6. HTML Report Generation (Pytest + Allure)

Combine

pytest

and

allure-pytest

to produce attractive HTML test reports.

import pytest

def add(a, b):
    return a + b

@pytest.mark.parametrize("a, b, expected", [
    (1, 1, 2),
    (2, 3, 5),
    (-1, 1, 0)
])
def test_add(a, b, expected):
    assert add(a, b) == expected

# Run command to generate report:
# pytest --alluredir=./allure-results test_add.py
# allure serve ./allure-results

Install dependencies:

pip install pytest allure-pytest

(Allure CLI also required).

7. CSV File Reading and Test Data Processing

Read test data from a CSV file, useful for API and data‑driven tests.

import csv

def read_test_data(file_path):
    with open(file_path, newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            yield row

for data in read_test_data('testdata.csv'):
    print(data['username'], data['password'])

Example CSV (testdata.csv):

username,password
testuser1,123456
testuser2,wrongpass
,testempty

8. Email Notification Script (SMTP)

Send an email after test execution to notify results.

import smtplib
from email.mime.text import MIMEText
from email.header import Header

def send_email(subject, content, to_emails):
    msg = MIMEText(content, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = "[email protected]"
    msg['To'] = ", ".join(to_emails)
    try:
        server = smtplib.SMTP("smtp.example.com", 587)
        server.starttls()
        server.login("[email protected]", "your_password")
        server.sendmail(msg['From'], to_emails, msg.as_string())
        print("Email sent successfully")
    except Exception as e:
        print("Email sending failed:", e)
    finally:
        server.quit()

# Example call
send_email("Automation Test Completed", "All 10 test cases passed.", ["[email protected]"])

9. Git Operation Script (Automatic Code Pull)

Automatically pull the latest repository code in CI/CD pipelines.

from git import Repo

def pull_latest_code(repo_path):
    repo = Repo(repo_path)
    origin = repo.remotes.origin
    origin.pull()
    print(f"Updated to latest version, current branch: {repo.active_branch}")

# Example call
pull_latest_code("/path/to/your/repo")

Install dependency:

pip install gitpython

10. Test Coverage Statistics (coverage.py)

Measure how much of the source code is exercised by tests.

coverage run -m pytest test_my_module.py
coverage report -m
coverage html

Install dependency:

pip install coverage

Summary Table

Commonly used script categories are illustrated in the image below.

Script classification table
Script classification table
PythonautomationtestingAPISeleniumLocustPytestScripts
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.