Using Python Generators for Dynamic Test Data Generation
This article explains how Python generators can be leveraged in interface automation testing to dynamically create test data, parameterize URLs, generate test cases, build report entries, tokens, HTTP status codes, query dates, API paths, report headings, and email templates, with complete code examples for each scenario.
Generators are an advanced feature in Python that allow creation of iterators which produce values on demand rather than storing all elements in memory, making them ideal for handling large or streaming data and useful in interface automation testing for dynamic test data generation and parameterization.
Scenario 1: Dynamically generate test user data
# 生成10个用户ID和随机密码
import random
import string
def generate_users(count):
for _ in range(count):
username = f"user{_}"
password = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
yield {"username": username, "password": password}
users = list(generate_users(10))
print(users)
# 输出结果:
[{'username': 'user0', 'password': 'aBcDeFgH'},
{'username': 'user1', 'password': 'iJkLmNoP'},
{'username': 'user2', 'password': 'qRsTuVwX'},
{'username': 'user3', 'password': 'yZaBcDfG'},
{'username': 'user4', 'password': 'hIjKlMnO'},
{'username': 'user5', 'password': 'pQrStUvW'},
{'username': 'user6', 'password': 'xYzAbCdE'},
{'username': 'user7', 'password': 'fGhIjKlM'},
{'username': 'user8', 'password': 'nOpQrStU'},
{'username': 'user9', 'password': 'vWxYzA'}]Scenario 2: Parameterize request URL
# 为不同环境生成请求URL
environments = ["dev", "qa", "prod"]
base_url = "https://api.example.com/{}/users".format
for env in environments:
url = base_url(env)
print(f"Request URL for {env}: {url}")
# 输出结果:
Request URL for dev: https://api.example.com/dev/users
Request URL for qa: https://api.example.com/qa/users
Request URL for prod: https://api.example.com/prod/usersScenario 3: Test case parameterization
# 为测试用例生成不同的查询参数
query_params_cases = (
{"page": page, "limit": limit}
for page in range(1, 6)
for limit in (10, 20, 50)
)
for case in query_params_cases:
print(f"Test case with params: {case}")
# 输出结果:
Test case with params: {'page': 1, 'limit': 10}
Test case with params: {'page': 1, 'limit': 20}
Test case with params: {'page': 1, 'limit': 50}
Test case with params: {'page': 2, 'limit': 10}
... (and so on until page 5)Scenario 4: Generate test report entries
# 基于测试结果生成报告条目
from itertools import product
statuses = ["PASS", "FAIL", "SKIP"]
features = ["login", "logout", "profile"]
report_entries = (
{"feature": feature, "status": status}
for feature, status in product(features, statuses)
)
for entry in report_entries:
print(entry)
# 输出结果:
{'feature': 'login', 'status': 'PASS'}
{'feature': 'login', 'status': 'FAIL'}
{'feature': 'login', 'status': 'SKIP'}
{'feature': 'logout', 'status': 'PASS'}
... (and so on through all combinations)Scenario 5: Dynamically generate authentication tokens
# 假设有一个生成令牌的函数token_generator
import time
def token_generator():
while True:
yield f"Token_{int(time.time())}"
tokens = token_generator()
for _ in range(10):
print(next(tokens))
# 输出结果:
Token_1645872968
Token_1645872969
...Scenario 6: Randomly generate HTTP status codes
# 生成随机HTTP状态码以模拟不同响应情况
http_status_codes = (
random.choice(range(200, 599)) # 常见的状态码范围
for _ in range(10)
)
for code in http_status_codes:
print(f"Simulated HTTP status code: {code}")
# 输出结果:
Simulated HTTP status code: 374
Simulated HTTP status code: 401
Simulated HTTP status code: 289
... (random codes between 200-599)Scenario 7: Database query parameter generation
# 假设要查询不同时间段内的数据
from datetime import timedelta, datetime
def generate_query_dates(start_date, end_date, interval=timedelta(days=1)):
current_date = start_date
while current_date <= end_date:
yield current_date.strftime('%Y-%m-%d')
current_date += interval
start = datetime(2024, 1, 1)
end = datetime(2024, 4, 30)
for date in generate_query_dates(start, end):
print(f"Querying data for date: {date}")
# 输出结果:
Querying data for date: 2024-01-01
Querying data for date: 2024-01-02
Querying data for date: 2024-01-03
... (daily dates up to 2024-04-30)Scenario 8: Construct API path parameters
# 生成不同资源ID的API路径
resources = ["user", "order", "product"]
ids = range(1, 6)
path_params = (
f"/{resource}/{id}"
for resource in resources
for id in ids
)
for path in path_params:
print(f"API Path: /api{path}")
# 输出结果:
API Path: /user/1
API Path: /user/2
API Path: /order/1
API Path: /order/2
... (all combinations of resources and IDs)Scenario 9: Generate test report headings
# 动态生成测试报告的章节标题
sections = ["Introduction", "Setup", "Test Cases", "Results", "Conclusion"]
headings = (
f"Section {i}: {section}"
for i, section in enumerate(sections, start=1)
)
for heading in headings:
print(heading)
# 输出结果:
Section 1: Introduction
Section 2: Setup
Section 3: Test Cases
Section 4: Results
Section 5: ConclusionScenario 10: Email notification template generation
# 为测试结果生成邮件通知内容
def email_template(result, details):
return f"""
Test Result: {result}
Detailed Information:
{details}
"""
results = ["Pass", "Fail"]
details = ["All tests executed successfully.", "Some tests did not pass."]
for res, det in zip(results, details):
print(email_template(res, det))
# 输出结果:
Test Result: Pass
Detailed Information:
All tests executed successfully.
Test Result: Fail
Detailed Information:
Some tests did not pass.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.