Wrote tests for 100% coverage

Update RetryAmbiguousDateWithSwap detection logic after testing
This commit is contained in:
troyspencer 2019-08-12 20:38:23 -05:00
parent 1bdd6d3fc9
commit aca798503a
2 changed files with 48 additions and 7 deletions

View File

@ -217,6 +217,10 @@ func parseTime(datestr string, loc *time.Location, opts ...ParserOption) (p *par
// this is because it means that a day is being interpreted as a month and overflowing the valid value for that
// by retrying in this case, we can fix a common situation with no assumptions
defer func() {
if p.ambiguousMD {
// if it errors out with the following error, swap before we
// get out of this function to reduce scope it needs to be applied on
_, err := p.parse()
if err != nil && strings.Contains(err.Error(), "month out of range") {
// create the option to reverse the preference
preferMonthFirst := PreferMonthFirst(!p.preferMonthFirst)
@ -225,6 +229,8 @@ func parseTime(datestr string, loc *time.Location, opts ...ParserOption) (p *par
modifiedOpts := append(opts, preferMonthFirst, retryAmbiguousDateWithSwap)
p, err = parseTime(datestr, time.Local, modifiedOpts...)
}
}
}()
}

View File

@ -669,3 +669,38 @@ func TestInLocation(t *testing.T) {
assert.Equal(t, zeroTime, ts.Unix())
assert.NotEqual(t, nil, err)
}
func TestPreferMonthFirst(t *testing.T) {
// default case is true
ts, err := ParseAny("04/02/2014 04:08:09 +0000 UTC")
assert.Equal(t, nil, err)
assert.Equal(t, "2014-04-02 04:08:09 +0000 UTC", fmt.Sprintf("%v", ts.In(time.UTC)))
preferMonthFirstTrue := PreferMonthFirst(true)
ts, err = ParseAny("04/02/2014 04:08:09 +0000 UTC", preferMonthFirstTrue)
assert.Equal(t, nil, err)
assert.Equal(t, "2014-04-02 04:08:09 +0000 UTC", fmt.Sprintf("%v", ts.In(time.UTC)))
// allows the day to be preferred before the month, when completely ambiguous
preferMonthFirstFalse := PreferMonthFirst(false)
ts, err = ParseAny("04/02/2014 04:08:09 +0000 UTC", preferMonthFirstFalse)
assert.Equal(t, nil, err)
assert.Equal(t, "2014-02-04 04:08:09 +0000 UTC", fmt.Sprintf("%v", ts.In(time.UTC)))
}
func TestRetryAmbiguousDateWithSwap(t *testing.T) {
// default is false
_, err := ParseAny("13/02/2014 04:08:09 +0000 UTC")
assert.NotEqual(t, nil, err)
// will fail error if the month preference cannot work due to the value being larger than 12
retryAmbiguousDateWithSwapFalse := RetryAmbiguousDateWithSwap(false)
_, err = ParseAny("13/02/2014 04:08:09 +0000 UTC", retryAmbiguousDateWithSwapFalse)
assert.NotEqual(t, nil, err)
// will retry with the other month preference if this error is detected
retryAmbiguousDateWithSwapTrue := RetryAmbiguousDateWithSwap(true)
ts, err := ParseAny("13/02/2014 04:08:09 +0000 UTC", retryAmbiguousDateWithSwapTrue)
assert.Equal(t, nil, err)
assert.Equal(t, "2014-02-13 04:08:09 +0000 UTC", fmt.Sprintf("%v", ts.In(time.UTC)))
}