package flagsaver
import (
"flag"
"testing"
"time"
_ "k8s.io/klog/v2"
)
var (
_ = flag.Int("int_flag", 123, "test integer flag")
_ = flag.String("str_flag", "foo", "test string flag")
_ = flag.Duration("duration_flag", 5*time.Second, "test duration flag")
)
func TestRestore(t *testing.T) {
tests := []struct {
desc string
flag string
oldValue string
newValue string
}{
{
desc: "RestoreDefaultIntValue",
flag: "int_flag",
newValue: "666",
},
{
desc: "RestoreDefaultStrValue",
flag: "str_flag",
newValue: "baz",
},
{
desc: "RestoreDefaultDurationValue",
flag: "duration_flag",
newValue: "1m0s",
},
{
desc: "RestoreSetIntValue",
flag: "int_flag",
oldValue: "555",
newValue: "666",
},
{
desc: "RestoreSetStrValue",
flag: "str_flag",
oldValue: "bar",
newValue: "baz",
},
{
desc: "RestoreSetDurationValue",
flag: "duration_flag",
oldValue: "10s",
newValue: "1m0s",
},
}
for _, test := range tests {
f := flag.Lookup(test.flag)
if f == nil {
t.Errorf("%v: flag.Lookup(%q) = nil, want not nil", test.desc, test.flag)
continue
}
if test.oldValue != "" {
if err := flag.Set(test.flag, test.oldValue); err != nil {
t.Errorf("%v: flag.Set(%q, %q) = %q, want nil", test.desc, test.flag, test.oldValue, err)
continue
}
} else {
test.oldValue = f.DefValue
}
func() {
defer Save().MustRestore()
if err := flag.Set(test.flag, test.newValue); err != nil {
t.Errorf("%v: flag.Set(%q) = %q, want nil", test.desc, test.flag, err)
}
if gotValue := f.Value.String(); gotValue != test.newValue {
t.Errorf("%v: flag.Lookup(%q).Value.String() = %q, want %q", test.desc, test.flag, gotValue, test.newValue)
}
}()
if gotValue := f.Value.String(); gotValue != test.oldValue {
t.Errorf("%v: flag.Lookup(%q).Value.String() = %q, want %q", test.desc, test.flag, gotValue, test.oldValue)
}
}
}