-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
handler_test.go
74 lines (60 loc) · 2.2 KB
/
handler_test.go
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
package jsonrpc_test
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/goccy/go-json"
"github.com/osamingo/jsonrpc/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHandler(t *testing.T) {
t.Parallel()
mr := jsonrpc.NewMethodRepository()
rec := httptest.NewRecorder()
r, err := http.NewRequestWithContext(context.Background(), "", "", nil)
require.NoError(t, err)
mr.ServeHTTP(rec, r)
res := jsonrpc.Response{}
err = json.NewDecoder(rec.Body).Decode(&res)
require.NoError(t, err)
assert.NotNil(t, res.Error)
rec = httptest.NewRecorder()
r, err = http.NewRequestWithContext(context.Background(), "", "", bytes.NewReader([]byte(`{"jsonrpc":"2.0","id":"test","method":"hello","params":{}}`)))
require.NoError(t, err)
r.Header.Set("Content-Type", "application/json")
mr.ServeHTTP(rec, r)
res = jsonrpc.Response{}
err = json.NewDecoder(rec.Body).Decode(&res)
require.NoError(t, err)
assert.NotNil(t, res.Error)
h1 := jsonrpc.HandlerFunc(func(c context.Context, params *json.RawMessage) (any, *jsonrpc.Error) {
return "hello", nil
})
require.NoError(t, mr.RegisterMethod("hello", h1, nil, nil))
h2 := jsonrpc.HandlerFunc(func(c context.Context, params *json.RawMessage) (any, *jsonrpc.Error) {
return nil, jsonrpc.ErrInternal()
})
require.NoError(t, mr.RegisterMethod("bye", h2, nil, nil))
rec = httptest.NewRecorder()
r, err = http.NewRequestWithContext(context.Background(), "", "", bytes.NewReader([]byte(`{"jsonrpc":"2.0","id":"test","method":"hello","params":{}}`)))
require.NoError(t, err)
r.Header.Set("Content-Type", "application/json")
mr.ServeHTTP(rec, r)
res = jsonrpc.Response{}
err = json.NewDecoder(rec.Body).Decode(&res)
require.NoError(t, err)
assert.Nil(t, res.Error)
assert.Equal(t, "hello", res.Result)
rec = httptest.NewRecorder()
r, err = http.NewRequestWithContext(context.Background(), "", "", bytes.NewReader([]byte(`{"jsonrpc":"2.0","id":"test","method":"bye","params":{}}`)))
require.NoError(t, err)
r.Header.Set("Content-Type", "application/json")
mr.ServeHTTP(rec, r)
res = jsonrpc.Response{}
err = json.NewDecoder(rec.Body).Decode(&res)
require.NoError(t, err)
assert.NotNil(t, res.Error)
}