-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions_test.go
More file actions
103 lines (96 loc) · 1.98 KB
/
functions_test.go
File metadata and controls
103 lines (96 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package gomongo
import (
"go.mongodb.org/mongo-driver/v2/bson"
"reflect"
"strings"
"testing"
)
func TestBuildUpdateDoc(t *testing.T) {
type sample struct {
Name string `bson:"name"`
Email string `bson:"email,omitempty"`
Age int `bson:"age"`
Active bool `bson:"active"`
Note string // no bson tag
}
tests := []struct {
name string
input sample
expected bson.M
}{
{
name: "all fields non-zero",
input: sample{
Name: "Alice",
Email: "a@example.com",
Age: 30,
Active: true,
Note: "ignored",
},
expected: bson.M{
"name": "Alice",
"email": "a@example.com",
"age": 30,
"active": true,
},
},
{
name: "zero string and int omitted",
input: sample{
Name: "",
Email: "",
Age: 0,
Active: false,
},
expected: bson.M{},
},
{
name: "some fields zero, others set",
input: sample{
Name: "Bob",
Email: "",
Age: 25,
Active: false,
},
expected: bson.M{
"name": "Bob",
"age": 25,
},
},
{
name: "bson tag with omitempty trimmed correctly",
input: sample{
Email: "x@example.com",
},
expected: bson.M{
"email": "x@example.com",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := BuildUpdateDoc(tt.input)
// Check same number of keys
if len(got) != len(tt.expected) {
t.Errorf("[%s] expected %d keys, got %d (%v)", tt.name, len(tt.expected), len(got), got)
}
// Check all expected keys and values
for k, v := range tt.expected {
gotVal, ok := got[k]
if !ok {
t.Errorf("[%s] missing key %s", tt.name, k)
continue
}
if !reflect.DeepEqual(gotVal, v) {
t.Errorf("[%s] for key %s expected %v, got %v", tt.name, k, v, gotVal)
}
}
// Ensure no field without bson tag
for k := range got {
if strings.Contains(k, "Note") {
t.Errorf("[%s] found unexpected Note field in update: %v", tt.name, got)
}
}
})
}
}