1// Copyright (c) 2014 Couchbase, Inc. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package flexible 16 17import ( 18 "reflect" 19 "testing" 20 "time" 21 22 "github.com/blevesearch/bleve/analysis" 23) 24 25func TestFlexibleDateTimeParser(t *testing.T) { 26 testLocation := time.FixedZone("", -8*60*60) 27 28 tests := []struct { 29 input string 30 expectedTime time.Time 31 expectedError error 32 }{ 33 { 34 input: "2014-08-03", 35 expectedTime: time.Date(2014, 8, 3, 0, 0, 0, 0, time.UTC), 36 expectedError: nil, 37 }, 38 { 39 input: "2014-08-03T15:59:30", 40 expectedTime: time.Date(2014, 8, 3, 15, 59, 30, 0, time.UTC), 41 expectedError: nil, 42 }, 43 { 44 input: "2014-08-03 15:59:30", 45 expectedTime: time.Date(2014, 8, 3, 15, 59, 30, 0, time.UTC), 46 expectedError: nil, 47 }, 48 { 49 input: "2014-08-03T15:59:30-08:00", 50 expectedTime: time.Date(2014, 8, 3, 15, 59, 30, 0, testLocation), 51 expectedError: nil, 52 }, 53 { 54 input: "2014-08-03T15:59:30.999999999-08:00", 55 expectedTime: time.Date(2014, 8, 3, 15, 59, 30, 999999999, testLocation), 56 expectedError: nil, 57 }, 58 { 59 input: "not a date time", 60 expectedTime: time.Time{}, 61 expectedError: analysis.ErrInvalidDateTime, 62 }, 63 } 64 65 rfc3339NoTimezone := "2006-01-02T15:04:05" 66 rfc3339NoTimezoneNoT := "2006-01-02 15:04:05" 67 rfc3339NoTime := "2006-01-02" 68 69 dateOptionalTimeParser := New( 70 []string{ 71 time.RFC3339Nano, 72 time.RFC3339, 73 rfc3339NoTimezone, 74 rfc3339NoTimezoneNoT, 75 rfc3339NoTime, 76 }) 77 78 for _, test := range tests { 79 actualTime, actualErr := dateOptionalTimeParser.ParseDateTime(test.input) 80 if actualErr != test.expectedError { 81 t.Errorf("expected error %#v, got %#v", test.expectedError, actualErr) 82 continue 83 } 84 if !reflect.DeepEqual(actualTime, test.expectedTime) { 85 t.Errorf("expected time %#v, got %#v", test.expectedTime, actualTime) 86 t.Errorf("expected location %#v,\n got %#v", test.expectedTime.Location(), actualTime.Location()) 87 } 88 } 89} 90