Skip to content

Commit 0c87fce

Browse files
committed
chore: added jsonrpc server test
1 parent e8b4ded commit 0c87fce

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

internal/jsonrpc2/jsonrpc2.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,9 @@ func HandleNotification[Params any](s *Server, method string, handler func(param
6565
}
6666

6767
// Send a json rpc request and wait for the response. Thread safe.
68-
func SendRequest(s *Server, method string, params any) (any, error) {
68+
//
69+
// TODO change the API in order to make sure SendRequest is never called before .Listen() is called
70+
func SendRequest[Res any](s *Server, method string, params any) (*Res, error) {
6971
bytes, err := json.Marshal(params)
7072
if err != nil {
7173
return nil, err
@@ -91,7 +93,9 @@ func SendRequest(s *Server, method string, params any) (any, error) {
9193
delete(s.pendingRequests, freshId)
9294
s.pendingRequestMu.Unlock()
9395

94-
return response, nil
96+
var res Res
97+
json.Unmarshal(response.Result, &res)
98+
return &res, nil
9599
}
96100

97101
// Send a json rpc request and wait for the message to be sent. Thread safe

internal/jsonrpc2/jsonrpc2_test.go

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package jsonrpc2_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/formancehq/numscript/internal/jsonrpc2"
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
func TestHandleRequest(t *testing.T) {
11+
type SumParams struct {
12+
X int `json:"x"`
13+
Y int `json:"y"`
14+
}
15+
16+
in := make(chan jsonrpc2.Message)
17+
out := make(chan jsonrpc2.Message)
18+
19+
server := jsonrpc2.NewServer(jsonrpc2.NewChanObjStream(in, out))
20+
jsonrpc2.HandleRequest(server, "sum", func(p SumParams) any {
21+
return p.X + p.Y
22+
})
23+
go server.Listen()
24+
defer server.Close()
25+
26+
client := jsonrpc2.NewServer(jsonrpc2.NewChanObjStream(out, in))
27+
go client.Listen()
28+
defer server.Close()
29+
30+
res, err := jsonrpc2.SendRequest[int](client, "sum", SumParams{X: 100, Y: 42})
31+
require.Nil(t, err)
32+
33+
require.Equal(t, 142, *res)
34+
}

0 commit comments

Comments
 (0)