From 8d0bef9e2fdcd5daf0c7cb1b4b2161d5c51d024d Mon Sep 17 00:00:00 2001 From: Andreas Linde Date: Tue, 29 Oct 2024 17:37:26 +0100 Subject: [PATCH] Fix TimePeriodType EndTime getting negative values If a relative duration is provided, the remaining duration may never go below 0s --- model/commondatatypes_additions.go | 4 ++++ model/commondatatypes_additions_test.go | 25 ++++++++++++++++++------- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/model/commondatatypes_additions.go b/model/commondatatypes_additions.go index 8272e55..1c099c5 100644 --- a/model/commondatatypes_additions.go +++ b/model/commondatatypes_additions.go @@ -65,6 +65,10 @@ func getTimePeriodTypeDuration(t *TimePeriodType) (time.Duration, error) { duration := endTime.Sub(now) duration = duration.Round(time.Second) + if duration < 0 { + return 0, nil + } + return duration, nil } diff --git a/model/commondatatypes_additions_test.go b/model/commondatatypes_additions_test.go index df9d3c0..0041c25 100644 --- a/model/commondatatypes_additions_test.go +++ b/model/commondatatypes_additions_test.go @@ -16,22 +16,22 @@ func TestTimePeriodType(t *testing.T) { assert.Equal(t, time.Duration(0), duration) tc = &TimePeriodType{ - EndTime: NewAbsoluteOrRelativeTimeTypeFromDuration(time.Minute * 1), + EndTime: NewAbsoluteOrRelativeTimeTypeFromDuration(time.Second * 3), } duration, err = tc.GetDuration() assert.Nil(t, err) - assert.Equal(t, time.Minute*1, duration) + assert.Equal(t, time.Second*3, duration) - tc = NewTimePeriodTypeWithRelativeEndTime(time.Minute * 1) + tc = NewTimePeriodTypeWithRelativeEndTime(time.Second * 3) duration, err = tc.GetDuration() assert.Nil(t, err) - assert.Equal(t, time.Minute*1, duration) + assert.Equal(t, time.Second*3, duration) data, err := json.Marshal(tc) assert.Nil(t, err) assert.NotNil(t, data) - assert.Equal(t, "{\"endTime\":\"PT1M\"}", string(data)) + assert.Equal(t, "{\"endTime\":\"PT3S\"}", string(data)) var tp1 TimePeriodType err = json.Unmarshal(data, &tp1) @@ -42,12 +42,23 @@ func TestTimePeriodType(t *testing.T) { duration, err = tc.GetDuration() assert.Nil(t, err) - assert.Equal(t, time.Second*59, duration) + assert.Equal(t, time.Second*2, duration) data, err = json.Marshal(tc) assert.Nil(t, err) assert.NotNil(t, data) - assert.Equal(t, "{\"endTime\":\"PT59S\"}", string(data)) + assert.Equal(t, "{\"endTime\":\"PT2S\"}", string(data)) + + time.Sleep(time.Second * 3) + + duration, err = tc.GetDuration() + assert.Nil(t, err) + assert.Equal(t, time.Second*0, duration) + + data, err = json.Marshal(tc) + assert.Nil(t, err) + assert.NotNil(t, data) + assert.Equal(t, "{\"endTime\":\"P0D\"}", string(data)) } func TestTimeType(t *testing.T) {