欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python3+Requests+Excel完整接口自動(dòng)化測(cè)試框架的實(shí)現(xiàn)

 更新時(shí)間:2019年10月11日 09:24:49   作者:CesareCheung  
這篇文章主要介紹了Python3+Requests+Excel完整接口自動(dòng)化測(cè)試框架的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

框架整體使用Python3+Requests+Excel:包含對(duì)實(shí)時(shí)token的獲取

1、------base

-------runmethond.py

runmethond:對(duì)不同的請(qǐng)求方式進(jìn)行封裝

import json
import requests

requests.packages.urllib3.disable_warnings()

class RunMethod:
  def post_main(self, url, data, header=None):
    res = None
    if header != None:
      res = requests.post(url=url, data=data, headers=header,verify=False)
    else:
      res = requests.post(url=url, data=data,verify=False)
    return res.json()

  def get_main(self, url, data=None, header=None):
    res = None
    if header != None:
      res = requests.get(url=url, params=data, headers=header, verify=False)
    else:
      res = requests.get(url=url, params=data, verify=False)
    return res.json()

  def run_main(self, method, url, data=None, header=None):
    res = None
    if method == 'Post':
      res = self.post_main(url, data, header)
    else:
      res = self.get_main(url, data, header)
    return json.dumps(res, indent=2, sort_keys=True, ensure_ascii=False)


if __name__ == '__main__':
  url = 'http://httpbin.org/post'
  data = {
    'cart': '11'
  }
  run = RunMethod()
  run_test = run.run_main(method="Post", url=url, data=data)
  print(run_test)

2、------data

------data_config.py

data_config:獲取excel模塊中數(shù)據(jù)

class global_val:
  Id = '0'
  request_name = '1'
  url = '2'
  run = '3'
  request_way = '4'
  header = '5'
  case_depend = '6'
  data_depend = '7'
  field_depend = '8'
  data = '9'
  expect = '10'
  result = '11'


def get_id():
  """獲取case_id"""
  return global_val.Id


def get_request_name():
  """獲取請(qǐng)求模塊名稱"""
  return global_val.request_name


def get_url():
  """獲取請(qǐng)求url"""
  return global_val.url


def get_run():
  """獲取是否運(yùn)行"""
  return global_val.run


def get_run_way():
  """獲取請(qǐng)求方式"""
  return global_val.request_way


def get_header():
  """獲取是否攜帶header"""
  return global_val.header


def get_case_depend():
  """case依賴"""
  return global_val.case_depend


def get_data_depend():
  """依賴的返回?cái)?shù)據(jù)"""
  return global_val.data_depend


def get_field_depend():
  """數(shù)據(jù)依賴字段"""
  return global_val.field_depend


def get_data():
  """獲取請(qǐng)求數(shù)據(jù)"""
  return global_val.data


def get_expect():
  """獲取預(yù)期結(jié)果"""
  return global_val.expect


def get_result():
  """獲取返回結(jié)果"""
  return global_val.result

3、-----data

-----dependent_data.py

dependent_data:解決數(shù)據(jù)依賴問(wèn)題

from util.operation_excel import OperationExcel
from base.runmethod import RunMethod
from data.get_data import GetData
from jsonpath_rw import jsonpath, parse
import json


class DependentData:
  """解決數(shù)據(jù)依賴問(wèn)題"""

  def __init__(self, case_id):
    self.case_id = case_id
    self.opera_excel = OperationExcel()
    self.data = GetData()

  def get_case_line_data(self):
    """
    通過(guò)case_id去獲取該case_id的整行數(shù)據(jù)
    :param case_id: 用例ID
    :return:
    """
    rows_data = self.opera_excel.get_row_data(self.case_id)
    return rows_data

  def run_dependent(self):
    """
    執(zhí)行依賴測(cè)試,獲取結(jié)果
    :return:
    """
    run_method = RunMethod()
    row_num = self.opera_excel.get_row_num(self.case_id)
    request_data = self.data.get_data_for_json(row_num)
    # header = self.data.is_header(row_num)
    method = self.data.get_request_method(row_num)
    url = self.data.get_request_url(row_num)
    res = run_method.run_main(method, url, request_data)
    return json.loads(res)

  def get_data_for_key(self, row):
    """
    根據(jù)依賴的key去獲取執(zhí)行依賴case的響應(yīng)然后返回
    :return:
    """
    depend_data = self.data.get_depend_key(row)
    response_data = self.run_dependent()
    return [match.value for match in parse(depend_data).find(response_data)][0]

4、-----data

-----get_data.py

get_data:獲取excel數(shù)據(jù)

from util.operation_excel import OperationExcel
from data import data_config
from util.operation_json import OperationJson


class GetData:
  """獲取excel數(shù)據(jù)"""

  def __init__(self):
    self.opera_excel = OperationExcel()

  def get_case_lines(self):
    """獲取excel行數(shù),即case的個(gè)數(shù)"""
    return self.opera_excel.get_lines()

  def get_is_run(self, row):
    """獲取是否執(zhí)行"""
    flag = None
    col = int(data_config.get_run())
    run_model = self.opera_excel.get_cell_value(row, col)
    if run_model == 'yes':
      flag = True
    else:
      flag = False
    return flag

  def is_header(self, row):
    """
    是否攜帶header
    :param row: 行號(hào)
    :return:
    """
    col = int(data_config.get_header())
    header = self.opera_excel.get_cell_value(row, col)
    if header != '':
      return header
    else:
      return None

  def get_request_method(self, row):
    """
    獲取請(qǐng)求方式
    :param row: 行號(hào)
    :return:
    """
    # col 列
    col = int(data_config.get_run_way())
    request_method = self.opera_excel.get_cell_value(row, col)
    return request_method

  def get_request_url(self, row):
    """
    獲取url
    :param row: 行號(hào)
    :return:
    """
    col = int(data_config.get_url())
    url = self.opera_excel.get_cell_value(row, col)
    return url

  def get_request_data(self, row):
    """
    獲取請(qǐng)求數(shù)據(jù)
    :param row:行號(hào)
    :return:
    """
    col = int(data_config.get_data())
    data = self.opera_excel.get_cell_value(row, col)
    if data == '':
      return None
    return data

  def get_data_for_json(self, row):
    """
    通過(guò)關(guān)鍵字拿到data數(shù)據(jù)
    :param row:
    :return:
    """
    opera_json = OperationJson()
    request_data = opera_json.get_data(self.get_request_data(row))
    return request_data

  def get_expcet_data(self, row):
    """
    獲取預(yù)期結(jié)果
    :param row:
    :return:
    """
    col = int(data_config.get_expect())
    expect = self.opera_excel.get_cell_value(row, col)
    if expect == "":
      return None
    else:
      return expect

  def write_result(self, row, value):
    """
    寫入結(jié)果數(shù)據(jù)
    :param row:
    :param col:
    :return:
    """
    col = int(data_config.get_result())
    self.opera_excel.write_value(row, col, value)

  def get_depend_key(self, row):
    """
    獲取依賴數(shù)據(jù)的key
    :param row:行號(hào)
    :return:
    """
    col = int(data_config.get_data_depend())
    depend_key = self.opera_excel.get_cell_value(row, col)
    if depend_key == "":
      return None
    else:
      return depend_key

  def is_depend(self, row):
    """
    判斷是否有case依賴
    :param row:行號(hào)
    :return:
    """
    col = int(data_config.get_case_depend()) # 獲取是否存在數(shù)據(jù)依賴列
    depend_case_id = self.opera_excel.get_cell_value(row, col)
    if depend_case_id == "":
      return None
    else:
      return depend_case_id

  def get_depend_field(self, row):
    """
    獲取依賴字段
    :param row:
    :return:
    """
    col = int(data_config.get_field_depend())
    data = self.opera_excel.get_cell_value(row, col)
    if data == "":
      return None
    else:
      return data

5、-----dataconfig

-----case.xls

case.xls:用例數(shù)據(jù)

6、-----dataconfig

-----data.json

data.json:請(qǐng)求數(shù)據(jù),根據(jù)自己實(shí)際業(yè)務(wù),且與case層的請(qǐng)求數(shù)據(jù)列是關(guān)聯(lián)的

{
 "user": {
  "username": "1111111",
  "password": "123456"
 },
 "filtrate": {
  "type_id": "2",
  "brand_id": "1",
  "model_id": "111"
 },
 "search": {
  "page": "1",
  "keyword": "oppo",
  "type": "12"
 },
 "token": {
  "token": ""
 }

7、-----dataconfig

-----token.json

token.json:實(shí)時(shí)自動(dòng)將獲取的token寫入到該文件

{"data": {"token": "db6f0abee4e5040f5337f5c47a82879"}}

8、-----main

-----run_test.py

run_test:主運(yùn)行程序

from base.runmethod import RunMethod
from data.get_data import GetData
from util.common_util import CommonUtil
from data.dependent_data import DependentData
# from util.send_email import SendEmail
from util.operation_header import OperationHeader
from util.operation_json import OperationJson


class RunTest:

  def __init__(self):
    self.run_method = RunMethod()
    self.data = GetData()
    self.com_util = CommonUtil()
    # self.send_email = SendEmail()

  def go_on_run(self):
    """程序執(zhí)行"""
    pass_count = []
    fail_count = []
    res = None
    # 獲取用例數(shù)
    rows_count = self.data.get_case_lines()
    # 第一行索引為0
    for i in range(1, rows_count):
      is_run = self.data.get_is_run(i)
      if is_run:
        url = self.data.get_request_url(i)
        method = self.data.get_request_method(i)
        request_data = self.data.get_data_for_json(i)
        expect = self.data.get_expcet_data(i)
        header = self.data.is_header(i)
        depend_case = self.data.is_depend(i)

        if depend_case != None:
          self.depend_data = DependentData(depend_case)
          # 獲取依賴的響應(yīng)數(shù)據(jù)
          depend_response_data = self.depend_data.get_data_for_key(i)
          # 獲取依賴的key
          depend_key = self.data.get_depend_field(i)
          # 更新請(qǐng)求字段
          request_data[depend_key] = depend_response_data
        # 如果header字段值為write則將該接口的返回的token寫入到token.json文件,如果為yes則讀取token.json文件
        if header == "write":
          res = self.run_method.run_main(method, url, request_data)
          op_header = OperationHeader(res)
          op_header.write_token()
        elif header == 'yes':
          op_json = OperationJson("../dataconfig/token.json")
          token = op_json.get_data('data')
          request_data = dict(request_data, **token) # 把請(qǐng)求數(shù)據(jù)與登錄token合并,并作為請(qǐng)求數(shù)據(jù)

          res = self.run_method.run_main(method, url, request_data)
        else:
          res = self.run_method.run_main(method, url, request_data)

        if expect != None:
          if self.com_util.is_contain(expect, res):
            self.data.write_result(i, "Pass")
            pass_count.append(i)
          else:
            self.data.write_result(i, res)
            fail_count.append(i)
        else:
          print(f"用例ID:case-{i},預(yù)期結(jié)果不能為空")

    # 發(fā)送郵件
    # self.send_email.send_main(pass_count, fail_count)

    print(f"通過(guò)用例數(shù):{len(pass_count)}")
    print(f"失敗用例數(shù):{len(fail_count)}")


if __name__ == '__main__':
  run = RunTest()
  run.go_on_run()

9、-----util

-----common_util.py

common_util:用于斷言

class CommonUtil:
  def is_contain(self, str_one, str_two):
    """
    判斷一個(gè)字符串是否在另一個(gè)字符串中
    :param str_one:
    :param str_two:
    :return:
    """
    flag = None
    if str_one in str_two:
      flag = True
    else:
      flag = False
    return flag

10、-----util

-----operation_excel.py

operation_excel:操作excel

import xlrd
from xlutils.copy import copy


class OperationExcel:
  """操作excel"""

  def __init__(self, file_name=None, sheet_id=None):
    if file_name:
      self.file_name = file_name
      self.sheet_id = sheet_id
    else:
      self.file_name ='../dataconfig/case1.xls'
      self.sheet_id = 0
    self.data = self.get_data()

  def get_data(self):
    """
    獲取sheets的內(nèi)容
    :return:
    """
    data = xlrd.open_workbook(self.file_name)
    tables = data.sheets()[self.sheet_id]
    return tables

  def get_lines(self):
    """
    獲取單元格行數(shù)
    :return:
    """
    tables = self.data
    return tables.nrows

  def get_cell_value(self, row, col):
    """
    獲取單元格數(shù)據(jù)
    :param row: 行
    :param col: 列
    :return:
    """
    tables = self.data
    cell = tables.cell_value(row, col)
    return cell

  def write_value(self, row, col, value):
    """
    回寫數(shù)據(jù)到excel
    :param row:行
    :param col:列
    :param value:值
    :return:
    """
    read_data = xlrd.open_workbook(self.file_name)
    write_data = copy(read_data)
    sheet_data = write_data.get_sheet(0)
    sheet_data.write(row, col, value)
    write_data.save(self.file_name)

  def get_row_data(self, case_id):
    """
    根據(jù)對(duì)應(yīng)的case_id獲取對(duì)應(yīng)行的內(nèi)容
    :param case_id: 用例id
    :return:
    """
    row_num = self.get_row_num(case_id)
    row_data = self.get_row_value(row_num)
    return row_data

  def get_row_num(self, case_id):
    """
    根據(jù)case_id獲取對(duì)應(yīng)行號(hào)
    :param case_id:
    :return:
    """
    num = 0
    cols_data = self.get_cols_data()
    for col_data in cols_data:
      if case_id in col_data:
        return num
      num = num + 1

  def get_row_value(self, row):
    """
     根據(jù)行號(hào),找到該行的內(nèi)容
    :param row:行號(hào)
    :return:

    """
    tables = self.data
    row_data = tables.row_values(row)
    return row_data

  def get_cols_data(self, col_id=None):
    """
    獲取某一列的內(nèi)容
    :param col_id:列號(hào)
    :return:
    """
    if col_id != None:
      cols = self.data.col_values(col_id)
    else:
      cols = self.data.col_values(0)
    return cols


if __name__ == '__main__':
  opera = OperationExcel()
  opera.get_data()
  print(opera.get_data().nrows)
  print(opera.get_lines())
  print(opera.get_cell_value(1, 2))

11、-----util

-----operation_header.py

operation_header:實(shí)時(shí)獲取登錄token及將token寫入到token.json文件

import json
from util.operation_json import OperationJson
from base.runmethod import RunMethod
class OperationHeader:

  def __init__(self, response):
    self.response = json.loads(response)

  def get_response_token(self):
    '''
    獲取登錄返回的token
    '''
    token = {"data":{"token":self.response['data']['token']}}
    return token

  def write_token(self):
    op_json = OperationJson()
    op_json.write_data(self.get_response_token())

 

if __name__ == '__main__':

  url = "http://xxxxx"

  data = {
    "username": "1111",
    "password": "123456"
  }
  run_method=RunMethod()
  # res = json.dumps(requests.post(url, data).json())
  res=run_method.run_main('Post', url, data)
  op = OperationHeader(res)
  op.write_token()

12、-----util

-----operation_json.py

operation_json:操作json文件

import json


class OperationJson:
  """操作json文件"""

  def __init__(self,file_path=None):
    if file_path==None:
      self.file_path="../dataconfig/data.json"
    else:
      self.file_path=file_path
    self.data = self.read_data()

  def read_data(self):
    """
    讀取json文件
    :param file_name:文件路徑
    :return:
    """
    with open(self.file_path) as fp:
      data = json.load(fp)
      return data

  def get_data(self, id):
    """根據(jù)關(guān)鍵字獲取對(duì)應(yīng)數(shù)據(jù)"""
    return self.data[id]

  # 寫入json
  def write_data(self, data):
    with open("../dataconfig/token.json", 'w') as fp:
      fp.write(json.dumps(data))


if __name__ == '__main__':
  # file_path = "../dataconfig/data.json"
  opejson = OperationJson()
  print(opejson.read_data())
  print(opejson.get_data('filtrate'))

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • numpy linalg模塊的具體使用方法

    numpy linalg模塊的具體使用方法

    這篇文章主要介紹了numpy linalg模塊的具體使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • python?中Mixin混入類的使用方法詳解

    python?中Mixin混入類的使用方法詳解

    這篇文章主要介紹了python?中Mixin混入類的使用方法詳解,Mixin?混入也可以說(shuō)是編程模式,并不是什么新的語(yǔ)法,用好混入類可以使自己的代碼結(jié)構(gòu)清晰,功能明了,所以以后在設(shè)計(jì)類時(shí)要多考慮使用Mixin混入類的實(shí)現(xiàn)方式
    2022-07-07
  • Python函數(shù)可變參數(shù)定義及其參數(shù)傳遞方式實(shí)例詳解

    Python函數(shù)可變參數(shù)定義及其參數(shù)傳遞方式實(shí)例詳解

    這篇文章主要介紹了Python函數(shù)可變參數(shù)定義及其參數(shù)傳遞方式,以實(shí)例形式較為詳細(xì)的分析了Python函數(shù)參數(shù)的使用技巧,需要的朋友可以參考下
    2015-05-05
  • 利用Python提取圖片經(jīng)緯度并鎖定拍照地點(diǎn)

    利用Python提取圖片經(jīng)緯度并鎖定拍照地點(diǎn)

    每張照片的屬性中都會(huì)有一個(gè)經(jīng)緯度信息,本文將利用Python實(shí)現(xiàn)提取圖片的經(jīng)緯度,并鎖定拍照的低點(diǎn),感興趣的小伙伴可以跟隨小編一起動(dòng)手試一試
    2022-02-02
  • Python中的time模塊與datetime模塊用法總結(jié)

    Python中的time模塊與datetime模塊用法總結(jié)

    Python中內(nèi)置的各項(xiàng)時(shí)間日期函數(shù)幾乎都來(lái)自于time和datetime這兩個(gè)模塊,下面整理了Python中的time模塊與datetime模塊用法總結(jié),需要的朋友可以參考下
    2016-06-06
  • python日志通過(guò)不同的等級(jí)打印不同的顏色(示例代碼)

    python日志通過(guò)不同的等級(jí)打印不同的顏色(示例代碼)

    這篇文章主要介紹了python日志通過(guò)不同的等級(jí)打印不同的顏色,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • pytest使用@pytest.mark.parametrize()實(shí)現(xiàn)參數(shù)化的示例代碼

    pytest使用@pytest.mark.parametrize()實(shí)現(xiàn)參數(shù)化的示例代碼

    這篇文章主要介紹了pytest使用@pytest.mark.parametrize()實(shí)現(xiàn)參數(shù)化,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07
  • Python自動(dòng)化完成tb喵幣任務(wù)的操作方法

    Python自動(dòng)化完成tb喵幣任務(wù)的操作方法

    2019雙十一,tb推出了新的活動(dòng),商店喵幣,看了一下每天都有幾個(gè)任務(wù)來(lái)領(lǐng)取喵幣,從而升級(jí)店鋪賺錢,然而我既想賺紅包又不想干苦力,遂使用python來(lái)進(jìn)行手機(jī)自動(dòng)化操作,需要的朋友跟隨小編一起看看吧
    2019-10-10
  • Python中利用原始套接字進(jìn)行網(wǎng)絡(luò)編程的示例

    Python中利用原始套接字進(jìn)行網(wǎng)絡(luò)編程的示例

    這篇文章主要介紹了Python中利用原始套接字進(jìn)行網(wǎng)絡(luò)編程的示例,使用sock_raw接受和發(fā)送數(shù)據(jù)包可以避開(kāi)網(wǎng)絡(luò)協(xié)議的諸多限制,需要的朋友可以參考下
    2015-05-05
  • Python利用pandas處理CSV文件的用法示例

    Python利用pandas處理CSV文件的用法示例

    pandas是一個(gè)第三方數(shù)據(jù)分析庫(kù),其集成了大量的數(shù)據(jù)分析工具,可以方便的處理和分析各類數(shù)據(jù),本文將給大家介紹Python利用pandas處理CSV文件的用法示例,文中通過(guò)代碼和圖文講解的非常詳細(xì),需要的朋友可以參考下
    2024-07-07

最新評(píng)論