Skip to content

Commit d9226d6

Browse files
committed
Some clenaup
1 parent a0a9fdd commit d9226d6

File tree

2 files changed

+52
-37
lines changed

2 files changed

+52
-37
lines changed

tests/integrations/aws_lambda/test_aws_lambda.py

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,33 +10,34 @@
1010

1111
from aws_cdk import App
1212

13-
from .utils import DummyLambdaStack, SentryTestServer, SAM_PORT
13+
from .utils import LocalLambdaStack, SentryServerForTesting, SAM_PORT
1414

1515

1616
SAM_TEMPLATE_FILE = "sam.template.yaml"
1717

1818

1919
@pytest.fixture(scope="session", autouse=True)
2020
def test_environment():
21-
print("Setting up AWS Lambda test infrastructure")
21+
print("[test_environment fixture] Setting up AWS Lambda test infrastructure")
2222

23-
# Setup dummy relay to capture envelopes
24-
server = SentryTestServer()
23+
# Start Sentry server
24+
server = SentryServerForTesting()
2525
server.start()
2626
time.sleep(1) # Give it a moment to start up
2727

28-
# Create the SAM stack
28+
# Create local AWS SAM stack
2929
app = App()
30-
stack = DummyLambdaStack(app, "DummyLambdaStack")
30+
stack = LocalLambdaStack(app, "LocalLambdaStack")
3131

32-
# Write template to file
33-
template = app.synth().get_stack_by_name("DummyLambdaStack").template
32+
# Write SAM template to file
33+
template = app.synth().get_stack_by_name("LocalLambdaStack").template
3434
with open(SAM_TEMPLATE_FILE, "w") as f:
3535
yaml.dump(template, f)
3636

37+
# Write SAM debug log to file
3738
debug_log_file = tempfile.gettempdir() + "/sentry_aws_lambda_tests_sam_debug.log"
3839
debug_log = open(debug_log_file, "w")
39-
print(f"Writing SAM debug log to: {debug_log_file}")
40+
print("[test_environment fixture] Writing SAM debug log to: %s" % debug_log_file)
4041

4142
# Start SAM local
4243
process = subprocess.Popen(
@@ -57,19 +58,19 @@ def test_environment():
5758

5859
try:
5960
# Wait for SAM to be ready
60-
DummyLambdaStack.wait_for_stack()
61+
LocalLambdaStack.wait_for_stack()
6162

6263
def before_test():
6364
server.clear_envelopes()
6465

6566
yield {
6667
"stack": stack,
6768
"server": server,
68-
"before_test": before_test, # Add this function to the yielded dict
69+
"before_test": before_test,
6970
}
7071

7172
finally:
72-
print("Tearing down AWS Lambda test infrastructure")
73+
print("[test_environment fixture] Tearing down AWS Lambda test infrastructure")
7374

7475
process.terminate()
7576
process.wait(timeout=5) # Give it time to shut down gracefully
@@ -439,8 +440,3 @@ def test_span_origin(lambda_client, test_environment):
439440
assert (
440441
transaction_event["contexts"]["trace"]["origin"] == "auto.function.aws_lambda"
441442
)
442-
443-
444-
def test_init_sentry_manually():
445-
# todo
446-
pass

tests/integrations/aws_lambda/utils.py

Lines changed: 39 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,30 +17,32 @@
1717
from scripts.build_aws_lambda_layer import build_packaged_zip, DIST_PATH
1818

1919

20-
PYTHON_VERSION = f"python{sys.version_info.major}.{sys.version_info.minor}"
21-
SAM_PORT = 3001
22-
LAMBDA_FUNCTION_TIMEOUT = 10
2320
LAMBDA_FUNCTION_DIR = "./tests/integrations/aws_lambda/lambda_functions/"
21+
LAMBDA_FUNCTION_TIMEOUT = 10
22+
SAM_PORT = 3001
23+
24+
PYTHON_VERSION = f"python{sys.version_info.major}.{sys.version_info.minor}"
2425

2526

26-
class DummyLambdaStack(Stack):
27+
class LocalLambdaStack(Stack):
2728
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
2829
super().__init__(scope, construct_id, **kwargs)
29-
30-
print(f"CREATING STACK: {self}")
30+
print("[LocalLambdaStack] Creating local SAM Lambda Stack: %s" % self)
3131

3232
# Override the template synthesis
3333
self.template_options.template_format_version = "2010-09-09"
3434
self.template_options.transforms = ["AWS::Serverless-2016-10-31"]
3535

36-
print("- Create Sentry Lambda layer package")
36+
print("[LocalLambdaStack] Create Sentry Lambda layer package")
3737
filename = "sentry-sdk-lambda-layer.zip"
3838
build_packaged_zip(
3939
make_dist=True,
4040
out_zip_filename=filename,
4141
)
4242

43-
print("- Add Sentry Lambda layer containing the Sentry SDK to the SAM stack")
43+
print(
44+
"[LocalLambdaStack] Add Sentry Lambda layer containing the Sentry SDK to the SAM stack"
45+
)
4446
self.sentry_layer = CfnResource(
4547
self,
4648
"SentryPythonServerlessSDK",
@@ -53,9 +55,12 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
5355
},
5456
)
5557

56-
print("- Add all Lambda functions defined in /tests/integrations/aws_lambda/lambda_functions/ to the SAM stack")
58+
print(
59+
"[LocalLambdaStack] Add all Lambda functions defined in /tests/integrations/aws_lambda/lambda_functions/ to the SAM stack"
60+
)
5761
lambda_dirs = [
58-
d for d in os.listdir(LAMBDA_FUNCTION_DIR)
62+
d
63+
for d in os.listdir(LAMBDA_FUNCTION_DIR)
5964
if os.path.isdir(os.path.join(LAMBDA_FUNCTION_DIR, d))
6065
]
6166
for lambda_dir in lambda_dirs:
@@ -68,7 +73,9 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
6873
"Handler": "sentry_sdk.integrations.init_serverless_sdk.sentry_lambda_handler",
6974
"Runtime": PYTHON_VERSION,
7075
"Timeout": LAMBDA_FUNCTION_TIMEOUT,
71-
"Layers": [{"Ref": self.sentry_layer.logical_id}], # Add layer containing the Sentry SDK to function.
76+
"Layers": [
77+
{"Ref": self.sentry_layer.logical_id}
78+
], # Add layer containing the Sentry SDK to function.
7279
"Environment": {
7380
"Variables": {
7481
"SENTRY_DSN": "http://[email protected]:9999/0",
@@ -78,8 +85,13 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
7885
},
7986
},
8087
)
81-
print(f" - Created Lambda function: {lambda_dir} ({os.path.join(LAMBDA_FUNCTION_DIR, lambda_dir)})")
82-
88+
print(
89+
"[LocalLambdaStack] - Created Lambda function: %s (%s)"
90+
% (
91+
lambda_dir,
92+
os.path.join(LAMBDA_FUNCTION_DIR, lambda_dir),
93+
)
94+
)
8395

8496
@classmethod
8597
def wait_for_stack(cls, timeout=30, port=SAM_PORT):
@@ -90,7 +102,8 @@ def wait_for_stack(cls, timeout=30, port=SAM_PORT):
90102
while True:
91103
if time.time() - start_time > timeout:
92104
raise TimeoutError(
93-
"SAM failed to start within {} seconds. (Maybe Docker is not running?)".format(timeout)
105+
"SAM failed to start within %s seconds. (Maybe Docker is not running?)"
106+
% timeout
94107
)
95108

96109
try:
@@ -104,18 +117,24 @@ def wait_for_stack(cls, timeout=30, port=SAM_PORT):
104117
continue
105118

106119

107-
class SentryTestServer:
108-
def __init__(self, port=9999):
120+
class SentryServerForTesting:
121+
"""
122+
A simple Sentry.io style server that accepts envelopes and stores them in a list.
123+
"""
124+
125+
def __init__(self, port=9999, log_level="warning"):
109126
self.envelopes = []
110127
self.port = port
128+
self.log_level = log_level
111129
self.app = FastAPI()
112130

113131
@self.app.post("/api/0/envelope/")
114132
async def envelope(request: Request):
133+
print("[SentryServerForTesting] Received envelope")
115134
try:
116135
raw_body = await request.body()
117136
except:
118-
return {"status": "no body"}
137+
return {"status": "no body received"}
119138

120139
try:
121140
body = gzip.decompress(raw_body).decode("utf-8")
@@ -143,13 +162,13 @@ async def envelope(request: Request):
143162
return {"status": "ok"}
144163

145164
def run_server(self):
146-
uvicorn.run(self.app, host="0.0.0.0", port=self.port, log_level="warning")
165+
uvicorn.run(self.app, host="0.0.0.0", port=self.port, log_level=self.log_level)
147166

148167
def start(self):
149-
print("[SENTRY SERVER] Starting server")
168+
print("[SentryServerForTesting] Starting server")
150169
server_thread = threading.Thread(target=self.run_server, daemon=True)
151170
server_thread.start()
152171

153172
def clear_envelopes(self):
154-
print("[SENTRY SERVER] Clearing envelopes")
173+
print("[SentryServerForTesting] Clearing envelopes")
155174
self.envelopes = []

0 commit comments

Comments
 (0)