Allow setting fields previously unset, like adding a connection when it was nil in db

This commit is contained in:
breel
2020-07-26 02:37:02 -06:00
parent 962a0b0585
commit 363d3143e8
5 changed files with 91 additions and 3 deletions

View File

@@ -444,6 +444,11 @@ func TestApplySet(t *testing.T) {
doc: bson.M{"hello": bson.M{"world": "not hi"}},
want: bson.M{"hello": bson.M{"world": "not hi", "notworld": "hi"}},
},
"add to nonexisting, nested field": {
operator: bson.M{"hello.notworld.notnotworld": "hi"},
doc: bson.M{"hello": bson.M{"world": "not hi"}},
want: bson.M{"hello": bson.M{"world": "not hi", "notworld": bson.M{"notnotworld": "hi"}}},
},
}
for name, d := range cases {
@@ -459,3 +464,55 @@ func TestApplySet(t *testing.T) {
})
}
}
func TestApplyUnset(t *testing.T) {
cases := map[string]struct {
doc bson.M
operator bson.M
want bson.M
}{
"noop on empty": {},
"noop on full": {
doc: bson.M{"hello": "world"},
want: bson.M{"hello": "world"},
},
"del one field on full": {
operator: bson.M{"hi": "mom"},
doc: bson.M{"hello": "world", "hi": "mom"},
want: bson.M{"hello": "world"},
},
"del only field on full": {
operator: bson.M{"hello": ""},
doc: bson.M{"hello": "world"},
want: bson.M{},
},
"del existing, nested field": {
operator: bson.M{"hello.world": ""},
doc: bson.M{"hello": bson.M{"world": "not hi"}},
want: bson.M{"hello": bson.M{}},
},
"del to existing, nested field": {
operator: bson.M{"hello.notworld": ""},
doc: bson.M{"hello": bson.M{"world": "not hi", "notworld": "hi"}},
want: bson.M{"hello": bson.M{"world": "not hi"}},
},
"del to nonexisting, nested field": {
operator: bson.M{"hello.notworld.notnotworld": "hi"},
doc: bson.M{"hello": bson.M{"world": "not hi"}},
want: bson.M{"hello": bson.M{"world": "not hi"}},
},
}
for name, d := range cases {
c := d
t.Run(name, func(t *testing.T) {
out, err := applyUnset(c.doc, c.operator)
if err != nil {
t.Fatal(err)
}
if fmt.Sprint(out) != fmt.Sprint(c.want) {
t.Fatalf("(%+v, %+v) => want \n%+v\n, got \n%+v", c.doc, c.operator, c.want, out)
}
})
}
}