pytest_api/test_case/conftest.py

214 lines
7.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import os
from config.settings import ConfigHandler
from tools.yaml_control import GetYamlData
from tools.allure_control import allure_step,allure_step_no
import time
from tools.log_control import WARNING, INFO, ERROR
from py._xmlgen import html
from time import strftime
import requests
from tools.cache_control import Cache
_PROJECT_NAME = GetYamlData(ConfigHandler.config_path).get_yaml_data()['ProjectName']
_TEST_NAME = GetYamlData(ConfigHandler.config_path).get_yaml_data()['TestName']
@pytest.fixture(scope="session", autouse=True)
def clear_report():
try:
for one in os.listdir(ConfigHandler.report_path + f'/tmp'):
if 'json' in one:
os.remove(ConfigHandler.report_path + f'/tmp/{one}')
if 'txt' in one:
os.remove(ConfigHandler.report_path + f'/tmp/{one}')
except Exception as e:
print("allure数据清除失败", e)
yield
print("ddd")
@pytest.fixture(scope="function", autouse=True)
def case_skip(in_data):
"""处理跳过用例"""
if in_data['is_run'] is False:
# allure.dynamic.title(in_data[YAMLDate.DETAIL.value])
allure_step_no(f"请求URL: 请求URL")
allure_step_no(f"请求方式: 请求URL")
allure_step("请求头: ", "请求URL")
allure_step("请求头: ", "请求URL")
allure_step("请求头: ", "请求URL")
allure_step("请求头: ", "请求URL")
pytest.skip()
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
INFO.logger.info(f"成功用例数: {_PASSED}")
ERROR.logger.error(f"异常用例数: {_ERROR}")
ERROR.logger.error(f"失败用例数: {_FAILED}")
WARNING.logger.warning(f"跳过用例数: {_SKIPPED}")
INFO.logger.info("用例执行时长: %.2f" % _TIMES + " s")
try:
_RATE = round((_PASSED + _SKIPPED) / _TOTAL * 100, 2)
INFO.logger.info("用例成功率: %.2f" % _RATE + " %")
except ZeroDivisionError:
INFO.logger.info("用例成功率: 0.00 %")
# @pytest.fixture(scope="session", autouse=True)
# def write_case_process():
# """
# 获取所有用例,写入用例池中
# :return:
# """
#
# case_data = {}
# # 循环拿到所有存放用例的文件路径
# for i in get_all_files(file_path=ConfigHandler.data_path, yaml_data_switch=True):
# # 循环读取文件中的数据
# case_process = CaseData(i).case_process(case_id_switch=True)
# # 转换数据类型
# for case in case_process:
# for k, v in case.items():
# # 判断 case_id 是否已存在
# case_id_exit = k in case_data.keys()
# # 如果case_id 不存在,则将用例写入缓存池中
# if case_id_exit is False:
# case_data[k] = v
# # 当 case_id 为 True 存在时,则跑出异常
# elif case_id_exit is True:
# raise ValueError(f"case_id: {k} 存在重复项, 请修改case_id\n"
# f"文件路径: {i}")
#
# Cache('case_process').set_caches(case_data)
@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
# cells.insert(1, html.th('用例描述', class_="sortable", col="name")) # 表头添加Description
cells.insert(3, html.th('执行时间', class_='sortable time', col='time'))
# cells.pop(-1) # 删除link
@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
# cells.insert(1, html.td(report.description)) # 表头对应的内容
cells.insert(3, html.td(strftime('%Y-%m-%d %H:%M:%S'), class_='col-time'))
# cells.pop(-1) # 删除link列
@pytest.mark.optionalhook
def pytest_html_results_table_html(report, data): # 清除执行成功的用例logs
if report.passed:
del data[:]
data.append(html.div('正常通过用例不抓取日志', class_='empty log'))
# 修改Environment部分信息配置测试报告环境信息
@pytest.mark.optionalhook
def pytest_html_report_title(report):
report.title = "自动化测试报告"
def pytest_configure(config):
from config.configs import Config
import datetime
host = str(Config().get_host11())
# 运行环境
try:
env = Config().__getattr__("DAV_ENVIRONMENT_SLUG")
except:
env = Config().__getattr__("CI_ENVIRONMENT_SLUG")
current_time = (datetime.datetime.now() + datetime.timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S')
# 添加接口地址与项目名称
config._metadata["项目名称"] = _PROJECT_NAME
config._metadata['域名'] = host
config._metadata['测试环境'] = env
config._metadata['开始时间'] = current_time
try:
config._metadata['部署项目commit ID'] = Config.DAV_COMMIT_ID
config._metadata['分支'] = Config.DAV_COMMIT_BRANCH
config._metadata['部署的镜像tag'] = Config.DAV_IMAGE_TAG
config._metadata['环境名字'] = Config.DAV_ENVIRONMENT_SLUG
config._metadata['项目路径'] = Config.DAV_PROJECT_PATH
except:
pass
# 删除Java_Home
if config._metadata.get("CI"):
config._metadata.pop("CI")
config._metadata.pop("CI_COMMIT_REF_NAME")
config._metadata.pop("CI_COMMIT_REF_SLUG")
config._metadata.pop("CI_COMMIT_SHA")
config._metadata.pop("CI_ENVIRONMENT_NAME")
config._metadata.pop("CI_ENVIRONMENT_SLUG")
config._metadata.pop("CI_JOB_ID")
config._metadata.pop("CI_JOB_NAME")
config._metadata.pop("CI_JOB_STAGE")
config._metadata.pop("CI_PIPELINE_ID")
config._metadata.pop("CI_PROJECT_DIR")
config._metadata.pop("CI_PROJECT_ID")
config._metadata.pop("CI_PROJECT_NAME")
config._metadata.pop("CI_PROJECT_NAMESPACE")
config._metadata.pop("CI_PROJECT_PATH")
config._metadata.pop("CI_PROJECT_URL")
config._metadata.pop("CI_REGISTRY")
config._metadata.pop("CI_REGISTRY_IMAGE")
config._metadata.pop("CI_REGISTRY_USER")
config._metadata.pop("CI_RUNNER_DESCRIPTION")
config._metadata.pop("CI_RUNNER_ID")
config._metadata.pop("CI_SERVER")
config._metadata.pop("CI_SERVER_NAME")
config._metadata.pop("CI_SERVER_REVISION")
config._metadata.pop("CI_SERVER_VERSION")
config._metadata.pop("GITLAB_CI")
config._metadata.pop("GITLAB_USER_EMAIL")
config._metadata.pop("GITLAB_USER_ID")
config._metadata.pop("JAVA_HOME")
config._metadata.pop("Packages")
config._metadata.pop("Platform")
config._metadata.pop("Plugins")
# 修改Summary部分的信息
def pytest_html_results_summary(prefix, summary, postfix):
from config.configs import Config
test_user = Config().__getattr__("GITLAB_USER_NAME")
prefix.extend([html.p("所属部门: 测试部")])
prefix.extend([html.p("测试人员: {}".format(test_user))])
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if item.function.__doc__ is None:
report.description = str(item.function.__name__)
else:
report.description = str(item.function.__doc__)
report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")