|
| 1 | +import json |
| 2 | +import base64 |
| 3 | +import pytest |
| 4 | +import boto3 |
| 5 | +from moto import mock_s3, mock_dynamodb |
| 6 | +from src.lambda.upload.handler import handler |
| 7 | + |
| 8 | +@pytest.fixture |
| 9 | +def aws_credentials(): |
| 10 | + """Mocked AWS Credentials for moto.""" |
| 11 | + import os |
| 12 | + os.environ["AWS_ACCESS_KEY_ID"] = "testing" |
| 13 | + os.environ["AWS_SECRET_ACCESS_KEY"] = "testing" |
| 14 | + os.environ["AWS_SECURITY_TOKEN"] = "testing" |
| 15 | + os.environ["AWS_SESSION_TOKEN"] = "testing" |
| 16 | + os.environ["AWS_DEFAULT_REGION"] = "us-east-1" |
| 17 | + os.environ["BUCKET_NAME"] = "test-bucket" |
| 18 | + os.environ["DYNAMODB_TABLE"] = "test-table" |
| 19 | + |
| 20 | +@mock_s3 |
| 21 | +@mock_dynamodb |
| 22 | +def test_upload_handler_success(aws_credentials): |
| 23 | + # Setup mock S3 |
| 24 | + s3 = boto3.client("s3", region_name="us-east-1") |
| 25 | + s3.create_bucket(Bucket="test-bucket") |
| 26 | + |
| 27 | + # Setup mock DynamoDB |
| 28 | + db = boto3.resource("dynamodb", region_name="us-east-1") |
| 29 | + db.create_table( |
| 30 | + TableName="test-table", |
| 31 | + KeySchema=[ |
| 32 | + {"AttributeName": "project_id", "KeyType": "HASH"}, |
| 33 | + {"AttributeName": "timestamp", "KeyType": "RANGE"} |
| 34 | + ], |
| 35 | + AttributeDefinitions=[ |
| 36 | + {"AttributeName": "project_id", "AttributeType": "S"}, |
| 37 | + {"AttributeName": "timestamp", "AttributeType": "N"} |
| 38 | + ], |
| 39 | + ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1} |
| 40 | + ) |
| 41 | + |
| 42 | + # Mock event |
| 43 | + file_content = b"hello world" |
| 44 | + encoded_content = base64.b64encode(file_content).decode("utf-8") |
| 45 | + event = { |
| 46 | + "body": encoded_content, |
| 47 | + "isBase64Encoded": True, |
| 48 | + "headers": { |
| 49 | + "file-name": "test.txt", |
| 50 | + "Content-Type": "text/plain", |
| 51 | + "project-id": "proj-123" |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + # Call handler |
| 56 | + response = handler(event, None) |
| 57 | + |
| 58 | + # Verify response |
| 59 | + assert response["statusCode"] == 200 |
| 60 | + body = json.loads(response["body"]) |
| 61 | + assert body["message"] == "Upload e registro concluídos" |
| 62 | + |
| 63 | + # Verify S3 content |
| 64 | + obj = s3.get_object(Bucket="test-bucket", Key="uploads/proj-123/test.txt") |
| 65 | + assert obj["Body"].read() == file_content |
| 66 | + |
| 67 | + # Verify DynamoDB metadata |
| 68 | + table = db.Table("test-table") |
| 69 | + items = table.scan()["Items"] |
| 70 | + assert len(items) == 1 |
| 71 | + assert items[0]["project_id"] == "proj-123" |
| 72 | + assert items[0]["filename"] == "test.txt" |
| 73 | + assert items[0]["status"] == "UPLOADED" |
0 commit comments