go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/clock/clockflag/duration_test.go (about) 1 // Copyright 2015 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 clockflag 16 17 import ( 18 "encoding/json" 19 "flag" 20 "testing" 21 "time" 22 23 . "github.com/smartystreets/goconvey/convey" 24 ) 25 26 func TestDuration(t *testing.T) { 27 t.Parallel() 28 29 Convey(`A Duration flag`, t, func() { 30 fs := flag.NewFlagSet("test", flag.ContinueOnError) 31 var d Duration 32 fs.Var(&d, "duration", "Test duration parameter.") 33 34 Convey(`Parses a 10-second Duration from "10s".`, func() { 35 err := fs.Parse([]string{"-duration", "10s"}) 36 So(err, ShouldBeNil) 37 So(d, ShouldEqual, time.Second*10) 38 So(d.IsZero(), ShouldBeFalse) 39 }) 40 41 Convey(`Returns an error when parsing "10z".`, func() { 42 err := fs.Parse([]string{"-duration", "10z"}) 43 So(err, ShouldNotBeNil) 44 }) 45 46 Convey(`When treated as a JSON field`, func() { 47 var s struct { 48 D Duration `json:"duration"` 49 } 50 51 testJSON := `{"duration":10}` 52 Convey(`Fails to unmarshal from `+testJSON+`.`, func() { 53 testJSON := testJSON 54 err := json.Unmarshal([]byte(testJSON), &s) 55 So(err, ShouldNotBeNil) 56 }) 57 58 Convey(`Marshals correctly to duration string.`, func() { 59 testDuration := (5 * time.Second) + (2 * time.Minute) 60 s.D = Duration(testDuration) 61 testJSON, err := json.Marshal(&s) 62 So(err, ShouldBeNil) 63 So(string(testJSON), ShouldEqual, `{"duration":"2m5s"}`) 64 65 Convey(`And Unmarshals correctly.`, func() { 66 s.D = Duration(0) 67 err := json.Unmarshal([]byte(testJSON), &s) 68 So(err, ShouldBeNil) 69 So(s.D, ShouldEqual, testDuration) 70 }) 71 }) 72 }) 73 }) 74 }