接口自动化获取excel中数据(一)

欢迎大家关注我的公众号哈。【软件测试小助手】,希望大家支持啦!

自动化测试可以分为数据驱动类别:一般通过excel中数据来测试;

代码驱动:一般测试用例以代码为主,通过读取代码进行测试;

关键字驱动:偏ui自动化,其中robotframework就是典型的关键字驱动框架;

接口自动化用例设计:基本设计用例的方法和功能测试一致

接口自动化步骤:

获取测试用例+调用测试接口+结果校验+发送测试报告+异常处理

接口测试网址:http://doc.nnzhp.cn/index.php?s=/6&page_id=12

目录结构:接口自动化获取excel中数据(一)_第1张图片

运用代码:

requests.post(url,data,json,**kwargs) 调用post请求,返回响应的相关信息

requests.get(url,params=None, **kwargs) 调用get请求,输入请求参数xlrd.open_workbook(file_path) 打开excel的目录 data.sheet_by_index(sheet_indx)) #输入0则获取第一个sheet页数据

data.sheet_by_name(sheet_name)#通过sheet名称获取数据

sheet.cell_value(self, rowx, colx):#获取第n行,第n列数据

1)以登录而言,相关测试用例如下图所示:

接口自动化获取excel中数据(一)_第2张图片

2)获取表格中的数据和建立请求连接进行判断,代码如下:

import requests
import xlrd
import math


def get_requsts(method, url, data):
    if method == 'POST':  #post请求
        results = requests.post(url, data=data)
    else:  #get请求
        results = requests.get(url, data)
    response = results.json()
    code = response.get('error_code')
    return code


def get_excel(file_path):  # 判断文件名是否正确
    if file_path.endswith('.xls') or file_path.endswith('.xlsx'):
        try:
            book = xlrd.open_workbook(file_path)  # 打开excel
            sheet = book.sheet_by_index(0)  # 获取第一个sheet页数据
            for i in range(1, sheet.nrows):  # sheet.nrows获取列表中的每一行
                 ex_no = sheet.cell_value(i, 1)  # 用例编号
                 ex_path = sheet.cell_value(i, 3)  # 请求url
                 ex_method = sheet.cell_value(i, 4)  # 请求方法
                 ex_user = sheet.cell_value(i, 5)  # 填写的参数username
                 ex_pwd = sheet.cell_value(i, 6)  # 填写的参数passwd
                 ex_code = sheet.cell_value(i, 7)  # 返回结果码
                 data ={'username': ex_user, 'passwd': ex_pwd}  # 讲取到的结果放入数组中,以key value的格式
                 get_code = get_requsts(ex_method,ex_path, data) # 调用请求连接方法
                 if get_code == ex_code:
                    print(math.floor(ex_no), 'pass')  # 判断是否和预期结果一致
                 else:
                     print('fail')
        except Exception as e:
            print('this is wrong', e)
    else:
        print('excel格式错误')


filepath = 'D:\资料汇总\python自学\接口自动化\lqwtest\cases\测试用例.xlsx'
get_excel(filepath)

3)查看结果:

接口自动化获取excel中数据(一)_第3张图片

你可能感兴趣的:(软件测试)