pytest+allure報告顯示錶格

目錄

背景:

環境:

mysql封裝

代碼


背景:

      做接口自動化時,有時候會連接數據庫查詢數據,在使用allure作爲報告時,就想着如何把sql查詢出來的數據在報告中,以表格的樣式展現出來

環境:

     python3.6,pytest==4.6.2,allure-pytest==2.6.5,allure-python-commons==2.6.5     

mysql封裝

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"])

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章