go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/gce/api/config/v1/duration_test.go (about) 1 // Copyright 2019 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 config 16 17 import ( 18 "context" 19 "math" 20 "testing" 21 22 "go.chromium.org/luci/config/validation" 23 24 . "github.com/smartystreets/goconvey/convey" 25 . "go.chromium.org/luci/common/testing/assertions" 26 ) 27 28 func TestDuration(t *testing.T) { 29 t.Parallel() 30 31 Convey("ToSeconds", t, func() { 32 Convey("invalid", func() { 33 Convey("mismatch", func() { 34 d := &TimePeriod_Duration{ 35 Duration: "1yr", 36 } 37 _, err := d.ToSeconds() 38 So(err, ShouldErrLike, "duration must match regex") 39 }) 40 41 Convey("overflow", func() { 42 d := &TimePeriod_Duration{ 43 Duration: "9223372036854775808s", 44 } 45 _, err := d.ToSeconds() 46 So(err, ShouldErrLike, "duration must not exceed") 47 }) 48 }) 49 50 Convey("valid", func() { 51 Convey("converts", func() { 52 d := &TimePeriod_Duration{ 53 Duration: "1h", 54 } 55 n, err := d.ToSeconds() 56 So(err, ShouldBeNil) 57 So(n, ShouldEqual, 3600) 58 }) 59 60 Convey("clamps", func() { 61 d := &TimePeriod_Duration{ 62 Duration: "9223372036854775807mo", 63 } 64 n, err := d.ToSeconds() 65 So(err, ShouldBeNil) 66 So(n, ShouldEqual, int64(math.MaxInt64)) 67 }) 68 }) 69 }) 70 71 Convey("Validate", t, func() { 72 c := &validation.Context{Context: context.Background()} 73 74 Convey("invalid", func() { 75 Convey("empty", func() { 76 d := &TimePeriod_Duration{} 77 d.Validate(c) 78 errs := c.Finalize().(*validation.Error).Errors 79 So(errs, ShouldContainErr, "duration must match regex") 80 }) 81 82 Convey("invalid", func() { 83 d := &TimePeriod_Duration{ 84 Duration: "1yr", 85 } 86 d.Validate(c) 87 errs := c.Finalize().(*validation.Error).Errors 88 So(errs, ShouldErrLike, "duration must match regex") 89 }) 90 }) 91 92 Convey("valid", func() { 93 d := &TimePeriod_Duration{ 94 Duration: "1h", 95 } 96 d.Validate(c) 97 So(c.Finalize(), ShouldBeNil) 98 }) 99 }) 100 }