1. 程式人生 > 實用技巧 >介面引數化

介面引數化

用例相關

import unittest
import requests
import random
import json
from wind.util.base_response import BaseResponse


class mytest():

    def test_01_reg(url, header, inData):
        ret = BaseResponse()

        inData = json.loads(inData)
        resp = requests.post(url, data=json.dumps(inData), headers=header)
        result 
= resp.json() return result # 新增使用者 # def add_user(data, Token, telState=False): # url = "http://127.0.0.1:8001/api/register/" # if telState: # tel_num = "13" + str(random.randint(100000000, 999999999)) # data["phone"] = tel_num # headers = {"Content-Type
": "application/json", "X-AUTH-TOKEN": Token} # resp = requests.post(url, json=data, headers=headers) # result = resp.json()["message"] # return result

自定義狀態碼

class BaseResponse(object):
    def __init__(self):
        self.code = 1000
        self.error = ''
        self.data 
= '' @property def dict(self): return self.__dict__

讀取excel

import xlrd
from wind.case.reg import mytest
import json
from xlutils import copy
import unittest


class ExcelSet(unittest.TestCase):
    excelPath = r"./自動化介面.xls"
    workBook = xlrd.open_workbook(excelPath, formatting_info=True)
    loginSheet = workBook.sheet_by_name("登入")
    # 1.拷貝
    newWorkBook = copy.copy(workBook)

    def test_excelData(self):
        workSheet = self.workBook.sheet_by_name("註冊")
        # 取拷貝的excel的sheet  --sheet下標(預設從0開始)
        newSheet = self.newWorkBook.get_sheet(1)

        for case in range(1, workSheet.nrows):
            idNum = workSheet.cell(case, 0).value
            cell_url = workSheet.cell(case, 3).value
            cell_data = workSheet.cell(case, 6).value
            cell_head = workSheet.cell(case, 5).value
            if not cell_data or not cell_url:
                err = f"測試用例{idNum}url或body為空"
                print(err)
                continue
            cell_head = json.loads(cell_head)
            cellResult = json.loads(workSheet.cell(case, 7).value)
            res = mytest.test_01_reg(cell_url, cell_head, cell_data)
            print(res)
            # 跟預期結果進行匹配
            if res['code'] == cellResult['code']:
                print(f'{idNum}-->測試用例成功-->')
                excel_res = "pass"
            else:
                print(f'{idNum}-->測試用例失敗-->')
                excel_res = "fail"

            # 3. 寫入資料--info--newSheet,write(行下標,列下標,內容)
            newSheet.write(case, 8, json.dumps(res))
            newSheet.write(case, 9, excel_res)

            # 4.儲存excel
            self.newWorkBook.save("../excel/result.xls")


if __name__ == '__main__':
    unittest.main()