github.com/erda-project/erda-infra@v1.0.9/base/servicehub/provider_context_test.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package servicehub 16 17 import ( 18 "reflect" 19 "testing" 20 "time" 21 22 "github.com/spf13/pflag" 23 ) 24 25 func Test_providerContext_BindConfig(t *testing.T) { 26 type config struct { 27 StrVal string 28 IntVal int 29 Int8Val int8 30 Int16Val int16 31 Int32Val int32 32 Int64Val int64 33 BoolVal bool 34 DefaultVal string `default:"default-val"` 35 DurationVal time.Duration 36 DefaultDurationVal time.Duration `default:"3s"` 37 Name string `file:"rename_field"` 38 Name1Name2Name3 string 39 DefaultVal2 string 40 } 41 tests := []struct { 42 name string 43 pc *providerContext 44 flags *pflag.FlagSet 45 wantErr bool 46 want interface{} 47 }{ 48 { 49 name: "test all", 50 pc: &providerContext{ 51 cfg: map[string]interface{}{ 52 "strval": "test-val", 53 "intval": 64, 54 "int8val": 8, 55 "int16val": 16, 56 "int32val": 32, 57 "int64val": 64, 58 "boolval": true, 59 "durationval": "5s", 60 "rename_field": "rename-val", 61 "name1Name2Name3": "long-name-val", 62 }, 63 define: &specDefine{&Spec{ 64 ConfigFunc: func() interface{} { 65 return &config{ 66 DefaultVal2: "default-val-2", 67 } 68 }, 69 }}, 70 }, 71 want: &config{ 72 StrVal: "test-val", 73 IntVal: 64, 74 Int8Val: 8, 75 Int16Val: 16, 76 Int32Val: 32, 77 Int64Val: 64, 78 BoolVal: true, 79 DefaultVal: "default-val", 80 DurationVal: 5 * time.Second, 81 DefaultDurationVal: 3 * time.Second, 82 Name: "rename-val", 83 Name1Name2Name3: "long-name-val", 84 DefaultVal2: "default-val-2", 85 }, 86 }, 87 { 88 name: "test nil", 89 pc: &providerContext{ 90 cfg: map[string]interface{}{ 91 "some-field": "test-val", 92 }, 93 define: &specDefine{&Spec{ 94 ConfigFunc: func() interface{} { 95 return nil 96 }, 97 }}, 98 }, 99 want: nil, 100 }, 101 } 102 for _, tt := range tests { 103 t.Run(tt.name, func(t *testing.T) { 104 if err := tt.pc.BindConfig(tt.flags); (err != nil) != tt.wantErr { 105 t.Errorf("providerContext.BindConfig() error = %v, wantErr %v", err, tt.wantErr) 106 } 107 if tt.pc.cfg == nil && tt.want == nil { 108 return 109 } 110 if !reflect.DeepEqual(tt.pc.cfg, tt.want) { 111 t.Errorf("providerContext.cfg = %v, want %v", tt.pc.cfg, tt.want) 112 } 113 }) 114 } 115 }