Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add trigger bucket event s3 #228

Merged
merged 5 commits into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions faster_sam/dependencies/events.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import hashlib
from datetime import datetime, timezone
import json
from typing import Any, Callable, Dict, Type
from uuid import uuid4
import uuid
Expand Down Expand Up @@ -67,3 +68,34 @@ def dep(message: schema) -> Dict[str, Any]:
return event

return dep


async def s3(request: Request) -> Dict[str, Any]:
body = await request.body()
body = json.loads(body)
event = {
"Records": [
{
"eventVersion": "2.0",
"eventSource": "aws:s3",
"awsRegion": None,
"eventTime": body["timeCreated"],
"eventName": "s3:ObjectCreated:*",
"s3": {
"s3SchemaVersion": "1.0",
"bucket": {
"name": body["bucket"],
"arn": f"arn:aws:s3:::{body['bucket']}",
},
"object": {
"key": body["name"],
"size": body["size"],
"eTag": body["etag"],
"sequencer": uuid.uuid4().int,
},
},
}
]
}

return event
46 changes: 39 additions & 7 deletions tests/test_dependencies_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,28 @@
from datetime import datetime, timezone
from unittest.mock import patch
import uuid
import json

from fastapi import FastAPI, Request

from faster_sam.dependencies import events
from faster_sam.schemas import PubSubEnvelope
from typing import Dict, Any, Optional


def build_request():
def build_request(method: str = "GET", path: str = "/", response: Optional[Dict[str, Any]] = None):
if response is None:
response = {}

async def receive():
return {"type": "http.request", "body": b'{"message": "pong"}'}
return response

scope = {
"type": "http",
"http_version": "1.1",
"root_path": "",
"path": "/ping/pong",
"method": "GET",
"path": path,
"method": method,
"query_string": b"q=all&skip=100",
"path_params": {"message": "pong"},
"client": ("127.0.0.1", 80),
Expand All @@ -35,12 +40,13 @@ async def receive():

class TestApiGatewayProxy(unittest.IsolatedAsyncioTestCase):
async def test_event(self):
request = build_request()
response = {"type": "http.request", "body": b'{"message": "pong"}'}
request = build_request(response=response)
event = await events.apigateway_proxy(request)

self.assertIsInstance(event, dict)
self.assertEqual(event["body"], '{"message": "pong"}')
self.assertEqual(event["path"], "/ping/pong")
self.assertEqual(event["path"], "/")
self.assertEqual(event["httpMethod"], "GET")
self.assertEqual(event["isBase64Encoded"], False)
self.assertEqual(event["queryStringParameters"], {"q": "all", "skip": "100"})
Expand All @@ -52,7 +58,7 @@ async def test_event(self):
self.assertEqual(event["requestContext"]["stage"], "0.1.0")
self.assertEqual(event["requestContext"]["identity"]["sourceIp"], "127.0.0.1")
self.assertEqual(event["requestContext"]["identity"]["userAgent"], "python/unittest")
self.assertEqual(event["requestContext"]["path"], "/ping/pong")
self.assertEqual(event["requestContext"]["path"], "/")
self.assertEqual(event["requestContext"]["httpMethod"], "GET")
self.assertEqual(event["requestContext"]["protocol"], "HTTP/1.1")

Expand Down Expand Up @@ -107,3 +113,29 @@ async def test_event(self):
record["eventSourceARN"],
f"arn:aws:sqs:::{data['subscription'].rsplit('/', maxsplit=1)[-1]}",
)


class TestS3(unittest.IsolatedAsyncioTestCase):
async def test_s3_event(self):
leonardoc-lima marked this conversation as resolved.
Show resolved Hide resolved
body = {
"name": "my-object",
"bucket": "test-bucket",
"timeCreated": "2024-04-19T19:20:02.583Z",
"size": 1234,
"etag": "CMKy4UDEAE=",
}
response = {"type": "http.request", "body": json.dumps(body).encode()}
request = build_request(response=response)
sequencer = uuid.uuid4()
with patch("uuid.uuid4", return_value=sequencer):
event = await events.s3(request)

self.assertIsInstance(event, dict)
self.assertIn("Records", event)
self.assertEqual(len(event["Records"]), 1)
record = event["Records"][0]
self.assertEqual(record["s3"]["bucket"]["name"], "test-bucket")
self.assertEqual(record["s3"]["object"]["key"], "my-object")
self.assertEqual(record["s3"]["object"]["size"], 1234)
self.assertEqual(record["s3"]["object"]["eTag"], "CMKy4UDEAE=")
self.assertEqual(record["s3"]["object"]["sequencer"], sequencer.int)