Skip to content

Commit b54959d

Browse files
committed
fix: handle unknown or invalid periods for date ranges
1 parent ad80049 commit b54959d

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

date.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ func getDateBoundaries(per Period, start, end time.Time) []time.Time {
8181
case PeriodYear:
8282
incYear = 1
8383
periodStart = time.Date(start.Year(), time.January, 1, 0, 0, 0, 0, time.UTC)
84+
default:
85+
return []time.Time{start, end}
8486
}
8587

8688
boundaries := []time.Time{periodStart}

date_test.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package ledger
2+
3+
import (
4+
"testing"
5+
"time"
6+
)
7+
8+
type boundCase struct {
9+
period Period
10+
start, end time.Time
11+
bounds []time.Time
12+
}
13+
14+
var boundCases = []boundCase{
15+
{
16+
PeriodYear,
17+
time.Date(2019, time.March, 23, 0, 0, 0, 0, time.UTC),
18+
time.Date(2021, time.March, 23, 0, 0, 0, 0, time.UTC),
19+
[]time.Time{
20+
time.Date(2019, time.January, 01, 0, 0, 0, 0, time.UTC),
21+
time.Date(2020, time.January, 01, 0, 0, 0, 0, time.UTC),
22+
time.Date(2021, time.January, 01, 0, 0, 0, 0, time.UTC),
23+
time.Date(2022, time.January, 01, 0, 0, 0, 0, time.UTC),
24+
},
25+
},
26+
{
27+
PeriodMonth,
28+
time.Date(2019, time.March, 23, 0, 0, 0, 0, time.UTC),
29+
time.Date(2019, time.April, 23, 0, 0, 0, 0, time.UTC),
30+
[]time.Time{
31+
time.Date(2019, time.March, 01, 0, 0, 0, 0, time.UTC),
32+
time.Date(2019, time.April, 01, 0, 0, 0, 0, time.UTC),
33+
time.Date(2019, time.May, 01, 0, 0, 0, 0, time.UTC),
34+
},
35+
},
36+
{
37+
Period("Unknown"),
38+
time.Date(2019, time.March, 23, 0, 0, 0, 0, time.UTC),
39+
time.Date(2019, time.April, 23, 0, 0, 0, 0, time.UTC),
40+
[]time.Time{
41+
time.Date(2019, time.March, 23, 0, 0, 0, 0, time.UTC),
42+
time.Date(2019, time.April, 23, 0, 0, 0, 0, time.UTC),
43+
},
44+
},
45+
}
46+
47+
func TestDateBoundaries(t *testing.T) {
48+
for _, tc := range boundCases {
49+
bounds := getDateBoundaries(tc.period, tc.start, tc.end)
50+
if len(bounds) != len(tc.bounds) {
51+
t.Fatalf("Error(%s): expected `%d` bounds, got `%d` bounds", tc.period, len(tc.bounds), len(bounds))
52+
}
53+
for i, b := range bounds {
54+
if !b.Equal(tc.bounds[i]) {
55+
t.Errorf("Error(%s): expected [%d] = `%s` , got `%s`", tc.period, i, tc.bounds[i].Format(time.RFC3339), b.Format(time.RFC3339))
56+
}
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)