-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtyped_test.go
More file actions
84 lines (67 loc) · 1.99 KB
/
Copy pathtyped_test.go
File metadata and controls
84 lines (67 loc) · 1.99 KB
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
package jsonrpc
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestTypedRPC(t *testing.T) {
t.Run("successful handling", func(t *testing.T) {
handler := TypedRPC(func(ctx context.Context, params string) (int, error) {
if params == "test" {
return 42, nil
}
return 0, errors.New("invalid input")
})
params, _ := json.Marshal("test")
result, err := handler(context.Background(), params)
assert.NoError(t, err)
var value int
err = json.Unmarshal(result, &value)
assert.NoError(t, err)
assert.Equal(t, 42, value)
})
t.Run("invalid params", func(t *testing.T) {
handler := TypedRPC(func(ctx context.Context, params int) (string, error) {
return "result", nil
})
// Invalid JSON for an int
result, err := handler(context.Background(), json.RawMessage(`"not an int"`))
assert.Error(t, err)
assert.Equal(t, ErrInvalidParams, err)
assert.Nil(t, result)
})
t.Run("handler error", func(t *testing.T) {
expectedErr := errors.New("handler error")
handler := TypedRPC(func(ctx context.Context, params string) (int, error) {
return 0, expectedErr
})
params, _ := json.Marshal("test")
result, err := handler(context.Background(), params)
assert.Error(t, err)
assert.Equal(t, expectedErr, err)
assert.Nil(t, result)
})
}
func TestTypedSubscription(t *testing.T) {
t.Run("successful subscription", func(t *testing.T) {
called := false
handler := TypedSubscription(func(ctx context.Context, params string) {
called = true
assert.Equal(t, "test", params)
})
params, _ := json.Marshal("test")
handler(context.Background(), params)
assert.True(t, called)
})
t.Run("invalid params", func(t *testing.T) {
called := false
handler := TypedSubscription(func(ctx context.Context, params int) {
called = true
})
// Invalid JSON for an int
handler(context.Background(), json.RawMessage(`"not an int"`))
assert.False(t, called, "Handler should not be called with invalid params")
})
}