Add conversion function to pointer metav1.Time

This commit is contained in:
wojtekt 2019-11-01 20:31:09 +01:00
parent 529d5dd4b2
commit 9b4134acce
2 changed files with 67 additions and 0 deletions

View File

@ -45,6 +45,7 @@ func AddConversionFuncs(scheme *runtime.Scheme) error {
Convert_v1_Duration_To_Pointer_v1_Duration,
Convert_Slice_string_To_v1_Time,
Convert_Slice_string_To_Pointer_v1_Time,
Convert_v1_Time_To_v1_Time,
Convert_v1_MicroTime_To_v1_MicroTime,
@ -263,6 +264,22 @@ func Convert_Slice_string_To_v1_Time(in *[]string, out *Time, s conversion.Scope
return out.UnmarshalQueryParameter(str)
}
func Convert_Slice_string_To_Pointer_v1_Time(in *[]string, out **Time, s conversion.Scope) error {
if in == nil {
return nil
}
str := ""
if len(*in) > 0 {
str = (*in)[0]
}
temp := Time{}
if err := temp.UnmarshalQueryParameter(str); err != nil {
return err
}
*out = &temp
return nil
}
func Convert_string_To_labels_Selector(in *string, out *labels.Selector, s conversion.Scope) error {
selector, err := labels.Parse(*in)
if err != nil {

View File

@ -17,10 +17,13 @@ limitations under the License.
package v1_test
import (
"net/url"
"testing"
"time"
apiequality "k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
)
func TestMapToLabelSelectorRoundTrip(t *testing.T) {
@ -82,3 +85,50 @@ func TestConvertSliceStringToDeletionPropagation(t *testing.T) {
}
}
}
func TestUrlValuesToPointerTime(t *testing.T) {
scheme := runtime.NewScheme()
v1.AddConversionFuncs(scheme)
type testType struct {
Time *v1.Time `json:"time"`
}
t1 := v1.Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC)
t1String := t1.Format(time.RFC3339)
t2 := v1.Date(2000, time.June, 6, 6, 6, 6, 0, time.UTC)
t2String := t2.Format(time.RFC3339)
tcs := []struct {
Input url.Values
Output *v1.Time
}{
{
Input: url.Values{},
Output: nil,
},
{
Input: url.Values{"time": []string{}},
Output: &v1.Time{},
},
{
Input: url.Values{"time": []string{""}},
Output: &v1.Time{},
},
{
Input: url.Values{"time": []string{t1String, t2String}},
Output: &t1,
},
}
for _, tc := range tcs {
result := &testType{}
if err := scheme.Convert(&tc.Input, &result, nil); err != nil {
t.Errorf("Failed to convert []string to *metav1.Time %#v: %v", tc.Input, err)
continue
}
if !apiequality.Semantic.DeepEqual(result.Time, tc.Output) {
t.Errorf("Unexpected output: %v, expected: %v", result.Time, tc.Output)
}
}
}