11import boto3
2+ import gzip
23import json
4+ import os
35import pytest
46import requests
57import subprocess
8+ import shutil
69import time
710import threading
811import yaml
12+
913from aws_cdk import (
1014 App ,
1115 CfnResource ,
1216 Stack ,
1317)
1418from constructs import Construct
19+ from fastapi import FastAPI , Request
20+ import uvicorn
21+
22+ from scripts .build_aws_lambda_layer import build_packaged_zip , DIST_PATH
1523
1624
1725SAM_PORT = 3001
@@ -28,12 +36,18 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
2836 self .template_options .transforms = ["AWS::Serverless-2016-10-31" ]
2937
3038 # Create Sentry Lambda Layer
39+ filename = "sentry-sdk-lambda-layer.zip"
40+ build_packaged_zip (
41+ make_dist = True ,
42+ out_zip_filename = filename ,
43+ )
44+
3145 layer = CfnResource (
3246 self ,
3347 "SentryPythonServerlessSDK" ,
3448 type = "AWS::Serverless::LayerVersion" ,
3549 properties = {
36- "ContentUri" : "./tests/integrations/aws_lambda/lambda_layer" ,
50+ "ContentUri" : os . path . join ( DIST_PATH , filename ) ,
3751 "CompatibleRuntimes" : [
3852 "python3.7" ,
3953 "python3.8" ,
@@ -53,9 +67,16 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
5367 type = "AWS::Serverless::Function" ,
5468 properties = {
5569 "CodeUri" : "./tests/integrations/aws_lambda/lambda_functions/hello_world" ,
56- "Handler" : "index.handler " ,
70+ "Handler" : "sentry_sdk.integrations.init_serverless_sdk.sentry_lambda_handler " ,
5771 "Runtime" : "python3.12" ,
58- "Layers" : [{"Ref" : layer .logical_id }],
72+ "Layers" : [{"Ref" : layer .logical_id }], # The layer adds the sentry-sdk
73+ "Environment" : { # The environment variables are set up the Sentry SDK to instrument the lambda function
74+ "Variables" : {
75+ "SENTRY_DSN" :
"http://[email protected] :9999/0" ,
76+ "SENTRY_INITIAL_HANDLER" : "index.handler" ,
77+ "SENTRY_TRACES_SAMPLE_RATE" : "1.0" ,
78+ }
79+ },
5980 },
6081 )
6182
@@ -84,32 +105,51 @@ class SentryTestServer:
84105 def __init__ (self , port = 9999 ):
85106 self .envelopes = []
86107 self .port = port
87-
88- from fastapi import FastAPI , Request
89-
90108 self .app = FastAPI ()
91109
92- @self .app .get ("/" )
93- async def root ():
94- return {
95- "message" : "Sentry Test Server. Use DSN http://123@localhost:9999/0 in your SDK."
96- }
97-
98110 @self .app .post ("/api/0/envelope/" )
99111 async def envelope (request : Request ):
100- self .envelopes .append (await request .json ())
112+ print ("[SENTRY SERVER] Received envelope" )
113+ try :
114+ raw_body = await request .body ()
115+ except :
116+ return {"status" : "no body" }
117+
118+ try :
119+ body = gzip .decompress (raw_body ).decode ("utf-8" )
120+ except :
121+ # If decompression fails, assume it's plain text
122+ body = raw_body .decode ("utf-8" )
123+
124+ lines = body .split ("\n " )
125+
126+ current_line = 1 # line 0 is envelope header
127+ while current_line < len (lines ):
128+ # skip empty lines
129+ if not lines [current_line ].strip ():
130+ current_line += 1
131+ continue
132+
133+ # skip envelope item header
134+ current_line += 1
135+
136+ # add envelope item to store
137+ envelope_item = lines [current_line ]
138+ if envelope_item .strip ():
139+ self .envelopes .append (json .loads (envelope_item ))
140+
101141 return {"status" : "ok" }
102142
103143 def run_server (self ):
104- import uvicorn
105-
106144 uvicorn .run (self .app , host = "0.0.0.0" , port = self .port )
107145
108146 def start (self ):
147+ print ("[SENTRY SERVER] Starting server" )
109148 server_thread = threading .Thread (target = self .run_server , daemon = True )
110149 server_thread .start ()
111150
112151 def clear_envelopes (self ):
152+ print ("[SENTRY SERVER] Clear envelopes" )
113153 self .envelopes = []
114154
115155
@@ -185,21 +225,27 @@ def test_basic(lambda_client, sentry_test_server):
185225 sentry_test_server .clear_envelopes ()
186226
187227 response = lambda_client .invoke (
188- FunctionName = "BasicTestFunction" , Payload = json .dumps ({"name" : "Anton " })
228+ FunctionName = "BasicTestFunction" , Payload = json .dumps ({"name" : "Ivana " })
189229 )
190230 result = json .loads (response ["Payload" ].read ().decode ())
231+ assert result == {"message" : "Hello, Ivana!" }
191232
233+ print ("envelopes:" )
192234 print (sentry_test_server .envelopes )
193- assert result == {"message" : "Hello, Anton!" }
235+
236+ # assert sentry_test_server.envelopes == [{"message": "[SENTRY MESSAGE] Hello, Ivana!"}]
194237
195238
196239def test_basic_2 (lambda_client , sentry_test_server ):
197240 sentry_test_server .clear_envelopes ()
198241
199242 response = lambda_client .invoke (
200- FunctionName = "BasicTestFunction" , Payload = json .dumps ({"name" : "Anton " })
243+ FunctionName = "BasicTestFunction" , Payload = json .dumps ({"name" : "Neel " })
201244 )
202245 result = json .loads (response ["Payload" ].read ().decode ())
246+ assert result == {"message" : "Hello, Neel!" }
203247
248+ print ("envelopes2:" )
204249 print (sentry_test_server .envelopes )
205- assert result == {"message" : "Hello, Anton!" }
250+
251+ # assert sentry_test_server.envelopes == [{"message": "[SENTRY MESSAGE] Hello, Neel!"}]
0 commit comments