You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pytest日志中按测试模块添加结束分隔标记?

实现方法

这个需求完全可以实现,用pytest的模块级自动fixture就能搞定,具体步骤如下:

  • 在项目根目录的conftest.py文件中添加以下代码:
import logging
import os
import pytest

# 获取已配置的日志器
logger = logging.getLogger(__name__)

@pytest.fixture(scope="module", autouse=True)
def log_module_finish(request):
    # 前置逻辑(不需要可留空)
    yield
    # 测试模块执行完成后触发这里的逻辑
    # 提取测试模块的文件名,比如tests_app.py → App
    module_file = request.module.__file__
    module_base = os.path.splitext(os.path.basename(module_file))[0]
    module_name = module_base.replace("tests_", "").capitalize()
    # 构造分隔标记
    finish_mark = f"================================= {module_name} tests finished =================================="
    # 写入日志
    logger.info(finish_mark)
  • 代码说明:
    • scope="module":这个fixture的作用域是整个测试模块,每个测试文件只会执行一次teardown逻辑
    • autouse=True:自动应用到所有测试模块,不用在每个测试文件里手动调用
    • 通过request.module.__file__获取当前测试模块的路径,进而提取出模块名称(自动去掉tests_前缀并首字母大写)
    • 最后用你已配置好的logging模块输出分隔标记,会自动写入到../logs/test.log中

如果不想给所有测试模块都加这个日志,可以把autouse=True删掉,然后在需要的测试文件里手动引入这个fixture:

def test_something(log_module_finish):
    # 测试逻辑
    pass

内容的提问来源于stack exchange,提问作者Jared

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:22:12