/
test_client.py
1326 lines (1200 loc) 路 50.5 KB
/
test_client.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
991
992
993
994
995
996
997
998
999
1000
import json
import os
import pathlib
import tempfile
import time
import uuid
from concurrent.futures import CancelledError, TimeoutError, wait
from contextlib import contextmanager
from datetime import datetime, timedelta
from pathlib import Path
from unittest.mock import MagicMock, patch
import gradio as gr
import httpx
import huggingface_hub
import pytest
import uvicorn
from fastapi import FastAPI
from gradio.http_server import Server
from huggingface_hub import HfFolder
from huggingface_hub.utils import RepositoryNotFoundError
from gradio_client import Client, file
from gradio_client.client import DEFAULT_TEMP_DIR
from gradio_client.exceptions import AuthenticationError
from gradio_client.utils import (
Communicator,
ProgressUnit,
QueueError,
Status,
StatusUpdate,
)
HF_TOKEN = os.getenv("HF_TOKEN") or HfFolder.get_token()
@contextmanager
def connect(
demo: gr.Blocks, serialize: bool = True, output_dir: str = DEFAULT_TEMP_DIR
):
_, local_url, _ = demo.launch(prevent_thread_lock=True)
try:
yield Client(local_url, serialize=serialize, output_dir=output_dir)
finally:
# A more verbose version of .close()
# because we should set a timeout
# the tests that call .cancel() can get stuck
# waiting for the thread to join
demo.close()
class TestClientInitialization:
@pytest.mark.flaky
def test_headers_constructed_correctly(self):
client = Client("gradio-tests/titanic-survival", hf_token=HF_TOKEN)
assert {"authorization": f"Bearer {HF_TOKEN}"}.items() <= client.headers.items()
client = Client(
"gradio-tests/titanic-survival",
hf_token=HF_TOKEN,
headers={"additional": "value"},
)
assert {
"authorization": f"Bearer {HF_TOKEN}",
"additional": "value",
}.items() <= client.headers.items()
client = Client(
"gradio-tests/titanic-survival",
hf_token=HF_TOKEN,
headers={"authorization": "Bearer abcde"},
)
assert {"authorization": "Bearer abcde"}.items() <= client.headers.items()
def test_many_endpoint_demo_loads_quickly(self, many_endpoint_demo):
import datetime
start = datetime.datetime.now()
with connect(many_endpoint_demo):
pass
assert (datetime.datetime.now() - start).seconds < 5
class TestClientPredictions:
@pytest.mark.flaky
def test_raise_error_invalid_state(self):
with pytest.raises(ValueError, match="invalid state"):
Client("gradio-tests/paused-space")
@pytest.mark.flaky
def test_numerical_to_label_space(self):
client = Client("gradio-tests/titanic-survival")
label = json.load(
open(client.predict("male", 77, 10, api_name="/predict")) # noqa: SIM115
)
assert label["label"] == "Perishes"
with pytest.raises(
ValueError,
match="This Gradio app might have multiple endpoints. Please specify an `api_name` or `fn_index`",
):
client.predict("male", 77, 10)
with pytest.raises(
ValueError,
match="Cannot find a function with `api_name`: predict. Did you mean to use a leading slash?",
):
client.predict("male", 77, 10, api_name="predict")
@pytest.mark.flaky
def test_numerical_to_label_space_v4(self):
client = Client("gradio-tests/titanic-survivalv4-sse")
label = client.predict("male", 77, 10, api_name="/predict")
assert label["label"] == "Perishes"
@pytest.mark.flaky
def test_private_space(self):
space_id = "gradio-tests/not-actually-private-space"
api = huggingface_hub.HfApi()
assert api.space_info(space_id).private
client = Client(space_id)
output = client.predict("abc", api_name="/predict")
assert output == "abc"
@pytest.mark.flaky
def test_private_space_v4(self):
space_id = "gradio-tests/not-actually-private-spacev4-sse"
api = huggingface_hub.HfApi()
assert api.space_info(space_id).private
client = Client(
space_id,
)
output = client.predict("abc", api_name="/predict")
assert output == "abc"
@pytest.mark.flaky
def test_private_space_v4_sse_v1(self):
space_id = "gradio-tests/not-actually-private-spacev4-sse-v1"
api = huggingface_hub.HfApi()
assert api.space_info(space_id).private
client = Client(
space_id,
)
output = client.predict("abc", api_name="/predict")
assert output == "abc"
@pytest.mark.flaky
def test_space_with_files_v4_sse_v2(self):
space_id = "gradio-tests/space_with_files_v4_sse_v2"
client = Client(space_id)
payload = (
"https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3",
{
"video": "https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4",
"subtitle": None,
},
"https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3",
)
output = client.predict(*payload, api_name="/predict")
assert output[0].endswith(".wav") # Audio files are converted to wav
assert output[1]["video"].endswith(
"world.mp4"
) # Video files are not converted by default
assert (
output[2]
== "https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3"
) # textbox string should remain exactly the same
def test_state(self, increment_demo):
with connect(increment_demo) as client:
output = client.predict(api_name="/increment_without_queue")
assert output == 1
output = client.predict(api_name="/increment_without_queue")
assert output == 2
output = client.predict(api_name="/increment_without_queue")
assert output == 3
client.reset_session()
output = client.predict(api_name="/increment_without_queue")
assert output == 1
output = client.predict(api_name="/increment_with_queue")
assert output == 2
client.reset_session()
output = client.predict(api_name="/increment_with_queue")
assert output == 1
output = client.predict(api_name="/increment_with_queue")
assert output == 2
def test_job_status(self, calculator_demo):
with connect(calculator_demo) as client:
statuses = []
job = client.submit(5, "add", 4, api_name="/predict")
while not job.done():
time.sleep(0.1)
statuses.append(job.status())
assert statuses
# Messages are sorted by time
assert sorted([s.time for s in statuses if s]) == [
s.time for s in statuses if s
]
assert sorted([s.code for s in statuses if s]) == [
s.code for s in statuses if s
]
@pytest.mark.flaky
def test_intermediate_outputs(self, count_generator_demo):
with connect(count_generator_demo) as client:
job = client.submit(3, fn_index=0)
while not job.done():
time.sleep(0.1)
assert job.outputs() == [str(i) for i in range(3)]
outputs = []
for o in client.submit(3, fn_index=0):
outputs.append(o)
assert outputs == [str(i) for i in range(3)]
@pytest.mark.flaky
def test_intermediate_outputs_with_exception(self, count_generator_demo_exception):
with connect(count_generator_demo_exception) as client:
with pytest.raises(Exception):
client.predict(7, api_name="/count")
with pytest.raises(
ValueError, match="Cannot call predict on this function"
):
client.predict(5, api_name="/count_forever")
def test_break_in_loop_if_error(self, calculator_demo):
with connect(calculator_demo) as client:
job = client.submit("foo", "add", 4, fn_index=0)
output = list(job)
assert output == []
@pytest.mark.flaky
def test_timeout(self, sentiment_classification_demo):
with pytest.raises(TimeoutError):
with connect(sentiment_classification_demo.queue()) as client:
job = client.submit(api_name="/sleep")
job.result(timeout=0.05)
@pytest.mark.flaky
def test_timeout_no_queue(self, sentiment_classification_demo):
with pytest.raises(TimeoutError):
with connect(sentiment_classification_demo) as client:
job = client.submit(api_name="/sleep")
job.result(timeout=0.1)
def test_raises_exception(self, calculator_demo):
with pytest.raises(Exception):
with connect(calculator_demo) as client:
job = client.submit("foo", "add", 9, fn_index=0)
job.result()
def test_raises_exception_no_queue(self, sentiment_classification_demo):
with pytest.raises(Exception):
with connect(sentiment_classification_demo) as client:
job = client.submit([5], api_name="/sleep")
job.result()
def test_job_output_video(self, video_component):
with connect(video_component) as client:
job = client.submit(
{
"video": file(
"https://huggingface.co/spaces/gradio/video_component/resolve/main/files/a.mp4"
)
},
fn_index=0,
)
assert Path(job.result()["video"]).exists()
assert (
Path(DEFAULT_TEMP_DIR).resolve()
in Path(job.result()["video"]).resolve().parents
)
temp_dir = tempfile.mkdtemp()
with connect(video_component, output_dir=temp_dir) as client:
job = client.submit(
{
"video": file(
"https://huggingface.co/spaces/gradio/video_component/resolve/main/files/a.mp4"
)
},
fn_index=0,
)
assert Path(job.result()["video"]).exists()
assert (
Path(temp_dir).resolve()
in Path(job.result()["video"]).resolve().parents
)
def test_progress_updates(self, progress_demo):
with connect(progress_demo) as client:
job = client.submit("hello", api_name="/predict")
statuses = []
while not job.done():
statuses.append(job.status())
time.sleep(0.02)
assert any(s.code == Status.PROGRESS for s in statuses)
assert any(s.progress_data is not None for s in statuses)
all_progress_data = [
p for s in statuses if s.progress_data for p in s.progress_data
]
count = 0
for i in range(20):
unit = ProgressUnit(
index=i, length=20, unit="steps", progress=None, desc=None
)
count += unit in all_progress_data
assert count
def test_upload_and_download_with_auth(self):
demo = gr.Interface(lambda x: x, "text", "text")
_, url, _ = demo.launch(auth=("user", "pass"), prevent_thread_lock=True)
with pytest.raises(AuthenticationError):
client = Client(url)
client = Client(url, auth=("user", "pass"))
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Hello file!")
output = client.predict(f.name, api_name="/predict")
with open(output) as f:
assert f.read() == "Hello file!"
def test_cancel_from_client_queued(self, cancel_from_client_demo):
with connect(cancel_from_client_demo) as client:
start = time.time()
job = client.submit(api_name="/long")
while not job.done():
if job.status().code == Status.STARTING:
job.cancel()
break
with pytest.raises(CancelledError):
job.result()
# The whole prediction takes 10 seconds to run
# and does not iterate. So this tests that we can cancel
# halfway through a prediction
assert time.time() - start < 10
assert job.status().code == Status.CANCELLED
job = client.submit(api_name="/iterate")
iteration_count = 0
while not job.done():
if job.status().code == Status.ITERATING:
iteration_count += 1
if iteration_count == 3:
job.cancel()
break
time.sleep(0.5)
# Result for iterative jobs will raise there is an exception
with pytest.raises(CancelledError):
job.result()
# The whole prediction takes 10 seconds to run
# and does not iterate. So this tests that we can cancel
# halfway through a prediction
assert time.time() - start < 10
# Test that we did not iterate all the way to the end
assert all(o in [0, 1, 2, 3, 4, 5] for o in job.outputs())
assert job.status().code == Status.CANCELLED
def test_cancel_subsequent_jobs_state_reset(self, yield_demo):
with connect(yield_demo) as client:
job1 = client.submit("abcdefefadsadfs", api_name="/predict")
time.sleep(3)
job1.cancel()
assert len(job1.outputs()) > 0
assert len(job1.outputs()) < len("abcdefefadsadfs")
assert job1.status().code == Status.CANCELLED
job2 = client.submit("abcd", api_name="/predict")
assert len(job2.outputs()) == 0
while not job2.done():
time.sleep(0.1)
# Ran all iterations from scratch
assert job2.status().code == Status.FINISHED
assert len(job2.outputs()) == 4
@pytest.mark.xfail
def test_stream_audio(self, stream_audio):
with connect(stream_audio) as client:
job1 = client.submit(
file("https://gradio-builds.s3.amazonaws.com/demo-files/bark_demo.mp4"),
api_name="/predict",
)
assert Path(job1.result()).exists()
job2 = client.submit(
file(
"https://gradio-builds.s3.amazonaws.com/demo-files/audio_sample.wav"
),
api_name="/predict",
)
assert Path(job2.result()).exists()
assert all(Path(p).exists() for p in job2.outputs())
@pytest.mark.xfail
def test_upload_file_private_space_v4(self):
client = Client(
src="gradio-tests/not-actually-private-file-uploadv4-sse",
)
with patch.object(
client.endpoints[0], "_upload", wraps=client.endpoints[0]._upload
) as upload:
with patch.object(
client.endpoints[0], "serialize", wraps=client.endpoints[0].serialize
) as serialize:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Hello from private space!")
output = client.submit(
1, "foo", f.name, api_name="/file_upload"
).result()
with open(output) as f:
assert f.read() == "Hello from private space!"
upload.assert_called_once()
assert all(f["is_file"] for f in serialize.return_value())
with patch.object(
client.endpoints[1], "_upload", wraps=client.endpoints[0]._upload
) as upload:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Hello from private space!")
with open(client.submit(f.name, api_name="/upload_btn").result()) as f:
assert f.read() == "Hello from private space!"
upload.assert_called_once()
with patch.object(
client.endpoints[2], "_upload", wraps=client.endpoints[0]._upload
) as upload:
# `delete=False` is required for Windows compat
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f1:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f2:
f1.write("File1")
f2.write("File2")
r1, r2 = client.submit(
3,
[f1.name, f2.name],
"hello",
api_name="/upload_multiple",
).result()
with open(r1) as f:
assert f.read() == "File1"
with open(r2) as f:
assert f.read() == "File2"
upload.assert_called_once()
@pytest.mark.flaky
def test_upload_file_private_space(self):
client = Client(
src="gradio-tests/not-actually-private-file-upload",
hf_token=HF_TOKEN,
)
with patch.object(
client.endpoints[0], "serialize", wraps=client.endpoints[0].serialize
) as serialize:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Hello from private space!")
output = client.submit(1, "foo", f.name, api_name="/file_upload").result()
with open(output) as f:
assert f.read() == "Hello from private space!"
assert all(f["is_file"] for f in serialize.return_value())
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Hello from private space!")
with open(client.submit(f.name, api_name="/upload_btn").result()) as f:
assert f.read() == "Hello from private space!"
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f1:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f2:
f1.write("File1")
f2.write("File2")
r1, r2 = client.submit(
3,
[f1.name, f2.name],
"hello",
api_name="/upload_multiple",
).result()
with open(r1) as f:
assert f.read() == "File1"
with open(r2) as f:
assert f.read() == "File2"
@pytest.mark.flaky
def test_upload_file_upload_route_does_not_exist(self):
client = Client(
src="gradio-tests/not-actually-private-file-upload-old-version",
hf_token=HF_TOKEN,
)
with patch.object(
client.endpoints[0], "serialize", wraps=client.endpoints[0].serialize
) as serialize:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write("Hello from private space!")
client.submit(1, "foo", f.name, fn_index=0).result()
serialize.assert_called_once_with(1, "foo", f.name)
def test_state_without_serialize(self, stateful_chatbot):
with connect(stateful_chatbot, serialize=False) as client:
initial_history = [["", None]]
message = "Hello"
ret = client.predict(message, initial_history, api_name="/submit")
assert ret == ("", [["", None], ["Hello", "I love you"]])
def test_does_not_upload_dir(self, stateful_chatbot):
with connect(stateful_chatbot) as client:
initial_history = [["", None]]
message = "Hello"
ret = client.predict(message, initial_history, api_name="/submit")
assert ret == ("", [["", None], ["Hello", "I love you"]])
def test_can_call_mounted_app_via_api(self):
def greet(name):
return "Hello " + name + "!"
gradio_app = gr.Interface(
fn=greet,
inputs=gr.Textbox(lines=2, placeholder="Name Here..."),
outputs="text",
)
app = FastAPI()
app = gr.mount_gradio_app(app, gradio_app, path="/test/gradio")
config = uvicorn.Config(
app=app,
port=8000,
log_level="info",
)
server = Server(config=config)
# Using the gradio Server class to not have
# to implement code again to run uvicorn in a separate thread
# However, that means we need to set this flag to prevent
# run_in_thread_from_blocking
server.started = True
try:
server.run_in_thread()
time.sleep(1)
client = Client("http://127.0.0.1:8000/test/gradio/")
assert client.predict("freddy") == "Hello freddy!"
finally:
server.thread.join(timeout=1)
@pytest.mark.flaky
def test_predict_with_space_with_api_name_false(self):
client = Client("gradio-tests/client-bool-api-name-error")
assert client.predict("Hello!", api_name="/run") == "Hello!"
assert client.predict("Freddy", api_name="/say_hello") == "hello"
def test_return_layout_component(self, hello_world_with_group):
with connect(hello_world_with_group) as demo:
assert demo.predict("Freddy", api_name="/greeting") == "Hello Freddy"
assert demo.predict(api_name="/show_group") == ()
def test_return_layout_and_state_components(
self, hello_world_with_state_and_accordion
):
with connect(hello_world_with_state_and_accordion) as demo:
assert demo.predict("Freddy", api_name="/greeting") == ("Hello Freddy", 1)
assert demo.predict("Abubakar", api_name="/greeting") == (
"Hello Abubakar",
2,
)
assert demo.predict(api_name="/open") == 3
assert demo.predict(api_name="/close") == 4
assert demo.predict("Ali", api_name="/greeting") == ("Hello Ali", 5)
def test_long_response_time_with_gr_info_and_big_payload(
self, long_response_with_info
):
with connect(long_response_with_info) as demo:
assert demo.predict(api_name="/predict") == "\ta\nb" * 90000
def test_queue_full_raises_error(self):
demo = gr.Interface(lambda s: f"Hello {s}", "textbox", "textbox").queue(
max_size=1
)
with connect(demo) as client:
with pytest.raises(QueueError):
job1 = client.submit("Freddy", api_name="/predict")
job2 = client.submit("Abubakar", api_name="/predict")
job3 = client.submit("Pete", api_name="/predict")
wait([job1, job2, job3])
job1.result()
job2.result()
job3.result()
def test_json_parse_error(self):
data = (
"Bonjour Olivier, tu as l'air bien r\u00e9veill\u00e9 ce matin. Tu veux que je te pr\u00e9pare tes petits-d\u00e9j.\n",
None,
)
def return_bad():
return data
demo = gr.Interface(return_bad, None, ["text", "text"])
with connect(demo) as client:
pred = client.predict(api_name="/predict")
assert pred[0] == data[0]
def test_state_reset_when_session_changes(self, capsys, state_demo, monkeypatch):
monkeypatch.setenv("GRADIO_IS_E2E_TEST", "1")
with connect(state_demo) as client:
client.predict("Hello", api_name="/predict")
client.reset_session()
time.sleep(5)
out = capsys.readouterr().out
assert "STATE DELETED" in out
class TestClientPredictionsWithKwargs:
def test_no_default_params(self, calculator_demo):
with connect(calculator_demo) as client:
result = client.predict(
num1=3, operation="add", num2=3, api_name="/predict"
)
assert result == 6
result = client.predict(33, operation="add", num2=3, api_name="/predict")
assert result == 36
def test_default_params(self, calculator_demo_with_defaults):
with connect(calculator_demo_with_defaults) as client:
result = client.predict(num2=10, api_name="/predict")
assert result == 20
result = client.predict(num2=33, operation="multiply", api_name="/predict")
assert result == 330
def test_missing_params(self, calculator_demo):
with connect(calculator_demo) as client:
with pytest.raises(
ValueError, match="No value provided for required argument: num2"
):
client.predict(num1=3, operation="add", api_name="/predict")
class TestStatusUpdates:
@patch("gradio_client.client.Endpoint.make_end_to_end_fn")
def test_messages_passed_correctly(self, mock_make_end_to_end_fn, calculator_demo):
now = datetime.now()
messages = [
StatusUpdate(
code=Status.STARTING,
eta=None,
rank=None,
success=None,
queue_size=None,
time=now,
progress_data=None,
),
StatusUpdate(
code=Status.SENDING_DATA,
eta=None,
rank=None,
success=None,
queue_size=None,
time=now + timedelta(seconds=1),
progress_data=None,
),
StatusUpdate(
code=Status.IN_QUEUE,
eta=3,
rank=2,
queue_size=2,
success=None,
time=now + timedelta(seconds=2),
progress_data=None,
),
StatusUpdate(
code=Status.IN_QUEUE,
eta=2,
rank=1,
queue_size=1,
success=None,
time=now + timedelta(seconds=3),
progress_data=None,
),
StatusUpdate(
code=Status.ITERATING,
eta=None,
rank=None,
queue_size=None,
success=None,
time=now + timedelta(seconds=3),
progress_data=None,
),
StatusUpdate(
code=Status.FINISHED,
eta=None,
rank=None,
queue_size=None,
success=True,
time=now + timedelta(seconds=4),
progress_data=None,
),
]
class MockEndToEndFunction:
def __init__(self, communicator: Communicator):
self.communicator = communicator
def __call__(self, *args, **kwargs):
for m in messages:
with self.communicator.lock:
self.communicator.job.latest_status = m
time.sleep(0.1)
mock_make_end_to_end_fn.side_effect = MockEndToEndFunction
with connect(calculator_demo) as client:
job = client.submit(5, "add", 6, api_name="/predict")
statuses = []
while not job.done():
statuses.append(job.status())
time.sleep(0.09)
assert all(s in messages for s in statuses)
@patch("gradio_client.client.Endpoint.make_end_to_end_fn")
def test_messages_correct_two_concurrent(
self, mock_make_end_to_end_fn, calculator_demo
):
now = datetime.now()
messages_1 = [
StatusUpdate(
code=Status.STARTING,
eta=None,
rank=None,
success=None,
queue_size=None,
time=now,
progress_data=None,
),
StatusUpdate(
code=Status.FINISHED,
eta=None,
rank=None,
queue_size=None,
success=True,
time=now + timedelta(seconds=4),
progress_data=None,
),
]
messages_2 = [
StatusUpdate(
code=Status.IN_QUEUE,
eta=3,
rank=2,
queue_size=2,
success=None,
time=now + timedelta(seconds=2),
progress_data=None,
),
StatusUpdate(
code=Status.IN_QUEUE,
eta=2,
rank=1,
queue_size=1,
success=None,
time=now + timedelta(seconds=3),
progress_data=None,
),
]
class MockEndToEndFunction:
n_counts = 0
def __init__(self, communicator: Communicator):
self.communicator = communicator
self.messages = (
messages_1 if MockEndToEndFunction.n_counts == 0 else messages_2
)
MockEndToEndFunction.n_counts += 1
def __call__(self, *args, **kwargs):
for m in self.messages:
with self.communicator.lock:
print(f"here: {m}")
self.communicator.job.latest_status = m
time.sleep(0.1)
mock_make_end_to_end_fn.side_effect = MockEndToEndFunction
with connect(calculator_demo) as client:
job_1 = client.submit(5, "add", 6, api_name="/predict")
job_2 = client.submit(11, "subtract", 1, api_name="/predict")
statuses_1 = []
statuses_2 = []
while not (job_1.done() and job_2.done()):
statuses_1.append(job_1.status())
statuses_2.append(job_2.status())
time.sleep(0.05)
assert all(s in messages_1 for s in statuses_1)
class TestAPIInfo:
@pytest.mark.parametrize("trailing_char", ["/", ""])
def test_test_endpoint_src(self, trailing_char):
src = "https://gradio-calculator.hf.space" + trailing_char
client = Client(src=src)
assert client.endpoints[0].root_url == "https://gradio-calculator.hf.space/"
@pytest.mark.flaky
def test_numerical_to_label_space(self):
client = Client("gradio-tests/titanic-survival")
assert client.view_api(return_format="dict") == {
"named_endpoints": {
"/predict": {
"parameters": [
{
"label": "Sex",
"type": {"type": "string"},
"python_type": {"type": "str", "description": ""},
"component": "Radio",
"example_input": "Howdy!",
"serializer": "StringSerializable",
},
{
"label": "Age",
"type": {"type": "number"},
"python_type": {"type": "int | float", "description": ""},
"component": "Slider",
"example_input": 5,
"serializer": "NumberSerializable",
},
{
"label": "Fare (british pounds)",
"type": {"type": "number"},
"python_type": {"type": "int | float", "description": ""},
"component": "Slider",
"example_input": 5,
"serializer": "NumberSerializable",
},
],
"returns": [
{
"label": "output",
"type": {"type": {}, "description": "any valid json"},
"python_type": {
"type": "str",
"description": "filepath to JSON file",
},
"component": "Label",
"serializer": "JSONSerializable",
}
],
},
"/predict_1": {
"parameters": [
{
"label": "Sex",
"type": {"type": "string"},
"python_type": {"type": "str", "description": ""},
"component": "Radio",
"example_input": "Howdy!",
"serializer": "StringSerializable",
},
{
"label": "Age",
"type": {"type": "number"},
"python_type": {"type": "int | float", "description": ""},
"component": "Slider",
"example_input": 5,
"serializer": "NumberSerializable",
},
{
"label": "Fare (british pounds)",
"type": {"type": "number"},
"python_type": {"type": "int | float", "description": ""},
"component": "Slider",
"example_input": 5,
"serializer": "NumberSerializable",
},
],
"returns": [
{
"label": "output",
"type": {"type": {}, "description": "any valid json"},
"python_type": {
"type": "str",
"description": "filepath to JSON file",
},
"component": "Label",
"serializer": "JSONSerializable",
}
],
},
"/predict_2": {
"parameters": [
{
"label": "Sex",
"type": {"type": "string"},
"python_type": {"type": "str", "description": ""},
"component": "Radio",
"example_input": "Howdy!",
"serializer": "StringSerializable",
},
{
"label": "Age",
"type": {"type": "number"},
"python_type": {"type": "int | float", "description": ""},
"component": "Slider",
"example_input": 5,
"serializer": "NumberSerializable",
},
{
"label": "Fare (british pounds)",
"type": {"type": "number"},
"python_type": {"type": "int | float", "description": ""},
"component": "Slider",
"example_input": 5,
"serializer": "NumberSerializable",
},
],
"returns": [
{
"label": "output",
"type": {"type": {}, "description": "any valid json"},
"python_type": {
"type": "str",
"description": "filepath to JSON file",
},
"component": "Label",
"serializer": "JSONSerializable",
}
],
},
},
"unnamed_endpoints": {},
}
def test_state_does_not_appear(self, state_demo):
with connect(state_demo) as client:
api_info = client.view_api(return_format="dict")
assert isinstance(api_info, dict)
for parameter in api_info["named_endpoints"]["/predict"]["parameters"]:
assert parameter["component"] != "State"
@pytest.mark.flaky
def test_private_space(self):
client = Client(
"gradio-tests/not-actually-private-space",
)
assert len(client.endpoints) == 3
assert len([e for e in client.endpoints if e.is_valid]) == 2
assert len([e for e in client.endpoints if e.is_valid and e.api_name]) == 1
assert client.view_api(return_format="dict") == {
"named_endpoints": {
"/predict": {
"parameters": [
{
"label": "x",
"type": {"type": "string"},
"python_type": {"type": "str", "description": ""},
"component": "Textbox",
"example_input": "Howdy!",
"serializer": "StringSerializable",
}
],
"returns": [
{
"label": "output",
"type": {"type": "string"},
"python_type": {"type": "str", "description": ""},
"component": "Textbox",
"serializer": "StringSerializable",
}
],
}
},
"unnamed_endpoints": {},
}
def test_api_info_of_local_demo(self, calculator_demo):
with connect(calculator_demo) as client:
api_info = client.view_api(return_format="dict")
assert isinstance(api_info, dict)
assert api_info["named_endpoints"]["/predict"] == {
"parameters": [
{
"label": "num1",
"parameter_name": "num1",
"parameter_has_default": False,
"parameter_default": None,
"type": {"type": "number"},
"python_type": {"type": "float", "description": ""},
"component": "Number",