Reputation: 83
I have an AWS lambda written in python. The lambda downloads a file from S3 to the folder /tmp/records. Then the lambda reads that file. Now I need to write a unit test for that. I need to mock the S3 call. I am wondering how to do that.
Here is my Lambda:
import os
import boto3
s3 = boto3.resource("s3")
def lambda_handler(event, context):
try:
download_records()
with open("/tmp/records/" + "go_message.json.j2") as f:
record = f.read()
except ValueError:
return "record could not be found"
def download_s3_folder(bucket_name, s3_folder, local_dir=None):
bucket = s3.Bucket(bucket_name)
for obj in bucket.objects.filter(Prefix=s3_folder):
target = (
obj.key
if local_dir is None
else os.path.join(local_dir, os.path.relpath(obj.key, s3_folder))
)
if not os.path.exists(os.path.dirname(target)):
os.makedirs(os.path.dirname(target))
if obj.key[-1] == "/":
continue
bucket.download_file(obj.key, target)
return True
def download_records(record=False):
download_s3_folder("sss-records-dev", "subscription", "/tmp/records")
Here is unittest:
import os
import sys
import unittest
from pathlib import Path
import mock # type: ignore
boto3_mock = mock.MagicMock()
sys.modules["boto3"] = boto3_mock
from testing_lambda import ( # noqa: E402 isort:skip
testing_lambda,
)
class TestingLambdaTests(unittest.TestCase):
def _test_message(self):
result = testing_lambda.lambda_handler(None, context="")
def test_package_for_promo(self):
self._test_message()
if __name__ == "__main__":
unittest.main()
I am getting this error when I run unittest: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/records/go_message.json.j2'
Upvotes: 1
Views: 263