-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtests.py
990 lines (820 loc) · 27.7 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
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
import asyncio
import os
import shutil
import time
import uuid
import pytest
from MicroPie import App, Request, WebSocket, HttpMiddleware, InMemorySessionBackend
from urllib.parse import parse_qs
# Mock MULTIPART_INSTALLED and JINJA_INSTALLED for testing optional dependencies
MULTIPART_INSTALLED = True
JINJA_INSTALLED = True
# Import optional dependencies safely
try:
import aiofiles
from multipart import PushMultipartParser, MultipartSegment
except ImportError:
pass
try:
from jinja2 import Environment
except ImportError:
pass
# Setup fixture for uploads directory
@pytest.fixture(autouse=True)
def setup_uploads():
upload_dir = "uploads"
if os.path.exists(upload_dir):
shutil.rmtree(upload_dir)
yield
if os.path.exists(upload_dir):
shutil.rmtree(upload_dir)
# Setup fixture for templates directory
@pytest.fixture
def setup_templates():
os.makedirs("templates", exist_ok=True)
yield
if os.path.exists("templates"):
shutil.rmtree("templates")
# Test 1: Basic HTTP GET Request
@pytest.mark.asyncio
async def test_basic_get_request():
class TestApp(App):
async def index(self):
return "Hello, World!"
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 2
assert sent_messages[0]["type"] == "http.response.start"
assert sent_messages[0]["status"] == 200
assert sent_messages[1]["type"] == "http.response.body"
assert sent_messages[1]["body"] == b"Hello, World!"
# Test 2: HTTP GET with Path Parameters
@pytest.mark.asyncio
async def test_get_with_path_params():
class TestApp(App):
async def user(self, user_id):
return f"User {user_id}"
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/user/123",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 2
assert sent_messages[0]["status"] == 200
assert sent_messages[1]["body"] == b"User 123"
# Test 3: HTTP GET with Query Parameters
@pytest.mark.asyncio
async def test_get_with_query_params():
class TestApp(App):
async def search(self, query):
return f"Search for {query}"
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/search",
"headers": [],
"query_string": b"query=python",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 2
assert sent_messages[0]["status"] == 200
assert sent_messages[1]["body"] == b"Search for python"
# Test 4: HTTP POST with Form Data
@pytest.mark.asyncio
async def test_post_with_form_data():
class TestApp(App):
async def login(self, username, password):
return "Login successful" if username == "admin" and password == "secret" else ("Invalid credentials", 401)
app = TestApp()
scope = {
"type": "http",
"method": "POST",
"path": "/login",
"headers": [(b"content-type", b"application/x-www-form-urlencoded")],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"username=admin&password=secret", "more_body": False}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 2
assert sent_messages[0]["status"] == 200
assert sent_messages[1]["body"] == b"Login successful"
# Test 5: HTTP POST with JSON Data
@pytest.mark.asyncio
async def test_post_with_json_data():
class TestApp(App):
async def create_user(self, name):
return f"User {name} created"
app = TestApp()
scope = {
"type": "http",
"method": "POST",
"path": "/create_user",
"headers": [(b"content-type", b"application/json")],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b'{"name": "Alice"}', "more_body": False}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 2
assert sent_messages[0]["status"] == 200
assert sent_messages[1]["body"] == b"User Alice created"
# Test 6: HTTP POST with Multipart File Upload
@pytest.mark.asyncio
async def test_post_with_multipart_file_upload():
class TestApp(App):
async def upload(self, file):
return f"File {file['filename']} uploaded to {file['saved_path']}"
app = TestApp()
scope = {
"type": "http",
"method": "POST",
"path": "/upload",
"headers": [(b"content-type", b"multipart/form-data; boundary=boundary")],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
body = (
b"--boundary\r\n"
b'Content-Disposition: form-data; name="file"; filename="test.txt"\r\n'
b"Content-Type: text/plain\r\n"
b"\r\n"
b"Hello, World!\r\n"
b"--boundary--\r\n"
)
async def mock_receive():
return {"type": "http.request", "body": body, "more_body": False}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 2
assert sent_messages[0]["status"] == 200
assert b"File test.txt uploaded to" in sent_messages[1]["body"]
files = os.listdir("uploads")
assert len(files) == 1
with open(os.path.join("uploads", files[0]), "rb") as f:
assert f.read() == b"Hello, World!"
# Test 7: Session Management
@pytest.mark.asyncio
async def test_session_management():
class TestApp(App):
async def login(self, username):
request = self.request
request.session["username"] = username
return "Logged in"
async def profile(self):
request = self.request
return f"Welcome, {request.session.get('username', 'Guest')}"
app = TestApp()
scope_login = {
"type": "http",
"method": "POST",
"path": "/login",
"headers": [],
"query_string": b"username=alice",
}
sent_messages_login = []
async def mock_send_login(message):
sent_messages_login.append(message)
async def mock_receive_login():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope_login, mock_receive_login, mock_send_login)
assert sent_messages_login[0]["status"] == 200
session_id = [h[1].decode().split(";")[0].split("=")[1] for h in sent_messages_login[0]["headers"] if h[0] == b"Set-Cookie"][0]
scope_profile = {
"type": "http",
"method": "GET",
"path": "/profile",
"headers": [(b"cookie", f"session_id={session_id}".encode())],
"query_string": b"",
}
sent_messages_profile = []
async def mock_send_profile(message):
sent_messages_profile.append(message)
async def mock_receive_profile():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope_profile, mock_receive_profile, mock_send_profile)
assert sent_messages_profile[0]["status"] == 200
assert sent_messages_profile[1]["body"] == b"Welcome, alice"
# Test 8: WebSocket Connection
@pytest.mark.asyncio
async def test_websocket_connection():
class TestApp(App):
async def ws_echo(self, websocket, path_params):
await websocket.accept()
message = await websocket.receive_text()
await websocket.send_text(f"Echo: {message}")
await websocket.close()
app = TestApp()
scope = {
"type": "websocket",
"path": "/echo",
"headers": [],
"query_string": b"",
}
sent_messages = []
received_messages = [
{"type": "websocket.connect"},
{"type": "websocket.receive", "text": "Hello"},
{"type": "websocket.disconnect", "code": 1000},
]
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return received_messages.pop(0)
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 3
assert sent_messages[0]["type"] == "websocket.accept"
assert sent_messages[1]["type"] == "websocket.send"
assert sent_messages[1]["text"] == "Echo: Hello"
assert sent_messages[2]["type"] == "websocket.close"
assert sent_messages[2]["code"] == 1000
# Test 9: HTTP Middleware
@pytest.mark.asyncio
async def test_http_middleware():
class CustomHeaderMiddleware(HttpMiddleware):
async def before_request(self, request):
pass
async def after_request(self, request, status_code, response_body, extra_headers):
extra_headers.append(("X-Custom-Header", "Test"))
return {"headers": extra_headers}
class TestApp(App):
async def index(self):
return "Hello"
app = TestApp()
app.middlewares.append(CustomHeaderMiddleware())
scope = {
"type": "http",
"method": "GET",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 2
assert any(h[0] == b"X-Custom-Header" and h[1] == b"Test" for h in sent_messages[0]["headers"])
# Test 10: Template Rendering
@pytest.mark.asyncio
async def test_template_rendering(setup_templates):
with open("templates/hello.html", "w") as f:
f.write("Hello, {{ name }}!")
class TestApp(App):
async def index(self):
return await self._render_template("hello.html", name="World")
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 200
assert sent_messages[1]["body"] == b"Hello, World!"
# Test 11: 404 Not Found
@pytest.mark.asyncio
async def test_404_not_found():
class TestApp(App):
pass
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/nonexistent",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 404
assert sent_messages[1]["body"] == b"404 Not Found"
# Test 12: 400 Bad Request (Missing Parameter)
@pytest.mark.asyncio
async def test_400_missing_parameter():
class TestApp(App):
async def index(self, required_param):
return "Should not reach here"
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 400
assert b"Missing required parameter" in sent_messages[1]["body"]
# Test 13: 500 Internal Server Error
@pytest.mark.asyncio
async def test_500_internal_server_error():
class TestApp(App):
async def index(self):
raise Exception("Test error")
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 500
assert sent_messages[1]["body"] == b"500 Internal Server Error"
# Test 14: WebSocket Error Handling
@pytest.mark.asyncio
async def test_websocket_error_handling():
class TestApp(App):
async def ws_index(self, websocket, path_params):
raise Exception("Test error")
app = TestApp()
scope = {
"type": "websocket",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "websocket.connect"}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 1
assert sent_messages[0]["type"] == "websocket.close"
assert sent_messages[0]["code"] == 1011
# Test 15: Parse Cookies
def test_parse_cookies():
app = App()
cookies = app._parse_cookies("session_id=abc123; user=alice")
assert cookies == {"session_id": "abc123", "user": "alice"}
# Test 16: Redirect
@pytest.mark.asyncio
async def test_redirect():
class TestApp(App):
async def index(self):
return self._redirect("/new_location")
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 302
assert any(h[0] == b"Location" and h[1] == b"/new_location" for h in sent_messages[0]["headers"])
# Test 17: In-Memory Session Backend
@pytest.mark.asyncio
async def test_in_memory_session_backend():
backend = InMemorySessionBackend()
session_id = "test_session"
data = {"key": "value"}
await backend.save(session_id, data, 3600)
loaded_data = await backend.load(session_id)
assert loaded_data == data
# Simulate session timeout
backend.last_access[session_id] = time.time() - 8 * 3600 - 1
assert await backend.load(session_id) == {}
# Test 18: Synchronous Handler
@pytest.mark.asyncio
async def test_synchronous_handler():
class TestApp(App):
def index(self):
return "Sync Hello"
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 200
assert sent_messages[1]["body"] == b"Sync Hello"
# Test 19: Asynchronous Streaming Response
@pytest.mark.asyncio
async def test_async_streaming_response():
class TestApp(App):
async def stream(self):
async def generate():
yield "Chunk 1"
await asyncio.sleep(0.1)
yield "Chunk 2"
return generate()
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/stream",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 4
assert sent_messages[1]["body"] == b"Chunk 1"
assert sent_messages[2]["body"] == b"Chunk 2"
assert sent_messages[3]["body"] == b""
# Test 20: Synchronous Generator Response
@pytest.mark.asyncio
async def test_sync_generator_response():
class TestApp(App):
def stream(self):
def generate():
yield "Chunk 1"
yield "Chunk 2"
return generate()
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/stream",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 4
assert sent_messages[1]["body"] == b"Chunk 1"
assert sent_messages[2]["body"] == b"Chunk 2"
# Test 21: JSON Response
@pytest.mark.asyncio
async def test_json_response():
class TestApp(App):
async def data(self):
return {"key": "value"}
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/data",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert any(h[0] == b"Content-Type" and h[1] == b"application/json" for h in sent_messages[0]["headers"])
assert sent_messages[1]["body"] == b'{"key": "value"}'
# Test 22: Protected Path (Starting with '_')
@pytest.mark.asyncio
async def test_protected_path():
class TestApp(App):
async def _hidden(self):
return "Should not reach here"
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/_hidden",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 404
# Test 23: WebSocket Protected Path
@pytest.mark.asyncio
async def test_websocket_protected_path():
class TestApp(App):
async def _ws_hidden(self, websocket, path_params):
pass
app = TestApp()
scope = {
"type": "websocket",
"path": "/_hidden",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "websocket.connect"}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["type"] == "websocket.close"
assert sent_messages[0]["code"] == 1008
# Test 24: Invalid JSON
@pytest.mark.asyncio
async def test_invalid_json():
class TestApp(App):
async def index(self):
pass
app = TestApp()
scope = {
"type": "http",
"method": "POST",
"path": "/index",
"headers": [(b"content-type", b"application/json")],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"{invalid}", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 400
assert sent_messages[1]["body"] == b"400 Bad Request: Bad JSON"
# Test 25: Header Injection Prevention
@pytest.mark.asyncio
async def test_header_injection_prevention():
class TestApp(App):
async def index(self):
return "Hello", 200, [("X-Test", "Value\nInjection")]
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert not any(b"\n" in h[1] for h in sent_messages[0]["headers"])
# Test 26: Missing Jinja2 Dependency
@pytest.mark.asyncio
async def test_missing_jinja2(monkeypatch):
monkeypatch.setattr("MicroPie.JINJA_INSTALLED", False)
class TestApp(App):
async def index(self):
return await self._render_template("hello.html", name="World")
app = TestApp()
scope = {
"type": "http",
"method": "GET",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 500
assert sent_messages[1]["body"] == b"500 Internal Server Error"
# Test 27: Missing Multipart Dependency
@pytest.mark.asyncio
async def test_missing_multipart(monkeypatch):
monkeypatch.setattr("MicroPie.MULTIPART_INSTALLED", False)
class TestApp(App):
async def upload(self, file):
return "Should not reach here"
app = TestApp()
scope = {
"type": "http",
"method": "POST",
"path": "/upload",
"headers": [(b"content-type", b"multipart/form-data; boundary=boundary")],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 500
assert sent_messages[1]["body"] == b"500 Internal Server Error"
# Test 28: WebSocket Send JSON
@pytest.mark.asyncio
async def test_websocket_send_json():
class TestApp(App):
async def ws_json(self, websocket, path_params):
await websocket.accept()
await websocket.send_json({"message": "Hello"})
await websocket.close()
app = TestApp()
scope = {
"type": "websocket",
"path": "/json",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "websocket.connect"}
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 3
assert sent_messages[0]["type"] == "websocket.accept"
assert sent_messages[1]["type"] == "websocket.send"
assert sent_messages[1]["text"] == '{"message": "Hello"}'
assert sent_messages[2]["type"] == "websocket.close"
# Test 29: WebSocket Receive JSON
@pytest.mark.asyncio
async def test_websocket_receive_json():
class TestApp(App):
async def ws_json(self, websocket, path_params):
await websocket.accept()
data = await websocket.receive_json()
await websocket.send_text(f"Received: {data['message']}")
await websocket.close()
app = TestApp()
scope = {
"type": "websocket",
"path": "/json",
"headers": [],
"query_string": b"",
}
sent_messages = []
received_messages = [
{"type": "websocket.connect"},
{"type": "websocket.receive", "text": '{"message": "Hello"}'},
{"type": "websocket.disconnect", "code": 1000},
]
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return received_messages.pop(0)
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 3
assert sent_messages[0]["type"] == "websocket.accept"
assert sent_messages[1]["type"] == "websocket.send"
assert sent_messages[1]["text"] == "Received: Hello"
assert sent_messages[2]["type"] == "websocket.close"
# Test 30: WebSocket Disconnect
@pytest.mark.asyncio
async def test_websocket_disconnect():
class TestApp(App):
async def ws_disconnect(self, websocket, path_params):
await websocket.accept()
await websocket.receive_text() # Should raise ConnectionError
await websocket.close()
app = TestApp()
scope = {
"type": "websocket",
"path": "/disconnect",
"headers": [],
"query_string": b"",
}
sent_messages = []
received_messages = [
{"type": "websocket.connect"},
{"type": "websocket.disconnect", "code": 1000},
]
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return received_messages.pop(0)
await app(scope, mock_receive, mock_send)
assert len(sent_messages) == 2
assert sent_messages[0]["type"] == "websocket.accept"
assert sent_messages[1]["type"] == "websocket.close"
# Test 31: Middleware Before Request Early Exit
@pytest.mark.asyncio
async def test_middleware_before_request_early_exit():
class EarlyExitMiddleware(HttpMiddleware):
async def before_request(self, request):
return {"status_code": 403, "body": "Forbidden"}
async def after_request(self, request, status_code, response_body, extra_headers):
pass
class TestApp(App):
async def index(self):
return "Should not reach here"
app = TestApp()
app.middlewares.append(EarlyExitMiddleware())
scope = {
"type": "http",
"method": "GET",
"path": "/",
"headers": [],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
async def mock_receive():
return {"type": "http.request", "body": b"", "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 403
assert sent_messages[1]["body"] == b"Forbidden"
# Test 32: Empty Cookie Header
def test_empty_cookie_header():
app = App()
cookies = app._parse_cookies("")
assert cookies == {}
# Test 33: Multipart Form Data Without File
@pytest.mark.asyncio
async def test_multipart_form_data_without_file():
class TestApp(App):
async def form(self, field):
return f"Field: {field[0]}"
app = TestApp()
scope = {
"type": "http",
"method": "POST",
"path": "/form",
"headers": [(b"content-type", b"multipart/form-data; boundary=boundary")],
"query_string": b"",
}
sent_messages = []
async def mock_send(message):
sent_messages.append(message)
body = (
b"--boundary\r\n"
b'Content-Disposition: form-data; name="field"\r\n'
b"\r\n"
b"test_value\r\n"
b"--boundary--\r\n"
)
async def mock_receive():
return {"type": "http.request", "body": body, "more_body": False}
await app(scope, mock_receive, mock_send)
assert sent_messages[0]["status"] == 200
assert sent_messages[1]["body"] == b"Field: test_value"