在我的podcasts.py
中,第一行是:
kms = boto3.client('kms')
access_key = kms.decrypt(
CiphertextBlob=base64.b64decode(os.environ['access_key'])
)['Plaintext'].decode()
根据docs,我尝试将其存入我的podcasts_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:
答案 0 :(得分:1)
这似乎是因为应用了Stubber之后正在重新定义客户端,并且它试图真正实现该API。
这是一个基于您的问题的最小示例,因此要使其与您的代码一起使用,您可能必须在重构时更普遍地应用此原理。我还会考虑使用unittest framework。
首先,可以将客户端实例传递到您要测试的代码中。
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)