forked from getsentry/sentry-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_client.py
More file actions
283 lines (206 loc) · 7.41 KB
/
test_client.py
File metadata and controls
283 lines (206 loc) · 7.41 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
# coding: utf-8
import logging
import pytest
import subprocess
import sys
import time
from datetime import datetime
from textwrap import dedent
from sentry_sdk import Hub, Client, configure_scope, capture_message, add_breadcrumb
from sentry_sdk.hub import HubMeta
from sentry_sdk.transport import Transport
from sentry_sdk._compat import reraise, text_type
class EventCaptured(Exception):
pass
class _TestTransport(Transport):
def capture_event(self, event):
raise EventCaptured(event)
def test_transport_option(monkeypatch):
dsn = "https://foo@sentry.io/123"
dsn2 = "https://bar@sentry.io/124"
assert str(Client(dsn=dsn).dsn) == dsn
assert Client().dsn is None
monkeypatch.setenv("SENTRY_DSN", dsn)
transport = Transport({"dsn": dsn2})
assert text_type(transport.parsed_dsn) == dsn2
assert str(Client(transport=transport).dsn) == dsn
def test_http_proxy(monkeypatch):
client = Client("https://foo@sentry.io/123", http_proxy="http://localhost/123")
assert client.transport._pool.proxy.scheme == "http"
client = Client(
"https://foo@sentry.io/123",
https_proxy="https://localhost/123",
http_proxy="http://localhost/123",
)
assert client.transport._pool.proxy.scheme == "https"
client = Client("http://foo@sentry.io/123", http_proxy="http://localhost/123")
assert client.transport._pool.proxy.scheme == "http"
client = Client(
"http://foo@sentry.io/123",
https_proxy="https://localhost/123",
http_proxy="http://localhost/123",
)
assert client.transport._pool.proxy.scheme == "http"
def test_simple_transport():
events = []
with Hub(Client(transport=events.append)):
capture_message("Hello World!")
assert events[0]["message"] == "Hello World!"
def test_ignore_errors():
class MyDivisionError(ZeroDivisionError):
pass
def raise_it(exc_info):
reraise(*exc_info)
hub = Hub(Client(ignore_errors=[ZeroDivisionError], transport=_TestTransport()))
hub._capture_internal_exception = raise_it
def e(exc):
try:
raise exc
except Exception:
hub.capture_exception()
e(ZeroDivisionError())
e(MyDivisionError())
pytest.raises(EventCaptured, lambda: e(ValueError()))
def test_with_locals_enabled():
events = []
hub = Hub(Client(with_locals=True, transport=events.append))
try:
1 / 0
except Exception:
hub.capture_exception()
event, = events
assert all(
frame["vars"]
for frame in event["exception"]["values"][0]["stacktrace"]["frames"]
)
def test_with_locals_disabled():
events = []
hub = Hub(Client(with_locals=False, transport=events.append))
try:
1 / 0
except Exception:
hub.capture_exception()
event, = events
assert all(
"vars" not in frame
for frame in event["exception"]["values"][0]["stacktrace"]["frames"]
)
def test_attach_stacktrace_enabled():
events = []
hub = Hub(Client(attach_stacktrace=True, transport=events.append))
def foo():
bar()
def bar():
hub.capture_message("HI")
foo()
event, = events
thread, = event["threads"]
functions = [x["function"] for x in thread["stacktrace"]["frames"]]
assert functions[-2:] == ["foo", "bar"]
def test_attach_stacktrace_disabled():
events = []
hub = Hub(Client(attach_stacktrace=False, transport=events.append))
hub.capture_message("HI")
event, = events
assert "threads" not in event
def test_capture_event_works():
c = Client(transport=_TestTransport())
pytest.raises(EventCaptured, lambda: c.capture_event({}))
pytest.raises(EventCaptured, lambda: c.capture_event({}))
@pytest.mark.parametrize("num_messages", [10, 20])
def test_atexit(tmpdir, monkeypatch, num_messages):
app = tmpdir.join("app.py")
app.write(
dedent(
"""
import time
from sentry_sdk import init, transport, capture_message
def send_event(self, event):
time.sleep(0.1)
print(event["message"])
transport.HttpTransport._send_event = send_event
init("http://foobar@localhost/123", shutdown_timeout={num_messages})
for _ in range({num_messages}):
capture_message("HI")
""".format(
num_messages=num_messages
)
)
)
start = time.time()
output = subprocess.check_output([sys.executable, str(app)])
end = time.time()
# Each message takes at least 0.1 seconds to process
assert int(end - start) >= num_messages / 10
assert output.count(b"HI") == num_messages
def test_configure_scope_available(sentry_init, request, monkeypatch):
# Test that scope is configured if client is configured
sentry_init()
with configure_scope() as scope:
assert scope is Hub.current._stack[-1][1]
scope.set_tag("foo", "bar")
calls = []
def callback(scope):
calls.append(scope)
scope.set_tag("foo", "bar")
assert configure_scope(callback) is None
assert len(calls) == 1
assert calls[0] is Hub.current._stack[-1][1]
@pytest.mark.parametrize("no_sdk", (True, False))
def test_configure_scope_unavailable(no_sdk, monkeypatch):
if no_sdk:
# Emulate minimal without SDK installation: callbacks are not called
monkeypatch.setattr(HubMeta, "current", None)
assert not Hub.current
else:
# Still, no client configured
assert Hub.current
calls = []
def callback(scope):
calls.append(scope)
scope.set_tag("foo", "bar")
with configure_scope() as scope:
scope.set_tag("foo", "bar")
assert configure_scope(callback) is None
assert not calls
@pytest.mark.parametrize("debug", (True, False))
def test_transport_works(httpserver, request, capsys, caplog, debug):
httpserver.serve_content("ok", 200)
caplog.set_level(logging.DEBUG)
client = Client(
"http://foobar@{}/123".format(httpserver.url[len("http://") :]), debug=debug
)
Hub.current.bind_client(client)
request.addfinalizer(lambda: Hub.current.bind_client(None))
add_breadcrumb(level="info", message="i like bread", timestamp=datetime.now())
capture_message("löl")
client.close()
out, err = capsys.readouterr()
assert not err and not out
assert httpserver.requests
assert any("Sending info event" in record.msg for record in caplog.records) == debug
@pytest.mark.tests_internal_exceptions
def test_client_debug_option_enabled(sentry_init, caplog):
sentry_init(debug=True)
Hub.current._capture_internal_exception((ValueError, ValueError("OK"), None))
assert "OK" in caplog.text
@pytest.mark.tests_internal_exceptions
@pytest.mark.parametrize("with_client", (True, False))
def test_client_debug_option_disabled(with_client, sentry_init, caplog):
if with_client:
sentry_init()
Hub.current._capture_internal_exception((ValueError, ValueError("OK"), None))
assert "OK" not in caplog.text
def test_scope_initialized_before_client(sentry_init, capture_events):
"""
This is a consequence of how configure_scope() works. We must
make `configure_scope()` a noop if no client is configured. Even
if the user later configures a client: We don't know that.
"""
with configure_scope() as scope:
scope.set_tag("foo", 42)
sentry_init()
events = capture_events()
capture_message("hi")
event, = events
assert "tags" not in event