Skip to content

Commit

Permalink
Merge pull request #22 from boynTeam/master
Browse files Browse the repository at this point in the history
#20 Add a MustSet function
  • Loading branch information
creasty authored Aug 16, 2020
2 parents 8240537 + ea4c44f commit 0e0a326
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
8 changes: 8 additions & 0 deletions defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ func Set(ptr interface{}) error {
return nil
}

// MustSet function is a wrapper of Set function
// It will call Set and panic if err not equals nil.
func MustSet(ptr interface{}) {
if err := Set(ptr); err != nil {
panic(err)
}
}

func setField(field reflect.Value, defaultVal string) error {
if !field.CanSet() {
return nil
Expand Down
46 changes: 46 additions & 0 deletions defaults_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,52 @@ type Emmbeded struct {
Int int `default:"1"`
}

func TestMustSet(t *testing.T) {

t.Run("right way", func(t *testing.T) {
defer func() {
if err := recover(); err != nil {
t.Fatalf("it should not panic error: %v", err)
}
}()
sample := &Sample{
NonInitialString: "string",
NonInitialSlice: []int{1, 2, 3},
NonInitialStruct: Struct{Foo: 123},
NonInitialStructPtr: &Struct{Foo: 123},
DeepSliceOfStructsWithNoTag: [][][]Struct{{{{Foo: 123}}}},
}
MustSet(sample)
})

t.Run("not struct", func(t *testing.T) {
defer func() {
if err := recover(); err != nil {
t.Logf("panic error: %v", err)
}
}()
var a int
MustSet(&a)
})

t.Run("not pointer", func(t *testing.T) {
defer func() {
if err := recover(); err != nil {
t.Logf("panic error: %v", err)
}
}()
sample := Sample{
NonInitialString: "string",
NonInitialSlice: []int{1, 2, 3},
NonInitialStruct: Struct{Foo: 123},
NonInitialStructPtr: &Struct{Foo: 123},
DeepSliceOfStructsWithNoTag: [][][]Struct{{{{Foo: 123}}}},
}
MustSet(sample)
})

}

func TestInit(t *testing.T) {
sample := &Sample{
NonInitialString: "string",
Expand Down

0 comments on commit 0e0a326

Please sign in to comment.