Python實現MySQL測試用例管理及執行
作者:huaan9527
在軟件開發過程中,自動化測試是非常重要的一環。本文將介紹如何使用Python和MySQL來管理和執行測試用例,并處理用例之間的依賴關系和參數化問題。我們將通過幾個簡單的步驟來構建一個完整的測試框架。
引言
在軟件開發過程中,自動化測試是非常重要的一環。本文將介紹如何使用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.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()
測試用例執行模塊 (test_executor.py)
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')
主程序 (main.py)
# main.py
from test_executor import run_tests
if __name__ == "__main__":
# 可以在這里添加額外的初始化代碼、日志記錄等
run_tests('localhost', 'your_database', 'your_user', 'your_password')
總結
通過上述步驟,我們已經構建了一個基本的測試框架,可以從MySQL數據庫中讀取測試用例,處理用例之間的依賴關系,并支持參數化。這個框架可以根據實際需求進一步擴展和完善,例如增加更多的錯誤處理機制、日志記錄以及更復雜的依賴邏輯。
責任編輯:華軒
來源:
測試開發學習交流