Files
numscript/internal/jsonrpc2/jsonrpc2_test.go
Maxence MaireauxGitHubcoderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
3dc4fdbe11 feat: Use Nix & Shipfox & Just for DevXP (#77)
* feat: add Nix flake for Go 1.23 development environment

* feat: add .envrc and Justfile for environment setup; remove obsolete scripts

* feat: add antlr to Nix flake dependencies

* chore: update ANTLR version in generated files to 4.13.2

* feat: add GitHub Actions for environment setup and release management; remove obsolete workflows

* chore: remove SPEAKEASY_API_KEY from workflows to streamline environment variables

* refactor: simplify range checks in hover functions and update variable end position

* refactor: improve error handling and logging across multiple files

* feat: Update flake.nix

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-07-15 15:15:31 +02:00

79 lines
1.8 KiB
Go

package jsonrpc2_test
import (
"encoding/json"
"testing"
"github.com/formancehq/numscript/internal/jsonrpc2"
"github.com/stretchr/testify/require"
)
func TestHandleRequest(t *testing.T) {
type SumParams struct {
X int `json:"x"`
Y int `json:"y"`
}
client := newClient(
jsonrpc2.NewRequestHandler("sum", jsonrpc2.AsyncHandling, func(p SumParams, conn *jsonrpc2.Conn) any {
return p.X + p.Y
}),
)
raw, err := client.SendRequest("sum", SumParams{X: 100, Y: 42})
require.Nil(t, err)
var res int
e := json.Unmarshal(raw, &res)
require.Nil(t, e)
require.Equal(t, 142, res)
}
func TestHandleNotification(t *testing.T) {
type NotifParams struct {
Value string `json:"value"`
}
ch := make(chan string)
client := newClient(
jsonrpc2.NewNotificationHandler("greet", jsonrpc2.AsyncHandling, func(p NotifParams, conn *jsonrpc2.Conn) {
ch <- p.Value
}),
)
err := client.SendNotification("greet", NotifParams{
Value: "Hello!",
})
require.NoError(t, err)
require.Equal(t, "Hello!", <-ch)
}
func TestErrMethodNotFound(t *testing.T) {
client := newClient()
_, err := client.SendRequest("notImplementedMethod", nil)
require.Equal(t, &jsonrpc2.ErrMethodNotFound, err)
}
func TestErrIvalidParam(t *testing.T) {
client := newClient(
jsonrpc2.NewRequestHandler("capitalize", jsonrpc2.AsyncHandling, func(name string, conn *jsonrpc2.Conn) any {
return name + "!"
}),
)
_, err := client.SendRequest("capitalize", 42)
require.Equal(t, &jsonrpc2.ErrInvalidParams, err)
}
func newClient(serverHandlers ...jsonrpc2.Handler) *jsonrpc2.Conn {
in := make(chan jsonrpc2.Message)
out := make(chan jsonrpc2.Message)
jsonrpc2.NewConn(jsonrpc2.NewChanObjStream(in, out), serverHandlers...)
client := jsonrpc2.NewConn(jsonrpc2.NewChanObjStream(out, in))
return client
}