首页 > 解决方案 > Python中具有try/except语句的单元测试函数

问题描述

我的班级有一个名为 updateTag 的方法,它针对 AWS 端点执行命令。我为它创建了一个单元测试并模拟了 AWS 调用,但我不知道如何测试 except 块。

当我执行 updateTag 时,如果 DryRun 为 False,它应该返回 0,如果是 True,它应该返回 1

你可以帮帮我吗?

这是我的功能:

def updateTag(self, resourceInterface: boto3.resource, commandExpression: str):
    response = {'command': commandExpression,
                'returnCode': bool, 'error': []}
    try:
        eval('resourceInterface.' + commandExpression)
        response['returnCode'] = 0
    except Exception as e:
        response['returnCode'] = 1
        response['error'] = e.args

    return response

这是我的单元测试代码:

    def test_updateTag_with_string_command_and_dryrun_set_false_should_pass(self):
        commandsExpression = "Image('ami-0b1116af7f69faeab').create_tags(DryRun=False,Tags=[{'Key':'state', 'Value': 'expired'}, {'Key': 'timestamp', 'Value':'expired#2019-11-13T22:46:32.725Z'}])"
        boto3 = MagicMock()
        ec2Resource = boto3.resource('ec2')
        imageLifecycle = Lifecycle(self.lifeCycleRules, self.dryRunEnabled)
        response = imageLifecycle.updateTag(ec2Resource, commandsExpression)
        self.assertEqual(response['returnCode'],0)

    def test_updateTag_with_string_command_and_dryrun_set_true_should_pass(self):
        commandsExpression = "Image('ami-00000000000000000').create_tags(DryRun=True,Tags=[{'Key':'state', 'Value': 'expired'}, {'Key': 'timestamp', 'Value':'expired#2019-11-13T22:46:32.725Z'}])"
        boto3 = MagicMock()
        ec2Resource = boto3.resource('ec2')
        imageLifecycle = Lifecycle(self.lifeCycleRules, self.dryRunEnabled)
        response = imageLifecycle.updateTag(ec2Resource, commandsExpression)
        self.assertEqual(response['returnCode'],1)

谢谢你。

标签: pythonunit-testingmockingtry-except

解决方案


推荐阅读