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

如何使用pytest fixtures的yield特性清理测试残留资源

解决方案

核心思路

pytest的fixture支持yield语法实现资源的创建/销毁分离:yield之前的代码为测试前置逻辑,用于创建AWS Service Catalog资源;yield之后的代码为后置清理逻辑,无论测试用例出现断言失败、运行异常还是正常执行完成,这部分代码都会被触发,从根本上解决资源残留问题。

实现步骤

1. 封装资源管理fixture

将原来散落在测试用例中的产品启动、信息查询、资源删除逻辑统一封装到fixture中:

import pytest
import subprocess
# 导入原有业务依赖:日志对象logger、Service Catalog客户端client、launch_product、delete_product方法等

@pytest.fixture(scope="function")
def sc_provisioned_product(request, role, product, storagerole):
    # 前置逻辑:启动SC产品
    product_name, result = launch_product(role, product, storagerole)
    logger.info("Creating pod with storagerole: {}".format(storagerole))
    assert result, f'Product {product} 无法被角色 {role} 启动,切换角色为 {storagerole}'

    # 获取pod唯一标识
    pod_unique_id = None
    for key in client.get_provisioned_product_outputs(ProvisionedProductName=product_name)["Outputs"]:
        if key["OutputKey"] == 'SSH':
            pod_unique_id = key["OutputValue"].split('-')[1]
            break
    
    # 查询启动的pod名称
    querypod = f"kubectl get po -n rstudio | grep {pod_unique_id} | awk 'END {{print $1}}'| tr -d '\n'"
    launched_pod = subprocess.check_output(querypod, shell=True).decode()
    logger.info("Provisioned pod: {}".format(launched_pod))

    # 向测试用例返回需要用到的参数
    yield product_name, launched_pod

    # 后置清理逻辑:无论测试结果如何都会执行
    logger.info("Start cleaning up Service Catalog product: {}".format(product_name))
    delete_result = delete_product(role, product_name)
    assert delete_result, f'Product {product_name} 无法被角色 {role} 删除'

2. 改造测试用例

测试用例无需再关心资源的创建和清理,只需要引入fixture,专注于业务断言即可:

# 可通过parametrize批量传入不同测试参数,适配多场景验证
@pytest.mark.parametrize("role, product, storagerole", [
    ("test-op-role", "rstudio-standard", "s3-readonly-role"),
    ("test-dev-role", "rstudio-gpu", "efs-fullaccess-role")
])
def test_storagerole_assume(sc_provisioned_product, storagerole):
    product_name, launched_pod = sc_provisioned_product
    cmd = f"kubectl -n rstudio exec {launched_pod} -- aws sts get-caller-identity"
    
    output = subprocess.check_output(cmd, shell=True).decode()
    # 仅保留业务断言逻辑
    assert f"assumed-role/{storagerole}/kiam-kiam" in output, f'容器内未成功切换到预期角色 {storagerole}'

方案优势

  • 逻辑解耦:资源生命周期管理全部收敛到fixture,测试用例仅关注业务逻辑,代码简洁易维护
  • 清理可靠:后置逻辑不受测试运行状态影响,彻底解决断言失败导致的资源残留问题
  • 复用性强:所有需要用到SC产品的测试用例都可以直接复用该fixture,无需重复编写创建、清理代码

内容的提问来源于stack exchange,提问作者Sonal Kakkar Chawla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:24:03