2017-08-10 143 views
0

我正在尝试为aws RDS编写一些单元测试。目前,启动停止rds api调用还没有在moto中实现。我试图嘲笑boto3,但遇到各种奇怪的问题。我做了一些谷歌搜索,发现http://botocore.readthedocs.io/en/latest/reference/stubber.htmlaws boto3客户端Stubber帮助存根单元测试

所以我试图实施RDS的例子,但似乎表现得像普通客户,即使我已经掐灭它的代码。不知道发生了什么事,或者我是否正确存根?

from LambdaRdsStartStop.lambda_function import lambda_handler 
from LambdaRdsStartStop.lambda_function import AWS_REGION 

def tests_turn_db_on_when_cw_event_matches_tag_value(self, mock_boto): 
    client = boto3.client('rds', AWS_REGION) 
    stubber = Stubber(client) 
    response = {u'DBInstances': [some copy pasted real data here], extra_info_about_call: extra_info} 
    stubber.add_response('describe_db_instances', response, {}) 

    with stubber: 
     r = client.describe_db_instances() 
     lambda_handler({u'AutoStart': u'10:00:00+10:00/mon'}, 'context') 

因此,stubber内部第一行的模拟工作和r的值将作为我的存根数据返回。当我试图进入我的lambda_handler方法我lambda_function.py内,仍然使用存根客户端,它的行为像一个正常的unstubbed客户端:

lambda_function.py

def lambda_handler(event, context): 
    rds_client = boto3.client('rds', region_name=AWS_REGION) 
    rds_instances = rds_client.describe_db_instances() 

错误输出:

File "D:\dev\projects\virtual_envs\rds_sloth\lib\site-packages\botocore\auth.py", line 340, in add_auth 
    raise NoCredentialsError 
NoCredentialsError: Unable to locate credentials 
+0

的stubber在一个典型的模拟的好处是,它的行为几乎完全像一个客户减去制造实际的http请求。因此,您仍然需要使用凭证设置客户端并配置区域,否则会出现这样的错误。 –

+0

嗨乔丹,我想你可能误解了我的帖子。在我的测试中嘲笑工程,直到我尝试在另一个文件中初始化客户端 - > lambda_function.py –

+0

您似乎没有将存根客户端传递给您的lambda处理程序。 –

回答

2

您将需要在要测试的例行程序中调用boto3。此外Stubber反应似乎在每次调用被消耗,因此将需要另一个add_response详情如下,每个存根电话:

def tests_turn_db_on_when_cw_event_matches_tag_value(self, mock_boto): 
    client = boto3.client('rds', AWS_REGION) 
    stubber = Stubber(client) 
    # response data below should match aws documentation otherwise more errors due to botocore error handling 
    response = {u'DBInstances': [{'DBInstanceIdentifier': 'rds_response1'}, {'DBInstanceIdentifierrd': 'rds_response2'}]} 

    stubber.add_response('describe_db_instances', response, {}) 
    stubber.add_response('describe_db_instances', response, {}) 

    with mock.patch('lambda_handler.boto3') as mock_boto3: 
     with stubber: 
      r = client.describe_db_instances() # first_add_response consumed here 
      mock_boto3.client.return_value = client 
      response=lambda_handler({u'AutoStart': u'10:00:00+10:00/mon'}, 'context') # second_add_response would be consumed here 
      # asert.equal(r,response)