-
Notifications
You must be signed in to change notification settings - Fork 7
/
tests.py
289 lines (213 loc) · 7.64 KB
/
tests.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
import asyncio
import json
import logging
import threading
import zlib
import sanic
import sanic.response
from sanic.websocket import WebSocketProtocol
import flask
import pytest
from werkzeug.routing import PathConverter
from werkzeug.serving import make_server
import sanic_sentry
@pytest.yield_fixture
def app():
try:
app = sanic.Sanic("test_sanic_app", register=False)
except TypeError as e:
if str(e) != "__init__() got an unexpected keyword argument 'register'":
raise
app = sanic.Sanic("test_sanic_app")
yield app
@pytest.fixture
def sanic_server(loop, app, test_server):
return loop.run_until_complete(test_server(app))
@pytest.fixture
def client(loop, app, test_client):
return loop.run_until_complete(test_client(app))
@pytest.fixture
def websocket_client(loop, app, test_client):
return loop.run_until_complete(test_client(app, protocol=WebSocketProtocol))
@pytest.fixture
def mock_service():
with Service(host='127.0.0.1', port=8000) as service:
yield service
@pytest.fixture
def sentry_calls():
return []
@pytest.fixture
def sentry_url(sentry_mock):
return 'http://public:secret@127.0.0.1:8000/1'
@pytest.fixture
def sentry_mock(mock_service, sentry_calls):
@mock_service.app.route('/<everything:path>', methods=['POST'])
def handle_request(path):
sentry_calls.append((path, flask.request.mimetype,
json.loads(zlib.decompress(flask.request.data).decode('utf-8'))))
return ''
return mock_service
async def test_simple(app, client, sentry_url, sentry_calls):
app.config['SENTRY_DSN'] = sentry_url
sanic_sentry.SanicSentry(app)
@app.route('/test')
def simple(request):
return sanic.response.text('text')
response = await client.get('/test')
assert response.status == 200
response_text = await response.text()
assert response_text == 'text'
await asyncio.sleep(0.01)
assert len(sentry_calls) == 0
@pytest.mark.parametrize('params', [
None,
{},
{'release': None},
{'release': 'myapp_v0.4'},
])
async def test_exception(app, client, sentry_calls, sentry_url, params):
app.config['SENTRY_DSN'] = sentry_url
if params is not None:
app.config['SENTRY_PARAMS'] = params
sanic_sentry.SanicSentry(app)
@app.route('/test')
def simple(request):
raise Exception
response = await client.get('/test')
assert response.status == 500
await asyncio.sleep(0.01)
assert len(sentry_calls) == 1
assert sentry_calls[0][0] == 'api/1/store/'
assert sentry_calls[0][1] == 'application/octet-stream'
assert sentry_calls[0][2]['level'] == 40
assert sentry_calls[0][2]['tags'] == {}
assert sentry_calls[0][2]['project'] == '1'
assert sentry_calls[0][2]['repos'] == {}
if params and params.get('release'):
assert sentry_calls[0][2]['release'] == params.get('release')
else:
assert 'release' not in sentry_calls[0][2]
assert set(sentry_calls[0][2]['extra'].keys()) == {'sys.argv', 'pathname', 'filename', 'stack_info', 'lineno',
'thread', 'threadName', 'processName', 'process', 'asctime'}
assert len(sentry_calls[0][2]['breadcrumbs']['values']) == 1
assert sentry_calls[0][2]['breadcrumbs']['values'][0]['data'] == {}
assert 'python' in sentry_calls[0][2]['modules']
async def test_warning(app, client, sentry_calls, sentry_url):
app.config['SENTRY_DSN'] = sentry_url
app.config['SENTRY_LEVEL'] = logging.WARNING
sanic_sentry.SanicSentry(app)
@app.route('/test')
def simple(request):
try:
from sanic.log import logger
except ImportError:
logger = logging.getLogger('sanic')
logger.warning('SOMETHING bad happen')
return sanic.response.text('text')
response = await client.get('/test')
assert response.status == 200
response_text = await response.text()
assert response_text == 'text'
await asyncio.sleep(0.01)
assert len(sentry_calls) == 1
assert sentry_calls[0][2]['level'] == 30
async def test_warning_not_sent(app, client, sentry_calls, sentry_url):
app.config['SENTRY_DSN'] = sentry_url
sanic_sentry.SanicSentry(app)
@app.route('/test')
def simple(request):
logging.getLogger('sanic').warning('SOMETHING bad happen')
return sanic.response.text('text')
response = await client.get('/test')
assert response.status == 200
response_text = await response.text()
assert response_text == 'text'
await asyncio.sleep(0.01)
assert len(sentry_calls) == 0
async def test_error_handler(app, client, sentry_calls, sentry_url):
app.config['SENTRY_DSN'] = sentry_url
sanic_sentry.SanicSentry(app)
class CustomException(Exception):
pass
@app.route('/test')
def simple(request):
raise CustomException
@app.exception(CustomException)
def handle_custom(request, exception):
return sanic.response.text('text')
response = await client.get('/test')
assert response.status == 200
response_text = await response.text()
assert response_text == 'text'
await asyncio.sleep(0.01)
assert len(sentry_calls) == 0
async def test_exception_in_error_handler(app, client, sentry_calls, sentry_url):
app.config['SENTRY_DSN'] = sentry_url
sanic_sentry.SanicSentry(app)
class CustomException(Exception):
pass
@app.route('/test')
def simple(request):
raise CustomException
@app.exception(CustomException)
def handle_custom(request, exception):
raise Exception
response = await client.get('/test')
assert response.status == 500
await asyncio.sleep(0.01)
assert len(sentry_calls) == 1
async def test_websocket(app, websocket_client, sentry_calls, sentry_url):
app.config['SENTRY_DSN'] = sentry_url
sanic_sentry.SanicSentry(app)
@app.websocket('/test')
async def simple(request, ws):
await ws.send('text')
ws_conn = await websocket_client.ws_connect('/test')
msg = await ws_conn.receive()
assert msg.data == 'text'
await ws_conn.close()
await asyncio.sleep(0.01)
assert len(sentry_calls) == 0
async def test_websocket_exception(app, websocket_client, sentry_calls, sentry_url):
app.config['SENTRY_DSN'] = sentry_url
sanic_sentry.SanicSentry(app)
@app.websocket('/test')
async def simple(request, ws):
raise Exception
ws_conn = await websocket_client.ws_connect('/test')
msg = await ws_conn.receive()
assert msg.type.value in {257, 258}
await ws_conn.close()
await asyncio.sleep(0.01)
assert len(sentry_calls) == 1
class EverythingConverter(PathConverter):
regex = '.*?'
class Service:
def __init__(self, *, host, port):
self.host = host
self.port = port
self.app = flask.Flask('test')
self.app.url_map.converters['everything'] = EverythingConverter
self.srv = make_server(host=self.host, port=self.port, app=self.app)
self.server_thread = threading.Thread(target=self.run, daemon=True)
def run(self):
self.srv.serve_forever()
@property
def url(self):
return 'http://{host}:{port}'.format(
host=self.host, port=self.port)
def __repr__(self):
return '{cls}(url={url})'.format(
cls=self.__class__.__name__,
url=self.url,
)
def start(self):
self.server_thread.start()
def stop(self):
self.srv.shutdown()
self.server_thread.join()
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop()