-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodec_test.go
More file actions
284 lines (242 loc) · 7.79 KB
/
Copy pathcodec_test.go
File metadata and controls
284 lines (242 loc) · 7.79 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package strut
// The two parsers that read untrusted input: component state out of a
// custom_id, and arguments out of a prefix message. Both are fuzzed.
import (
"reflect"
"strings"
"testing"
"github.com/disgoorg/snowflake/v2"
)
// The custom_id codec is the one place component state crosses a process
// boundary, so a wrong encoding silently corrupts every button.
type PageBtn struct {
Page int `strut:"p"`
Owner snowflake.ID `strut:"u"`
Open bool `strut:"o"`
}
func TestStateCodecRoundTrip(t *testing.T) {
c, err := newStateCodec(reflect.TypeFor[PageBtn]())
if err != nil {
t.Fatalf("newStateCodec: %v", err)
}
if want := "/c/PageBtn/{p}/{u}/{o}"; c.route != want {
t.Errorf("route = %q; want %q", c.route, want)
}
in := PageBtn{Page: 2, Owner: 123456789012345678, Open: true}
id, err := c.encode(reflect.ValueOf(in))
if err != nil {
t.Fatalf("encode: %v", err)
}
if want := "/c/PageBtn/2/123456789012345678/1"; id != want {
t.Fatalf("custom_id = %q; want %q", id, want)
}
// The router splits the id into vars; decoding reverses the encoding.
out, err := c.decode(map[string]string{"p": "2", "u": "123456789012345678", "o": "1"})
if err != nil {
t.Fatalf("decode: %v", err)
}
if got := out.Interface().(PageBtn); got != in {
t.Errorf("round trip = %+v; want %+v", got, in)
}
}
func TestStateCodecIsStableAcrossRestarts(t *testing.T) {
// The id embeds the type name, not a registration index, so a button
// created before a restart still routes afterwards.
c1, _ := newStateCodec(reflect.TypeFor[PageBtn]())
c2, _ := newStateCodec(reflect.TypeFor[PageBtn]())
if c1.route != c2.route {
t.Errorf("route changed between builds: %q vs %q", c1.route, c2.route)
}
}
func TestStateCodecMissingVarStaysZero(t *testing.T) {
c, _ := newStateCodec(reflect.TypeFor[PageBtn]())
// A field added after a component was created has no var to read.
out, err := c.decode(map[string]string{"p": "5"})
if err != nil {
t.Fatalf("decode: %v", err)
}
got := out.Interface().(PageBtn)
if got.Page != 5 || got.Owner != 0 || got.Open {
t.Errorf("got %+v; want only Page set", got)
}
}
func TestStateCodecRejectsOversizedID(t *testing.T) {
c, _ := newStateCodec(reflect.TypeFor[longState]())
_, err := c.encode(reflect.ValueOf(longState{Note: strings.Repeat("x", maxCustomID)}))
if err == nil {
t.Fatal("encode = nil error; want the 100 character limit enforced")
}
if !strings.Contains(err.Error(), "max 100") {
t.Errorf("error = %v; want it to name the limit", err)
}
}
func TestStateCodecRejectsSlash(t *testing.T) {
c, _ := newStateCodec(reflect.TypeFor[longState]())
// A slash would be read as a field separator.
if _, err := c.encode(reflect.ValueOf(longState{Note: "a/b"})); err == nil {
t.Error("encode = nil error; want a slash rejected")
}
}
func TestStateCodecRejectsUnstorableField(t *testing.T) {
_, err := newStateCodec(reflect.TypeFor[badState]())
if err == nil {
t.Fatal("newStateCodec = nil error; want an unstorable field rejected")
}
if !strings.Contains(err.Error(), "cannot be stored") {
t.Errorf("error = %v", err)
}
}
// FuzzStateCodec checks decoding arbitrary path variables never panics.
func FuzzStateCodec(f *testing.F) {
for _, seed := range []string{"1", "", "-3", "99999999999999999999", "x"} {
f.Add(seed)
}
c, err := newStateCodec(reflect.TypeFor[PageBtn]())
if err != nil {
f.Fatal(err)
}
f.Fuzz(func(t *testing.T, raw string) {
// Errors are fine; panics are not.
_, _ = c.decode(map[string]string{"p": raw, "u": raw, "o": raw})
})
}
type longState struct {
Note string `strut:"n"`
}
type badState struct {
Ch chan int `strut:"c"`
}
func tokens(s string) []string {
l := NewLexer(s)
var out []string
for {
tok, ok := l.Next()
if !ok {
return out
}
out = append(out, tok)
}
}
func TestLexerNext(t *testing.T) {
tests := []struct {
name string
in string
want []string
}{
{"empty", "", nil},
{"whitespace only", " \t ", nil},
{"plain", "a b c", []string{"a", "b", "c"}},
{"collapses runs", " a \t\n b ", []string{"a", "b"}},
{"quoted", `a "b c" d`, []string{"a", "b c", "d"}},
{"empty quotes", `a "" b`, []string{"a", "", "b"}},
{"escaped quote", `"say \"hi\""`, []string{`say "hi"`}},
{"escaped backslash", `"a\\b"`, []string{`a\b`}},
{"unterminated quote", `a "b c`, []string{"a", "b c"}},
{"trailing backslash", `"a\`, []string{`a\`}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tokens(tt.in); !reflect.DeepEqual(got, tt.want) {
t.Errorf("tokens(%q) = %q; want %q", tt.in, got, tt.want)
}
})
}
}
func TestLexerRest(t *testing.T) {
l := NewLexer(`ban some long "reason here" `)
if tok, _ := l.Next(); tok != "ban" {
t.Fatalf("first token = %q; want ban", tok)
}
// Rest is raw: quotes are not interpreted and trailing space is kept.
if got, want := l.Rest(), `some long "reason here" `; got != want {
t.Errorf("Rest = %q; want %q", got, want)
}
if !l.Empty() {
t.Error("lexer should be empty after Rest")
}
}
func FuzzLexer(f *testing.F) {
for _, seed := range []string{"", `a "b c"`, `"unterminated`, `a\`, " \t ", `"a\\"`} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, in string) {
l := NewLexer(in)
for range len(in) + 1 {
if _, ok := l.Next(); !ok {
return
}
}
t.Fatalf("lexer produced more tokens than input bytes: %q", in)
})
}
// Every component is built the same way, so the decorations must work
// uniformly rather than only on buttons.
func TestComponentDecorations(t *testing.T) {
state := PageBtn{Page: 1}
built := map[string]Component{
"button": Button(state, "Go", Primary),
"link": LinkButton("Docs", "https://example.com"),
"select": Select(state, "Pick", Choice[string]{Name: "One", Value: "1"}),
"user": UserSelect(state, "Who"),
"role": RoleSelect(state, "Roles"),
"channel": ChannelSelect(state, "Where"),
"mentionable": MentionableSelect(state, "Anyone"),
}
for name, c := range built {
t.Run(name, func(t *testing.T) {
if c.err != nil {
t.Fatalf("build: %v", c.err)
}
// Disabling must reach every kind, not just buttons.
if got := c.WithDisabled(true); got.err != nil {
t.Errorf("WithDisabled: %v", got.err)
}
if r := Content("x").Row(c); r.err != nil {
t.Errorf("Row: %v", r.err)
}
})
}
}
func TestSelectRange(t *testing.T) {
ok := UserSelect(PageBtn{}, "Who").WithRange(1, 5)
if ok.err != nil {
t.Fatalf("WithRange: %v", ok.err)
}
// A range only means something for a menu.
if bad := Button(PageBtn{}, "Go", Primary).WithRange(1, 5); bad.err == nil {
t.Error("WithRange on a button should fail")
}
if bad := UserSelect(PageBtn{}, "Who").WithRange(3, 1); bad.err == nil {
t.Error("an impossible range should fail")
}
}
func TestRowSurfacesComponentError(t *testing.T) {
// A component that failed to build must not be sent silently.
broken := Button(longState{Note: strings.Repeat("x", 200)}, "Go", Primary)
r := Content("x").Row(broken)
if r.err == nil {
t.Fatal("Row swallowed a failed component")
}
if len(r.Components) != 0 {
t.Error("a row with a failed component was added anyway")
}
}
// Every kind of component a reply can carry needs somewhere for the click to
// go, or it is decoration.
func TestEveryComponentHasAHandler(t *testing.T) {
f := New[testData](nil)
f.OnComponent(func(*Event[testData], PageBtn) error { return nil })
f.OnSelect(func(*Event[testData], longState, []string) error { return nil })
f.OnEntitySelect(func(*Event[testData], badRoute, []snowflake.ID) error { return nil })
if err := f.Validate(); err != nil {
t.Fatalf("Validate: %v", err)
}
for _, route := range []string{"/c/PageBtn/{p}/{u}/{o}", "/c/longState/{n}", "/c/badRoute/{v}"} {
if _, ok := f.paths[route]; !ok {
t.Errorf("no handler registered at %s", route)
}
}
}
type badRoute struct {
V int `strut:"v"`
}