5
5
import subprocess
6
6
import sys
7
7
import uuid
8
+ from textwrap import dedent
8
9
9
10
import pytest
10
11
11
12
boto3 = pytest .importorskip ("boto3" )
12
13
13
- LAMBDA_TEMPLATE = """
14
+ LAMBDA_PRELUDE = """
14
15
from __future__ import print_function
15
16
16
17
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration
@@ -31,16 +32,12 @@ def shutdown(self, timeout, callback=None):
31
32
for event in self._queue:
32
33
print("EVENT:", json.dumps(event))
33
34
34
- sentry_sdk.init(
35
-
36
- transport=TestTransport(),
37
- integrations=[AwsLambdaIntegration()],
38
- **{extra_init_args}
39
- )
40
-
41
-
42
- def test_handler(event, context):
43
- {code}
35
+ def init_sdk(**extra_init_args):
36
+ sentry_sdk.init(
37
+ transport=TestTransport(),
38
+ integrations=[AwsLambdaIntegration()],
39
+ **extra_init_args
40
+ )
44
41
"""
45
42
46
43
@@ -59,17 +56,13 @@ def lambda_client():
59
56
60
57
@pytest .fixture (params = ["python3.6" , "python2.7" ])
61
58
def run_lambda_function (tmpdir , lambda_client , request , assert_semaphore_acceptance ):
62
- def inner (lambda_body , payload , extra_init_args = None ):
59
+ def inner (code , payload ):
60
+ runtime = request .param
63
61
tmpdir .ensure_dir ("lambda_tmp" ).remove ()
64
62
tmp = tmpdir .ensure_dir ("lambda_tmp" )
65
63
66
64
# https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html
67
- tmp .join ("test_lambda.py" ).write (
68
- LAMBDA_TEMPLATE .format (
69
- code = "\n " .join (" " + x .strip () for x in lambda_body .splitlines ()),
70
- extra_init_args = repr (extra_init_args or {}),
71
- )
72
- )
65
+ tmp .join ("test_lambda.py" ).write (code )
73
66
tmp .join ("setup.cfg" ).write ("[install]\n prefix=" )
74
67
subprocess .check_call ([sys .executable , "setup.py" , "sdist" , "-d" , str (tmpdir )])
75
68
subprocess .check_call ("pip install ../*.tar.gz -t ." , cwd = str (tmp ), shell = True )
@@ -79,7 +72,7 @@ def inner(lambda_body, payload, extra_init_args=None):
79
72
80
73
lambda_client .create_function (
81
74
FunctionName = fn_name ,
82
- Runtime = request . param ,
75
+ Runtime = runtime ,
83
76
Role = os .environ ["AWS_IAM_ROLE" ],
84
77
Handler = "test_lambda.test_handler" ,
85
78
Code = {"ZipFile" : tmpdir .join ("ball.zip" ).read (mode = "rb" )},
@@ -116,7 +109,15 @@ def delete_function():
116
109
117
110
def test_basic (run_lambda_function ):
118
111
events , response = run_lambda_function (
119
- 'raise Exception("something went wrong")\n ' , b'{"foo": "bar"}'
112
+ LAMBDA_PRELUDE
113
+ + dedent (
114
+ """
115
+ init_sdk()
116
+ def test_handler(event, context):
117
+ raise Exception("something went wrong")
118
+ """
119
+ ),
120
+ b'{"foo": "bar"}' ,
120
121
)
121
122
122
123
assert response ["FunctionError" ] == "Unhandled"
@@ -139,9 +140,41 @@ def test_basic(run_lambda_function):
139
140
assert event ["extra" ]["lambda" ]["function_name" ].startswith ("test_function_" )
140
141
141
142
143
+ def test_initialization_order (run_lambda_function ):
144
+ """Zappa lazily imports our code, so by the time we monkeypatch the handler
145
+ as seen by AWS already runs. At this point at least draining the queue
146
+ should work."""
147
+
148
+ events , _response = run_lambda_function (
149
+ LAMBDA_PRELUDE
150
+ + dedent (
151
+ """
152
+ def test_handler(event, context):
153
+ init_sdk()
154
+ sentry_sdk.capture_exception(Exception("something went wrong"))
155
+ """
156
+ ),
157
+ b'{"foo": "bar"}' ,
158
+ )
159
+
160
+ event , = events
161
+ assert event ["level" ] == "error"
162
+ exception , = event ["exception" ]["values" ]
163
+ assert exception ["type" ] == "Exception"
164
+ assert exception ["value" ] == "something went wrong"
165
+
166
+
142
167
def test_request_data (run_lambda_function ):
143
168
events , _response = run_lambda_function (
144
- 'sentry_sdk.capture_message("hi")\n return "ok"' ,
169
+ LAMBDA_PRELUDE
170
+ + dedent (
171
+ """
172
+ init_sdk()
173
+ def test_handler(event, context):
174
+ sentry_sdk.capture_message("hi")
175
+ return "ok"
176
+ """
177
+ ),
145
178
payload = b"""
146
179
{
147
180
"resource": "/asd",
0 commit comments