如何使用 pytest 夹具产量清理剩余物?

问题描述 投票:0回答:1

目前,如果测试因任何原因失败,则在 AWS 服务目录(SC)中创建的对象可以在测试完成后保留在那里,因为所有失败的断言都会停止脚本,因此无法调用后清理几行。

代码示例:

product_name, result = launch_product(role, product, storagerole)
    logger.info("Creating pod with storagerole: {}".format(storagerole))
    assert result, 'Product ' + product + ' could not be launched by role ' + role + ' assuming role ' + storagerole

    # Get part of pod unique name
    for key in client.get_provisioned_product_outputs(ProvisionedProductName=product_name)["Outputs"]:
        if key["OutputKey"] == 'SSH':
            pod_unique_id = key["OutputValue"].split('-')[1]

    # Pick up pod with selected unique name
    querypod = "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("Checking pod: {}".format(launched_pod))
    cmd = "kubectl -n rstudio exec " + launched_pod + " -- aws sts get-caller-identity"

    try:
        output = subprocess.check_output(cmd, shell=True).decode()
    except subprocess.CalledProcessError as error:
        logger.error("error: {}".format(error))
        assert delete_product(role, product_name), 'Product ' + product_name + ' could not be deleted by role ' + role
        assert False, error
    try:
        assert "assumed-role/" + storagerole + "/kiam-kiam" in output, 'Expected role ' + storagerole + ' was not assumed within container'
    except AssertionError as error:
        logger.error("error: {}".format(error))
        assert delete_product(role, product_name), 'Product ' + product_name + ' could not be deleted by role ' + role
        assert False, error

    logger.info("All steps passed, deleting pod: {}".format(launched_pod))
    assert delete_product(role, product_name), 'Product ' + product_name + ' could not be deleted by role ' + role

即使使用 pytest 装置任何断言失败,我们如何制定清理残留物的解决方案?

python pytest yield fixtures teardown
1个回答
0
投票

您将需要一个带有固定装饰器的方法,如下所示。然后在该方法中,您需要使用

yield
跳转到测试方法,然后返回到夹具以在完成测试后进行任何清理。

@pytest.fixture()
def setup(self):
    # do setup stuff
    yield # go to test_xyz
    # return here after test_xyz for cleanup
    assert delete_product(role, product_name), 'Product ' + product_name + ' could not be deleted by role ' + role
© www.soinside.com 2019 - 2024. All rights reserved.