接口参数化

用例相关

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
import logging
from wind.log.logger import logs
from HTMLTestRunner import HTMLTestRunner
import time


class ExcelSet(unittest.TestCase):
excelPath = r"./自动化接口.xls"
workBook = xlrd.open_workbook(excelPath, formatting_info=True)
loginSheet = workBook.sheet_by_name("登录")
# 拷贝
newWorkBook = copy.copy(workBook)

def test_excelData(self):
logger = logs("../log/testCase1.log")
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为空"
logging.error(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)
# 跟预期结果进行匹配
if res['code'] == cellResult['code']:
print(f'{idNum}-->测试用例成功-->')
excel_res = "pass"
else:
logging.error(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__':
suite = unittest.TestLoader().loadTestsFromTestCase(ExcelSet) # 定义一个单元测试容器
now = time.strftime("%Y-%m-%d %H:%M:%S")

filename = "../report/测试报告.html" # 定义个报告存放路径,支持相对路径
f = open(filename, 'wb') # 结果写入HTML 文件

runner = HTMLTestRunner(stream=f, title="TestReport", tester="灵感", description="用例执行明细如下",
verbosity=2) # 使用HTMLTestRunner配置参数,输出报告路径、报告标题、描述
runner.run(suite)

 日志logger

import logging


def logs(log_path):
file_handler = logging.FileHandler(filename=log_path, mode='a', encoding='utf-8', )
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
handlers=[file_handler, ],
level=logging.ERROR,
)

读取配置文件

# 1.读取配置文件
with open("./config.ini") as f:
    file_list = f.read().splitlines()  # 读取同时去掉换行符

print(file_list)

# 2.执行安装库指令
backInfo = os.popen("pip list")
info = backInfo.read()
# print(info)

# 3.安装库
for line in file_list:
    if line in info:
        print("该库已经安装成功!")
        logging.warning(f"----> {line} installed")
    else:
        # 没有安装的
        pipObject = os.popen("pip install " + line)
        pipRes = pipObject.read()
        if "Successfully" in pipRes:
            print("安装成功")
            logging.info(f"----> {line} installed pass")
        else:
            print("安装失败")
            logging.info(f"----> {line} installed fail")
幻想毫无价值,计划渺如尘埃,目标不可能达到。这一切的一切毫无意义——除非我们付诸行动。
原文地址:https://www.cnblogs.com/TodayWind/p/14163459.html