summaryrefslogtreecommitdiff
path: root/jstests/noPassthrough/shell_cmd_assertions.js
blob: 4bc800663f807e087d8c91c34e5c590289f2bde7 (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
/**
 * Tests for the command assertion functions in mongo/shell/assert.js.
 */

(function() {
"use strict";

const conn = MongoRunner.runMongod();
const db = conn.getDB("commandAssertions");
const kFakeErrCode = 1234567890;
const tests = [];

const sampleWriteConcernError = {
    n: 1,
    ok: 1,
    writeConcernError: {
        code: ErrorCodes.WriteConcernFailed,
        codeName: "WriteConcernFailed",
        errmsg: "waiting for replication timed out",
        errInfo: {
            wtimeout: true,
        },
    },
};

function setup() {
    db.coll.drop();
    assert.writeOK(db.coll.insert({_id: 1}));
}

// Raw command responses.
tests.push(function rawCommandOk() {
    const res = db.runCommand({"ping": 1});
    assert.doesNotThrow(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.throws(() => assert.commandFailed(res));
    assert.throws(() => assert.commandFailedWithCode(res, 0));
});

function _assertMsgFunctionExecution(
    assertFunc, assertParameter, {expectException: expectException = false} = {}) {
    var msgFunctionCalled = false;
    var expectedAssert = assert.doesNotThrow;

    if (expectException) {
        expectedAssert = assert.throws;
    }

    expectedAssert(() => {
        assertFunc(assertParameter, () => {
            msgFunctionCalled = true;
        });
    });

    assert.eq(expectException, msgFunctionCalled, "msg function execution should match assertion");
}

tests.push(function msgFunctionOnlyCalledOnFailure() {
    const res = db.runCommand({"ping": 1});

    _assertMsgFunctionExecution(assert.commandWorked, res, {expectException: false});
    _assertMsgFunctionExecution(
        assert.commandWorkedIgnoringWriteErrors, res, {expectException: false});
    _assertMsgFunctionExecution(assert.commandFailed, res, {expectException: true});

    var msgFunctionCalled = false;
    assert.throws(() => assert.commandFailedWithCode(res, 0, () => {
        msgFunctionCalled = true;
    }));
    assert.eq(true, msgFunctionCalled, "msg function execution should match assertion");
});

tests.push(function rawCommandErr() {
    const res = db.runCommand({"IHopeNobodyEverMakesThisACommand": 1});
    assert.throws(() => assert.commandWorked(res));
    assert.throws(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.CommandNotFound));
    // commandFailedWithCode should succeed if any of the passed error codes are matched.
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.CommandNotFound, kFakeErrCode]));
    assert.doesNotThrow(() => assert.commandWorkedOrFailedWithCode(
                            res,
                            [ErrorCodes.CommandNotFound, kFakeErrCode],
                            "threw even though failed with correct error codes"));
    assert.throws(
        () => assert.commandWorkedOrFailedWithCode(
            res, [kFakeErrCode], "didn't throw even though failed with incorrect error code"));
});

tests.push(function rawCommandWriteOk() {
    const res = db.runCommand({insert: "coll", documents: [{_id: 2}]});
    assert.doesNotThrow(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.throws(() => assert.commandFailed(res));
    assert.throws(() => assert.commandFailedWithCode(res, 0));
    assert.doesNotThrow(
        () => assert.commandWorkedOrFailedWithCode(res, 0, "threw even though succeeded"));
});

tests.push(function rawCommandWriteErr() {
    const res = db.runCommand({insert: "coll", documents: [{_id: 1}]});
    assert.throws(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.DuplicateKey));
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.DuplicateKey, kFakeErrCode]));
    assert.throws(
        () => assert.commandWorkedOrFailedWithCode(
            res, [ErrorCodes.DuplicateKey, kFakeErrCode], "expected to throw on write error"));
    assert.throws(() => assert.commandWorkedOrFailedWithCode(
                      res, [kFakeErrCode], "expected to throw on write error"));
});

tests.push(function collInsertWriteOk() {
    const res = db.coll.insert({_id: 2});
    assert(res instanceof WriteResult);
    assert.doesNotThrow(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.throws(() => assert.commandFailed(res));
    assert.throws(() => assert.commandFailedWithCode(res, 0));
});

tests.push(function collInsertWriteErr() {
    const res = db.coll.insert({_id: 1});
    assert(res instanceof WriteResult);
    assert.throws(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.DuplicateKey));
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.DuplicateKey, kFakeErrCode]));
});

tests.push(function collMultiInsertWriteOk() {
    const res = db.coll.insert([{_id: 3}, {_id: 2}]);
    assert(res instanceof BulkWriteResult);
    assert.doesNotThrow(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.throws(() => assert.commandFailed(res));
    assert.throws(() => assert.commandFailedWithCode(res, 0));
    assert.throws(() =>
                      assert.commandWorkedOrFailedWithCode(res, 0, "threw even though succeeded"));
});

tests.push(function collMultiInsertWriteErr() {
    const res = db.coll.insert([{_id: 1}, {_id: 2}]);
    assert(res instanceof BulkWriteResult);
    assert.throws(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.DuplicateKey));
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.DuplicateKey, kFakeErrCode]));
});

// Test when the insert command fails with ok:0 (i.e. not failing due to write err)
tests.push(function collInsertCmdErr() {
    const res = db.coll.insert({x: 1}, {writeConcern: {"bad": 1}});
    assert(res instanceof WriteCommandError);
    assert.throws(() => assert.commandWorked(res));
    assert.throws(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.FailedToParse));
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.FailedToParse, kFakeErrCode]));
});

tests.push(function collMultiInsertCmdErr() {
    const res = db.coll.insert([{x: 1}, {x: 2}], {writeConcern: {"bad": 1}});
    assert(res instanceof WriteCommandError);
    assert.throws(() => assert.commandWorked(res));
    assert.throws(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.FailedToParse));
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.FailedToParse, kFakeErrCode]));
    assert.doesNotThrow(() => assert.commandWorkedOrFailedWithCode(
                            res,
                            [ErrorCodes.FailedToParse, kFakeErrCode],
                            "threw even though failed with correct error codes"));
    assert.throws(
        () => assert.commandWorkedOrFailedWithCode(
            res, [kFakeErrCode], "didn't throw even though failed with incorrect error codes"));
});

tests.push(function mapReduceOk() {
    const res = db.coll.mapReduce(
        function() {
            emit(this._id, 0);
        },
        function(k, v) {
            return v[0];
        },
        {out: "coll_out"});
    assert(res instanceof MapReduceResult);
    assert.doesNotThrow(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.throws(() => assert.commandFailed(res));
    assert.throws(() => assert.commandFailedWithCode(res, 0));
});

tests.push(function mapReduceErr() {
    // db.coll.mapReduce throws if the command response has ok:0
    // Instead manually construct a MapReduceResult with ok:0
    const res = new MapReduceResult(db, {
        "ok": 0,
        "errmsg": "Example Error",
        "code": ErrorCodes.JSInterpreterFailure,
        "codeName": "JSInterpreterFailure"
    });
    assert.throws(() => assert.commandWorked(res));
    assert.throws(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.JSInterpreterFailure));
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.JSInterpreterFailure, kFakeErrCode]));
});

tests.push(function crudInsertOneOk() {
    const res = db.coll.insertOne({_id: 2});
    assert(res.hasOwnProperty("acknowledged"));
    assert.doesNotThrow(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.throws(() => assert.commandFailed(res));
    assert.throws(() => assert.commandFailedWithCode(res, 0));
});

tests.push(function crudInsertOneErr() {
    let threw = false;
    let res = null;
    try {
        db.coll.insertOne({_id: 1});
    } catch (e) {
        threw = true;
        res = e;
    }
    assert(threw);
    assert(res instanceof WriteError);
    assert.throws(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.DuplicateKey));
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.DuplicateKey, kFakeErrCode]));
});

tests.push(function crudInsertManyOk() {
    const res = db.coll.insertMany([{_id: 2}, {_id: 3}]);
    assert(res.hasOwnProperty("acknowledged"));
    assert.doesNotThrow(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.throws(() => assert.commandFailed(res));
    assert.throws(() => assert.commandFailedWithCode(res, 0));
});

tests.push(function crudInsertManyErr() {
    let threw = false;
    let res = null;
    try {
        db.coll.insertMany([{_id: 1}, {_id: 2}]);
    } catch (e) {
        threw = true;
        res = e;
    }
    assert(threw);
    assert(res instanceof BulkWriteError);
    assert.throws(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.DuplicateKey));
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.DuplicateKey, kFakeErrCode]));
});

tests.push(function rawMultiWriteErr() {
    // Do an unordered bulk insert with duplicate keys to produce multiple write errors.
    const res = db.runCommand({"insert": "coll", documents: [{_id: 1}, {_id: 1}], ordered: false});
    assert(res.writeErrors.length == 2, "did not get multiple write errors");
    assert.throws(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.DuplicateKey));
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.DuplicateKey, kFakeErrCode]));
});

tests.push(function bulkMultiWriteErr() {
    // Do an unordered bulk insert with duplicate keys to produce multiple write errors.
    const res = db.coll.insert([{_id: 1}, {_id: 1}], {ordered: false});
    assert.throws(() => assert.commandWorked(res));
    assert.doesNotThrow(() => assert.commandWorkedIgnoringWriteErrors(res));
    assert.doesNotThrow(() => assert.commandFailed(res));
    assert.doesNotThrow(() => assert.commandFailedWithCode(res, ErrorCodes.DuplicateKey));
    assert.doesNotThrow(
        () => assert.commandFailedWithCode(res, [ErrorCodes.DuplicateKey, kFakeErrCode]));
});

tests.push(function writeConcernErrorCausesCommandWorkedToAssert() {
    const result = sampleWriteConcernError;

    assert.throws(() => {
        assert.commandWorked(result);
    });
});

tests.push(function writeConcernErrorCausesCommandFailedToPass() {
    const result = sampleWriteConcernError;

    assert.doesNotThrow(() => {
        assert.commandFailed(result);
        assert.commandFailedWithCode(result, ErrorCodes.WriteConcernFailed);
    });
});

tests.push(function writeConcernErrorCanBeIgnored() {
    const result = sampleWriteConcernError;

    assert.doesNotThrow(() => {
        assert.commandWorkedIgnoringWriteConcernErrors(result);
    });
});

tests.push(function invalidResponsesAttemptToProvideInformationToCommandWorks() {
    const invalidResponses = [undefined, 'not a valid response', 42];

    invalidResponses.forEach((invalidRes) => {
        const error = assert.throws(() => {
            assert.commandWorked(invalidRes);
        });

        assert.gte(error.message.indexOf(invalidRes), 0);
        assert.gte(error.message.indexOf(typeof invalidRes), 0);
    });
});

tests.push(function invalidResponsesAttemptToProvideInformationCommandFailed() {
    const invalidResponses = [undefined, 'not a valid response', 42];

    invalidResponses.forEach((invalidRes) => {
        const error = assert.throws(() => {
            assert.commandFailed(invalidRes);
        });

        assert.gte(error.message.indexOf(invalidRes), 0);
        assert.gte(error.message.indexOf(typeof invalidRes), 0);
    });
});

tests.forEach((test) => {
    jsTest.log(`Starting test '${test.name}'`);
    setup();
    test();
});

/* cleanup */
MongoRunner.stopMongod(conn);
})();