summaryrefslogtreecommitdiff
path: root/src/mongo/shell/assert.js
blob: 2d207a021bdbf3532b7982db9a769b7adf5021c7 (plain)
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
doassert = function(msg, obj) {
    // eval if msg is a function
    if (typeof(msg) == "function")
        msg = msg();

    if (typeof (msg) == "string" && msg.indexOf("assert") == 0)
        print(msg);
    else
        print("assert: " + msg);

    var ex;
    if (obj) {
        ex = _getErrorWithCode(obj, msg);
    } else {
        ex = Error(msg);
    }
    print(ex.stack);
    throw ex;
}

assert = function(b, msg){
    if (assert._debug && msg) print("in assert for: " + msg);
    if (b)
        return;
    doassert(msg == undefined ? "assert failed" : "assert failed : " + msg);
}

assert.automsg = function(b) {
    assert(eval(b), b);
}

assert._debug = false;

assert.eq = function(a, b, msg){
    if (assert._debug && msg) print("in assert for: " + msg);

    if (a == b)
        return;

    if ((a != null && b != null) && friendlyEqual(a, b))
        return;

    doassert("[" + tojson(a) + "] != [" + tojson(b) + "] are not equal : " + msg);
}

// Sort doc/obj fields and return new sorted obj
sortDoc = function(doc) {

    // Helper to sort the elements of the array
    var sortElementsOfArray = function(arr) {
        var newArr = [];
        if(!arr || arr.constructor != Array)
            return arr;
        for(var i=0; i < arr.length; i++) {
            newArr.push(sortDoc(arr[i]));

        }
        return newArr;
    }

    // not a container we can sort
    if (!(doc instanceof Object))
        return doc;

    // if it an array, sort the elements
    if (doc.constructor == Array)
        return sortElementsOfArray(doc);

    var newDoc = {};
    var fields = Object.keys(doc);
    if (fields.length > 0) {
        fields.sort();
        for(var i=0; i < fields.length; i++){
            var field = fields[i];
            if (doc.hasOwnProperty(field)) {
                var tmp = doc[field];

                if (tmp) {
                    // Sort recursively for Arrays and Objects (including bson ones)
                    if (tmp.constructor == Array)
                        tmp = sortElementsOfArray(tmp);
                    else if (tmp._bson || tmp.constructor == Object)
                        tmp = sortDoc(tmp);
                }
                newDoc[field] = tmp;
            }
        }
    } else {
        newDoc = doc;
    }

    return newDoc;
}

assert.docEq = function(a, b, msg) {
    if (assert._debug && msg) print("in assert for: " + msg);

    if (a == b)
        return;

    var aSorted = sortDoc(a);
    var bSorted = sortDoc(b);

    if ((aSorted != null && bSorted != null) && friendlyEqual(aSorted, bSorted))
        return;

    doassert("[" + tojson(aSorted) + "] != [" + tojson(bSorted) + "] are not equal : " + msg);
}

assert.eq.automsg = function(a, b) {
    assert.eq(eval(a), eval(b), "[" + a + "] != [" + b + "]");
}

assert.neq = function(a, b, msg){
    if (assert._debug && msg) print("in assert for: " + msg);
    if (a != b)
        return;

    doassert("[" + a + "] != [" + b + "] are equal : " + msg);
}

assert.contains = function(o, arr, msg){
    var wasIn = false

    if(! arr.length){
        for(var i in arr){
            wasIn = arr[i] == o || ((arr[i] != null && o != null) && friendlyEqual(arr[i], o))
                return;
            if(wasIn) break
        }
    }
    else {
        for(var i = 0; i < arr.length; i++){
            wasIn = arr[i] == o || ((arr[i] != null && o != null) && friendlyEqual(arr[i], o))
            if(wasIn) break
        }
    }

    if(! wasIn) doassert(tojson(o) + " was not in " + tojson(arr) + " : " + msg)
}

assert.repeat = function(f, msg, timeout, interval) {
    if (assert._debug && msg) print("in assert for: " + msg);

    var start = new Date();
    timeout = timeout || 30000;
    interval = interval || 200;
    var last;
    while(1) {

        if (typeof(f) == "string"){
            if (eval(f))
                return;
        }
        else {
            if (f())
                return;
        }

        if ((new Date()).getTime() - start.getTime() > timeout)
            break;
        sleep(interval);
    }
}

assert.soon = function(f, msg, timeout /*ms*/, interval) {
    if (assert._debug && msg) print("in assert for: " + msg);

    if (msg) {
        if (typeof(msg) != "function") {
            msg = "assert.soon failed, msg:" + msg;
        }
    }
    else {
        msg = "assert.soon failed: " + f;
    }

    var start = new Date();
    timeout = timeout || 30000;
    interval = interval || 200;
    var last;
    while(1) {
        if (typeof(f) == "string"){
            if (eval(f))
                return;
        }
        else {
            if (f())
                return;
        }

        diff = (new Date()).getTime() - start.getTime();
        if (diff > timeout) {
            doassert(msg);
        }
        sleep(interval);
    }
}

assert.time = function(f, msg, timeout /*ms*/) {
    if (assert._debug && msg) print("in assert for: " + msg);

    var start = new Date();
    timeout = timeout || 30000;
        if (typeof(f) == "string"){
            res = eval(f);
        }
        else {
            res = f();
        }

        diff = (new Date()).getTime() - start.getTime();
        if (diff > timeout)
            doassert("assert.time failed timeout " + timeout + "ms took " + diff + "ms : " + f + ", msg:" + msg);
        return res;
}

assert.throws = function(func, params, msg) {
    if (assert._debug && msg) print("in assert for: " + msg);
    if (params && typeof(params) == "string") {
        throw ("2nd argument to assert.throws has to be an array, not " + params);
    }
    try {
        func.apply(null, params);
    }
    catch (e) {
        return e;
    }
    doassert("did not throw exception: " + msg);
};

assert.doesNotThrow = function(func, params, msg) {
    if (assert._debug && msg) print("in assert for: " + msg);
    if (params && typeof(params) == "string") {
        throw ("2nd argument to assert.throws has to be an array, not " + params);
    }
    try {
        func.apply(null, params);
    }
    catch (e) {
        doassert("threw unexpected exception: " + e + " : " + msg);
    }
    return;
};

assert.throws.automsg = function(func, params) {
    assert.throws(func, params, func.toString());
};

assert.doesNotThrow.automsg = function(func, params) {
    assert.doesNotThrow(func, params, func.toString());
};

assert.commandWorked = function(res, msg){
    if (assert._debug && msg) print("in assert for: " + msg);

    if (res.ok == 1)
        return res;
    doassert("command failed: " + tojson(res) + " : " + msg, res);
}

assert.commandFailed = function(res, msg){
    if (assert._debug && msg) print("in assert for: " + msg);

    if (res.ok == 0)
        return res;
    doassert("command worked when it should have failed: " + tojson(res) + " : " + msg);
}

assert.commandFailedWithCode = function(res, code, msg){
    if (assert._debug && msg) print("in assert for: " + msg);

    assert(!res.ok, "Command result indicates success, but expected failure with code " + code +
          ": " + tojson(res) + " : " + msg);
    assert.eq(res.code, code, "Expected failure code did not match actual in command result: " +
              tojson(res) + " : " + msg);
    return res;
}

assert.isnull = function(what, msg){
    if (assert._debug && msg) print("in assert for: " + msg);

    if (what == null)
        return;
    doassert("supposed to be null (" + (msg || "") + ") was: " + tojson(what));
}

assert.lt = function(a, b, msg){
    if (assert._debug && msg) print("in assert for: " + msg);

    if (a < b)
        return;
    doassert(a + " is not less than " + b + " : " + msg);
}

assert.gt = function(a, b, msg){
    if (assert._debug && msg) print("in assert for: " + msg);

    if (a > b)
        return;
    doassert(a + " is not greater than " + b + " : " + msg);
}

assert.lte = function(a, b, msg){
    if (assert._debug && msg) print("in assert for: " + msg);

    if (a <= b)
        return;
    doassert(a + " is not less than or eq " + b + " : " + msg);
}

assert.gte = function(a, b, msg){
    if (assert._debug && msg) print("in assert for: " + msg);

    if (a >= b)
        return;
    doassert(a + " is not greater than or eq " + b + " : " + msg);
}

assert.between = function(a, b, c, msg, inclusive){
    if (assert._debug && msg) print("in assert for: " + msg);

    if((inclusive == undefined || inclusive == true) &&
        a <= b && b <= c) return;
    else if(a < b && b < c) return;
    doassert(b + " is not between " + a + " and " + c + " : " + msg);
}

assert.betweenIn = function(a, b, c, msg){ assert.between(a, b, c, msg, true) }
assert.betweenEx = function(a, b, c, msg){ assert.between(a, b, c, msg, false) }

assert.close = function(a, b, msg, places){
    if (places === undefined) {
        places = 4;
    }

    // This treats 'places' as digits past the decimal point.
    var absoluteError = Math.abs(a - b);
    if (Math.round(absoluteError * Math.pow(10, places)) === 0) {
        return;
    }

    // This treats 'places' as significant figures.
    var relativeError = Math.abs(absoluteError / b);
    if (Math.round(relativeError * Math.pow(10, places)) === 0) {
        return;
    }

    doassert(a + " is not equal to " + b + " within " + places +
              " places, absolute error: " + absoluteError +
              ", relative error: " + relativeError + " : " + msg);
};

/**
 * Asserts if the times in millis are not withing delta milliseconds, in either direction.
 * Default Delta: 1 second
 */
assert.closeWithinMS = function(a, b, msg, deltaMS) {
    "use strict";
    if (deltaMS === undefined) {
        deltaMS = 1000;
    }
    var aMS = a instanceof Date ? a.getTime() : a;
    var bMS = b instanceof Date ? b.getTime() : b;
    var actualDelta = Math.abs(Math.abs(aMS) - Math.abs(bMS));
    if (actualDelta <= deltaMS) return;

    doassert(a + " is not equal to " + b + " within " + deltaMS +
              " millis, actual delta: " + actualDelta + " millis : " + msg);
};

assert.writeOK = function(res, msg) {
    
    var errMsg = null;

    if (res instanceof WriteResult) {
        if (res.hasWriteError()) {
            errMsg = "write failed with error: " + tojson(res); 
        }
        else if(res.hasWriteConcernError()) {
            errMsg = "write concern failed with errors: " + tojson(res);
        }
    }
    else if (res instanceof BulkWriteResult) {
        // Can only happen with bulk inserts
        if (res.hasWriteErrors()) {
            errMsg = "write failed with errors: " + tojson(res);
        }
        else if(res.hasWriteConcernError()) {
            errMsg = "write concern failed with errors: " + tojson(res);
        }
    }
    else if (res instanceof WriteCommandError) {
        // Can only happen with bulk inserts
        errMsg = "write command failed: " + tojson(res);
    }
    else {
        errMsg = "unknown type of write result, cannot check ok: " 
                 + tojson(res);
    }
    
    if (errMsg) {
        if (msg)
            errMsg = errMsg + ": " + msg;
        doassert(errMsg, res);
    }
    
    return res;
}

assert.writeError = function(res, msg) {
    
    var errMsg = null;

    if (res instanceof WriteResult) {
        if (!res.hasWriteError() && !res.hasWriteConcernError()) {
            errMsg = "no write error: " + tojson(res); 
        }
    }
    else if (res instanceof BulkWriteResult) {
        // Can only happen with bulk inserts
        if (!res.hasWriteErrors() && !res.hasWriteConcernError()) {
            errMsg = "no write errors: " + tojson(res);
        }
    }
    else if (res instanceof WriteCommandError) {
        // Can only happen with bulk inserts
        // No-op since we're expecting an error
    }
    else {
        errMsg = "unknown type of write result, cannot check error: "
                 + tojson(res);
    }
    
    if (errMsg) {
        if (msg)
            errMsg = errMsg + ": " + msg;
        doassert(errMsg);
    }
    
    return res;
}

assert.gleOK = function(res, msg) {
    
    var errMsg = null;

    if (!res) {
        errMsg = "missing first argument, no response to check"
    }
    else if (!res.ok) {
        errMsg = "getLastError failed: " + tojson(res);
    }
    else if ('code' in res || 'errmsg' in res
             || ('err' in res && res['err'] != null)) {
        errMsg = "write or write concern failed: " + tojson(res);
    }
    
    if (errMsg) {
        if (msg)
            errMsg = errMsg + ": " + msg;
        doassert(errMsg, res);
    }
    
    return res;
}

assert.gleSuccess = function(dbOrGLEDoc, msg) {
    var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;
    if (gle.err) {
        if (typeof(msg) == "function") 
            msg = msg(gle);
        doassert("getLastError not null:" + tojson(gle) + " :" + msg, gle);
    }
    return gle;
}

assert.gleError = function(dbOrGLEDoc, msg) {
    var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;
    if (!gle.err) {
        if (typeof(msg) == "function") 
            msg = msg(gle);
        doassert("getLastError is null: " + tojson(gle) + " :" + msg);
    }
}

assert.gleErrorCode = function(dbOrGLEDoc, code, msg) {
    var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;
    if (!gle.err || gle.code != code) {
        if (typeof(msg) == "function") 
            msg = msg(gle);
        doassert("getLastError is null or has code other than \"" + code + "\": "
                 + tojson(gle) + " :" + msg);
    }
}

assert.gleErrorRegex = function(dbOrGLEDoc, regex, msg) {
    var gle = dbOrGLEDoc instanceof DB ? dbOrGLEDoc.getLastErrorObj() : dbOrGLEDoc;
    if (!gle.err || !regex.test(gle.err)) {
        if (typeof(msg) == "function") 
            msg = msg(gle);
        doassert("getLastError is null or doesn't match regex (" + regex + "): " 
                 + tojson(gle) + " :" + msg);
    }
}