Ravindra BagaleCourses & study guides मराठी

Chapter 93: AWS Lambda and Serverless for DevOps

DevOps

93.14 Local lab — validate, calculate and adapt

Story (fictional teaching scenario). Meera from Satara and Ken from Kyoto build a fictional shop calculator on a laptop. It sends nothing to AWS and contains no SDK, credentials, network calls or real customer data.

Local lab — validate, calculate and adapt
Local lab — validate, calculate and adapt

Why

A deterministic local test is the fastest way to understand handlers and failure cases without cloud costs.

What

  • Unit test checks a small behaviour with known inputs and expected results.
  • Validation rejects bad input before calculation.
  • Integer paise avoids floating-point rounding in this small money example. It is not a full tax/payment implementation.

How

  1. Create an empty practice folder and save the complete price.py below.

  2. Save test_price.py beside it.

  3. Run python3 -m unittest -v.

  4. Read each test, then change a calculation deliberately and observe a failure.

  5. Restore the code and rerun. No cloud account is involved.

Example 1: Complete price.py

"""Pure local teaching handler: no SDK, files, network or secrets."""
import json

def lambda_handler(event, context):
    qty = event.get('qty')
    unit_paise = event.get('unit_paise')
    if type(qty) is not int or not 1 <= qty <= 20:
        raise ValueError('qty must be an integer from 1 to 20')
    if type(unit_paise) is not int or not 0 <= unit_paise <= 100000:
        raise ValueError('unit_paise must be an integer from 0 to 100000')
    return {'total_paise': qty * unit_paise, 'currency': 'INR'}

def api_handler(event, context):
    try:
        payload = json.loads(event.get('body') or '{}')
        if not isinstance(payload, dict):
            raise ValueError('body must be an object')
        result = lambda_handler(payload, context)
        return {'statusCode': 200, 'body': json.dumps(result, sort_keys=True)}
    except (ValueError, TypeError, AttributeError):
        return {'statusCode': 400, 'body': json.dumps({'error': 'invalid input'})}
  1. json is the standard-library serializer.
  2. event.get reads optional fields. type(x) is int deliberately rejects True/False, which Python otherwise treats as integers.
  3. The bounds stop negative, huge or missing inputs.
  4. ValueError clearly signals invalid input; it does not pretend the total is zero.
  5. The adapter accepts an object encoded as JSON and returns a 400 result for bad shapes or bad fields.
  6. No request body, secret or customer identifier is logged.

Example 2: Complete test_price.py

import unittest
import json
from price import lambda_handler, api_handler

class PriceTests(unittest.TestCase):
    def test_total(self):
        self.assertEqual(lambda_handler({'qty': 3, 'unit_paise': 4000}, None),
                         {'total_paise': 12000, 'currency': 'INR'})
    def test_zero_price(self):
        self.assertEqual(lambda_handler({'qty': 1, 'unit_paise': 0}, None)['total_paise'], 0)
    def test_invalid_qty(self):
        for q in [0, 21, -1, True, '3', None]:
            with self.subTest(q=q), self.assertRaises(ValueError):
                lambda_handler({'qty': q, 'unit_paise': 4000}, None)
    def test_invalid_price(self):
        for p in [-1, 100001, False, '40', None]:
            with self.subTest(p=p), self.assertRaises(ValueError):
                lambda_handler({'qty': 1, 'unit_paise': p}, None)
    def test_repeat(self):
        event = {'qty': 3, 'unit_paise': 4000}
        self.assertEqual(lambda_handler(event, None), lambda_handler(event, None))
    def test_api_success(self):
        result = api_handler({'body': '{"qty":3,"unit_paise":4000}'}, None)
        self.assertEqual(result['statusCode'], 200)
        self.assertEqual(json.loads(result['body'])['total_paise'], 12000)
    def test_api_bad_json(self):
        self.assertEqual(api_handler({'body': 'bad'}, None)['statusCode'], 400)
    def test_api_wrong_shape(self):
        self.assertEqual(api_handler({'body': '[]'}, None)['statusCode'], 400)

if __name__ == '__main__':
    unittest.main()

Example 3: Run the tests

  1. Read the input and the code.
python3 -m unittest -v
  1. Read the result.

Output (tested locally; not on AWS)

Ran 8 tests
OK
  1. What each part means: unittest discovers test_price.py. Tests cover totals, zero price, invalid quantity/price, repeated calculation, valid HTTP-shaped input, malformed JSON and wrong JSON shape. Subtests check multiple bad values. Timing varies. These tests validate pure Python, not IAM, Lambda cold starts, billing, integration permissions or cloud scaling.

Ravindra Bagale's Tip

A passing unit test is evidence for code, not proof of cloud wiring.

Did you understand? Let us try it once more.