在软件开发过程中,自动化测试是非常重要的一环。本文将介绍如何使用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)

项目结构
为了更好地组织代码,我们将项目分为以下几个部分:
数据库操作模块 (db_operations.py)
测试用例执行模块 (test_executor.py)
主程序 (main.py)

数据库操作模块 (db_operations.py)
import mysql.connectorfrom mysql.connector import Errorclass DB:def __init__(self, host, database, user, password):self.host = hostself.database = databaseself.user = userself.password = passwordself.connection = Nonedef 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 Trueexcept Error as e:print(f"Error while connecting to MySQL: {e}")return Falsedef close(self):if self.connection and self.connection.is_connected():self.connection.close()def get_test_cases(self):cursor = self.connection.cursor(dictionary=True)query = "SELECT * FROM testdata"cursor.execute(query)results = cursor.fetchall()cursor.close()return resultsdef 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()

测试用例执行模块 (test_executor.py)
import requestsimport jsonfrom db_operations import DBdef 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 URLif test_case['请求方式'] == 0:response = requests.get(url, params=data, headers=headers)else:if test_case['是否需要token'] == 0:headers['Authorization'] = 'Bearer your_token_here' # 替换为实际的Tokenresponse = requests.post(url, data=json.dumps(data) if headers['Content-Type'] == 'application/json' else data, headers=headers)return response.textdef run_tests(host, database, user, password):db = DB(host, database, user, password)if not db.connect():returntest_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')

主程序 (main.py)
# main.pyfrom test_executor import run_testsif __name__ == "__main__":# 可以在这里添加额外的初始化代码、日志记录等run_tests('localhost', 'your_database', 'your_user', 'your_password')

总结
通过上述步骤,我们已经构建了一个基本的测试框架,可以从MySQL数据库中读取测试用例,处理用例之间的依赖关系,并支持参数化。这个框架可以根据实际需求进一步扩展和完善,例如增加更多的错误处理机制、日志记录以及更复杂的依赖逻辑。
