forked from mongodb/mongo-go-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread_write_concern_spec_test.go
318 lines (251 loc) · 8.42 KB
/
read_write_concern_spec_test.go
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package mongo
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"path"
"testing"
"time"
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/core/connstring"
"github.com/mongodb/mongo-go-driver/core/readconcern"
"github.com/mongodb/mongo-go-driver/core/writeconcern"
"github.com/mongodb/mongo-go-driver/internal/testutil/helpers"
"github.com/stretchr/testify/require"
)
type connectionStringTest struct {
Description string
URI string
Valid bool
ReadConcern map[string]interface{}
WriteConcern map[string]interface{}
}
type documentTest struct {
Description string
URI string
Valid bool
ReadConcern *readConcern
ReadConcernDocument map[string]interface{}
WriteConcern *writeConcern
WriteConcernDocument map[string]interface{}
IsServerDefault bool
IsAcknowledged *bool
}
type readConcern struct {
Level *string
}
type writeConcern struct {
W interface{}
Journal *bool
WtimeoutMS *int64
}
type connectionStringTests struct {
Tests []connectionStringTest
}
type documentTestContainer struct {
Tests []documentTest
}
const testsDir = "../data/read-write-concern/"
const connStringTestsDir = "connection-string"
const documentTestsDir = "document"
// Test case for all connection string spec tests.
func TestReadWriteConcernSpec(t *testing.T) {
for _, file := range testhelpers.FindJSONFilesInDir(t, path.Join(testsDir, connStringTestsDir)) {
runConnectionStringTestsInFile(t, file)
}
for _, file := range testhelpers.FindJSONFilesInDir(t, path.Join(testsDir, documentTestsDir)) {
runDocumentTestsInFile(t, file)
}
}
func runConnectionStringTestsInFile(t *testing.T, filename string) {
filepath := path.Join(testsDir, connStringTestsDir, filename)
content, err := ioutil.ReadFile(filepath)
require.NoError(t, err)
var container connectionStringTests
require.NoError(t, json.Unmarshal(content, &container))
// Remove ".json" from filename.
filename = filename[:len(filename)-5]
for _, testCase := range container.Tests {
runConnectionStringTest(t, fmt.Sprintf("%s/%s/%s", connStringTestsDir, filename, testCase.Description), &testCase)
}
}
func runDocumentTestsInFile(t *testing.T, filename string) {
filepath := path.Join(testsDir, documentTestsDir, filename)
content, err := ioutil.ReadFile(filepath)
require.NoError(t, err)
var container documentTestContainer
require.NoError(t, json.Unmarshal(content, &container))
// Remove ".json" from filename.
filename = filename[:len(filename)-5]
for _, testCase := range container.Tests {
runDocumentTest(t, fmt.Sprintf("%s/%s/%s", documentTestsDir, filename, testCase.Description), &testCase)
}
}
func runConnectionStringTest(t *testing.T, testName string, testCase *connectionStringTest) {
t.Run(testName, func(t *testing.T) {
cs, err := connstring.Parse(testCase.URI)
if !testCase.Valid {
require.Error(t, err)
return
}
require.NoError(t, err)
if testCase.ReadConcern != nil {
rc := readConcernFromConnString(&cs)
if rc == nil {
rc = readconcern.New()
}
rcBSON, err := rc.MarshalBSONElement()
require.NoError(t, err)
rcDoc := rcBSON.Value().MutableDocument()
expectedLevel, expectedFound := testCase.ReadConcern["level"]
actualLevel, actualErr := rcDoc.Lookup("level")
require.Equal(t, expectedFound, actualErr == nil)
if expectedFound {
require.Equal(t, expectedLevel, actualLevel.Value().StringValue())
}
}
if testCase.WriteConcern != nil {
wc := writeConcernFromConnString(&cs)
if wc == nil {
wc = writeconcern.New()
}
wcBSON, err := wc.MarshalBSONElement()
require.NoError(t, err)
wcDoc := wcBSON.Value().MutableDocument()
// Don't count journal=false since our write concern type doesn't encode it.
expectedLength := len(testCase.WriteConcern)
if j, found := testCase.WriteConcern["journal"]; found && !j.(bool) {
expectedLength--
}
require.Equal(t, wcDoc.Len(), expectedLength)
itr := wcDoc.Iterator()
for itr.Next() {
e := itr.Element()
switch e.Key() {
case "w":
v, found := testCase.WriteConcern["w"]
require.True(t, found)
vInt := testhelpers.GetIntFromInterface(v)
if vInt == nil {
require.Equal(t, e.Value().Type(), bson.TypeString)
vString, ok := v.(string)
require.True(t, ok)
require.Equal(t, vString, e.Value().StringValue())
break
}
require.Equal(t, e.Value().Type(), bson.TypeInt32)
require.Equal(t, *vInt, int64(e.Value().Int32()))
case "wtimeout":
v, found := testCase.WriteConcern["wtimeoutMS"]
require.True(t, found)
i := testhelpers.GetIntFromInterface(v)
require.NotNil(t, i)
require.Equal(t, *i, e.Value().Int64())
case "j":
v, found := testCase.WriteConcern["journal"]
require.True(t, found)
vBool, ok := v.(bool)
require.True(t, ok)
require.Equal(t, vBool, e.Value().Boolean())
}
}
require.NoError(t, itr.Err())
}
})
}
func runDocumentTest(t *testing.T, testName string, testCase *documentTest) {
t.Run(testName, func(t *testing.T) {
if testCase.ReadConcern != nil {
rc := readConcernFromStruct(*testCase.ReadConcern)
rcDoc, err := rc.MarshalBSONElement()
require.NoError(t, err)
rcBytes := rcDoc.Value().ReaderDocument()
actual := make(map[string]interface{})
decoder := bson.NewDecoder(bytes.NewBuffer(rcBytes))
err = decoder.Decode(actual)
requireMapEqual(t, testCase.ReadConcernDocument, actual)
}
if testCase.WriteConcern != nil {
wc, err := writeConcernFromStruct(*testCase.WriteConcern)
require.NoError(t, err)
if testCase.IsAcknowledged != nil {
require.Equal(t, *testCase.IsAcknowledged, wc.Acknowledged())
}
wcDoc, err := wc.MarshalBSONElement()
if !testCase.Valid {
require.Error(t, err)
return
}
require.NoError(t, err)
wcBytes := wcDoc.Value().ReaderDocument()
actual := make(map[string]interface{})
decoder := bson.NewDecoder(bytes.NewBuffer(wcBytes))
err = decoder.Decode(actual)
require.NoError(t, err)
requireMapEqual(t, testCase.WriteConcernDocument, actual)
}
})
}
func requireMapEqual(t *testing.T, expected, actual map[string]interface{}) {
// Since `actual` won't contain j=false, we just check that actual isn't bigger than `expected`.
// Later, we check that all other keys in `expected` are in `actual`.
require.True(t, len(expected) >= len(actual))
for key, expectedVal := range expected {
actualVal, ok := actual[key]
// Since write concern's MarshalBSON doesn't marshal j=false, we treat j=false as the
// same as j not being present.
//
// We know that MarshalBSON will only populate j with a bool, so the coercion is safe.
if key == "j" {
require.Equal(t, expectedVal, ok && actualVal.(bool))
continue
}
// Assert that the key from `expected` is in `actual`.
require.True(t, ok)
// Coerce both to integers if possible (to ensure that things like `float(3)` and `int32(3)` are true)/
expectedInt := testhelpers.GetIntFromInterface(expectedVal)
actualInt := testhelpers.GetIntFromInterface(actualVal)
require.Equal(t, expectedInt == nil, actualInt == nil)
if expectedInt != nil {
require.Equal(t, expectedInt, actualInt)
continue
}
// Otherwise, check equality regularly.
require.Equal(t, expectedVal, actualVal)
}
}
func readConcernFromStruct(rc readConcern) *readconcern.ReadConcern {
opts := make([]readconcern.Option, 0)
if rc.Level != nil {
opts = append(opts, readconcern.Level(*rc.Level))
}
return readconcern.New(opts...)
}
func writeConcernFromStruct(wc writeConcern) (*writeconcern.WriteConcern, error) {
opts := make([]writeconcern.Option, 0)
if wc.W != nil {
if i := testhelpers.GetIntFromInterface(wc.W); i != nil {
if !int64FitsInInt(*i) {
return nil, errors.New("write concern `w` value is too large for int")
}
opts = append(opts, writeconcern.W(int(*i)))
} else if s, ok := wc.W.(string); ok {
opts = append(opts, writeconcern.WTagSet(s))
} else {
return nil, errors.New("write concern `w` must be int or string")
}
}
if wc.Journal != nil {
opts = append(opts, writeconcern.J(*wc.Journal))
}
if wc.WtimeoutMS != nil {
opts = append(opts, writeconcern.WTimeout(time.Duration(*wc.WtimeoutMS)*time.Millisecond))
}
return writeconcern.New(opts...), nil
}
func int64FitsInInt(i int64) bool {
// If casting an int64 to an int changes the value, then it doesn't fit in an int.
return int64(int(i)) == i
}