美文网首页
python接口测试

python接口测试

作者: 程一川 | 来源:发表于2019-11-27 15:11 被阅读0次

    一、requests库
    二、pandas库
    三、接口示例

    前言
    本文档讲述使用python requests库请求接口、以excel表格的方式维护测试用例

    一、requests库

    1、环境准备

    1、在已安装python3条件下,在cmd窗口中,输入以下命令进行安装:

    pip install requests
    
    图片.png
    出现提示:Successfully installed requests-2.22.0,说明已安装成功。
    2、查看安装结果:
    pip show requests
    
    图片.png

    3、引用方式
    在python中,requests库的引用方式很简单,使用import requests
    使用requests库请求接口如下:

    import requests
    
    r = requests.get('https://api.github.com/events')
    print(r)
    
    

    上述代码中:
    (1)import requests表示引用python requests库
    (2)get表示接口请求方式
    (3)https://api.github.com/events表示接口地址
    (4)最后把请求结果赋值给变量r,并打印

    2、headers/参数传递
    import requests
    
    url = "https://xxx/xxx-api/api/common/login"
    payload = '{"username": "13916166492", "password": "111111", "rememberMe": false, "language": "zh_CN", "source": "ts"}'
    headers = {'Content-Type': "application/javascript"}
    response = requests.post(url, data=payload, headers=headers)
    print(response.text)
    

    上述代码中:
    (1)payload为请求参数,无则不写
    (2)headers为请求头,无则不写

    3、接口响应

    1、获取响应码

    import requests
    
    url = "https://xxx/xxx-api/api/common/login"
    payload = '{"username": "13916166492", "password": "111111", "rememberMe": false, "language": "zh_CN", "source": "ts"}'
    headers = {'Content-Type': "application/javascript"}
    response = requests.post(url, data=payload, headers=headers)
    print(response.status_code)
    

    python中使用status_code获取响应状态码

    2、获取响应数据
    响应数据类型为字符串:

    import requests
    
    url = "https://xxx/xxx-api/api/common/login"
    payload = '{"username": "13916166492", "password": "111111", "rememberMe": false, "language": "zh_CN", "source": "ts"}'
    headers = {'Content-Type': "application/javascript"}
    response = requests.post(url, data=payload, headers=headers)
    print(response.text)
    

    响应数据类型为字典:

    import requests
    
    url = "https://xxx/xxx-api/api/common/login"
    payload = '{"username": "13916166492", "password": "111111", "rememberMe": false, "language": "zh_CN", "source": "ts"}'
    headers = {'Content-Type': "application/javascript"}
    response = requests.post(url, data=payload, headers=headers).json()
    print(type(response))
    

    3、获取/引用cookie
    (1)获取cookie

    import requests
    
    url = "https://xxx/xxx-api/api/common/login"
    payload = '{"username": "13916166492", "password": "111111", "rememberMe": false, "language": "zh_CN", "source": "ts"}'
    headers = {'Content-Type': "application/javascript"}
    response = requests.post(url, data=payload, headers=headers)
    get_cookies = requests.utils.dict_from_cookiejar(response.cookies)
    print(get_cookies)
    

    python中使用requests.utils.dict_from_cookiejar(response.cookies)获取cookies

    (2)使用cookies

    import requests
    
    url = "https://xxx/xxx-api/api/common/login"
    payload = '{"username": "13916166492", "password": "111111", "rememberMe": false, "language": "zh_CN", "source": "ts"}'
    headers = {'Content-Type': "application/javascript"}
    res = requests.post(url, data=payload, headers=headers)
    get_cookies = requests.utils.dict_from_cookiejar(res.cookies)
    # print(get_cookies)
    url_ = 'https://xxx/xxx-api/api/news/home?channelId=360&pageSize=20'
    r = requests.get(url_, cookies=get_cookies)
    print(r)
    

    4、设置请求超时

    import requests
    
    url = "https://xxx/xxx-api/api/common/login"
    payload = '{"username": "13916166492", "password": "111111", "rememberMe": false, "language": "zh_CN", "source": "ts"}'
    headers = {'Content-Type': "application/javascript"}
    res = requests.post(url, data=payload, headers=headers, timeout=3)
    print(res)
    
    

    在requests请求中使用timeout设置请求超时时间

    官方文档:http://2.python-requests.org/zh_CN/latest/user/quickstart.html#post

    二、pandas库

    使用python pandas库读、写入表格来读取接口请求信息,通过写入表格来记录请求结果

    1、安装

    cmd窗口中输入pip install pandas进行安装

    2、pandas读取excel表格

    表格如下:


    图片.png
    import pandas as pd
    
    # 读
    data = pd.read_excel('1.xlsx')
    
    # 查看所有的值
    print(data.values)
    
    # 查看第一行的值
    print(data.values[0])
    
    # 查看某一列所有的值
    print(data['user'].values)
    
    # 新增列
    data['sex'] = None
    
    # 新增行
    data.loc[3] = ['name5', 231, '男']
    
    # 删除行:axis=0
    data = data.drop([0, 1], axis=0)
    
    # 删除列:axis=1
    data.drop('sex', axis=1)
    

    读取excel并以字典的形式展示输出结果:

    import pandas as pd
    
    
    # 读取测试用例Excel文件
    def read_csv_file(file_path):
        df = pd.read_excel(file_path)
        df.fillna("", inplace=True)  # 填充表格中失却的值
        test_data = []
        # 获取行号的索引,并对其进行遍历
        for i in df.index.values:
            # 根据i来获取每一行指定的数据 并利用to_dict转成字典
            row_data = df.loc[i, ['user', 'pwd']].to_dict()
            test_data.append(row_data)
        print("最终获取到的数据是:", test_data)
    
    
    file_path = '1.xlsx'
    read_csv_file(file_path)
    
    
    3、pandas写入excel表格
    import pandas as pd
    
    # 生成表格名称
    name_xls = 'demo.xlsx'
    # 要写入的表格的内容
    data = {'usr': ['name01', 'name002', 'name003'], 'age': [15, 16, 17], 'sex': ['boy', 'girl', 'girl']}
    # 写入表格
    df = pd.DataFrame(data)
    df.to_excel(name_xls, sheet_name="表格", index=False, header=True)  # index:索引, header:表头
    
    import pandas as pd
    
    # 写入指定表格
    # name_xls = 'demo.xlsx'
    writer = pd.ExcelWriter('demo.xlsx')
    # 要写入的表格的内容
    data = {'usr': ['name04', 'name006', 'name007', 'name009'], 'age': [15, 16, 17, 18], 'sex': ['boy', 'boy', 'girl', 'girl']}
    # 写入表格
    df = pd.DataFrame(data)
    df.to_excel(writer, '表格2')
    writer.save()
    
    

    表格中追加内容:

    import pandas as pd
    
    # 写入指定表格
    # name_xls = 'demo.xlsx'
    writer = pd.ExcelWriter('demo.xlsx')
    # 要写入的表格的内容
    data = {'usr': ['name04', 'name006', 'name007', 'name009'], 'age': [15, 16, 17, 18], 'sex': ['boy', 'boy', 'girl', 'girl'], 'addre': ['北京', '天津', '上海', '杭州']}
    # 写入表格
    df = pd.DataFrame(data)
    df.to_excel(writer, '表格2')
    writer.save()
    
    

    3、接口测试示例

    图片.png

    测试用例test.xlsx:


    图片.png

    执行文件api_test_execl.py:

    import sys
    import time
    from os.path import dirname, abspath
    current_path = dirname(dirname(abspath(__file__))).replace("\\", '/')
    print(current_path)
    sys.path.append(current_path)
    import requests
    import pandas as pd
    
    
    # post请求
    def request_api_post_form(url, headers, data):
        response = requests.post(url, headers=eval(headers), data=data, timeout=5)
        return response.text
    
    
    # GET 请求
    def request_api_get(url, headers, data):
        response = requests.get(url, headers=eval(headers), params=data, timeout=5)
        return response.text
    
    
    # 读取测试用例excel文件
    def read_csv_file():
        df = pd.read_excel(current_path + '/api_test/test.xlsx')
        df.fillna("", inplace=True)
        test_data = []
        # 获取行号的索引,并对其进行遍历
        for i in df.index.values:
            # 根据i来获取每一行指定的数据 并利用to_dict转成字典
            row_data = df.loc[i, ['interface_name', 'headers', 'domain_name', 'addre', 'data', 'request_type', 'Actual_results']].to_dict()
            test_data.append(row_data)
        # print("最终获取到的数据是:", test_data)
        return test_data
    
    
    data = {"interface_name": [], "headers": [], "domain_name": [], "addre": [], "data": [], "request_type": [], "Actual_results": [], "response": [], "result": []}
    for i in read_csv_file():
        url = str(i['domain_name']) + str(i['addre'])
        try:
            if i['request_type'] == 'get':
                response_result = request_api_get(url, i['headers'], i['data'])
            elif i['request_type'] == 'post':
                response_result = request_api_post_form(url, i['headers'], i['data'])
            else:
                print("请检查接口的请求方式!!")
            # print("response_result:", response_result)
            for j in ("interface_name", "headers", "domain_name", "addre", "data", "request_type", "Actual_results"):
                data[j].append(i[j])
            data["response"].append(response_result)
            if i['Actual_results'] in response_result:
                resul = 'SUCCESS'
            else:
                resul = 'FAIL'
            data["result"].append(resul)
        except Exception as err:
            print("请检查 " + i['interface_name'] + "接口: " + i['addre'])
            raise err
    
    # 生成报告名称
    now_time = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
    report_name_xls = f'/测试报告-{str(now_time)}.xlsx'  # 生成Execl命名
    
    # 生成报告
    report_path = current_path + "/api_test/report" + report_name_xls
    df = pd.DataFrame(data)
    df.to_excel(report_path, sheet_name="报告", index=False, header=True)
    
    

    测试报告


    测试报告.png

    相关文章

      网友评论

          本文标题:python接口测试

          本文链接:https://www.haomeiwen.com/subject/ghfywctx.html