使用python读取配置文件并从mysql数据库中获取数据进行传参(基于Httprunner)

时间:2023-01-30 08:59:16

最近在使用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脚本了。