最近在使用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= 123456port= 3306database= rbac
二、readConfig.py(读取config.ini)
importosimportcodecsimportconfigparser
proDir= os.path.split(os.path.realpath(__file__))[0]
configPath= os.path.join(proDir, "config.ini")printconfigPathclassReadConfig: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)defMysql(self, name):
value= self.cf.get("Mysql", name)returnvaluedefDatabase(self, name):
value= self.cf.get("DATABASE", name)return value
三、mysqlDB.py
#-*- coding:utf-8 -*-
importMySQLdbfrom readConfig importReadConfig
mysql=ReadConfig()#db = MySQLdb.connect(host,user,passwd,database,charset="utf8")
classMysqlDb: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")defuser_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 importMysqlDb
test=MysqlDb()defUserId():
User_Id=test.user_id()return int(User_Id[0])
五.在test.yml中引用
-config:
name:'dashboard'request:
variables:- user_id: ${UserId()}
然后就可以跑test脚本了。