From 85b210955e7dd39dc914eeab0d49fc430c9b4796 Mon Sep 17 00:00:00 2001 From: Adam Luzsi Date: Tue, 4 Jun 2024 20:25:19 +0200 Subject: [PATCH] improve panic message when invalid time range is given to random TimeBetween --- random/Random.go | 7 +++++++ random/Random_test.go | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/random/Random.go b/random/Random.go index 8c47629..5c43321 100644 --- a/random/Random.go +++ b/random/Random.go @@ -117,8 +117,15 @@ func (r *Random) StringNWithCharset(length int, charset string) string { return string(bytes) } +const panicInvalidTimeRangeMessage = `invalid time range given for TimeBetween, [to] time is earlier in time than [from] time. +[from]: %s + [to]: %s` + // TimeBetween returns, as an time.Time, a non-negative pseudo-random time in [from,to]. func (r *Random) TimeBetween(from, to time.Time) time.Time { + if to.Before(from) { + panic(fmt.Sprintf(panicInvalidTimeRangeMessage, from.Format(time.RFC3339), to.Format(time.RFC3339))) + } return time.Unix(int64(r.IntBetween(int(from.Unix()), int(to.Unix()))), 0).UTC() } diff --git a/random/Random_test.go b/random/Random_test.go index 3c90623..5439799 100644 --- a/random/Random_test.go +++ b/random/Random_test.go @@ -843,4 +843,25 @@ func SpecTimeBetween(s *testcase.Spec, rnd testcase.Var[*random.Random], sbj fun t2, _ := time.Parse(time.RFC3339, t1.Format(time.RFC3339)) t.Must.Equal(t1.UTC(), t2.UTC()) }) + + s.And("till is smaller than from", func(s *testcase.Spec) { + fromTime.Let(s, func(t *testcase.T) time.Time { + return time.Date(2000, 1, 1, 12, 0, 0, 0, time.Local) + }) + toTime.Let(s, func(t *testcase.T) time.Time { + return fromTime.Get(t).Add(-1 * time.Second) + }) + + s.Then("", func(t *testcase.T) { + out := assert.Panic(t, func() { subject(t) }) + assert.NotNil(t, out) + panicMessage := fmt.Sprintf("%v", out) + assert.Contain(t, panicMessage, `invalid`) + assert.Contain(t, panicMessage, `[to]`) + assert.Contain(t, panicMessage, `earlier`) + assert.Contain(t, panicMessage, `[from]`) + assert.Contain(t, panicMessage, fromTime.Get(t).Format(time.RFC3339)) + assert.Contain(t, panicMessage, toTime.Get(t).Format(time.RFC3339)) + }) + }) }