最近在使用httprunner進行接口測試,在傳參時,用到了三種方法:(1)從csv文件中獲取;(2)在config中聲名然后進行引用;(3)從函數中獲取。在測試過程中,往往有些參數是需要從數據庫中獲取的,然后考慮到Httprunner提供的debugtalk.py插件,決定試試編寫一個從數據庫讀取值的方法,在經過調試后,最后終於成功了,今天在這里記錄下。
連接mysql數據庫使用的是python的MySQLdb庫,讀取配置文件使用的是configparser庫。debugtalk.py同級目錄下包含文件有:
(1)mysqlDB.py
(2)readConfig.py
(3)config.ini
分別內容如下
一、配置文件config.ini內容如下:
[Mysql] user_id = select id from user where name="root" [DATABASE] host = x.x.x.x user = test passwd = 123456 port = 3306 database = rbac
二、readConfig.py(讀取config.ini)
import os import codecs import configparser proDir = os.path.split(os.path.realpath(__file__))[0] configPath = os.path.join(proDir, "config.ini") print configPath class ReadConfig: def __init__(self): fd = open(configPath) data = fd.read() # remove BOM if data[:3] == codecs.BOM_UTF8: data = data[3:] file = codecs.open(configPath, "w") file.write(data) file.close() fd.close() self.cf = configparser.ConfigParser() self.cf.read(configPath) 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
# -*- coding:utf-8 -*- import MySQLdb from readConfig import ReadConfig mysql = ReadConfig() #db = MySQLdb.connect(host,user,passwd,database,charset="utf8") class MysqlDb: def __init__(self): self.host = mysql.Database("host") self.user = mysql.Database("user") self.passwd = mysql.Database("passwd") self.database = mysql.Database("database") self.db = MySQLdb.connect(self.host,self.user,self.passwd,self.database,charset="utf8") def user_id(self): cursor = self.db.cursor() sql = mysql.Mysql("user_id") cursor.execute(sql) #db.commit()提交到數據庫執行 data = cursor.fetchone() #cursor return data
四、debugtalk.py(提供給httprunnertest函數)
# -*- coding:utf-8 from mysqlDB import MysqlDb test = MysqlDb() def UserId(): User_Id = test.user_id() return int(User_Id[0])
五.在test.yml中引用
- config: name: 'dashboard' request: variables: - user_id: ${UserId()}
然后就可以跑test腳本了。