用Python实现接口自动化测试并保存测试结果

Posted 程序猿的玻璃心

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用Python实现接口自动化测试并保存测试结果相关的知识,希望对你有一定的参考价值。

介绍

  1. 用Python来做接口自动化测试的好处,我觉得就一点,访问http接口简单,一行代码就行;
  2. 代码不用写很多,可以把若干接口配置成JSON就行;
  3. Python解析之后,将访问结果等数据保存到excel中;

大致就上面3点,

实现

json配置(config.json)


    "service":"http://127.0.0.1:8080",
    "versionCode":"1",
    "apiList":[
        
            "api":"/app/login",
            "name":"登录接口",
            "type":"POST",
            "desc":"登录之后产生的Token是之后接口的基础",
            "params":
                "password": "123", "loginName": "test"
            
        ,
        
            "api":"/app/reportInfo",
            "name":"上报信息",
            "type":"POST",
            "params":
                "dyId": "", 
                "dyName": ""
            
        
    ]

里面的接口api和params信息等需要替换成自己需要测试的内容。
python实现

import requests
import json
import xlwt
import time

token = ""
headers = "Content-Type": "application/json", "charset": "UTF-8"
mTime = time.strftime('%Y年%m月%d日')
mWorkBook = xlwt.Workbook()
mWorkSheet = mWorkBook.add_sheet(mTime)

column = 0
row = 0

# xls error style excel错误样式
def errorStyle():
    font = xlwt.Font()
    # 字体类型
    font.name = 'name Times New Roman'
    # 字体颜色
    font.colour_index = 1

    # 设置背景颜色
    pattern = xlwt.Pattern()
    # 设置背景颜色的模式
    pattern.pattern = xlwt.Pattern.SOLID_PATTERN
    # 背景颜色
    pattern.pattern_fore_colour = 2

    myStyle = xlwt.XFStyle()
    myStyle.font = font
    myStyle.pattern = pattern  # 设置背景颜色
    return myStyle


# 读取config.json
def read_config():
    """"读取配置"""
    with open("./config/config.json",
              encoding='utf-8') as json_file:
        config = json.load(json_file)
    return config


# 遍历接口
def iterateApi():
    config = read_config()
    serviceAdr = config['service']
    for api in config['apiList']:
        url = serviceAdr + api['api']
        params = api['params']
        type = api['type']
        if type == "POST":
            post_json = requests.post(url=url, json=params, headers=headers)
        elif type == "GET":
            post_json = requests.get(url=url, json=params, headers=headers)
        print("reponse =  ", post_json.text)
        text = json.loads(post_json.text)
        getResult(api["name"], url, params, text)


def getResult(name,
              url,
              params,
              result=
                  'code': '-1',
                  'msg': '默认值',
                  'entity': ""
              ):
    global column
    if (column == 0):
        mWorkSheet.write(column, 0, "接口名")
        mWorkSheet.write(column, 1, "地址")
        mWorkSheet.write(column, 2, "参数")
        mWorkSheet.write(column, 3, "结果")
        mWorkSheet.write(column, 4, "服务器返回内容")

    column += 1
    if (result["code"] == "10000"):
        writeSheet(name, column, url, params, result)
        print("success, tip: ", result["msg"])
        entity = result["entity"]
        if (type(entity) is dict) and (result["entity"] !=
                                       None) and ("token" in result["entity"]):
            global token
            token = result["entity"]["token"]
            global headers
            headers["Cookie"] = "access_token=" + token
            print("token = ", token)
    else:
        print("fail, tip: ", result["msg"])
        writeSheet(name, column, url, params, result, True)


# 保存到excel
def writeSheet(name, column, url, params, result, error=False):
    if error is True:
        myStyle = errorStyle()
    else:
        myStyle = xlwt.XFStyle()
    # print("style = ", type(myStyle))
    mWorkSheet.write(column, 0, name, myStyle)
    mWorkSheet.write(column, 1, url, myStyle)
    mWorkSheet.write(column, 2, json.dumps(params,
                                           indent=2,
                                           ensure_ascii=False), myStyle)
    mWorkSheet.write(column, 3, result['msg'], myStyle)
    mWorkSheet.write(column, 4, json.dumps(result,
                                           indent=2,
                                           ensure_ascii=False), myStyle)


if __name__ == '__main__':
    iterateApi()
    mWorkBook.save(mTime + ".xls")

返回参数可以根据自己的接口内容修改。
这套代码只是作为一个参考,具体怎么实现,是需要根据自己需要的接口实现方式进行修改的。

以上是关于用Python实现接口自动化测试并保存测试结果的主要内容,如果未能解决你的问题,请参考以下文章

用Python实现接口自动化测试并保存测试结果

资深程序员用Python实现数据驱动的接口自动化测试!

实现Python接口自动化平台并形成可视化界面

Python实现头条项目接口自动化测试

Python实现头条项目接口自动化测试

我所理解的接口测试—接口自动化测试