From 4c1a11c1bc128d4234e8660245aeb1de1565838a Mon Sep 17 00:00:00 2001 From: Mariano Cano Date: Wed, 31 Jul 2019 12:36:31 -0700 Subject: [PATCH] Add Unix method to TimeDuration. --- authority/provisioner/timeduration.go | 7 ++++- authority/provisioner/timeduration_test.go | 32 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/authority/provisioner/timeduration.go b/authority/provisioner/timeduration.go index ca80ba10..7d197217 100644 --- a/authority/provisioner/timeduration.go +++ b/authority/provisioner/timeduration.go @@ -113,11 +113,16 @@ func (t *TimeDuration) UnmarshalJSON(data []byte) error { return errors.Errorf("failed to parse %s", data) } -// Time calculates the embedded time.Time, sets it if necessary, and returns it. +// Time calculates the time if needed and returns it. func (t *TimeDuration) Time() time.Time { return t.RelativeTime(now()) } +// Unix calculates the time if needed it and returns the Unix time in seconds. +func (t *TimeDuration) Unix() int64 { + return t.RelativeTime(now()).Unix() +} + // RelativeTime returns the embedded time.Time or the base time plus the // duration if this is not zero. func (t *TimeDuration) RelativeTime(base time.Time) time.Time { diff --git a/authority/provisioner/timeduration_test.go b/authority/provisioner/timeduration_test.go index 642a79ed..1def427c 100644 --- a/authority/provisioner/timeduration_test.go +++ b/authority/provisioner/timeduration_test.go @@ -217,6 +217,38 @@ func TestTimeDuration_Time(t *testing.T) { } } +func TestTimeDuration_Unix(t *testing.T) { + nowFn := now + defer func() { + now = nowFn + now() + }() + tm := time.Unix(1584198566, 535897000).UTC() + now = func() time.Time { + return tm + } + tests := []struct { + name string + timeDuration *TimeDuration + want int64 + }{ + {"zero", nil, -62135596800}, + {"zero", &TimeDuration{}, -62135596800}, + {"timestamp", &TimeDuration{t: tm}, 1584198566}, + {"local", &TimeDuration{t: tm.Local()}, 1584198566}, + {"duration", &TimeDuration{d: 1 * time.Hour}, 1584202166}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.timeDuration.Unix() + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("TimeDuration.Unix() = %v, want %v", got, tt.want) + + } + }) + } +} + func TestTimeDuration_String(t *testing.T) { nowFn := now defer func() {