-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathtest_sse.py
559 lines (442 loc) · 16.7 KB
/
test_sse.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
import asyncio
import sys
import pytest
from aiohttp import web
from aiohttp.pytest_plugin import AiohttpClient
from aiohttp.test_utils import make_mocked_request
from aiohttp_sse import EventSourceResponse, sse_response
socket = web.AppKey("socket", list[EventSourceResponse])
@pytest.mark.parametrize(
"with_sse_response",
(False, True),
ids=("without_sse_response", "with_sse_response"),
)
async def test_func(with_sse_response: bool, aiohttp_client: AiohttpClient) -> None:
async def func(request: web.Request) -> web.StreamResponse:
if with_sse_response:
resp = await sse_response(request, headers={"X-SSE": "aiohttp_sse"})
else:
resp = EventSourceResponse(headers={"X-SSE": "aiohttp_sse"})
await resp.prepare(request)
await resp.send("foo")
await resp.send("foo", event="bar")
await resp.send("foo", event="bar", id="xyz")
await resp.send("foo", event="bar", id="xyz", retry=1)
resp.stop_streaming()
await resp.wait()
return resp
app = web.Application()
app.router.add_route("GET", "/", func)
app.router.add_route("POST", "/", func)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 200 == resp.status
# make sure that EventSourceResponse supports passing
# custom headers
assert resp.headers.get("X-SSE") == "aiohttp_sse"
# make sure default headers set
assert resp.headers.get("Content-Type") == "text/event-stream"
assert resp.headers.get("Cache-Control") == "no-cache"
assert resp.headers.get("Connection") == "keep-alive"
assert resp.headers.get("X-Accel-Buffering") == "no"
# check streamed data
streamed_data = await resp.text()
expected = (
"data: foo\r\n\r\n"
"event: bar\r\ndata: foo\r\n\r\n"
"id: xyz\r\nevent: bar\r\ndata: foo\r\n\r\n"
"id: xyz\r\nevent: bar\r\ndata: foo\r\nretry: 1\r\n\r\n"
)
assert streamed_data == expected
async def test_wait_stop_streaming(aiohttp_client: AiohttpClient) -> None:
async def func(request: web.Request) -> web.StreamResponse:
app = request.app
resp = EventSourceResponse()
await resp.prepare(request)
await resp.send("foo", event="bar", id="xyz", retry=1)
app[socket].append(resp)
await resp.wait()
return resp
app = web.Application()
app[socket] = []
app.router.add_route("GET", "/", func)
client = await aiohttp_client(app)
resp_task = asyncio.create_task(client.get("/"))
await asyncio.sleep(0.1)
esourse = app[socket][0]
esourse.stop_streaming()
await esourse.wait()
resp = await resp_task
assert 200 == resp.status
streamed_data = await resp.text()
expected = "id: xyz\r\nevent: bar\r\ndata: foo\r\nretry: 1\r\n\r\n"
assert streamed_data == expected
async def test_retry(aiohttp_client: AiohttpClient) -> None:
async def func(request: web.Request) -> web.StreamResponse:
resp = EventSourceResponse()
await resp.prepare(request)
with pytest.raises(TypeError):
await resp.send("foo", retry="one") # type: ignore[arg-type]
await resp.send("foo", retry=1)
resp.stop_streaming()
await resp.wait()
return resp
app = web.Application()
app.router.add_route("GET", "/", func)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 200 == resp.status
# check streamed data
streamed_data = await resp.text()
expected = "data: foo\r\nretry: 1\r\n\r\n"
assert streamed_data == expected
async def test_wait_stop_streaming_errors() -> None:
response = EventSourceResponse()
with pytest.raises(RuntimeError) as ctx:
await response.wait()
assert str(ctx.value) == "Response is not started"
with pytest.raises(RuntimeError) as ctx:
response.stop_streaming()
assert str(ctx.value) == "Response is not started"
def test_compression_not_implemented() -> None:
response = EventSourceResponse()
with pytest.raises(NotImplementedError):
response.enable_compression()
class TestPingProperty:
@pytest.mark.parametrize("value", (25, 25.0, 0), ids=("int", "float", "zero int"))
def test_success(self, value: float) -> None:
response = EventSourceResponse()
response.ping_interval = value
assert response.ping_interval == value
@pytest.mark.parametrize("value", [None, "foo"], ids=("None", "str"))
def test_wrong_type(self, value: float) -> None:
response = EventSourceResponse()
with pytest.raises(TypeError) as ctx:
response.ping_interval = value
assert ctx.match("ping interval must be int or float")
def test_negative_int(self) -> None:
response = EventSourceResponse()
with pytest.raises(ValueError) as ctx:
response.ping_interval = -42
assert ctx.match("ping interval must be greater then 0")
def test_default_value(self) -> None:
response = EventSourceResponse()
assert response.ping_interval == response.DEFAULT_PING_INTERVAL
async def test_ping(aiohttp_client: AiohttpClient) -> None:
async def func(request: web.Request) -> web.StreamResponse:
app = request.app
resp = EventSourceResponse()
resp.ping_interval = 1
await resp.prepare(request)
await resp.send("foo")
app[socket].append(resp)
await resp.wait()
return resp
app = web.Application()
app[socket] = []
app.router.add_route("GET", "/", func)
client = await aiohttp_client(app)
resp_task = asyncio.create_task(client.get("/"))
await asyncio.sleep(1.15)
esourse = app[socket][0]
esourse.stop_streaming()
await esourse.wait()
resp = await resp_task
assert 200 == resp.status
streamed_data = await resp.text()
expected = "data: foo\r\n\r\n" + ": ping\r\n\r\n"
assert streamed_data == expected
async def test_ping_reset(
aiohttp_client: AiohttpClient,
monkeypatch: pytest.MonkeyPatch,
) -> None:
async def func(request: web.Request) -> web.StreamResponse:
app = request.app
resp = EventSourceResponse()
resp.ping_interval = 1
await resp.prepare(request)
await resp.send("foo")
app[socket].append(resp)
await resp.wait()
return resp
app = web.Application()
app[socket] = []
app.router.add_route("GET", "/", func)
client = await aiohttp_client(app)
resp_task = asyncio.create_task(client.get("/"))
await asyncio.sleep(1.15)
esource = app[socket][0]
def reset_error_write(data: str) -> None:
raise ConnectionResetError("Cannot write to closing transport")
assert esource._ping_task
assert not esource._ping_task.done()
monkeypatch.setattr(esource, "write", reset_error_write)
await esource.wait()
assert esource._ping_task.done()
resp = await resp_task
assert 200 == resp.status
streamed_data = await resp.text()
expected = "data: foo\r\n\r\n" + ": ping\r\n\r\n"
assert streamed_data == expected
async def test_ping_auto_close(aiohttp_client: AiohttpClient) -> None:
"""Test ping task automatically closed on send failure."""
async def handler(request: web.Request) -> EventSourceResponse:
async with sse_response(request) as sse:
sse.ping_interval = 999
request.protocol.force_close()
with pytest.raises(ConnectionResetError):
await sse.send("never-should-be-delivered")
assert sse._ping_task is not None
assert sse._ping_task.cancelled()
return sse # pragma: no cover
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/") as response:
assert 200 == response.status
async def test_context_manager(aiohttp_client: AiohttpClient) -> None:
async def func(request: web.Request) -> web.StreamResponse:
h = {"X-SSE": "aiohttp_sse"}
async with sse_response(request, headers=h) as sse:
await sse.send("foo")
await sse.send("foo", event="bar")
await sse.send("foo", event="bar", id="xyz")
await sse.send("foo", event="bar", id="xyz", retry=1)
return sse
app = web.Application()
app.router.add_route("GET", "/", func)
app.router.add_route("POST", "/", func)
client = await aiohttp_client(app)
resp = await client.get("/")
assert resp.status == 200
# make sure that EventSourceResponse supports passing
# custom headers
assert resp.headers["X-SSE"] == "aiohttp_sse"
# check streamed data
streamed_data = await resp.text()
expected = (
"data: foo\r\n\r\n"
"event: bar\r\ndata: foo\r\n\r\n"
"id: xyz\r\nevent: bar\r\ndata: foo\r\n\r\n"
"id: xyz\r\nevent: bar\r\ndata: foo\r\nretry: 1\r\n\r\n"
)
assert streamed_data == expected
class TestCustomResponseClass:
async def test_subclass(self) -> None:
class CustomEventSource(EventSourceResponse):
pass
request = make_mocked_request("GET", "/")
await sse_response(request, response_cls=CustomEventSource)
async def test_not_related_class(self) -> None:
class CustomClass:
pass
request = make_mocked_request("GET", "/")
with pytest.raises(TypeError):
await sse_response(
request=request,
response_cls=CustomClass, # type: ignore[type-var]
)
@pytest.mark.parametrize("sep", ["\n", "\r", "\r\n"], ids=("LF", "CR", "CR+LF"))
async def test_custom_sep(aiohttp_client: AiohttpClient, sep: str) -> None:
async def func(request: web.Request) -> web.StreamResponse:
h = {"X-SSE": "aiohttp_sse"}
async with sse_response(request, headers=h, sep=sep) as sse:
await sse.send("foo")
await sse.send("foo", event="bar")
await sse.send("foo", event="bar", id="xyz")
await sse.send("foo", event="bar", id="xyz", retry=1)
return sse
app = web.Application()
app.router.add_route("GET", "/", func)
client = await aiohttp_client(app)
resp = await client.get("/")
assert resp.status == 200
# make sure that EventSourceResponse supports passing
# custom headers
assert resp.headers["X-SSE"] == "aiohttp_sse"
# check streamed data
streamed_data = await resp.text()
expected = (
"data: foo{0}{0}"
"event: bar{0}data: foo{0}{0}"
"id: xyz{0}event: bar{0}data: foo{0}{0}"
"id: xyz{0}event: bar{0}data: foo{0}retry: 1{0}{0}"
)
assert streamed_data == expected.format(sep)
@pytest.mark.parametrize(
"stream_sep,line_sep",
[
(
"\n",
"\n",
),
(
"\n",
"\r",
),
(
"\n",
"\r\n",
),
(
"\r",
"\n",
),
(
"\r",
"\r",
),
(
"\r",
"\r\n",
),
(
"\r\n",
"\n",
),
(
"\r\n",
"\r",
),
(
"\r\n",
"\r\n",
),
],
ids=(
"steam-LF:line-LF",
"steam-LF:line-CR",
"steam-LF:line-CR+LF",
"steam-CR:line-LF",
"steam-CR:line-CR",
"steam-CR:line-CR+LF",
"steam-CR+LF:line-LF",
"steam-CR+LF:line-CR",
"steam-CR+LF:line-CR+LF",
),
)
async def test_multiline_data(
aiohttp_client: AiohttpClient,
stream_sep: str,
line_sep: str,
) -> None:
async def func(request: web.Request) -> web.StreamResponse:
h = {"X-SSE": "aiohttp_sse"}
lines = line_sep.join(["foo", "bar", "xyz"])
async with sse_response(request, headers=h, sep=stream_sep) as sse:
await sse.send(lines)
await sse.send(lines, event="bar")
await sse.send(lines, event="bar", id="xyz")
await sse.send(lines, event="bar", id="xyz", retry=1)
return sse
app = web.Application()
app.router.add_route("GET", "/", func)
client = await aiohttp_client(app)
resp = await client.get("/")
assert resp.status == 200
# make sure that EventSourceResponse supports passing
# custom headers
assert resp.headers["X-SSE"] == "aiohttp_sse"
# check streamed data
streamed_data = await resp.text()
expected = (
"data: foo{0}data: bar{0}data: xyz{0}{0}"
"event: bar{0}data: foo{0}data: bar{0}data: xyz{0}{0}"
"id: xyz{0}event: bar{0}data: foo{0}data: bar{0}data: xyz{0}{0}"
"id: xyz{0}event: bar{0}data: foo{0}data: bar{0}data: xyz{0}"
"retry: 1{0}{0}"
)
assert streamed_data == expected.format(stream_sep)
class TestSSEState:
async def test_context_states(self, aiohttp_client: AiohttpClient) -> None:
async def func(request: web.Request) -> web.StreamResponse:
async with sse_response(request) as resp:
assert resp.is_connected()
assert not resp.is_connected()
return resp
app = web.Application()
app.router.add_route("GET", "/", func)
client = await aiohttp_client(app)
resp = await client.get("/")
assert resp.status == 200
async def test_not_prepared(self) -> None:
response = EventSourceResponse()
assert not response.is_connected()
async def test_connection_is_not_alive(aiohttp_client: AiohttpClient) -> None:
async def func(request: web.Request) -> web.StreamResponse:
# within context manager first preparation is already done
async with sse_response(request) as sse:
request.protocol.force_close()
# this call should be cancelled, cause connection is closed
with pytest.raises(asyncio.CancelledError):
await sse.prepare(request)
return sse # pragma: no cover
app = web.Application()
app.router.add_route("GET", "/", func)
client = await aiohttp_client(app)
async with client.get("/") as resp:
assert resp.status == 200
class TestLastEventId:
async def test_success(self, aiohttp_client: AiohttpClient) -> None:
async def func(request: web.Request) -> web.StreamResponse:
async with sse_response(request) as sse:
assert sse.last_event_id is not None
await sse.send(sse.last_event_id)
return sse
app = web.Application()
app.router.add_route("GET", "/", func)
client = await aiohttp_client(app)
async with client.get("/") as resp:
assert resp.status == 200
last_event_id = "42"
headers = {EventSourceResponse.DEFAULT_LAST_EVENT_HEADER: last_event_id}
async with client.get("/", headers=headers) as resp:
assert resp.status == 200
# check streamed data
streamed_data = await resp.text()
assert streamed_data == f"data: {last_event_id}\r\n\r\n"
async def test_get_before_prepare(self) -> None:
sse = EventSourceResponse()
with pytest.raises(RuntimeError):
_ = sse.last_event_id
@pytest.mark.parametrize(
"http_method",
("GET", "POST", "PUT", "DELETE", "PATCH"),
)
async def test_http_methods(aiohttp_client: AiohttpClient, http_method: str) -> None:
async def handler(request: web.Request) -> EventSourceResponse:
async with sse_response(request) as sse:
await sse.send("foo")
return sse
app = web.Application()
app.router.add_route(http_method, "/", handler)
client = await aiohttp_client(app)
async with client.request(http_method, "/") as resp:
assert resp.status == 200
# check streamed data
streamed_data = await resp.text()
assert streamed_data == "data: foo\r\n\r\n"
@pytest.mark.skipif(
sys.version_info < (3, 11),
reason=".cancelling() missing in older versions",
)
async def test_cancelled_not_swallowed(aiohttp_client: AiohttpClient) -> None:
"""Test asyncio.CancelledError is not swallowed by .wait().
Relates to:
https://github.com/aio-libs/aiohttp-sse/issues/458
"""
async def endless_task(sse: EventSourceResponse) -> None:
while True:
await sse.wait()
async def handler(request: web.Request) -> EventSourceResponse:
async with sse_response(request) as sse:
task = asyncio.create_task(endless_task(sse))
await asyncio.sleep(0)
task.cancel()
await task
return sse # pragma: no cover
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/") as response:
assert 200 == response.status