go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/jsonmap_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 flag
    16  
    17  import (
    18  	"flag"
    19  	"io"
    20  	"reflect"
    21  	"testing"
    22  )
    23  
    24  // Check that a JSON object string gets parsed correctly using JSONMap.
    25  func TestParseJSONMap(t *testing.T) {
    26  	t.Parallel()
    27  	cases := []struct {
    28  		arg      string
    29  		expected map[string]string
    30  	}{
    31  		{`{"foo": "bar"}`, map[string]string{"foo": "bar"}},
    32  	}
    33  	for _, c := range cases {
    34  		var m map[string]string
    35  		fs := testFlagSet()
    36  		fs.Var(JSONMap(&m), "map", "Some map")
    37  		if err := fs.Parse([]string{"-map", c.arg}); err != nil {
    38  			t.Errorf("Parse returned an error for %s: %s", c.arg, err)
    39  			continue
    40  		}
    41  		if !reflect.DeepEqual(m, c.expected) {
    42  			t.Errorf("Parsing %s, got %#v, expected %#v", c.arg, m, c.expected)
    43  		}
    44  	}
    45  }
    46  
    47  func testFlagSet() *flag.FlagSet {
    48  	fs := flag.NewFlagSet("test", flag.ContinueOnError)
    49  	fs.Usage = func() {}
    50  	fs.SetOutput(io.Discard)
    51  	return fs
    52  }