优化之后的代码如下:
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/01
# @Author : Laopi
import json
import logging
import allure
from testcase.conftest import *
baseUrl = GetYamlData(ConfigHandler.config_path).get_yaml_data()
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
case_path = os.path.join(root_path, 'testdata')
os.chdir(case_path) # 修改工作路径
workbook = openpyxl.load_workbook('接口测试用例.xlsx') # 返回一个workbook数据类型的值
sheets = workbook.sheetnames
def get_token():
baseUrl = GetYamlData(ConfigHandler.config_path).get_yaml_data()
url = baseUrl['host']+"/login"
headers={"Content-Type":"application/x-www-form-urlencoded"}
data={"username":"admin","password":"123456"}
response = requests.post(url=url,
headers=headers,
data=data)
return response.json()['Admin-Token']
listdemo =[]
for i in range(len(sheets)):
workbook._active_sheet_index=i
sheet = workbook.active
for j in range(6,sheet.max_row+1):
case_name = sheet.cell(j, 1).value
listdemo.append([i,j,case_name])
# listdemo= [[0, 6]]
class TestCases:
@pytest.mark.parametrize("i,j,casename", listdemo)
@allure.title("{casename}")
def test_CRM(self,i,j,casename):
cookie = get_token()
url = baseUrl['host'] + sheet.cell(row=2, column=2).value
headers = json.loads(sheet.cell(j, 2).value)
headers.update({'Admin-Token': cookie})
if headers['Content-Type'] == 'application/json':
data = json.dumps(json.loads(sheet.cell(j, 3).value))
else:
data = json.loads(sheet.cell(j, 3).value)
response1 = requests.post(url=url, headers=headers, data=data)
logging.info(response1.json())
expectResult = sheet.cell(j, 5).value
assert json.loads(expectResult)['code'] == response1.json()['code']
logging.info(i)
logging.info(j)
设计思路:
首先把所有的Excel拼接成一个list,按照参数规则传给
@pytest.mark.parametrize("i,j,casename", listdemo)
之后,再将Excel的用例标题传入
@allure.title("{casename}")
将conftest里面的部分删除,写入这个里面
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/01
# @Author : Laopi
import json
import logging
import os
import time
import openpyxl
import requests
from config.setting import ConfigHandler
from tools.yamlControl import GetYamlData
import pytest
# @pytest.fixture(scope="session", autouse=True)
# def get_baseUrl():
# baseUrl = GetYamlData(ConfigHandler.config_path).get_yaml_data()
# yield baseUrl
#
# @pytest.fixture(scope="session", autouse=True)
# def get_workbook():
# root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# case_path = os.path.join(root_path, 'testdata')
# os.chdir(case_path) # 修改工作路径
# workbook = openpyxl.load_workbook('接口测试用例.xlsx') # 返回一个workbook数据类型的值
# print("执行了这个getworkbook")
# yield workbook
def pytest_collection_modifyitems(items):
"""
测试用例收集完成时,将收集到的 item 的 name 和 node_id 的中文显示在控制台上
:return:
"""
for item in items:
item.name = item.name.encode("utf-8").decode("unicode_escape")
item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")
# 期望用例顺序
# print("收集到的测试用例:%s" % items)
appoint_items = ["test_get_user_info", "test_collect_addtool", "test_Cart_List", "test_ADD", "test_Guest_ADD",
"test_Clear_Cart_Item"]
# 指定运行顺序
run_items = []
for i in appoint_items:
for item in items:
module_item = item.name.split("[")[0]
if i == module_item:
run_items.append(item)
for i in run_items:
run_index = run_items.index(i)
items_index = items.index(i)
if run_index != items_index:
n_data = items[run_index]
run_index = items.index(n_data)
items[items_index], items[run_index] = items[run_index], items[items_index]
def pytest_terminal_summary(terminalreporter):
"""
收集用例执行结果
"""
_PASSED = len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
_ERROR = len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
_FAILED = len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
_SKIPPED = len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
_TOTAL = terminalreporter._numcollected
_TIMES = time.time() - terminalreporter._sessionstarttime
print(f"用例总数: {_TOTAL}")
print(f"异常用例数: {_ERROR}")
print(f"失败用例数: {_FAILED}")
print(f"跳过用例数: {_SKIPPED}")
print("用例执行时长: %.2f" % _TIMES + " s")
("用例执行时长: %.2f" % _TIMES + " s")
try:
_RATE = _PASSED / _TOTAL * 100
print("用例成功率: %.2f" % _RATE + " %")
except ZeroDivisionError:
print("用例成功率: 0.00 %")
def pytest_terminal_summary(terminalreporter):
"""
收集用例执行结果
"""
_PASSED = len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
_ERROR = len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
_FAILED = len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
_SKIPPED = len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
_TOTAL = terminalreporter._numcollected
_TIMES = time.time() - terminalreporter._sessionstarttime
print(f"用例总数: {_TOTAL}")
print(f"异常用例数: {_ERROR}")
print(f"失败用例数: {_FAILED}")
print(f"跳过用例数: {_SKIPPED}")
print("用例执行时长: %.2f" % _TIMES + " s")
("用例执行时长: %.2f" % _TIMES + " s")
try:
_RATE = _PASSED / _TOTAL * 100
print("用例成功率: %.2f" % _RATE + " %")
except ZeroDivisionError:
print("用例成功率: 0.00 %")
# 定义日志输出目录
log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
# 设置logging模块
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(os.path.join(log_path, 'output.log')),
logging.StreamHandler()
]
)
运行输出的报告如下: