Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 3c50160232f3527beebf17f0bb0976ec067e277b (plain) (blame)
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
// ==================================================================================
// Copyright (c) 2000-2018 Ericsson Telecom AB AB
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v2.0
// which accompanies this distribution, and is available at
// https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html
// ==================================================================================
// Contributors:
//  Krisztian Gulyas - initial implementation and initial documentation
//
//  File:               MongoDBTest.ttcn
//  Rev:                R1A
//  Prodnr:             CNL 0
// ==================================================================================

module MongoDBTest
{
    // ==============================================================================
    //
    // Import(s)
    //
    // ==============================================================================

    // mongoDB prototol messages and helper functions
    import from MongoDB_Types all;
    import from MongoDB_Functions all;

    // import basic defitions for TCP/IP communication
    import from IPL4asp_Types all;
	import from IPL4asp_PortType all;
    import from SimpleTCP all;

    // ==============================================================================
    //
    // Module parameter(s)
    //
    // ==============================================================================

    // local and remote TCP host/port
    modulepar { SimpleTCP.ConnectionData LocalTCPConnection, RemoteTCPConnection }

    // ==============================================================================
    //
    // Component(s)
    //
    // ==============================================================================

    // test component type definition
    type component testComponent
    {
        port IPL4asp_PT testPort;
    }

    // ==============================================================================
    //
    // Additional types and functions
    //
    // ==============================================================================

    // Wrapper function for MongoDB message length function
    function IPL4asp_MsgLen(in octetstring stream, inout ro_integer args) return integer {
        var integer l := MsgLen(stream)
        log ("  [::] TCP (mongoDB) message length: ", l);
        return l;
    }

    // ------------------------------------------------------------------------------
    // Generic function testing mongoDB wire protocol (using testComponent):
    //
    // 1) encoding the given mongoDB wire message
    // 2) sending message (via TCP)
    // 3) if necessary:
    //  - catching reply message
    //  - decoding and evaluating it
    //
    // parameters:
    //      - Msg               mongoDB message template
    //      - expectResponse    expect response message [true/false]
    // ------------------------------------------------------------------------------
    function testMongoDB (
        in template Msg     mongo_msg,          // mongoDB test message template
        boolean             expectResponse)     // expect response message [true/false]
        runs on testComponent
    {
        var octetstring pduOut, pduIn;

        @try {
            // trying to encode the outgoing message
            pduOut := encMsg(valueof(mongo_msg));
        }
        @catch(err) {
            log("[!!] Unable to encode the outgoing message | error: ", err);
            setverdict(fail);
        }

        // logging the encoded message (encoder updates some fields)
        log("[=>] MongoDB message encoded and sent: ", decMsg(pduOut));

        if (SimpleTCP.sendReceiveMsg (
            testPort,
            refers(IPL4asp_MsgLen),
            LocalTCPConnection,
            RemoteTCPConnection,
            pduOut,
            pduIn,
            expectResponse)) {

            if (expectResponse) {
                // initalize a mongoDB query message
                var Msg mongo_reply_msg;

                // trying to decode the incomming message
                @try {
                    mongo_reply_msg := decMsg(pduIn);

                    var JSONRecords json;
                    var integer error_code := bsonStream2json(mongo_reply_msg.reply_.documents.octets, json);
                    // check return value of bson stream conversion
                    if (error_code != 0) {
                        setverdict(fail);
                    }
                    else {
                        mongo_reply_msg.reply_.documents.json := json;
                    }
                }
                @catch(err) {
                    log("[!!] Unable to decode incomming message | error: ", err);
                    setverdict(fail);
                }

                // compare received message with reply template
                if (match(mongo_reply_msg, replyMsgTemplate)) {
                    log("[<=] MongoDB reply message received: ", mongo_reply_msg);
                    setverdict(pass);
                }
                else {
                    log("[<=] Response does not match.");
                    setverdict(fail);
                }
            }
            else {
                setverdict(pass);
            }
        }
        else {
            // TCP communication error
            setverdict(fail);
        }
    }

    // ==============================================================================
    //
    // mongoDB message template definitions (based on the message definitions)
    //
    // ==============================================================================

    // ------------------------------------------------------------------------------
    // mongoDB insert template
    // ------------------------------------------------------------------------------
    template Msg insertMsgTemplate (
        universal charstring    fullConnectionName_,
        integer                 flag_bytes_,
        octetstring             documents_
        ) :=
    {
        insert := {
            header :=               { messageLength := 0, requestId := 1, responseTo := 0, opCode := OP_UNDEFINED },
            flags :=                { bytes := flag_bytes_ },
            fullCollectionName :=   fullConnectionName_,
            documents :=            documents_
        }
    }


    // ------------------------------------------------------------------------------
    // mongoDB update template
    // ------------------------------------------------------------------------------
    template Msg updateMsgTemplate (
        universal charstring    fullConnectionName_,
        integer                 flag_bytes_,
        octetstring             selector_,
        octetstring             update_
    ) :=
    {
        update := {
            header :=               { messageLength := 0, requestId := 1, responseTo := 0, opCode := OP_UNDEFINED },
            ZERO :=                 0,
            fullCollectionName :=   fullConnectionName_,
            flags :=                { bytes := flag_bytes_ },
            selector :=             selector_,
            update :=               update_
        }
    }

    // ------------------------------------------------------------------------------
    // mongoDB query template
    // ------------------------------------------------------------------------------
    template Msg queryMsgTemplate (
        universal charstring    fullConnectionName_,
        integer                 flag_bytes_,
        integer                 numberToSkip_,
        integer                 numberToReturn_,
        octetstring             query_
        ) :=
    {
        query := {
            header :=               { messageLength := 0, requestId := 1, responseTo := 0, opCode := OP_UNDEFINED},
            flags :=                { bytes := flag_bytes_ },
            fullCollectionName :=   fullConnectionName_,
            numberToSkip :=         numberToSkip_,
            numberToReturn :=       numberToReturn_,
            query :=                query_,
            returnFieldsSelector := omit
        }
    }

    // ------------------------------------------------------------------------------
    // mongoDB get more template
    // ------------------------------------------------------------------------------
    template Msg getMoreMsgTemplate (
        universal charstring    fullConnectionName_,
        integer                 numberToReturn_,
        integer                 cursorID_
        ) :=
    {
        getMore := {
            header :=               { messageLength := 0, requestId := 1, responseTo := 0, opCode := OP_UNDEFINED},
            ZERO :=                 0,
            fullCollectionName :=   fullConnectionName_,
            numberToReturn :=       numberToReturn_,
            cursorID :=             cursorID_
        }
    }

    // ------------------------------------------------------------------------------
    // mongoDB delete template
    // ------------------------------------------------------------------------------
    template Msg deleteMsgTemplate (
        universal charstring    fullConnectionName_,
        integer                 flag_bytes_,
        octetstring             selector_
        ) :=
    {
        delete := {
            header :=               { messageLength := 0, requestId := 1, responseTo := 0, opCode := OP_UNDEFINED },
            ZERO :=                 0,
            fullCollectionName :=   fullConnectionName_,
            flags :=                { bytes := flag_bytes_ },
            selector :=             selector_
        }
    }

    // ------------------------------------------------------------------------------
    // mongoDB kill cursor template
    // ------------------------------------------------------------------------------
    // record of integer
    type record of integer roInteger;

    template Msg killCursorMsgTemplate (
        integer                 numberOfCursorIDs_,
        roInteger               cursorID_
        ) :=
    {
        killCursor := {
            header :=               { messageLength := 0, requestId := 1, responseTo := 0, opCode := OP_UNDEFINED },
            ZERO :=                 0,
            numberOfCursorIDs :=    numberOfCursorIDs_,
            cursorIDs :=            cursorID_
        }
    }

    // ------------------------------------------------------------------------------
    // mongoDB reply message template
    // ------------------------------------------------------------------------------
    template Msg replyMsgTemplate :=
    {
        reply_ := {
            header :=           { messageLength := ?, requestId := ?, responseTo := ?, opCode := OP_REPLY },
            responseFlags :=    ?,
            cursorID :=         ?,
            startingFrom :=     ?,
            numberReturned :=   ?,
            documents :=        ?
        }
    }

    // ==============================================================================
    //
    // Test cases
    //
    // ==============================================================================

    // ------------------------------------------------------------------------------
    // Testing MongoDB insert message (no reply message)
    // ------------------------------------------------------------------------------
    testcase TC_Insert(in universal charstring data) runs on testComponent
    {
        log("===================================================================================");
        log("[::] TC: Insert message test");

        map(mtc:testPort, system:testPort);

        testMongoDB(
            insertMsgTemplate(
                "test.ttcn",        // dbname.collectionname
                1,                  // insert flags as byte
                // one or more BSON documents to insert into the collection
                json2bson("{ \"command\": \"insert\", \"data\": " & data & "}")
            ),
            false);

        log("");
    }



    // ------------------------------------------------------------------------------
    // Testing MongoDB update message (no reply message)
    // ------------------------------------------------------------------------------
    testcase TC_Update() runs on testComponent
    {
        log("===================================================================================");
        log("[::] TC Update message test");

        map(mtc:testPort, system:testPort);

        testMongoDB(
            updateMsgTemplate(
                "test.ttcn",        // dbname.collectionname
                1,                  // update flags as byte
                // BSON document that specifies the query for selection of the document to update
                json2bson("{}"),
                // BSON document that specifies the update to be performed
                json2bson("{ \"command\": \"update\", \"data\": \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \"}")
            ),
            false);

        log("");
    }


    // ------------------------------------------------------------------------------
    // Testing MongoDB query message
    // ------------------------------------------------------------------------------
    testcase TC_Query() runs on testComponent
    {
        log("===================================================================================");
        log("[::] TC: Query message test");

        map(mtc:testPort, system:testPort);

        testMongoDB(
            queryMsgTemplate(
                "test.ttcn",        // dbname.collectionname
                0,                  // query flags as byte
                0,                  // number of documents to skip
                0,                  // number of documents to return in the first OP_REPLY batch
                // BSON document that represents the query
                json2bson("{}")
            ),
            true);

        log("");
    }


    // ------------------------------------------------------------------------------
    // Testing MongoDB get more message
    // ------------------------------------------------------------------------------
    testcase TC_GetMore() runs on testComponent
    {
        log("===================================================================================");
        log("[::] TC: Get More message test");

        map(mtc:testPort, system:testPort);

        testMongoDB(
            getMoreMsgTemplate(
                "test.ttcn",        // dbname.collectionname
                0,                  // number of documents to return
                0                   // cursor id from OP_REPLY
            ),
            true);

        log("");
    }


    // ------------------------------------------------------------------------------
    // Testing MongoDB delete message (no reply message)
    // ------------------------------------------------------------------------------
    testcase TC_Delete() runs on testComponent
    {
        log("===================================================================================");
        log("[::] TC: Delete message test");

        map(mtc:testPort, system:testPort);

        testMongoDB(
            deleteMsgTemplate(
                "test.ttcn",        // dbname.collectionname
                0,                  // query flags as byte
                // BSON document that represent the query used to select the documents to be removed.
                json2bson("{\"data\": 17}")
            ),
            false);

        log("");
    }


    // ------------------------------------------------------------------------------
    // Testing MongoDB delete message (no reply message)
    // ------------------------------------------------------------------------------
    testcase TC_KillCursor() runs on testComponent
    {

        log("===================================================================================");
        log("[::] TC: KillCursor message test");

        map(mtc:testPort, system:testPort);

        testMongoDB(valueof(
            killCursorMsgTemplate(
                    1,              // number of cursorIDs in message
                    {1, 2, 3}       // sequence of cursorIDs
                )),
            false);

        log("");
    }

    // ==============================================================================
    //
    // Run the following testcases
    //
    // ==============================================================================
    control
    {

        // insert 20 records
        for (var integer i := 0; i < 20; i := i + 1) {
            execute(TC_Insert(int2str(i)));
        }
        execute(TC_Update());
        execute(TC_Query());
        execute(TC_GetMore());
        execute(TC_Delete());
        execute(TC_KillCursor());
        execute(TC_Query());

    }
}

Back to the top