-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathtest_dispatcher.py
953 lines (765 loc) · 24.8 KB
/
test_dispatcher.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
"""Test dispatcher.py
TODO: Add tests for dispatch_requests (non-pure version)
"""
import json
from typing import Any, Dict
from unittest.mock import Mock, patch, sentinel
import pytest
from returns.result import Failure, Success
from jsonrpcserver.codes import (
ERROR_INTERNAL_ERROR,
ERROR_INVALID_PARAMS,
ERROR_INVALID_REQUEST,
ERROR_METHOD_NOT_FOUND,
ERROR_PARSE_ERROR,
ERROR_SERVER_ERROR,
)
from jsonrpcserver.dispatcher import (
call,
create_request,
dispatch_deserialized,
dispatch_request,
dispatch_to_response_pure,
extract_args,
extract_kwargs,
extract_list,
get_method,
not_notification,
to_response,
validate_args,
validate_request,
)
from jsonrpcserver.exceptions import JsonRpcError
from jsonrpcserver.main import default_jsonrpc_validator
from jsonrpcserver.methods import Method
from jsonrpcserver.request import Request
from jsonrpcserver.response import ErrorResponse, SuccessResponse
from jsonrpcserver.result import (
ErrorResult,
InvalidParams,
Ok,
Result,
SuccessResult,
)
from jsonrpcserver.sentinels import NOCONTEXT, NODATA, NOID
from jsonrpcserver.utils import identity
def ping() -> Result:
return Ok("pong")
# extract_list
def test_extract_list() -> None:
assert extract_list(False, [Success(SuccessResponse("foo", 1))]) == Success(
SuccessResponse("foo", 1)
)
def test_extract_list_notification() -> None:
assert extract_list(False, []) is None
def test_extract_list_batch() -> None:
assert extract_list(True, [Success(SuccessResponse("foo", 1))]) == [
Success(SuccessResponse("foo", 1))
]
def test_extract_list_batch_all_notifications() -> None:
assert extract_list(True, []) is None
# to_response
def test_to_response_SuccessResult() -> None:
assert to_response(
Request("ping", [], sentinel.id), Success(SuccessResult(sentinel.result))
) == Success(SuccessResponse(sentinel.result, sentinel.id))
def test_to_response_ErrorResult() -> None:
assert (
to_response(
Request("ping", [], sentinel.id),
Failure(
ErrorResult(
code=sentinel.code, message=sentinel.message, data=sentinel.data
)
),
)
) == Failure(
ErrorResponse(sentinel.code, sentinel.message, sentinel.data, sentinel.id)
)
def test_to_response_InvalidParams() -> None:
assert to_response(
Request("ping", [], sentinel.id), InvalidParams(sentinel.data)
) == Failure(ErrorResponse(-32602, "Invalid params", sentinel.data, sentinel.id))
def test_to_response_InvalidParams_no_data() -> None:
assert to_response(Request("ping", [], sentinel.id), InvalidParams()) == Failure(
ErrorResponse(-32602, "Invalid params", NODATA, sentinel.id)
)
def test_to_response_notification() -> None:
with pytest.raises(AssertionError):
to_response(
Request("ping", [], NOID), Success(SuccessResult(result=sentinel.result))
)
# extract_args
def test_extract_args() -> None:
assert extract_args(Request("ping", [], NOID), NOCONTEXT) == []
def test_extract_args_with_context() -> None:
assert extract_args(Request("ping", ["bar"], NOID), "foo") == ["foo", "bar"]
# extract_kwargs
def test_extract_kwargs() -> None:
assert extract_kwargs(Request("ping", {"foo": "bar"}, NOID)) == {"foo": "bar"}
# validate_args
def test_validate_args_result_no_arguments() -> None:
def f() -> Result:
return Ok()
assert validate_args(Request("f", [], NOID), NOCONTEXT, f) == Success(f)
def test_validate_args_result_no_arguments_too_many_positionals() -> None:
def f() -> Result:
return Ok()
assert validate_args(Request("f", ["foo"], NOID), NOCONTEXT, f) == Failure(
ErrorResult(
code=ERROR_INVALID_PARAMS,
message="Invalid params",
data="too many positional arguments",
)
)
def test_validate_args_positionals() -> None:
def ping_(_: int) -> Result:
return Ok()
assert validate_args(Request("ping_", [1], NOID), NOCONTEXT, ping_) == Success(
ping_
)
def test_validate_args_positionals_not_passed() -> None:
def ping_(name: str) -> Result:
return Ok()
assert validate_args(
Request("ping_", {"foo": "bar"}, NOID), NOCONTEXT, ping_
) == Failure(
ErrorResult(
ERROR_INVALID_PARAMS,
"Invalid params",
"missing a required argument: 'name'",
)
)
def test_validate_args_keywords() -> None:
def f(**_: str) -> Result:
return Ok()
assert validate_args(Request("f", {"foo": "bar"}, NOID), NOCONTEXT, f) == Success(f)
def test_validate_args_object_method() -> None:
class FooClass:
def f(self, *_: str) -> Result:
return Ok()
g = FooClass().f
assert validate_args(Request("g", ["one", "two"], NOID), NOCONTEXT, g) == Success(g)
# call
def test_call() -> None:
assert call(Request("ping", [], 1), NOCONTEXT, ping) == Success(
SuccessResult("pong")
)
def test_call_raising_jsonrpcerror() -> None:
def method_() -> Result:
raise JsonRpcError(code=1, message="foo", data=NODATA)
assert call(Request("ping", [], 1), NOCONTEXT, method_) == Failure(
ErrorResult(1, "foo")
)
def test_call_raising_exception() -> None:
def method_() -> Result:
raise ValueError("foo")
assert call(Request("ping", [], 1), NOCONTEXT, method_) == Failure(
ErrorResult(ERROR_INTERNAL_ERROR, "Internal error", "foo")
)
# validate_args
@pytest.mark.parametrize(
"argument,value",
[
(
Request("ping", [], 1),
Success(ping),
),
(
Request("ping", ["foo"], 1),
Failure(
ErrorResult(
ERROR_INVALID_PARAMS,
"Invalid params",
"too many positional arguments",
)
),
),
],
)
def test_validate_args(argument: Request, value: Result) -> None:
assert validate_args(argument, NOCONTEXT, ping) == value
# get_method
@pytest.mark.parametrize(
"argument,value",
[
(
get_method({"ping": ping}, "ping"),
Success(ping),
),
(
get_method({"ping": ping}, "non-existant"),
Failure(
ErrorResult(ERROR_METHOD_NOT_FOUND, "Method not found", "non-existant")
),
),
],
)
def test_get_method(argument: Result, value: Result) -> None:
assert argument == value
# dispatch_request
def test_dispatch_request() -> None:
request = Request("ping", [], 1)
assert dispatch_request(validate_args, {"ping": ping}, NOCONTEXT, request) == (
request,
Success(SuccessResult("pong")),
)
def test_dispatch_request_with_context() -> None:
def ping_with_context(context: Any) -> Result:
assert context is sentinel.context
return Ok()
dispatch_request(
validate_args,
{"ping_with_context": ping_with_context},
sentinel.context,
Request("ping_with_context", [], 1),
)
# Assert is in the method
# create_request
def test_create_request() -> None:
request = create_request({"jsonrpc": "2.0", "method": "ping"})
assert isinstance(request, Request)
# not_notification
def test_not_notification() -> None:
assert not_notification((Request("ping", [], 1), SuccessResult("pong"))) is True
def test_not_notification_false() -> None:
assert not_notification((Request("ping", [], NOID), SuccessResult("pong"))) is False
# dispatch_deserialized
def test_dispatch_deserialized() -> None:
assert dispatch_deserialized(
validate_args,
identity,
{"ping": ping},
NOCONTEXT,
{"jsonrpc": "2.0", "method": "ping", "id": 1},
) == Success(SuccessResponse("pong", 1))
# validate_request
def test_validate_request() -> None:
request = {"jsonrpc": "2.0", "method": "ping"}
assert validate_request(default_jsonrpc_validator, request) == Success(request)
def test_validate_request_invalid() -> None:
assert validate_request(default_jsonrpc_validator, {"jsonrpc": "2.0"}) == Failure(
ErrorResponse(
ERROR_INVALID_REQUEST,
"Invalid request",
"The request failed schema validation",
None,
)
)
# dispatch_to_response_pure
def test_dispatch_to_response_pure() -> None:
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"ping": ping},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "ping", "id": 1}',
) == Success(SuccessResponse("pong", 1))
def test_dispatch_to_response_pure_parse_error() -> None:
"""Unable to parse, must return an error"""
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"ping": ping},
NOCONTEXT,
"{",
) == Failure(
ErrorResponse(
ERROR_PARSE_ERROR,
"Parse error",
(
"Expecting property name enclosed in double quotes: "
"line 1 column 2 (char 1)"
),
None,
)
)
def test_dispatch_to_response_pure_invalid_request() -> None:
"""Invalid JSON-RPC, must return an error. (impossible to determine if
notification).
"""
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"ping": ping},
NOCONTEXT,
"{}",
) == Failure(
ErrorResponse(
ERROR_INVALID_REQUEST,
"Invalid request",
"The request failed schema validation",
None,
)
)
def test_dispatch_to_response_pure_method_not_found() -> None:
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "non_existant", "id": 1}',
) == Failure(
ErrorResponse(ERROR_METHOD_NOT_FOUND, "Method not found", "non_existant", 1)
)
def test_dispatch_to_response_pure_invalid_params_auto() -> None:
def f(colour: str, size: str) -> Result: # pylint: disable=unused-argument
return Ok()
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"f": f},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "f", "params": {"colour":"blue"}, "id": 1}',
) == Failure(
ErrorResponse(
ERROR_INVALID_PARAMS,
"Invalid params",
"missing a required argument: 'size'",
1,
)
)
def test_dispatch_to_response_pure_invalid_params_explicitly_returned() -> None:
def foo(colour: str) -> Result:
if colour not in ("orange", "red", "yellow"):
return InvalidParams()
return Ok()
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"foo": foo},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "foo", "params": ["blue"], "id": 1}',
) == Failure(ErrorResponse(ERROR_INVALID_PARAMS, "Invalid params", NODATA, 1))
def test_dispatch_to_response_pure_internal_error() -> None:
def foo() -> Result:
raise ValueError("foo")
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"foo": foo},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "foo", "id": 1}',
) == Failure(ErrorResponse(ERROR_INTERNAL_ERROR, "Internal error", "foo", 1))
@patch("jsonrpcserver.dispatcher.dispatch_request", side_effect=ValueError("foo"))
def test_dispatch_to_response_pure_server_error(*_: Mock) -> None:
def foo() -> Result:
return Ok()
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"foo": foo},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "foo", "id": 1}',
) == Failure(ErrorResponse(ERROR_SERVER_ERROR, "Server error", "foo", None))
def test_dispatch_to_response_pure_invalid_result() -> None:
"""Methods should return a Result, otherwise we get an Internal Error response."""
def not_a_result() -> Result:
return None # type: ignore
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"not_a_result": not_a_result},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "not_a_result", "id": 1}',
) == Failure(
ErrorResponse(
ERROR_INTERNAL_ERROR,
"Internal error",
"The method did not return a valid Result (returned None)",
1,
)
)
def test_dispatch_to_response_pure_raising_exception() -> None:
"""Allow raising an exception to return an error."""
def raise_exception() -> Result:
raise JsonRpcError(code=0, message="foo", data="bar")
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"raise_exception": raise_exception},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "raise_exception", "id": 1}',
) == Failure(ErrorResponse(0, "foo", "bar", 1))
# dispatch_to_response_pure -- Notifications
def test_dispatch_to_response_pure_notification() -> None:
assert (
dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"ping": ping},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "ping"}',
)
is None
)
def test_dispatch_to_response_pure_notification_parse_error() -> None:
"""Unable to parse, must return an error"""
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"ping": ping},
NOCONTEXT,
"{",
) == Failure(
ErrorResponse(
ERROR_PARSE_ERROR,
"Parse error",
(
"Expecting property name enclosed in double quotes: "
"line 1 column 2 (char 1)"
),
None,
)
)
def test_dispatch_to_response_pure_notification_invalid_request() -> None:
"""Invalid JSON-RPC, must return an error. (impossible to determine if
notification)
"""
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"ping": ping},
NOCONTEXT,
"{}",
) == Failure(
ErrorResponse(
ERROR_INVALID_REQUEST,
"Invalid request",
"The request failed schema validation",
None,
)
)
def test_dispatch_to_response_pure_notification_method_not_found() -> None:
assert (
dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "non_existant"}',
)
is None
)
def test_dispatch_to_response_pure_notification_invalid_params_auto() -> None:
def foo(colour: str, size: str) -> Result: # pylint: disable=unused-argument
return Ok()
assert (
dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"foo": foo},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "foo", "params": {"colour":"blue"}}',
)
is None
)
def test_dispatch_to_response_pure_invalid_params_notification_returned() -> None:
def foo(colour: str) -> Result:
if colour not in ("orange", "red", "yellow"):
return InvalidParams()
return Ok()
assert (
dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"foo": foo},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "foo", "params": ["blue"]}',
)
is None
)
def test_dispatch_to_response_pure_notification_internal_error() -> None:
def foo(bar: str) -> Result:
raise ValueError
assert (
dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"foo": foo},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "foo"}',
)
is None
)
@patch("jsonrpcserver.dispatcher.dispatch_request", side_effect=ValueError("foo"))
def test_dispatch_to_response_pure_notification_server_error(*_: Mock) -> None:
def foo() -> Result:
return Ok()
assert dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"foo": foo},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "foo"}',
) == Failure(ErrorResponse(ERROR_SERVER_ERROR, "Server error", "foo", None))
def test_dispatch_to_response_pure_notification_invalid_result() -> None:
"""Methods should return a Result, otherwise we get an Internal Error response."""
def not_a_result() -> Result:
return None # type: ignore
assert (
dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"not_a_result": not_a_result},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "not_a_result"}',
)
is None
)
def test_dispatch_to_response_pure_notification_raising_exception() -> None:
"""Allow raising an exception to return an error."""
def raise_exception() -> Result:
raise JsonRpcError(code=0, message="foo", data="bar")
assert (
dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"raise_exception": raise_exception},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "raise_exception"}',
)
is None
)
# The remaining tests are direct from the examples in the specification
def test_examples_positionals() -> None:
def subtract(minuend: int, subtrahend: int) -> Result:
return Ok(minuend - subtrahend)
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"subtract": subtract},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}',
)
assert response == Success(SuccessResponse(19, 1))
# Second example
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"subtract": subtract},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2}',
)
assert response == Success(SuccessResponse(-19, 2))
def test_examples_nameds() -> None:
def subtract(**kwargs: int) -> Result:
return Ok(kwargs["minuend"] - kwargs["subtrahend"])
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"subtract": subtract},
NOCONTEXT,
(
'{"jsonrpc": "2.0", "method": "subtract", '
'"params": {"subtrahend": 23, "minuend": 42}, "id": 3}'
),
)
assert response == Success(SuccessResponse(19, 3))
# Second example
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"subtract": subtract},
NOCONTEXT,
(
'{"jsonrpc": "2.0", "method": "subtract", '
'"params": {"minuend": 42, "subtrahend": 23}, "id": 4}'
),
)
assert response == Success(SuccessResponse(19, 4))
def test_examples_notification() -> None:
def f() -> Result:
return Ok()
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"update": f, "foobar": f},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "update", "params": [1, 2, 3, 4, 5]}',
)
assert response is None
# Second example
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"update": f, "foobar": f},
NOCONTEXT,
'{"jsonrpc": "2.0", "method": "foobar"}',
)
assert response is None
def test_examples_invalid_json() -> None:
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"ping": ping},
NOCONTEXT,
(
'[{"jsonrpc": "2.0", "method": "sum", '
'"params": [1,2,4], "id": "1"}, {"jsonrpc": "2.0", "method"]'
),
)
assert response == Failure(
ErrorResponse(
ERROR_PARSE_ERROR,
"Parse error",
"Expecting ':' delimiter: line 1 column 96 (char 95)",
None,
)
)
def test_examples_empty_array() -> None:
# This is an invalid JSON-RPC request, should return an error.
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"ping": ping},
NOCONTEXT,
"[]",
)
assert response == Failure(
ErrorResponse(
ERROR_INVALID_REQUEST,
"Invalid request",
"The request failed schema validation",
None,
)
)
def test_examples_invalid_jsonrpc_batch() -> None:
"""
We break the spec here, by not validating each request in the batch individually.
The examples are expecting a batch response full of error responses.
"""
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"ping": ping},
NOCONTEXT,
"[1]",
)
assert response == Failure(
ErrorResponse(
ERROR_INVALID_REQUEST,
"Invalid request",
"The request failed schema validation",
None,
)
)
def test_examples_multiple_invalid_jsonrpc() -> None:
"""
We break the spec here, by not validating each request in the batch individually.
The examples are expecting a batch response full of error responses.
"""
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
{"ping": ping},
NOCONTEXT,
"[1, 2, 3]",
)
assert response == Failure(
ErrorResponse(
ERROR_INVALID_REQUEST,
"Invalid request",
"The request failed schema validation",
None,
)
)
def test_examples_mixed_requests_and_notifications() -> None:
"""We break the spec here. The examples put an invalid jsonrpc request in the mix
here, but it's removed to test the rest, because we're not validating each request
individually. Any invalid jsonrpc will respond with a single error message.
The spec example includes this which invalidates the entire request:
{"foo": "boo"},
"""
methods: Dict[str, Method] = {
"sum": lambda *args: Ok(sum(args)),
"notify_hello": lambda *args: Ok(19),
"subtract": lambda *args: Ok(args[0] - sum(args[1:])),
"get_data": lambda: Ok(["hello", 5]),
}
response = dispatch_to_response_pure(
validate_args,
json.loads,
default_jsonrpc_validator,
identity,
methods,
NOCONTEXT,
"""[
{"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
{"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
{"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
{
"jsonrpc": "2.0",
"method": "foo.get",
"params": {"name": "myself"},
"id": "5"
},
{"jsonrpc": "2.0", "method": "get_data", "id": "9"}
]""",
)
assert response == [
Success(SuccessResponse(7, id="1")),
Success(SuccessResponse(19, id="2")),
Failure(ErrorResponse(-32601, "Method not found", "foo.get", id="5")),
Success(SuccessResponse(["hello", 5], id="9")),
]