forked from encode/uvicorn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_http.py
793 lines (621 loc) · 27.5 KB
/
test_http.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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
import asyncio
import contextlib
import logging
import os
import sys
import httpx
import pytest
from tests.response import Response
from tests.utils import run_server
from uvicorn.config import Config
from uvicorn.main import ServerState
from uvicorn.protocols.http.h11_impl import H11Protocol
try:
from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol
except ImportError: # pragma: nocover
HttpToolsProtocol = None
HTTP_PROTOCOLS = [p for p in [H11Protocol, HttpToolsProtocol] if p is not None]
SIMPLE_GET_REQUEST = b"\r\n".join([b"GET / HTTP/1.1", b"Host: example.org", b"", b""])
SIMPLE_HEAD_REQUEST = b"\r\n".join([b"HEAD / HTTP/1.1", b"Host: example.org", b"", b""])
SIMPLE_POST_REQUEST = b"\r\n".join(
[
b"POST / HTTP/1.1",
b"Host: example.org",
b"Content-Type: application/json",
b"Content-Length: 18",
b"",
b'{"hello": "world"}',
]
)
LARGE_POST_REQUEST = b"\r\n".join(
[
b"POST / HTTP/1.1",
b"Host: example.org",
b"Content-Type: text/plain",
b"Content-Length: 100000",
b"",
b"x" * 100000,
]
)
START_POST_REQUEST = b"\r\n".join(
[
b"POST / HTTP/1.1",
b"Host: example.org",
b"Content-Type: application/json",
b"Content-Length: 18",
b"",
b"",
]
)
FINISH_POST_REQUEST = b'{"hello": "world"}'
HTTP10_GET_REQUEST = b"\r\n".join([b"GET / HTTP/1.0", b"Host: example.org", b"", b""])
GET_REQUEST_WITH_RAW_PATH = b"\r\n".join(
[b"GET /one%2Ftwo HTTP/1.1", b"Host: example.org", b"", b""]
)
UPGRADE_REQUEST = b"\r\n".join(
[
b"GET / HTTP/1.1",
b"Host: example.org",
b"Connection: upgrade",
b"Upgrade: websocket",
b"Sec-WebSocket-Version: 11",
b"",
b"",
]
)
INVALID_REQUEST_TEMPLATE = b"\r\n".join(
[
b"%s",
b"Host: example.org",
b"",
b"",
]
)
class MockTransport:
def __init__(self, sockname=None, peername=None, sslcontext=False):
self.sockname = ("127.0.0.1", 8000) if sockname is None else sockname
self.peername = ("127.0.0.1", 8001) if peername is None else peername
self.sslcontext = sslcontext
self.closed = False
self.buffer = b""
self.read_paused = False
def get_extra_info(self, key):
return {
"sockname": self.sockname,
"peername": self.peername,
"sslcontext": self.sslcontext,
}.get(key)
def write(self, data):
assert not self.closed
self.buffer += data
def close(self):
assert not self.closed
self.closed = True
def pause_reading(self):
self.read_paused = True
def resume_reading(self):
self.read_paused = False
def is_closing(self):
return self.closed
def clear_buffer(self):
self.buffer = b""
def set_protocol(self, protocol):
pass
def set_write_buffer_limits(self, high=None, low=None):
pass
class MockLoop(asyncio.AbstractEventLoop):
def __init__(self, event_loop):
self.tasks = []
self.later = []
self.loop = event_loop
def is_running(self):
return True # pragma: no cover
def create_task(self, coroutine):
self.tasks.insert(0, coroutine)
return MockTask()
def call_later(self, delay, callback, *args):
self.later.insert(0, (delay, callback, args))
def run_one(self):
coroutine = self.tasks.pop()
self.run_until_complete(coroutine)
def run_until_complete(self, coroutine):
asyncio._set_running_loop(None)
try:
return self.loop.run_until_complete(coroutine)
finally:
asyncio._set_running_loop(self)
def close(self):
self.loop.close()
def run_later(self, with_delay):
later = []
for delay, callback, args in self.later:
if with_delay >= delay:
callback(*args)
else:
later.append((delay, callback, args))
self.later = later
class MockTask:
def add_done_callback(self, callback):
pass
@contextlib.contextmanager
def get_connected_protocol(app, protocol_cls, event_loop, **kwargs):
loop = MockLoop(event_loop)
asyncio._set_running_loop(loop)
transport = MockTransport()
config = Config(app=app, **kwargs)
server_state = ServerState()
protocol = protocol_cls(config=config, server_state=server_state, _loop=loop)
protocol.connection_made(transport)
try:
yield protocol
finally:
protocol.loop.close()
asyncio._set_running_loop(None)
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_get_request(protocol_cls, event_loop):
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert b"Hello, world" in protocol.transport.buffer
@pytest.mark.parametrize("path", ["/", "/?foo", "/?foo=bar", "/?foo=bar&baz=1"])
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_request_logging(path, protocol_cls, caplog, event_loop):
get_request_with_query_string = b"\r\n".join(
["GET {} HTTP/1.1".format(path).encode("ascii"), b"Host: example.org", b"", b""]
)
caplog.set_level(logging.INFO, logger="uvicorn.access")
logging.getLogger("uvicorn.access").propagate = True
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(
app, protocol_cls, event_loop, log_config=None
) as protocol:
protocol.data_received(get_request_with_query_string)
protocol.loop.run_one()
assert '"GET {} HTTP/1.1" 200'.format(path) in caplog.records[0].message
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_head_request(protocol_cls, event_loop):
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_HEAD_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert b"Hello, world" not in protocol.transport.buffer
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_post_request(protocol_cls, event_loop):
async def app(scope, receive, send):
body = b""
more_body = True
while more_body:
message = await receive()
body += message.get("body", b"")
more_body = message.get("more_body", False)
response = Response(b"Body: " + body, media_type="text/plain")
await response(scope, receive, send)
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_POST_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert b'Body: {"hello": "world"}' in protocol.transport.buffer
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_keepalive(protocol_cls, event_loop):
app = Response(b"", status_code=204)
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 204 No Content" in protocol.transport.buffer
assert not protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_keepalive_timeout(protocol_cls, event_loop):
app = Response(b"", status_code=204)
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 204 No Content" in protocol.transport.buffer
assert not protocol.transport.is_closing()
protocol.loop.run_later(with_delay=1)
assert not protocol.transport.is_closing()
protocol.loop.run_later(with_delay=5)
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_close(protocol_cls, event_loop):
app = Response(b"", status_code=204, headers={"connection": "close"})
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 204 No Content" in protocol.transport.buffer
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_chunked_encoding(protocol_cls, event_loop):
app = Response(
b"Hello, world!", status_code=200, headers={"transfer-encoding": "chunked"}
)
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert b"0\r\n\r\n" in protocol.transport.buffer
assert not protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_chunked_encoding_empty_body(protocol_cls, event_loop):
app = Response(
b"Hello, world!", status_code=200, headers={"transfer-encoding": "chunked"}
)
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert protocol.transport.buffer.count(b"0\r\n\r\n") == 1
assert not protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_chunked_encoding_head_request(protocol_cls, event_loop):
app = Response(
b"Hello, world!", status_code=200, headers={"transfer-encoding": "chunked"}
)
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_HEAD_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert not protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_pipelined_requests(protocol_cls, event_loop):
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert b"Hello, world" in protocol.transport.buffer
protocol.transport.clear_buffer()
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert b"Hello, world" in protocol.transport.buffer
protocol.transport.clear_buffer()
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert b"Hello, world" in protocol.transport.buffer
protocol.transport.clear_buffer()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_undersized_request(protocol_cls, event_loop):
app = Response(b"xxx", headers={"content-length": "10"})
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_oversized_request(protocol_cls, event_loop):
app = Response(b"xxx" * 20, headers={"content-length": "10"})
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_large_post_request(protocol_cls, event_loop):
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(LARGE_POST_REQUEST)
assert protocol.transport.read_paused
protocol.loop.run_one()
assert not protocol.transport.read_paused
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_invalid_http(protocol_cls, event_loop):
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(b"x" * 100000)
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_app_exception(protocol_cls, event_loop):
async def app(scope, receive, send):
raise Exception()
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 500 Internal Server Error" in protocol.transport.buffer
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_exception_during_response(protocol_cls, event_loop):
async def app(scope, receive, send):
await send({"type": "http.response.start", "status": 200})
await send({"type": "http.response.body", "body": b"1", "more_body": True})
raise Exception()
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 500 Internal Server Error" not in protocol.transport.buffer
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_no_response_returned(protocol_cls, event_loop):
async def app(scope, receive, send):
pass
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 500 Internal Server Error" in protocol.transport.buffer
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_partial_response_returned(protocol_cls, event_loop):
async def app(scope, receive, send):
await send({"type": "http.response.start", "status": 200})
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 500 Internal Server Error" not in protocol.transport.buffer
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_duplicate_start_message(protocol_cls, event_loop):
async def app(scope, receive, send):
await send({"type": "http.response.start", "status": 200})
await send({"type": "http.response.start", "status": 200})
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 500 Internal Server Error" not in protocol.transport.buffer
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_missing_start_message(protocol_cls, event_loop):
async def app(scope, receive, send):
await send({"type": "http.response.body", "body": b""})
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 500 Internal Server Error" in protocol.transport.buffer
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_message_after_body_complete(protocol_cls, event_loop):
async def app(scope, receive, send):
await send({"type": "http.response.start", "status": 200})
await send({"type": "http.response.body", "body": b""})
await send({"type": "http.response.body", "body": b""})
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_value_returned(protocol_cls, event_loop):
async def app(scope, receive, send):
await send({"type": "http.response.start", "status": 200})
await send({"type": "http.response.body", "body": b""})
return 123
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_early_disconnect(protocol_cls, event_loop):
got_disconnect_event = False
async def app(scope, receive, send):
nonlocal got_disconnect_event
while True:
message = await receive()
if message["type"] == "http.disconnect":
break
got_disconnect_event = True
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_POST_REQUEST)
protocol.eof_received()
protocol.connection_lost(None)
protocol.loop.run_one()
assert got_disconnect_event
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_early_response(protocol_cls, event_loop):
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(START_POST_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
protocol.data_received(FINISH_POST_REQUEST)
assert not protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_read_after_response(protocol_cls, event_loop):
message_after_response = None
async def app(scope, receive, send):
nonlocal message_after_response
response = Response("Hello, world", media_type="text/plain")
await response(scope, receive, send)
message_after_response = await receive()
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_POST_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert message_after_response == {"type": "http.disconnect"}
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_http10_request(protocol_cls, event_loop):
async def app(scope, receive, send):
content = "Version: %s" % scope["http_version"]
response = Response(content, media_type="text/plain")
await response(scope, receive, send)
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(HTTP10_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert b"Version: 1.0" in protocol.transport.buffer
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_root_path(protocol_cls, event_loop):
async def app(scope, receive, send):
path = scope.get("root_path", "") + scope["path"]
response = Response("Path: " + path, media_type="text/plain")
await response(scope, receive, send)
with get_connected_protocol(
app, protocol_cls, event_loop, root_path="/app"
) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert b"Path: /app/" in protocol.transport.buffer
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_raw_path(protocol_cls, event_loop):
async def app(scope, receive, send):
path = scope["path"]
raw_path = scope.get("raw_path", None)
assert "/one/two" == path
assert b"/one%2Ftwo" == raw_path
response = Response("Done", media_type="text/plain")
await response(scope, receive, send)
with get_connected_protocol(
app, protocol_cls, event_loop, root_path="/app"
) as protocol:
protocol.data_received(GET_REQUEST_WITH_RAW_PATH)
protocol.loop.run_one()
assert b"Done" in protocol.transport.buffer
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_max_concurrency(protocol_cls, event_loop):
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(
app, protocol_cls, event_loop, limit_concurrency=1
) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 503 Service Unavailable" in protocol.transport.buffer
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_shutdown_during_request(protocol_cls, event_loop):
app = Response(b"", status_code=204)
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.shutdown()
protocol.loop.run_one()
assert b"HTTP/1.1 204 No Content" in protocol.transport.buffer
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_shutdown_during_idle(protocol_cls, event_loop):
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.shutdown()
assert protocol.transport.buffer == b""
assert protocol.transport.is_closing()
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_100_continue_sent_when_body_consumed(protocol_cls, event_loop):
async def app(scope, receive, send):
body = b""
more_body = True
while more_body:
message = await receive()
body += message.get("body", b"")
more_body = message.get("more_body", False)
response = Response(b"Body: " + body, media_type="text/plain")
await response(scope, receive, send)
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
EXPECT_100_REQUEST = b"\r\n".join(
[
b"POST / HTTP/1.1",
b"Host: example.org",
b"Expect: 100-continue",
b"Content-Type: application/json",
b"Content-Length: 18",
b"",
b'{"hello": "world"}',
]
)
protocol.data_received(EXPECT_100_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 100 Continue" in protocol.transport.buffer
assert b"HTTP/1.1 200 OK" in protocol.transport.buffer
assert b'Body: {"hello": "world"}' in protocol.transport.buffer
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_100_continue_not_sent_when_body_not_consumed(protocol_cls, event_loop):
app = Response(b"", status_code=204)
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
EXPECT_100_REQUEST = b"\r\n".join(
[
b"POST / HTTP/1.1",
b"Host: example.org",
b"Expect: 100-continue",
b"Content-Type: application/json",
b"Content-Length: 18",
b"",
b'{"hello": "world"}',
]
)
protocol.data_received(EXPECT_100_REQUEST)
protocol.loop.run_one()
assert b"HTTP/1.1 100 Continue" not in protocol.transport.buffer
assert b"HTTP/1.1 204 No Content" in protocol.transport.buffer
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_unsupported_upgrade_request(protocol_cls, event_loop):
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(app, protocol_cls, event_loop, ws="none") as protocol:
protocol.data_received(UPGRADE_REQUEST)
assert b"HTTP/1.1 400 Bad Request" in protocol.transport.buffer
assert b"Unsupported upgrade request." in protocol.transport.buffer
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_supported_upgrade_request(protocol_cls, event_loop):
app = Response("Hello, world", media_type="text/plain")
with get_connected_protocol(
app, protocol_cls, event_loop, ws="wsproto"
) as protocol:
protocol.data_received(UPGRADE_REQUEST)
assert b"HTTP/1.1 426 " in protocol.transport.buffer
async def asgi3app(scope, receive, send):
pass
def asgi2app(scope):
async def asgi(receive, send):
pass
return asgi
asgi_scope_data = [
(asgi3app, {"version": "3.0", "spec_version": "2.3"}),
(asgi2app, {"version": "2.0", "spec_version": "2.3"}),
]
@pytest.mark.parametrize("asgi2or3_app, expected_scopes", asgi_scope_data)
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_scopes(asgi2or3_app, expected_scopes, protocol_cls, event_loop):
with get_connected_protocol(asgi2or3_app, protocol_cls, event_loop) as protocol:
protocol.data_received(SIMPLE_GET_REQUEST)
protocol.loop.run_one()
assert expected_scopes == protocol.scope.get("asgi")
@pytest.mark.parametrize(
"request_line",
[
pytest.param(b"G?T / HTTP/1.1", id="invalid-method"),
pytest.param(b"GET /?x=y z HTTP/1.1", id="invalid-path"),
pytest.param(b"GET / HTTP1.1", id="invalid-http-version"),
],
)
@pytest.mark.parametrize("protocol_cls", HTTP_PROTOCOLS)
def test_invalid_http_request(request_line, protocol_cls, caplog, event_loop):
app = Response("Hello, world", media_type="text/plain")
request = INVALID_REQUEST_TEMPLATE % request_line
caplog.set_level(logging.INFO, logger="uvicorn.error")
logging.getLogger("uvicorn.error").propagate = True
with get_connected_protocol(app, protocol_cls, event_loop) as protocol:
protocol.data_received(request)
assert not protocol.transport.buffer
assert "Invalid HTTP request received." in caplog.messages
@pytest.mark.skipif(
sys.version_info[:2] < (3, 7),
not hasattr(os, "sendfile"),
reason="Sendfile only available in python3.7+",
)
@pytest.mark.parametrize("http", ["h11", "httptools"])
@pytest.mark.parametrize("loop", ["asyncio"])
@pytest.mark.asyncio
async def test_sendfile(http, loop):
async def app(scope, receive, send):
with open("./README.md", "rb") as file:
content_length = len(file.read())
file.seek(0, 0)
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [
(b"Content-Length", str(content_length).encode("ascii")),
(b"Content-Type", b"text/plain; charset=utf8"),
],
}
)
await send(
{
"type": "http.response.zerocopysend",
"file": file.fileno(),
}
)
config = Config(app=app, http=http, loop=loop, limit_max_requests=1)
async with run_server(config):
with open("./README.md", "rb") as file:
file_content = file.read()
async with httpx.AsyncClient() as client:
response = await client.get("http://127.0.0.1:8000")
assert response.content == file_content