-
Notifications
You must be signed in to change notification settings - Fork 3
/
date_test.go
62 lines (55 loc) · 1.43 KB
/
date_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package examples
import (
"testing"
"time"
"github.com/a-h/lexical/input"
"github.com/a-h/lexical/parse"
)
func TestDateParsing(t *testing.T) {
tests := []struct {
input string
expectedMatch bool
expectedValue time.Time
}{
{
input: "2001-02-03",
expectedMatch: true,
expectedValue: time.Date(2001, 02, 03, 0, 0, 0, 0, time.UTC),
},
{
input: "clearly not a date",
expectedMatch: false,
},
{
input: "201-01-1", // Missing some digits
expectedMatch: false,
},
}
for _, test := range tests {
ip := input.NewFromString(test.input)
result := date(ip)
if result.Success != test.expectedMatch {
t.Errorf("for input '%v', expected sucess %v, but was %v", test.input, test.expectedMatch, result.Success)
}
}
}
var year = parse.Many(parse.WithIntegerCombiner, 4, 4, parse.ZeroToNine)
var month = parse.All(parse.WithIntegerCombiner, parse.RuneIn("01"), parse.ZeroToNine)
var day = parse.All(parse.WithIntegerCombiner, parse.RuneIn("0123"), parse.ZeroToNine)
var date = parse.All(dateConverter, year, parse.Rune('-'), month, parse.Rune('-'), day)
func dateConverter(items []interface{}) (item interface{}, value bool) {
yi, mi, di := items[0], items[2], items[4]
y, ok := yi.(int)
if !ok {
return 0, false
}
m, ok := mi.(int)
if !ok {
return 0, false
}
d, ok := di.(int)
if !ok {
return 0, false
}
return time.Date(y, time.Month(m), d, 0, 0, 0, 0, time.UTC), true
}