2019-05-30 02:58:29 -05:00
|
|
|
package gtime
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2020-08-12 10:45:03 -05:00
|
|
|
"regexp"
|
2019-05-30 02:58:29 -05:00
|
|
|
"testing"
|
|
|
|
"time"
|
2020-04-06 02:00:05 -05:00
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
2019-05-30 02:58:29 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestParseInterval(t *testing.T) {
|
2020-04-06 02:00:05 -05:00
|
|
|
now := time.Now()
|
|
|
|
|
2019-05-30 02:58:29 -05:00
|
|
|
tcs := []struct {
|
|
|
|
interval string
|
|
|
|
duration time.Duration
|
2020-08-12 10:45:03 -05:00
|
|
|
err *regexp.Regexp
|
2019-05-30 02:58:29 -05:00
|
|
|
}{
|
2020-04-06 02:00:05 -05:00
|
|
|
{interval: "1d", duration: now.Sub(now.AddDate(0, 0, -1))},
|
|
|
|
{interval: "1w", duration: now.Sub(now.AddDate(0, 0, -7))},
|
|
|
|
{interval: "2w", duration: now.Sub(now.AddDate(0, 0, -14))},
|
|
|
|
{interval: "1M", duration: now.Sub(now.AddDate(0, -1, 0))},
|
|
|
|
{interval: "1y", duration: now.Sub(now.AddDate(-1, 0, 0))},
|
|
|
|
{interval: "5y", duration: now.Sub(now.AddDate(-5, 0, 0))},
|
2020-08-12 10:45:03 -05:00
|
|
|
{interval: "invalid-duration", err: regexp.MustCompile(`^time: invalid duration "?invalid-duration"?$`)},
|
2019-05-30 02:58:29 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
for i, tc := range tcs {
|
|
|
|
t.Run(fmt.Sprintf("testcase %d", i), func(t *testing.T) {
|
|
|
|
res, err := ParseInterval(tc.interval)
|
2020-08-12 10:45:03 -05:00
|
|
|
if tc.err == nil {
|
2020-04-06 02:00:05 -05:00
|
|
|
require.NoError(t, err, "interval %q", tc.interval)
|
|
|
|
require.Equal(t, tc.duration, res, "interval %q", tc.interval)
|
|
|
|
} else {
|
2020-08-12 10:45:03 -05:00
|
|
|
require.Error(t, err, "interval %q", tc.interval)
|
|
|
|
require.Regexp(t, tc.err, err.Error())
|
2019-05-30 02:58:29 -05:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|