pytest.ini 文件的配置:
[pytest]
;这是让log输出到控制台
log_cli=1
;设置log输出等级
log_level=info
;控制台输出的格式
log_cli_format = %(asctime)s [%(levelname)s] %(message)s [%(filename)s:%(lineno)s]
log_cli_date_format = %Y-%m-%d %H:%M:%S
;输出到log文件的格式
log_file_format = %(asctime)s [%(levelname)s] %(message)s [%(filename)s:%(lineno)s]
log_file_date_format = %Y-%m-%d %H:%M:%S
也可以在命令行输入: pytest -h 查看其他的配置信息
conftest.py 的代码
#先执行pytest.ini,再执行conftest.py
import pytest, platform, sys, requests, pymysql, pandas, pytest_html, os, time
from py.xml import html
report_title="Apitest接口测试报告名称"
project_name="Apitest项目名称"
now=time.strftime('%Y%m%d') #以日期时间做报告文件名,'%Y%m%d_%H%M%S'
logfile_name=f'{now}.log' #日志文件名
# 测试报告名称
def pytest_html_report_title(report):
report.title = report_title
# 日志文件名和Environment部分配置
def pytest_configure(config):
# 如果只需要输出log日志只要设置此行就可下方的都删掉就行,意思设置log输出文件目录
config.option.log_file = os.path.join(config.rootdir, 'log', logfile_name)
# 删除项
if 'JAVA_HOME' in config._metadata:
config._metadata.pop("JAVA_HOME")
config._metadata.pop("Packages")
config._metadata.pop("Platform")
config._metadata.pop("Plugins")
config._metadata.pop("Python")
# 添加项
config._metadata["平台"] = platform.platform()
config._metadata["Python版本"] = platform.python_version()
config._metadata["包"] = f'Requests({requests.__version__}),PyMySQL({pymysql.__version__}),Pandas({pandas.__version__}),Pytest({pytest.__version__}),Pytest-html({pytest_html.__version__})'
config._metadata["项目名称"] = project_name
# 在result表格中添加测试描述列
@pytest.mark.optionalhook
def pytest_html_results_table_header(cells): #添加列
cells.insert(1, html.th('测试描述')) #第2列处添加一列,列名测试描述
cells.pop()
# 修改result表格测试描述列的数据来源
@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells): #添加数据
cells.insert(1, html.td(report.description)) #第2列的数据
cells.pop()
# 修改result表格测试描述列的数据
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.description = str(item.function.__doc__) #函数注释文档字符串
# # 测试统计部分添加测试部门和人员
# @pytest.mark.optionalhook
# def pytest_html_results_summary(prefix):
# prefix.extend([html.p("所属部门: 自动化测试部")])
# prefix.extend([html.p("测试人员: ***")])
# 解决参数化时汉字不显示问题
def pytest_collection_modifyitems(items):
#下面3行只能解决控制台中,参数化时汉字不显示问题
# for item in items:
# item.name = item.name.encode('utf-8').decode('unicode-escape')
# item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape')
#下面3行只能解决测试报告中,参数化时汉字不显示问题
outcome = yield
report = outcome.get_result()
report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")
pytest运行时会先读取pytest.ini中的配置信息,之后就会运行conftest.py中的代码。config类pytest运行时会调用所以我们设置config.option.log_file的路径就可以了。
将pytest.ini与conftest.py文件都放在项目的根目录下就只运行一次。