接口测试框架层级目录结构示意图:
- page目录下面的mysqlTest.py:存放的是mysql的操作代码
- utils目录下面的helper.py:存放的是公共的配置方法
- log目录log.md:存放的日志信息
- data目录下面:存放的是公共数据的分离
- testCase目录下面的test_tasks文件:存放的是接口测试用例
- config目录config.ini文件:存放的配置文件信息
我之前在helper.py文件中写入过getConfig这个方法方便我们后面使用到mysql读取config.ini写好的配置信息。
helper.py文件如下:
#coding=utf-8
__author__ = "Fighter Lu"
#cmd pip install xlrd 安装失败 再次安装
import os
import xlrd
import json
import logging
# import configparser #py3
import ConfigParser #py2
class Helper(object):
def dir_base(self,fileName,filepath='data'): #默认参数
'''
获取要读取的文件路径
:parameter filepath:文件存储的文件路径文件夹名称
:parameter fileName:要操作的文件的名字
'''
return os.path.join(os.path.dirname(os.path.dirname(__file__)),filepath,fileName)
def log(self,log_content):
'''定义log日志级别'''
# 定义文件
logFile = logging.FileHandler(self.dir_base('log.md','log'), 'a')
# log格式
fmt = logging.Formatter(fmt='%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s')
logFile.setFormatter(fmt)
# 定义日志
logger1 = logging.Logger('logTest',level=logging.DEBUG)
logger1.addHandler(logFile)
logger1.info(log_content)
def getReader(self,rowx,index='0'):
'''
读取excel文件数据
:parameter index:读取excel的sheet
:parameter rowx:读取第几行
'''
sheet =xlrd.open_workbook(self.dir_base('fours.xlsx'))
table=sheet.sheet_by_index(int(index)) #获取第一个sheet
return table.row_values(rowx) #读取行
def getUrl(self,rowx):
'''
获取接口测试中的请求地址
:parameter index:读取excel的sheet
:parameter rowx:读取第几行
'''
return self.getReader(rowx)[1] #获取
def getData(self,rowx):
'''
获取接口测试中的请求地址
:parameter index:读取excel的sheet
:parameter rowx:读取第几行
'''
# return self.getReader(rowx)[2] # 获取 转换为字典类型 反序列化转为字典类型
return json.loads(self.getReader(rowx)[2])
def getConfig(self): #py2 py3加 encoding='utf-8' 否则报错ascii
'''读取配置文件中的内容'''
list = []
config = ConfigParser.ConfigParser()
config.read(self.dir_base('config.ini', 'config'))
hostname = config.get(config.sections()[0], 'host')
username = config.get(config.sections()[0], 'username')
password = config.get(config.sections()[0], 'password')
list.append(hostname)
list.append(username)
list.append(password)
return list
# def getConfig(self): #python3
# '''读取配置文件中的内容'''
# list = []
# config = configparser.ConfigParser()
# config.read(self.dir_base('config.ini','config'),encoding='utf-8')
# hostname=config.get(config.sections()[0],'host')
# username=config.get(config.sections()[0],'username')
# password=config.get(config.sections()[0],'password')
# list.append(hostname)
# list.append(username)
# list.append(password)
# return list
per = Helper()
# print(per.getReader(0))
# # print(type(per.getReader(1)))
# # print(type(per.getReader(0)[1]))
# print(per.getUrl(6))
# print(type(per.getUrl(6)))
# print(per.getData(2))
print(per.getConfig())
myTest.py文件下面的代码:
#coding=utf-8
__author__ = "Fighter Lu"
# status 状态
# net start mysql
# net stop mysql
# mysql -h localhost -u root -p 使用该命令访问mysql
# show databases; 查看mysql有哪些库
# use db; 切换数库
# show tables;查看有哪些表
# desc xxx; 查看表中有哪些字段
# show create table user G: 查看创建表的脚本 信息
import MySQLdb
def connectMySql():
'''连接mysql'''
try:
connect = MySQLdb.connect(host='127.0.0.1',user='root',passwd='admin123',db='mysql')
print (u'连接成功!')
except Exception as e:
raise ('连接mysql失败!') #错误演示
else:
pass
finally:
connect.close() #有打开就有关闭
connectMySql()
下面我读取config.ini文件的配置信息:
import JieKou.utils.helper import *
先将helper.py下面的getConfig方法调用过来,然后在进行读取:
def getConfig(self): #py2 py3加 encoding='utf-8' 否则报错ascii
'''读取配置文件中的内容'''
list = []
config = ConfigParser.ConfigParser()
config.read(self.dir_base('config.ini', 'config'))
hostname = config.get(config.sections()[0], 'host')
username = config.get(config.sections()[0], 'username')
password = config.get(config.sections()[0], 'password')
list.append(hostname)
list.append(username)
list.append(password)
return list
调用getConfig方法进行调试,下面的代码是myTest.py:
import MySQLdb
from JieKou.utils.helper import Helper
def connectMySql():
'''连接mysql'''
try:
connect = MySQLdb.connect(host='127.0.0.1',user='root',passwd='admin123',db='mysql')
print (u'连接成功!')
except Exception as e:
raise ('连接mysql失败!') #错误演示
else:
pass
finally:
connect.close() #有打开就有关闭
# connectMySql()
per = Helper()
print (per.getConfig())
print (per.getConfig()[0])
print (type(per.getConfig()))
config.ini文件代码如下:
[阿里云CI服务器(188)]
host = 127.0.0.1
username = root
password = admin123
[阿里云CI服务器(189)]
host = 127.0.0.1
username = admin
password = sdfsadfsdfa
myTests.py文件读取config.ini文件:
import MySQLdb
from JieKou.utils.helper import Helper
def connectMySql():
'''连接mysql'''
try:
connect = MySQLdb.connect(
host=per.getConfig()[0],
user=per.getConfig()[1],
passwd=per.getConfig()[2],
db='mysql')
print (u'连接成功!')
except Exception as e:
raise ('连接mysql失败!') #错误演示
else:
pass
finally:
connect.close() #有打开就有关闭
connectMySql()
出现报错:
Traceback (most recent call last):
File "D:/project/JieKou/page/mysqTests.py", line 35, in <module>
connectMySql()
File "D:/project/JieKou/page/mysqTests.py", line 33, in connectMySql
connect.close() #有打开就有关闭
['127.0.0.1', 'root', 'admin123']
UnboundLocalError: local variable 'connect' referenced before assignment
解决方法:
import MySQLdb
from JieKou.utils.helper import Helper
def connectMySql():
'''连接mysql'''
try:
per = Helper()
connect = MySQLdb.connect(
host=per.getConfig()[0],
user= per.getConfig()[1],
passwd=per.getConfig()[2],
db='mysql')
print (u'连接成功!')
except Exception as e:
raise ('连接mysql失败!') #错误演示
else:
pass
finally:
connect.close() #有打开就有关闭
connectMySql()
没有导入实例化对象 per = Helper(),导入即可解决报错!这时候就显示正常了!!!
C:Python27python2.exe D:/project/JieKou/page/mysqTests.py
['127.0.0.1', 'root', 'admin123']
连接成功!
Process finished with exit code 0