go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/time_test.go (about) 1 // Copyright 2020 The LUCI Authors. 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 15 package flag_test 16 17 import ( 18 "testing" 19 "time" 20 21 "go.chromium.org/luci/common/flag" 22 ) 23 24 func TestTimeFlag(t *testing.T) { 25 t.Parallel() 26 cases := []struct { 27 Tag string 28 Input string 29 Want time.Time 30 }{ 31 { 32 Tag: "riff on default format time", 33 Input: "2006-01-02T15:04:05.999999999Z", 34 Want: time.Date(2006, time.January, 2, 15, 4, 5, 999999999, time.UTC), 35 }, 36 { 37 Tag: "typical example from stiptime", 38 Input: "2015-06-30T18:50:50.0Z", 39 Want: time.Date(2015, time.June, 30, 18, 50, 50, 0, time.UTC), 40 }, 41 } 42 43 for _, c := range cases { 44 c := c 45 t.Run(c.Tag, func(t *testing.T) { 46 t.Parallel() 47 var got time.Time 48 f := flag.Time(&got) 49 if err := f.Set(c.Input); err != nil { 50 t.Fatalf("Error parsing %s: %s", c.Input, err) 51 } 52 if c.Want != got { 53 t.Errorf("Incorrectly parsed %s, want %s got %s", c.Input, c.Want, got) 54 } 55 }) 56 } 57 } 58 59 func TestTimeFlagErrors(t *testing.T) { 60 t.Parallel() 61 cases := []struct { 62 Tag string 63 Input string 64 }{ 65 { 66 Tag: "empty input", 67 Input: "", 68 }, 69 { 70 Tag: "leap second example from stiptime", 71 Input: "2015-06-30T23:59:60.123Z", 72 }, 73 { 74 Tag: "incorrect timezone suffix", 75 Input: "2006-01-02T15:04:05.999999999+07:00", 76 }, 77 { 78 Tag: "incorrect timezone", 79 Input: "2006-01-02T15:04:05.999999999-01:00", 80 }, 81 } 82 83 for _, c := range cases { 84 c := c 85 t.Run(c.Tag, func(t *testing.T) { 86 t.Parallel() 87 var got time.Time 88 f := flag.Time(&got) 89 if err := f.Set(c.Input); err == nil { 90 t.Errorf("Successfully parsed corrupted input %s as %s", c.Input, got) 91 } 92 }) 93 } 94 }