/
test_starlite.py
297 lines (238 loc) · 8.76 KB
/
test_starlite.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import base64
import functools
import os
import pytest
from sentry_sdk import capture_exception, capture_message, last_event_id
from sentry_sdk.integrations.starlite import StarliteIntegration
from sentry_sdk.utils import AnnotatedValue
starlite = pytest.importorskip("starlite")
from typing import Any, Dict
from starlite import AbstractMiddleware, LoggingConfig, Starlite, get
from starlite.middleware import LoggingMiddlewareConfig, RateLimitConfig
from starlite.middleware.session.memory_backend import MemoryBackendConfig
from starlite.status_codes import HTTP_500_INTERNAL_SERVER_ERROR
from starlite.testing import TestClient
class SampleMiddleware(AbstractMiddleware):
async def __call__(self, scope, receive, send) -> None:
async def do_stuff(message):
if message["type"] == "http.response.start":
# do something here.
pass
await send(message)
await self.app(scope, receive, do_stuff)
class SampleReceiveSendMiddleware(AbstractMiddleware):
async def __call__(self, scope, receive, send):
message = await receive()
assert message
assert message["type"] == "http.request"
send_output = await send({"type": "something-unimportant"})
assert send_output is None
await self.app(scope, receive, send)
class SamplePartialReceiveSendMiddleware(AbstractMiddleware):
async def __call__(self, scope, receive, send):
message = await receive()
assert message
assert message["type"] == "http.request"
send_output = await send({"type": "something-unimportant"})
assert send_output is None
async def my_receive(*args, **kwargs):
pass
async def my_send(*args, **kwargs):
pass
partial_receive = functools.partial(my_receive)
partial_send = functools.partial(my_send)
await self.app(scope, partial_receive, partial_send)
def starlite_app_factory(middleware=None, debug=True, exception_handlers=None):
@get("/some_url")
async def homepage_handler() -> Dict[str, Any]:
1 / 0
return {"status": "ok"}
@get("/custom_error")
async def custom_error() -> Any:
raise Exception("Too Hot")
@get("/message")
async def message() -> Dict[str, Any]:
capture_message("hi")
return {"status": "ok"}
@get("/message/{message_id:str}")
async def message_with_id() -> Dict[str, Any]:
capture_message("hi")
return {"status": "ok"}
logging_config = LoggingConfig()
app = Starlite(
route_handlers=[homepage_handler, custom_error, message, message_with_id],
debug=debug,
middleware=middleware,
logging_config=logging_config,
exception_handlers=exception_handlers,
)
return app
@pytest.mark.parametrize(
"test_url,expected_error,expected_message",
[
("/some_url", ZeroDivisionError, "division by zero"),
("/custom_error", Exception, "Too Hot"),
],
)
def test_catch_exceptions(
sentry_init,
capture_exceptions,
capture_events,
test_url,
expected_error,
expected_message,
):
sentry_init(integrations=[StarliteIntegration()])
starlite_app = starlite_app_factory()
exceptions = capture_exceptions()
events = capture_events()
client = TestClient(starlite_app)
try:
client.get(test_url)
except Exception:
pass
(exc,) = exceptions
assert isinstance(exc, expected_error)
assert str(exc) == expected_message
(event,) = events
assert event["exception"]["values"][0]["mechanism"]["type"] == "starlite"
def test_middleware_spans(sentry_init, capture_events):
sentry_init(
traces_sample_rate=1.0,
integrations=[StarliteIntegration()],
)
logging_config = LoggingMiddlewareConfig()
session_config = MemoryBackendConfig()
rate_limit_config = RateLimitConfig(rate_limit=("hour", 5))
starlite_app = starlite_app_factory(
middleware=[
session_config.middleware,
logging_config.middleware,
rate_limit_config.middleware,
]
)
events = capture_events()
client = TestClient(
starlite_app, raise_server_exceptions=False, base_url="http://testserver.local"
)
try:
client.get("/message")
except Exception:
pass
(_, transaction_event) = events
expected = ["SessionMiddleware", "LoggingMiddleware", "RateLimitMiddleware"]
idx = 0
for span in transaction_event["spans"]:
if span["op"] == "middleware.starlite":
assert span["description"] == expected[idx]
assert span["tags"]["starlite.middleware_name"] == expected[idx]
idx += 1
def test_middleware_callback_spans(sentry_init, capture_events):
sentry_init(
traces_sample_rate=1.0,
integrations=[StarliteIntegration()],
)
starlette_app = starlite_app_factory(middleware=[SampleMiddleware])
events = capture_events()
client = TestClient(starlette_app, raise_server_exceptions=False)
try:
client.get("/message")
except Exception:
pass
(_, transaction_event) = events
expected = [
{
"op": "middleware.starlite",
"description": "SampleMiddleware",
"tags": {"starlite.middleware_name": "SampleMiddleware"},
},
{
"op": "middleware.starlite.send",
"description": "TestClientTransport.create_send.<locals>.send",
"tags": {"starlite.middleware_name": "SampleMiddleware"},
},
{
"op": "middleware.starlite.send",
"description": "TestClientTransport.create_send.<locals>.send",
"tags": {"starlite.middleware_name": "SampleMiddleware"},
},
]
print(transaction_event["spans"])
idx = 0
for span in transaction_event["spans"]:
assert span["op"] == expected[idx]["op"]
assert span["description"] == expected[idx]["description"]
assert span["tags"] == expected[idx]["tags"]
idx += 1
def test_middleware_receive_send(sentry_init, capture_events):
sentry_init(
traces_sample_rate=1.0,
integrations=[StarliteIntegration()],
)
starlette_app = starlite_app_factory(middleware=[SampleReceiveSendMiddleware])
client = TestClient(starlette_app, raise_server_exceptions=False)
try:
# NOTE: the assert statements checking
# for correct behaviour are in `SampleReceiveSendMiddleware`!
client.get("/message")
except Exception:
pass
def test_middleware_partial_receive_send(sentry_init, capture_events):
sentry_init(
traces_sample_rate=1.0,
integrations=[StarliteIntegration()],
)
starlette_app = starlite_app_factory(
middleware=[SamplePartialReceiveSendMiddleware]
)
events = capture_events()
client = TestClient(starlette_app, raise_server_exceptions=False)
try:
client.get("/message")
except Exception:
pass
(_, transaction_event) = events
expected = [
{
"op": "middleware.starlite",
"description": "SamplePartialReceiveSendMiddleware",
"tags": {"starlite.middleware_name": "SamplePartialReceiveSendMiddleware"},
},
{
"op": "middleware.starlite.receive",
"description": "TestClientTransport.create_receive.<locals>.receive",
"tags": {"starlite.middleware_name": "SamplePartialReceiveSendMiddleware"},
},
{
"op": "middleware.starlite.send",
"description": "TestClientTransport.create_send.<locals>.send",
"tags": {"starlite.middleware_name": "SamplePartialReceiveSendMiddleware"},
},
]
print(transaction_event["spans"])
idx = 0
for span in transaction_event["spans"]:
assert span["op"] == expected[idx]["op"]
assert span["description"].startswith(expected[idx]["description"])
assert span["tags"] == expected[idx]["tags"]
idx += 1
def test_last_event_id(sentry_init, capture_events):
sentry_init(
integrations=[StarliteIntegration()],
)
events = capture_events()
def handler(request, exc):
capture_exception(exc)
return starlite.response.Response(last_event_id(), status_code=500)
app = starlite_app_factory(
debug=False, exception_handlers={HTTP_500_INTERNAL_SERVER_ERROR: handler}
)
client = TestClient(app, raise_server_exceptions=False)
response = client.get("/custom_error")
assert response.status_code == 500
print(events)
event = events[-1]
assert response.content.strip().decode("ascii") == event["event_id"]
(exception,) = event["exception"]["values"]
assert exception["type"] == "Exception"
assert exception["value"] == "Too Hot"