Skip to content

Commit

Permalink
add lambda test (#796)
Browse files Browse the repository at this point in the history
  • Loading branch information
thehesiod committed Apr 10, 2020
1 parent 9e2f56b commit b86e8ce
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 2 deletions.
16 changes: 16 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,22 @@ async def batch_client(session, region, config, batch_server, mocking_test):
yield client


@pytest.fixture
async def lambda_client(session, region, config, lambda_server, mocking_test):
kw = moto_config(lambda_server) if mocking_test else {}
async with session.create_client('lambda', region_name=region,
config=config, **kw) as client:
yield client


@pytest.fixture
async def iam_client(session, region, config, iam_server, mocking_test):
kw = moto_config(iam_server) if mocking_test else {}
async with session.create_client('iam', region_name=region,
config=config, **kw) as client:
yield client


async def recursive_delete(s3_client, bucket_name):
# Recursively deletes a bucket and all of its contents.
paginator = s3_client.get_paginator('list_object_versions')
Expand Down
14 changes: 13 additions & 1 deletion tests/mock_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def __init__(self):
super().__init__(target=self._run)
self._loop = None
self._port = get_free_tcp_port(True)
self.endpoint_url = 'http://{}:{}'.format(host, self._port)
self.endpoint_url = f'http://{host}:{self._port}'
self.daemon = True # die when parent dies

def _run(self):
Expand Down Expand Up @@ -128,3 +128,15 @@ async def sqs_server():
async def batch_server():
async with MotoService('batch') as svc:
yield svc.endpoint_url


@pytest.fixture
async def lambda_server():
async with MotoService('lambda') as svc:
yield svc.endpoint_url


@pytest.fixture
async def iam_server():
async with MotoService('iam') as svc:
yield svc.endpoint_url
2 changes: 1 addition & 1 deletion tests/moto_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

def get_free_tcp_port(release_socket: bool = False):
sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sckt.bind(('', 0))
sckt.bind((host, 0))
addr, port = sckt.getsockname()
if release_socket:
sckt.close()
Expand Down
68 changes: 68 additions & 0 deletions tests/test_lambda.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import base64
import io
import json
import zipfile

# Third Party
import botocore.client
import pytest


async def _get_role_arn(iam_client, role_name: str):
try:
response = await iam_client.get_role(RoleName=role_name)
return response["Role"]["Arn"]
except botocore.client.ClientError:
response = await iam_client.create_role(
RoleName=role_name,
AssumeRolePolicyDocument="some policy",
Path="/my-path/",
)
return response["Role"]["Arn"]


def _process_lambda(func_str) -> bytes:
zip_output = io.BytesIO()
zip_file = zipfile.ZipFile(zip_output, "w", zipfile.ZIP_DEFLATED)
zip_file.writestr("lambda_function.py", func_str)
zip_file.close()
zip_output.seek(0)
return zip_output.read()


@pytest.fixture
def aws_lambda_zip() -> bytes:
lambda_src = """
import json
def lambda_handler(event, context):
print(event)
return {"statusCode": 200, "body": event}
"""
return _process_lambda(lambda_src)


@pytest.mark.moto
@pytest.mark.asyncio
async def test_run_lambda(iam_client, lambda_client, aws_lambda_zip):
role_arn = await _get_role_arn(iam_client, 'test-iam-role')
lambda_response = await lambda_client.create_function(
FunctionName='test-function', Runtime='python3.8',
Role=role_arn, Handler='lambda_function.lambda_handler',
Timeout=10, MemorySize=128, Publish=True,
Code={'ZipFile': aws_lambda_zip}
)
assert lambda_response['FunctionName'] == 'test-function'

invoke_response = await lambda_client.invoke(
FunctionName="test-function",
InvocationType="RequestResponse",
Payload=json.dumps({"hello": "world"}),
)

async with invoke_response['Payload'] as stream:
data = await stream.read()

log_result = base64.b64decode(invoke_response["LogResult"])

assert data is not None and data == log_result
assert b'{"hello":"world"}' in log_result

0 comments on commit b86e8ce

Please sign in to comment.