From 7b69af3bd0423bab7b8ff4d5f7f784006e25a520 Mon Sep 17 00:00:00 2001 From: Tamal Saha Date: Sun, 22 Oct 2017 09:43:24 -0700 Subject: [PATCH] Fix NPE in time.Equal method --- .../apimachinery/pkg/apis/meta/v1/time.go | 8 ++++++- .../pkg/apis/meta/v1/time_test.go | 24 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go b/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go index 435f6a8f599..0a9f2a37756 100644 --- a/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go +++ b/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go @@ -80,7 +80,13 @@ func (t *Time) Before(u *Time) bool { // Equal reports whether the time instant t is equal to u. func (t *Time) Equal(u *Time) bool { - return t.Time.Equal(u.Time) + if t == nil && u == nil { + return true + } + if t != nil && u != nil { + return t.Time.Equal(u.Time) + } + return false } // Unix returns the local time corresponding to the given Unix time diff --git a/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go b/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go index c0fafab9bfc..9923958ee00 100644 --- a/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go @@ -171,3 +171,27 @@ func TestTimeProto(t *testing.T) { } } } + +func TestTimeEqual(t *testing.T) { + t1 := NewTime(time.Now()) + cases := []struct { + name string + x *Time + y *Time + result bool + }{ + {"nil =? nil", nil, nil, true}, + {"!nil =? !nil", &t1, &t1, true}, + {"nil =? !nil", nil, &t1, false}, + {"!nil =? nil", &t1, nil, false}, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + result := c.x.Equal(c.y) + if result != c.result { + t.Errorf("Failed equality test for '%v', '%v': expected %+v, got %+v", c.x, c.y, c.result, result) + } + }) + } +}