-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbind_test.go
More file actions
408 lines (338 loc) · 8.98 KB
/
bind_test.go
File metadata and controls
408 lines (338 loc) · 8.98 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package cli_test
import (
"context"
"fmt"
"strings"
"testing"
"github.com/bjaus/bind"
"github.com/bjaus/cli"
)
type mockDB struct {
name string
}
type Cache interface {
Get(key string) string
}
type redisCache struct {
prefix string
}
func (r *redisCache) Get(key string) string {
return r.prefix + ":" + key
}
// bindTestCmd has a field that can be injected by type.
type bindTestCmd struct {
DB *mockDB // will be injected if bound
Port int `flag:"port" default:"8080"`
ran bool
}
func (c *bindTestCmd) Run(ctx context.Context) error {
c.ran = true
return nil
}
func TestBind(t *testing.T) {
db := &mockDB{name: "testdb"}
cmd := &bindTestCmd{}
err := cli.Execute(context.Background(), cmd, []string{},
cli.WithBindings(bind.Value(db)),
)
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if cmd.DB != db {
t.Errorf("DB not injected: got %v, want %v", cmd.DB, db)
}
if !cmd.ran {
t.Error("Run was not called")
}
}
type bindToCmd struct {
Cache Cache // interface field
}
func (c *bindToCmd) Run(ctx context.Context) error {
return nil
}
func TestBindTo(t *testing.T) {
cache := &redisCache{prefix: "test"}
cmd := &bindToCmd{}
err := cli.Execute(context.Background(), cmd, []string{},
cli.WithBindings(bind.Interface(cache, (*Cache)(nil))),
)
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if cmd.Cache == nil {
t.Fatal("Cache not injected")
}
if cmd.Cache.Get("foo") != "test:foo" {
t.Errorf("Cache.Get returned wrong value: %s", cmd.Cache.Get("foo"))
}
}
func TestBindNoMatchingBinding(t *testing.T) {
// When no binding matches, field remains zero (no error).
cmd := &bindTestCmd{}
err := cli.Execute(context.Background(), cmd, []string{},
cli.WithBindings(bind.Interface(&redisCache{}, (*Cache)(nil))),
)
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if cmd.DB != nil {
t.Error("DB should remain nil when not bound")
}
}
func TestBindNoBindingsProvided(t *testing.T) {
// When no Bind options are used, fields remain at zero value.
cmd := &bindTestCmd{}
err := cli.Execute(context.Background(), cmd, []string{})
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if cmd.DB != nil {
t.Error("DB should remain nil")
}
}
type flagOnlyCmd struct {
Port int `flag:"port" default:"8080"`
}
func (c *flagOnlyCmd) Run(ctx context.Context) error { return nil }
func TestBindSkipsFlagFields(t *testing.T) {
// Fields with flag tags should not be injected even if type matches.
c := &flagOnlyCmd{}
// Bind an int - it should NOT inject into Port because it has flag tag.
err := cli.Execute(context.Background(), c, []string{},
cli.WithBindings(bind.Value(9999)),
)
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if c.Port != 8080 {
t.Errorf("Port should be default 8080, got %d (was incorrectly injected)", c.Port)
}
}
// Test that bindings are available in subcommands.
type bindParentCmd struct {
DB *mockDB
}
func (c *bindParentCmd) Subcommands() []cli.Commander {
return []cli.Commander{&bindChildCmd{}}
}
func (c *bindParentCmd) Run(ctx context.Context) error {
return nil
}
type bindChildCmd struct {
DB *mockDB
Cache Cache
}
func (c *bindChildCmd) Name() string { return "child" }
func (c *bindChildCmd) Run(ctx context.Context) error {
return nil
}
func TestBindInChain(t *testing.T) {
db := &mockDB{name: "shared"}
cache := &redisCache{prefix: "child"}
parent := &bindParentCmd{}
err := cli.Execute(context.Background(), parent, []string{"child"},
cli.WithBindings(
bind.Value(db),
bind.Interface(cache, (*Cache)(nil)),
),
)
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if parent.DB != db {
t.Error("parent DB not injected")
}
}
type argsCmd struct {
Args cli.Args
ran bool
}
func (c *argsCmd) Run(ctx context.Context) error {
c.ran = true
return nil
}
func TestBindArgs(t *testing.T) {
cmd := &argsCmd{}
err := cli.Execute(context.Background(), cmd, []string{"foo", "bar", "baz"})
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if !cmd.ran {
t.Error("Run was not called")
}
want := cli.Args{"foo", "bar", "baz"}
if len(cmd.Args) != len(want) {
t.Fatalf("wrong args length: got %d, want %d", len(cmd.Args), len(want))
}
for i, arg := range cmd.Args {
if arg != want[i] {
t.Errorf("args[%d] = %q, want %q", i, arg, want[i])
}
}
}
type argsFlagsCmd struct {
Args cli.Args
Port int `flag:"port" default:"8080"`
}
func (c *argsFlagsCmd) Run(ctx context.Context) error {
return nil
}
// --- Provider ---
type providerCmd struct {
DB *mockDB
}
func (c *providerCmd) Run(_ context.Context) error { return nil }
func TestBindProvider(t *testing.T) {
calls := 0
cmd := &providerCmd{}
err := cli.Execute(context.Background(), cmd, []string{},
cli.WithBindings(bind.Provider(func() (*mockDB, error) {
calls++
return &mockDB{name: "provided"}, nil
})),
)
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if cmd.DB == nil || cmd.DB.name != "provided" {
t.Error("DB not injected by provider")
}
if calls != 1 {
t.Errorf("provider called %d times, want 1", calls)
}
}
func TestBindProvider_Error(t *testing.T) {
cmd := &providerCmd{}
err := cli.Execute(context.Background(), cmd, []string{},
cli.WithBindings(bind.Provider(func() (*mockDB, error) {
return nil, fmt.Errorf("connection failed")
})),
)
if err == nil {
t.Fatal("expected error from provider")
}
if !strings.Contains(err.Error(), "connection failed") {
t.Errorf("error should contain provider error: %v", err)
}
}
// --- Singleton ---
func TestBindSingleton(t *testing.T) {
calls := 0
db := &mockDB{name: "singleton"}
cmd := &providerCmd{}
err := cli.Execute(context.Background(), cmd, []string{},
cli.WithBindings(bind.Singleton(func() (*mockDB, error) {
calls++
return db, nil
})),
)
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if cmd.DB != db {
t.Error("DB not injected by singleton")
}
if calls != 1 {
t.Errorf("singleton called %d times, want 1", calls)
}
}
type singletonParentCmd struct {
DB *mockDB
}
func (c *singletonParentCmd) Run(_ context.Context) error { return nil }
func (c *singletonParentCmd) Subcommands() []cli.Commander {
return []cli.Commander{&singletonChildCmd{}}
}
type singletonChildCmd struct {
DB *mockDB
}
func (c *singletonChildCmd) Name() string { return "child" }
func (c *singletonChildCmd) Run(_ context.Context) error { return nil }
func TestBindSingleton_CachedAcrossChain(t *testing.T) {
calls := 0
parent := &singletonParentCmd{}
err := cli.Execute(context.Background(), parent, []string{"child"},
cli.WithBindings(bind.Singleton(func() (*mockDB, error) {
calls++
return &mockDB{name: "shared"}, nil
})),
)
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
// Singleton should be called once but injected into both parent and child.
if calls != 1 {
t.Errorf("singleton called %d times, want 1", calls)
}
if parent.DB == nil || parent.DB.name != "shared" {
t.Error("parent DB not injected")
}
}
func TestBindSingleton_Error(t *testing.T) {
cmd := &providerCmd{}
err := cli.Execute(context.Background(), cmd, []string{},
cli.WithBindings(bind.Singleton(func() (*mockDB, error) {
return nil, fmt.Errorf("init failed")
})),
)
if err == nil {
t.Fatal("expected error from singleton")
}
if !strings.Contains(err.Error(), "init failed") {
t.Errorf("error should contain singleton error: %v", err)
}
}
func TestBindArgsWithFlags(t *testing.T) {
c := &argsFlagsCmd{}
err := cli.Execute(context.Background(), c, []string{"--port", "3000", "file1.txt", "file2.txt"})
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if c.Port != 3000 {
t.Errorf("Port = %d, want 3000", c.Port)
}
if len(c.Args) != 2 || c.Args[0] != "file1.txt" || c.Args[1] != "file2.txt" {
t.Errorf("Args = %v, want [file1.txt file2.txt]", c.Args)
}
}
// contextLookupCmd demonstrates using bind.Get[T](ctx) in Run.
type contextLookupCmd struct {
DB *mockDB // still populated via struct injection
// These are set in Run to verify context lookup works.
gotDB *mockDB
gotCache Cache
}
func (c *contextLookupCmd) Run(ctx context.Context) error {
// Use context-based lookup instead of struct injection.
c.gotDB = bind.Get[*mockDB](ctx)
c.gotCache = bind.Get[Cache](ctx)
return nil
}
func TestBindContextLookup(t *testing.T) {
db := &mockDB{name: "context-test"}
cache := &redisCache{prefix: "ctx"}
cmd := &contextLookupCmd{}
err := cli.Execute(context.Background(), cmd, []string{},
cli.WithBindings(
bind.Value(db),
bind.Interface(cache, (*Cache)(nil)),
),
)
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
// Struct injection should work.
if cmd.DB != db {
t.Errorf("struct injection: DB = %v, want %v", cmd.DB, db)
}
// Context lookup should also work.
if cmd.gotDB != db {
t.Errorf("bind.Get[*mockDB]: got %v, want %v", cmd.gotDB, db)
}
if cmd.gotCache == nil {
t.Error("bind.Get[Cache] returned nil")
} else if cmd.gotCache.Get("key") != "ctx:key" {
t.Errorf("bind.Get[Cache].Get(key) = %q, want %q", cmd.gotCache.Get("key"), "ctx:key")
}
}