• 【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,实际回归测试时,会有大量的用例和数据): 

    测试数据

    测试框架

    整个工程目录如下:

    1. E:\LLF_58TESTSUITES\JZ_WEBINTERGRATION\ROBOT_CODE
    2. │ execPybot.bat
    3. ├─pycode
    4. │ │ Common_Excel.py
    5. │ │ Common_Excel.pyc
    6. │ │ Common_Exec.py
    7. │ │ Common_Exec.pyc
    8. │ │ testHTTP.py
    9. │ │ __init__.py
    10. │ │
    11. │ ├─.idea
    12. │ │ │ misc.xml
    13. │ │ │ modules.xml
    14. │ │ │ pycode.iml
    15. │ │ │ workspace.xml
    16. │ │ │
    17. │ │ └─inspectionProfiles
    18. │ └─__pycache__
    19. Common_Excel.cpython-36.pyc
    20. Common_Exec.cpython-36.pyc
    21. │ __init__.cpython-36.pyc
    22. ├─report
    23. │ │ log.html
    24. │ │ output.xml
    25. │ │ report.html
    26. │ │
    27. │ └─TestCaseReport
    28. │ ├─result_calendar
    29. │ │ log_20180130195712.html
    30. │ │ output_20180130195712.xml
    31. │ │ report_20180130195712.html
    32. │ │
    33. │ ├─result_getScheduleFlags
    34. │ │ log_20180130195710.html
    35. │ │ output_20180130195710.xml
    36. │ │ report_20180130195710.html
    37. │ │
    38. │ └─result_showCityName
    39. │ log_20180130195707.html
    40. output_20180130195707.xml
    41. report_20180130195707.html
    42. ├─rfcode
    43. │ │ batch_Request.txt
    44. │ │ http_Request.txt
    45. │ │ __init__.robot
    46. │ │
    47. │ ├─关键字
    48. │ │ 关键字index.txt
    49. │ │ 自定义关键字.txt
    50. │ │
    51. │ └─配置信息
    52. │ config.txt
    53. │ configIndex.txt
    54. │ RequestHeaders.txt
    55. └─testData
    56. testData.xlsx

    工程有4部分构成:

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

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

    1. # coding: utf-8
    2. import xlrd
    3. def getTestData(testDataFile, testScene, host, caseNo):
    4. '''
    5. 从excel中获取测试数据
    6. :param testDataFile: 测试数据文件
    7. :param testScene: 测试场景
    8. :param host: 服务器主机
    9. :param caseNo: 用例No
    10. :param method: 请求方法
    11. :return: url,用例No,用例名称,请求参数,预期返回码,预期响应内容
    12. '''
    13. caseNo = int(caseNo)
    14. data = xlrd.open_workbook(testDataFile)
    15. table = data.sheet_by_name(testScene)
    16. cols = table.ncols
    17. resource_path = table.cell(0, 1).value # 文件路径
    18. url = "http://" + host + resource_path # 访问的url
    19. method = table.cell(1, 1).value # 请求方法
    20. dict_params = {}
    21. for i in range(cols):
    22. dict_params[table.cell(2, i).value] = table.cell(caseNo+2, i).value
    23. caseNo = dict_params.pop("caseNo")
    24. caseName = dict_params.pop("caseName")
    25. expectCode = dict_params.pop("expect_code")
    26. expectCotent = dict_params.pop("expect_content")
    27. testName = "TestCase" + caseNo + "_" + caseName
    28. return method, url, caseNo, testName, dict_params, expectCode, expectCotent
    29. def getTestCaseNum(testDataFile, testScene):
    30. '''
    31. 获取testScene测试场景中的测试用例数
    32. :param testDataFile: 测试数据文件
    33. :param testScene: 测试场景
    34. :return: 测试用例数
    35. '''
    36. data = xlrd.open_workbook(testDataFile)
    37. table = data.sheet_by_name(testScene)
    38. rows = table.nrows
    39. return rows-3
    40. def getTestHttpMethod(testDataFile, testScene):
    41. '''
    42. 获取testScene测试场景的请求方法
    43. :param testDataFile: 测试数据文件
    44. :param testScene: 测试场景
    45. :return: 请求方法
    46. '''
    47. data = xlrd.open_workbook(testDataFile)
    48. table = data.sheet_by_name(testScene)
    49. method = table.cell(1, 1).value # 请求方法
    50. return method

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

    1. # coding: utf-8
    2. import requests
    3. import os
    4. import time
    5. def batch_Call(robot_testSuite, robot_testCase, testScene, caseNum, testCaseReportPath, execTime):
    6. '''
    7. 批量执行testScene测试场景下的用例
    8. :param robot_testSuite: robot testSuite路径
    9. :param robot_testCase: robot testCase路径
    10. :param testScene: 测试场景
    11. :param caseNum: 用例数
    12. :param testCaseReportPath: 业务用例测试报告路径
    13. :param execTime: 执行时间
    14. :return:
    15. '''
    16. try:
    17. for caseNo in range(caseNum):
    18. testCase = ""
    19. caseNo = caseNo + 1
    20. testName = "testcase" + "_" + str(caseNo)
    21. output_dir = "-d " + testCaseReportPath + "/result_{0}".format(testScene) # 输出目录
    22. output_xml = "-o output_{0}_{1}.xml".format(testName, execTime)
    23. output_log = "-l log_{0}_{1}.html".format(testName, execTime)
    24. output_report = "-r report_{0}_{1}.html".format(testName, execTime)
    25. variable = "-v caseNo:" + str(caseNo) + " -v testScene:" + testScene
    26. testCase = "--test " + robot_testCase
    27. pybot_cmd = "pybot " + output_dir + " " + output_xml + " " + output_log + " " + output_report + " " + variable + " " + " " + testCase + " " + robot_testSuite
    28. os.system(pybot_cmd) # 执行pybot命令
    29. return "done"
    30. except Exception as e:
    31. return "Error: " + str(e)
    32. def send_HttpRequest(url, data=None, headers=None, method=None):
    33. '''
    34. 发送http请求
    35. :param url: 请求的url
    36. :param data: 请求数据
    37. :param headers: 请求头
    38. :param method: 请求方法
    39. :return: 响应码,响应内容
    40. '''
    41. if method == "get":
    42. response = requests.get(url, data, headers=headers)
    43. if method == "post":
    44. response = requests.post(url, data, headers=headers)
    45. code = str(response.status_code)
    46. content = response.content.decode("utf-8") # 转码
    47. return code, content
    48. def cleanLogs(testScene, testCaseReportPath):
    49. '''
    50. 删除硬盘中合并前的测试报告
    51. :param testScene: 测试场景
    52. :param testCaseReportPath: 业务用例测试报告路径
    53. :return:
    54. '''
    55. testCaseReportPath = testCaseReportPath + "/result_{0}".format(testScene)
    56. report_files = testCaseReportPath + "/report_testcase*"
    57. xml_files = testCaseReportPath + "/output_testcase*"
    58. log_files = testCaseReportPath + "/log_testcase*"
    59. cmd = "del " + report_files + " " + xml_files + " " + log_files # windows
    60. cmd = cmd.replace("/", "\\")
    61. print(cmd)
    62. os.system(cmd)
    63. def getCurtime():
    64. '''
    65. 获取当前时间
    66. :return: 当前时间
    67. '''
    68. return time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
    69. def mergeReport(testScene, testCaseReportPath, execTime):
    70. '''
    71. # 合并报告
    72. :param testScene: 测试场景
    73. :param testCaseReportPath: 业务用例测试报告路径
    74. :param execTime: 执行时间
    75. :return:
    76. '''
    77. try:
    78. output_dir = "-d " + testCaseReportPath + "/result_{0}".format(testScene) # 输出目录
    79. output_xml = "-o output_{0}.xml".format(execTime)
    80. output_log = "-l log_{0}.html".format(execTime)
    81. output_report = "-r report_{0}.html".format(execTime)
    82. # 被合并的报告
    83. merge_report = testCaseReportPath + "/result_{0}".format(testScene) + "/output_testcase_*.xml"
    84. name = "--name " + testScene
    85. rebot_cmd = r"rebot " + output_dir + " " + output_xml + " " + output_log + " " + output_report + " " + name + " " + merge_report
    86. os.system(rebot_cmd) # 执行rebot命令
    87. return "done"
    88. except Exception as e:
    89. 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页获取相应的测试数据。

    1. *** Settings ***
    2. Library ../pycode/Common_Exec.py
    3. Resource 关键字/关键字index.txt
    4. Resource 配置信息/configIndex.txt
    5. Library ../pycode/Common_Excel.py
    6. *** Test Cases ***
    7. test_showCityName
    8. [Documentation] /areaplug/showCityName
    9. # 测试场景
    10. ${testScene} Set Variable showCityName
    11. # 请求方法
    12. ${method} getTestHttpMethod ${testDataFile} ${testScene}
    13. 执行测试 ${testScene} ${method}
    14. test_getScheduleFlags
    15. [Documentation] /ManageSchedule/getScheduleFlags
    16. # 测试场景
    17. ${testScene} Set Variable getScheduleFlags
    18. # 请求方法
    19. ${method} getTestHttpMethod ${testDataFile} ${testScene}
    20. 执行测试 ${testScene} ${method}
    21. test_calendar
    22. # 测试场景
    23. ${testScene} Set Variable calendar
    24. # 请求方法
    25. ${method} getTestHttpMethod ${testDataFile} ${testScene}
    26. 执行测试 ${testScene} ${method}

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

    1. *** Settings ***
    2. Library ../pycode/Common_Exec.py
    3. Library ../pycode/Common_Excel.py
    4. Resource 关键字/关键字index.txt
    5. *** Test Cases ***
    6. sendHttpRequest
    7. # 获取测试用例数据
    8. ${method} ${url} ${caseNo} ${testName} ${dict_params} ${expectCode} ${expectCotent}
    9. ... getTestData ${testDataFile} ${testScene} ${Host} ${caseNo}
    10. # 设置用例说明
    11. Set Test Documentation ${testName}
    12. # 请求头
    13. ${headers} 获取请求头
    14. #根据method发送对应的http请求
    15. ${actualCode} ${actualContent} send_HttpRequest ${url} ${dict_params} ${headers} ${method}
    16. # 响应码比对
    17. Should Be Equal ${actualCode} ${expectCode}
    18. # 响应内容比对
    19. Should Be Equal ${actualContent} ${expectCotent}

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

    1. *** Settings ***
    2. Resource ../配置信息/configIndex.txt
    3. Library ../../pycode/Common_Excel.py
    4. Library ../../pycode/Common_Exec.py
    5. *** Keywords ***
    6. 获取请求头
    7. ${dict_headers} Create Dictionary Host=${Host} User-Agent=${User-Agent} Accept=${Accept} Accept-Language=${Accept-Language} Accept-Encoding=${Accept-Encoding}
    8. ... Cookie=${Cookie} Connection=${Connection} Cache-Control=${Cache-Control}
    9. Return From Keyword ${dict_headers}
    10. 执行测试
    11. [Arguments] ${testScene} ${method} # 测试场景|请求方法
    12. # 获取用例数目
    13. ${case_num} getTestCaseNum ${testDataFile} ${testScene}
    14. # 获取当前时间
    15. ${execTime} getCurtime
    16. #批量执行testScene测试场景下的用例
    17. ${status} batch_Call ${httpTestSuite} ${httpRequestTestCase} ${testScene} ${case_num} ${testCaseReportPath}
    18. ... ${execTime}
    19. log ${status}
    20. # 合并报告
    21. ${status} mergeReport ${testScene} ${testCaseReportPath} ${execTime}
    22. log ${status}
    23. # 清理合并前的报告
    24. cleanLogs ${testScene} ${testCaseReportPath}

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

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

    RequestHeaders.txt

    1. *** Settings ***
    2. Documentation 请求头信息
    3. *** Variables ***
    4. ${Host} ******* # 服务器主机
    5. ${User-Agent} Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0 # 浏览器代理
    6. ${Accept} text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    7. ${Accept-Language} en-US,en;q=0.5
    8. ${Accept-Encoding} gzip, deflate
    9. ${Cookie} ************
    10. ${Connection} keep-alive
    11. ${Cache-Control} max-age=0
    12. ${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去实现,也是为了后续用例管理以及集成到平台实现工具化的考虑结果。希望这篇文章可以对其他同学有所帮助。

  • 相关阅读:
    linu入门9—操作系统正则符号
    PCE模型,FomoCat为何发起反Web3空气资产的社区试验
    presto和hive中grouping sets的格式不一致问题
    第三次工业革命(四)
    神经网络方法研究及应用,神经网络优化遗传算法
    虚析构+纯虚函数+抽象类+友元
    buuctf_练[GYCTF2020]FlaskApp
    linux应用hook实例(含源码分析)
    【子网,超网和掩码】
    单片机理论1
  • 原文地址:https://blog.csdn.net/2301_76643199/article/details/132980127