forked from DataDog/dd-trace-py
/
test_sanic.py
402 lines (325 loc) · 13.2 KB
/
test_sanic.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import asyncio
import random
import re
import pytest
from sanic import Sanic
from sanic import __version__ as sanic_version
from sanic.config import DEFAULT_CONFIG
from sanic.exceptions import InvalidUsage
from sanic.exceptions import ServerError
from sanic.response import ResponseStream
from sanic.response import json
from sanic.response import text
from sanic.server import HttpProtocol
from ddtrace import config
from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY
from ddtrace.constants import ERROR_MSG
from ddtrace.constants import ERROR_STACK
from ddtrace.constants import ERROR_TYPE
from ddtrace.propagation import http as http_propagation
from tests.utils import override_config
from tests.utils import override_http_config
# Helpers for handling response objects across sanic versions
sanic_version = tuple(map(int, sanic_version.split(".")))
def _response_status(response):
return getattr(response, "status_code", getattr(response, "status", None))
async def _response_json(response):
resp_json = response.json
if callable(resp_json):
resp_json = response.json()
if asyncio.iscoroutine(resp_json):
resp_json = await resp_json
return resp_json
async def _response_text(response):
resp_text = response.text
if callable(resp_text):
resp_text = resp_text()
if asyncio.iscoroutine(resp_text):
resp_text = await resp_text
return resp_text
@pytest.fixture
def app(tracer):
# Sanic 20.12 and newer prevent loading multiple applications
# with the same name if register is True.
DEFAULT_CONFIG["REGISTER"] = False
DEFAULT_CONFIG["RESPONSE_TIMEOUT"] = 1.0
app = Sanic("sanic")
@tracer.wrap()
async def random_sleep():
await asyncio.sleep(random.random() * 0.1)
@app.route("/hello")
async def hello(request):
await random_sleep()
return json({"hello": "world"})
@app.route("/hello/<first_name>")
async def hello_single_param(request, first_name):
await random_sleep()
return json({"hello": first_name})
@app.route("/hello/<first_name>/<surname>")
async def hello_multiple_params(request, first_name, surname):
await random_sleep()
return json({"hello": f"{first_name} {surname}"})
@app.route("/stream_response")
async def stream_response(request):
async def sample_streaming_fn(response):
await response.write("foo,")
await response.write("bar")
return ResponseStream(sample_streaming_fn, content_type="text/csv")
@app.route("/error400")
async def error_400(request):
raise InvalidUsage("Something bad with the request")
@app.route("/error")
async def error(request):
raise ServerError("Something bad happened", status_code=500)
@app.route("/invalid")
async def invalid(request):
return "This should fail"
@app.route("/empty")
async def empty(request):
pass
@app.route("/<n:int>/count", methods=["GET"])
async def count(request, n):
return json({"hello": n})
@app.exception(ServerError)
def handler_exception(request, exception):
return text(exception.args[0], exception.status_code)
yield app
# DEV: pytest-sanic is not compatible with sanic >= 21.9.0 so we instead
# are using sanic_testing, but need to create a compatible fixture/API
if sanic_version >= (21, 9, 0):
@pytest.fixture
def client(app):
from sanic_testing.testing import SanicASGITestClient
# Create a test client compatible with pytest-sanic test client
class TestClient(SanicASGITestClient):
async def request(self, *args, **kwargs):
request, response = await super(TestClient, self).request(*args, **kwargs)
return response
return TestClient(app)
else:
@pytest.fixture
@pytest.mark.asyncio
async def client(sanic_client, app):
return await sanic_client(app, protocol=HttpProtocol)
@pytest.fixture(
params=[
dict(),
dict(service="mysanicsvc"),
dict(analytics_enabled=False),
dict(analytics_enabled=True),
dict(analytics_enabled=True, analytics_sample_rate=0.5),
dict(analytics_enabled=False, analytics_sample_rate=0.5),
dict(distributed_tracing=False),
],
ids=[
"default",
"service_override",
"disable_analytics",
"enable_analytics_default_sample_rate",
"enable_analytics_custom_sample_rate",
"disable_analytics_custom_sample_rate",
"disable_distributed_tracing",
],
)
def integration_config(request):
return request.param
@pytest.fixture(
params=[
dict(),
dict(trace_query_string=False),
dict(trace_query_string=True),
],
ids=[
"default",
"disable trace query string",
"enable trace query string",
],
)
def integration_http_config(request):
return request.param
@pytest.mark.asyncio
async def test_basic_app(tracer, client, integration_config, integration_http_config, test_spans):
"""Test Sanic Patching"""
with override_http_config("sanic", integration_http_config):
with override_config("sanic", integration_config):
headers = [
(http_propagation.HTTP_HEADER_PARENT_ID, "1234"),
(http_propagation.HTTP_HEADER_TRACE_ID, "5678"),
]
response = await client.get("/hello", params=[("foo", "bar")], headers=headers)
assert _response_status(response) == 200
assert await _response_json(response) == {"hello": "world"}
spans = test_spans.pop_traces()
assert len(spans) == 1
assert len(spans[0]) == 2
request_span = spans[0][0]
assert request_span.name == "sanic.request"
assert request_span.error == 0
assert request_span.get_tag("http.method") == "GET"
assert re.search("/hello$", request_span.get_tag("http.url"))
assert request_span.get_tag("http.status_code") == "200"
assert request_span.resource == "GET /hello"
sleep_span = spans[0][1]
assert sleep_span.name == "tests.contrib.sanic.test_sanic.random_sleep"
assert sleep_span.parent_id == request_span.span_id
if integration_config.get("service"):
assert request_span.service == integration_config["service"]
else:
assert request_span.service == "sanic"
if integration_http_config.get("trace_query_string"):
assert request_span.get_tag("http.query.string") == "foo=bar"
else:
assert request_span.get_tag("http.query.string") is None
if integration_config.get("analytics_enabled"):
analytics_sample_rate = integration_config.get("analytics_sample_rate") or 1.0
assert request_span.get_metric(ANALYTICS_SAMPLE_RATE_KEY) == analytics_sample_rate
else:
assert request_span.get_metric(ANALYTICS_SAMPLE_RATE_KEY) is None
if integration_config.get("distributed_tracing", True):
assert request_span.parent_id == 1234
assert request_span.trace_id == 5678
else:
assert request_span.parent_id is None
assert request_span.trace_id is not None and request_span.trace_id != 5678
@pytest.mark.parametrize(
"url, expected_json, expected_resource",
[
("/hello/foo", {"hello": "foo"}, "GET /hello/<first_name>"),
("/hello/foo/bar", {"hello": "foo bar"}, "GET /hello/<first_name>/<surname>"),
],
)
@pytest.mark.asyncio
async def test_resource_name(tracer, client, url, expected_json, expected_resource, test_spans):
response = await client.get(url)
assert _response_status(response) == 200
assert await _response_json(response) == expected_json
spans = test_spans.pop_traces()
request_span = spans[0][0]
assert request_span.resource == expected_resource
@pytest.mark.asyncio
async def test_streaming_response(tracer, client, test_spans):
response = await client.get("/stream_response")
assert _response_status(response) == 200
assert (await _response_text(response)).endswith("foo,bar")
spans = test_spans.pop_traces()
assert len(spans) == 1
assert len(spans[0]) == 1
request_span = spans[0][0]
assert request_span.name == "sanic.request"
assert request_span.service == "sanic"
assert request_span.error == 0
assert request_span.get_tag("http.method") == "GET"
assert re.search("/stream_response$", request_span.get_tag("http.url"))
assert request_span.get_tag("http.query.string") is None
assert request_span.get_tag("http.status_code") == "200"
@pytest.mark.asyncio
@pytest.mark.parametrize(
"status_code,url,content",
[(400, "/error400", "Something bad with the request"), (404, "/nonexistent", "not found")],
)
async def test_error_app(tracer, client, test_spans, status_code, url, content):
response = await client.get(url)
assert _response_status(response) == status_code
assert content in await _response_text(response)
spans = test_spans.pop_traces()
assert len(spans) == 1
assert len(spans[0]) == 1
request_span = spans[0][0]
assert request_span.name == "sanic.request"
assert request_span.service == "sanic"
# We do not attach exception info for 404s
assert request_span.error == 0
assert request_span.get_tag(ERROR_MSG) is None
assert request_span.get_tag(ERROR_TYPE) is None
assert request_span.get_tag(ERROR_STACK) is None
assert request_span.get_tag("http.method") == "GET"
assert re.search(f"{url}$", request_span.get_tag("http.url"))
assert request_span.get_tag("http.query.string") is None
assert request_span.get_tag("http.status_code") == str(status_code)
@pytest.mark.asyncio
async def test_exception(tracer, client, test_spans):
response = await client.get("/error")
assert _response_status(response) == 500
assert "Something bad happened" in await _response_text(response)
spans = test_spans.pop_traces()
assert len(spans) == 1
assert len(spans[0]) == 1
request_span = spans[0][0]
assert request_span.name == "sanic.request"
assert request_span.service == "sanic"
assert request_span.error == 1
assert request_span.get_tag("http.method") == "GET"
assert re.search("/error$", request_span.get_tag("http.url"))
assert request_span.get_tag("http.query.string") is None
assert request_span.get_tag("http.status_code") == "500"
@pytest.mark.asyncio
async def test_multiple_requests(tracer, client, test_spans):
responses = await asyncio.gather(
client.get("/hello"),
client.get("/hello"),
)
assert len(responses) == 2
assert [_response_status(r) for r in responses] == [200] * 2
assert [await _response_json(r) for r in responses] == [{"hello": "world"}] * 2
spans = test_spans.pop_traces()
assert len(spans) == 2
assert len(spans[0]) == 2
assert len(spans[1]) == 2
assert spans[0][0].name == "sanic.request"
assert spans[0][1].name == "tests.contrib.sanic.test_sanic.random_sleep"
assert spans[0][0].parent_id is None
assert spans[0][1].parent_id == spans[0][0].span_id
assert spans[1][0].name == "sanic.request"
assert spans[1][1].name == "tests.contrib.sanic.test_sanic.random_sleep"
assert spans[1][0].parent_id is None
assert spans[1][1].parent_id == spans[1][0].span_id
@pytest.mark.asyncio
async def test_invalid_response_type_str(tracer, client, test_spans):
response = await client.get("/invalid")
assert _response_status(response) == 500
spans = test_spans.pop_traces()
assert len(spans) == 1
assert len(spans[0]) == 1
request_span = spans[0][0]
assert request_span.name == "sanic.request"
assert request_span.service == "sanic"
assert request_span.error == 1
assert request_span.get_tag("http.method") == "GET"
assert re.search("/invalid$", request_span.get_tag("http.url"))
assert request_span.get_tag("http.query.string") is None
assert request_span.get_tag("http.status_code") == "500"
@pytest.mark.asyncio
async def test_invalid_response_type_empty(tracer, client, test_spans):
response = await client.get("/empty")
assert _response_status(response) == 500
spans = test_spans.pop_traces()
assert len(spans) == 1
assert len(spans[0]) == 1
request_span = spans[0][0]
assert request_span.name == "sanic.request"
assert request_span.service == "sanic"
assert request_span.error == 1
assert request_span.get_tag("http.method") == "GET"
assert re.search("/empty$", request_span.get_tag("http.url"))
assert request_span.get_tag("http.query.string") is None
assert request_span.get_tag("http.status_code") == "500"
@pytest.mark.asyncio
async def test_http_request_header_tracing(tracer, client, test_spans):
config.sanic.http.trace_headers(["my-header"])
response = await client.get(
"/hello",
headers={
"my-header": "my_value",
},
)
assert _response_status(response) == 200
spans = test_spans.pop_traces()
assert len(spans) == 1
assert len(spans[0]) == 2
request_span = spans[0][0]
assert request_span.get_tag("http.request.headers.my-header") == "my_value"
@pytest.mark.asyncio
async def test_endpoint_with_numeric_arg(tracer, client, test_spans):
response = await client.get("/42/count")
assert _response_status(response) == 200
assert (await _response_text(response)) == '{"hello":42}'