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

如何用pytest实现硬件在环测试用例的流水线复用?求推荐框架

适配硬件在环测试流水线复用需求的框架推荐

核心思路

你已经基于pytest编写了独立的硬件测试用例(如TestCamera、TestAudio),现在要实现运行时响应式的系统测试流水线,核心是把现有pytest用例集成到事件驱动/循环执行的工作流中,同时支持同步/异步批量执行。以下是几种适配的方案:

推荐框架与实现方案

1. pytest原生扩展(轻量快速方案)

pytest支持通过pytest.main()在代码中直接调用测试用例,结合Python线程/协程就能实现流水线执行,完全复用现有用例:

# system_test.py
import pytest
import asyncio

async def run_test_suite(test_class_name):
    # 异步运行指定测试类
    result = await asyncio.to_thread(
        pytest.main, [f"-k {test_class_name}", "--tb=short"]
    )
    return result == 0  # 返回测试是否通过

async def handle_user_input(user_input):
    # 映射用户输入到对应测试类
    test_mapping = {
        "camera": "TestCamera",
        "audio": "TestAudio"
        # 可扩展其他硬件测试映射
    }
    target_test = test_mapping.get(user_input)
    if target_test:
        success = await run_test_suite(target_test)
        print(f"{target_test}测试结果: {'通过' if success else '失败'}")

async def main():
    while phone_is_booted():
        user_input = get_user_input_over_simulated_screen()
        await handle_user_input(user_input)

if __name__ == "__main__":
    asyncio.run(main())

这种方案无需额外学习新框架,适合快速落地需求。

2. pytest-xdist(并行执行方案)

如果需要同时运行多个硬件测试用例(比如并行测试相机和音频),可以用pytest-xdist扩展实现多进程并行执行:

# 修改run_test_suite中的pytest参数
result = await asyncio.to_thread(
    pytest.main, [f"-k {test_class_name}", "-n auto", "--tb=short"]
)

-n auto会自动根据CPU核心数分配并行进程,提升多硬件模块测试的效率。

3. Robot Framework(复杂流水线编排)

如果需要更复杂的测试流程编排(比如依赖前置测试、条件分支、多步骤流水线),可以将pytest用例封装为Robot Framework的关键字,在Robot中定义可视化的流水线逻辑,响应用户输入执行对应测试流。这种方案优势在于测试流程易读易维护,适合团队协作场景。

4. 自定义测试调度器(完全定制方案)

如果以上框架无法满足个性化需求,可基于Python的concurrent.futures或asyncio实现自定义调度器,完全掌控测试执行逻辑:

from concurrent.futures import ThreadPoolExecutor

def run_test(test_class_name):
    # 直接调用pytest内部API执行测试
    from _pytest.main import Session
    from _pytest.config import Config
    config = Config.from_args([f"-k {test_class_name}"])
    session = Session(config)
    session.perform_collect()
    return session.run()

# 线程池实现流水线执行
with ThreadPoolExecutor(max_workers=3) as executor:
    while phone_is_booted():
        user_input = get_user_input_over_simulated_screen()
        test_class = get_test_class_from_input(user_input)
        future = executor.submit(run_test, test_class)
        # 处理测试结果
        result = future.result()

这种方案灵活性最高,但需要自行维护测试执行的细节逻辑。

关键注意事项

  • 硬件资源隔离:若多个测试用例操作同一硬件(如相机),需添加锁或串行执行,避免资源竞争导致的测试失败。
  • 异步安全:如果硬件驱动不支持异步操作,优先使用线程而非协程,防止阻塞事件循环。
  • 结果持久化:可结合pytest-html生成测试报告,或把结果写入数据库,方便后续分析与回溯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:25:21