Skip to content

Commit

Permalink
improve panic message when invalid time range is given to random Time…
Browse files Browse the repository at this point in the history
…Between
  • Loading branch information
adamluzsi committed Jun 4, 2024
1 parent f80f420 commit 85b2109
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
7 changes: 7 additions & 0 deletions random/Random.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand Down
21 changes: 21 additions & 0 deletions random/Random_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})
})
}

0 comments on commit 85b2109

Please sign in to comment.