Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#20 Add a MustSet function #22

Merged
merged 2 commits into from
Aug 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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