pytest log日志输出到文件

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文件都放在项目的根目录下就只运行一次。

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Pytest中,可以使用`-r`选项来输出测试结果的详细信息,包括测试结果、测试耗时、测试文件名等。你可以将这些信息重定向到一个日志文件中,并使用`-s`选项在终端上输出运行日志。 如果你想控制日志文件的大小,可以考虑使用Python内置的`RotatingFileHandler`类,该类可以在日志文件达到指定大小时自动滚动日志,以避免日志文件过大。 以下是一个示例代码,可以在Pytest中使用`RotatingFileHandler`类来控制日志文件大小: ```python import logging import pytest from logging.handlers import RotatingFileHandler # 定义日志文件名和路径 log_file = "test.log" log_path = "./logs" # 创建RotatingFileHandler对象,设置日志文件大小为10MB,保留最近3个日志文件 handler = RotatingFileHandler(filename=log_file, mode='a', maxBytes=10*1024*1024, backupCount=3) # 设置日志级别为INFO handler.setLevel(logging.INFO) # 定义日志格式 formatter = logging.Formatter('[%(asctime)s] %(levelname)s: %(message)s') handler.setFormatter(formatter) # 添加handler到root logger中 logging.getLogger('').addHandler(handler) def test_example(): logging.info("Running test example...") # 测试代码 assert 1 == 1 if __name__ == "__main__": # 运行pytest,并将日志输出到控制台和日志文件pytest.main(["-s", "-rA", "--log-file={}/{}".format(log_path, log_file)]) ``` 在这个示例中,我们创建了一个`RotatingFileHandler`对象,并将其添加到root logger中。然后,我们定义了一个测试函数`test_example()`,在其中使用`logging`模块写入日志信息。最后,我们使用Pytest运行测试,并将日志输出到控制台和日志文件中。你可以在`RotatingFileHandler`构造函数中根据需要调整`maxBytes`和`backupCount`参数来控制日志文件大小和保留的日志文件数量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值