Python中具有try/except statamen的单元测试函数

2024-09-30 00:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当我执行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)

多谢各位


Tags: keyselfvalueresponsedefboto3resourcedryrun

热门问题