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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
"""Contains tests for networking.py and app.py"""

import functools
import json
import os
import pickle
import tempfile
import time
from contextlib import asynccontextmanager, closing
from pathlib import Path
from threading import Thread
from unittest.mock import patch

import gradio_client as grc
import httpx
import numpy as np
import pandas as pd
import pytest
import requests
import starlette.routing
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from gradio_client import media_data

import gradio as gr
from gradio import (
    Blocks,
    Button,
    Interface,
    Number,
    Textbox,
    close_all,
    routes,
    wasm_utils,
)
from gradio.route_utils import (
    API_PREFIX,
    FnIndexInferError,
    compare_passwords_securely,
    get_root_url,
    starts_with_protocol,
)


@pytest.fixture()
def test_client():
    io = Interface(lambda x: x + x, "text", "text")
    app, _, _ = io.launch(prevent_thread_lock=True)
    test_client = TestClient(app)
    yield test_client
    io.close()
    close_all()


class TestRoutes:
    def test_get_main_route(self, test_client):
        response = test_client.get("/")
        assert response.status_code == 200

    def test_static_files_served_safely(self, test_client):
        # Make sure things outside the static folder are not accessible
        response = test_client.get(r"/static/..%2findex.html")
        assert response.status_code == 403
        response = test_client.get(r"/static/..%2f..%2fapi_docs.html")
        assert response.status_code == 403

    def test_get_config_route(self, test_client):
        response = test_client.get("/config/")
        assert response.status_code == 200

    def test_favicon_route(self, test_client):
        response = test_client.get("/favicon.ico")
        assert response.status_code == 200

    def test_upload_path(self, test_client):
        with open("test/test_files/alphabet.txt", "rb") as f:
            response = test_client.post(f"{API_PREFIX}/upload", files={"files": f})
        assert response.status_code == 200
        file = response.json()[0]
        assert "alphabet" in file
        assert file.endswith(".txt")
        with open(file, "rb") as saved_file:
            assert saved_file.read() == b"abcdefghijklmnopqrstuvwxyz"

    def test_custom_upload_path(self, gradio_temp_dir):
        io = Interface(lambda x: x + x, "text", "text")
        app, _, _ = io.launch(prevent_thread_lock=True)
        test_client = TestClient(app)
        with open("test/test_files/alphabet.txt", "rb") as f:
            response = test_client.post(f"{API_PREFIX}/upload", files={"files": f})
        assert response.status_code == 200
        file = response.json()[0]
        assert "alphabet" in file
        assert file.startswith(str(gradio_temp_dir))
        assert file.endswith(".txt")
        with open(file, "rb") as saved_file:
            assert saved_file.read() == b"abcdefghijklmnopqrstuvwxyz"

    def test_predict_route(self, test_client):
        response = test_client.post(
            f"{API_PREFIX}/api/predict/", json={"data": ["test"], "fn_index": 0}
        )
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["testtest"]

    def test_named_predict_route(self):
        with Blocks() as demo:
            i = Textbox()
            o = Textbox()
            i.change(lambda x: f"{x}1", i, o, api_name="p")
            i.change(lambda x: f"{x}2", i, o, api_name="q")

        app, _, _ = demo.launch(prevent_thread_lock=True)
        client = TestClient(app)
        response = client.post(f"{API_PREFIX}/api/p/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test1"]

        response = client.post(f"{API_PREFIX}/api/q/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test2"]

    def test_same_named_predict_route(self):
        with Blocks() as demo:
            i = Textbox()
            o = Textbox()
            i.change(lambda x: f"{x}0", i, o, api_name="p")
            i.change(lambda x: f"{x}1", i, o, api_name="p")

        app, _, _ = demo.launch(prevent_thread_lock=True)
        client = TestClient(app)
        response = client.post(f"{API_PREFIX}/api/p/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test0"]

        response = client.post(f"{API_PREFIX}/api/p_1/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test1"]

    def test_multiple_renamed(self):
        with Blocks() as demo:
            i = Textbox()
            o = Textbox()
            i.change(lambda x: f"{x}0", i, o, api_name="p")
            i.change(lambda x: f"{x}1", i, o, api_name="p")
            i.change(lambda x: f"{x}2", i, o, api_name="p_1")

        app, _, _ = demo.launch(prevent_thread_lock=True)
        client = TestClient(app)
        response = client.post(f"{API_PREFIX}/api/p/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test0"]

        response = client.post(f"{API_PREFIX}/api/p_1/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test1"]

        response = client.post(f"{API_PREFIX}/api/p_1_1/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test2"]

    def test_predict_route_without_fn_index(self, test_client):
        response = test_client.post(
            f"{API_PREFIX}/api/predict/", json={"data": ["test"]}
        )
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["testtest"]

    def test_predict_route_batching(self):
        def batch_fn(x):
            results = []
            for word in x:
                results.append(f"Hello {word}")
            return (results,)

        with gr.Blocks() as demo:
            text = gr.Textbox()
            btn = gr.Button()
            btn.click(batch_fn, inputs=text, outputs=text, batch=True, api_name="pred")

        demo.queue(api_open=True)
        app, _, _ = demo.launch(prevent_thread_lock=True)
        client = TestClient(app)
        response = client.post(f"{API_PREFIX}/api/pred/", json={"data": ["test"]})
        output = dict(response.json())
        assert output["data"] == ["Hello test"]

        app, _, _ = demo.launch(prevent_thread_lock=True)
        client = TestClient(app)
        response = client.post(
            f"{API_PREFIX}/api/pred/",
            json={"data": [["test", "test2"]], "batched": True},
        )
        output = dict(response.json())
        assert output["data"] == [["Hello test", "Hello test2"]]

    def test_state(self):
        def predict(input, history):
            if history is None:
                history = ""
            history += input
            return history, history

        io = Interface(predict, ["textbox", "state"], ["textbox", "state"])
        app, _, _ = io.launch(prevent_thread_lock=True)
        client = TestClient(app)
        response = client.post(
            f"{API_PREFIX}/api/predict/",
            json={"data": ["test", None], "fn_index": 0, "session_hash": "_"},
        )
        output = dict(response.json())
        assert output["data"] == ["test", None]
        response = client.post(
            f"{API_PREFIX}/api/predict/",
            json={"data": ["test", None], "fn_index": 0, "session_hash": "_"},
        )
        output = dict(response.json())
        assert output["data"] == ["testtest", None]

    def test_get_allowed_paths(self):
        allowed_file = tempfile.NamedTemporaryFile(mode="w", delete=False)
        allowed_file.write(media_data.BASE64_IMAGE)
        allowed_file.flush()

        io = gr.Interface(lambda s: s.name, gr.File(), gr.File())
        app, _, _ = io.launch(prevent_thread_lock=True)
        client = TestClient(app)
        file_response = client.get(f"{API_PREFIX}/file={allowed_file.name}")
        assert file_response.status_code == 403
        io.close()

        io = gr.Interface(lambda s: s.name, gr.File(), gr.File())
        app, _, _ = io.launch(
            prevent_thread_lock=True,
            allowed_paths=[os.path.dirname(allowed_file.name)],
        )
        client = TestClient(app)
        file_response = client.get(f"{API_PREFIX}/file={allowed_file.name}")
        assert file_response.status_code == 200
        assert len(file_response.text) == len(media_data.BASE64_IMAGE)
        io.close()

        io = gr.Interface(lambda s: s.name, gr.File(), gr.File())
        app, _, _ = io.launch(
            prevent_thread_lock=True,
            allowed_paths=[os.path.abspath(allowed_file.name)],
        )
        client = TestClient(app)
        file_response = client.get(f"{API_PREFIX}/file={allowed_file.name}")
        assert file_response.status_code == 200
        assert len(file_response.text) == len(media_data.BASE64_IMAGE)
        io.close()

    def test_response_attachment_format(self):
        image_file = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".png")
        image_file.write(media_data.BASE64_IMAGE)
        image_file.flush()

        html_file = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".html")
        html_file.write("<html>Hello, world!</html>")
        html_file.flush()

        io = gr.Interface(lambda s: s.name, gr.File(), gr.File())
        app, _, _ = io.launch(
            prevent_thread_lock=True,
            allowed_paths=[
                image_file.name,
                html_file.name,
            ],
        )

        html_file2 = tempfile.NamedTemporaryFile(
            mode="w", delete=False, suffix=".html", dir=app.uploaded_file_dir
        )
        html_file2.write("<html>Hello, world!</html>")
        html_file2.flush()
        html_file2_name = str(Path(app.uploaded_file_dir) / html_file2.name)

        client = TestClient(app)

        file_response = client.get(f"{API_PREFIX}/file={image_file.name}")
        assert file_response.headers["Content-Type"] == "image/png"
        assert "inline" in file_response.headers["Content-Disposition"]

        file_response = client.get(f"{API_PREFIX}/file={html_file.name}")
        assert file_response.headers["Content-Type"] == "text/html; charset=utf-8"
        assert "inline" in file_response.headers["Content-Disposition"]

        file_response = client.get(f"{API_PREFIX}/file={html_file2_name}")
        assert file_response.headers["Content-Type"] == "application/octet-stream"
        assert "attachment" in file_response.headers["Content-Disposition"]

    def test_allowed_and_blocked_paths(self):
        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_file:
            io = gr.Interface(lambda s: s.name, gr.File(), gr.File())
            app, _, _ = io.launch(
                prevent_thread_lock=True,
                allowed_paths=[os.path.dirname(tmp_file.name)],
            )
            client = TestClient(app)
            file_response = client.get(f"{API_PREFIX}/file={tmp_file.name}")
            assert file_response.status_code == 200
        io.close()
        os.remove(tmp_file.name)

        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_file:
            io = gr.Interface(lambda s: s.name, gr.File(), gr.File())
            app, _, _ = io.launch(
                prevent_thread_lock=True,
                allowed_paths=[os.path.dirname(tmp_file.name)],
                blocked_paths=[os.path.dirname(tmp_file.name)],
            )
            client = TestClient(app)
            file_response = client.get(f"{API_PREFIX}/file={tmp_file.name}")
            assert file_response.status_code == 403
        io.close()
        os.remove(tmp_file.name)

    def test_get_file_created_by_app(self, test_client):
        app, _, _ = gr.Interface(lambda s: s.name, gr.File(), gr.File()).launch(
            prevent_thread_lock=True
        )
        client = TestClient(app)
        with open("test/test_files/alphabet.txt", "rb") as f:
            file_response = test_client.post(f"{API_PREFIX}/upload", files={"files": f})
        response = client.post(
            f"{API_PREFIX}/api/predict/",
            json={
                "data": [
                    {
                        "path": file_response.json()[0],
                        "size": os.path.getsize("test/test_files/alphabet.txt"),
                    }
                ],
                "fn_index": 0,
                "session_hash": "_",
            },
        ).json()
        created_file = response["data"][0]["path"]
        file_response = client.get(f"{API_PREFIX}/file={created_file}")
        assert file_response.is_success

        backwards_compatible_file_response = client.get(
            f"{API_PREFIX}/file/{created_file}"
        )
        assert backwards_compatible_file_response.is_success

        file_response_with_full_range = client.get(
            f"{API_PREFIX}/file={created_file}", headers={"Range": "bytes=0-"}
        )
        assert file_response_with_full_range.is_success
        assert file_response.text == file_response_with_full_range.text

        file_response_with_partial_range = client.get(
            f"{API_PREFIX}/file={created_file}", headers={"Range": "bytes=0-10"}
        )
        assert file_response_with_partial_range.is_success
        assert len(file_response_with_partial_range.text) == 11

    def test_mount_gradio_app(self):
        app = FastAPI()

        demo = gr.Interface(
            lambda s: f"Hello from ps, {s}!", "textbox", "textbox"
        ).queue()
        demo1 = gr.Interface(
            lambda s: f"Hello from py, {s}!", "textbox", "textbox"
        ).queue()

        app = gr.mount_gradio_app(app, demo, path="/ps")
        app = gr.mount_gradio_app(app, demo1, path="/py")

        # Use context manager to trigger start up events
        with TestClient(app) as client:
            assert client.get("/ps").is_success
            assert client.get("/py").is_success

    def test_mount_gradio_app_with_app_kwargs(self):
        app = FastAPI()
        demo = gr.Interface(lambda s: f"You said {s}!", "textbox", "textbox").queue()
        app = gr.mount_gradio_app(
            app,
            demo,
            path="/echo",
            app_kwargs={"docs_url": "/docs-custom"},
        )
        # Use context manager to trigger start up events
        with TestClient(app) as client:
            assert client.get("/echo/docs-custom").is_success

    def test_mount_gradio_app_with_auth_and_params(self):
        app = FastAPI()
        demo = gr.Interface(lambda s: f"You said {s}!", "textbox", "textbox").queue()
        app = gr.mount_gradio_app(
            app,
            demo,
            path=f"{API_PREFIX}/echo",
            auth=("a", "b"),
            root_path=f"{API_PREFIX}/echo",
            allowed_paths=["test/test_files/bus.png"],
        )
        # Use context manager to trigger start up events
        with TestClient(app) as client:
            assert client.get(f"{API_PREFIX}/echo/config").status_code == 401
        assert demo.root_path == f"{API_PREFIX}/echo"
        assert demo.allowed_paths == ["test/test_files/bus.png"]
        assert demo.show_error

    def test_mount_gradio_app_with_lifespan(self):
        @asynccontextmanager
        async def empty_lifespan(app: FastAPI):
            yield

        app = FastAPI(lifespan=empty_lifespan)

        demo = gr.Interface(
            lambda s: f"Hello from ps, {s}!", "textbox", "textbox"
        ).queue()
        demo1 = gr.Interface(
            lambda s: f"Hello from py, {s}!", "textbox", "textbox"
        ).queue()

        app = gr.mount_gradio_app(app, demo, path="/ps")
        app = gr.mount_gradio_app(app, demo1, path="/py")

        # Use context manager to trigger start up events
        with TestClient(app) as client:
            assert client.get("/ps").is_success
            assert client.get("/py").is_success

    def test_mount_gradio_app_with_startup(self):
        app = FastAPI()

        @app.on_event("startup")
        async def empty_startup():
            return

        demo = gr.Interface(
            lambda s: f"Hello from ps, {s}!", "textbox", "textbox"
        ).queue()
        demo1 = gr.Interface(
            lambda s: f"Hello from py, {s}!", "textbox", "textbox"
        ).queue()

        app = gr.mount_gradio_app(app, demo, path="/ps")
        app = gr.mount_gradio_app(app, demo1, path="/py")

        # Use context manager to trigger start up events
        with TestClient(app) as client:
            assert client.get("/ps").is_success
            assert client.get("/py").is_success

    def test_gradio_app_with_auth_dependency(self):
        def block_anonymous(request: Request):
            return request.headers.get("user")

        demo = gr.Interface(lambda s: s, "textbox", "textbox")
        app, _, _ = demo.launch(
            auth_dependency=block_anonymous, prevent_thread_lock=True
        )

        with TestClient(app) as client:
            assert not client.get("/", headers={}).is_success
            assert client.get("/", headers={"user": "abubakar"}).is_success

    def test_mount_gradio_app_with_auth_dependency(self):
        app = FastAPI()

        def get_user(request: Request):
            return request.headers.get("user")

        demo = gr.Interface(lambda s: f"Hello from ps, {s}!", "textbox", "textbox")

        app = gr.mount_gradio_app(app, demo, path="/demo", auth_dependency=get_user)

        with TestClient(app) as client:
            assert client.get("/demo", headers={"user": "abubakar"}).is_success
            assert not client.get("/demo").is_success

    def test_static_file_missing(self, test_client):
        response = test_client.get(rf"{API_PREFIX}/static/not-here.js")
        assert response.status_code == 404

    def test_asset_file_missing(self, test_client):
        response = test_client.get(rf"{API_PREFIX}/assets/not-here.js")
        assert response.status_code == 404

    def test_cannot_access_files_in_working_directory(self, test_client):
        response = test_client.get(rf"{API_PREFIX}/file=not-here.js")
        assert response.status_code == 403
        response = test_client.get(rf"{API_PREFIX}/file=subdir/.env")
        assert response.status_code == 403

    def test_cannot_access_directories_in_working_directory(self, test_client):
        response = test_client.get(rf"{API_PREFIX}/file=gradio")
        assert response.status_code == 403

    def test_block_protocols_that_expose_windows_credentials(self, test_client):
        response = test_client.get(rf"{API_PREFIX}/file=//11.0.225.200/share")
        assert response.status_code == 403

    def test_do_not_expose_existence_of_files_outside_working_directory(
        self, test_client
    ):
        response = test_client.get(
            rf"{API_PREFIX}/file=../fake-file-that-does-not-exist.js"
        )
        assert response.status_code == 403  # not a 404

    def test_proxy_route_is_restricted_to_load_urls(self):
        gr.context.Context.hf_token = "abcdef"  # type: ignore
        app = routes.App()
        interface = gr.Interface(lambda x: x, "text", "text")
        app.configure_app(interface)
        with pytest.raises(PermissionError):
            app.build_proxy_request(
                "https://gradio-tests-test-loading-examples-private.hf.space/file=Bunny.obj"
            )
        with pytest.raises(PermissionError):
            app.build_proxy_request("https://google.com")
        interface.proxy_urls = {
            "https://gradio-tests-test-loading-examples-private.hf.space"
        }
        app.build_proxy_request(
            "https://gradio-tests-test-loading-examples-private.hf.space/file=Bunny.obj"
        )

    def test_proxy_does_not_leak_hf_token_externally(self):
        gr.context.Context.hf_token = "abcdef"  # type: ignore
        app = routes.App()
        interface = gr.Interface(lambda x: x, "text", "text")
        interface.proxy_urls = {
            "https://gradio-tests-test-loading-examples-private.hf.space",
            "https://google.com",
        }
        app.configure_app(interface)
        r = app.build_proxy_request(
            "https://gradio-tests-test-loading-examples-private.hf.space/file=Bunny.obj"
        )
        assert "authorization" in dict(r.headers)
        r = app.build_proxy_request("https://google.com")
        assert "authorization" not in dict(r.headers)

    def test_can_get_config_that_includes_non_pickle_able_objects(self):
        my_dict = {"a": 1, "b": 2, "c": 3}
        with Blocks() as demo:
            gr.JSON(my_dict.keys())  # type: ignore

        app, _, _ = demo.launch(prevent_thread_lock=True)
        client = TestClient(app)
        response = client.get("/")
        assert response.is_success
        response = client.get("/config/")
        assert response.is_success

    def test_default_cors_restrictions(self):
        io = gr.Interface(lambda s: s.name, gr.File(), gr.File())
        app, _, _ = io.launch(prevent_thread_lock=True)
        client = TestClient(app)
        custom_headers = {
            "host": "localhost:7860",
            "origin": "https://example.com",
        }
        file_response = client.get(f"{API_PREFIX}/config", headers=custom_headers)
        assert "access-control-allow-origin" not in file_response.headers

        custom_headers = {
            "host": "localhost:7860",
            "origin": "null",
        }
        file_response = client.get(f"{API_PREFIX}/config", headers=custom_headers)
        assert "access-control-allow-origin" not in file_response.headers

        custom_headers = {
            "host": "localhost:7860",
            "origin": "127.0.0.1",
        }
        file_response = client.get(f"{API_PREFIX}/config", headers=custom_headers)
        assert file_response.headers["access-control-allow-origin"] == "127.0.0.1"

        io.close()

    def test_loose_cors_restrictions(self):
        io = gr.Interface(lambda s: s.name, gr.File(), gr.File())
        app, _, _ = io.launch(prevent_thread_lock=True, strict_cors=False)
        client = TestClient(app)
        custom_headers = {
            "host": "localhost:7860",
            "origin": "https://example.com",
        }
        file_response = client.get(f"{API_PREFIX}/config", headers=custom_headers)
        assert "access-control-allow-origin" not in file_response.headers

        custom_headers = {
            "host": "localhost:7860",
            "origin": "null",
        }
        file_response = client.get(f"{API_PREFIX}/config", headers=custom_headers)
        assert file_response.headers["access-control-allow-origin"] == "null"

        io.close()

    def test_delete_cache(self, connect, gradio_temp_dir, capsys):
        def check_num_files_exist(blocks: Blocks):
            num_files = 0
            for temp_file_set in blocks.temp_file_sets:
                for temp_file in temp_file_set:
                    if os.path.exists(temp_file):
                        num_files += 1
            return num_files

        demo = gr.Interface(lambda s: s, gr.Textbox(), gr.File(), delete_cache=None)
        with connect(demo) as client:
            client.predict("test/test_files/cheetah1.jpg")
        assert check_num_files_exist(demo) == 1

        demo_delete = gr.Interface(
            lambda s: s, gr.Textbox(), gr.File(), delete_cache=(60, 30)
        )
        with connect(demo_delete) as client:
            client.predict("test/test_files/alphabet.txt")
            client.predict("test/test_files/bus.png")
            assert check_num_files_exist(demo_delete) == 2
        assert check_num_files_exist(demo_delete) == 0
        assert check_num_files_exist(demo) == 1

        @asynccontextmanager
        async def mylifespan(app: FastAPI):
            print("IN CUSTOM LIFESPAN")
            yield
            print("AFTER CUSTOM LIFESPAN")

        demo_custom_lifespan = gr.Interface(
            lambda s: s, gr.Textbox(), gr.File(), delete_cache=(5, 1)
        )

        with connect(
            demo_custom_lifespan, app_kwargs={"lifespan": mylifespan}
        ) as client:
            client.predict("test/test_files/alphabet.txt")
        assert check_num_files_exist(demo_custom_lifespan) == 0
        captured = capsys.readouterr()
        assert "IN CUSTOM LIFESPAN" in captured.out
        assert "AFTER CUSTOM LIFESPAN" in captured.out

    def test_monitoring_link(self):
        with Blocks() as demo:
            i = Textbox()
            o = Textbox()
            i.change(lambda x: x, i, o)

        app, _, _ = demo.launch(prevent_thread_lock=True)
        client = TestClient(app)
        response = client.get(f"{API_PREFIX}/monitoring")
        assert response.status_code == 200

    def test_monitoring_link_disabled(self):
        with Blocks() as demo:
            i = Textbox()
            o = Textbox()
            i.change(lambda x: x, i, o)

        app, _, _ = demo.launch(prevent_thread_lock=True, enable_monitoring=False)
        client = TestClient(app)
        response = client.get(f"{API_PREFIX}/monitoring")
        assert response.status_code == 403


class TestApp:
    def test_create_app(self):
        app = routes.App.create_app(Interface(lambda x: x, "text", "text"))
        assert isinstance(app, FastAPI)


class TestAuthenticatedRoutes:
    def test_post_login(self):
        io = Interface(lambda x: x, "text", "text")
        app, _, _ = io.launch(
            auth=("test", "correct_password"),
            prevent_thread_lock=True,
        )
        client = TestClient(app)

        response = client.post(
            "/login",
            data={"username": "test", "password": "correct_password"},
        )
        assert response.status_code == 200

        response = client.post(
            "/login",
            data={"username": "test", "password": "incorrect_password"},
        )
        assert response.status_code == 400

        client.post(
            "/login",
            data={"username": "test", "password": "correct_password"},
        )
        response = client.post(
            "/login",
            data={"username": " test ", "password": "correct_password"},
        )
        assert response.status_code == 200

    def test_logout(self):
        io = Interface(lambda x: x, "text", "text")
        app, _, _ = io.launch(
            auth=("test", "correct_password"),
            prevent_thread_lock=True,
        )
        client = TestClient(app)

        client.post(
            "/login",
            data={"username": "test", "password": "correct_password"},
        )

        response = client.post(
            f"{API_PREFIX}/run/predict",
            json={"data": ["test"]},
        )
        assert response.status_code == 200

        response = client.get("/logout")

        response = client.post(
            "{API_PREFIX}/run/predict",
            json={"data": ["test"]},
        )
        assert response.status_code == 404

    def test_monitoring_route(self):
        io = Interface(lambda x: x, "text", "text")
        app, _, _ = io.launch(
            auth=("test", "correct_password"),
            prevent_thread_lock=True,
        )
        client = TestClient(app)
        client.post(
            "/login",
            data={"username": "test", "password": "correct_password"},
        )

        response = client.get(
            f"{API_PREFIX}/monitoring",
        )
        assert response.status_code == 200

        response = client.get("/logout")

        response = client.get(
            f"{API_PREFIX}/monitoring",
        )
        assert response.status_code == 401


class TestQueueRoutes:
    @pytest.mark.asyncio
    async def test_queue_join_routes_sets_app_if_none_set(self):
        io = Interface(lambda x: x, "text", "text").queue()
        io.launch(prevent_thread_lock=True)
        assert io.local_url
        client = grc.Client(io.local_url)
        client.predict("test")

        assert io._queue.server_app == io.server_app


class TestDevMode:
    def test_mount_gradio_app_set_dev_mode_false(self):
        app = FastAPI()

        @app.get(f"{API_PREFIX}/")
        def read_main():
            return {"message": "Hello!"}

        with gr.Blocks() as blocks:
            gr.Textbox("Hello from gradio!")

        app = routes.mount_gradio_app(app, blocks, path=f"{API_PREFIX}/gradio")
        gradio_fast_api = next(
            route for route in app.routes if isinstance(route, starlette.routing.Mount)
        )
        assert not gradio_fast_api.app.blocks.dev_mode  # type: ignore


class TestPassingRequest:
    def test_request_included_with_interface(self):
        def identity(name, request: gr.Request):
            assert isinstance(request.client.host, str)
            return name

        app, _, _ = gr.Interface(identity, "textbox", "textbox").launch(
            prevent_thread_lock=True,
        )
        client = TestClient(app)

        response = client.post(f"{API_PREFIX}/api/predict/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test"]

    def test_request_included_with_chat_interface(self):
        def identity(x, y, request: gr.Request):
            assert isinstance(request.client.host, str)
            return x

        app, _, _ = gr.ChatInterface(identity).launch(
            prevent_thread_lock=True,
        )
        client = TestClient(app)

        response = client.post(f"{API_PREFIX}/api/chat/", json={"data": ["test", None]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test", None]

    def test_request_included_with_chat_interface_when_streaming(self):
        def identity(x, y, request: gr.Request):
            assert isinstance(request.client.host, str)
            for i in range(len(x)):
                yield x[: i + 1]

        app, _, _ = (
            gr.ChatInterface(identity)
            .queue(api_open=True)
            .launch(
                prevent_thread_lock=True,
            )
        )
        client = TestClient(app)

        response = client.post(f"{API_PREFIX}/api/chat/", json={"data": ["test", None]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["t", None]

    def test_request_get_headers(self):
        def identity(name, request: gr.Request):
            assert isinstance(request.headers["user-agent"], str)
            assert isinstance(request.headers.items(), list)
            assert isinstance(request.headers.keys(), list)
            assert isinstance(request.headers.values(), list)
            assert isinstance(dict(request.headers), dict)
            user_agent = request.headers["user-agent"]
            assert "testclient" in user_agent
            return name

        app, _, _ = gr.Interface(identity, "textbox", "textbox").launch(
            prevent_thread_lock=True,
        )
        client = TestClient(app)

        response = client.post(f"{API_PREFIX}/api/predict/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test"]

    def test_request_includes_username_as_none_if_no_auth(self):
        def identity(name, request: gr.Request):
            assert request.username is None
            return name

        app, _, _ = gr.Interface(identity, "textbox", "textbox").launch(
            prevent_thread_lock=True,
        )
        client = TestClient(app)

        response = client.post(f"{API_PREFIX}/api/predict/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test"]

    def test_request_includes_username_with_auth(self):
        def identity(name, request: gr.Request):
            assert request.username == "admin"
            return name

        app, _, _ = gr.Interface(identity, "textbox", "textbox").launch(
            prevent_thread_lock=True, auth=("admin", "password")
        )
        client = TestClient(app)

        client.post(
            "/login",
            data={"username": "admin", "password": "password"},
        )
        response = client.post(f"{API_PREFIX}/api/predict/", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test"]

    def test_request_is_pickleable(self):
        """
        For ZeroGPU, we need to ensure that the gr.Request object is pickle-able.
        """

        def identity(name, request: gr.Request):
            pickled = pickle.dumps(request)
            unpickled = pickle.loads(pickled)
            assert request.client.host == unpickled.client.host
            assert request.client.port == unpickled.client.port
            assert dict(request.query_params) == dict(unpickled.query_params)
            assert request.query_params["a"] == unpickled.query_params["a"]
            assert dict(request.headers) == dict(unpickled.headers)
            assert request.username == unpickled.username
            return name

        app, _, _ = gr.Interface(identity, "textbox", "textbox").launch(
            prevent_thread_lock=True,
        )
        client = TestClient(app)

        response = client.post(f"{API_PREFIX}/api/predict?a=b", json={"data": ["test"]})
        assert response.status_code == 200
        output = dict(response.json())
        assert output["data"] == ["test"]


def test_predict_route_is_blocked_if_api_open_false():
    io = Interface(lambda x: x, "text", "text", examples=[["freddy"]]).queue(
        api_open=False
    )
    app, _, _ = io.launch(prevent_thread_lock=True)
    assert io.show_api
    client = TestClient(app)
    result = client.post(
        f"{API_PREFIX}/api/predict",
        json={"fn_index": 0, "data": [5], "session_hash": "foo"},
    )
    assert result.status_code == 404


def test_predict_route_not_blocked_if_queue_disabled():
    with Blocks() as demo:
        input = Textbox()
        output = Textbox()
        number = Number()
        button = Button()
        button.click(
            lambda x: f"Hello, {x}!", input, output, queue=False, api_name="not_blocked"
        )
        button.click(lambda: 42, None, number, queue=True, api_name="blocked")
    app, _, _ = demo.queue(api_open=False).launch(
        prevent_thread_lock=True, show_api=True
    )
    assert demo.show_api
    client = TestClient(app)

    result = client.post(
        f"{API_PREFIX}/api/blocked", json={"data": [], "session_hash": "foo"}
    )
    assert result.status_code == 404
    result = client.post(
        f"{API_PREFIX}/api/not_blocked",
        json={"data": ["freddy"], "session_hash": "foo"},
    )
    assert result.status_code == 200
    assert result.json()["data"] == ["Hello, freddy!"]


def test_predict_route_not_blocked_if_routes_open():
    with Blocks() as demo:
        input = Textbox()
        output = Textbox()
        button = Button()
        button.click(
            lambda x: f"Hello, {x}!", input, output, queue=True, api_name="not_blocked"
        )
    app, _, _ = demo.queue(api_open=True).launch(
        prevent_thread_lock=True, show_api=False
    )
    assert not demo.show_api
    client = TestClient(app)

    result = client.post(
        f"{API_PREFIX}/api/not_blocked",
        json={"data": ["freddy"], "session_hash": "foo"},
    )
    assert result.status_code == 200
    assert result.json()["data"] == ["Hello, freddy!"]

    demo.close()
    demo.queue(api_open=False).launch(prevent_thread_lock=True, show_api=False)
    assert not demo.show_api


def test_show_api_queue_not_enabled():
    io = Interface(lambda x: x, "text", "text", examples=[["freddy"]])
    app, _, _ = io.launch(prevent_thread_lock=True)
    assert io.show_api
    io.close()
    io.launch(prevent_thread_lock=True, show_api=False)
    assert not io.show_api


def test_orjson_serialization():
    df = pd.DataFrame(
        {
            "date_1": pd.date_range("2021-01-01", periods=2),
            "date_2": pd.date_range("2022-02-15", periods=2).strftime("%B %d, %Y, %r"),
            "number": np.array([0.2233, 0.57281]),
            "number_2": np.array([84, 23]).astype(np.int64),
            "bool": [True, False],
            "markdown": ["# Hello", "# Goodbye"],
        }
    )

    with gr.Blocks() as demo:
        gr.DataFrame(df)
    app, _, _ = demo.launch(prevent_thread_lock=True)
    test_client = TestClient(app)
    response = test_client.get("/")
    assert response.status_code == 200
    demo.close()


def test_api_name_set_for_all_events(connect):
    with gr.Blocks() as demo:
        i = Textbox()
        o = Textbox()
        btn = Button()
        btn1 = Button()
        btn2 = Button()
        btn3 = Button()
        btn4 = Button()
        btn5 = Button()
        btn6 = Button()
        btn7 = Button()
        btn8 = Button()

        def greet(i):
            return "Hello " + i

        def goodbye(i):
            return "Goodbye " + i

        def greet_me(i):
            return "Hello"

        def say_goodbye(i):
            return "Goodbye"

        say_goodbye.__name__ = "Say_$$_goodbye"

        # Otherwise changed by ruff
        foo = lambda s: s  # noqa

        def foo2(s):
            return s + " foo"

        foo2.__name__ = "foo-2"

        class Callable:
            def __call__(self, a) -> str:
                return "From __call__"

        def from_partial(a, b):
            return b + a

        part = functools.partial(from_partial, b="From partial: ")

        btn.click(greet, i, o)
        btn1.click(goodbye, i, o)
        btn2.click(greet_me, i, o)
        btn3.click(say_goodbye, i, o)
        btn4.click(None, i, o)
        btn5.click(foo, i, o)
        btn6.click(foo2, i, o)
        btn7.click(Callable(), i, o)
        btn8.click(part, i, o)

    with closing(demo) as io:
        app, _, _ = io.launch(prevent_thread_lock=True)
        client = TestClient(app)
        assert client.post(
            f"{API_PREFIX}/api/greet", json={"data": ["freddy"], "session_hash": "foo"}
        ).json()["data"] == ["Hello freddy"]
        assert client.post(
            f"{API_PREFIX}/api/goodbye",
            json={"data": ["freddy"], "session_hash": "foo"},
        ).json()["data"] == ["Goodbye freddy"]
        assert client.post(
            f"{API_PREFIX}/api/greet_me",
            json={"data": ["freddy"], "session_hash": "foo"},
        ).json()["data"] == ["Hello"]
        assert client.post(
            f"{API_PREFIX}/api/Say__goodbye",
            json={"data": ["freddy"], "session_hash": "foo"},
        ).json()["data"] == ["Goodbye"]
        assert client.post(
            f"{API_PREFIX}/api/lambda", json={"data": ["freddy"], "session_hash": "foo"}
        ).json()["data"] == ["freddy"]
        assert client.post(
            f"{API_PREFIX}/api/foo-2", json={"data": ["freddy"], "session_hash": "foo"}
        ).json()["data"] == ["freddy foo"]
        assert client.post(
            f"{API_PREFIX}/api/Callable",
            json={"data": ["freddy"], "session_hash": "foo"},
        ).json()["data"] == ["From __call__"]
        assert client.post(
            f"{API_PREFIX}/api/partial",
            json={"data": ["freddy"], "session_hash": "foo"},
        ).json()["data"] == ["From partial: freddy"]
        with pytest.raises(FnIndexInferError):
            client.post(
                f"{API_PREFIX}/api/Say_goodbye",
                json={"data": ["freddy"], "session_hash": "foo"},
            )

    with connect(demo) as client:
        assert client.predict("freddy", api_name="/greet") == "Hello freddy"
        assert client.predict("freddy", api_name="/goodbye") == "Goodbye freddy"
        assert client.predict("freddy", api_name="/greet_me") == "Hello"
        assert client.predict("freddy", api_name="/Say__goodbye") == "Goodbye"


class TestShowAPI:
    @patch.object(wasm_utils, "IS_WASM", True)
    def test_show_api_false_when_is_wasm_true(self):
        interface = Interface(lambda x: x, "text", "text", examples=[["hannah"]])
        assert (
            interface.show_api is False
        ), "show_api should be False when IS_WASM is True"

    @patch.object(wasm_utils, "IS_WASM", False)
    def test_show_api_true_when_is_wasm_false(self):
        interface = Interface(lambda x: x, "text", "text", examples=[["hannah"]])
        assert (
            interface.show_api is True
        ), "show_api should be True when IS_WASM is False"


def test_component_server_endpoints(connect):
    here = os.path.dirname(os.path.abspath(__file__))
    with gr.Blocks() as demo:
        file_explorer = gr.FileExplorer(root_dir=here)

    with closing(demo) as io:
        app, _, _ = io.launch(prevent_thread_lock=True)
        client = TestClient(app)
        success_req = client.post(
            f"{API_PREFIX}/component_server/",
            json={
                "session_hash": "123",
                "component_id": file_explorer._id,
                "fn_name": "ls",
                "data": None,
            },
        )
        assert success_req.status_code == 200
        assert len(success_req.json()) > 0
        fail_req = client.post(
            f"{API_PREFIX}/component_server/",
            json={
                "session_hash": "123",
                "component_id": file_explorer._id,
                "fn_name": "preprocess",
                "data": None,
            },
        )
        assert fail_req.status_code == 404


@pytest.mark.parametrize(
    "request_url, route_path, root_path, expected_root_url",
    [
        (
            f"http://localhost:7860/{API_PREFIX}",
            f"{API_PREFIX}/",
            None,
            "http://localhost:7860",
        ),
        (
            f"http://localhost:7860/{API_PREFIX}/demo/test",
            f"{API_PREFIX}/demo/test",
            None,
            "http://localhost:7860",
        ),
        (
            f"http://localhost:7860/{API_PREFIX}/demo/test?query=1",
            f"{API_PREFIX}/demo/test",
            None,
            "http://localhost:7860",
        ),
        (
            f"http://localhost:7860/{API_PREFIX}/demo/test?query=1",
            f"{API_PREFIX}/demo/test/",
            "/gradio",
            "http://localhost:7860/gradio",
        ),
        (
            "http://localhost:7860/demo/test?query=1",
            "/demo/test",
            "/gradio/",
            "http://localhost:7860/gradio",
        ),
        (
            "https://localhost:7860/demo/test?query=1",
            "/demo/test",
            "/gradio/",
            "https://localhost:7860/gradio",
        ),
        (
            "https://www.gradio.app/playground/",
            f"{API_PREFIX}/",
            "/playground",
            "https://www.gradio.app/playground",
        ),
        (
            "https://www.gradio.app/playground/",
            f"{API_PREFIX}/",
            "http://www.gradio.app/",
            "http://www.gradio.app",
        ),
    ],
)
def test_get_root_url(
    request_url: str, route_path: str, root_path: str, expected_root_url: str
):
    scope = {
        "type": "http",
        "headers": [],
        "path": request_url,
    }
    request = Request(scope)
    assert get_root_url(request, route_path, root_path) == expected_root_url


@pytest.mark.parametrize(
    "headers, root_path, route_path, expected_root_url",
    [
        ({}, "/gradio/", "/", "http://gradio.app/gradio"),
        (
            {"x-forwarded-proto": "http"},
            "/gradio/",
            "/",
            "http://gradio.app/gradio",
        ),
        (
            {"x-forwarded-proto": "https"},
            "/gradio/",
            "/",
            "https://gradio.app/gradio",
        ),
        (
            {"x-forwarded-host": "gradio.dev"},
            "/gradio/",
            "/",
            "http://gradio.dev/gradio",
        ),
        (
            {"x-forwarded-host": "gradio.dev"},
            "/gradio/",
            "/config",
            "http://gradio.dev/gradio",
        ),
        (
            {"x-forwarded-host": "gradio.dev", "x-forwarded-proto": "https"},
            "/",
            "/",
            "https://gradio.dev",
        ),
        (
            {
                "x-forwarded-host": "gradio.dev,internal.gradio.dev",
                "x-forwarded-proto": "https,http",
            },
            "/",
            "/",
            "https://gradio.dev",
        ),
        (
            {"x-forwarded-host": "gradio.dev", "x-forwarded-proto": "https"},
            "http://google.com",
            "/",
            "http://google.com",
        ),
    ],
)
def test_get_root_url_headers(
    headers: dict[str, str], root_path: str, route_path: str, expected_root_url: str
):
    scope = {
        "type": "http",
        "headers": [(k.encode(), v.encode()) for k, v in headers.items()],
        "path": "http://gradio.app",
    }
    request = Request(scope)
    assert get_root_url(request, route_path, root_path) == expected_root_url


class TestSimpleAPIRoutes:
    def get_demo(self):
        with Blocks() as demo:
            input = Textbox()
            output = Textbox()
            output2 = Textbox()

            def fn_1(x):
                return f"Hello, {x}!"

            def fn_2(x):
                for i in range(len(x)):
                    time.sleep(0.5)
                    yield f"Hello, {x[:i+1]}!"
                if len(x) < 3:
                    raise ValueError("Small input")

            def fn_3():
                return "a", "b"

            btn1, btn2, btn3 = Button(), Button(), Button()
            btn1.click(fn_1, input, output, api_name="fn1")
            btn2.click(fn_2, input, output2, api_name="fn2")
            btn3.click(fn_3, None, [output, output2], api_name="fn3")
        return demo

    def test_successful_simple_route(self):
        demo = self.get_demo()
        demo.launch(prevent_thread_lock=True)

        response = requests.post(
            f"{demo.local_api_url}call/fn1", json={"data": ["world"]}
        )

        assert response.status_code == 200, "Failed to call fn1"
        response = response.json()
        event_id = response["event_id"]

        output = []
        response = requests.get(f"{demo.local_api_url}call/fn1/{event_id}", stream=True)

        for line in response.iter_lines():
            if line:
                output.append(line.decode("utf-8"))

        assert output == ["event: complete", 'data: ["Hello, world!"]']

        response = requests.post(f"{demo.local_api_url}call/fn3", json={"data": []})

        assert response.status_code == 200, "Failed to call fn3"
        response = response.json()
        event_id = response["event_id"]

        output = []
        response = requests.get(f"{demo.local_api_url}call/fn3/{event_id}", stream=True)

        for line in response.iter_lines():
            if line:
                output.append(line.decode("utf-8"))

        assert output == ["event: complete", 'data: ["a", "b"]']

    def test_generative_simple_route(self):
        demo = self.get_demo()
        demo.launch(prevent_thread_lock=True)

        response = requests.post(
            f"{demo.local_api_url}call/fn2", json={"data": ["world"]}
        )

        assert response.status_code == 200, "Failed to call fn2"
        response = response.json()
        event_id = response["event_id"]

        output = []
        response = requests.get(f"{demo.local_api_url}call/fn2/{event_id}", stream=True)

        for line in response.iter_lines():
            if line:
                output.append(line.decode("utf-8"))

        assert output == [
            "event: generating",
            'data: ["Hello, w!"]',
            "event: generating",
            'data: ["Hello, wo!"]',
            "event: generating",
            'data: ["Hello, wor!"]',
            "event: generating",
            'data: ["Hello, worl!"]',
            "event: generating",
            'data: ["Hello, world!"]',
            "event: complete",
            'data: ["Hello, world!"]',
        ]

        response = requests.post(f"{demo.local_api_url}call/fn2", json={"data": ["w"]})

        assert response.status_code == 200, "Failed to call fn2"
        response = response.json()
        event_id = response["event_id"]

        output = []
        response = requests.get(f"{demo.local_api_url}call/fn2/{event_id}", stream=True)

        for line in response.iter_lines():
            if line:
                output.append(line.decode("utf-8"))

        assert output == [
            "event: generating",
            'data: ["Hello, w!"]',
            "event: error",
            "data: null",
        ]


def test_compare_passwords_securely():
    password1 = "password"
    password2 = "pässword"
    assert compare_passwords_securely(password1, password1)
    assert not compare_passwords_securely(password1, password2)
    assert compare_passwords_securely(password2, password2)


@pytest.mark.parametrize(
    "string, expected",
    [
        ("http://localhost:7860/", True),
        ("https://localhost:7860/", True),
        ("ftp://localhost:7860/", True),
        ("smb://example.com", True),
        ("ipfs://QmTzQ1Nj5R9BzF1djVQv8gvzZxVkJb1vhrLcXL1QyJzZE", True),
        ("usr/local/bin", False),
        ("localhost:7860", False),
        ("localhost", False),
        ("C:/Users/username", False),
        ("//path", True),
        ("\\\\path", True),
        ("/usr/bin//test", False),
        ("/\\10.0.225.200/share", True),
        ("\\/10.0.225.200/share", True),
        ("/home//user", False),
        ("C:\\folder\\file", False),
    ],
)
def test_starts_with_protocol(string, expected):
    assert starts_with_protocol(string) == expected


def test_max_file_size_used_in_upload_route(connect):
    with gr.Blocks() as demo:
        gr.Markdown("Max file size demo")

    app, _, _ = demo.launch(prevent_thread_lock=True, max_file_size="1kb")
    test_client = TestClient(app)
    with open("test/test_files/cheetah1.jpg", "rb") as f:
        r = test_client.post(f"{API_PREFIX}/upload", files={"files": f})
        assert r.status_code == 413
    with open("test/test_files/alphabet.txt", "rb") as f:
        r = test_client.post(f"{API_PREFIX}/upload", files={"files": f})
        assert r.status_code == 200


def test_docs_url():
    with gr.Blocks() as demo:
        num = gr.Number(value=0)
        button = gr.Button()
        button.click(lambda n: n + 1, [num], [num])

    app, _, _ = demo.launch(
        app_kwargs={"docs_url": f"{API_PREFIX}/docs"}, prevent_thread_lock=True
    )
    try:
        test_client = TestClient(app)
        with test_client:
            r = test_client.get(f"{API_PREFIX}/docs")
            assert r.status_code == 200
    finally:
        demo.close()


def test_file_access():
    with gr.Blocks() as demo:
        gr.Markdown("Test")

    allowed_dir = (Path(tempfile.gettempdir()) / "test_file_access_dir").resolve()
    allowed_dir.mkdir(parents=True, exist_ok=True)
    allowed_file = Path(allowed_dir / "allowed.txt")
    allowed_file.touch()

    not_allowed_file = Path(tempfile.gettempdir()) / "not_allowed.txt"
    not_allowed_file.touch()

    app, _, _ = demo.launch(
        prevent_thread_lock=True,
        blocked_paths=["test/test_files"],
        allowed_paths=[str(allowed_dir)],
    )
    test_client = TestClient(app)
    try:
        with test_client:
            r = test_client.get(f"{API_PREFIX}/file={allowed_dir}/allowed.txt")
            assert r.status_code == 200
            r = test_client.get(f"{API_PREFIX}/file={allowed_dir}/../not_allowed.txt")
            assert r.status_code in [403, 404]  # 403 in Linux, 404 in Windows
            r = test_client.get(f"{API_PREFIX}/file=//test/test_files/cheetah1.jpg")
            assert r.status_code == 403
            r = test_client.get(f"{API_PREFIX}/file=test/test_files/cheetah1.jpg")
            assert r.status_code == 403
            r = test_client.get(f"{API_PREFIX}/file=//test/test_files/cheetah1.jpg")
            assert r.status_code == 403
            tmp = Path(tempfile.gettempdir()) / "upload_test.txt"
            tmp.write_text("Hello")
            with open(str(tmp), "rb") as f:
                files = {"files": ("..", f)}
                response = test_client.post(f"{API_PREFIX}/upload", files=files)
                assert response.status_code == 400
    finally:
        demo.close()
        not_allowed_file.unlink()
        allowed_file.unlink()


def test_bash_api_serialization():
    demo = gr.Interface(lambda x: x, "json", "json")

    app, _, _ = demo.launch(prevent_thread_lock=True)
    test_client = TestClient(app)

    with test_client:
        submit = test_client.post(
            f"{API_PREFIX}/call/predict", json={"data": [{"a": 1}]}
        )
        event_id = submit.json()["event_id"]
        response = test_client.get(f"{API_PREFIX}/call/predict/{event_id}")
        assert response.status_code == 200
        assert "event: complete\ndata:" in response.text
        assert json.dumps({"a": 1}) in response.text


def test_bash_api_multiple_inputs_outputs():
    demo = gr.Interface(
        lambda x, y: (y, x), ["textbox", "number"], ["number", "textbox"]
    )

    app, _, _ = demo.launch(prevent_thread_lock=True)
    test_client = TestClient(app)

    with test_client:
        submit = test_client.post(
            f"{API_PREFIX}/call/predict", json={"data": ["abc", 123]}
        )
        event_id = submit.json()["event_id"]
        response = test_client.get(f"{API_PREFIX}/call/predict/{event_id}")
        assert response.status_code == 200
        assert "event: complete\ndata:" in response.text
        assert json.dumps([123, "abc"]) in response.text


def test_attacker_cannot_change_root_in_config(
    attacker_threads=1, victim_threads=10, max_attempts=30
):
    def attacker(url):
        """Simulates the attacker sending a request with a malicious header."""
        for _ in range(max_attempts):
            httpx.get(url + "config", headers={"X-Forwarded-Host": "evil"})

    def victim(url, results):
        """Simulates the victim making a normal request and checking the response."""
        for _ in range(max_attempts):
            res = httpx.get(url)
            config = json.loads(
                res.text.split("window.gradio_config =", 1)[1].split(";</script>", 1)[0]
            )
            if "evil" in config["root"]:
                results.append(True)
                return

        results.append(False)

    with gr.Blocks() as demo:
        i1 = gr.Image("test/test_files/cheetah1.jpg")
        t = gr.Textbox()
        i2 = gr.Image()
        t.change(lambda x: x, i1, i2)

    _, url, _ = demo.launch(prevent_thread_lock=True)

    threads = []
    results = []

    for _ in range(attacker_threads):
        t_attacker = Thread(target=attacker, args=(url,))
        threads.append(t_attacker)

    for _ in range(victim_threads):
        t_victim = Thread(
            target=victim,
            args=(
                url,
                results,
            ),
        )
        threads.append(t_victim)

    for t in threads:
        t.start()

    for t in threads:
        t.join()

    assert not any(results), "attacker was able to modify a victim's config root url"