Python+requests+excel接口測試

2018-06-14   17:00:13html

環境準備:json

- Python 3.7api

- requests庫app

- xlrdpost

 

一、建立Excel文件測試

 

二、讀取Excel文件ui

import xlrd

class readExcel(object):
    def __init__(self, path):
        self.path = path

    @property
    def getSheet(self):
        # 獲取索引
        xl = xlrd.open_workbook(self.path)
        sheet = xl.sheet_by_index(1)
        # print( xl.sheet_names() )   打印全部sheet名字
        # print (sheet.cell_value( 2, 3 ))   打印第3行第4列
        return sheet

    @property
    def getRows(self):
        # 獲取行數
        row = self.getSheet.nrows
        return row

    @property
    def getCol(self):
        # 獲取列數
        col = self.getSheet.ncols
        return col

    # 如下是分別獲取每一列的數值

    @property
    def getId(self):
        TestId = []
        for i in range( 1, self.getRows ):
            TestId.append( self.getSheet.cell_value( i, 0 ) )
        # print(TestName)
        return TestId

    @property
    def getName(self):
        TestName = []
        for i in range(1, self.getRows):
            TestName.append(self.getSheet.cell_value(i, 1))
        # print(TestName)
        return TestName

    @property
    def getData(self):
        TestData = []
        for i in range(1, self.getRows):
            TestData.append(self.getSheet.cell_value(i, 2))
        return TestData

    @property
    def getUrl(self):
        TestUrl = []
        for i in range(1, self.getRows):
            TestUrl.append(self.getSheet.cell_value(i, 3))
        return TestUrl

    @property
    def getMethod(self):
        TestMethod = []
        for i in range(1, self.getRows):
            TestMethod.append(self.getSheet.cell_value(i, 4))
        return TestMethod

    @property
    def getStatusCode(self):
        TestUid = []
        for i in range(1, self.getRows):
            TestUid.append(self.getSheet.cell_value(i, 5))
        return TestUid

    @property
    def getCode(self):
        TestCode = []
        for i in range(1, self.getRows):
            TestCode.append(self.getSheet.cell_value(i, 6))
        return TestCode

 

三、封裝請求類型與返回的數據,此處只封裝了get和post請求,還有delete、put、options、head等,有興趣的能夠自行添加url

import requests
import json
from baseData import readExcel
from common import keywords

class testApi(object):
    def __init__(self, method, url, data):
        self.method = method
        self.url = url
        self.data = data

    @property
    def headers(self):
        headers = {
            "Content-Type": "application/json"
        }
        return headers

    @property
    def testApi(self):
        # 根據不一樣的訪問方式來訪問接口
        try:
            if self.method == 'post':
                r = requests.post(self.url, data=json.dumps(eval(self.data)), headers=self.headers)
            elif self.method == 'get':
                r = requests.get(self.url, params=self.data)
            return r
        except:
            print('失敗')

    def getCode(self):
        # 獲取訪問接口的狀態碼
        code = self.testApi.json()['code']
        return code

    def getStatusCode(self):
        # 獲取返回信息status_code
        status_code = self.testApi.json()['status_code']
        return status_code

    def getJson(self):
    #     獲取返回信息的json數據
        json_data = self.testApi.json()
        return json_data

 

四、經過unittest執行測試用例,用HTMLTestRunner生成測試報告spa

from baseData import readExcel
from testApiWay import testApi
from base_test import baseTest
import unittest
from HTMLTestRunner import HTMLTestRunner
from common import keywords  #一些參數封裝成了關鍵字


class testLoginApi( baseTest ):
    def testLoginApi(self):
        '''測試登錄接口,登錄的幾種狀況。'''
        excel = readExcel( r'C:\Users\Jasmine\Desktop\data.xlsx' )
        name = excel.getName
        data = excel.getData
        url = excel.getUrl
        method = excel.getMethod
        id = excel.getId
        status_code = excel.getStatusCode
        code = excel.getCode
        row = excel.getRows
        # print(code)
        for i in range( 0, row - 1 ):
            api = testApi( method[i], url[i], data[i])
            # apicode = api.getCode()
            # print(apicode)
            apistatus = api.getStatusCode()
            print(apistatus)
            apijson = api.getJson()
            if apistatus == status_code[i]:
                print('{}.{}:測試成功。json數據爲:{}'.format( id[i], name[i], apijson ))   #i+1
            else:
                print('{}.{}:測試失敗。json數據爲:{}'.format( id[i], name[i], apijson ))
# 生成測試報告
def runAutomation():
    suite = unittest.TestLoader().loadTestsFromTestCase( testLoginApi )
    runner = HTMLTestRunner(
        stream=open(keywords.Time+ 'testReport.html', 'wb' ),  #k.getNowTime()
        title=u'TestReport',
        description=u'測試報告詳細信息'
        )
    runner.run( suite )


if __name__ == '__main__':
    # runAutomation()

    unittest.main( verbosity=2 )

 

ps:Python3中HTMLTestRunner生成的測試報告很簡陋,須要本身手動修改HTMLTestRunner.py文件,因爲我是初學者,因此還在研究用其餘方法生成測試報告excel

相關文章
相關標籤/搜索