pytest实现日志按用例输出到指定文件中

场景

执行自动化用例时,希望日志按用例生成一个文件,并且按用例所在文件生成目录,用例失败时便于查看日志记录

实现方式

  • pytest.ini文件
    在pytest.ini配置文件中设置配置项(定义日志输出级别和格式)
log_cli=true
log_cli_level = DEBUG
log_file_date_format = %Y-%m-%d %H:%M:%S
log_file_format = %(asctime)s %(filename)s:%(funcName)s:%(lineno)d  %(levelname)s:%(message)s
  • conftest.py文件
    设置日志文件路径
import logging

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_setup(item):   #pytest_runtest_setup是pytest中hook函数,用例执行前都会执行
    file = os.path.basename(item.path) # 获取case所在文件
    logging.info(file)
    config = item.config
    logging_plugin = config.pluginmanager.get_plugin("logging-plugin") #获取logging-plugin,在_pytest/logging.py文件中可以看到此plugin的实现
    full_fname = os.path.join("logs/", file, item._request.node.name + '.log')  #日志文件路径
    logging_plugin.set_log_path(full_fname) #设置日志路径
    yield
  • test_case.py 测试文件
    如下所示编写测试用例, 会在logs文件下生成目录"test_case.py", 并且此目录下会有执行的两个用例的日志文件
import logging
test_data = [{"id": "11111"}, {"id": "2222"}]

@pytest.mark.parametrize("data", test_data,ids=["test1", "test2"])
class TestCase:
    def test_case(self,data):
        logging.inf("test info")
        pass
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值