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

如何拆分pytest测试为独立分组,实现每次全新运行?

解决pytest批量参数化用例内存超限问题

问题背景

  • 测试框架在tests/setup/conftest目录外存在逻辑,会在collect阶段创建实例从数据库获取数据,生成pytest.mark.parametrize所需的测试用例
  • 部分场景下数据量可达500万条,即使做了优化,collect阶段峰值内存仍达11GB,超出Docker 8GB内存限制
  • 计划将原始数据拆分为本地存储的多个分片,每次运行仅加载20万条用例(该规模在内存可接受范围内)

尝试过的无效方案

曾尝试编写独立Python脚本,循环调用pytest.main()并传入不同批次参数,但同一Python进程内的单例实例会被复用,无法根据新批次数据重新初始化:

class Logger:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            print("Creating new instance")
            cls._instance = super(Logger, cls).__new__(cls)
        return cls._instance

import pytest

def test_1():
    pytest.logger = Logger()
    print(f'{id(pytest.logger)=}')

def test_2():
    pytest.logger = Logger()
    print(f'{id(pytest.logger)=}')

if __name__ == "__main__":
    pytest.main(['-k', 'test_1'])
    pytest.main(['-k', 'test_2'])

运行结果显示单例实例未重新创建:

id(pytest.logger) = 140325718144768
id(pytest.logger) = 140325718144768

其他无效方案:

  • 收集后拆分测试:仍会先加载500万条用例,直接触发内存崩溃
  • 使用@pytest.mark标记测试:单个标记可能对应多达400万条用例,不具备可操作性

可行方案:subprocess启动独立pytest进程+合并报告

通过subprocess.run为每个测试批次启动独立的pytest进程,彻底避免单例复用问题,最后合并所有批次的测试报告:

# run_batches.py

filtered_batches = sorted(filter(lambda _batch: case_name.lower() in _batch, os.listdir(json_batches_path)))
for batch in filtered_batches:
    subprocess.run(
        [
            "pytest",
            f"--single-report={report_folder}",
            f"--batch={batch}",
            "-q",
            "--tb=no",
            "--capture=no",
            "-p no:cacheprovider"
        ]
    )

# 合并所有报告
subprocess.run(["pytest", f"--merge-report={report_folder}"])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 22:33:22