I am writing a unit test for my lambda function using pytest. I cannot figure out how should I pass my event parameters to the function call. I learnt that it can be achieved using @pytest.fixture. I am very very new to Python and pytest. Believe I am using fixures in the wrong way. Please help me!!
Below is my lambda handler:
lambda_service.py
def lambda_handler(event, context):
logger.info('Event received: ' + json.dumps(event))
try:
sort = (event['sort'])
size = int(event['size'])
page = int(event['page'])
list_response = MyService().get_people_list(sort, size, page)
logger.info(list_response)
except Exception as e:
logger.error("Unable to fetch details")
logger.exception(e)
return list_response
This is my test class-
class TestServiceHandler:
@pytest.fixture
def event(self):
return {
"sort": "asc",
"size": 5,
"page": 0
}
@pytest.fixture
def context(self):
return None
def test_lambda_handler(self):
result = lambda_service.lambda_handler(self.event, self.context)
assert_valid_schema(result, 'vendor_list.json')
And I am getting below error when running this test
line 17, in lambda_handler
sort = (event['sort'])\nTypeError: 'method' object is not subscriptable"
Though I am passing event and context in fixtures, it is still referring to event[sort]
inside lambda_handler
.
Event and contextEvent object is the first argument of the handler function and contains information about the event, for example an API request event holds the HTTP request object. Context object contains information about the invocation, function configuration and execution environment.
const awsUrl = "https://random-id.execute-api.us-west-2.amazonaws.com/default/lambda-function"; let event = { "queryStringParameters": { "gdrive_folder_id": consFolderId, "invitee_email": email } }; let response = await fetch(awsUrl, { method: "POST", body: JSON.
Just like a normal function, a Lambda function can have multiple arguments with one expression. In Python, lambda expressions (or lambda forms) are utilized to construct anonymous functions. To do so, you will use the lambda keyword (just as you use def to define normal functions).
This function handler name reflects the function name ( lambda_handler ) and the file where the handler code is stored ( lambda_function.py ). To change the function handler name in the Lambda console, on the Runtime settings pane, choose Edit.
You've defined the fixtures correctly, but using them wrong. To fix, add arguments to the test_lambda_handler
method named exactly as the fixtures. When running tests, pytest
will analyze each argument and insert the fixture return value if it can find a fixture with that name. Example:
class TestServiceHandler:
@pytest.fixture
def event(self):
...
@pytest.fixture
def context(self):
...
def test_lambda_handler(self, event, context):
result = lambda_service.lambda_handler(event, context)
assert ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With