forked from sanic-org/sanic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_request_stream.py
623 lines (501 loc) · 17.7 KB
/
test_request_stream.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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
import asyncio
import pytest
from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.response import json, text
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
data = "abc" * 1_000_000
def test_request_stream_method_view(app):
class SimpleView(HTTPMethodView):
def get(self, request):
return text("OK")
@stream_decorator
async def post(self, request):
result = b""
while True:
body = await request.stream.read()
if body is None:
break
result += body
return text(result.decode())
app.add_route(SimpleView.as_view(), "/method_view")
request, response = app.test_client.get("/method_view")
assert response.status == 200
assert response.text == "OK"
request, response = app.test_client.post("/method_view", data=data)
assert response.status == 200
assert response.text == data
@pytest.mark.parametrize(
"headers, expect_raise_exception",
[
({"EXPECT": "100-continue"}, False),
# The below test SHOULD work, and it does produce a 417
# However, httpx now intercepts this and raises an exception,
# so we will need a new method for testing this
# ({"EXPECT": "100-continue-extra"}, True),
],
)
def test_request_stream_100_continue(app, headers, expect_raise_exception):
class SimpleView(HTTPMethodView):
@stream_decorator
async def post(self, request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
app.add_route(SimpleView.as_view(), "/method_view")
if not expect_raise_exception:
request, response = app.test_client.post(
"/method_view", data=data, headers=headers
)
assert response.status == 200
assert response.text == data
else:
request, response = app.test_client.post(
"/method_view", data=data, headers=headers
)
assert response.status == 417
def test_request_stream_app(app):
@app.get("/get")
async def get(request):
return text("GET")
@app.head("/head")
async def head(request):
return text("HEAD")
@app.delete("/delete")
async def delete(request):
return text("DELETE")
@app.options("/options")
async def options(request):
return text("OPTIONS")
@app.post("/_post/<id>")
async def _post(request, id):
return text("_POST")
@app.post("/post/<id>", stream=True)
async def post(request, id):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
@app.put("/_put")
async def _put(request):
return text("_PUT")
@app.put("/put", stream=True)
async def put(request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
@app.patch("/_patch")
async def _patch(request):
return text("_PATCH")
@app.patch("/patch", stream=True)
async def patch(request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
request, response = app.test_client.get("/get")
assert response.status == 200
assert response.text == "GET"
request, response = app.test_client.head("/head")
assert response.status == 200
assert response.text == ""
request, response = app.test_client.delete("/delete")
assert response.status == 200
assert response.text == "DELETE"
request, response = app.test_client.options("/options")
assert response.status == 200
assert response.text == "OPTIONS"
request, response = app.test_client.post("/_post/1", data=data)
assert response.status == 200
assert response.text == "_POST"
request, response = app.test_client.post("/post/1", data=data)
assert response.status == 200
assert response.text == data
request, response = app.test_client.put("/_put", data=data)
assert response.status == 200
assert response.text == "_PUT"
request, response = app.test_client.put("/put", data=data)
assert response.status == 200
assert response.text == data
request, response = app.test_client.patch("/_patch", data=data)
assert response.status == 200
assert response.text == "_PATCH"
request, response = app.test_client.patch("/patch", data=data)
assert response.status == 200
assert response.text == data
@pytest.mark.asyncio
async def test_request_stream_app_asgi(app):
@app.get("/get")
async def get(request):
return text("GET")
@app.head("/head")
async def head(request):
return text("HEAD")
@app.delete("/delete")
async def delete(request):
return text("DELETE")
@app.options("/options")
async def options(request):
return text("OPTIONS")
@app.post("/_post/<id>")
async def _post(request, id):
return text("_POST")
@app.post("/post/<id>", stream=True)
async def post(request, id):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
@app.put("/_put")
async def _put(request):
return text("_PUT")
@app.put("/put", stream=True)
async def put(request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
@app.patch("/_patch")
async def _patch(request):
return text("_PATCH")
@app.patch("/patch", stream=True)
async def patch(request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
request, response = await app.asgi_client.get("/get")
assert response.status == 200
assert response.text == "GET"
request, response = await app.asgi_client.head("/head")
assert response.status == 200
assert response.text == ""
request, response = await app.asgi_client.delete("/delete")
assert response.status == 200
assert response.text == "DELETE"
request, response = await app.asgi_client.options("/options")
assert response.status == 200
assert response.text == "OPTIONS"
request, response = await app.asgi_client.post("/_post/1", data=data)
assert response.status == 200
assert response.text == "_POST"
request, response = await app.asgi_client.post("/post/1", data=data)
assert response.status == 200
assert response.text == data
request, response = await app.asgi_client.put("/_put", data=data)
assert response.status == 200
assert response.text == "_PUT"
request, response = await app.asgi_client.put("/put", data=data)
assert response.status == 200
assert response.text == data
request, response = await app.asgi_client.patch("/_patch", data=data)
assert response.status == 200
assert response.text == "_PATCH"
request, response = await app.asgi_client.patch("/patch", data=data)
assert response.status == 200
assert response.text == data
def test_request_stream_handle_exception(app):
"""for handling exceptions properly"""
@app.post("/post/<id>", stream=True)
async def post(request, id):
result = b""
while True:
body = await request.stream.read()
if body is None:
break
result += body
return text(result.decode())
# 404
request, response = app.test_client.post("/in_valid_post", data=data)
assert response.status == 404
assert "Requested URL /in_valid_post not found" in response.text
# 405
request, response = app.test_client.get("/post/random_id")
assert response.status == 405
assert "Method GET not allowed for URL /post/random_id" in response.text
def test_request_stream_blueprint(app):
bp = Blueprint("test_blueprint_request_stream_blueprint")
@app.get("/get")
async def get(request):
return text("GET")
@bp.head("/head")
async def head(request):
return text("HEAD")
@bp.delete("/delete")
async def delete(request):
return text("DELETE")
@bp.options("/options")
async def options(request):
return text("OPTIONS")
@bp.post("/_post/<id>")
async def _post(request, id):
return text("_POST")
@bp.post("/post/<id>", stream=True)
async def post(request, id):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
@bp.put("/_put")
async def _put(request):
return text("_PUT")
@bp.put("/put", stream=True)
async def put(request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
@bp.patch("/_patch")
async def _patch(request):
return text("_PATCH")
@bp.patch("/patch", stream=True)
async def patch(request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
async def post_add_route(request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
bp.add_route(
post_add_route, "/post/add_route", methods=["POST"], stream=True
)
app.blueprint(bp)
request, response = app.test_client.get("/get")
assert response.status == 200
assert response.text == "GET"
request, response = app.test_client.head("/head")
assert response.status == 200
assert response.text == ""
request, response = app.test_client.delete("/delete")
assert response.status == 200
assert response.text == "DELETE"
request, response = app.test_client.options("/options")
assert response.status == 200
assert response.text == "OPTIONS"
request, response = app.test_client.post("/_post/1", data=data)
assert response.status == 200
assert response.text == "_POST"
request, response = app.test_client.post("/post/1", data=data)
assert response.status == 200
assert response.text == data
request, response = app.test_client.put("/_put", data=data)
assert response.status == 200
assert response.text == "_PUT"
request, response = app.test_client.put("/put", data=data)
assert response.status == 200
assert response.text == data
request, response = app.test_client.patch("/_patch", data=data)
assert response.status == 200
assert response.text == "_PATCH"
request, response = app.test_client.patch("/patch", data=data)
assert response.status == 200
assert response.text == data
request, response = app.test_client.post("/post/add_route", data=data)
assert response.status == 200
assert response.text == data
def test_request_stream(app):
"""test for complex application"""
bp = Blueprint("test_blueprint_request_stream")
class SimpleView(HTTPMethodView):
def get(self, request):
return text("OK")
@stream_decorator
async def post(self, request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
@app.post("/stream", stream=True)
async def handler(request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
@app.get("/get")
async def get(request):
return text("OK")
@bp.post("/bp_stream", stream=True)
async def bp_stream(request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
@bp.get("/bp_get")
async def bp_get(request):
return text("OK")
def get_handler(request):
return text("OK")
async def post_handler(request):
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
app.add_route(SimpleView.as_view(), "/method_view")
app.blueprint(bp)
request, response = app.test_client.get("/method_view")
assert response.status == 200
assert response.text == "OK"
request, response = app.test_client.post("/method_view", data=data)
assert response.status == 200
assert response.text == data
request, response = app.test_client.get("/get")
assert response.status == 200
assert response.text == "OK"
request, response = app.test_client.post("/stream", data=data)
assert response.status == 200
assert response.text == data
request, response = app.test_client.get("/bp_get")
assert response.status == 200
assert response.text == "OK"
request, response = app.test_client.post("/bp_stream", data=data)
assert response.status == 200
assert response.text == data
def test_streaming_new_api(app):
@app.post("/non-stream")
async def handler1(request):
assert request.body == b"x"
await request.receive_body() # This should do nothing
assert request.body == b"x"
return text("OK")
@app.post("/1", stream=True)
async def handler2(request):
assert request.stream
assert not request.body
await request.receive_body()
return text(request.body.decode().upper())
@app.post("/2", stream=True)
async def handler(request):
ret = []
async for data in request.stream:
# We should have no b"" or None, just proper chunks
assert data
assert isinstance(data, bytes)
ret.append(data.decode("ASCII"))
return json(ret)
request, response = app.test_client.post("/non-stream", data="x")
assert response.status == 200
request, response = app.test_client.post("/1", data="TEST data")
assert request.body == b"TEST data"
assert response.status == 200
assert response.text == "TEST DATA"
request, response = app.test_client.post("/2", data=data)
assert response.status == 200
res = response.json
assert isinstance(res, list)
assert "".join(res) == data
def test_streaming_echo():
"""2-way streaming chat between server and client."""
app = Sanic(name="Test")
@app.post("/echo", stream=True)
async def handler(request):
res = await request.respond(content_type="text/plain; charset=utf-8")
# Send headers
await res.send(end_stream=False)
# Echo back data (case swapped)
async for data in request.stream:
await res.send(data.swapcase())
# Add EOF marker after successful operation
await res.send(b"-", end_stream=True)
@app.listener("after_server_start")
async def client_task(app, loop):
try:
reader, writer = await asyncio.open_connection("localhost", 8000)
await client(app, reader, writer)
finally:
writer.close()
app.stop()
async def client(app, reader, writer):
# httpx doesn't support 2-way streaming,so do it by hand.
host = "host: localhost:8000\r\n".encode()
writer.write(
b"POST /echo HTTP/1.1\r\n" + host + b"content-length: 2\r\n"
b"content-type: text/plain; charset=utf-8\r\n"
b"\r\n"
)
# Read response
res = b""
while b"\r\n\r\n" not in res:
res += await reader.read(4096)
assert res.startswith(b"HTTP/1.1 200 OK\r\n")
assert res.endswith(b"\r\n\r\n")
buffer = b""
async def read_chunk():
nonlocal buffer
while b"\r\n" not in buffer:
data = await reader.read(4096)
assert data
buffer += data
size, buffer = buffer.split(b"\r\n", 1)
size = int(size, 16)
if size == 0:
return None
while len(buffer) < size + 2:
data = await reader.read(4096)
assert data
buffer += data
assert buffer[size : size + 2] == b"\r\n"
ret, buffer = buffer[:size], buffer[size + 2 :]
return ret
# Chat with server
writer.write(b"a")
res = await read_chunk()
assert res == b"A"
writer.write(b"b")
res = await read_chunk()
assert res == b"B"
res = await read_chunk()
assert res == b"-"
res = await read_chunk()
assert res is None
app.run(access_log=False, single_process=True)