forked from GoCodeAlone/modular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstance_aware_feeding_test.go
More file actions
643 lines (555 loc) · 18 KB
/
instance_aware_feeding_test.go
File metadata and controls
643 lines (555 loc) · 18 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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
package modular
import (
"fmt"
"log/slog"
"os"
"testing"
"github.com/CrisisTextLine/modular/feeders"
)
// TestInstanceAwareFeedingAfterYAML verifies instance-aware feeding after YAML load.
// Env vars are hoisted (when non-conflicting) so subtests can run with t.Parallel safely.
func TestInstanceAwareFeedingAfterYAML(t *testing.T) {
tests := []struct {
name string
yamlContent string
envVars map[string]string
expected map[string]string
}{
{
name: "database_connections_with_yaml_structure_and_env_overrides",
yamlContent: `
database:
default: "primary"
connections:
primary:
driver: "postgres"
dsn: "postgres://localhost:5432/defaultdb"
secondary:
driver: "mysql"
dsn: "mysql://localhost:3306/defaultdb"
cache:
driver: "sqlite3"
dsn: ":memory:"
`,
envVars: map[string]string{
"DB_PRIMARY_DRIVER": "sqlite3",
"DB_PRIMARY_DSN": "./test_primary.db",
"DB_SECONDARY_DRIVER": "sqlite3",
"DB_SECONDARY_DSN": "./test_secondary.db",
"DB_CACHE_DRIVER": "sqlite3",
"DB_CACHE_DSN": "./test_cache.db",
},
expected: map[string]string{
"primary.driver": "sqlite3",
"primary.dsn": "./test_primary.db",
"secondary.driver": "sqlite3",
"secondary.dsn": "./test_secondary.db",
"cache.driver": "sqlite3",
"cache.dsn": "./test_cache.db",
},
},
{
name: "webapp_instances_with_yaml_and_env",
yamlContent: `
webapp:
default: "api"
instances:
api:
port: 8080
host: "localhost"
admin:
port: 8081
host: "localhost"
`,
envVars: map[string]string{
"WEBAPP_API_PORT": "9080",
"WEBAPP_API_HOST": "0.0.0.0",
"WEBAPP_ADMIN_PORT": "9081",
},
expected: map[string]string{
"api.port": "9080",
"api.host": "0.0.0.0",
"admin.port": "9081",
"admin.host": "localhost",
},
},
}
// Merge env vars and detect conflicting assignments.
merged := map[string]string{}
collision := false
for _, tc := range tests {
for k, v := range tc.envVars {
if existing, ok := merged[k]; ok && existing != v {
collision = true
break
}
merged[k] = v
}
if collision {
break
}
}
if !collision {
for k, v := range merged {
t.Setenv(k, v)
}
}
for _, tc := range tests {
c := tc
t.Run(c.name, func(t *testing.T) {
if collision {
for k, v := range c.envVars {
t.Setenv(k, v)
}
} else {
// Safe to parallelize: env vars pre-set and per-app feeders avoid global mutation.
t.Parallel()
}
tmpFile := createTempYAMLFile(t, c.yamlContent)
defer os.Remove(tmpFile)
var dbConfig *TestDatabaseConfig
var webConfig *TestWebappConfig
if c.name == "database_connections_with_yaml_structure_and_env_overrides" {
dbConfig = &TestDatabaseConfig{Default: "primary", Connections: make(map[string]*TestConnectionConfig)}
} else {
webConfig = &TestWebappConfig{Default: "api", Instances: make(map[string]*TestWebappInstance)}
}
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelError}))
app := NewStdApplication(NewStdConfigProvider(&TestAppConfig{}), logger)
// Use per-app feeders to avoid touching global state
app.(*StdApplication).SetConfigFeeders([]Feeder{feeders.NewYamlFeeder(tmpFile), feeders.NewEnvFeeder()})
if dbConfig != nil {
instancePrefixFunc := func(instanceKey string) string { return "DB_" + instanceKey + "_" }
configProvider := NewInstanceAwareConfigProvider(dbConfig, instancePrefixFunc)
app.RegisterConfigSection("database", configProvider)
} else {
instancePrefixFunc := func(instanceKey string) string { return "WEBAPP_" + instanceKey + "_" }
configProvider := NewInstanceAwareConfigProvider(webConfig, instancePrefixFunc)
app.RegisterConfigSection("webapp", configProvider)
}
if err := app.Init(); err != nil {
t.Fatalf("Failed to initialize application: %v", err)
}
var provider ConfigProvider
var err error
if dbConfig != nil {
provider, err = app.GetConfigSection("database")
} else {
provider, err = app.GetConfigSection("webapp")
}
if err != nil {
t.Fatalf("Failed to get config section: %v", err)
}
if dbConfig != nil {
testDatabaseInstanceAwareFeedingResults(t, provider, c.expected)
} else {
testWebappInstanceAwareFeedingResults(t, provider, c.expected)
}
})
}
}
// TestInstanceAwareFeedingRegressionBug tests the specific bug that was fixed:
// instance-aware feeding was checking the original provider config instead of
// the config that was populated by YAML feeders.
func TestInstanceAwareFeedingRegressionBug(t *testing.T) {
// NOTE: Cannot use t.Parallel here because this test calls t.Setenv. Go 1.25 restriction.
// Create YAML content with database connections
yamlContent := `
database:
default: "writer"
connections:
writer:
driver: "postgres"
dsn: "postgres://localhost:5432/defaultdb"
reader:
driver: "postgres"
dsn: "postgres://localhost:5432/defaultdb"
`
// Create temporary YAML file
tmpFile := createTempYAMLFile(t, yamlContent)
defer os.Remove(tmpFile)
// Set environment variables for instance-aware feeding
envVars := map[string]string{
"DB_WRITER_DRIVER": "sqlite3",
"DB_WRITER_DSN": "./writer.db",
"DB_READER_DRIVER": "sqlite3",
"DB_READER_DSN": "./reader.db",
}
for key, value := range envVars {
t.Setenv(key, value)
}
// Create database config with empty connections (this simulates the bug)
dbConfig := &TestDatabaseConfig{
Default: "writer",
Connections: make(map[string]*TestConnectionConfig),
}
// Setup per-app feeders (avoid mutating global ConfigFeeders)
// Create application
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelError}))
app := NewStdApplication(NewStdConfigProvider(&TestAppConfig{}), logger)
if cfSetter, ok := app.(interface{ SetConfigFeeders([]Feeder) }); ok {
cfSetter.SetConfigFeeders([]Feeder{feeders.NewYamlFeeder(tmpFile), feeders.NewEnvFeeder()})
}
// Register database config section with instance-aware provider
instancePrefixFunc := func(instanceKey string) string {
return "DB_" + instanceKey + "_"
}
configProvider := NewInstanceAwareConfigProvider(dbConfig, instancePrefixFunc)
app.RegisterConfigSection("database", configProvider)
// Initialize the application (this triggers config loading)
if err := app.Init(); err != nil {
t.Fatalf("Failed to initialize application: %v", err)
}
// Get the config section
provider, err := app.GetConfigSection("database")
if err != nil {
t.Fatalf("Failed to get config section: %v", err)
}
// Validate that the fix works: instance-aware feeding should find the connections
// that were loaded from YAML and apply environment variable overrides
iaProvider, ok := provider.(*InstanceAwareConfigProvider)
if !ok {
t.Fatalf("Expected InstanceAwareConfigProvider, got %T", provider)
}
finalConfig, ok := iaProvider.GetConfig().(*TestDatabaseConfig)
if !ok {
t.Fatalf("Expected TestDatabaseConfig, got %T", iaProvider.GetConfig())
}
// Validate that connections were loaded from YAML
if len(finalConfig.Connections) == 0 {
t.Fatal("REGRESSION: No connections found - YAML feeding failed")
}
// Validate that environment variable overrides were applied
if writerConn, exists := finalConfig.Connections["writer"]; exists {
if writerConn.Driver != "sqlite3" {
t.Errorf("REGRESSION: Writer driver should be 'sqlite3' from env var, got '%s'", writerConn.Driver)
}
if writerConn.DSN != "./writer.db" {
t.Errorf("REGRESSION: Writer DSN should be './writer.db' from env var, got '%s'", writerConn.DSN)
}
} else {
t.Error("REGRESSION: Writer connection not found")
}
if readerConn, exists := finalConfig.Connections["reader"]; exists {
if readerConn.Driver != "sqlite3" {
t.Errorf("REGRESSION: Reader driver should be 'sqlite3' from env var, got '%s'", readerConn.Driver)
}
if readerConn.DSN != "./reader.db" {
t.Errorf("REGRESSION: Reader DSN should be './reader.db' from env var, got '%s'", readerConn.DSN)
}
} else {
t.Error("REGRESSION: Reader connection not found")
}
}
// Test structures for instance-aware configuration testing
type TestDatabaseConfig struct {
Default string `yaml:"default"`
Connections map[string]*TestConnectionConfig `yaml:"connections"`
}
func (c *TestDatabaseConfig) Validate() error {
return nil
}
func (c *TestDatabaseConfig) GetInstanceConfigs() map[string]interface{} {
instances := make(map[string]interface{})
for name, connection := range c.Connections {
instances[name] = connection
}
return instances
}
type TestConnectionConfig struct {
Driver string `yaml:"driver" env:"DRIVER"`
DSN string `yaml:"dsn" env:"DSN"`
}
type TestWebappConfig struct {
Default string `yaml:"default"`
Instances map[string]*TestWebappInstance `yaml:"instances"`
}
func (c *TestWebappConfig) Validate() error {
return nil
}
func (c *TestWebappConfig) GetInstanceConfigs() map[string]interface{} {
instances := make(map[string]interface{})
for name, instance := range c.Instances {
instances[name] = instance
}
return instances
}
type TestWebappInstance struct {
Port int `yaml:"port" env:"PORT"`
Host string `yaml:"host" env:"HOST"`
}
type TestAppConfig struct {
App TestAppSettings `yaml:"app"`
}
type TestAppSettings struct {
Name string `yaml:"name" env:"APP_NAME" default:"Test App"`
}
func (c *TestAppConfig) Validate() error {
return nil
}
func createTempYAMLFile(t *testing.T, content string) string {
tmpFile, err := os.CreateTemp("", "test_config_*.yaml")
if err != nil {
t.Fatalf("Failed to create temp file: %v", err)
}
defer tmpFile.Close()
if _, err := tmpFile.WriteString(content); err != nil {
t.Fatalf("Failed to write to temp file: %v", err)
}
return tmpFile.Name()
}
func testDatabaseInstanceAwareFeedingResults(t *testing.T, provider ConfigProvider, expected map[string]string) {
iaProvider, ok := provider.(*InstanceAwareConfigProvider)
if !ok {
t.Fatalf("Expected InstanceAwareConfigProvider, got %T", provider)
}
config, ok := iaProvider.GetConfig().(*TestDatabaseConfig)
if !ok {
t.Fatalf("Expected TestDatabaseConfig, got %T", iaProvider.GetConfig())
}
// Validate each expected value
for key, expectedValue := range expected {
parts := splitKey(key)
if len(parts) != 2 {
t.Errorf("Invalid key format: %s", key)
continue
}
connectionName := parts[0]
fieldName := parts[1]
connection, exists := config.Connections[connectionName]
if !exists {
t.Errorf("Connection '%s' not found", connectionName)
continue
}
var actualValue string
switch fieldName {
case "driver":
actualValue = connection.Driver
case "dsn":
actualValue = connection.DSN
default:
t.Errorf("Unknown field: %s", fieldName)
continue
}
if actualValue != expectedValue {
t.Errorf("Expected %s to be '%s', got '%s'", key, expectedValue, actualValue)
}
}
}
func testWebappInstanceAwareFeedingResults(t *testing.T, provider ConfigProvider, expected map[string]string) {
iaProvider, ok := provider.(*InstanceAwareConfigProvider)
if !ok {
t.Fatalf("Expected InstanceAwareConfigProvider, got %T", provider)
}
config, ok := iaProvider.GetConfig().(*TestWebappConfig)
if !ok {
t.Fatalf("Expected TestWebappConfig, got %T", iaProvider.GetConfig())
}
// Validate each expected value
for key, expectedValue := range expected {
parts := splitKey(key)
if len(parts) != 2 {
t.Errorf("Invalid key format: %s", key)
continue
}
instanceName := parts[0]
fieldName := parts[1]
instance, exists := config.Instances[instanceName]
if !exists {
t.Errorf("Instance '%s' not found", instanceName)
continue
}
var actualValue string
switch fieldName {
case "port":
actualValue = fmt.Sprintf("%d", instance.Port)
case "host":
actualValue = instance.Host
default:
t.Errorf("Unknown field: %s", fieldName)
continue
}
if actualValue != expectedValue {
t.Errorf("Expected %s to be '%s', got '%s'", key, expectedValue, actualValue)
}
}
}
func splitKey(key string) []string {
parts := make([]string, 0, 2)
for i := 0; i < 2; i++ {
if dotIndex := findDotIndex(key); dotIndex != -1 {
if i == 0 {
parts = append(parts, key[:dotIndex])
key = key[dotIndex+1:]
} else {
parts = append(parts, key)
}
} else {
parts = append(parts, key)
break
}
}
return parts
}
func findDotIndex(s string) int {
for i, c := range s {
if c == '.' {
return i
}
}
return -1
}
// TestInstanceAwareFeedingOrderMatter tests that instance-aware feeding happens
// AFTER regular config feeding, not before. This ensures that the instances
// are available when the instance-aware feeding process runs.
func TestInstanceAwareFeedingOrderMatters(t *testing.T) {
// NOTE: Cannot mark this test as t.Parallel because it uses t.Setenv to
// define environment variable overrides. Go 1.25 forbids calling t.Setenv
// in a test that also calls t.Parallel on the same *testing.T instance.
// Keeping this serial avoids the panic: "test using t.Setenv or t.Chdir can not use t.Parallel".
// Create YAML content
yamlContent := `
test:
default: "instance1"
items:
instance1:
value: "yaml_value1"
instance2:
value: "yaml_value2"
`
// Create temporary YAML file
tmpFile := createTempYAMLFile(t, yamlContent)
defer os.Remove(tmpFile)
// Set environment variables
t.Setenv("TEST_INSTANCE1_VALUE", "env_value1")
t.Setenv("TEST_INSTANCE2_VALUE", "env_value2")
// Create test config
testConfig := &TestInstanceConfig{
Default: "instance1",
Items: make(map[string]*TestInstanceItem),
}
// Setup per-app feeders instead of mutating global ConfigFeeders
// Create application
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelError}))
app := NewStdApplication(NewStdConfigProvider(&TestAppConfig{}), logger)
if cfSetter, ok := app.(interface{ SetConfigFeeders([]Feeder) }); ok {
cfSetter.SetConfigFeeders([]Feeder{feeders.NewYamlFeeder(tmpFile), feeders.NewEnvFeeder()})
}
// Register config section
instancePrefixFunc := func(instanceKey string) string {
return "TEST_" + instanceKey + "_"
}
configProvider := NewInstanceAwareConfigProvider(testConfig, instancePrefixFunc)
app.RegisterConfigSection("test", configProvider)
// Initialize the application
if err := app.Init(); err != nil {
t.Fatalf("Failed to initialize application: %v", err)
}
// Get the config section
provider, err := app.GetConfigSection("test")
if err != nil {
t.Fatalf("Failed to get config section: %v", err)
}
// Validate results
iaProvider, ok := provider.(*InstanceAwareConfigProvider)
if !ok {
t.Fatalf("Expected InstanceAwareConfigProvider, got %T", provider)
}
finalConfig, ok := iaProvider.GetConfig().(*TestInstanceConfig)
if !ok {
t.Fatalf("Expected TestInstanceConfig, got %T", iaProvider.GetConfig())
}
// Validate that YAML loaded the structure first
if len(finalConfig.Items) == 0 {
t.Fatal("YAML feeding failed - no items found")
}
// Validate that environment variables overrode YAML values
if item1, exists := finalConfig.Items["instance1"]; exists {
if item1.Value != "env_value1" {
t.Errorf("Expected instance1.value to be 'env_value1', got '%s'", item1.Value)
}
} else {
t.Error("instance1 not found")
}
if item2, exists := finalConfig.Items["instance2"]; exists {
if item2.Value != "env_value2" {
t.Errorf("Expected instance2.value to be 'env_value2', got '%s'", item2.Value)
}
} else {
t.Error("instance2 not found")
}
}
type TestInstanceConfig struct {
Default string `yaml:"default"`
Items map[string]*TestInstanceItem `yaml:"items"`
}
func (c *TestInstanceConfig) Validate() error {
return nil
}
func (c *TestInstanceConfig) GetInstanceConfigs() map[string]interface{} {
instances := make(map[string]interface{})
for name, item := range c.Items {
instances[name] = item
}
return instances
}
type TestInstanceItem struct {
Value string `yaml:"value" env:"VALUE"`
}
// TestInstanceAwareFeedingWithNoInstances tests that instance-aware feeding
// gracefully handles the case where no instances are defined in the config.
func TestInstanceAwareFeedingWithNoInstances(t *testing.T) {
t.Parallel()
// Create YAML content with no instances
yamlContent := `
test:
default: "none"
items: {}
`
// Create temporary YAML file
tmpFile := createTempYAMLFile(t, yamlContent)
defer os.Remove(tmpFile)
// Create test config
testConfig := &TestInstanceConfig{
Default: "none",
Items: make(map[string]*TestInstanceItem),
}
// Setup per-app feeders (avoid mutating global ConfigFeeders)
// Create application
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelError}))
app := NewStdApplication(NewStdConfigProvider(&TestAppConfig{}), logger)
if cfSetter, ok := app.(interface{ SetConfigFeeders([]Feeder) }); ok {
cfSetter.SetConfigFeeders([]Feeder{feeders.NewYamlFeeder(tmpFile), feeders.NewEnvFeeder()})
}
// Register config section
instancePrefixFunc := func(instanceKey string) string {
return "TEST_" + instanceKey + "_"
}
configProvider := NewInstanceAwareConfigProvider(testConfig, instancePrefixFunc)
app.RegisterConfigSection("test", configProvider)
// Initialize the application - this should not fail even with no instances
if err := app.Init(); err != nil {
t.Fatalf("Failed to initialize application: %v", err)
}
// Get the config section
provider, err := app.GetConfigSection("test")
if err != nil {
t.Fatalf("Failed to get config section: %v", err)
}
// Validate results
iaProvider, ok := provider.(*InstanceAwareConfigProvider)
if !ok {
t.Fatalf("Expected InstanceAwareConfigProvider, got %T", provider)
}
finalConfig, ok := iaProvider.GetConfig().(*TestInstanceConfig)
if !ok {
t.Fatalf("Expected TestInstanceConfig, got %T", iaProvider.GetConfig())
}
// Validate that empty instances are handled gracefully
if len(finalConfig.Items) != 0 {
t.Errorf("Expected 0 items, got %d", len(finalConfig.Items))
}
if finalConfig.Default != "none" {
t.Errorf("Expected default to be 'none', got '%s'", finalConfig.Default)
}
}