【Robotframework+python】实现http接口自动化测试

前言

下周即将展开一个http接口测试的需求,刚刚完成的java类接口测试工作中,由于之前犯懒,没有提前搭建好自动化回归测试框架,以至于后期rd每修改一个bug,经常导致之前没有问题的case又产生了bug,所以需要一遍遍回归case,过程一直手工去执行,苦不堪言。所以,对于即将开始的http接口测试需求,立马花了两天时间搭建了一个http接口自动化测试框架用于测试后期回归测试,实在是被大量的重复手工执行搞怕了。

基础框架选择

最方便的方法就是用python直接写代码,代码和测试数据分离,测试数据放在excel中保存。这种实现最快捷方便,但也有些缺点:
(1)用例管理不太方便,不直观;
(2)HTMLTestRunner输出报告做的比较烂。

相较而言,robot framework具有用例管理清晰,输出报告美观的特点。但robot的缺点就是编码起来不如python直接写代码方便。所以,为了快速搭建http接口自动化框架用于回归测试,我直接用python写了一个框架。为了后续长远考虑,便于用例管理,测试报告美观,且集成到测试平台工具化以及推广给rd和其他qa同学使用,又用robot搭建了一套框架。本文就详细说明该搭建过程。

搭建思路

框架采用robot和python实现,因为robot中的复杂逻辑实现起来比较繁琐,故选择用python实现,然后以外部库的形式导入robot中使用。测试用例数据保存在excel中。
使用过robot的人了解,robot中测试维度划分为测试套件(Test Suite)和测试用例(Test Case),一个Suite为一组Case的集合,每个Case对应为我们手工执行测试时的Case。

假设测试一个路径为/areaplug/showCityName的http接口,常规方法是在robot中新建一个showCityName的Suite,其下包含测试该http接口的用例集,如下图所示: 

showCityName Test Suite

倘若测试该接口有20个异常用例,则建立20条相应的test case。但是,对于测试http接口来讲,以上用例无非就是请求参数和响应不一样而已,发送请求的逻辑是一模一样的。所以,这20条test case其实用一条test case就能实现了,在这1条case中分别遍历读取20个异常用例的测试数据执行测试就ok了。所以最后构造的suite和case如下:

接口case

图中,batch_Request为测试套件,其下的每个robot的test case对应一个http接口测试场景,比如测试路径为/areaplug/showCityName的http接口,该接口的所有正向和异常用例均在test_showCityName中实现,在test_showCityName中读取测试数据文件,获取该接口的测试用例数目,遍历每一条测试用例数据,调用http_Request下的sendHttpRequest发送http请求。其实,这里的test_showCityName就相当于test suite了,而遍历测试数据文件中的每一行测试数据去调用sendHttpRequest时,就相当于生成了一条test case,这样就可以将一个接口的所有测试用例用robot的一条test case实现(实质是robot的一条test case相当于一个test suite,在这个robot的test case中动态生成n条test case)。整个流程如下图所示:

框架流程图

搭建
测试数据

测试数据保存在excel中,每一个sheet页对应一个测试场景,即一个http接口。该sheet也保存有测试该接口的所有测试用例数据以及接口路径和请求方法,如下图所示(这里仅仅是一个demo,实际回归测试时,会有大量的用例和数据): 

测试数据

测试框架

整个工程目录如下:

E:\LLF_58TESTSUITES\JZ_WEBINTERGRATION\ROBOT_CODE
│  execPybot.bat
│
├─pycode
│  │  Common_Excel.py
│  │  Common_Excel.pyc
│  │  Common_Exec.py
│  │  Common_Exec.pyc
│  │  testHTTP.py
│  │  __init__.py
│  │
│  ├─.idea
│  │  │  misc.xml
│  │  │  modules.xml
│  │  │  pycode.iml
│  │  │  workspace.xml
│  │  │
│  │  └─inspectionProfiles
│  └─__pycache__
│          Common_Excel.cpython-36.pyc
│          Common_Exec.cpython-36.pyc
│          __init__.cpython-36.pyc
│
├─report
│  │  log.html
│  │  output.xml
│  │  report.html
│  │
│  └─TestCaseReport
│      ├─result_calendar
│      │      log_20180130195712.html
│      │      output_20180130195712.xml
│      │      report_20180130195712.html
│      │
│      ├─result_getScheduleFlags
│      │      log_20180130195710.html
│      │      output_20180130195710.xml
│      │      report_20180130195710.html
│      │
│      └─result_showCityName
│              log_20180130195707.html
│              output_20180130195707.xml
│              report_20180130195707.html
│
├─rfcode
│  │  batch_Request.txt
│  │  http_Request.txt
│  │  __init__.robot
│  │
│  ├─关键字
│  │      关键字index.txt
│  │      自定义关键字.txt
│  │
│  └─配置信息
│          config.txt
│          configIndex.txt
│          RequestHeaders.txt
│
└─testData
        testData.xlsx

工程有4部分构成:

  • pycode
    由于robot中复杂逻辑的实现比较繁琐,所以将一些复杂逻辑直接用python代码实现,然后以外部库的形式导入robot中调用。共有2个文件:

Common_Excel.py
主要负责对测试数据excel文件的读取操作。

# coding: utf-8
import xlrd
def getTestData(testDataFile, testScene, host, caseNo):
    '''
    从excel中获取测试数据
    :param testDataFile: 测试数据文件
    :param testScene: 测试场景
    :param host: 服务器主机
    :param caseNo: 用例No
    :param method: 请求方法
    :return: url,用例No,用例名称,请求参数,预期返回码,预期响应内容
    '''
    caseNo = int(caseNo)
    data = xlrd.open_workbook(testDataFile)
    table = data.sheet_by_name(testScene)
    cols = table.ncols
 
    resource_path = table.cell(0, 1).value  # 文件路径
    url = "http://" + host + resource_path  # 访问的url
    method = table.cell(1, 1).value  # 请求方法
 
    dict_params = {}
    for i in range(cols):
        dict_params[table.cell(2, i).value] = table.cell(caseNo+2, i).value
 
    caseNo = dict_params.pop("caseNo")
    caseName = dict_params.pop("caseName")
    expectCode = dict_params.pop("expect_code")
    expectCotent = dict_params.pop("expect_content")
    testName = "TestCase" + caseNo + "_" + caseName
 
    return method, url, caseNo, testName, dict_params, expectCode, expectCotent
 
def getTestCaseNum(testDataFile, testScene):
    '''
    获取testScene测试场景中的测试用例数
    :param testDataFile: 测试数据文件
    :param testScene: 测试场景
    :return: 测试用例数
    '''
    data = xlrd.open_workbook(testDataFile)
    table = data.sheet_by_name(testScene)
    rows = table.nrows
    return rows-3
 
def getTestHttpMethod(testDataFile, testScene):
    '''
    获取testScene测试场景的请求方法
    :param testDataFile: 测试数据文件
    :param testScene: 测试场景
    :return: 请求方法
    '''
    data = xlrd.open_workbook(testDataFile)
    table = data.sheet_by_name(testScene)
    method = table.cell(1, 1).value  # 请求方法
    return method

Common_Exec.py
主要负责根据测试数据批量构造pybot命令来调用robot执行测试。

# coding: utf-8
import requests
import os
import time
 
def batch_Call(robot_testSuite, robot_testCase, testScene, caseNum, testCaseReportPath, execTime):
    '''
    批量执行testScene测试场景下的用例
    :param robot_testSuite: robot testSuite路径
    :param robot_testCase: robot testCase路径
    :param testScene: 测试场景
    :param caseNum: 用例数
    :param testCaseReportPath: 业务用例测试报告路径
    :param execTime: 执行时间
    :return:
    '''
    try:
        for caseNo in range(caseNum):
            testCase = ""
            caseNo = caseNo + 1
            testName = "testcase" + "_" + str(caseNo)
            output_dir = "-d " + testCaseReportPath + "/result_{0}".format(testScene)  # 输出目录
            output_xml = "-o output_{0}_{1}.xml".format(testName, execTime)
            output_log = "-l log_{0}_{1}.html".format(testName, execTime)
            output_report = "-r report_{0}_{1}.html".format(testName, execTime)
            variable = "-v caseNo:" + str(caseNo) + " -v testScene:" + testScene
            testCase = "--test " + robot_testCase
            pybot_cmd = "pybot " + output_dir + " " + output_xml + " " + output_log + " " + output_report + " " + variable + " " +  " " + testCase + " " + robot_testSuite
            os.system(pybot_cmd)  # 执行pybot命令
        return "done"
    except Exception as e:
        return "Error: " + str(e)
 
def send_HttpRequest(url, data=None, headers=None, method=None):
    '''
    发送http请求
    :param url: 请求的url
    :param data: 请求数据
    :param headers: 请求头
    :param method: 请求方法
    :return: 响应码,响应内容
    '''
    if method == "get":
        response = requests.get(url, data, headers=headers)
    if method == "post":
        response = requests.post(url, data, headers=headers)
    code = str(response.status_code)
    content = response.content.decode("utf-8")  # 转码
    return code, content
 
def cleanLogs(testScene, testCaseReportPath):
    '''
    删除硬盘中合并前的测试报告
    :param testScene: 测试场景
    :param testCaseReportPath: 业务用例测试报告路径
    :return:
    '''
    testCaseReportPath = testCaseReportPath + "/result_{0}".format(testScene)
    report_files = testCaseReportPath + "/report_testcase*"
    xml_files = testCaseReportPath + "/output_testcase*"
    log_files = testCaseReportPath + "/log_testcase*"
    cmd = "del " + report_files + " " + xml_files + " " + log_files  # windows
    cmd = cmd.replace("/", "\\")
    print(cmd)
    os.system(cmd)
 
def getCurtime():
    '''
    获取当前时间
    :return: 当前时间
    '''
    return time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
 
def mergeReport(testScene, testCaseReportPath, execTime):
    '''
    # 合并报告
    :param testScene: 测试场景
    :param testCaseReportPath: 业务用例测试报告路径
    :param execTime: 执行时间
    :return:
    '''
    try:
        output_dir = "-d " + testCaseReportPath + "/result_{0}".format(testScene)  # 输出目录
        output_xml = "-o output_{0}.xml".format(execTime)
        output_log = "-l log_{0}.html".format(execTime)
        output_report = "-r report_{0}.html".format(execTime)
        # 被合并的报告
        merge_report = testCaseReportPath + "/result_{0}".format(testScene) + "/output_testcase_*.xml"
        name = "--name " + testScene
        rebot_cmd = r"rebot " + output_dir + " " + output_xml + " " + output_log + " " + output_report + " " + name + " "  + merge_report
        os.system(rebot_cmd)  # 执行rebot命令
        return "done"
    except Exception as e:
        return "Error: " + str(e)

report
该目录用于存放测试报告。其中report目录下的robot测试报告为测试Suite的测试报告,而TestCaseReport下会根据不同的测试场景生成对应该场景名称的测试报告文件夹,其下会包含该测试场景下所有用例的合并报告(即excel中的每一条case会生成一个报告,最后会将这些cases的报告合并为一个报告,作为该测试场景即该http接口的测试报告)。

rfcode
该目录下为robot的代码。

batch_Request.txt
batch_Request下包含要测试的各http接口对应的测试场景(即robot的测试用例)。在各测试场景中会设置${testScene}变量,通过该变量去excel文件中对应的sheet页获取相应的测试数据。

*** Settings ***
Library           ../pycode/Common_Exec.py
Resource          关键字/关键字index.txt
Resource          配置信息/configIndex.txt
Library           ../pycode/Common_Excel.py
 
*** Test Cases ***
test_showCityName
    [Documentation]    /areaplug/showCityName
    # 测试场景
    ${testScene}    Set Variable    showCityName
    # 请求方法
    ${method}    getTestHttpMethod    ${testDataFile}    ${testScene}
    执行测试    ${testScene}    ${method}
 
test_getScheduleFlags
    [Documentation]    /ManageSchedule/getScheduleFlags
    # 测试场景
    ${testScene}    Set Variable    getScheduleFlags
    # 请求方法
    ${method}    getTestHttpMethod    ${testDataFile}    ${testScene}
    执行测试    ${testScene}    ${method}
 
test_calendar
    # 测试场景
    ${testScene}    Set Variable    calendar
    # 请求方法
    ${method}    getTestHttpMethod    ${testDataFile}    ${testScene}
    执行测试    ${testScene}    ${method}

http_Request.txt
在各测试场景中会根据excel中的测试用例记录数目去批量调用http_Request下的sendHttpRequest执行http接口测试。在sendHttpRequest中会根据caseNo去excel中查询相应测试数据,并发送对应的http请求到相应http接口中。收到响应后,与excel中的预期响应码和响应内容做比对。

*** Settings ***
Library           ../pycode/Common_Exec.py
Library           ../pycode/Common_Excel.py
Resource          关键字/关键字index.txt
 
*** Test Cases ***
sendHttpRequest
    # 获取测试用例数据
    ${method}    ${url}    ${caseNo}    ${testName}    ${dict_params}    ${expectCode}    ${expectCotent}
    ...    getTestData    ${testDataFile}    ${testScene}    ${Host}    ${caseNo}
    # 设置用例说明
    Set Test Documentation    ${testName}
    # 请求头
    ${headers}    获取请求头
    #根据method发送对应的http请求
    ${actualCode}    ${actualContent}    send_HttpRequest    ${url}    ${dict_params}    ${headers}    ${method}
    # 响应码比对
    Should Be Equal    ${actualCode}    ${expectCode}
    # 响应内容比对
    Should Be Equal    ${actualContent}    ${expectCotent}

关键字
关键字模块主要是对一些复用逻辑的封装。

*** Settings ***
Resource          ../配置信息/configIndex.txt
Library           ../../pycode/Common_Excel.py
Library           ../../pycode/Common_Exec.py
 
*** Keywords ***
获取请求头
    ${dict_headers}    Create Dictionary    Host=${Host}    User-Agent=${User-Agent}    Accept=${Accept}    Accept-Language=${Accept-Language}    Accept-Encoding=${Accept-Encoding}
    ...    Cookie=${Cookie}    Connection=${Connection}    Cache-Control=${Cache-Control}
    Return From Keyword    ${dict_headers}
 
执行测试
    [Arguments]    ${testScene}    ${method}    # 测试场景|请求方法
    # 获取用例数目
    ${case_num}    getTestCaseNum    ${testDataFile}    ${testScene}
    # 获取当前时间
    ${execTime}    getCurtime
    #批量执行testScene测试场景下的用例
    ${status}    batch_Call    ${httpTestSuite}    ${httpRequestTestCase}    ${testScene}    ${case_num}    ${testCaseReportPath}
    ...    ${execTime}
    log    ${status}
    # 合并报告
    ${status}    mergeReport    ${testScene}    ${testCaseReportPath}    ${execTime}
    log    ${status}
    # 清理合并前的报告
    cleanLogs    ${testScene}    ${testCaseReportPath}

配置信息
配置信息中存储配置信息以及通讯头的信息。通讯头中有cookie,保存有登录信息,通讯头的部分涉及隐私,故这部分数据不放出来了。
config.txt

*** Settings ***
 
*** Variables ***
${testDataFile}    E:/llf_58TestSuites/jz_webIntergration/robot_code/testData/testData.xlsx    # 测试数据
${httpRequestTestCase}    sendHttpRequest    # http请求用例模板
${httpTestSuite}    E:/llf_58TestSuites/jz_webIntergration/robot_code/rfcode/http_Request.txt    # http请求测试套件
${testCaseReportPath}    E:/llf_58TestSuites/jz_webIntergration/robot_code/report/TestCaseReport    # 业务用例测试报告路径

RequestHeaders.txt

*** Settings ***
Documentation     请求头信息
 
*** Variables ***
${Host}           *******    # 服务器主机
${User-Agent}     Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0    # 浏览器代理
${Accept}         text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
${Accept-Language}    en-US,en;q=0.5
${Accept-Encoding}    gzip, deflate
${Cookie}         ************
${Connection}     keep-alive
${Cache-Control}    max-age=0
${Upgrade-Insecure-Requests}    ***
  • testData
    该目录下存放测试数据excel文件。
执行测试
pybot -d E:/llf_58TestSuites/jz_webIntergration/robot_code/report -o output.xml -l log.html -r report.html E:\llf_58TestSuites\jz_webIntergration\robot_code\rfcode\batch_Request.txt

执行测试

可见,showCityName测试场景已根据excel中的用例条数批量执行了测试。

进入TestCaseReport目录,可以看到已根据测试场景分别生成了对应目录的测试报告: 

各测试场景的报告存在相应目录中

进入showCityName目录,打开最新生成的该场景测试报告:

showCityName场景测试报告

根据说明列辨别是哪条用例的报告数据

sendHttpRequest被批量调用

总结
经过了上一个项目吃过的亏,这次在http接口测试需求前,提前把自动化框架搭好了,便于测试后期的回归测试。其实http接口自动化测试框架可以很方便的搭建,之所以这么费劲用robot去实现,也是为了后续用例管理以及集成到平台实现工具化的考虑结果。希望这篇文章可以对其他同学有所帮助。

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你! 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/144982.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

MHA的那些事儿

什么是MHA? masterhight availability:基于主库的高可用环境下,主从复制和故障切换 主从的架构 MHA至少要一主两从 出现的目的:解决MySQL的单点故障问题。一旦主库崩溃,MHA可以在0-30s内自动完成故障切换 MHA使用的…

[MySQL] MySQL中的数据类型

在MySQL中,数据类型用于定义表中列的数据的类型。在前面的几篇文章中,我们也会看到有很多的数据类型,例如:char、varchar、date、int等等。本篇文章会对常见的数据类型进行详细讲解。希望会对你有所帮助! 文章目录 一、…

海康G5系列(armv7l) heop模式下交叉编译Qt qmqtt demo,出现moc缺少高版本GLibc问题之解决

1.编辑源 sudo vi /etc/apt/sources.list 2.添加高版本的源 deb http://th.archive.ubuntu.com/ubuntu jammy main #添加该行到文件 3.运行升级 sudo apt update sudo apt install libc6 4.strings /**/libc.so.6 |grep GLIBC_ 参考链接:version GLIBC_2.3…

github 私人仓库clone的问题

github 私人仓库clone的问题 公共仓库直接克隆就可以,私人仓库需要权限验证,要先申请token 1、登录到github,点击setting 打开的页面最底下,有一个developer setting 这里申请到token之后,注意要保存起来&#xff…

【Python+requests+unittest+excel】实现接口自动化测试框架

一、框架结构: 工程目录 二、Case文件设计 三、基础包 base3.1 封装get/post请求(runmethon.py) 1 import requests2 import json3 class RunMethod:4 def post_main(self,url,data,headerNone):5 res None6 if header …

Stable Diffusion新手村-我们一起完成AI绘画

1.工具搭建 感谢bilibili的"秋葉aaaki"大佬出的整合包,让我们方便下载安装一键启动,去它的网盘里下载 我的显卡设备,暂时还够哈,出图速度还可以1-2分钟比较美的质感画面 下载以后需要解压下sd-webui-aki-v4.4.7z&#…

spring-cloud-alibaba-sentinel

sentinel (哨兵) 简介 # 官网 - https://spring-cloud-alibaba-group.github.io/github-pages/hoxton/en-us/index.html#_spring_cloud_alibaba_sentinel # github - https://github.com/alibaba/Sentinel/wiki# 简介 - 随着微服务的普及,服务调用的稳定性变得越来…

Eigen的基操

转自博客 博客

浏览器Cookie是什么?如何在MaskFog指纹浏览器中导入Cookie?

在使用互联网时我们常常听到cookie这个词,那到底什么是cookie呢? Cookie是某些网站为了辨别用户身份而储存在用户本地终端上的数据(通常经过加密),由用户客户端计算机暂时或永久保存的信息客户端向服务器发起请求&…

【23真题】易,学硕爆冷,题目常规!

今天分享的是23年广州大学823的信号与系统试题及解析。广州大学23年学硕爆冷,一志愿全部录取,不知道24情况将如何。我们拭目以待! 本套试卷难度分析:本套试题内容难度中等偏下,考察的知识点都是比较常见的&#xff0c…

如何使用线性模型的【分箱】操作处理非线性问题

让线性回归在非线性数据上表现提升的核心方法之一是对数据进行分箱,也就是离散化。与线性回归相比,我们常用的一种回归是决策树的回归。为了对比不同分类器和分箱前后拟合效果的差异,我们设置对照实验。 生成一个非线性数据集前,…

【论文阅读】(CTGAN)Modeling Tabular data using Conditional GAN

论文地址:[1907.00503] Modeling Tabular data using Conditional GAN (arxiv.org) 摘要 对表格数据中行的概率分布进行建模并生成真实的合成数据是一项非常重要的任务,有着许多挑战。本文设计了CTGAN,使用条件生成器解决挑战。为了帮助进行公…

flutter下拉列表

下拉列表 内容和下拉列表的标题均可滑动 Expanded: 内容限制组件,将其子类中的无限扩展的界面限制在一定范围中。在此使用,是为了防止下拉列表中的内容超过了屏幕限制。 SingleChildScrollView: 这个组件,从名字中可…

C++——友元函数

如下是一个日期类&#xff1a; class Date { public:Date(int year 2023, int month 10, int day 1){_year year;_month month;_day day;if (_month < 1 || month > 12 || _day < 1 || _day > GetMonthDay(_year, _month)){cout << "日期不规范&…

元数据管理,数字化时代企业的基础建设

随着新一代信息化、数字化技术的应用&#xff0c;众多领域通过科技革命和产业革命实现了深度化的数字改造&#xff0c;进入到以数据为核心驱动力的&#xff0c;全新的数据处理时代&#xff0c;并通过业务系统、商业智能BI等数字化技术和应用实现了数据价值&#xff0c;从数字经…

hadoop 如何关闭集群 hadoop使用脚本关闭集群 hadoop(八)

1. hadoop22, hadoop23, hadoop24三台机器 2. namenode 所在hadoop22关闭 hdfs: # 找到/etc/hadoop位置 cd /opt/module/hadoop-3.3.4/etc/hadoop # 找到shell脚本&#xff0c;关闭即可sbin/stop-dfs.sh 3. 关闭yarn脚本&#xff0c;我的在hadoop23&#xff1a; # 找到/etc…

【云原生进阶之PaaS中间件】第三章Kafka-1-综述

1 Kafka简介 Kafka是最初由Linkedin公司开发&#xff0c;是一个分布式、支持分区的&#xff08;partition&#xff09;、多副本的&#xff08;replica&#xff09;&#xff0c;基于zookeeper协调的分布式消息系统&#xff0c;它的最大的特性就是可以实时的处理大量数据以满足各…

数据同步到Redis消息队列,并实现消息发布/订阅

一、假设需求&#xff1a; 某系统在MySQL某表中操作了一条数据在其他系统中&#xff0c;实时获取最新被操作数据的数据库名、数据表名、操作类型、数据内容 应用场景&#xff1a; 按最近项目的一个需求来说&#xff1a; 1.当某子系统向报警表中新增了一条报警数据&#xff1b;…

如何实现Redisson分布式锁

首先&#xff0c;不要将分布式锁想的太复杂&#xff0c;如果我们只是平时业务中去使用&#xff0c;其实不算难&#xff0c;但是很多人写的文章不能让人快速上手&#xff0c;接下来&#xff0c;一起看下Redisson分布式锁的快速实现 Redisson 是一个在 Redis 的基础上实现的 Java…

java导出excel思路

1、构建导出的数据模型&#xff0c; 这个模型可以自己画&#xff0c;也可以读取一个自己制作好的模板&#xff0c;根据模板填充数据&#xff0c;然后flush到一个新的excel文件。 1&#xff09;、自己画 GetMapping("/exportTemplate") public void exportTemp…
最新文章