-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathazureappconfiguration_test.go
More file actions
1802 lines (1588 loc) · 53.3 KB
/
azureappconfiguration_test.go
File metadata and controls
1802 lines (1588 loc) · 53.3 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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package azureappconfiguration
import (
"context"
"net/http"
"net/url"
"sync"
"testing"
"time"
"encoding/json"
"github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration/internal/fm"
"github.com/Azure/AppConfiguration-GoProvider/azureappconfiguration/internal/tracing"
"github.com/Azure/azure-sdk-for-go/sdk/data/azappconfig/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type mockSettingsClient struct {
mock.Mock
}
func (m *mockSettingsClient) getSettings(ctx context.Context) (*settingsResponse, error) {
args := m.Called(ctx)
return args.Get(0).(*settingsResponse), args.Error(1)
}
func TestLoadKeyValues_Success(t *testing.T) {
ctx := context.Background()
mockClient := new(mockSettingsClient)
value1 := "value1"
value2 := `{"jsonKey": "jsonValue"}`
mockResponse := &settingsResponse{
settings: []azappconfig.Setting{
{Key: toPtr("key1"), Value: &value1, ContentType: toPtr("")},
{Key: toPtr("key2"), Value: &value2, ContentType: toPtr("application/json")},
},
}
mockClient.On("getSettings", ctx).Return(mockResponse, nil)
azappcfg := &AzureAppConfiguration{
clientManager: &configurationClientManager{
staticClient: &configurationClientWrapper{client: &azappconfig.Client{}},
},
kvSelectors: deduplicateSelectors([]Selector{}),
keyValues: make(map[string]any),
}
err := azappcfg.loadKeyValues(ctx, mockClient)
assert.NoError(t, err)
assert.Equal(t, &value1, azappcfg.keyValues["key1"])
assert.Equal(t, map[string]interface{}{"jsonKey": "jsonValue"}, azappcfg.keyValues["key2"])
}
func TestLoadKeyValues_WithKeyVaultReferences(t *testing.T) {
ctx := context.Background()
mockSettingsClient := new(mockSettingsClient)
mockSecretResolver := new(mockSecretResolver)
kvReference := `{"uri":"https://myvault.vault.azure.net/secrets/mysecret"}`
mockResponse := &settingsResponse{
settings: []azappconfig.Setting{
{Key: toPtr("key1"), Value: toPtr("value1"), ContentType: toPtr("")},
{Key: toPtr("secret1"), Value: toPtr(kvReference), ContentType: toPtr(secretReferenceContentType)},
},
}
mockSettingsClient.On("getSettings", ctx).Return(mockResponse, nil)
expectedURL, _ := url.Parse("https://myvault.vault.azure.net/secrets/mysecret")
mockSecretResolver.On("ResolveSecret", ctx, *expectedURL).Return("resolved-secret", nil)
azappcfg := &AzureAppConfiguration{
clientManager: &configurationClientManager{
staticClient: &configurationClientWrapper{client: nil},
},
kvSelectors: deduplicateSelectors([]Selector{}),
keyValues: make(map[string]any),
resolver: &keyVaultReferenceResolver{
clients: sync.Map{},
secretResolver: mockSecretResolver,
},
}
err := azappcfg.loadKeyValues(ctx, mockSettingsClient)
assert.NoError(t, err)
assert.Equal(t, "value1", *azappcfg.keyValues["key1"].(*string))
assert.Equal(t, "resolved-secret", azappcfg.keyValues["secret1"])
mockSettingsClient.AssertExpectations(t)
mockSecretResolver.AssertExpectations(t)
}
func TestLoadFeatureFlags_Success(t *testing.T) {
ctx := context.Background()
mockClient := new(mockSettingsClient)
value1 := `{
"id": "Beta",
"description": "",
"enabled": false,
"conditions": {
"client_filters": []
}
}`
value2 := `{
"id": "Alpha",
"description": "Test feature",
"enabled": true,
"conditions": {
"client_filters": [
{
"name": "TestGroup",
"parameters": {"Users": ["user1@example.com", "user2@example.com"]}
}
]
}
}`
mockResponse := &settingsResponse{
settings: []azappconfig.Setting{
{Key: toPtr(".appconfig.featureflag/Beta"), Value: &value1, ContentType: toPtr(featureFlagContentType)},
{Key: toPtr(".appconfig.featureflag/Alpha"), Value: &value2, ContentType: toPtr(featureFlagContentType)},
},
pageWatchers: map[comparableSelector][]settingWatcher{},
}
mockClient.On("getSettings", ctx).Return(mockResponse, nil)
azappcfg := &AzureAppConfiguration{
clientManager: &configurationClientManager{
staticClient: &configurationClientWrapper{client: &azappconfig.Client{}},
},
ffSelectors: getFeatureFlagSelectors([]Selector{}),
featureFlags: make(map[string]any),
}
err := azappcfg.loadFeatureFlags(ctx, mockClient)
assert.NoError(t, err)
// Verify feature flag structure is created correctly
assert.Contains(t, azappcfg.featureFlags, featureManagementSectionKey)
featureManagement, ok := azappcfg.featureFlags[featureManagementSectionKey].(map[string]any)
assert.True(t, ok, "feature_management should be a map")
// Verify feature_flags array exists
assert.Contains(t, featureManagement, featureFlagSectionKey)
featureFlags, ok := featureManagement[featureFlagSectionKey].([]any)
assert.True(t, ok, "feature_flags should be an array")
// Verify we have 2 feature flags
assert.Len(t, featureFlags, 2)
// Verify the feature flags are properly unmarshaled
foundBeta := false
foundAlpha := false
for _, flag := range featureFlags {
flagMap, ok := flag.(map[string]any)
assert.True(t, ok, "feature flag should be a map")
if id, ok := flagMap["id"].(string); ok {
switch id {
case "Beta":
foundBeta = true
assert.Equal(t, false, flagMap["enabled"])
case "Alpha":
foundAlpha = true
assert.Equal(t, true, flagMap["enabled"])
assert.Equal(t, "Test feature", flagMap["description"])
// Verify conditions structure
conditions, ok := flagMap["conditions"].(map[string]any)
assert.True(t, ok, "conditions should be a map")
clientFilters, ok := conditions["client_filters"].([]any)
assert.True(t, ok, "client_filters should be an array")
assert.Len(t, clientFilters, 1)
}
}
}
assert.True(t, foundBeta, "Should have found Beta feature flag")
assert.True(t, foundAlpha, "Should have found Alpha feature flag")
}
func TestLoadKeyValues_WithTrimPrefix(t *testing.T) {
ctx := context.Background()
mockClient := new(mockSettingsClient)
value1 := "value1"
value2 := "value2"
value3 := "value3"
mockResponse := &settingsResponse{
settings: []azappconfig.Setting{
{Key: toPtr("prefix:key1"), Value: &value1, ContentType: toPtr("")},
{Key: toPtr("other:key2"), Value: &value2, ContentType: toPtr("")},
{Key: toPtr("key3"), Value: &value3, ContentType: toPtr("")},
},
}
mockClient.On("getSettings", ctx).Return(mockResponse, nil)
azappcfg := &AzureAppConfiguration{
clientManager: &configurationClientManager{
staticClient: &configurationClientWrapper{client: &azappconfig.Client{}},
},
kvSelectors: deduplicateSelectors([]Selector{}),
trimPrefixes: []string{"prefix:", "other:"},
keyValues: make(map[string]any),
}
err := azappcfg.loadKeyValues(ctx, mockClient)
assert.NoError(t, err)
assert.Equal(t, &value1, azappcfg.keyValues["key1"])
assert.Equal(t, &value2, azappcfg.keyValues["key2"])
assert.Equal(t, &value3, azappcfg.keyValues["key3"])
}
func TestLoadKeyValues_EmptyKeyAfterTrim(t *testing.T) {
ctx := context.Background()
mockClient := new(mockSettingsClient)
value1 := "value1"
mockResponse := &settingsResponse{
settings: []azappconfig.Setting{
{Key: toPtr("prefix:"), Value: &value1, ContentType: toPtr("")},
},
}
mockClient.On("getSettings", ctx).Return(mockResponse, nil)
azappcfg := &AzureAppConfiguration{
clientManager: &configurationClientManager{
staticClient: &configurationClientWrapper{client: &azappconfig.Client{}},
},
kvSelectors: deduplicateSelectors([]Selector{}),
trimPrefixes: []string{"prefix:"},
keyValues: make(map[string]any),
}
err := azappcfg.loadKeyValues(ctx, mockClient)
assert.NoError(t, err)
assert.Empty(t, azappcfg.keyValues)
}
func TestLoadKeyValues_InvalidJson(t *testing.T) {
ctx := context.Background()
mockClient := new(mockSettingsClient)
value1 := "value1"
value2 := `{"jsonKey": invalid}`
mockResponse := &settingsResponse{
settings: []azappconfig.Setting{
{Key: toPtr("key1"), Value: &value1, ContentType: toPtr("")},
{Key: toPtr("key2"), Value: &value2, ContentType: toPtr("application/json")},
},
}
mockClient.On("getSettings", ctx).Return(mockResponse, nil)
azappcfg := &AzureAppConfiguration{
clientManager: &configurationClientManager{
staticClient: &configurationClientWrapper{client: &azappconfig.Client{}},
},
kvSelectors: deduplicateSelectors([]Selector{}),
keyValues: make(map[string]any),
}
err := azappcfg.loadKeyValues(ctx, mockClient)
assert.NoError(t, err)
assert.Len(t, azappcfg.keyValues, 2)
assert.Equal(t, &value1, azappcfg.keyValues["key1"])
// The invalid JSON key should be treated as a plain string
assert.Equal(t, &value2, azappcfg.keyValues["key2"])
}
func TestDeduplicateSelectors(t *testing.T) {
tests := []struct {
name string
input []Selector
expectedOutput []Selector
}{
{
name: "empty input",
input: []Selector{},
expectedOutput: []Selector{
{KeyFilter: wildCard, LabelFilter: defaultLabel},
},
},
{
name: "no duplicates",
input: []Selector{
{KeyFilter: "one*", LabelFilter: "prod"},
{KeyFilter: "two*", LabelFilter: "dev"},
},
expectedOutput: []Selector{
{KeyFilter: "one*", LabelFilter: "prod"},
{KeyFilter: "two*", LabelFilter: "dev"},
},
},
{
name: "with duplicates",
input: []Selector{
{KeyFilter: "one*", LabelFilter: "prod"},
{KeyFilter: "two*", LabelFilter: "dev"},
{KeyFilter: "one*", LabelFilter: "prod"},
},
expectedOutput: []Selector{
{KeyFilter: "two*", LabelFilter: "dev"},
{KeyFilter: "one*", LabelFilter: "prod"},
},
},
{
name: "normalize empty label",
input: []Selector{
{KeyFilter: "one*", LabelFilter: ""},
{KeyFilter: "two*", LabelFilter: "dev"},
},
expectedOutput: []Selector{
{KeyFilter: "one*", LabelFilter: defaultLabel},
{KeyFilter: "two*", LabelFilter: "dev"},
},
},
{
name: "duplicates after normalization",
input: []Selector{
{KeyFilter: "one*", LabelFilter: ""},
{KeyFilter: "two*", LabelFilter: "dev"},
{KeyFilter: "one*", LabelFilter: defaultLabel},
},
expectedOutput: []Selector{
{KeyFilter: "two*", LabelFilter: "dev"},
{KeyFilter: "one*", LabelFilter: defaultLabel},
},
},
{
name: "precedence - later duplicates override earlier ones",
input: []Selector{
{KeyFilter: "one*", LabelFilter: "prod"},
{KeyFilter: "two*", LabelFilter: "dev"},
{KeyFilter: "one*", LabelFilter: "prod"},
{KeyFilter: "three*", LabelFilter: "test"},
},
expectedOutput: []Selector{
{KeyFilter: "two*", LabelFilter: "dev"},
{KeyFilter: "one*", LabelFilter: "prod"},
{KeyFilter: "three*", LabelFilter: "test"},
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
result := deduplicateSelectors(test.input)
assert.Equal(t, test.expectedOutput, result)
})
}
}
func TestTrimPrefix(t *testing.T) {
tests := []struct {
name string
key string
prefixesToTrim []string
expected string
}{
{
name: "no prefixes to trim",
key: "appSettings:theme",
prefixesToTrim: []string{},
expected: "appSettings:theme",
},
{
name: "empty prefixes list",
key: "appSettings:theme",
prefixesToTrim: nil,
expected: "appSettings:theme",
},
{
name: "matching prefix",
key: "appSettings:theme",
prefixesToTrim: []string{"appSettings:"},
expected: "theme",
},
{
name: "non-matching prefix",
key: "appSettings:theme",
prefixesToTrim: []string{"config:"},
expected: "appSettings:theme",
},
{
name: "multiple prefixes with match",
key: "appSettings:theme",
prefixesToTrim: []string{"config:", "appSettings:", "settings:"},
expected: "theme",
},
{
name: "multiple prefixes with no match",
key: "appSettings:theme",
prefixesToTrim: []string{"config:", "settings:"},
expected: "appSettings:theme",
},
{
name: "prefix equals key",
key: "appSettings:",
prefixesToTrim: []string{"appSettings:"},
expected: "",
},
{
name: "multiple matching prefixes - only first match is trimmed",
key: "config:appSettings:theme",
prefixesToTrim: []string{"config:", "appSettings:"},
expected: "appSettings:theme",
},
{
name: "nested prefixes - longer prefix should be prioritized",
key: "prefix:subprefix:value",
prefixesToTrim: []string{"prefix:", "prefix:subprefix:"},
expected: "subprefix:value",
},
{
name: "nested prefixes in reverse order - first match is used",
key: "prefix:subprefix:value",
prefixesToTrim: []string{"prefix:subprefix:", "prefix:"},
expected: "value",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
azappcfg := &AzureAppConfiguration{
trimPrefixes: test.prefixesToTrim,
}
result := azappcfg.trimPrefix(test.key)
assert.Equal(t, test.expected, result)
})
}
}
func TestIsJsonContentType(t *testing.T) {
tests := []struct {
name string
contentType *string
expected bool
}{
{
name: "nil content type",
contentType: nil,
expected: false,
},
{
name: "empty content type",
contentType: toPtr(""),
expected: false,
},
{
name: "standard JSON content type",
contentType: toPtr("application/json"),
expected: true,
},
{
name: "JSON content type with charset",
contentType: toPtr("application/json; charset=utf-8"),
expected: true,
},
{
name: "JSON content type with vendor prefix",
contentType: toPtr("application/vnd+json"),
expected: true,
},
{
name: "non-JSON content type",
contentType: toPtr("text/plain"),
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
result := isJsonContentType(test.contentType)
assert.Equal(t, test.expected, result)
})
}
}
func TestUnmarshal_BasicTypes(t *testing.T) {
// Define a simple struct with basic types
type Config struct {
String string
Int int
Bool bool
Float float64
Slice []string
Timeout time.Duration
}
// Setup test data
azappcfg := &AzureAppConfiguration{
keyValues: map[string]interface{}{
"String": "hello world",
"Int": "42", // Test string to int conversion
"Bool": "true",
"Float": 3.14,
"Slice": "item1,item2,item3",
"Timeout": "5s",
},
}
// Unmarshal into the struct
var config Config
err := azappcfg.Unmarshal(&config, nil)
// Verify results
assert.NoError(t, err)
assert.Equal(t, "hello world", config.String)
assert.Equal(t, 42, config.Int)
assert.Equal(t, true, config.Bool)
assert.Equal(t, 3.14, config.Float)
assert.Equal(t, []string{"item1", "item2", "item3"}, config.Slice)
assert.Equal(t, 5*time.Second, config.Timeout)
}
func TestUnmarshal_NestedStructs(t *testing.T) {
// Define nested structs
type Database struct {
Host string
Port int
Username string
Password string
SSL bool
}
type Cache struct {
TTL time.Duration
MaxSize int
Endpoints []string
}
type Config struct {
AppName string
Version string
Database Database
Cache Cache
Debug bool
}
// Setup test data
azappcfg := &AzureAppConfiguration{
keyValues: map[string]interface{}{
"AppName": "MyApp",
"Version": "1.0.0",
"Database.Host": "localhost",
"Database.Port": "5432",
"Database.Username": "admin",
"Database.Password": "secret",
"Database.SSL": true,
"Cache.TTL": "30s",
"Cache.MaxSize": 1024,
"Cache.Endpoints": "endpoint1.com,endpoint2.com",
"Debug": "true",
},
}
// Unmarshal into the struct
var config Config
err := azappcfg.Unmarshal(&config, nil)
// Verify results
assert.NoError(t, err)
assert.Equal(t, "MyApp", config.AppName)
assert.Equal(t, "1.0.0", config.Version)
// Database checks
assert.Equal(t, "localhost", config.Database.Host)
assert.Equal(t, 5432, config.Database.Port)
assert.Equal(t, "admin", config.Database.Username)
assert.Equal(t, "secret", config.Database.Password)
assert.Equal(t, true, config.Database.SSL)
// Cache checks
assert.Equal(t, 30*time.Second, config.Cache.TTL)
assert.Equal(t, 1024, config.Cache.MaxSize)
assert.Equal(t, []string{"endpoint1.com", "endpoint2.com"}, config.Cache.Endpoints)
// Debug check
assert.Equal(t, true, config.Debug)
}
func TestUnmarshal_CustomTags(t *testing.T) {
// Define a struct with custom field tags
type Config struct {
AppName string `json:"application_name"`
MaxConnCount int `json:"connection_limit"`
Endpoints struct {
Primary string `json:"main_endpoint"`
Secondary string `json:"backup_endpoint"`
} `json:"endpoints"`
FeatureEnabled bool `json:"is_feature_enabled"`
AllowedIPs []string `json:"allowed_ip_addresses"`
}
// Setup test data
azappcfg := &AzureAppConfiguration{
keyValues: map[string]interface{}{
"application_name": "CustomTagApp",
"connection_limit": 100,
"endpoints.main_endpoint": "https://primary.example.com",
"endpoints.backup_endpoint": "https://secondary.example.com",
"is_feature_enabled": "true",
"allowed_ip_addresses": "192.168.1.1,10.0.0.1,172.16.0.1",
},
}
// Unmarshal into the struct
var config Config
err := azappcfg.Unmarshal(&config, nil)
// Verify results
assert.NoError(t, err)
assert.Equal(t, "CustomTagApp", config.AppName)
assert.Equal(t, 100, config.MaxConnCount)
assert.Equal(t, "https://primary.example.com", config.Endpoints.Primary)
assert.Equal(t, "https://secondary.example.com", config.Endpoints.Secondary)
assert.Equal(t, true, config.FeatureEnabled)
assert.Equal(t, []string{"192.168.1.1", "10.0.0.1", "172.16.0.1"}, config.AllowedIPs)
}
func TestUnmarshal_EmptyValues(t *testing.T) {
// Define a struct with default values
type Config struct {
String string
StringPtr *string
Int int
IntPtr *int
Bool bool
BoolPtr *bool
StringSlice []string
}
// Setup test data with some empty values
defaultString := "default"
defaultInt := 42
defaultBool := true
config := Config{
String: defaultString,
StringPtr: &defaultString,
Int: defaultInt,
IntPtr: &defaultInt,
Bool: defaultBool,
BoolPtr: &defaultBool,
StringSlice: []string{"default1", "default2"},
}
azappcfg := &AzureAppConfiguration{
keyValues: map[string]interface{}{
// Intentionally empty map to test empty values
},
}
// Unmarshal into the struct with existing default values
err := azappcfg.Unmarshal(&config, nil)
// Verify results - default values should remain unchanged
assert.NoError(t, err)
assert.Equal(t, defaultString, config.String)
assert.Equal(t, &defaultString, config.StringPtr)
assert.Equal(t, defaultInt, config.Int)
assert.Equal(t, &defaultInt, config.IntPtr)
assert.Equal(t, defaultBool, config.Bool)
assert.Equal(t, &defaultBool, config.BoolPtr)
assert.Equal(t, []string{"default1", "default2"}, config.StringSlice)
}
func TestUnmarshal_EmptyValues_2(t *testing.T) {
// Define a struct with default values
type Config struct {
String string
StringPtr *string
Int int
IntPtr *int
Bool bool
BoolPtr *bool
StringSlice []string
}
// Setup test data with some empty values
defaultString := "default"
defaultInt := 42
defaultBool := true
// Partially initialize config
config := Config{
StringPtr: &defaultString,
IntPtr: &defaultInt,
BoolPtr: &defaultBool,
}
azappcfg := &AzureAppConfiguration{
keyValues: map[string]interface{}{
// Intentionally empty map to test empty values
},
}
// Unmarshal into the struct with existing default values
err := azappcfg.Unmarshal(&config, nil)
// Verify results - default values should remain unchanged
assert.NoError(t, err)
assert.Equal(t, "", config.String)
assert.Equal(t, &defaultString, config.StringPtr)
assert.Equal(t, 0, config.Int)
assert.Equal(t, &defaultInt, config.IntPtr)
assert.Equal(t, false, config.Bool)
assert.Equal(t, &defaultBool, config.BoolPtr)
assert.Nil(t, config.StringSlice)
}
func toPtr(s string) *string {
return &s
}
// mockDelayedSecretResolver simulates a resolver with variable response times
type mockDelayedSecretResolver struct {
mock.Mock
delays map[string]time.Duration
mu sync.Mutex
calls []time.Time
}
func (m *mockDelayedSecretResolver) ResolveSecret(ctx context.Context, keyVaultReference url.URL) (string, error) {
m.mu.Lock()
m.calls = append(m.calls, time.Now())
m.mu.Unlock()
if delay, ok := m.delays[keyVaultReference.String()]; ok {
time.Sleep(delay)
}
args := m.Called(ctx, keyVaultReference)
return args.String(0), args.Error(1)
}
func TestLoadKeyValues_WithConcurrentKeyVaultReferences(t *testing.T) {
ctx := context.Background()
mockSettingsClient := new(mockSettingsClient)
// Create a resolver with intentional delays to verify concurrent execution
mockResolver := &mockDelayedSecretResolver{
delays: map[string]time.Duration{
"https://vault1.vault.azure.net/secrets/secret1": 50 * time.Millisecond,
"https://vault1.vault.azure.net/secrets/secret2": 30 * time.Millisecond,
"https://vault2.vault.azure.net/secrets/secret3": 40 * time.Millisecond,
},
calls: make([]time.Time, 0, 3),
}
// Create key vault references
kvReference1 := `{"uri":"https://vault1.vault.azure.net/secrets/secret1"}`
kvReference2 := `{"uri":"https://vault1.vault.azure.net/secrets/secret2"}`
kvReference3 := `{"uri":"https://vault2.vault.azure.net/secrets/secret3"}`
// Set up mock response with multiple key vault references
mockResponse := &settingsResponse{
settings: []azappconfig.Setting{
{Key: toPtr("standard"), Value: toPtr("value1"), ContentType: toPtr("")},
{Key: toPtr("secret1"), Value: toPtr(kvReference1), ContentType: toPtr(secretReferenceContentType)},
{Key: toPtr("secret2"), Value: toPtr(kvReference2), ContentType: toPtr(secretReferenceContentType)},
{Key: toPtr("secret3"), Value: toPtr(kvReference3), ContentType: toPtr(secretReferenceContentType)},
},
}
mockSettingsClient.On("getSettings", ctx).Return(mockResponse, nil)
// Set up expectations for mock resolver
secret1URL, _ := url.Parse("https://vault1.vault.azure.net/secrets/secret1")
secret2URL, _ := url.Parse("https://vault1.vault.azure.net/secrets/secret2")
secret3URL, _ := url.Parse("https://vault2.vault.azure.net/secrets/secret3")
mockResolver.On("ResolveSecret", ctx, *secret1URL).Return("resolved-secret1", nil)
mockResolver.On("ResolveSecret", ctx, *secret2URL).Return("resolved-secret2", nil)
mockResolver.On("ResolveSecret", ctx, *secret3URL).Return("resolved-secret3", nil)
// Create app configuration
azappcfg := &AzureAppConfiguration{
clientManager: &configurationClientManager{
staticClient: &configurationClientWrapper{client: nil},
},
kvSelectors: deduplicateSelectors([]Selector{}),
keyValues: make(map[string]any),
resolver: &keyVaultReferenceResolver{
clients: sync.Map{},
secretResolver: mockResolver,
},
}
// Record start time
startTime := time.Now()
// Load key values
err := azappcfg.loadKeyValues(ctx, mockSettingsClient)
// Record elapsed time
elapsed := time.Since(startTime)
// Verify results
assert.NoError(t, err)
assert.Equal(t, "value1", *azappcfg.keyValues["standard"].(*string))
assert.Equal(t, "resolved-secret1", azappcfg.keyValues["secret1"])
assert.Equal(t, "resolved-secret2", azappcfg.keyValues["secret2"])
assert.Equal(t, "resolved-secret3", azappcfg.keyValues["secret3"])
// Verify all resolver calls were made
mockResolver.AssertNumberOfCalls(t, "ResolveSecret", 3)
mockSettingsClient.AssertExpectations(t)
// Verify concurrent execution by checking elapsed time
// If executed sequentially, it would take at least 50+30+40=120ms
// With concurrency, it should take closer to the longest delay (50ms) plus some overhead
assert.Less(t, elapsed, 110*time.Millisecond, "Expected concurrent execution to complete faster than sequential execution")
// Verify that calls started close to each other (within 10ms)
// This indicates that the goroutines were started concurrently
if len(mockResolver.calls) == 3 {
firstCallTime := mockResolver.calls[0]
for i := 1; i < len(mockResolver.calls); i++ {
timeDiff := mockResolver.calls[i].Sub(firstCallTime)
assert.Less(t, timeDiff, 10*time.Millisecond, "Expected resolver calls to start concurrently")
}
}
}
// mockTracingClient is a mock client that captures the HTTP header containing the correlation context
type mockTracingClient struct {
mock.Mock
capturedHeader http.Header
}
func (m *mockTracingClient) getSettings(ctx context.Context) (*settingsResponse, error) {
// Extract header from context
if header, ok := ctx.Value(tracing.CorrelationContextHeader).(http.Header); ok {
m.capturedHeader = header
}
args := m.Called(ctx)
return args.Get(0).(*settingsResponse), args.Error(1)
}
func TestLoadKeyValues_WithAIContentTypes(t *testing.T) {
ctx := context.Background()
mockClient := new(mockSettingsClient)
// Create settings with different content types
value1 := "regular value"
value2 := `{"ai": "configuration"}`
value3 := `{"ai": "chat completion"}`
mockResponse := &settingsResponse{
settings: []azappconfig.Setting{
{Key: toPtr("key1"), Value: &value1, ContentType: toPtr("text/plain")},
{Key: toPtr("key2"), Value: &value2, ContentType: toPtr("application/json; profile=\"https://azconfig.io/mime-profiles/ai\"")},
{Key: toPtr("key3"), Value: &value3, ContentType: toPtr("application/json; profile=\"https://azconfig.io/mime-profiles/ai/chat-completion\"")},
},
}
mockClient.On("getSettings", ctx).Return(mockResponse, nil)
// Create the app configuration with tracing enabled
azappcfg := &AzureAppConfiguration{
clientManager: &configurationClientManager{
staticClient: &configurationClientWrapper{client: &azappconfig.Client{}},
},
kvSelectors: deduplicateSelectors([]Selector{}),
keyValues: make(map[string]any),
tracingOptions: tracing.Options{
Enabled: true,
},
}
// Load the key values
err := azappcfg.loadKeyValues(ctx, mockClient)
assert.NoError(t, err)
// Verify the tracing options were updated correctly
assert.True(t, azappcfg.tracingOptions.UseAIConfiguration, "UseAIConfiguration flag should be set to true")
assert.True(t, azappcfg.tracingOptions.UseAIChatCompletionConfiguration, "UseAIChatCompletionConfiguration flag should be set to true")
// Verify the data was loaded correctly
assert.Equal(t, &value1, azappcfg.keyValues["key1"])
assert.Equal(t, map[string]interface{}{"ai": "configuration"}, azappcfg.keyValues["key2"])
assert.Equal(t, map[string]interface{}{"ai": "chat completion"}, azappcfg.keyValues["key3"])
}
func TestCorrelationContextHeader(t *testing.T) {
ctx := context.Background()
mockClient := new(mockTracingClient)
// Create settings with different content types
value1 := "regular value"
value2 := `{"ai": "configuration"}`
value3 := `{"ai": "chat completion"}`
mockResponse := &settingsResponse{
settings: []azappconfig.Setting{
{Key: toPtr("key1"), Value: &value1, ContentType: toPtr("text/plain")},
{Key: toPtr("key2"), Value: &value2, ContentType: toPtr("application/json; profile=\"https://azconfig.io/mime-profiles/ai\"")},
{Key: toPtr("key3"), Value: &value3, ContentType: toPtr("application/json; profile=\"https://azconfig.io/mime-profiles/ai/chat-completion\"")},
},
}
mockClient.On("getSettings", ctx).Return(mockResponse, nil)
// Create app configuration with key vault configured
tracingOptions := tracing.Options{
Enabled: true,
KeyVaultConfigured: true,
Host: tracing.HostTypeAzureWebApp,
}
azappcfg := &AzureAppConfiguration{
clientManager: &configurationClientManager{
staticClient: &configurationClientWrapper{client: &azappconfig.Client{}},
},
kvSelectors: deduplicateSelectors([]Selector{}),
keyValues: make(map[string]any),
tracingOptions: tracingOptions,
}
// Load the key values
err := azappcfg.loadKeyValues(ctx, mockClient)
assert.NoError(t, err)
// Verify the header contains all expected values
header := tracing.CreateCorrelationContextHeader(ctx, azappcfg.tracingOptions)
correlationCtx := header.Get(tracing.CorrelationContextHeader)
assert.Contains(t, correlationCtx, tracing.HostTypeKey+"="+string(tracing.HostTypeAzureWebApp))
assert.Contains(t, correlationCtx, tracing.KeyVaultConfiguredTag)
// Verify AI features are detected and included in the header
assert.True(t, azappcfg.tracingOptions.UseAIConfiguration)
assert.True(t, azappcfg.tracingOptions.UseAIChatCompletionConfiguration)
assert.Contains(t, correlationCtx, tracing.FeaturesKey+"="+
tracing.AIConfigurationTag+tracing.DelimiterPlus+tracing.AIChatCompletionConfigurationTag)
}
func TestUnmarshal_FeatureManagement(t *testing.T) {
// Setup a feature flag configuration
azappcfg := &AzureAppConfiguration{
ffEnabled: true,
featureFlags: map[string]any{
"feature_management": map[string]any{
"feature_flags": []any{
map[string]any{
"id": "BasicFlag",
"description": "A simple feature flag",
"enabled": true,
},
map[string]any{
"id": "FlagWithConditions",
"description": "A flag with conditions",
"enabled": false,
"conditions": map[string]any{
"client_filters": []any{
map[string]any{
"name": "Microsoft.TimeWindow",
"parameters": map[string]any{
"Start": "2023-01-01T00:00:00Z",
"End": "2023-12-31T23:59:59Z",
},
},
},
},
},
map[string]any{
"id": "FlagWithVariants",
"description": "A flag with variants",
"enabled": true,
"variants": []any{
map[string]any{
"name": "variantA",
"configuration_value": "value-a",
},
map[string]any{
"name": "variantB",
"configuration_value": "value-b",
"status_override": "Disabled",
},
},
"allocation": map[string]any{
"default_when_enabled": "variantA",
"percentile": []any{
map[string]any{
"variant": "variantB",
"from": 0.0,
"to": 50.0,
},
map[string]any{
"variant": "variantA",
"from": 50.0,
"to": 100.0,
},
},