Skip to content

Commit

Permalink
private/date: fix PeriodToTime for invalid periods
Browse files Browse the repository at this point in the history
Updates #6818

Change-Id: I626945636bac901700b900a5594473fa33c3f288
  • Loading branch information
egonelbre committed Feb 29, 2024
1 parent bae61ed commit 6b626bc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
10 changes: 8 additions & 2 deletions private/date/utils.go
Expand Up @@ -4,7 +4,10 @@
// Package date contains various date-related utilities
package date

import "time"
import (
"fmt"
"time"
)

// MonthBoundary extract month from the provided date and returns its edges.
func MonthBoundary(t time.Time) (time.Time, time.Time) {
Expand All @@ -21,8 +24,11 @@ func DayBoundary(t time.Time) (time.Time, time.Time) {

// PeriodToTime returns time.Time period in format YYYY-MM from string.
func PeriodToTime(period string) (_ time.Time, err error) {
if len(period) < 7 {
return time.Time{}, fmt.Errorf("invalid period %q", period)
}
shortPeriod := period[:7]
layout := "2006-01"
shortPeriod := period[0:7]
result, err := time.Parse(layout, shortPeriod)
if err != nil {
return time.Time{}, err
Expand Down
15 changes: 15 additions & 0 deletions private/date/utils_test.go
Expand Up @@ -48,6 +48,21 @@ func TestPeriodToTime(t *testing.T) {
}
}

func TestPeriodToTime_Invalid(t *testing.T) {
testCases := [...]struct {
period string
error string
}{
{"", "invalid period \"\""},
{"2020", "invalid period \"2020\""},
}

for _, tc := range testCases {
_, err := date.PeriodToTime(tc.period)
require.ErrorContains(t, err, tc.error)
}
}

func TestMonthsBetweenDates(t *testing.T) {
testCases := [...]struct {
from time.Time
Expand Down

0 comments on commit 6b626bc

Please sign in to comment.