python - 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)
谢谢你。
解决方案
推荐阅读
- google-app-engine - Google App Engine dispatch.yaml 意外属性“服务”
- sql - 在内部联接中选择不同的值
- grails - Grails 插件数据库迁移使用 hashmap 添加域对象
- java - Oracle JDK 公开更新到 2019 年 1 月 31 日还是 2019 年 1 月 1 日?
- ms-access - Access 找不到我刚刚创建的程序
- sql-server - 最佳实践指南:发布到服务器以获取 SQL 查询数据并将用户重定向回带有数据的 UI
- python-2.7 - 在 Python 2 中重置 GUI 值
- magento2 - 在产品页面 magento 2 上获取选定的产品库存数量
- javascript - 打印另一页,但留在当前页上
- r - Extract parameters from EMCluster package