10 Common Python Automation Testing Scripts for API Testing
This article presents ten practical Python automation testing scripts—including batch test execution, data‑driven testing, API monitoring, performance measurement, database checks, screenshot capture, email reporting, data generation, logging, and response validation—to help developers streamline API testing and improve efficiency.
Batch Execute Interface Test Cases
This script uses unittest to define two simple test methods that can be run together.
import unittest
class MyTestCase(unittest.TestCase):
def test_case1(self):
# Execute interface test case 1
pass
def test_case2(self):
# Execute interface test case 2
pass
if __name__ == '__main__':
unittest.main()Data‑Driven Testing
Read test data from a CSV file and run tests with each row.
import csv
def read_test_data(file_path):
test_data = []
with open(file_path, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
test_data.append(row)
return test_data
def test_with_data(test_data):
for data in test_data:
# Use test data to execute interface test
pass
if __name__ == '__main__':
test_data = read_test_data('test_data.csv')
test_with_data(test_data)Interface Monitoring
Check the availability of API endpoints and print their status.
import requests
def check_api_status(api_url):
response = requests.get(api_url)
if response.status_code == 200:
print(f"接口{api_url}正常")
else:
print(f"接口{api_url}异常")
if __name__ == '__main__':
api_urls = ['https://api.example.com/user', 'https://api.example.com/product']
for url in api_urls:
check_api_status(url)Interface Performance Testing
Measure and display the response time of API calls.
import time
import requests
def measure_response_time(api_url):
start_time = time.time()
response = requests.get(api_url)
end_time = time.time()
response_time = end_time - start_time
print(f"接口{api_url}的响应时间为:{response_time}秒")
if __name__ == '__main__':
api_urls = ['https://api.example.com/user', 'https://api.example.com/product']
for url in api_urls:
measure_response_time(url)Database Testing
Connect to a MySQL database, execute a query, and print the results.
import pymysql
def connect_to_database(host, user, password, database):
conn = pymysql.connect(host=host, user=user, password=password, database=database)
return conn
def execute_sql_query(conn, sql_query):
cursor = conn.cursor()
cursor.execute(sql_query)
result = cursor.fetchall()
cursor.close()
return result
if __name__ == '__main__':
db_conn = connect_to_database('localhost', 'root', 'password', 'mydatabase')
result = execute_sql_query(db_conn, 'SELECT * FROM users')
print(result)
db_conn.close()Page Screenshot (Selenium)
Open a web page with Chrome and capture a screenshot.
from selenium import webdriver
def take_screenshot(url, file_path):
driver = webdriver.Chrome()
driver.get(url)
driver.save_screenshot(file_path)
driver.quit()
if __name__ == '__main__':
take_screenshot('https://www.example.com', 'screenshot.png')Email Sending Report
Send an automated test report via SMTP.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(sender, password, receiver, subject, message):
smtp_server = 'smtp.example.com'
smtp_port = 587
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(sender, password)
server.send_message(msg)
if __name__ == '__main__':
sender = '[email protected]'
password = 'password'
receiver = '[email protected]'
subject = '自动化测试报告'
message = '这是自动化测试的报告,请查收。'
send_email(sender, password, receiver, subject, message)Data Generator
Generate a list of random numbers for test data.
import random
def generate_random_number(min_value, max_value):
return random.randint(min_value, max_value)
def generate_test_data(num_samples):
test_data = []
for _ in range(num_samples):
test_data.append(generate_random_number(1, 100))
return test_data
if __name__ == '__main__':
data = generate_test_data(10)
print(data)Logging
Configure file logging and write an informational message.
import logging
def configure_logging(log_file):
logging.basicConfig(filename=log_file, level=logging.DEBUG)
def log_info(message):
logging.info(message)
if __name__ == '__main__':
log_file = 'test.log'
configure_logging(log_file)
log_info('这是一条日志记录')Interface Data Validation
Validate JSON response data to ensure required fields exist.
import json
def validate_response_data(response_data):
try:
data = json.loads(response_data)
if 'name' in data and 'email' in data:
print("接口返回数据验证通过")
else:
print("接口返回数据验证不通过")
except ValueError:
print("接口返回数据无效")
if __name__ == '__main__':
response_data = '{"name": "John", "email": "[email protected]"}'
validate_response_data(response_data)These ten scripts cover batch execution, data‑driven testing, API monitoring, performance testing, database verification, screenshot capture, email reporting, random data generation, logging, and response validation, providing a solid foundation for automating interface testing tasks.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.