Skip to content

Commit

Permalink
👔 up(cflag): update some method logic and add more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Mar 18, 2023
1 parent a31b4d6 commit 62df9a8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
21 changes: 18 additions & 3 deletions cflag/ext.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,13 @@ func (s *String) Ints(sep string) []int {
//
// Implemented the flag.Value interface.
//
// Usage:
//
// type myOpts struct {
// vars cflag.KVString
// }
// var mo &myOpts{ vars: cflag.NewKVString() }
//
// Example:
//
// --var name=inhere => string map {name:inhere}
Expand All @@ -266,10 +273,16 @@ type KVString struct {

// NewKVString instance
func NewKVString() KVString {
return KVString{
Sep: comdef.EqualStr,
SMap: make(maputil.SMap),
return *(&KVString{}).Init()
}

// Init settings
func (s *KVString) Init() *KVString {
if s.Sep == "" {
s.Sep = comdef.EqualStr
s.SMap = make(maputil.SMap)
}
return s
}

// Get value
Expand All @@ -285,6 +298,8 @@ func (s *KVString) Data() maputil.SMap {
// Set new value, will check value is right
func (s *KVString) Set(value string) error {
if value != "" {
s.Init()

key, val := strutil.SplitKV(value, s.Sep)
if key != "" {
s.SMap[key] = val
Expand Down
6 changes: 5 additions & 1 deletion cflag/ext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ func TestConfString_Set(t *testing.T) {
cs = cflag.ConfString{}
err := cs.Set("name=inhere;age=123")
assert.NoErr(t, err)
assert.NotEmpty(t, cs.Data())
assert.NotEmpty(t, cs.Get())
assert.NotEmpty(t, cs.String())
assert.Eq(t, "inhere", cs.Str("name"))
assert.Eq(t, 123, cs.Int("age"))
}
Expand All @@ -41,8 +42,11 @@ func TestKVString_Set(t *testing.T) {

assert.NoErr(t, kv.Set("age=234"))
assert.NotEmpty(t, kv.Data())
assert.NotEmpty(t, kv.Get())
assert.Eq(t, 234, kv.Int("age"))
assert.Eq(t, "{age:234}", kv.String())
assert.False(t, kv.IsEmpty())
assert.True(t, kv.IsRepeatable())

assert.NoErr(t, kv.Set("name=inhere"))
assert.Eq(t, "inhere", kv.Str("name"))
Expand Down

0 comments on commit 62df9a8

Please sign in to comment.