github.com/fiatjaf/generic-ristretto@v0.0.1/z/flags_test.go (about) 1 package z 2 3 import ( 4 "fmt" 5 "os" 6 "os/user" 7 "path/filepath" 8 "testing" 9 "time" 10 11 "github.com/stretchr/testify/require" 12 ) 13 14 func TestFlag(t *testing.T) { 15 const opt = `bool_key=true; int-key=5; float-key=0.05; string_key=value; ;` 16 const def = `bool_key=false; int-key=0; float-key=1.0; string-key=; other-key=5; 17 duration-minutes=15m; duration-hours=12h; duration-days=30d;` 18 19 _, err := NewSuperFlag("boolo-key=true").mergeAndCheckDefaultImpl(def) 20 require.Error(t, err) 21 _, err = newSuperFlagImpl("key-without-value") 22 require.Error(t, err) 23 24 // bool-key and int-key should not be overwritten. Only other-key should be set. 25 sf := NewSuperFlag(opt) 26 sf.MergeAndCheckDefault(def) 27 28 require.Equal(t, true, sf.GetBool("bool-key")) 29 require.Equal(t, uint64(5), sf.GetUint64("int-key")) 30 require.Equal(t, "value", sf.GetString("string-key")) 31 require.Equal(t, uint64(5), sf.GetUint64("other-key")) 32 33 require.Equal(t, time.Minute*15, sf.GetDuration("duration-minutes")) 34 require.Equal(t, time.Hour*12, sf.GetDuration("duration-hours")) 35 require.Equal(t, time.Hour*24*30, sf.GetDuration("duration-days")) 36 } 37 38 func TestFlagDefault(t *testing.T) { 39 def := `one=false; two=; three=;` 40 f := NewSuperFlag(`one=true; two=4;`).MergeAndCheckDefault(def) 41 require.Equal(t, true, f.GetBool("one")) 42 require.Equal(t, int64(4), f.GetInt64("two")) 43 } 44 45 func TestGetPath(t *testing.T) { 46 usr, err := user.Current() 47 require.NoError(t, err) 48 homeDir := usr.HomeDir 49 cwd, err := os.Getwd() 50 require.NoError(t, err) 51 52 tests := []struct { 53 path string 54 expected string 55 }{ 56 { 57 "/home/user/file.txt", 58 "/home/user/file.txt", 59 }, 60 { 61 "~/file.txt", 62 filepath.Join(homeDir, "file.txt"), 63 }, 64 { 65 "~/abc/../file.txt", 66 filepath.Join(homeDir, "file.txt"), 67 }, 68 { 69 "~/", 70 homeDir, 71 }, 72 { 73 "~filename", 74 filepath.Join(cwd, "~filename"), 75 }, 76 { 77 "./filename", 78 filepath.Join(cwd, "filename"), 79 }, 80 { 81 "", 82 "", 83 }, 84 { 85 "./", 86 cwd, 87 }, 88 } 89 90 get := func(p string) string { 91 opt := fmt.Sprintf("file=%s", p) 92 sf := NewSuperFlag(opt) 93 return sf.GetPath("file") 94 } 95 96 for _, tc := range tests { 97 actual := get(tc.path) 98 require.Equalf(t, tc.expected, actual, "Failed on testcase: %s", tc.path) 99 } 100 }