Python 无法从boto3模拟方法(使用botocore.stub.Stubber)

Python 无法从boto3模拟方法(使用botocore.stub.Stubber),python,boto3,aws-kms,botocore,Python,Boto3,Aws Kms,Botocore,在mypodcasts.py中,我的第一行有: kms = boto3.client('kms') access_key = kms.decrypt( CiphertextBlob=base64.b64decode(os.environ['access_key']) )['Plaintext'].decode() 根据,我试图在我的podcasts\u test.py中存根它: import base64 import os from botocore.stub import Stu

在my
podcasts.py
中,我的第一行有:

kms = boto3.client('kms')
access_key = kms.decrypt(
    CiphertextBlob=base64.b64decode(os.environ['access_key'])
)['Plaintext'].decode()
根据,我试图在我的
podcasts\u test.py
中存根它:

import base64
import os

from botocore.stub import Stubber

os.environ['access_key'] = base64.b64encode('my_test_access_key'.encode()).decode()
client = boto3.client('kms')
stubber = Stubber(client)
stubber.add_response('decrypt', {'Plaintext': b'my_test_key'})
stubber.activate()

import podcasts_build
但我得到:

Traceback (most recent call last):
  File "podcasts_build_test.py", line 14, in <module>
    import podcasts_build
  File "/Users/vitaly/intelligent-speaker/backend/lambdas/podcasts_build/podcasts_build.py", line 23, in <module>
    CiphertextBlob=base64.b64decode(os.environ['access_key'])
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 320, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 623, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.InvalidCiphertextException: An error occurred (InvalidCiphertextException) when calling the Decrypt operation:
回溯(最近一次呼叫最后一次):
文件“podcasts\u build\u test.py”,第14行,在
导入播客
文件“/Users/vitaly/intelligent speaker/backend/lambdas/podcasts\u build/podcasts\u build.py”,第23行,在
CiphertextBlob=base64.b64解码(os.environ['access\u key'])
文件“/usr/local/lib/python3.7/site packages/botocore/client.py”,第320行,在api调用中
返回self.\u make\u api\u调用(操作名称,kwargs)
文件“/usr/local/lib/python3.7/site packages/botocore/client.py”,第623行,在make\u api\u调用中
引发错误\u类(解析的\u响应、操作\u名称)
botocore.errorfactory.InvalidCiphertextException:调用解密操作时发生错误(InvalidCiphertextException):

造成这种情况的原因似乎是应用stuber后重新定义了客户机,并且它正试图真正使用API

这是一个基于您的问题的最小示例,因此要使其与您的代码一起工作,您可能需要在重构时更普遍地应用这一原则。我还将考虑使用.< /P> 首先,可以将客户机实例传递到正在测试的代码中

podcasts.py:

def decrypt_kms(kms_client):
    access_key = kms_client.decrypt(
        CiphertextBlob=base64.b64decode(os.environ['access_key'])
    )['Plaintext'].decode()
    return access_key
然后在测试中,创建存根客户机并将其传递到要测试的代码中

tests.py:

from botocore.stub import Stubber
from podcasts import decrypt_kms

kms_decrypt_response = {'Plaintext': 'my_test_key'}
stubbed_client = boto3.client('kms')
stubber = Stubber(stubbed_client)
stubber.add_response('decrypt', kms_decrypt_response)
stubber.activate()
result = decrypt_kms(kms_client=stubbed_client)

我的模拟响应被返回,但在返回之后,出现了相同的异常。已尝试在我要测试的产品代码中
print()
响应-无响应。请尝试以接受客户端实例的方法重新编写生产代码。我会更新我的答案。