fs: Add string alternatives for setting options over the rc

Before this change options were read and set in native format. This
means for example nanoseconds for durations or an integer for
enumerated types, which isn't very convenient for humans.

This change enables these types to be set with a string with the
syntax as used in the command line instead, so `"10s"` rather than
`10000000000` or `"DEBUG"` rather than `8` for log level.
This commit is contained in:
Nick Craig-Wood 2020-12-11 17:48:09 +00:00
parent e32f08f37b
commit ae3963e4b4
17 changed files with 516 additions and 20 deletions

View file

@ -1,14 +1,15 @@
package fs
import (
"encoding/json"
"strconv"
"testing"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
)
// Check it satisfies the interface
var _ pflag.Value = (*DumpFlags)(nil)
var _ flagger = (*DumpFlags)(nil)
func TestDumpFlagsString(t *testing.T) {
assert.Equal(t, "", DumpFlags(0).String())
@ -56,3 +57,39 @@ func TestDumpFlagsType(t *testing.T) {
f := DumpFlags(0)
assert.Equal(t, "DumpFlags", f.Type())
}
func TestDumpFlagsUnmarshallJSON(t *testing.T) {
for _, test := range []struct {
in string
want DumpFlags
wantErr string
}{
{`""`, DumpFlags(0), ""},
{`"bodies"`, DumpBodies, ""},
{`"bodies,headers,auth"`, DumpBodies | DumpHeaders | DumpAuth, ""},
{`"bodies,headers,auth"`, DumpBodies | DumpHeaders | DumpAuth, ""},
{`"headers,bodies,requests,responses,auth,filters"`, DumpHeaders | DumpBodies | DumpRequests | DumpResponses | DumpAuth | DumpFilters, ""},
{`"headers,bodies,unknown,auth"`, 0, "Unknown dump flag \"unknown\""},
{`0`, DumpFlags(0), ""},
{strconv.Itoa(int(DumpBodies)), DumpBodies, ""},
{strconv.Itoa(int(DumpBodies | DumpHeaders | DumpAuth)), DumpBodies | DumpHeaders | DumpAuth, ""},
} {
f := DumpFlags(-1)
initial := f
err := json.Unmarshal([]byte(test.in), &f)
if err != nil {
if test.wantErr == "" {
t.Errorf("Got an error when not expecting one on %q: %v", test.in, err)
} else {
assert.Contains(t, err.Error(), test.wantErr)
}
assert.Equal(t, initial, f, test.want)
} else {
if test.wantErr != "" {
t.Errorf("Got no error when expecting one on %q", test.in)
} else {
assert.Equal(t, test.want, f)
}
}
}
}