Skip to content

Commit eca03a4

Browse files
committed
More coverage
1 parent 1c2e689 commit eca03a4

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

lib/json_rpc_handler.rb

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,18 @@ def handle(request, &find_method)
3434
responses = request.map { |req| process_request(req, &find_method) }.compact
3535
# And empty array yields nil
3636
responses if responses.any?
37-
else
37+
elsif request.is_a? Hash
3838
# Handle single request
3939
process_request(request, &find_method)
40+
else
41+
error_response(
42+
id: nil,
43+
error: {
44+
code: ErrorCode::InvalidRequest,
45+
message: 'Invalid Request',
46+
data: 'Request must be an array or a hash',
47+
},
48+
)
4049
end
4150
end
4251

@@ -108,8 +117,6 @@ def process_request(request, &find_method)
108117

109118
def validate_request(request)
110119
error = case
111-
when !request.is_a?(Hash)
112-
'Request must be an object'
113120
when !valid_version?(request[:jsonrpc])
114121
'JSON-RPC version must be 2.0'
115122
when !valid_id?(request[:id])

test/json_rpc_handler_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@
2727
# jsonrpc
2828
# A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0".
2929

30+
it "returns an error when the request is not an array or a hash" do
31+
handle(true)
32+
33+
assert_rpc_error(expected_error: { code: -32600, message: "Invalid Request", data: "Request must be an array or a hash" })
34+
end
35+
3036
it "returns a result when jsonrpc is 2.0" do
3137
register("add") do |params|
3238
params[:a] + params[:b]
@@ -252,6 +258,12 @@
252258
assert_rpc_error(expected_error: { code: -32601, message: "Method not found", data: "add" })
253259
end
254260

261+
it "returns nil when the method does not exist and the id is nil" do
262+
handle({ jsonrpc: "2.0", method: "add", params: { a: 1, b: 2 } })
263+
264+
assert_nil @response
265+
end
266+
255267
it "returns an error with the code set to -32602 when the method parameters are invalid" do
256268
handle({ jsonrpc: "2.0", id: 1, method: "set_active", params: true })
257269

0 commit comments

Comments
 (0)