-
Notifications
You must be signed in to change notification settings - Fork 10
/
code_test.go
102 lines (93 loc) · 2.64 KB
/
code_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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Copyright (C) 2017 Michael J. Fromberger. All Rights Reserved.
package jrpc2_test
import (
"context"
"errors"
"fmt"
"io"
"testing"
"github.com/creachadair/jrpc2"
)
type testCoder jrpc2.Code
func (t testCoder) ErrCode() jrpc2.Code { return jrpc2.Code(t) }
func (testCoder) Error() string { return "bogus" }
func TestErrorCode(t *testing.T) {
tests := []struct {
input error
want jrpc2.Code
}{
{nil, jrpc2.NoError},
{testCoder(jrpc2.ParseError), jrpc2.ParseError},
{testCoder(jrpc2.InvalidRequest), jrpc2.InvalidRequest},
{fmt.Errorf("wrapped parse error: %w", jrpc2.ParseError.Err()), jrpc2.ParseError},
{context.Canceled, jrpc2.Cancelled},
{fmt.Errorf("wrapped cancellation: %w", context.Canceled), jrpc2.Cancelled},
{context.DeadlineExceeded, jrpc2.DeadlineExceeded},
{fmt.Errorf("wrapped deadline: %w", context.DeadlineExceeded), jrpc2.DeadlineExceeded},
{errors.New("other"), jrpc2.SystemError},
{io.EOF, jrpc2.SystemError},
}
for _, test := range tests {
if got := jrpc2.ErrorCode(test.input); got != test.want {
t.Errorf("ErrorCode(%v): got %v, want %v", test.input, got, test.want)
}
}
}
func TestCodeIs(t *testing.T) {
tests := []struct {
code jrpc2.Code
err error
want bool
}{
{jrpc2.NoError, nil, true},
{0, nil, false},
{1, jrpc2.Code(1).Err(), true},
{2, jrpc2.Code(3).Err(), false},
{4, fmt.Errorf("blah: %w", jrpc2.Code(4).Err()), true},
{5, fmt.Errorf("nope: %w", jrpc2.Code(6).Err()), false},
}
for _, test := range tests {
cerr := test.code.Err()
got := errors.Is(test.err, cerr)
if got != test.want {
t.Errorf("Is(%v, %v): got %v, want %v", test.err, cerr, got, test.want)
}
}
}
func TestErr(t *testing.T) {
eqv := func(e1, e2 error) bool {
return e1 == e2 || (e1 != nil && e2 != nil && e1.Error() == e2.Error())
}
type test struct {
code jrpc2.Code
want error
}
tests := []test{
{jrpc2.NoError, nil},
{0, errors.New("error code 0")},
{1, errors.New("error code 1")},
{-17, errors.New("error code -17")},
}
// Make sure all the pre-defined errors get their messages hit.
for _, v := range []int32{
// Codes reserved by the JSON-RPC 2.0 spec.
-32700, -32600, -32601, -32602, -32603,
// Codes reserved by this implementation.
-32098, -32097, -32096,
} {
c := jrpc2.Code(v)
tests = append(tests, test{
code: c,
want: errors.New(c.String()),
})
}
for _, test := range tests {
got := test.code.Err()
if !eqv(got, test.want) {
t.Errorf("Code(%d).Err(): got %#v, want %#v", test.code, got, test.want)
}
if c := jrpc2.ErrorCode(got); c != test.code {
t.Errorf("Code(%d).Err(): got code %v, want %v", test.code, c, test.code)
}
}
}