summaryrefslogtreecommitdiff
path: root/src/mongo/dbtests/mock_dbclient_conn_test.cpp
blob: 0aeedceb720face7ae6ec6152cc6141ca583764a (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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

/**
 * This file includes integration testing between the MockDBClientBase and MockRemoteDB.
 */

#include "mongo/platform/basic.h"

#include "mongo/db/jsobj.h"
#include "mongo/dbtests/mock/mock_dbclient_connection.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/net/socket_exception.h"
#include "mongo/util/timer.h"

#include <ctime>
#include <string>
#include <vector>

using mongo::BSONObj;
using mongo::ConnectionString;
using mongo::MockDBClientConnection;
using mongo::MockRemoteDBServer;
using mongo::NamespaceString;
using mongo::Query;

using std::string;
using std::vector;

namespace mongo_test {

TEST(MockDBClientConnTest, ServerAddress) {
    MockRemoteDBServer server("test");
    MockDBClientConnection conn(&server);
    uassertStatusOK(conn.connect(server.getServerHostAndPort(), mongo::StringData(), boost::none));

    ASSERT_EQUALS("test:27017", conn.getServerAddress());
    ASSERT_EQUALS("test:27017", conn.toString());
    ASSERT_EQUALS(mongo::HostAndPort("test"), conn.getServerHostAndPort());
}

TEST(MockDBClientConnTest, QueryCount) {
    MockRemoteDBServer server("test");

    {
        MockDBClientConnection conn(&server);

        ASSERT_EQUALS(0U, server.getQueryCount());
        conn.query(NamespaceString("foo.bar"));
    }

    ASSERT_EQUALS(1U, server.getQueryCount());

    {
        MockDBClientConnection conn(&server);
        conn.query(NamespaceString("foo.bar"));
        ASSERT_EQUALS(2U, server.getQueryCount());
    }
}

TEST(MockDBClientConnTest, InsertAndQuery) {
    MockRemoteDBServer server("test");
    const string ns("test.user");

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns));
        ASSERT(!cursor->more());

        server.insert(ns, BSON("x" << 1));
        server.insert(ns, BSON("y" << 2));
    }

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns));

        ASSERT(cursor->more());
        BSONObj firstDoc = cursor->next();
        ASSERT_EQUALS(1, firstDoc["x"].numberInt());

        ASSERT(cursor->more());
        BSONObj secondDoc = cursor->next();
        ASSERT_EQUALS(2, secondDoc["y"].numberInt());

        ASSERT(!cursor->more());
    }

    // Make sure that repeated calls will still give you the same result
    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns));

        ASSERT(cursor->more());
        BSONObj firstDoc = cursor->next();
        ASSERT_EQUALS(1, firstDoc["x"].numberInt());

        ASSERT(cursor->more());
        BSONObj secondDoc = cursor->next();
        ASSERT_EQUALS(2, secondDoc["y"].numberInt());

        ASSERT(!cursor->more());
    }
}

TEST(MockDBClientConnTest, InsertAndQueryTwice) {
    MockRemoteDBServer server("test");
    const string ns("test.user");

    server.insert(ns, BSON("x" << 1));

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns));

        ASSERT(cursor->more());
        BSONObj firstDoc = cursor->next();
        ASSERT_EQUALS(1, firstDoc["x"].numberInt());
    }

    server.insert(ns, BSON("y" << 2));

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns));

        ASSERT(cursor->more());
        BSONObj firstDoc = cursor->next();
        ASSERT_EQUALS(1, firstDoc["x"].numberInt());

        ASSERT(cursor->more());
        BSONObj secondDoc = cursor->next();
        ASSERT_EQUALS(2, secondDoc["y"].numberInt());

        ASSERT(!cursor->more());
    }
}

TEST(MockDBClientConnTest, QueryWithNoResults) {
    MockRemoteDBServer server("test");
    const string ns("test.user");

    server.insert(ns, BSON("x" << 1));
    MockDBClientConnection conn(&server);
    std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString("other.ns"));

    ASSERT(!cursor->more());
}

TEST(MockDBClientConnTest, MultiNSInsertAndQuery) {
    MockRemoteDBServer server("test");
    const string ns1("test.user");
    const string ns2("foo.bar");
    const string ns3("mongo.db");

    {
        MockDBClientConnection conn(&server);
        conn.insert(ns1, BSON("a" << 1));
        conn.insert(ns2,
                    BSON("ef"
                         << "gh"));
        conn.insert(ns3, BSON("x" << 2));

        conn.insert(ns1, BSON("b" << 3));
        conn.insert(ns2,
                    BSON("jk"
                         << "lm"));

        conn.insert(ns2,
                    BSON("x"
                         << "yz"));
    }

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns1));

        ASSERT(cursor->more());
        BSONObj firstDoc = cursor->next();
        ASSERT_EQUALS(1, firstDoc["a"].numberInt());

        ASSERT(cursor->more());
        BSONObj secondDoc = cursor->next();
        ASSERT_EQUALS(3, secondDoc["b"].numberInt());

        ASSERT(!cursor->more());
    }

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns2));

        ASSERT(cursor->more());
        BSONObj firstDoc = cursor->next();
        ASSERT_EQUALS("gh", firstDoc["ef"].String());

        ASSERT(cursor->more());
        BSONObj secondDoc = cursor->next();
        ASSERT_EQUALS("lm", secondDoc["jk"].String());

        ASSERT(cursor->more());
        BSONObj thirdDoc = cursor->next();
        ASSERT_EQUALS("yz", thirdDoc["x"].String());

        ASSERT(!cursor->more());
    }

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns3));

        ASSERT(cursor->more());
        BSONObj firstDoc = cursor->next();
        ASSERT_EQUALS(2, firstDoc["x"].numberInt());

        ASSERT(!cursor->more());
    }
}

TEST(MockDBClientConnTest, SimpleRemove) {
    MockRemoteDBServer server("test");
    const string ns("test.user");

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns));
        ASSERT(!cursor->more());

        conn.insert(ns, BSON("x" << 1));
        conn.insert(ns, BSON("y" << 1));
    }

    {
        MockDBClientConnection conn(&server);
        conn.remove(ns, BSONObj{} /*filter*/);
    }

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns));

        ASSERT(!cursor->more());
    }

    // Make sure that repeated calls will still give you the same result
    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns));

        ASSERT(!cursor->more());
    }
}

TEST(MockDBClientConnTest, MultiNSRemove) {
    MockRemoteDBServer server("test");
    const string ns1("test.user");
    const string ns2("foo.bar");
    const string ns3("mongo.db");

    {
        MockDBClientConnection conn(&server);
        conn.insert(ns1, BSON("a" << 1));
        conn.insert(ns2,
                    BSON("ef"
                         << "gh"));
        conn.insert(ns3, BSON("x" << 2));

        conn.insert(ns1, BSON("b" << 3));
        conn.insert(ns2,
                    BSON("jk"
                         << "lm"));

        conn.insert(ns2,
                    BSON("x"
                         << "yz"));
    }

    {
        MockDBClientConnection conn(&server);
        conn.remove(ns2, BSONObj{} /*filter*/);

        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns2));
        ASSERT(!cursor->more());
    }

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns1));

        ASSERT(cursor->more());
        BSONObj firstDoc = cursor->next();
        ASSERT_EQUALS(1, firstDoc["a"].numberInt());

        ASSERT(cursor->more());
        BSONObj secondDoc = cursor->next();
        ASSERT_EQUALS(3, secondDoc["b"].numberInt());

        ASSERT(!cursor->more());
    }

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns3));

        ASSERT(cursor->more());
        BSONObj firstDoc = cursor->next();
        ASSERT_EQUALS(2, firstDoc["x"].numberInt());

        ASSERT(!cursor->more());
    }
}

TEST(MockDBClientConnTest, InsertAfterRemove) {
    MockRemoteDBServer server("test");
    const string ns("test.user");

    {
        MockDBClientConnection conn(&server);
        conn.insert(ns, BSON("a" << 1));
        conn.insert(ns, BSON("b" << 3));
        conn.insert(ns,
                    BSON("x"
                         << "yz"));
    }

    {
        MockDBClientConnection conn(&server);
        conn.remove(ns, BSONObj{} /*filter*/);
    }

    {
        MockDBClientConnection conn(&server);
        conn.insert(ns, BSON("x" << 100));
    }

    {
        MockDBClientConnection conn(&server);
        std::unique_ptr<mongo::DBClientCursor> cursor = conn.query(NamespaceString(ns));

        ASSERT(cursor->more());
        BSONObj firstDoc = cursor->next();
        ASSERT_EQUALS(100, firstDoc["x"].numberInt());

        ASSERT(!cursor->more());
    }
}

TEST(MockDBClientConnTest, SetCmdReply) {
    MockRemoteDBServer server("test");
    server.setCommandReply("serverStatus",
                           BSON("ok" << 1 << "host"
                                     << "local"));

    {
        MockDBClientConnection conn(&server);
        BSONObj response;
        ASSERT(conn.runCommand("foo.bar", BSON("serverStatus" << 1), response));
        ASSERT_EQUALS(1, response["ok"].numberInt());
        ASSERT_EQUALS("local", response["host"].str());

        ASSERT_EQUALS(1U, server.getCmdCount());
    }

    // Make sure that repeated calls will still give you the same result
    {
        MockDBClientConnection conn(&server);
        BSONObj response;
        ASSERT(conn.runCommand("foo.bar", BSON("serverStatus" << 1), response));
        ASSERT_EQUALS(1, response["ok"].numberInt());
        ASSERT_EQUALS("local", response["host"].str());

        ASSERT_EQUALS(2U, server.getCmdCount());
    }

    {
        MockDBClientConnection conn(&server);
        BSONObj response;
        ASSERT(conn.runCommand("foo.bar", BSON("serverStatus" << 1), response));
        ASSERT_EQUALS(1, response["ok"].numberInt());
        ASSERT_EQUALS("local", response["host"].str());

        ASSERT_EQUALS(3U, server.getCmdCount());
    }
}

TEST(MockDBClientConnTest, CyclingCmd) {
    MockRemoteDBServer server("test");

    {
        vector<mongo::StatusWith<BSONObj>> isMasterSequence;
        isMasterSequence.push_back(BSON("set"
                                        << "a"
                                        << "isMaster" << true << "ok" << 1));
        isMasterSequence.push_back(BSON("set"
                                        << "a"
                                        << "isMaster" << false << "ok" << 1));
        server.setCommandReply("isMaster", isMasterSequence);
    }

    {
        MockDBClientConnection conn(&server);
        BSONObj response;
        ASSERT(conn.runCommand("foo.baz", BSON("isMaster" << 1), response));
        ASSERT_EQUALS(1, response["ok"].numberInt());
        ASSERT_EQUALS("a", response["set"].str());
        ASSERT(response["isMaster"].trueValue());

        ASSERT_EQUALS(1U, server.getCmdCount());
    }

    {
        MockDBClientConnection conn(&server);
        BSONObj response;
        ASSERT(conn.runCommand("foo.baz", BSON("isMaster" << 1), response));
        ASSERT_EQUALS(1, response["ok"].numberInt());
        ASSERT_EQUALS("a", response["set"].str());
        ASSERT(!response["isMaster"].trueValue());

        ASSERT_EQUALS(2U, server.getCmdCount());
    }

    {
        MockDBClientConnection conn(&server);
        BSONObj response;
        ASSERT(conn.runCommand("foo.baz", BSON("isMaster" << 1), response));
        ASSERT_EQUALS(1, response["ok"].numberInt());
        ASSERT_EQUALS("a", response["set"].str());
        ASSERT(response["isMaster"].trueValue());

        ASSERT_EQUALS(3U, server.getCmdCount());
    }
}

TEST(MockDBClientConnTest, MultipleStoredResponse) {
    MockRemoteDBServer server("test");
    server.setCommandReply("serverStatus", BSON("ok" << 0));
    server.setCommandReply("isMaster", BSON("ok" << 1 << "secondary" << false));

    MockDBClientConnection conn(&server);
    {
        BSONObj response;
        ASSERT(conn.runCommand("foo.baz",
                               BSON("isMaster"
                                    << "abc"),
                               response));
        ASSERT(!response["secondary"].trueValue());
    }

    {
        BSONObj response;
        ASSERT(!conn.runCommand("a.b", BSON("serverStatus" << 1), response));
    }
}

TEST(MockDBClientConnTest, CmdCount) {
    MockRemoteDBServer server("test");
    ASSERT_EQUALS(0U, server.getCmdCount());

    server.setCommandReply("serverStatus", BSON("ok" << 1));

    {
        MockDBClientConnection conn(&server);
        BSONObj response;
        ASSERT(conn.runCommand("foo.bar", BSON("serverStatus" << 1), response));
        ASSERT_EQUALS(1U, server.getCmdCount());
    }

    {
        MockDBClientConnection conn(&server);
        BSONObj response;
        ASSERT(conn.runCommand("baz.bar", BSON("serverStatus" << 1), response));
        ASSERT_EQUALS(2U, server.getCmdCount());
    }
}

TEST(MockDBClientConnTest, Shutdown) {
    MockRemoteDBServer server("test");
    server.setCommandReply("serverStatus", BSON("ok" << 1));
    ASSERT(server.isRunning());

    {
        MockDBClientConnection conn(&server);

        server.shutdown();
        ASSERT(!server.isRunning());

        ASSERT_THROWS(conn.query(NamespaceString("test.user")), mongo::NetworkException);
    }

    {
        MockDBClientConnection conn(&server);
        BSONObj response;
        ASSERT_THROWS(conn.runCommand("test.user", BSON("serverStatus" << 1), response),
                      mongo::NetworkException);
    }

    ASSERT_EQUALS(0U, server.getQueryCount());
    ASSERT_EQUALS(0U, server.getCmdCount());
}

TEST(MockDBClientConnTest, Restart) {
    MockRemoteDBServer server("test");
    server.setCommandReply("serverStatus", BSON("ok" << 1));

    MockDBClientConnection conn1(&server);

    // Do some queries and commands then check the counters later that
    // new instance still has it
    conn1.query(NamespaceString("test.user"));
    BSONObj response;
    conn1.runCommand("test.user", BSON("serverStatus" << 1), response);

    server.shutdown();
    ASSERT_THROWS(conn1.query(NamespaceString("test.user")), mongo::NetworkException);

    // New connections shouldn't work either
    MockDBClientConnection conn2(&server);
    ASSERT_THROWS(conn2.query(NamespaceString("test.user")), mongo::NetworkException);

    ASSERT_EQUALS(1U, server.getQueryCount());
    ASSERT_EQUALS(1U, server.getCmdCount());

    server.reboot();
    ASSERT(server.isRunning());

    {
        MockDBClientConnection conn(&server);
        conn.query(NamespaceString("test.user"));
    }

    // Old connections still shouldn't work
    ASSERT_THROWS(conn1.query(NamespaceString("test.user")), mongo::NetworkException);
    ASSERT_THROWS(conn2.query(NamespaceString("test.user")), mongo::NetworkException);

    ASSERT_EQUALS(2U, server.getQueryCount());
    ASSERT_EQUALS(1U, server.getCmdCount());
}

TEST(MockDBClientConnTest, ClearCounter) {
    MockRemoteDBServer server("test");
    server.setCommandReply("serverStatus", BSON("ok" << 1));

    MockDBClientConnection conn(&server);
    conn.query(NamespaceString("test.user"));
    BSONObj response;
    conn.runCommand("test.user", BSON("serverStatus" << 1), response);

    server.clearCounters();
    ASSERT_EQUALS(0U, server.getQueryCount());
    ASSERT_EQUALS(0U, server.getCmdCount());
}

TEST(MockDBClientConnTest, Delay) {
    MockRemoteDBServer server("test");
    server.setCommandReply("serverStatus", BSON("ok" << 1));
    server.setDelay(150);

    MockDBClientConnection conn(&server);

    {
        mongo::Timer timer;
        conn.query(NamespaceString("x.x"));
        const int nowInMilliSec = timer.millis();
        // Use a more lenient lower bound since some platforms like Windows
        // don't guarantee that sleeps will not wake up earlier (unlike
        // nanosleep we use for Linux)
        ASSERT_GREATER_THAN_OR_EQUALS(nowInMilliSec, 130);
    }

    {
        mongo::Timer timer;
        BSONObj response;
        conn.runCommand("x.x", BSON("serverStatus" << 1), response);
        const int nowInMilliSec = timer.millis();
        ASSERT_GREATER_THAN_OR_EQUALS(nowInMilliSec, 130);
    }

    ASSERT_EQUALS(1U, server.getQueryCount());
    ASSERT_EQUALS(1U, server.getCmdCount());
}

const auto docObj = [](int i) { return BSON("_id" << i); };
const auto metadata = [](int i) { return BSON("$fakeMetaData" << i); };
const long long cursorId = 123;
const bool moreToCome = true;
const NamespaceString nss("test", "coll");

TEST(MockDBClientConnTest, SimulateCallAndRecvResponses) {
    MockRemoteDBServer server("test");
    MockDBClientConnection conn(&server);

    mongo::DBClientCursor cursor(&conn,
                                 mongo::NamespaceStringOrUUID(nss),
                                 BSONObj{},
                                 Query(),
                                 0,
                                 0,
                                 nullptr,
                                 mongo::QueryOption_Exhaust,
                                 0);
    cursor.setBatchSize(2);

    // Two batches from the initial find and getMore command.
    MockDBClientConnection::Responses callResponses = {
        MockDBClientConnection::mockFindResponse(
            nss, cursorId, {docObj(1), docObj(2)}, metadata(1)),
        MockDBClientConnection::mockGetMoreResponse(
            nss, cursorId, {docObj(3), docObj(4)}, metadata(2), moreToCome)};
    conn.setCallResponses(callResponses);

    // Two more batches from the exhaust stream.
    MockDBClientConnection::Responses recvResponses = {
        MockDBClientConnection::mockGetMoreResponse(
            nss, cursorId, {docObj(5), docObj(6)}, metadata(3), moreToCome),
        // Terminal getMore responses with cursorId 0 and no kMoreToCome flag.
        MockDBClientConnection::mockGetMoreResponse(nss, 0, {docObj(7), docObj(8)}, metadata(4))};
    conn.setRecvResponses(recvResponses);

    int numMetaRead = 0;
    conn.setReplyMetadataReader(
        [&](mongo::OperationContext* opCtx, const BSONObj& metadataObj, mongo::StringData target) {
            numMetaRead++;
            // Verify metadata for each batch.
            ASSERT(metadataObj.hasField("$fakeMetaData"));
            ASSERT_EQ(numMetaRead, metadataObj["$fakeMetaData"].number());
            return mongo::Status::OK();
        });

    // First batch from the initial find command.
    ASSERT_TRUE(cursor.init());
    ASSERT_BSONOBJ_EQ(docObj(1), cursor.next());
    ASSERT_BSONOBJ_EQ(docObj(2), cursor.next());
    ASSERT_FALSE(cursor.moreInCurrentBatch());

    // Second batch from the first getMore command.
    ASSERT_TRUE(cursor.more());
    ASSERT_BSONOBJ_EQ(docObj(3), cursor.next());
    ASSERT_BSONOBJ_EQ(docObj(4), cursor.next());
    ASSERT_FALSE(cursor.moreInCurrentBatch());

    // Third batch from the exhaust stream.
    ASSERT_TRUE(cursor.more());
    ASSERT_BSONOBJ_EQ(docObj(5), cursor.next());
    ASSERT_BSONOBJ_EQ(docObj(6), cursor.next());
    ASSERT_FALSE(cursor.moreInCurrentBatch());

    // Last batch from the exhaust stream.
    ASSERT_TRUE(cursor.more());
    ASSERT_BSONOBJ_EQ(docObj(7), cursor.next());
    ASSERT_BSONOBJ_EQ(docObj(8), cursor.next());
    ASSERT_FALSE(cursor.moreInCurrentBatch());

    // No more batches.
    ASSERT_FALSE(cursor.more());
    ASSERT_TRUE(cursor.isDead());

    // Test that metadata reader is called four times for the four batches.
    ASSERT_EQ(4, numMetaRead);
}

TEST(MockDBClientConnTest, SimulateCallErrors) {
    MockRemoteDBServer server("test");
    MockDBClientConnection conn(&server);

    mongo::DBClientCursor cursor(
        &conn, mongo::NamespaceStringOrUUID(nss), BSONObj{}, Query(), 0, 0, nullptr, 0, 0);

    // Test network exception and error response for the initial find.
    MockDBClientConnection::Responses callResponses = {
        // Network exception during call().
        mongo::Status{mongo::ErrorCodes::NetworkTimeout, "Fake socket timeout"},
        // Error response from the find command.
        MockDBClientConnection::mockErrorResponse(mongo::ErrorCodes::Interrupted)};
    conn.setCallResponses(callResponses);

    // Throw call exception.
    ASSERT_THROWS_CODE_AND_WHAT(cursor.init(),
                                mongo::DBException,
                                mongo::ErrorCodes::NetworkTimeout,
                                "Fake socket timeout");
    ASSERT_TRUE(cursor.isDead());

    // Throw exception on non-OK response.
    ASSERT_THROWS_CODE(cursor.init(), mongo::DBException, mongo::ErrorCodes::Interrupted);
    ASSERT_TRUE(cursor.isDead());
}

void runUntilExhaustRecv(MockDBClientConnection* conn, mongo::DBClientCursor* cursor) {
    cursor->setBatchSize(1);

    // Two batches from the initial find and getMore command.
    MockDBClientConnection::Responses callResponses = {
        MockDBClientConnection::mockFindResponse(nss, cursorId, {docObj(1)}, metadata(1)),
        MockDBClientConnection::mockGetMoreResponse(
            nss, cursorId, {docObj(2)}, metadata(2), moreToCome)};
    conn->setCallResponses(callResponses);

    // First batch from the initial find command.
    ASSERT_TRUE(cursor->init());
    ASSERT_BSONOBJ_EQ(docObj(1), cursor->next());
    ASSERT_FALSE(cursor->moreInCurrentBatch());

    // Second batch from the first getMore command.
    ASSERT_TRUE(cursor->more());
    ASSERT_BSONOBJ_EQ(docObj(2), cursor->next());
    ASSERT_FALSE(cursor->moreInCurrentBatch());
}

TEST(MockDBClientConnTest, SimulateRecvErrors) {
    MockRemoteDBServer server("test");
    MockDBClientConnection conn(&server);

    mongo::DBClientCursor cursor(&conn,
                                 mongo::NamespaceStringOrUUID(nss),
                                 BSONObj{},
                                 Query(),
                                 0,
                                 0,
                                 nullptr,
                                 mongo::QueryOption_Exhaust,
                                 0);

    runUntilExhaustRecv(&conn, &cursor);

    // Test network exception and error response from exhaust stream.
    MockDBClientConnection::Responses recvResponses = {
        // Network exception during recv().
        mongo::Status{mongo::ErrorCodes::NetworkTimeout, "Fake socket timeout"},
        // Error response from the exhaust cursor.
        MockDBClientConnection::mockErrorResponse(mongo::ErrorCodes::Interrupted)};
    conn.setRecvResponses(recvResponses);

    // The first recv() call gets a network exception.
    ASSERT_THROWS_CODE_AND_WHAT(cursor.more(),
                                mongo::DBException,
                                mongo::ErrorCodes::NetworkTimeout,
                                "Fake socket timeout");
    // Cursor is still valid on network exceptions.
    ASSERT_FALSE(cursor.isDead());

    // Throw exception on non-OK response.
    ASSERT_THROWS_CODE(cursor.more(), mongo::DBException, mongo::ErrorCodes::Interrupted);
    // Cursor is dead on command errors.
    ASSERT_TRUE(cursor.isDead());
}

bool blockedOnNetworkSoon(MockDBClientConnection* conn) {
    // Wait up to 10 seconds.
    for (auto i = 0; i < 100; i++) {
        if (conn->isBlockedOnNetwork()) {
            return true;
        }
        mongo::sleepmillis(100);
    }
    return false;
}

TEST(MockDBClientConnTest, BlockingNetwork) {
    MockRemoteDBServer server("test");
    MockDBClientConnection conn(&server);

    mongo::DBClientCursor cursor(&conn,
                                 mongo::NamespaceStringOrUUID(nss),
                                 BSONObj{},
                                 Query(),
                                 0,
                                 0,
                                 nullptr,
                                 mongo::QueryOption_Exhaust,
                                 0);
    cursor.setBatchSize(1);

    mongo::stdx::thread cursorThread([&] {
        // First batch from the initial find command.
        ASSERT_TRUE(cursor.init());
        ASSERT_BSONOBJ_EQ(docObj(1), cursor.next());
        ASSERT_FALSE(cursor.moreInCurrentBatch());

        // Second batch from the first getMore command.
        ASSERT_TRUE(cursor.more());
        ASSERT_BSONOBJ_EQ(docObj(2), cursor.next());
        ASSERT_FALSE(cursor.moreInCurrentBatch());

        // Last batch from the exhaust stream.
        ASSERT_TRUE(cursor.more());
        ASSERT_BSONOBJ_EQ(docObj(3), cursor.next());
        ASSERT_FALSE(cursor.moreInCurrentBatch());
        ASSERT_TRUE(cursor.isDead());
    });

    // Cursor should be blocked on the first find command.
    ASSERT_TRUE(blockedOnNetworkSoon(&conn));
    auto m = conn.getLastSentMessage();
    auto msg = mongo::OpMsg::parse(m);
    ASSERT_EQ(mongo::StringData(msg.body.firstElement().fieldName()), "find");
    // Set the response for the find command and unblock network call().
    conn.setCallResponses(
        {MockDBClientConnection::mockFindResponse(nss, cursorId, {docObj(1)}, metadata(1))});

    // Cursor should be blocked on the getMore command.
    ASSERT_TRUE(blockedOnNetworkSoon(&conn));
    m = conn.getLastSentMessage();
    msg = mongo::OpMsg::parse(m);
    ASSERT_EQ(mongo::StringData(msg.body.firstElement().fieldName()), "getMore");
    // Set the response for the getMore command and unblock network call().
    conn.setCallResponses({MockDBClientConnection::mockGetMoreResponse(
        nss, cursorId, {docObj(2)}, metadata(2), moreToCome)});

    // Cursor should be blocked on the exhaust stream.
    ASSERT_TRUE(blockedOnNetworkSoon(&conn));
    // Set the response for the exhaust stream and unblock network recv().
    conn.setRecvResponses(
        {MockDBClientConnection::mockGetMoreResponse(nss, 0, {docObj(3)}, metadata(3))});

    cursorThread.join();
}

TEST(MockDBClientConnTest, ShutdownServerBeforeCall) {
    MockRemoteDBServer server("test");
    MockDBClientConnection conn(&server);

    ASSERT_OK(
        conn.connect(mongo::HostAndPort("localhost", 12345), mongo::StringData(), boost::none));
    mongo::DBClientCursor cursor(&conn,
                                 mongo::NamespaceStringOrUUID(nss),
                                 BSONObj{},
                                 Query(),
                                 0,
                                 0,
                                 nullptr,
                                 mongo::QueryOption_Exhaust,
                                 0);

    // Shut down server before call.
    server.shutdown();

    // Connection is broken before call.
    ASSERT_THROWS_CODE(cursor.init(), mongo::DBException, mongo::ErrorCodes::SocketException);

    // Reboot the mock server but the cursor.init() would still fail because the connection does not
    // support autoreconnect.
    server.reboot();
    ASSERT_THROWS_CODE(cursor.init(), mongo::DBException, mongo::ErrorCodes::SocketException);
}

TEST(MockDBClientConnTest, ShutdownServerAfterCall) {
    MockRemoteDBServer server("test");
    MockDBClientConnection conn(&server);

    mongo::DBClientCursor cursor(&conn,
                                 mongo::NamespaceStringOrUUID(nss),
                                 BSONObj{},
                                 Query(),
                                 0,
                                 0,
                                 nullptr,
                                 mongo::QueryOption_Exhaust,
                                 0);

    mongo::stdx::thread cursorThread([&] {
        ASSERT_THROWS_CODE(cursor.init(), mongo::DBException, mongo::ErrorCodes::HostUnreachable);
    });

    // Cursor should be blocked on the first find command.
    ASSERT_TRUE(blockedOnNetworkSoon(&conn));

    // Shutting down the server doesn't interrupt the blocking network call, so we shut down the
    // connection as well to simulate shutdown of the server.
    server.shutdown();
    conn.shutdown();

    cursorThread.join();
}

TEST(MockDBClientConnTest, ConnectionAutoReconnect) {
    const bool autoReconnect = true;
    MockRemoteDBServer server("test");
    MockDBClientConnection conn(&server, autoReconnect);

    ASSERT_OK(
        conn.connect(mongo::HostAndPort("localhost", 12345), mongo::StringData(), boost::none));
    mongo::DBClientCursor cursor(&conn,
                                 mongo::NamespaceStringOrUUID(nss),
                                 BSONObj{},
                                 Query(),
                                 0,
                                 0,
                                 nullptr,
                                 mongo::QueryOption_Exhaust,
                                 0);

    server.shutdown();

    // Connection is broken before call.
    ASSERT_THROWS_CODE(cursor.init(), mongo::DBException, mongo::ErrorCodes::SocketException);

    // AutoReconnect fails because the server is down.
    ASSERT_THROWS_CODE(cursor.init(), mongo::DBException, mongo::ErrorCodes::HostUnreachable);

    // Reboot the mock server and the cursor.init() will reconnect and succeed.
    server.reboot();

    conn.setCallResponses(
        {MockDBClientConnection::mockFindResponse(nss, cursorId, {docObj(1)}, metadata(1))});
    ASSERT_TRUE(cursor.init());
    ASSERT_BSONOBJ_EQ(docObj(1), cursor.next());
    ASSERT_FALSE(cursor.moreInCurrentBatch());
}

TEST(MockDBClientConnTest, ShutdownServerBeforeRecv) {
    const bool autoReconnect = true;
    MockRemoteDBServer server("test");
    MockDBClientConnection conn(&server, autoReconnect);

    mongo::DBClientCursor cursor(&conn,
                                 mongo::NamespaceStringOrUUID(nss),
                                 BSONObj{},
                                 Query(),
                                 0,
                                 0,
                                 nullptr,
                                 mongo::QueryOption_Exhaust,
                                 0);

    runUntilExhaustRecv(&conn, &cursor);

    server.shutdown();

    // cursor.more() will call recv on the exhaust stream.
    ASSERT_THROWS_CODE(cursor.more(), mongo::DBException, mongo::ErrorCodes::SocketException);

    server.reboot();
    // Reconnect is not possible for exhaust recv.
    ASSERT_THROWS_CODE(cursor.more(), mongo::DBException, mongo::ErrorCodes::SocketException);
}

TEST(MockDBClientConnTest, ShutdownServerAfterRecv) {
    MockRemoteDBServer server("test");
    MockDBClientConnection conn(&server);

    mongo::DBClientCursor cursor(&conn,
                                 mongo::NamespaceStringOrUUID(nss),
                                 BSONObj{},
                                 Query(),
                                 0,
                                 0,
                                 nullptr,
                                 mongo::QueryOption_Exhaust,
                                 0);

    runUntilExhaustRecv(&conn, &cursor);

    mongo::stdx::thread cursorThread([&] {
        ASSERT_THROWS_CODE(cursor.more(), mongo::DBException, mongo::ErrorCodes::HostUnreachable);
    });

    // Cursor should be blocked on the recv.
    ASSERT_TRUE(blockedOnNetworkSoon(&conn));

    // Shutting down the server doesn't interrupt the blocking network call, so we shut down the
    // connection as well to simulate shutdown of the server.
    server.shutdown();
    conn.shutdown();

    cursorThread.join();
}
}  // namespace mongo_test