github.com/operator-framework/operator-lifecycle-manager@v0.30.0/pkg/lib/codec/mapstructure_test.go (about) 1 package codec 2 3 import ( 4 "reflect" 5 "testing" 6 "time" 7 8 "github.com/stretchr/testify/require" 9 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 10 ) 11 12 func TestMetaTimeHookFunc(t *testing.T) { 13 type args struct { 14 fromType, toType reflect.Type 15 data interface{} 16 } 17 type expected struct { 18 converted interface{} 19 err error 20 } 21 tests := []struct { 22 description string 23 args args 24 expected expected 25 }{ 26 { 27 description: "TimeToNil/Passthrough", 28 args: args{ 29 fromType: reflect.TypeOf(metav1.Time{}), 30 toType: reflect.TypeOf(nil), 31 data: &metav1.Time{}, 32 }, 33 expected: expected{ 34 converted: &metav1.Time{}, 35 }, 36 }, 37 { 38 description: "TimeToUnsupported/Passthrough", 39 args: args{ 40 fromType: reflect.TypeOf(metav1.Time{}), 41 toType: reflect.TypeOf(0), 42 data: &metav1.Time{}, 43 }, 44 expected: expected{ 45 converted: &metav1.Time{}, 46 }, 47 }, 48 { 49 description: "TimeToTime/Passthrough", 50 args: args{ 51 fromType: reflect.TypeOf(metav1.Time{}), 52 toType: reflect.TypeOf(metav1.Time{}), 53 data: &metav1.Time{}, 54 }, 55 expected: expected{ 56 converted: &metav1.Time{}, 57 }, 58 }, 59 { 60 description: "UnsupportedToTime/Passthrough", 61 args: args{ 62 fromType: reflect.TypeOf(0), 63 toType: reflect.TypeOf(metav1.Time{}), 64 data: 0, 65 }, 66 expected: expected{ 67 converted: 0, 68 }, 69 }, 70 { 71 description: "InvalidStringToTime/Errors", 72 args: args{ 73 fromType: reflect.TypeOf(""), 74 toType: reflect.TypeOf(metav1.Time{}), 75 data: "Not a valid RFC3339 string!", 76 }, 77 expected: expected{ 78 err: func() error { 79 _, err := time.Parse(time.RFC3339, "Not a valid RFC3339 string!") 80 return err 81 }(), 82 }, 83 }, 84 { 85 description: "StringToTime", 86 args: args{ 87 fromType: reflect.TypeOf(""), 88 toType: reflect.TypeOf(metav1.Time{}), 89 data: "2002-10-02T10:00:00-05:00", 90 }, 91 expected: expected{ 92 converted: func() metav1.Time { 93 tm, err := time.Parse(time.RFC3339, "2002-10-02T10:00:00-05:00") 94 require.NoError(t, err) 95 return metav1.NewTime(tm) 96 }(), 97 }, 98 }, 99 { 100 description: "Float64ToTime", 101 args: args{ 102 fromType: reflect.TypeOf(float64(0.0)), 103 toType: reflect.TypeOf(metav1.Time{}), 104 data: float64(0.0), 105 }, 106 expected: expected{ 107 converted: metav1.NewTime(time.Unix(0, 0)), 108 }, 109 }, 110 { 111 description: "Int64ToTime", 112 args: args{ 113 fromType: reflect.TypeOf(int64(0)), 114 toType: reflect.TypeOf(metav1.Time{}), 115 data: int64(0), 116 }, 117 expected: expected{ 118 converted: metav1.NewTime(time.Unix(0, 0)), 119 }, 120 }, 121 } 122 123 for _, tt := range tests { 124 t.Run(tt.description, func(t *testing.T) { 125 converted, err := metaTimeHookFunc(tt.args.fromType, tt.args.toType, tt.args.data) 126 require.Equal(t, tt.expected.err, err) 127 require.EqualValues(t, tt.expected.converted, converted) 128 }) 129 } 130 }