github.com/GoogleCloudPlatform/compute-image-tools/cli_tools@v0.0.0-20240516224744-de2dabc4ed1b/common/utils/flags/key_value_flag_test.go (about)

     1  //  Copyright 2020 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 flags
    16  
    17  import (
    18  	"testing"
    19  
    20  	"github.com/stretchr/testify/assert"
    21  )
    22  
    23  func TestKeyValueSetReturnsMap(t *testing.T) {
    24  	input := "KEY1=AB,KEY2=CD"
    25  	expected := map[string]string{"KEY1": "AB", "KEY2": "CD"}
    26  	var s KeyValueString
    27  	err := s.Set(input)
    28  	assert.Nil(t, err)
    29  	assert.Equal(t, expected, map[string]string(s))
    30  }
    31  
    32  func TestKeyValueSetReturnsEmptyMap(t *testing.T) {
    33  	input := ""
    34  	expected := map[string]string{}
    35  	var s KeyValueString
    36  	err := s.Set(input)
    37  	assert.Nil(t, err)
    38  	assert.Equal(t, expected, map[string]string(s))
    39  }
    40  
    41  func TestKeyValueSetReturnsErrorIfNotNil(t *testing.T) {
    42  	input := "KEY1=AB,KEY2=CD"
    43  	var s KeyValueString = map[string]string{}
    44  	err := s.Set(input)
    45  	assert.NotNil(t, err)
    46  	assert.EqualError(t, err, "only one instance of this flag is allowed")
    47  }
    48  
    49  func TestKeyValueSetReturnsErrorIfWrongStringFormat(t *testing.T) {
    50  	input := "KEY1->AB,KEY2->CD"
    51  	var s KeyValueString
    52  	err := s.Set(input)
    53  	assert.NotNil(t, err)
    54  	assert.Contains(t, err.Error(), "failed to parse key-value pair. "+
    55  		"key-value should be in the following format: KEY=VALUE")
    56  }
    57  
    58  func TestKeyValueStringReturnsFormattedString(t *testing.T) {
    59  	var s KeyValueString = map[string]string{"KEY1": "AB", "KEY2": "CD"}
    60  	output := s.String()
    61  	// Both strings can be valid output, as order is not maintained in map.
    62  	validOutput1 := "KEY1=AB,KEY2=CD"
    63  	validOutput2 := "KEY2=CD,KEY1=AB"
    64  	expected := []string{validOutput1, validOutput2}
    65  	assert.Contains(t, expected, output)
    66  }