python实现简单的http接口自动化

今天给大家分享一个简单的Python脚本,使用python进行http接口的自动化测试,脚本很简单,逻辑是:读取excel写好的测试用例,然后根据excel中的用例内容进行调用,判断预期结果中的返回值和返回报文中的值是否一致,如果不一致则根据用例标题把bug提交到bug管理系统,这里使用的bug管理系统是bugfree。最后统计测试结果:总共执行多少条用例、通过多少条用例,失败多少条用例,邮件标题加上当前时间,将测试结果发送到指定邮箱。

实现步骤:

               1、读取excel,保存测试用例中的内容,这里需要定义一个读取excel的函数readExcel();

               2、根据excel中的请求url和参数拼接请求报文,调用接口,并保存返回报文,这里需要定义一个将请求数据转换为字典的函数param_To_Dic();

               3、读取返回报文,和预期结果对比,不一致的往bugfree数据库中写入一条bug,并且把请求报文、返回报文和测试结果写到测试用例的excel中,这里需要定义一个比对预期结果和返回结果的函数contrastRes(),一个往bugfree提交bug的函数writeBug(),一个将测试结果写入excel的函数copy_excel(),还需定义一个接口请求的函数interfaceTest()。

               4、统计测试结果,发送测试邮件。需定义一个send_email()的函数。

http接口最常用的两种请求方式,POST和GET两种方法,这篇博客分享的就是最简单常用的url请求。例如:http://192.168.21.129/bugfree/index.php/info/edit?type=bug&action=opened&product_id=1

需要用的到几个模块有:requests、xlrd(读取excel)、xlutils(写excel)、pymysql(连接数据库)、yagmail(发送邮件)这五个模块都是第三方模块,需要自己单独安装。

首先在excel中写好用例,需要有的字段 项目、用例id、接口名称、用例描述、请求方式、请求url、请求数据(多个的参数话用&分号隔开)、预期结果、请求报文、返回报文、测试人员、测试结果

测试用例截图如下:

整体代码如下:

import xlrd,requests,time,pymysql,yagmail
from xlutils import copy

def readExcel(file_path):
    try:
        book = xlrd.open_workbook(file_path)
    except Exception as e:
        print('路径不在或者excel不正确',e)
    else:
        sheet = book.sheet_by_index(0)
        rows = sheet.nrows
        count_check = rows - 1
        case_list = []
        for i in range(rows):
            if i != 0:
                case_list.append(sheet.row_values(i))

    interfaceTest(count_check,case_list,file_path)

def interfaceTest(count_check,case_list,file_path):
    result_flags = []  #存测试结果,pass或fail
    request_urls = []  #存请求报文的list
    response = []     #存返回报文的list
    count_pass = 0
    count_fail = 0
    for case in case_list:
        try:
            product = case[0]       # 项目,提bug的时候可以根据项目来提
            case_id = case[1]       # 用例id,提bug的时候用
            interface_name = case[2]  # 接口名称,也是提bug的时候用
            case_detail = case[3]     # 用例描述
            method = case[4]      # 请求方式
            url = case[5]     # 请求url
            param = case[6]   # 入参
            res_check = case[7]   # 预期结果
            tester = case[10]    # 测试人员
        except Exception as e:
            print('测试用例格式不正确!%s' % e)

        if param == '':
            new_url =url
            request_urls.append(new_url)
        else:
            new_url = url + '?' + param
            request_urls.append(new_url)
        if method.upper() == 'GET':
            results = requests.get(url, params=param_To_Dic(param)).json()
            results_str = requests.get(url, params=param_To_Dic(param)).text
            response.append(results)
            res = contrastRes(results, res_check)
        else:
            results = requests.post(url, param_To_Dic(param)).json()
            results_str = requests.post(url, param_To_Dic(param)).text
            response.append(results)
            res = contrastRes(results, res_check)
        if 'pass' in res:
            result_flags.append('pass')
            count_pass += 1
        else:
            result_flags.append('fail')
            count_fail += 1

            writeBug(case_id, interface_name, new_url, results_str, res_check)
    copy_excel(file_path, result_flags, request_urls, response,count_check,count_pass,count_fail)




def param_To_Dic(param):
    data_list = param.split('&')
    data = {}
    for i in data_list:
        k, v = i.split('=')
        data[k] = v
    return data

def contrastRes(results, res_check):
    check_code = res_check.split('=')[1]
    if int(check_code) == results['error_code']:
        return 'pass'
    else:
        # print('错误,返回参数和预期结果不一致' + res_check)
        return 'fail'

def copy_excel(file_path, res_flags, request_urls, response,count_check,count_pass,count_fail):
    book = xlrd.open_workbook(file_path)
    new_book = copy.copy(book)
    sheet = new_book.get_sheet(0)
    i = 1
    for request_url, response, flag in zip(request_urls, response, res_flags):
        sheet.write(i, 8, u'%s' % request_url)
        sheet.write(i, 9, u'%s' % response)
        sheet.write(i, 11, u'%s' % flag)
        i += 1
    new_book.save('%s_测试结果.xls' % time.strftime('%Y%m%d%H%M%S'))
    atta = '%s_测试结果.xls' % time.strftime('%Y%m%d%H%M%S')
    send_mail(count_check, count_fail, count_pass, atta)

def writeBug(bug_id, interface_name, request, response, res_check):
now = time.strftime("%Y-%m-%d %H:%M:%S") # 取当前时间,作为提bug的时间
bug_title = bug_id + '_' + interface_name + '_结果和预期不符' # bug标题用bug编号加上接口名称然后加上_结果和预期不符,可以自己随便定义要什么样的bug标题
step = '[请求报文]<br />' + request + '<br/>' + '[预期结果]<br/>' + res_check + '<br/>' + '<br/>' + '[响应报文]<br />' + '<br/>' + response # 复现步骤就是请求报文+预期结果+返回报文
sql = "INSERT INTO `bf_bug_info` (`created_at`, `created_by`, `updated_at`, `updated_by`, `bug_status`, `assign_to`, `title`, `mail_to`, `repeat_step`, `lock_version`, `resolved_at`, `resolved_by`, `closed_at`, `closed_by`, `related_bug`, `related_case`, `related_result`, " \
"`productmodule_id`, `modified_by`, `solution`, `duplicate_id`, `product_id`, " \
"`reopen_count`, `priority`, `severity`) VALUES ('%s', '1', '%s', '1', 'Active', '1', '%s', '系统管理员', '%s', '1', NULL , NULL, NULL, NULL, '', '', '', NULL, " \
"'1', NULL, NULL, '1', '0', '1', '1');" % (now, now, bug_title, step) # 拼sql,这里面的项目id,创建人,严重程度,指派给谁,都在sql里面写死,使用的时候可以根据项目和接口来判断提bug的严重程度和提交给谁
coon = pymysql.connect(user='root', passwd='123456', db='bugfree', port=3306, host='192.168.21.129', charset='utf8') # 建立连接,使用pymysql模块的connect方法连接mysql,传入账号、密码、数据库、端口、ip和字符集
cursor = coon.cursor() # 建立游标
cursor.execute(sql) # 执行sql
coon.commit() # 提交
cursor.close() # 关闭游标
coon.close() # 关闭连接
 
 
def send_mail(count_check,count_fail,count_pass,atta):
now = time.strftime("%Y-%m-%d %H:%M:%S")
username = '[email protected]'
passwd = 'xxxxxxxxxx'
rece = '[email protected]'
title = 'python接口自动化测试报告'+now
cc = '[email protected]'
content = '大佬 你好:本次测试共运行%s条用例,失败%s条,成功%s条,测试用例详细执行结果请查看附件' % (count_check, count_fail, count_pass)
mail_host = 'smtp.qq.com'
mail = yagmail.SMTP(user = username,password = passwd,host = mail_host,smtp_ssl = True)
mail.send(to = rece,cc = cc,subject = title,contents = content,attachments = atta)
# print('发送成功!')
 

 查看测试邮件

查看bugfree中bug的提交:

猜你喜欢

转载自www.cnblogs.com/mululu/p/9081526.html