Study Guide860 words

AWS Developer Guide: Writing and Running Test Code

Write and run test code by using AWS services and tools

AWS Developer Guide: Writing and Running Test Code

Testing in the AWS ecosystem requires a shift from traditional local testing to a hybrid approach involving local emulation, cloud-based integration testing, and automated validation within CI/CD pipelines. This guide focuses on the tools and strategies required for the AWS Certified Developer - Associate (DVA-C02) exam.

Learning Objectives

After studying this guide, you should be able to:

  • Configure and execute unit tests using the AWS Serverless Application Model (SAM) CLI.
  • Design JSON test events for AWS Lambda and API Gateway.
  • Implement automated testing phases within an AWS CodeBuild buildspec.yml file.
  • Perform integration testing using Amazon API Gateway stages and mock integrations.
  • Utilize Amazon Q Developer to generate automated test cases efficiently.

Key Terms & Glossary

  • AWS SAM (Serverless Application Model): An open-source framework for building serverless applications. It provides a CLI to local-invoke and test functions.
  • buildspec.yml: A collection of build commands and settings in YAML format that AWS CodeBuild uses to run a build and its associated tests.
  • Mock Integration: An API Gateway feature that allows developers to return a response directly from the API without calling a backend service, useful for testing frontend components.
  • Lambda Alias: A pointer to a specific Lambda function version, often used to differentiate between DEV, TEST, and PROD environments.
  • Integration Testing: Testing the communication between multiple AWS services (e.g., Lambda to DynamoDB) to ensure they work together as expected.

The "Big Idea"

In an AWS environment, Testing is not a single event—it is a continuous layer. Effective testing moves from Local (using SAM to simulate Lambda) to Automated Build (using CodeBuild to run suites) to Staging (using API Gateway stages to verify deployments). The goal is to catch configuration errors and integration failures before they reach the production environment.

Formula / Concept Box

Testing LevelPrimary ToolKey ArtifactValidation Focus
Unit TestingAWS SAM / PyTest / Jestsam local invokeBusiness logic in isolation
Automated BuildAWS CodeBuildbuildspec.ymlCode quality & package integrity
IntegrationAPI Gateway / LambdaJSON Test EventsPermissions (IAM) & Data Flow
EnvironmentAWS AppConfig / AliasesLambda AliasesConfiguration & Performance

Hierarchical Outline

  1. Local Development & Unit Testing
    • AWS SAM CLI: Using sam local start-api and sam local invoke to simulate the cloud environment locally.
    • Amazon Q Developer: Generating unit test boilerplate and edge-case scenarios using AI-assisted coding.
  2. Lambda Test Events
    • JSON Payloads: Creating specific structures that mimic AWS service triggers (e.g., S3 Put, SQS message).
    • Shareable Test Events: Using the Lambda console to save and share events with team members.
  3. Continuous Integration (CI) Testing
    • AWS CodeBuild: Executing tests in a managed environment.
    • Buildspec Structure: Defining pre_build and build phases to run linters and test suites.
  4. API Testing & Stages
    • API Gateway Stages: Using stages (e.g., /v1, /beta) to isolate test traffic.
    • Stage Variables: Passing dynamic values to Lambda functions to toggle between test and production databases.

Visual Anchors

Automated Test Workflow

Loading Diagram...

Lambda Testing Architecture

\begin{tikzpicture}[node distance=2cm, every node/.style={rectangle, draw, rounded corners, minimum width=3cm, minimum height=1cm, align=center}] \node (event) [fill=blue!10] {\textbf{Test Event}$JSON Payload)}; \node (lambda) [right=of event, fill=orange!10] {\textbf{AWS Lambda}$Logic/Handler)}; \node (mock) [below=of lambda, fill=gray!10] {\textbf{Mocks/Stubs}$External APIs)}; \node (output) [right=of lambda, fill=green!10] {\textbf{Test Result}$Success/Fail)};

code
\draw[->, thick] (event) -- (lambda); \draw[->, thick] (lambda) -- (output); \draw[<->, dashed] (lambda) -- (mock); \node[draw=none, below=0.5cm of event] {\small Input Simulation}; \node[draw=none, below=0.5cm of output] {\small Response Validation};

\end{tikzpicture}

Definition-Example Pairs

  • Test Event Payload: A JSON object representing the data a service sends to Lambda.
    • Example: An S3 Event payload containing the bucket name and file key so a Lambda can test its image-processing logic without an actual upload.
  • Environment Variable Injection: Providing configuration to code at runtime rather than hardcoding values.
    • Example: Using a variable TABLE_NAME that points to Movies_Test during CodeBuild testing and Movies_Prod during final deployment.
  • Canary Testing: A deployment strategy where a small percentage of traffic is shifted to a new version to test its stability.
    • Example: Routing 10% of users to a new API Gateway stage to monitor for 5XX errors before a full rollout.

Worked Examples

Example 1: AWS CodeBuild buildspec.yml with Testing

To automate tests during the build process, you must define the install and build phases.

yaml
version: 0.2 phases: install: runtime-versions: python: 3.9 commands: - pip install -r requirements.txt - pip install pytest pre_build: commands: - echo Running unit tests... - pytest tests/unit_tests.py build: commands: - echo Build started on `date` - sam package --output-template-file packaged.yaml artifacts: files: - packaged.yaml

Example 2: Invoking Lambda Locally with SAM

If you have a file named event.json, you can test your Lambda locally without deploying to AWS:

bash
# Invokes the function 'MyLambdaFunction' using the local JSON event sam local invoke MyLambdaFunction -e event.json

Checkpoint Questions

  1. Which file is used to provide AWS CodeBuild with instructions on how to run tests and compile code?
  2. What is the benefit of using API Gateway Stage Variables for integration testing?
  3. How does AWS SAM assist in the "Inner Loop" of development (the phase before code is committed)?
  4. True or False: Amazon Q Developer can be used to generate automated tests based on existing code context.
Click to view answers
  1. buildspec.yml (typically located at the root of the source directory).
  2. They allow you to dynamically change backend endpoints or database names without modifying the application code.
  3. It allows developers to test Lambda functions and APIs locally on their machine, reducing the feedback loop and cloud costs.
  4. True. It assists in generating test code and identifying edge cases.

Ready to study AWS Certified Developer - Associate (DVA-C02)?

Practice tests, flashcards, and all study notes — free, no sign-up needed.

Start Studying — Free