2023-03-15 16:00:52 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2022-11-29 14:07:04 +00:00
|
|
|
package command
|
|
|
|
|
|
|
|
import (
|
2023-01-11 20:04:57 +00:00
|
|
|
"flag"
|
2022-11-29 14:07:04 +00:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestLogFlags_ValuesProvider(t *testing.T) {
|
|
|
|
cases := map[string]struct {
|
|
|
|
flagKey string
|
|
|
|
envVarKey string
|
2023-01-11 20:04:57 +00:00
|
|
|
wantValue string
|
|
|
|
wantFound bool
|
2022-11-29 14:07:04 +00:00
|
|
|
}{
|
|
|
|
"flag-missing": {
|
|
|
|
flagKey: "invalid",
|
|
|
|
envVarKey: "valid-env-var",
|
2023-01-11 20:04:57 +00:00
|
|
|
wantValue: "envVarValue",
|
|
|
|
wantFound: true,
|
2022-11-29 14:07:04 +00:00
|
|
|
},
|
|
|
|
"envVar-missing": {
|
|
|
|
flagKey: "valid-flag",
|
|
|
|
envVarKey: "invalid",
|
2023-01-11 20:04:57 +00:00
|
|
|
wantValue: "flagValue",
|
|
|
|
wantFound: true,
|
2022-11-29 14:07:04 +00:00
|
|
|
},
|
|
|
|
"all-present": {
|
|
|
|
flagKey: "valid-flag",
|
|
|
|
envVarKey: "valid-env-var",
|
2023-01-11 20:04:57 +00:00
|
|
|
wantValue: "flagValue",
|
|
|
|
wantFound: true,
|
|
|
|
},
|
|
|
|
"all-missing": {
|
|
|
|
flagKey: "invalid",
|
|
|
|
envVarKey: "invalid",
|
|
|
|
wantValue: "",
|
|
|
|
wantFound: false,
|
2022-11-29 14:07:04 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2023-01-11 20:04:57 +00:00
|
|
|
// Sneaky little fake providers
|
|
|
|
flagFaker := func(key string) (flag.Value, bool) {
|
|
|
|
var result fakeFlag
|
|
|
|
var found bool
|
|
|
|
|
|
|
|
if key == "valid-flag" {
|
|
|
|
result.Set("flagValue")
|
|
|
|
found = true
|
2022-11-29 14:07:04 +00:00
|
|
|
}
|
|
|
|
|
2023-01-11 20:04:57 +00:00
|
|
|
return &result, found
|
|
|
|
}
|
|
|
|
|
|
|
|
envFaker := func(key string) (string, bool) {
|
|
|
|
var found bool
|
|
|
|
var result string
|
|
|
|
|
|
|
|
if key == "valid-env-var" {
|
|
|
|
result = "envVarValue"
|
|
|
|
found = true
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, found
|
2022-11-29 14:07:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
vp := valuesProvider{
|
2023-01-11 20:04:57 +00:00
|
|
|
flagProvider: flagFaker,
|
|
|
|
envVarProvider: envFaker,
|
2022-11-29 14:07:04 +00:00
|
|
|
}
|
|
|
|
|
2023-01-11 20:04:57 +00:00
|
|
|
for name, tc := range cases {
|
|
|
|
val, found := vp.overrideValue(tc.flagKey, tc.envVarKey)
|
|
|
|
assert.Equal(t, tc.wantFound, found, name)
|
|
|
|
assert.Equal(t, tc.wantValue, val, name)
|
2022-11-29 14:07:04 +00:00
|
|
|
}
|
|
|
|
}
|
2023-01-11 20:04:57 +00:00
|
|
|
|
|
|
|
type fakeFlag struct {
|
|
|
|
value string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (v *fakeFlag) String() string {
|
|
|
|
return v.value
|
|
|
|
}
|
|
|
|
|
|
|
|
func (v *fakeFlag) Set(raw string) error {
|
|
|
|
v.value = raw
|
|
|
|
return nil
|
|
|
|
}
|