forked from elastic/apm-agent-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexception_tests.py
More file actions
414 lines (344 loc) · 16.1 KB
/
exception_tests.py
File metadata and controls
414 lines (344 loc) · 16.1 KB
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
403
404
405
406
407
408
409
410
411
412
413
414
# BSD 3-Clause License
#
# Copyright (c) 2019, Elasticsearch BV
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
from unittest import mock
import pytest
import elasticapm
from elasticapm.conf.constants import ERROR, KEYWORD_MAX_LENGTH
from elasticapm.utils import encoding
from tests.utils.stacks import get_me_more_test_frames
def test_explicit_message_on_exception_event(elasticapm_client):
try:
raise ValueError("foo")
except ValueError:
elasticapm_client.capture("Exception", message="foobar")
assert len(elasticapm_client.events) == 1
event = elasticapm_client.events[ERROR][0]
assert event["exception"]["message"] == "foobar"
@pytest.mark.parametrize(
"elasticapm_client",
[{"include_paths": ("tests",), "local_var_max_length": 20, "local_var_list_max_length": 10}],
indirect=True,
)
def test_exception_event(elasticapm_client):
try:
a_local_var = 1
a_long_local_var = 100 * "a"
a_long_local_list = list(range(100))
raise ValueError("foo")
except ValueError:
elasticapm_client.capture("Exception")
assert len(elasticapm_client.events) == 1
event = elasticapm_client.events[ERROR][0]
assert "exception" in event
exc = event["exception"]
assert exc["message"] == "ValueError: foo"
assert exc["type"] == "ValueError"
assert exc["module"] == ValueError.__module__ # this differs in some Python versions
assert "stacktrace" in exc
frames = exc["stacktrace"]
assert len(frames) == 1
frame = frames[0]
assert frame["abs_path"], __file__.replace(".pyc" == ".py")
assert frame["filename"] == os.path.join("tests", "client", "exception_tests.py")
assert frame["module"] == __name__
assert frame["function"] == "test_exception_event"
assert not frame["library_frame"]
assert frame["vars"]["a_local_var"] == 1
assert len(frame["vars"]["a_long_local_var"]) == 20
assert len(frame["vars"]["a_long_local_list"]) == 12
assert frame["vars"]["a_long_local_list"][-1] == "(90 more elements)"
assert "timestamp" in event
assert "log" not in event
# check that only frames from `tests` module are not marked as library frames
assert all(
frame["library_frame"] or frame["module"].startswith("tests") for frame in event["exception"]["stacktrace"]
)
def test_sending_exception(sending_elasticapm_client: elasticapm.Client):
try:
1 / 0
except Exception:
sending_elasticapm_client.capture_exception()
sending_elasticapm_client.close()
assert (
sending_elasticapm_client.httpserver.responses[0]["code"] == 202
), sending_elasticapm_client.httpserver.responses[0]
@pytest.mark.parametrize(
"elasticapm_client",
[{"include_paths": ("*/tests/*",), "local_var_max_length": 20, "local_var_list_max_length": 10}],
indirect=True,
)
def test_message_event(elasticapm_client):
a_local_var = 1
a_long_local_var = 100 * "a"
a_long_local_list = list(range(100))
elasticapm_client.capture("Message", message="test")
assert len(elasticapm_client.events) == 1
event = elasticapm_client.events[ERROR][0]
assert event["log"]["message"] == "test"
assert "stacktrace" not in event
assert "timestamp" in event
assert "stacktrace" in event["log"]
# check that only frames from `tests` module are not marked as library frames
for frame in event["log"]["stacktrace"]:
# vscode's python extension runs tests using libraries from the
# extension's dir, which results in false positives here. This is where
# runpy, _pydevd, and debugpy come from.
assert frame["library_frame"] or frame["module"].startswith(
("tests", "__main__", "runpy", "_pydevd", "debugpy")
), (
frame["module"],
frame["abs_path"],
)
frame = event["log"]["stacktrace"][0]
assert frame["vars"]["a_local_var"] == 1
assert len(frame["vars"]["a_long_local_var"]) == 20
assert len(frame["vars"]["a_long_local_list"]) == 12
assert frame["vars"]["a_long_local_list"][-1] == "(90 more elements)"
def test_param_message_event(elasticapm_client):
elasticapm_client.capture("Message", param_message={"message": "test %s %d", "params": ("x", 1)})
assert len(elasticapm_client.events[ERROR]) == 1
event = elasticapm_client.events[ERROR][0]
assert event["log"]["message"] == "test x 1"
assert event["log"]["param_message"] == "test %s %d"
def test_message_with_percent(elasticapm_client):
elasticapm_client.capture("Message", message="This works 100% of the time")
assert len(elasticapm_client.events[ERROR]) == 1
event = elasticapm_client.events[ERROR][0]
assert event["log"]["message"] == "This works 100% of the time"
assert event["log"]["param_message"] == "This works 100% of the time"
def test_logger(elasticapm_client):
elasticapm_client.capture("Message", message="test", logger_name="test")
assert len(elasticapm_client.events[ERROR]) == 1
event = elasticapm_client.events[ERROR][0]
assert event["log"]["logger_name"] == "test"
assert "timestamp" in event
@pytest.mark.parametrize(
"elasticapm_client",
[
{"collect_local_variables": "errors"},
{"collect_local_variables": "transactions"},
{"collect_local_variables": "all"},
{"collect_local_variables": "something"},
],
indirect=True,
)
def test_collect_local_variables_errors(elasticapm_client):
mode = elasticapm_client.config.collect_local_variables
try:
1 / 0
except ZeroDivisionError:
elasticapm_client.capture_exception()
event = elasticapm_client.events[ERROR][0]
if mode in ("errors", "all"):
assert "vars" in event["exception"]["stacktrace"][0], mode
else:
assert "vars" not in event["exception"]["stacktrace"][0], mode
@pytest.mark.parametrize(
"elasticapm_client",
[
{"source_lines_error_library_frames": 0, "source_lines_error_app_frames": 0},
{"source_lines_error_library_frames": 1, "source_lines_error_app_frames": 1},
{"source_lines_error_library_frames": 7, "source_lines_error_app_frames": 3},
],
indirect=True,
)
def test_collect_source_errors(elasticapm_client):
library_frame_context = elasticapm_client.config.source_lines_error_library_frames
in_app_frame_context = elasticapm_client.config.source_lines_error_app_frames
try:
import datetime
import json
json.dumps(datetime.datetime.now())
except TypeError:
elasticapm_client.capture_exception()
event = elasticapm_client.events[ERROR][0]
in_app_frame = event["exception"]["stacktrace"][0]
library_frame = event["exception"]["stacktrace"][1]
assert not in_app_frame["library_frame"]
assert library_frame["library_frame"]
if library_frame_context:
assert "context_line" in library_frame, library_frame_context
assert "pre_context" in library_frame, library_frame_context
assert "post_context" in library_frame, library_frame_context
lines = len([library_frame["context_line"]] + library_frame["pre_context"] + library_frame["post_context"])
assert lines == library_frame_context, library_frame_context
else:
assert "context_line" not in library_frame, library_frame_context
assert "pre_context" not in library_frame, library_frame_context
assert "post_context" not in library_frame, library_frame_context
if in_app_frame_context:
assert "context_line" in in_app_frame, in_app_frame_context
assert "pre_context" in in_app_frame, in_app_frame_context
assert "post_context" in in_app_frame, in_app_frame_context
lines = len([in_app_frame["context_line"]] + in_app_frame["pre_context"] + in_app_frame["post_context"])
assert lines == in_app_frame_context, (in_app_frame_context, in_app_frame["lineno"])
else:
assert "context_line" not in in_app_frame, in_app_frame_context
assert "pre_context" not in in_app_frame, in_app_frame_context
assert "post_context" not in in_app_frame, in_app_frame_context
def test_transaction_data_is_attached_to_errors_no_transaction(elasticapm_client):
elasticapm_client.capture_message("noid")
elasticapm_client.begin_transaction("test")
elasticapm_client.end_transaction("test", "test")
elasticapm_client.capture_message("noid")
errors = elasticapm_client.events[ERROR]
assert "transaction_id" not in errors[0]
assert "transaction_id" not in errors[1]
def test_transaction_data_is_attached_to_errors_message_outside_span(elasticapm_client):
elasticapm_client.begin_transaction("test")
elasticapm_client.capture_message("outside_span")
transaction = elasticapm_client.end_transaction("test", "test")
error = elasticapm_client.events[ERROR][0]
assert error["transaction_id"] == transaction.id
assert error["parent_id"] == transaction.id
assert error["transaction"]["sampled"]
assert error["transaction"]["type"] == "test"
def test_transaction_data_is_attached_to_errors_message_in_span(elasticapm_client):
elasticapm_client.begin_transaction("test")
with elasticapm.capture_span("in_span_handler_test") as span_obj:
elasticapm_client.capture_message("in_span")
transaction = elasticapm_client.end_transaction("test", "test")
error = elasticapm_client.events[ERROR][0]
assert error["transaction_id"] == transaction.id
assert error["parent_id"] == span_obj.id
assert error["transaction"]["sampled"]
assert error["transaction"]["type"] == "test"
def test_transaction_data_is_attached_to_errors_exc_handled_in_span(elasticapm_client):
elasticapm_client.begin_transaction("test")
with elasticapm.capture_span("in_span_handler_test") as span_obj:
try:
assert False
except AssertionError:
elasticapm_client.capture_exception()
transaction = elasticapm_client.end_transaction("test", "test")
error = elasticapm_client.events[ERROR][0]
assert error["transaction_id"] == transaction.id
assert error["parent_id"] == span_obj.id
assert error["transaction"]["sampled"]
assert error["transaction"]["type"] == "test"
def test_transaction_data_is_attached_to_errors_exc_handled_outside_span(elasticapm_client):
elasticapm_client.begin_transaction("test")
try:
with elasticapm.capture_span("out_of_span_handler_test") as span_obj:
assert False
except AssertionError:
elasticapm_client.capture_exception()
transaction = elasticapm_client.end_transaction("test", "test")
error = elasticapm_client.events[ERROR][0]
assert error["transaction_id"] == transaction.id
assert error["parent_id"] == span_obj.id
assert error["transaction"]["sampled"]
assert error["transaction"]["type"] == "test"
def test_transaction_context_is_used_in_errors(elasticapm_client):
elasticapm_client.begin_transaction("test")
elasticapm.label(foo="baz")
elasticapm.set_custom_context({"a": "b"})
elasticapm.set_user_context(username="foo", email="foo@example.com", user_id=42)
elasticapm_client.capture_message("x", custom={"foo": "bar"})
transaction = elasticapm_client.end_transaction("test", "OK")
message = elasticapm_client.events[ERROR][0]
assert message["context"]["custom"] == {"a": "b", "foo": "bar"}
assert message["context"]["user"] == {"username": "foo", "email": "foo@example.com", "id": 42}
assert message["context"]["tags"] == {"foo": "baz"}
assert "a" in transaction.context["custom"]
assert "foo" not in transaction.context["custom"]
def test_error_keyword_truncation(sending_elasticapm_client):
too_long = "x" * (KEYWORD_MAX_LENGTH + 1)
expected = encoding.keyword_field(too_long)
# let's create a way too long Exception type with a way too long module name
WayTooLongException = type(too_long.upper(), (Exception,), {})
WayTooLongException.__module__ = too_long
try:
raise WayTooLongException()
except WayTooLongException:
with mock.patch("elasticapm.events.get_culprit") as mock_get_culprit:
mock_get_culprit.return_value = too_long
sending_elasticapm_client.capture_exception(handled=False)
sending_elasticapm_client.close()
error = sending_elasticapm_client.httpserver.payloads[0][1]["error"]
assert error["exception"]["type"] == expected.upper()
assert error["exception"]["module"] == expected
assert error["culprit"] == expected
def test_message_keyword_truncation(sending_elasticapm_client):
too_long = "x" * (KEYWORD_MAX_LENGTH + 1)
expected = encoding.keyword_field(too_long)
sending_elasticapm_client.capture_message(
param_message={"message": too_long, "params": []}, logger_name=too_long, handled=False
)
sending_elasticapm_client.close()
error = sending_elasticapm_client.httpserver.payloads[0][1]["error"]
assert error["log"]["param_message"] == expected
assert error["log"]["message"] == too_long # message is not truncated
assert error["log"]["logger_name"] == expected
@pytest.mark.parametrize("elasticapm_client", [{"stack_trace_limit": 10}], indirect=True)
def test_stack_trace_limit(elasticapm_client):
def func():
1 / 0 # I'm the context line of the last frame!
try:
list(get_me_more_test_frames(15, func))
except ZeroDivisionError:
elasticapm_client.capture_exception()
exception = elasticapm_client.events[ERROR][-1]
frames = exception["exception"]["stacktrace"]
assert len(frames) == 10
assert "I'm the context line of the last frame" in frames[-1]["context_line"]
elasticapm_client.config.update("1", stack_trace_limit=-1)
try:
list(get_me_more_test_frames(15, func))
except ZeroDivisionError:
elasticapm_client.capture_exception()
exception = elasticapm_client.events[ERROR][-1]
frames = exception["exception"]["stacktrace"]
assert len(frames) > 15
assert "I'm the context line of the last frame" in frames[-1]["context_line"]
elasticapm_client.config.update("1", stack_trace_limit=0)
try:
list(get_me_more_test_frames(15, func))
except ZeroDivisionError:
elasticapm_client.capture_exception()
exception = elasticapm_client.events[ERROR][-1]
frames = exception["exception"]["stacktrace"]
assert len(frames) == 0
def test_fail_on_uuid_raise(elasticapm_client):
def generate_uuid():
from uuid import UUID
return UUID("INVALID")
try:
generate_uuid()
except Exception:
elasticapm_client.capture_exception()
def test_long_message(elasticapm_client):
try:
raise Exception("t" * 1000000)
except:
elasticapm_client.capture_exception()
exception = elasticapm_client.events[ERROR][0]
assert exception["exception"]["message"] == f'Exception: {"t"*9988}{"…"}'