Skip to content

Commit

Permalink
fixes issue #187. adds test to verify the fix.
Browse files Browse the repository at this point in the history
  • Loading branch information
vsemichev committed Aug 8, 2024
1 parent 4da170b commit 2f1a615
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 1 deletion.
71 changes: 71 additions & 0 deletions issue187_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package mergo_test

import (
"dario.cat/mergo"
"testing"
)

func TestIssue187MergeStructToMap(t *testing.T) {
dst := map[string]interface{}{
"empty": "data",
}

src := struct {
Foo string
Bar int
Empty string
}{
Foo: "hello",
Bar: 42,
}
if err := mergo.Map(&dst, src); err != nil {
t.Error(err)
}
if dst["foo"] != "hello" || dst["bar"] != 42 || dst["empty"] != "data" {
t.Errorf("expected dst to be {foo: hello, bar: 42, empty: data}, got {foo: %v, bar: %v, empty: %v}", dst["foo"], dst["bar"], dst["empty"])
}
}

func TestIssue187MergeStructToMapWithOverwrite(t *testing.T) {
dst := map[string]interface{}{
"foo": "initial",
"bar": 1,
"empty": "data",
}
src := struct {
Foo string
Bar int
Empty string
}{
Foo: "hello",
Bar: 42,
}
if err := mergo.Map(&dst, src, mergo.WithOverride); err != nil {
t.Error(err)
}
if dst["foo"] != "hello" || dst["bar"] != 42 || dst["empty"] != "data" {
t.Errorf("expected dst to be {foo: hello, bar: 42, empty: data}, got {foo: %v, bar: %v, empty: %v}", dst["foo"], dst["bar"], dst["empty"])
}
}

func TestIssue187MergeStructToMapWithOverwriteWithEmptyValue(t *testing.T) {
dst := map[string]interface{}{
"foo": "initial",
"bar": 1,
"empty": "data",
}
src := struct {
Foo string
Bar int
Empty string
}{
Foo: "hello",
Bar: 42,
}
if err := mergo.Map(&dst, src, mergo.WithOverwriteWithEmptyValue); err != nil {
t.Error(err)
}
if dst["foo"] != "hello" || dst["bar"] != 42 || dst["empty"] != "" {
t.Errorf("expected dst to be {foo: hello, bar: 42, empty: }, got {foo: %v, bar: %v, empty: %v}", dst["foo"], dst["bar"], dst["empty"])
}
}
2 changes: 1 addition & 1 deletion map.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf
}
fieldName := field.Name
fieldName = changeInitialCase(fieldName, unicode.ToLower)
if _, ok := dstMap[fieldName]; !ok || (!isEmptyValue(reflect.ValueOf(src.Field(i).Interface()), !config.ShouldNotDereference) && overwrite) {
if _, ok := dstMap[fieldName]; !ok || (!isEmptyValue(reflect.ValueOf(src.Field(i).Interface()), !config.ShouldNotDereference) && overwrite) || config.overwriteWithEmptyValue {
dstMap[fieldName] = src.Field(i).Interface()
}
}
Expand Down

0 comments on commit 2f1a615

Please sign in to comment.