github.com/lmb/consul@v1.4.1/lib/telemetry_test.go (about) 1 package lib 2 3 import ( 4 "reflect" 5 "testing" 6 "time" 7 8 "github.com/stretchr/testify/require" 9 ) 10 11 func makeFullTelemetryConfig(t *testing.T) TelemetryConfig { 12 var ( 13 strSliceVal = []string{"foo"} 14 strVal = "foo" 15 intVal = int64(1 * time.Second) 16 ) 17 18 cfg := TelemetryConfig{} 19 cfgP := reflect.ValueOf(&cfg) 20 cfgV := cfgP.Elem() 21 for i := 0; i < cfgV.NumField(); i++ { 22 f := cfgV.Field(i) 23 if !f.IsValid() || !f.CanSet() { 24 continue 25 } 26 // Set non-zero values for all fields. We only implement kinds that exist 27 // now for brevity but will fail the test if a new field type is added since 28 // this is likely not implemented in MergeDefaults either. 29 switch f.Kind() { 30 case reflect.Slice: 31 if f.Type() != reflect.TypeOf(strSliceVal) { 32 t.Fatalf("unknown slice type in TelemetryConfig." + 33 " You need to update MergeDefaults and this test code.") 34 } 35 f.Set(reflect.ValueOf(strSliceVal)) 36 case reflect.Int, reflect.Int64: // time.Duration == int64 37 f.SetInt(intVal) 38 case reflect.String: 39 f.SetString(strVal) 40 case reflect.Bool: 41 f.SetBool(true) 42 default: 43 t.Fatalf("unknown field type in TelemetryConfig" + 44 " You need to update MergeDefaults and this test code.") 45 } 46 } 47 return cfg 48 } 49 50 func TestTelemetryConfig_MergeDefaults(t *testing.T) { 51 tests := []struct { 52 name string 53 cfg TelemetryConfig 54 defaults TelemetryConfig 55 want TelemetryConfig 56 }{ 57 { 58 name: "basic merge", 59 cfg: TelemetryConfig{ 60 StatsiteAddr: "stats.it:4321", 61 }, 62 defaults: TelemetryConfig{ 63 StatsdAddr: "localhost:5678", 64 StatsiteAddr: "localhost:1234", 65 }, 66 want: TelemetryConfig{ 67 StatsdAddr: "localhost:5678", 68 StatsiteAddr: "stats.it:4321", 69 }, 70 }, 71 { 72 // This test uses reflect to build a TelemetryConfig with every value set 73 // to ensure that we exercise every possible field type. This means that 74 // if new fields are added that are not supported types in the code, this 75 // test should either ensure they work or fail to build the test case and 76 // fail the test. 77 name: "exhaustive", 78 cfg: TelemetryConfig{}, 79 defaults: makeFullTelemetryConfig(t), 80 want: makeFullTelemetryConfig(t), 81 }, 82 } 83 for _, tt := range tests { 84 t.Run(tt.name, func(t *testing.T) { 85 c := tt.cfg 86 c.MergeDefaults(&tt.defaults) 87 require.Equal(t, tt.want, c) 88 }) 89 } 90 }