-
Notifications
You must be signed in to change notification settings - Fork 4
/
hive_test.go
557 lines (471 loc) · 14 KB
/
hive_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
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package hive_test
import (
"context"
"errors"
"fmt"
"log/slog"
"sync"
"testing"
"time"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/cilium/hive"
"github.com/cilium/hive/cell"
"github.com/cilium/hive/hivetest"
)
type Config struct {
Foo string
Bar int
}
func (Config) Flags(flags *pflag.FlagSet) {
flags.String("foo", "hello world", "sets the greeting")
flags.Int("bar", 123, "bar")
}
func TestHiveGoodConfig(t *testing.T) {
var cfg Config
testCell := cell.Module(
"test",
"Test Module",
cell.Config(Config{}),
cell.Invoke(func(c Config) {
cfg = c
}),
)
hive := hive.New(testCell)
flags := pflag.NewFlagSet("", pflag.ContinueOnError)
hive.RegisterFlags(flags)
// Test the two ways of setting it
flags.Set("foo", "test")
hive.Viper().Set("bar", 13)
log := hivetest.Logger(t)
err := hive.Start(log, context.TODO())
assert.NoError(t, err, "expected Start to succeed")
err = hive.Stop(log, context.TODO())
assert.NoError(t, err, "expected Stop to succeed")
assert.Equal(t, "test", cfg.Foo, "Config.Foo not set correctly")
assert.Equal(t, 13, cfg.Bar, "Config.Bar not set correctly")
}
// BadConfig has a field that matches no flags, and Flags
// declares a flag that matches no field.
type BadConfig struct {
Bar string
}
func (BadConfig) Flags(flags *pflag.FlagSet) {
flags.String("foo", "foobar", "foo")
}
func TestHiveBadConfig(t *testing.T) {
testCell := cell.Module(
"test",
"Test Module",
cell.Config(BadConfig{}),
cell.Invoke(func(c BadConfig) {}),
)
hive := hive.New(testCell)
err := hive.Start(hivetest.Logger(t), context.TODO())
assert.ErrorContains(t, err, "has invalid keys: foo", "expected 'invalid keys' error")
assert.ErrorContains(t, err, "has unset fields: Bar", "expected 'unset fields' error")
}
type MapConfig struct {
Foo map[string]string
}
func (MapConfig) Flags(flags *pflag.FlagSet) {
flags.StringToString("foo", nil, "foo")
}
func TestHiveConfigOverride(t *testing.T) {
var cfg Config
h := hive.New(
cell.Config(Config{}),
cell.Invoke(func(c Config) {
cfg = c
}),
)
hive.AddConfigOverride(
h,
func(cfg *Config) {
cfg.Foo = "override"
})
// Set "foo" flag via Viper. This should be ignored.
h.Viper().Set("foo", "viper")
log := hivetest.Logger(t)
err := h.Start(log, context.TODO())
assert.NoError(t, err, "expected Start to succeed")
err = h.Stop(log, context.TODO())
assert.NoError(t, err, "expected Stop to succeed")
assert.Equal(t, "override", cfg.Foo, "Config.Foo not set correctly")
}
type StringSliceConfig struct {
SpacesFlag, CommasFlag []string
SpacesMap, CommasMap []string
Mixed []string
StringFlag string
}
func (StringSliceConfig) Flags(flags *pflag.FlagSet) {
flags.StringSlice("spaces-flag", nil, "split by spaces via pflag")
flags.StringSlice("commas-flag", nil, "split by commas via pflag")
flags.StringSlice("spaces-map", nil, "split by spaces via configmap")
flags.StringSlice("commas-map", nil, "split by commas via configmap")
// One can also use just flags.String against a []string config field and
// it will be parsed the same way as via configmap.
flags.String("mixed", "", "mixed")
flags.String("string-flag", "", "plain string untouched")
}
func TestHiveStringSlice(t *testing.T) {
var cfg StringSliceConfig
testCell := cell.Module(
"test",
"Test Module",
cell.Config(StringSliceConfig{}),
cell.Invoke(func(c StringSliceConfig) {
cfg = c
}),
)
hive := hive.New(testCell)
flags := pflag.NewFlagSet("", pflag.ContinueOnError)
hive.RegisterFlags(flags)
spaces := "foo bar baz"
commas := "foo,bar,baz"
expected := []string{"foo", "bar", "baz"}
// When the values are provided via the flags then the value given
// to Viper is already a []string as parsed by pflag. This will be
// processed by stringSliceToStringSliceHookFunc to re-split if needed.
flags.Set("spaces-flag", spaces)
flags.Set("commas-flag", commas)
// Plain string flags are not split in any way.
flags.Set("string-flag", "foo, bar, baz")
// If spaces and commas are mixed then commas take precedence.
flags.Set("mixed", "foo bar,baz")
// When the values are provided via the configmap or environment they're
// given to Viper as plain strings that will be processed by stringToSliceHookFunc.
hive.Viper().MergeConfigMap(
map[string]any{
"spaces-map": spaces,
"commas-map": commas,
})
log := hivetest.Logger(t)
err := hive.Start(log, context.TODO())
require.NoError(t, err, "expected Start to succeed")
err = hive.Stop(log, context.TODO())
require.NoError(t, err, "expected Stop to succeed")
assert.ElementsMatch(t, cfg.SpacesFlag, expected, "unexpected SpacesFlag")
assert.ElementsMatch(t, cfg.SpacesMap, expected, "unexpected SpacesMap")
assert.ElementsMatch(t, cfg.CommasFlag, expected, "unexpected CommasFlag")
assert.ElementsMatch(t, cfg.CommasMap, expected, "unexpected CommasMap")
assert.ElementsMatch(t, cfg.Mixed, []string{"foo bar", "baz"}, "unexpected Mixed")
assert.Equal(t, cfg.StringFlag, "foo, bar, baz", "unexpected StringFlag")
}
type SomeObject struct {
X int
}
type OtherObject struct {
Y int
}
func TestProvideInvoke(t *testing.T) {
invoked := false
testCell := cell.Module(
"test",
"Test Module",
cell.Provide(func() *SomeObject { return &SomeObject{10} }),
cell.Invoke(func(*SomeObject) { invoked = true }),
)
err := hive.New(
testCell,
shutdownOnStartCell,
).Run(hivetest.Logger(t))
assert.NoError(t, err, "expected Run to succeed")
assert.True(t, invoked, "expected invoke to be called, but it was not")
}
func TestModuleID(t *testing.T) {
invoked := false
inner := cell.Module(
"inner",
"inner module",
cell.Invoke(func(id cell.ModuleID, fid cell.FullModuleID) error {
invoked = true
if id != "inner" {
return fmt.Errorf("inner id mismatch, expected 'inner', got %q", id)
}
if fid.String() != "outer.inner" {
return fmt.Errorf("outer id mismatch, expected 'outer.inner', got %q", fid)
}
return nil
}),
)
outer := cell.Module(
"outer",
"outer module",
inner,
)
err := hive.New(
outer,
shutdownOnStartCell,
).Run(hivetest.Logger(t))
assert.NoError(t, err, "expected Run to succeed")
assert.True(t, invoked, "expected invoke to be called, but it was not")
}
func TestGroup(t *testing.T) {
sum := 0
testCell := cell.Group(
cell.Provide(func() *SomeObject { return &SomeObject{10} }),
cell.Provide(func() *OtherObject { return &OtherObject{5} }),
)
err := hive.New(
testCell,
cell.Invoke(func(a *SomeObject, b *OtherObject) { sum = a.X + b.Y }),
shutdownOnStartCell,
).Run(hivetest.Logger(t))
assert.NoError(t, err, "expected Run to succeed")
assert.Equal(t, 15, sum)
}
func TestProvidePrivate(t *testing.T) {
invoked := false
testCell := cell.Module(
"test",
"Test Module",
cell.ProvidePrivate(func() *SomeObject { return &SomeObject{10} }),
cell.Invoke(func(*SomeObject) { invoked = true }),
)
// Test happy path.
err := hive.New(
testCell,
shutdownOnStartCell,
).Run(hivetest.Logger(t))
assert.NoError(t, err, "expected Start to succeed")
if !invoked {
t.Fatal("expected invoke to be called, but it was not")
}
// Now test that we can't access it from root scope.
h := hive.New(
testCell,
cell.Invoke(func(*SomeObject) {}),
shutdownOnStartCell,
)
err = h.Start(hivetest.Logger(t), context.TODO())
assert.ErrorContains(t, err, "missing type: *hive_test.SomeObject", "expected Start to fail to find *SomeObject")
}
func TestDecorate(t *testing.T) {
invoked := false
testCell := cell.Decorate(
func(o *SomeObject) *SomeObject {
return &SomeObject{X: o.X + 1}
},
cell.Invoke(
func(o *SomeObject) error {
if o.X != 2 {
return errors.New("X != 2")
}
invoked = true
return nil
}),
)
hive := hive.New(
cell.Provide(func() *SomeObject { return &SomeObject{1} }),
// Here *SomeObject is not decorated.
cell.Invoke(func(o *SomeObject) error {
if o.X != 1 {
return errors.New("X != 1")
}
return nil
}),
testCell,
shutdownOnStartCell,
)
assert.NoError(t, hive.Run(hivetest.Logger(t)), "expected Run() to succeed")
assert.True(t, invoked, "expected decorated invoke function to be called")
}
func TestDecorateAll(t *testing.T) {
rootX, testX, test2Int := 0, 0, 0
type rootInt int
hive := hive.New(
cell.Module("test", "test",
cell.Provide(func() *SomeObject { return &SomeObject{1} }),
cell.Invoke(func(o *SomeObject) { testX = o.X }),
),
cell.Module("test2", "test2",
cell.Provide(func(o *SomeObject) int { return o.X }),
),
cell.Invoke(func(o *SomeObject, x int) {
rootX = o.X
test2Int = x
}),
cell.DecorateAll(
func(o *SomeObject) *SomeObject {
return &SomeObject{X: o.X + 1}
},
),
shutdownOnStartCell,
)
assert.NoError(t, hive.Run(hivetest.Logger(t)), "expected Run() to succeed")
assert.Equal(t, 2, rootX, "expected object at root scope to have X=2")
assert.Equal(t, 2, testX, "expected object in test module scope to have X=2")
assert.Equal(t, 2, test2Int, "expected object in test module scope to be 2")
}
func TestShutdown(t *testing.T) {
//
// Happy paths without a shutdown error:
//
// Test from a start hook
h := hive.New(
cell.Invoke(func(lc cell.Lifecycle, shutdowner hive.Shutdowner) {
lc.Append(cell.Hook{
OnStart: func(cell.HookContext) error {
shutdowner.Shutdown()
return nil
}})
}),
)
assert.NoError(t, h.Run(hivetest.Logger(t)), "expected Run() to succeed")
// Test from a goroutine forked from start hook
h = hive.New(
cell.Invoke(func(lc cell.Lifecycle, shutdowner hive.Shutdowner) {
lc.Append(cell.Hook{
OnStart: func(cell.HookContext) error {
go shutdowner.Shutdown()
return nil
}})
}),
)
assert.NoError(t, h.Run(hivetest.Logger(t)), "expected Run() to succeed")
// Test from an invoke. Shouldn't really be used, but should still work.
h = hive.New(
cell.Invoke(func(lc cell.Lifecycle, shutdowner hive.Shutdowner) {
shutdowner.Shutdown()
}),
)
assert.NoError(t, h.Run(hivetest.Logger(t)), "expected Run() to succeed")
//
// Unhappy paths that fatal with an error:
//
shutdownErr := errors.New("shutdown error")
// Test from a start hook
h = hive.New(
cell.Invoke(func(lc cell.Lifecycle, shutdowner hive.Shutdowner) {
lc.Append(cell.Hook{
OnStart: func(cell.HookContext) error {
shutdowner.Shutdown(hive.ShutdownWithError(shutdownErr))
return nil
}})
}),
)
assert.ErrorIs(t, h.Run(hivetest.Logger(t)), shutdownErr, "expected Run() to fail with shutdownErr")
}
func TestRunRollback(t *testing.T) {
var started, stopped int
opts := hive.DefaultOptions()
opts.StartTimeout = time.Millisecond
h := hive.NewWithOptions(
opts,
cell.Invoke(func(lc cell.Lifecycle, shutdowner hive.Shutdowner) {
lc.Append(cell.Hook{
OnStart: func(ctx cell.HookContext) error {
started++
return nil
},
OnStop: func(ctx cell.HookContext) error {
stopped++
return nil
},
})
lc.Append(cell.Hook{
OnStart: func(ctx cell.HookContext) error {
started++
<-ctx.Done()
return ctx.Err()
},
OnStop: func(cell.HookContext) error {
// Should not be called.
t.Fatal("unexpected call to second OnStop")
return nil
},
})
}),
)
err := h.Run(hivetest.Logger(t))
assert.ErrorIs(t, err, context.DeadlineExceeded, "expected Run() to fail with timeout")
// We should see 2 start hooks invoked, and then 1 stop hook as first
// one is rolled back.
assert.Equal(t, 2, started)
assert.Equal(t, 1, stopped)
}
var shutdownOnStartCell = cell.Invoke(func(lc cell.Lifecycle, shutdowner hive.Shutdowner) {
lc.Append(cell.Hook{
OnStart: func(cell.HookContext) error {
shutdowner.Shutdown()
return nil
}})
})
// Assert that we can reuse the same cell as part of multiple hives
func TestSameCellMultipleHives(t *testing.T) {
var (
got1 string
got2 int
)
common := cell.Group(
cell.Config(Config{}),
cell.Provide(func() int { return 10 }),
cell.Invoke(func(_ Config, in1 string, in2 int) { got1, got2 = in1, in2 }),
)
h1 := hive.New(common, cell.Provide(func() string { return "foo" }))
h2 := hive.New(common, cell.Provide(func() string { return "bar" }))
log := hivetest.Logger(t)
require.NoError(t, h1.Start(log, context.TODO()))
require.Equal(t, "foo", got1)
require.Equal(t, 10, got2)
require.NoError(t, h2.Start(log, context.TODO()))
require.Equal(t, "bar", got1)
require.Equal(t, 10, got2)
require.NoError(t, h1.Stop(log, context.TODO()))
require.NoError(t, h1.Stop(log, context.TODO()))
}
func TestModulePrivateProvidersDecorators(t *testing.T) {
var intCalled bool
opts := hive.DefaultOptions()
opts.ModuleDecorators = cell.ModuleDecorators{
func(n int) int { intCalled = true; return n + 1 },
func(base string, mod cell.ModuleID) string { return base + string(mod) },
}
opts.ModulePrivateProviders = cell.ModulePrivateProviders{
func() float64 { return 3.1415 },
}
var stringContents string
var floatContents float64
h := hive.NewWithOptions(opts,
cell.Provide(
// Things to decorate
func() int { return 1 },
func() string { return "hello, " },
),
cell.Module("test", "test",
cell.Invoke(func(s string, f float64) {
stringContents = s
floatContents = f
}),
))
require.NoError(t, h.Populate(hivetest.Logger(t)))
require.Equal(t, "hello, test", stringContents)
require.Equal(t, 3.1415, floatContents)
require.False(t, intCalled, "did not expect unreferenced module decorator to be called")
}
// Test_Regression_Parallel_Config is a (-race) regression test for parallel use of cell.Config.
// pflag.FlagSet is keen on mutating things, even AddFlag() mutates the flag passed to it.
func Test_Regression_Parallel_Config(t *testing.T) {
testCell := cell.Module(
"test",
"Test Module",
cell.Config(Config{}),
)
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
hive := hive.New(testCell)
log := hivetest.Logger(t, hivetest.LogLevel(slog.LevelError))
require.NoError(t, hive.Start(log, context.TODO()))
require.NoError(t, hive.Stop(log, context.TODO()))
}()
}
wg.Wait()
}