Python实现MySQL测试用例管理及执行
引言
项目结构
测试用例执行模块 (test_executor.py)
主程序 (main.py)
总结
在软件开发过程中,自动化测试是非常重要的一环。本文将介绍如何使用Python和MySQL来管理和执行测试用例,并处理用例之间的依赖关系和参数化问题。我们将通过几个简单的步骤来构建一个完整的测试框架。
项目需求概述我们的目标是创建一个测试框架,能够从MySQL数据库中读取测试用例,然后根据这些用例发送HTTP请求,并记录响应结果。此外,我们还需要支持用例之间的依赖关系以及参数化功能。
数据库表testdata包含以下字段:复制
id: 用例ID
用例名称: 用例的描述
是否需要token (0为需要, 1为不需要,默认为0)
请求方式 (0为GET, 1为POST)
请求数据格式 (0为application/json, 1为application/x-www-form-urlencoded)
请求数据 (统一存放格式为JSON)
返回数据 (测试用例执行后回写)
depends_on (依赖的用例ID)1.2.3.4.5.6.7.8.
为了更好地组织代码,我们将项目分为以下几个部分:
数据库操作模块 (db_operations.py)测试用例执行模块 (test_executor.py)主程序 (main.py)数据库操作模块 (db_operations.py)复制
import mysql.connector
from mysql.connector import Error
class DB:
def __init__(self, host, database, user, password):
self.host = host
self.database = database
self.user = user
self.password = password
self.connection = None
def connect(self):
try:
self.connection = mysql.connector.connect(
host=self.host,
database=self.database,
user=self.user,
password=self.password
)
if self.connection.is_connected():
return True
except Error as e:
print(f"Error while connecting to MySQL: {e}")
return False
def close(self):
if self.connection and self.connection.is_connected():
self.connection.close()
def get_test_cases(self):
cursor = self.connection.cursor(dictinotallow=True)
query = "SELECT * FROM testdata"
cursor.execute(query)
results = cursor.fetchall()
cursor.close()
return results
def update_test_case(self, id, response):
cursor = self.connection.cursor()
query = "UPDATE testdata SET 返回数据 = %s WHERE id = %s"
cursor.execute(query, (response, id))
self.connection.commit()
cursor.close()1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.
复制
import requests
import json
from db_operations import DB
def send_request(test_case, context):
headers = {}
if test_case[请求数据格式] == 0:
headers[Content-Type] = application/json
data = json.loads(test_case[请求数据])
else:
headers[Content-Type] = application/x-www-form-urlencoded
data = test_case[请求数据]
# 参数化:替换请求数据中的占位符
for key, value in data.items():
if isinstance(value, str) and value.startswith({{) and value.endswith(}}):
var_name = value[2:-2]
if var_name in context:
data[key] = context[var_name]
url = "http://your_api_url_here" # 替换为实际的API URL
if test_case[请求方式] == 0:
response = requests.get(url, params=data, headers=headers)
else:
if test_case[是否需要token] == 0:
headers[Authorization] = Bearer your_token_here # 替换为实际的Token
response = requests.post(url, data=json.dumps(data) if headers[Content-Type] == application/json else data, headers=headers)
return response.text
def run_tests(host, database, user, password):
db = DB(host, database, user, password)
if not db.connect():
return
test_cases = db.get_test_cases()
context = {} # 用于存储变量值
for test_case in test_cases:
# 检查是否存在依赖
depends_on = test_case.get(depends_on)
if depends_on:
# 获取依赖用例的结果
dependency = next((tc for tc in test_cases if tc[id] == depends_on), None)
if dependency and 返回数据 in dependency:
# 将依赖用例的结果放入上下文中
context.update(json.loads(dependency[返回数据]))
# 执行当前用例
response = send_request(test_case, context)
db.update_test_case(test_case[id], response)
# 更新上下文
context.update(json.loads(response))
db.close()
if __name__ == "__main__":
# 这里可以添加参数解析器来动态获取数据库连接信息等
run_tests(localhost, your_database, your_user, your_password)1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.
复制
# main.py
from test_executor import run_tests
if __name__ == "__main__":
# 可以在这里添加额外的初始化代码、日志记录等
run_tests(localhost, your_database, your_user, your_password)1.2.3.4.5.
通过上述步骤,我们已经构建了一个基本的测试框架,可以从MySQL数据库中读取测试用例,处理用例之间的依赖关系,并支持参数化。这个框架可以根据实际需求进一步扩展和完善,例如增加更多的错误处理机制、日志记录以及更复杂的依赖逻辑。
THE END