最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python http接口自動(dòng)化測(cè)試框架實(shí)現(xiàn)方法示例

 更新時(shí)間:2018年12月06日 09:44:20   作者:slq520  
這篇文章主要介紹了Python http接口自動(dòng)化測(cè)試框架實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Python針對(duì)http接口測(cè)試的相關(guān)實(shí)現(xiàn)與使用操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python http接口自動(dòng)化測(cè)試框架實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:

一、測(cè)試需求描述

對(duì)服務(wù)后臺(tái)一系列的http接口功能測(cè)試。

輸入:根據(jù)接口描述構(gòu)造不同的參數(shù)輸入值

輸出:XML文件

eg:http://xxx.com/xxx_product/test/content_book_list.jsp?listid=1

二、實(shí)現(xiàn)方法

1、選用Python腳本來(lái)驅(qū)動(dòng)測(cè)試

2、采用Excel表格管理測(cè)試數(shù)據(jù),包括用例的管理、測(cè)試數(shù)據(jù)錄入、測(cè)試結(jié)果顯示等等,這個(gè)需要封裝一個(gè)Excel的類即可。

3、調(diào)用http接口采用Python封裝好的API即可

4、測(cè)試需要的http組裝字符轉(zhuǎn)處理即可

5、設(shè)置2個(gè)檢查點(diǎn),XML文件中的返回值字段(通過(guò)解析XML得到);XML文件的正確性(文件對(duì)比)

6、首次執(zhí)行測(cè)試采用半自動(dòng)化的方式,即人工檢查輸出的XML文件是否正確,一旦正確將封存XML文件,為后續(xù)回歸測(cè)試的預(yù)期結(jié)果,如果發(fā)現(xiàn)錯(cuò)誤手工修正為預(yù)期文件。(注意不是每次測(cè)試都人工檢查該文件,只首次測(cè)試的時(shí)候才檢查)

三、Excel表格樣式

四、實(shí)現(xiàn)代碼(代碼才是王道,有注釋很容易就能看明白的)

1、測(cè)試框架代碼

#****************************************************************
# TestFrame.py
# Author   : Vince
# Version  : 1.1.2
# Date    : 2011-3-14
# Description: 自動(dòng)化測(cè)試平臺(tái)
#****************************************************************
import os,sys, urllib, httplib, profile, datetime, time
from xml2dict import XML2Dict
import win32com.client
from win32com.client import Dispatch
import xml.etree.ElementTree as et
#import MySQLdb
#Excel表格中測(cè)試結(jié)果底色
OK_COLOR=0xffffff
NG_COLOR=0xff
#NT_COLOR=0xffff
NT_COLOR=0xC0C0C0
#Excel表格中測(cè)試結(jié)果匯總顯示位置
TESTTIME=[1, 14]
TESTRESULT=[2, 14]
#Excel模版設(shè)置
#self.titleindex=3    #Excel中測(cè)試用例標(biāo)題行索引
#self.casebegin =4    #Excel中測(cè)試用例開(kāi)始行索引
#self.argbegin  =3    #Excel中參數(shù)開(kāi)始列索引
#self.argcount =8    #Excel中支持的參數(shù)個(gè)數(shù)
class create_excel:
  def __init__(self, sFile, dtitleindex=3, dcasebegin=4, dargbegin=3, dargcount=8):
    self.xlApp = win32com.client.Dispatch('et.Application')  #MS:Excel WPS:et
    try:
      self.book = self.xlApp.Workbooks.Open(sFile)
    except:
      print_error_info()
      print "打開(kāi)文件失敗"
      exit()
    self.file=sFile
    self.titleindex=dtitleindex
    self.casebegin=dcasebegin
    self.argbegin=dargbegin
    self.argcount=dargcount
    self.allresult=[]
    self.retCol=self.argbegin+self.argcount
    self.xmlCol=self.retCol+1
    self.resultCol=self.xmlCol+1
  def close(self):
    #self.book.Close(SaveChanges=0)
    self.book.Save()
    self.book.Close()
    #self.xlApp.Quit()
    del self.xlApp
  def read_data(self, iSheet, iRow, iCol):
    try:
      sht = self.book.Worksheets(iSheet)
      sValue=str(sht.Cells(iRow, iCol).Value)
    except:
      self.close()
      print('讀取數(shù)據(jù)失敗')
      exit()
    #去除'.0'
    if sValue[-2:]=='.0':
      sValue = sValue[0:-2]
    return sValue
  def write_data(self, iSheet, iRow, iCol, sData, color=OK_COLOR):
    try:
      sht = self.book.Worksheets(iSheet)
      sht.Cells(iRow, iCol).Value = sData.decode("utf-8")
      sht.Cells(iRow, iCol).Interior.Color=color
      self.book.Save()
    except:
      self.close()
      print('寫入數(shù)據(jù)失敗')
      exit()
  #獲取用例個(gè)數(shù)
  def get_ncase(self, iSheet):
    try:
      return self.get_nrows(iSheet)-self.casebegin+1
    except:
      self.close()
      print('獲取Case個(gè)數(shù)失敗')
      exit()
  def get_nrows(self, iSheet):
    try:
      sht = self.book.Worksheets(iSheet)
      return sht.UsedRange.Rows.Count
    except:
      self.close()
      print('獲取nrows失敗')
      exit()
  def get_ncols(self, iSheet):
    try:
      sht = self.book.Worksheets(iSheet)
      return sht.UsedRange.Columns.Count
    except:
      self.close()
      print('獲取ncols失敗')
      exit()
  def del_testrecord(self, suiteid):
    try:
      #為提升性能特別從For循環(huán)提取出來(lái)
      nrows=self.get_nrows(suiteid)+1
      ncols=self.get_ncols(suiteid)+1
      begincol=self.argbegin+self.argcount
      #提升性能
      sht = self.book.Worksheets(suiteid)
      for row in range(self.casebegin, nrows):
        for col in range(begincol, ncols):
          str=self.read_data(suiteid, row, col)
          #清除實(shí)際結(jié)果[]
          startpos = str.find('[')
          if startpos>0:
            str = str[0:startpos].strip()
            self.write_data(suiteid, row, col, str, OK_COLOR)
          else:
            #提升性能
            sht.Cells(row, col).Interior.Color = OK_COLOR
        #清除TestResul列中的測(cè)試結(jié)果,設(shè)置為NT
        self.write_data(suiteid, row, self.argbegin+self.argcount+1, ' ', OK_COLOR)
        self.write_data(suiteid, row, self.resultCol, 'NT', NT_COLOR)
    except:
      self.close()
      print('清除數(shù)據(jù)失敗')
      exit()
#執(zhí)行調(diào)用
def HTTPInvoke(IPPort, url):
  conn = httplib.HTTPConnection(IPPort)
  conn.request("GET", url)
  rsps = conn.getresponse()
  data = rsps.read()
  conn.close()
  return data
#獲取用例基本信息[Interface,argcount,[ArgNameList]]
def get_caseinfo(Data, SuiteID):
  caseinfolist=[]
  sInterface=Data.read_data(SuiteID, 1, 2)
  argcount=int(Data.read_data(SuiteID, 2, 2))
  #獲取參數(shù)名存入ArgNameList
  ArgNameList=[]
  for i in range(0, argcount):
    ArgNameList.append(Data.read_data(SuiteID, Data.titleindex, Data.argbegin+i))
  caseinfolist.append(sInterface)
  caseinfolist.append(argcount)
  caseinfolist.append(ArgNameList)
  return caseinfolist
#獲取輸入
def get_input(Data, SuiteID, CaseID, caseinfolist):
  sArge=''
  #參數(shù)組合
  for j in range(0, caseinfolist[1]):
    if Data.read_data(SuiteID, Data.casebegin+CaseID, Data.argbegin+j) != "None":
      sArge=sArge+caseinfolist[2][j]+'='+Data.read_data(SuiteID, Data.casebegin+CaseID, Data.argbegin+j)+'&'
  #去掉結(jié)尾的&字符
  if sArge[-1:]=='&':
    sArge = sArge[0:-1]
  sInput=caseinfolist[0]+sArge  #組合全部參數(shù)
  return sInput
#結(jié)果判斷
def assert_result(sReal, sExpect):
  sReal=str(sReal)
  sExpect=str(sExpect)
  if sReal==sExpect:
    return 'OK'
  else:
    return 'NG'
#將測(cè)試結(jié)果寫入文件
def write_result(Data, SuiteId, CaseId, resultcol, *result):
  if len(result)>1:
    ret='OK'
    for i in range(0, len(result)):
      if result[i]=='NG':
        ret='NG'
        break
    if ret=='NG':
      Data.write_data(SuiteId, Data.casebegin+CaseId, resultcol,ret, NG_COLOR)
    else:
      Data.write_data(SuiteId, Data.casebegin+CaseId, resultcol,ret, OK_COLOR)
    Data.allresult.append(ret)
  else:
    if result[0]=='NG':
      Data.write_data(SuiteId, Data.casebegin+CaseId, resultcol,result[0], NG_COLOR)
    elif result[0]=='OK':
      Data.write_data(SuiteId, Data.casebegin+CaseId, resultcol,result[0], OK_COLOR)
    else: #NT
      Data.write_data(SuiteId, Data.casebegin+CaseId, resultcol,result[0], NT_COLOR)
    Data.allresult.append(result[0])
  #將當(dāng)前結(jié)果立即打印
  print 'case'+str(CaseId+1)+':', Data.allresult[-1]
#打印測(cè)試結(jié)果
def statisticresult(excelobj):
  allresultlist=excelobj.allresult
  count=[0, 0, 0]
  for i in range(0, len(allresultlist)):
    #print 'case'+str(i+1)+':', allresultlist[i]
    count=countflag(allresultlist[i],count[0], count[1], count[2])
  print 'Statistic result as follow:'
  print 'OK:', count[0]
  print 'NG:', count[1]
  print 'NT:', count[2]
#解析XmlString返回Dict
def get_xmlstring_dict(xml_string):
  xml = XML2Dict()
  return xml.fromstring(xml_string)
#解析XmlFile返回Dict
def get_xmlfile_dict(xml_file):
  xml = XML2Dict()
  return xml.parse(xml_file)
#去除歷史數(shù)據(jù)expect[real]
def delcomment(excelobj, suiteid, iRow, iCol, str):
  startpos = str.find('[')
  if startpos>0:
    str = str[0:startpos].strip()
    excelobj.write_data(suiteid, iRow, iCol, str, OK_COLOR)
  return str
#檢查每個(gè)item (非結(jié)構(gòu)體)
def check_item(excelobj, suiteid, caseid,real_dict, checklist, begincol):
  ret='OK'
  for checkid in range(0, len(checklist)):
    real=real_dict[checklist[checkid]]['value']
    expect=excelobj.read_data(suiteid, excelobj.casebegin+caseid, begincol+checkid)
    #如果檢查不一致測(cè)將實(shí)際結(jié)果寫入expect字段,格式:expect[real]
    #將return NG
    result=assert_result(real, expect)
    if result=='NG':
      writestr=expect+'['+real+']'
      excelobj.write_data(suiteid, excelobj.casebegin+caseid, begincol+checkid, writestr, NG_COLOR)
      ret='NG'
  return ret
#檢查結(jié)構(gòu)體類型
def check_struct_item(excelobj, suiteid, caseid,real_struct_dict, structlist, structbegin, structcount):
  ret='OK'
  if structcount>1: #傳入的是List
    for structid in range(0, structcount):
      structdict=real_struct_dict[structid]
      temp=check_item(excelobj, suiteid, caseid,structdict, structlist, structbegin+structid*len(structlist))
      if temp=='NG':
        ret='NG'
  else: #傳入的是Dict
    temp=check_item(excelobj, suiteid, caseid,real_struct_dict, structlist, structbegin)
    if temp=='NG':
      ret='NG'
  return ret
#獲取異常函數(shù)及行號(hào)
def print_error_info():
  """Return the frame object for the caller's stack frame."""
  try:
    raise Exception
  except:
    f = sys.exc_info()[2].tb_frame.f_back
  print (f.f_code.co_name, f.f_lineno)
#測(cè)試結(jié)果計(jì)數(shù)器,類似Switch語(yǔ)句實(shí)現(xiàn)
def countflag(flag,ok, ng, nt):
  calculation = {'OK':lambda:[ok+1, ng, nt],
             'NG':lambda:[ok, ng+1, nt],
             'NT':lambda:[ok, ng, nt+1]}
  return calculation[flag]()

2、項(xiàng)目測(cè)試代碼

# -*- coding: utf-8 -*-
#****************************************************************
# xxx_server_case.py
# Author   : Vince
# Version  : 1.0
# Date    : 2011-3-10
# Description: 內(nèi)容服務(wù)系統(tǒng)測(cè)試代碼
#****************************************************************
from testframe import *
from common_lib import *
httpString='http://xxx.com/xxx_product/test/'
expectXmldir=os.getcwd()+'/TestDir/expect/'
realXmldir=os.getcwd()+'/TestDir/real/'
def run(interface_name, suiteid):
  print '【'+interface_name+'】' + ' Test Begin,please waiting...'
  global expectXmldir, realXmldir
  #根據(jù)接口名分別創(chuàng)建預(yù)期結(jié)果目錄和實(shí)際結(jié)果目錄
  expectDir=expectXmldir+interface_name
  realDir=realXmldir+interface_name
  if os.path.exists(expectDir) == 0:
    os.makedirs(expectDir)
  if os.path.exists(realDir) == 0:
    os.makedirs(realDir)
  excelobj.del_testrecord(suiteid) #清除歷史測(cè)試數(shù)據(jù)
  casecount=excelobj.get_ncase(suiteid) #獲取case個(gè)數(shù)
  caseinfolist=get_caseinfo(excelobj, suiteid) #獲取Case基本信息
  #遍歷執(zhí)行case
  for caseid in range(0, casecount):
    #檢查是否執(zhí)行該Case
    if excelobj.read_data(suiteid,excelobj.casebegin+caseid, 2)=='N':
      write_result(excelobj, suiteid, caseid, excelobj.resultCol, 'NT')
      continue #當(dāng)前Case結(jié)束,繼續(xù)執(zhí)行下一個(gè)Case
    #獲取測(cè)試數(shù)據(jù)
    sInput=httpString+get_input(excelobj, suiteid, caseid, caseinfolist)
    XmlString=HTTPInvoke(com_ipport, sInput)   #執(zhí)行調(diào)用
    #獲取返回碼并比較
    result_code=et.fromstring(XmlString).find("result_code").text
    ret1=check_result(excelobj, suiteid, caseid,result_code, excelobj.retCol)
    #保存預(yù)期結(jié)果文件
    expectPath=expectDir+'/'+str(caseid+1)+'.xml'
    #saveXmlfile(expectPath, XmlString)
    #保存實(shí)際結(jié)果文件
    realPath=realDir+'/'+str(caseid+1)+'.xml'
    saveXmlfile(realPath, XmlString)
    #比較預(yù)期結(jié)果和實(shí)際結(jié)果
    ret2= check_xmlfile(excelobj, suiteid, caseid,expectPath, realPath)
    #寫測(cè)試結(jié)果
    write_result(excelobj, suiteid, caseid, excelobj.resultCol, ret1, ret2)
  print '【'+interface_name+'】' + ' Test End!'

3、測(cè)試入口

# -*- coding: utf-8 -*-
#****************************************************************
# main.py
# Author   : Vince
# Version  : 1.0
# Date    : 2011-3-16
# Description: 測(cè)試組裝,用例執(zhí)行入口
#****************************************************************
from testframe import *
from xxx_server_case import *
import xxx_server_case
#產(chǎn)品系統(tǒng)接口測(cè)試
#設(shè)置測(cè)試環(huán)境
xxx_server_case.excelobj=create_excel(os.getcwd()+'/TestDir/xxx_Testcase.xls')
xxx_server_case.com_ipport=xxx.com'
#Add testsuite begin
run("xxx_book_list", 4)
#Add other suite from here
#Add testsuite end
statisticresult(xxx_server_case.excelobj)
xxx_server_case.excelobj.close()

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • pandas讀取文件夾下所有excel文件的實(shí)現(xiàn)

    pandas讀取文件夾下所有excel文件的實(shí)現(xiàn)

    最近需要做一個(gè)需求,要求匯總一個(gè)文件夾所有的excel文件,所以本文就來(lái)介紹一下pandas讀取文件夾下所有excel文件的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-09-09
  • python3的UnicodeDecodeError解決方法

    python3的UnicodeDecodeError解決方法

    這篇文章主要介紹了python3的UnicodeDecodeError解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • python爬取內(nèi)容存入Excel實(shí)例

    python爬取內(nèi)容存入Excel實(shí)例

    這篇文章主要為大家詳細(xì)介紹了python爬取內(nèi)容存入Excel實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-02-02
  • Python編寫簡(jiǎn)單的HTML頁(yè)面合并腳本

    Python編寫簡(jiǎn)單的HTML頁(yè)面合并腳本

    這篇文章主要介紹了Python編寫簡(jiǎn)單的HTML頁(yè)面合并腳本的相關(guān)資料,需要的朋友可以參考下
    2016-07-07
  • Python類型注解必備利器typing模塊全面解讀

    Python類型注解必備利器typing模塊全面解讀

    在Python 3.5版本后引入的typing模塊為Python的靜態(tài)類型注解提供了支持,這個(gè)模塊在增強(qiáng)代碼可讀性和維護(hù)性方面提供了幫助,本文將深入探討typing模塊,介紹其基本概念、常用類型注解以及使用示例,以幫助讀者更全面地了解和應(yīng)用靜態(tài)類型注解
    2024-01-01
  • pytorch 獲取tensor維度信息示例

    pytorch 獲取tensor維度信息示例

    今天小編就為大家分享一篇pytorch 獲取tensor維度信息示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-01-01
  • windows支持哪個(gè)版本的python

    windows支持哪個(gè)版本的python

    在本篇文章中小編給大家分享了關(guān)于windows支持python的版本的相關(guān)內(nèi)容知識(shí)點(diǎn),需要的朋友們可以學(xué)習(xí)下。
    2020-07-07
  • Python多線程編程(七):使用Condition實(shí)現(xiàn)復(fù)雜同步

    Python多線程編程(七):使用Condition實(shí)現(xiàn)復(fù)雜同步

    這篇文章主要介紹了Python多線程編程(七):使用Condition實(shí)現(xiàn)復(fù)雜同步,本文講解通過(guò)很著名的“生產(chǎn)者-消費(fèi)者”模型來(lái)來(lái)演示在Python中使用Condition實(shí)現(xiàn)復(fù)雜同步,需要的朋友可以參考下
    2015-04-04
  • python統(tǒng)計(jì)文本字符串里單詞出現(xiàn)頻率的方法

    python統(tǒng)計(jì)文本字符串里單詞出現(xiàn)頻率的方法

    這篇文章主要介紹了python統(tǒng)計(jì)文本字符串里單詞出現(xiàn)頻率的方法,涉及Python字符串操作的相關(guān)技巧,需要的朋友可以參考下
    2015-05-05
  • Python 將 CSV 分割成多個(gè)文件的示例代碼

    Python 將 CSV 分割成多個(gè)文件的示例代碼

    在本文中,我們討論了如何使用 Pandas 庫(kù)創(chuàng)建 CSV 文件, 此外,我們還討論了兩種常見(jiàn)的數(shù)據(jù)拆分技術(shù),行式數(shù)據(jù)拆分和列式數(shù)據(jù)拆分,需要的朋友可以參考下
    2023-06-06

最新評(píng)論

宿松县| 天峨县| 成安县| 长春市| 嵊泗县| 青冈县| 临汾市| 洛浦县| 天镇县| 陈巴尔虎旗| 东海县| 洛南县| 岑溪市| 柘荣县| 山阳县| 汝州市| 宣城市| 宝坻区| 乐平市| 盘山县| 江永县| 长宁区| 金平| 称多县| 加查县| 东安县| 新闻| 灵宝市| 泰和县| 广东省| 温泉县| 龙里县| 梁平县| 金塔县| 呼伦贝尔市| 华坪县| 瓦房店市| 合肥市| 荆门市| 龙胜| 临夏县|