Skip to content

Fix AWS Lambda tests #4199

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

Merged
merged 2 commits into from
Mar 26, 2025
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
2 changes: 1 addition & 1 deletion sentry_sdk/integrations/stdlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def putrequest(self, method, url, *args, **kwargs):

client = sentry_sdk.get_client()
if client.get_integration(StdlibIntegration) is None or is_sentry_url(
client, host
client, f"{host}:{port}"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can port be None? On line 85 we fill in the port in real_url and there's a fallback to empty string: port != default_port and ":%s" % port or "", so I'm wondering if that's there to handle the potential port = None case

Copy link
Contributor

@sentrivana sentrivana Mar 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm ok parsing it again I guess that's actually for the port == default_port case.

And anyways this is only used in is_sentry_url which doesn't seem to care. So probably just disregard.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think port is always there. I tried it with a normal Sentry DSN and then the port was 443 and it still worked. (because the check in is_sentry_url is if dsn_url in given_url.)

):
return real_putrequest(self, method, url, *args, **kwargs)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,14 @@
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration

# Global variables to store sampling context for verification
sampling_context_data = {
"aws_event_present": False,
"aws_context_present": False,
"event_data": None,
}
sampling_context_data = None


def trace_sampler(sampling_context):
# Store the sampling context for verification
global sampling_context_data
sampling_context_data = sampling_context

# Check if aws_event and aws_context are in the sampling_context
if "aws_event" in sampling_context:
sampling_context_data["aws_event_present"] = True
sampling_context_data["event_data"] = sampling_context["aws_event"]

if "aws_context" in sampling_context:
sampling_context_data["aws_context_present"] = True

print("Sampling context data:", sampling_context_data)
return 1.0 # Always sample


Expand Down
53 changes: 41 additions & 12 deletions tests/integrations/aws_lambda/test_aws_lambda.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def test_environment():

try:
# Wait for SAM to be ready
LocalLambdaStack.wait_for_stack()
LocalLambdaStack.wait_for_stack(log_file=debug_log_file)

def before_test():
server.clear_envelopes()
Expand Down Expand Up @@ -137,12 +137,12 @@ def test_basic_no_exception(lambda_client, test_environment):
}
assert transaction_event["contexts"]["trace"] == {
"op": "function.aws",
"description": mock.ANY,
"span_id": mock.ANY,
"parent_span_id": mock.ANY,
"trace_id": mock.ANY,
"origin": "auto.function.aws_lambda",
"data": mock.ANY,
"status": "ok",
}


Expand Down Expand Up @@ -178,7 +178,6 @@ def test_basic_exception(lambda_client, test_environment):
}
assert error_event["contexts"]["trace"] == {
"op": "function.aws",
"description": mock.ANY,
"span_id": mock.ANY,
"parent_span_id": mock.ANY,
"trace_id": mock.ANY,
Expand Down Expand Up @@ -314,9 +313,7 @@ def test_non_dict_event(
"headers": {"Host": "x1.io", "X-Forwarded-Proto": "https"},
"method": "GET",
"url": "https://x1.io/1",
"query_string": {
"done": "f",
},
"query_string": "done=f",
}
else:
request_data = {"url": "awslambda:///BasicException"}
Expand All @@ -343,7 +340,8 @@ def test_request_data(lambda_client, test_environment):
"X-Forwarded-Proto": "https"
},
"queryStringParameters": {
"bonkers": "true"
"bonkers": "true",
"wild": "false"
},
"pathParameters": null,
"stageVariables": null,
Expand Down Expand Up @@ -373,7 +371,7 @@ def test_request_data(lambda_client, test_environment):
"X-Forwarded-Proto": "https",
},
"method": "GET",
"query_string": {"bonkers": "true"},
"query_string": "bonkers=true&wild=false",
"url": "https://iwsz2c7uwi.execute-api.us-east-1.amazonaws.com/asd",
}

Expand Down Expand Up @@ -457,7 +455,19 @@ def test_traces_sampler_has_correct_sampling_context(lambda_client, test_environ
Test that aws_event and aws_context are passed in the custom_sampling_context
when using the AWS Lambda integration.
"""
test_payload = {"test_key": "test_value"}
test_payload = {
"test_key": "test_value",
"httpMethod": "GET",
"queryStringParameters": {
"test_query_param": "test_query_value",
},
"path": "/test",
"headers": {
"X-Forwarded-Proto": "https",
"Host": "example.com",
"X-Bla": "blabla",
},
}
response = lambda_client.invoke(
FunctionName="TracesSampler",
Payload=json.dumps(test_payload),
Expand All @@ -466,9 +476,28 @@ def test_traces_sampler_has_correct_sampling_context(lambda_client, test_environ
sampling_context_data = json.loads(response_payload["body"])[
"sampling_context_data"
]
assert sampling_context_data.get("aws_event_present") is True
assert sampling_context_data.get("aws_context_present") is True
assert sampling_context_data.get("event_data", {}).get("test_key") == "test_value"

assert sampling_context_data == {
"transaction_context": {
"name": "TracesSampler",
"op": "function.aws",
"source": "component",
},
"http.request.method": "GET",
"url.query": "test_query_param=test_query_value",
"url.path": "/test",
"url.full": "https://example.com/test?test_query_param=test_query_value",
"network.protocol.name": "https",
"server.address": "example.com",
"faas.name": "TracesSampler",
"http.request.header.x-forwarded-proto": "https",
"http.request.header.host": "example.com",
"http.request.header.x-bla": "blabla",
"sentry.op": "function.aws",
"sentry.source": "component",
"parent_sampled": None,
"cloud.provider": "aws",
}


@pytest.mark.parametrize(
Expand Down
6 changes: 3 additions & 3 deletions tests/integrations/aws_lambda/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,16 +211,16 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
)

@classmethod
def wait_for_stack(cls, timeout=60, port=SAM_PORT):
def wait_for_stack(cls, timeout=60, port=SAM_PORT, log_file=None):
"""
Wait for SAM to be ready, with timeout.
"""
start_time = time.time()
while True:
if time.time() - start_time > timeout:
raise TimeoutError(
"AWS SAM failed to start within %s seconds. (Maybe Docker is not running?)"
% timeout
"AWS SAM failed to start within %s seconds. (Maybe Docker is not running, or new docker images could not be built in time?) Check the log for more details: %s"
% (timeout, log_file)
)

try:
Expand Down
Loading