Skip to content

Instantly share code, notes, and snippets.

@mikegrima
Last active March 25, 2024 15:41
Show Gist options
  • Save mikegrima/c46a3da584dee019f3003ecd3babe1a7 to your computer and use it in GitHub Desktop.
Save mikegrima/c46a3da584dee019f3003ecd3babe1a7 to your computer and use it in GitHub Desktop.
pytest fixture to mock out the moto AWS Lambda capability such that it DOES NOT try to execute the code in a Docker container
import pytest
import moto
from mock import mock, patch
from moto import mock_lambda
@pytest.fixture(scope='function')
def aws_credentials():
"""Mocked AWS Credentials for moto."""
os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
os.environ['AWS_SECURITY_TOKEN'] = 'testing'
os.environ['AWS_SESSION_TOKEN'] = 'testing'
@pytest.fixture(scope='function')
def lambda_mock(aws_credentials):
with mock_lambda():
yield boto3.client('lambda', region_name='us-east-1')
@pytest.fixture(scope='function')
def no_docker_lambda(lambda_mock):
# Mock out the moto lambda code so that it __does not__ make a Docker container to run it 🤦
p = patch.object(moto.awslambda.models.LambdaFunction, 'invoke', lambda *args, **kwargs: '{}')
p.start()
lambda_mock.create_function(FunctionName='some-function',
Runtime='python3.7',
Role='somerole',
Handler='lambda_handler',
Code={'ZipFile': b'muh lamduh'})
yield
p.stop()
def test_lambda(lambda_mock, no_docker_lambda):
lambda_mock.invoke(FunctionName='some-function', InvocationType='Event', Payload='{}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment