github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/cli/opts/parse_test.go (about)

     1  package opts
     2  
     3  import (
     4  	"testing"
     5  
     6  	"gotest.tools/v3/assert"
     7  	"gotest.tools/v3/env"
     8  	"gotest.tools/v3/fs"
     9  )
    10  
    11  func TestReadKVEnvStrings(t *testing.T) {
    12  	emptyEnvFile := fs.NewFile(t, t.Name())
    13  	defer emptyEnvFile.Remove()
    14  
    15  	// EMPTY_VAR should be set, but with an empty string as value
    16  	// FROM_ENV value should be substituted with FROM_ENV in the current environment
    17  	// NO_SUCH_ENV does not exist in the current environment, so should be omitted
    18  	envFile1 := fs.NewFile(t, t.Name(), fs.WithContent(`Z1=z
    19  EMPTY_VAR=
    20  FROM_ENV
    21  NO_SUCH_ENV
    22  `))
    23  	defer envFile1.Remove()
    24  	envFile2 := fs.NewFile(t, t.Name(), fs.WithContent("Z2=z\nA2=a"))
    25  	defer envFile2.Remove()
    26  	defer env.Patch(t, "FROM_ENV", "from-env")()
    27  
    28  	tests := []struct {
    29  		name      string
    30  		files     []string
    31  		overrides []string
    32  		expected  []string
    33  	}{
    34  		{
    35  			name: "empty",
    36  		},
    37  		{
    38  			name:  "empty file",
    39  			files: []string{emptyEnvFile.Path()},
    40  		},
    41  		{
    42  			name:     "single file",
    43  			files:    []string{envFile1.Path()},
    44  			expected: []string{"Z1=z", "EMPTY_VAR=", "FROM_ENV=from-env"},
    45  		},
    46  		{
    47  			name:     "two files",
    48  			files:    []string{envFile1.Path(), envFile2.Path()},
    49  			expected: []string{"Z1=z", "EMPTY_VAR=", "FROM_ENV=from-env", "Z2=z", "A2=a"},
    50  		},
    51  		{
    52  			name:      "single file and override",
    53  			files:     []string{envFile1.Path()},
    54  			overrides: []string{"Z1=override", "EXTRA=extra"},
    55  			expected:  []string{"Z1=z", "EMPTY_VAR=", "FROM_ENV=from-env", "Z1=override", "EXTRA=extra"},
    56  		},
    57  		{
    58  			name:      "overrides only",
    59  			overrides: []string{"Z1=z", "EMPTY_VAR="},
    60  			expected:  []string{"Z1=z", "EMPTY_VAR="},
    61  		},
    62  	}
    63  
    64  	for _, tc := range tests {
    65  		tc := tc
    66  		t.Run(tc.name, func(t *testing.T) {
    67  			envs, err := ReadKVEnvStrings(tc.files, tc.overrides)
    68  			assert.NilError(t, err)
    69  			assert.DeepEqual(t, tc.expected, envs)
    70  		})
    71  	}
    72  }