github.com/bartle-stripe/trillian@v1.2.1/cmd/flags_test.go (about) 1 // Copyright 2017 Google Inc. All Rights Reserved. 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 cmd 16 17 import ( 18 "flag" 19 "os" 20 "testing" 21 22 _ "github.com/golang/glog" 23 ) 24 25 func TestParseFlags(t *testing.T) { 26 var a, b string 27 flag.StringVar(&a, "a", "", "") 28 flag.StringVar(&b, "b", "", "") 29 30 flag.CommandLine.Init(os.Args[0], flag.ContinueOnError) 31 32 tests := []struct { 33 name string 34 contents string 35 env map[string]string 36 cliArgs []string 37 expectedErr string 38 expectedA string 39 expectedB string 40 }{ 41 { 42 name: "two flags per line", 43 contents: "-a one -b two", 44 expectedA: "one", 45 expectedB: "two", 46 }, 47 { 48 name: "one flag per line", 49 contents: "-a one\n-b two", 50 expectedA: "one", 51 expectedB: "two", 52 }, 53 { 54 name: "one flag per line, with line continuation", 55 contents: "-a one \\\n-b two", 56 expectedA: "one", 57 expectedB: "two", 58 }, 59 { 60 name: "one flag in file, one flag on command-line", 61 contents: "-a one", 62 cliArgs: []string{"-b", "two"}, 63 expectedA: "one", 64 expectedB: "two", 65 }, 66 { 67 name: "two flags, one overridden by command-line", 68 contents: "-a one\n-b two", 69 cliArgs: []string{"-b", "three"}, 70 expectedA: "one", 71 expectedB: "three", 72 }, 73 { 74 name: "two flags, one using an environment variable", 75 contents: "-a one\n-b $TEST_VAR", 76 env: map[string]string{"TEST_VAR": "from env"}, 77 expectedA: "one", 78 expectedB: "from env", 79 }, 80 { 81 name: "three flags, one undefined", 82 contents: "-a one -b two -c three", 83 expectedErr: "flag provided but not defined: -c", 84 }, 85 } 86 87 initialArgs := os.Args[:] 88 for _, tc := range tests { 89 a, b = "", "" 90 os.Args = append(initialArgs, tc.cliArgs...) 91 for k, v := range tc.env { 92 if err := os.Setenv(k, v); err != nil { 93 t.Errorf("%v: os.SetEnv(%q, %q) = %q", tc.name, k, v, err) 94 } 95 } 96 97 if err := parseFlags(tc.contents); err != nil { 98 if err.Error() != tc.expectedErr { 99 t.Errorf("%v: parseFlags() = %q, want %q", tc.name, err, tc.expectedErr) 100 } 101 continue 102 } 103 104 if tc.expectedA != a { 105 t.Errorf("%v: flag 'a' not properly set: got %q, want %q", tc.name, a, tc.expectedA) 106 } 107 if tc.expectedB != b { 108 t.Errorf("%v: flag 'b' not properly set: got %q, want %q", tc.name, b, tc.expectedB) 109 } 110 } 111 }