目录
背景:
环境:
mysql封装
代码
做接口自动化时,有时候会连接数据库查询数据,在使用allure作为报告时,就想着如何把sql查询出来的数据在报告中,以表格的样式展现出来
python3.6,pytest==4.6.2,allure-pytest==2.6.5,allure-python-commons==2.6.5
import pymysql
class MySQLConfig:
# MySQL数据库初始化
def __init__(self, host, port, user, password):
self.host = host
self.port = port
self.user = user
self.password = password
def __enter__(self):
self.conn = self.get_conn(self.host, self.port, self.user, self.password)
self.cursor = self.conn.cursor()
return self
@staticmethod
def get_conn(host, port, user, password):
config = {
"host": host,
"port": int(port),
"user": user,
"password": password,
# "database": db,
"charset": "utf8"
}
conn = pymysql.connect(**config)
return conn
def select_sql(self, sql):
try:
self.cursor.execute(sql)
data = self.cursor.fetchall()
_list = []
# 获取表头
for i in self.cursor.description:
_list.append(i[0])
data = list(data)
data.insert(0, _list)
return data[:31], True
except Exception as e:
return str(e), False
def __exit__(self, exc_type, exc_val, exc_tb):
self.cursor.close()
if __name__ == "__main__":
pass
要显示表格样式,使用allure.attach,type选择csv
allure.attach(response, '执行结果', attachment_type=AttachmentType.CSV)
这段语句会把response的内容写入一个csv文件中
因为sql查询结果是一个二维数组,而csv是由 , 和 换行符构成的二维列表(可使用文本打开csv格式文件就能明白), 所以需要将sql查询结果格式修改一下
response = ""
# value是sql查询返回的二维数组或任意二维数组
for i in value:
for j in i:
response = response + str(j).replace(",", ",") + ","
response = response + "\n"
最后在生成的alluredir文件中,查找csv文件内容如图
点击展开后
import allure
import pytest
from allure_commons.types import AttachmentType
from TestScript.common.MySQLini import MySQLConfig
class TestApi:
def test_api(self):
host = ""
port = 3306
username = ""
password = ""
sql = ""
with MySQLConfig(host, port, username, password) as f:
value, result = f.select_sql(sql)
if result:
response = ""
for i in value:
for j in i:
response = response + str(j).replace(",", ",") + ","
response = response + "\n"
allure.attach(sql, "sql语句")
allure.attach(response, '执行结果', attachment_type=AttachmentType.CSV)
if __name__ == "__main__":
pytest.main(["--alluredir=allur_result"])