Writing Unit Tests for My Lambda Function with pytest and moto

writing-unit-tests-for-my-lambda-function-with-pytest-and-moto

I genuinely believed I’d be able to do both Step 11 and Step 12 of the Cloud Resume Challenge this week, but alas, I only got through Step 11. I’m not disappointed, because time is the cost of learning. It would all be in vain if I sped through without understanding what I was actually doing, right?

Updating the Lambda function

I updated my Lambda function so it checks for POST, then GET (using elif), and returns a 405 for anything else. This isn’t strictly necessary, because my API Gateway only allows POST and GET and rejects other methods earlier. I added it as a safety net in case the function is ever called another way or someone adds a route later (which I doubt will happen), and so I’d have something to test.

import json
import boto3

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("visitor-counter")

def lambda_handler(event, context):
    method = event["requestContext"]["http"]["method"]

    if method == "POST":
        response = table.update_item(
            Key={"id":"visitors"},
            UpdateExpression="ADD #c :inc",
            ExpressionAttributeNames={"#c":"count"},
            ExpressionAttributeValues={":inc":1},
            ReturnValues="UPDATED_NEW"
        )
        count = int(response["Attributes"]["count"])
    elif method == "GET":
        response = table.get_item(Key={"id":"visitors"})
        count = int(response["Item"]["count"])
    else:
        return{
            'statusCode': 405,
            'headers':{'Content-Type': "application/json"},
            'body': json.dumps({"error": "Method not allowed"})
        }

    return {
        'statusCode': 200,
        'headers':{'Content-Type': "application/json"},
        'body': json.dumps({"count": count})
    }

Choosing unit tests and moto

Step 11 is to add some tests to my Python code. I went with unit tests, because they let me check that each method behaves as it should. They’re also fast and free, and they don’t touch my real table, so the live counter doesn’t change.

The article linked in Step 11 uses unittest for its examples, but I used pytest instead because it needs less code. In unittest, each test has to live inside a class and use special methods like self.assertEqual(). In pytest, a test is just a function that starts with test_, and I check results with Python’s regular assert.

For faking DynamoDB, I compared unittest.mock (Python’s built-in tool) with moto, and chose moto. With unittest.mock, I’d have to write the fake responses myself, so a test could pass even if my code was broken. It would only prove that my code calls the mock the way I expected. moto simulates DynamoDB in memory, so it’s a working fake database. My real code runs against it and does the increment itself, so a result of 6 proves my UpdateExpression actually works.

These are the three things I test:

  • POST increments the count by 1

  • GET returns the count without changing it

  • Any other method returns a 405

My setup

I copied my Lambda function into a file on my computer, in a folder called cloud-resume-backend. Then I created a pytest.ini file, which is pytest’s settings file. pytest reads it before running anything. The only thing I put in it is pythonpath = ., which tells pytest to look in the root folder for modules. My Lambda function lives there, and without this setting, the tests fail because they can’t find it.

[pytest]
pythonpath = .

([pytest] is the section header that says these settings are for pytest.)

Next, I created and activated a virtual environment, so the packages stay inside this project and don’t get mixed up with the rest of my computer. Note the .fish in the activate command. That’s because I use the fish shell.

python3 -m venv .venv
source .venv/bin/activate.fish
pip install pytest boto3 moto

Then I created a tests folder with a file called test_lambda.py. Spoiler alert: this is what took most of my time, because I was learning as I wrote the tests, and my background is more TypeScript than Python. My hope is that the more I do this, the better I’ll know the syntax and the steps for writing tests, but that only comes with consistency.

The test file

import importlib
import json

import boto3
import pytest
from moto import mock_aws

@pytest.fixture
def lambda_module(monkeypatch):
    monkeypatch.setenv("AWS_ACCESS_KEY_ID", "testing")
    monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "testing")
    monkeypatch.setenv("AWS_DEFAULT_REGION", "ca-central-1")

    with mock_aws():
        dynamodb = boto3.resource("dynamodb")
        table = dynamodb.create_table(
            TableName="visitor-counter",
            KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
            AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
            BillingMode="PAY_PER_REQUEST",
        )
        table.put_item(Item={"id": "visitors", "count": 5}) 

        import lambda_function
        importlib.reload(lambda_function)

        yield lambda_function, table


def make_event(method):
    return {"requestContext": {"http": {"method": method}}}


def test_post_increments_count(lambda_module):
   module, table = lambda_module
   result = module.lambda_handler(make_event("POST"), None) 

   assert result["statusCode"] == 200
   assert json.loads(result["body"])["count"] == 6

def test_get_count(lambda_module):
   module, table = lambda_module
   result = module.lambda_handler(make_event("GET"), None) 

   assert result["statusCode"] == 200
   assert json.loads(result["body"])["count"] == 5
   assert table.get_item(Key={"id": "visitors"})["Item"]["count"] == 5

@pytest.mark.parametrize("method", ["DELETE", "PUT", "PATCH"])
def test_other_methods_rejected(lambda_module, method):
    module, table = lambda_module
    result = module.lambda_handler(make_event(method), None) 

    assert result["statusCode"] == 405
    assert table.get_item(Key={"id":"visitors"})["Item"]["count"] == 5

How the fixture works

I created lambda_module and labeled it a fixture with @pytest.fixture. That marks it as a setup helper, not a test. Any test that takes lambda_module as a parameter receives whatever the fixture hands over. Here’s what happens inside it:

  • Fake credentials and region: monkeypatch is a pytest tool that makes temporary changes and undoes them when the test finishes. I use it to set fake credentials, because boto3 refuses to talk to AWS unless it has credentials and knows which city to go to (the region). moto never validates them. The fake details also protect me, because they can’t reach my real account.

  • The pretend AWS: Everything inside with mock_aws():happens in a fake AWS. When the indented block ends, it disappears.

  • A fake table: I create it with the same code I’d use for a real table:
    TableName: matches the name of my actual table
    KeySchema: states rows are found by the column called id
    AttributeDefinitions: states the id holds text, the type is string, S = string
    BillingMode: this is required by AWS when you create a table, so it’s set on-demand to match my real table, I don’t actually test with it.

  • One seeded row: table.put_item(Item={"id": "visitors", "count": 5}) is my starting point. Every test starts at 5, because the fixture is function-scoped, so it runs fresh for each test and rebuilds the table and the row.

  • Importing my Lambda: I import it inside the pretend AWS, because my Lambda creates its DynamoDB connection when it’s first loaded. I want that to happen while the fake AWS and fake credentials exist. If it loaded earlier, the connection could be created before moto is active or before the fake region is set. The reload is an extra precaution. Python caches imported modules, so reload re-runs my lambda_function code from the top for each test. It isn’t what makes the data fresh (the function-scoped fixture does that), but it protects me if my Lambda ever keeps state at the top level of the module.

  • **yield**: This pauses the fixture and hands over the lambda_function and table to test. The test runs. Then the fixture resumes, the with block ends, and the pretend AWS is thrown away.

The three tests

  • POST: I check the status is 200 and the count in the response body went from 5 to 6. I didn’t check the table directly, because my Lambda returns the value DynamoDB sends back after the write.

  • GET: I check the status is 200 and compare the value with both the response body and the table directly. I imagined a case where the Lambda returns the right value but accidentally writes a new one to the table, so I needed to confirm the value is unchanged.

  • Other methods: I tested that other methods are rejected. Today I learned @pytest.mark.parametrize, which lets me check for a 405 and an unchanged count for DELETE, PUT, and PATCH without writing three separate tests.

Running them

I ran pytest -v, and here’s the result. The parametrize test shows up as three separate results, one for each method.

pytest -v output showing all tests passing

As you can see, all I did was write three tests, and they don’t take long to write. I took my time because I wanted to understand what I was doing, so I’d know it for next time and not just today. I also learned a lot along the way, from moto and fixtures to parametrize and writing the tests themselves.

That’s all for now. The resume looks the same, but if you haven’t seen it, here’s the link: Lois resume

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
basic-html-structure-of-a-webpage

Basic HTML structure of a webpage

Related Posts