1. 程式人生 > >robot framework + python實現http接口自動化測試框架

robot framework + python實現http接口自動化測試框架

accept testsuite def max IV 每一個 聯系 ria method

https://www.jianshu.com/p/6d1e8cb90e7d

前言

下周即將展開一個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去實現,也是為了後續用例管理以及集成到平臺實現工具化的考慮結果。希望這篇文章可以對其他同學有所幫助。



作者:Ivanli1990
鏈接:https://www.jianshu.com/p/6d1e8cb90e7d
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請註明出處。

robot framework + python實現http接口自動化測試框架