56 / 75 · 08 Infrastructure as Code Testing · Testcontainers for Infrastructure Testing← prev⊞ allnext →☰ Read as one page
10.6LocalStack for AWS Services
# tests/integration/test_aws_services.py
import pytest
from testcontainers.localstack import LocalStackContainer
import boto3
@pytest.fixture(scope="module")
def localstack():
with LocalStackContainer("localstack/localstack:3.0") as ls:
yield ls
@pytest.fixture
def dynamodb(localstack):
client = boto3.client(
"dynamodb",
endpoint_url=localstack.get_url(),
region_name="us-east-1",
aws_access_key_id="test",
aws_secret_access_key="test",
)
# Create test table
client.create_table(
TableName="orders",
KeySchema=[{"AttributeName": "orderId", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "orderId", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
return client
def test_dynamodb_put_and_get(dynamodb):
dynamodb.put_item(
TableName="orders",
Item={
"orderId": {"S": "ORD-TC-001"},
"status": {"S": "pending"},
"total": {"N": "99.99"},
}
)
result = dynamodb.get_item(
TableName="orders",
Key={"orderId": {"S": "ORD-TC-001"}}
)
assert result["Item"]["status"]["S"] == "pending"