1.第一个配置我们开关、文件路径 ,新增一个文件: pytest.ini
文件内容如下:
[pytest]
log_cli=true
log_level=NOTSET
log_format = %(asctime)s %(levelname)s %(message)s %(filename)s %(funcName)s %(lineno)d
log_date_format = %Y-%m-%d %H:%M:%S
log_file = ./logdata.log
log_file_level = info
log_file_format = %(asctime)s %(levelname)s %(message)s %(filename)s %(funcName)s %(lineno)d
log_file_date_format = %Y-%m-%d %H:%M:%S
2.添加钩子函数(固定),进行格式设置
新建一个conftest.py文件(文件名不可修改)
添加钩子函数:
# 文件名必须这个,不能改。
# 钩子函数都是框架自带的。pytest的钩子函数
import pytest
import logging
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
# 通过 out = yield 定义了一个生成器。在生成器中,res = out.get_result() 获取了测试结果对象。
out = yield # 类似于return,但是它返回之后执行完毕会自动回来
res = out.get_result()
# res.when == "call":表示正在运行调用测试函数的阶段。
if res.when == "call":
logging.info(f"用例ID:{res.nodeid}")
logging.info(f"测试结果:{res.outcome}")
logging.info(f"故障表示:{res.longrepr}")
logging.info(f"异常:{call.excinfo}")
logging.info(f"用例耗时:{res.duration}")
logging.info("**************************************")