HttpRunner3.X - 連線資料庫實踐
阿新 • • 發佈:2021-08-19
一、前言
做自動化測試的時候,有時要跟資料庫有互動,經常遇到的場景有:
- 從資料庫中讀取資料,並將這些資料作為介面引數使用
- 從資料庫中讀取資料,並斷言介面返回的資料與落表的資料是否一致
二、檔案目錄框架如下
三、建立資料庫配置檔案 config/config.ini
輸入自己用的資料庫的相關資訊即可,這裡我給 user_name 賦值了一個 SQL語句,可以根據需求調整。
[Mysql] user_name = select room_name from clothim where created_name="李白" [DATABASE] host = 192.8.0.2 user = doud passwd= Oc0C&=3a port = 13306 database = croom
四、建立讀取資料庫配置檔案 readConfig.py
import os,codecs,configparser #建立讀取資料庫配置檔案 class ReadConfig: def __init__(self): self.cf = configparser.ConfigParser() #例項化configparser物件 #獲取當前資料夾的父目錄絕對路徑 self.path = os.path.dirname(os.path.dirname(__file__)) #獲取config資料夾中的ini檔案 self.file_path = os.path.join(self.path,'config','config.ini') #讀取ini檔案 self.cf.read(self.file_path,encoding='utf-8') def Mysql(self,name): value = self.cf.get("Mysql",name) return value def DataBase(self,name): value= self.cf.get("DATABASE",name) return value
五、連線資料庫及執行資料庫檔案 mysqlDB.py
import pymysql from config.readConfig import ReadConfig #連線資料庫及執行資料庫檔案 mysql = ReadConfig() class MysqlDb: def __init__(self): self.host = mysql.DataBase("host") self.user = mysql.DataBase("user") self.passwd = mysql.DataBase("passwd") self.port = mysql.DataBase("port") self.database = mysql.DataBase("database") self.db = pymysql.connect(host=self.host,user=self.user,password=self.passwd,database=self.database,port=13306,charset="utf8") def execute(self,sql,data): connect = self.db cursor = connect.cursor() cursor.execute(sql % data) connect.commit() def execute_read(self,sql,data): connect = self.db cursor = connect.cursor() cursor.execute(sql % data) for row in cursor.fetchall(): return row def user_name(self): sql = mysql.Mysql("user_name") data = self.execute_read(sql,()) return data def user_code(self): sql = mysql.Mysql("user_code") data = self.execute_read(sql,()) return data
六、在 debugtalk.py(必須是這裡)中寫一個查詢資料 sql 的方法
import time from httprunner import __version__ from mysqlDB import MysqlDb #定義查詢資料 sql 的方法 mysqlDB = MysqlDb() def get_user_name(): user_name = mysqlDB.user_name() return user_name[0]
七、在測試用例中呼叫該方法
用 $ 符號即可
"username": "${get_user_name()}"
八、執行指令碼即可