go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/nestedflagset/nestedflagset_test.go (about) 1 // Copyright 2016 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 nestedflagset 16 17 import ( 18 "flag" 19 "fmt" 20 21 "testing" 22 23 . "github.com/smartystreets/goconvey/convey" 24 ) 25 26 func TestNestedFlagSet(t *testing.T) { 27 Convey("Given a multi-field FlagSet object", t, func() { 28 nfs := FlagSet{} 29 s := nfs.F.String("field-str", "", "String field.") 30 i := nfs.F.Int("field-int", 0, "Integer field.") 31 d := nfs.F.String("field-default", "default", 32 "Another string field.") 33 34 Convey("When parsed with a valid field set", func() { 35 err := nfs.Parse("field-str=foo,field-int=123") 36 Convey("It should parse without error.", FailureHalts, func() { 37 So(err, ShouldBeNil) 38 }) 39 40 Convey("It should parse 'field-str' as 'foo'", func() { 41 So(*s, ShouldEqual, "foo") 42 }) 43 44 Convey("It should parse 'field-int' as 123", func() { 45 So(*i, ShouldEqual, 123) 46 }) 47 48 Convey("It should leave 'field-default' to its default value, 'default'", func() { 49 So(*d, ShouldEqual, "default") 50 }) 51 }) 52 53 Convey("When parsed with an unexpected field", func() { 54 err := nfs.Parse("field-invalid=foo") 55 56 Convey("It should error.", FailureHalts, func() { 57 So(err, ShouldNotBeNil) 58 }) 59 }) 60 61 Convey("It should return a valid usage string.", func() { 62 So(nfs.Usage(), ShouldEqual, "help[,field-default][,field-int][,field-str]") 63 }) 64 65 Convey(`When installed as a flag`, func() { 66 fs := flag.NewFlagSet("test", flag.PanicOnError) 67 fs.Var(&nfs, "flagset", "The FlagSet instance.") 68 69 Convey(`Accepts the FlagSet as a parameter.`, func() { 70 fs.Parse([]string{"-flagset", `field-str="hello",field-int=20`}) 71 So(*s, ShouldEqual, "hello") 72 So(*i, ShouldEqual, 20) 73 So(*d, ShouldEqual, "default") 74 }) 75 }) 76 }) 77 } 78 79 // ExampleFlagSet demonstrates nestedflagset.FlagSet usage. 80 func ExampleFlagSet() { 81 nfs := &FlagSet{} 82 s := nfs.F.String("str", "", "Nested string option.") 83 i := nfs.F.Int("int", 0, "Nested integer option.") 84 85 if err := nfs.Parse(`str="Hello, world!",int=10`); err != nil { 86 panic(err) 87 } 88 fmt.Printf("Parsed str=[%s], int=%d.\n", *s, *i) 89 90 // Output: 91 // Parsed str=[Hello, world!], int=10. 92 }