![](/img/trans.png)
[英]How to mock global variable in a imported module in python unit test?
[英]Unit test for Python AWS Lambda: mock function before module is imported
我正在嘗試為我用 python 3.9
編寫的 aws lambda function 編寫單元測試。 我嘗試了不同的方法來模擬調用S3
的get_object
function 。 我只想專注於calculate
方法,以驗證我是否得到了正確的計算結果。
當我嘗試運行以下方法時,我收到有關boto3
的憑據錯誤
python -m unittest tests/app-test.py
...
botocore.exceptions.NoCredentialsError: Unable to locate credentials
有沒有辦法從app.py
導入calculate
方法並模擬調用get_object
fn?
目錄:
functions:
- __init__.py
- app.py
tests:
- __init__.py
- app-test.py
lambda function app.py
:
import json
import boto3
def get_object():
s3 = boto3.client('s3')
response = s3.get_object(Bucket='mybucket', Key='object.json')
content = response['Body'].read().decode('utf-8')
return json.loads(content)
stops = get_object()
def lambda_handler(event, context):
params = event['queryStringParameters']
a = int(params['a'])
b = int(params['b'])
result = calculate(a, b)
return {
'statusCode': 200,
'body': json.dumps(result)
}
def calculate(a, b):
return a + b
單元測試app-test.py
:
import unittest
from unittest import mock
with mock.patch('functions.app.get_object', return_value={}):
from functions.app import calculate
class TestCalculation(unittest.TestCase):
def test_should_return_correct_calculation(self):
# when
result = calculate(1, 2)
# then
self.assertEqual(3, result)
我能夠解決這個問題。 最大的障礙是在boto3
中模擬app.py
。 我這樣做是通過 mocking 在導入整個boto3
模塊之前完成的。 這是app-test.py
的代碼
import sys
from io import BytesIO
from json import dumps
from unittest import TestCase, main
from unittest.mock import Mock
from botocore.stub import Stubber
from botocore.session import get_session
from botocore.response import StreamingBody
# prepare mocks for boto3
stubbed_client = get_session().create_client('s3')
stubber = Stubber(stubbed_client)
# mock response from S3
body_encoded = dumps({'name': 'hello world'}).encode()
body = StreamingBody(BytesIO(body_encoded), len(body_encoded))
stubbed.add_response('get_object', {'Body': body})
stubber.activate()
# add mocks to the real module
sys.modules['boto3'] = Mock()
sys.modules['boto3'].client = Mock(return_value=stubbed_client)
# Import the module that will be tested
# boto3 should be mocked in the app.py
from functions.app import calculate
class TestCalculation(TestCase):
def test_should_return_correct_calculation(self):
# when
result = calculate(1, 2)
# then
self.assertEqual(3, result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.