File: client_construction_spec.rb

package info (click to toggle)
ruby-mongo 2.21.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 14,764 kB
  • sloc: ruby: 108,806; makefile: 5; sh: 2
file content (2723 lines) | stat: -rw-r--r-- 90,417 bytes parent folder | download
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
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
# frozen_string_literal: true

require 'spec_helper'

SINGLE_CLIENT = [ '127.0.0.1:27017' ].freeze

# let these existing styles stand, rather than going in for a deep refactoring
# of these specs.
#
# possible future work: re-enable these one at a time and do the hard work of
# making them right.
#
# rubocop:disable RSpec/ExpectInHook, RSpec/ExampleLength
# rubocop:disable RSpec/ContextWording, RSpec/RepeatedExampleGroupDescription
# rubocop:disable RSpec/ExampleWording, Style/BlockComments, RSpec/AnyInstance
# rubocop:disable RSpec/VerifiedDoubles
describe Mongo::Client do
  clean_slate

  let(:subscriber) { Mrss::EventSubscriber.new }

  describe '.new' do
    context 'with scan: false' do
      fails_on_jruby

      it 'does not perform i/o' do
        allow_any_instance_of(Mongo::Server::Monitor).to receive(:run!)
        expect_any_instance_of(Mongo::Server::Monitor).not_to receive(:scan!)

        # return should be instant
        c = Timeout.timeout(1) do
          ClientRegistry.instance.new_local_client([ '1.1.1.1' ], scan: false)
        end
        expect(c.cluster.servers).to be_empty
        c.close
      end
    end

    context 'with default scan: true' do
      shared_examples 'does not wait for server selection timeout' do
        let(:logger) do
          Logger.new($stdout, level: Logger::DEBUG)
        end

        let(:subscriber) do
          Mongo::Monitoring::UnifiedSdamLogSubscriber.new(
            logger: logger,
            log_prefix: 'CCS-SDAM'
          )
        end

        let(:client) do
          ClientRegistry.instance.new_local_client(
            [ address ],
            # Specify server selection timeout here because test suite sets
            # one by default and it's fairly low
            SpecConfig.instance.test_options.merge(
              connect_timeout: 1,
              socket_timeout: 1,
              server_selection_timeout: 8,
              logger: logger,
              log_prefix: 'CCS-CLIENT',
              sdam_proc: ->(client) { subscriber.subscribe(client) }
            )
          )
        end

        it 'does not wait for server selection timeout' do
          time_taken = Benchmark.realtime do
            # Client is created here.
            client
          end
          puts "client_construction_spec.rb: Cluster is: #{client.cluster.summary}"

          # Because the first round of sdam waits for server statuses to change
          # rather than for server selection semaphore on the cluster which
          # is signaled after topology is updated, the topology here could be
          # old (i.e. a monitor thread was just about to update the topology
          # but hasn't quite gotten to it. Add a small delay to compensate.
          # This issue doesn't apply to real applications which will wait for
          # server selection semaphore.
          sleep 0.1

          actual_class = client.cluster.topology.class
          expect([
                   Mongo::Cluster::Topology::ReplicaSetWithPrimary,
                   Mongo::Cluster::Topology::Single,
                   Mongo::Cluster::Topology::Sharded,
                   Mongo::Cluster::Topology::LoadBalanced,
                 ]).to include(actual_class)
          expect(time_taken).to be < 5

          # run a command to ensure the client is a working one
          client.database.command(ping: 1)
        end
      end

      context 'when cluster is monitored' do
        require_topology :single, :replica_set, :sharded

        # TODO: this test requires there being no outstanding background
        # monitoring threads running, as otherwise the scan! expectation
        # can be executed on a thread that belongs to one of the global
        # clients for instance
        it 'performs one round of sdam' do
          # Does not work due to
          # https://github.com/rspec/rspec-mocks/issues/1242.
          #
          # expect_any_instance_of(Mongo::Server::Monitor).to receive(:scan!).
          #  exactly(SpecConfig.instance.addresses.length).times.and_call_original
          c = new_local_client(SpecConfig.instance.addresses, SpecConfig.instance.test_options)
          expect(c.cluster.servers).not_to be_empty
        end

        # This checks the case of all initial seeds being removed from
        # cluster during SDAM
        context 'me mismatch on the only initial seed' do
          let(:address) do
            ClusterConfig.instance.alternate_address.to_s
          end

          include_examples 'does not wait for server selection timeout'
        end
      end

      context 'when cluster is not monitored' do
        require_topology :load_balanced

        let(:address) do
          ClusterConfig.instance.alternate_address.to_s
        end

        include_examples 'does not wait for server selection timeout'
      end
    end

    context 'with monitoring_io: false' do
      let(:client) do
        new_local_client(SINGLE_CLIENT, monitoring_io: false)
      end

      it 'passes monitoring_io: false to cluster' do
        expect(client.cluster.options[:monitoring_io]).to be false
      end
    end
  end

  describe '#initialize' do
    context 'when providing options' do
      context 'with auto_encryption_options' do
        require_libmongocrypt

        include_context 'define shared FLE helpers'

        let(:client) do
          new_local_client_nmio(
            SpecConfig.instance.addresses,
            SpecConfig.instance.test_options.merge(client_opts)
          )
        end

        let(:client_opts) { { auto_encryption_options: auto_encryption_options } }

        let(:auto_encryption_options) do
          {
            key_vault_client: key_vault_client,
            key_vault_namespace: key_vault_namespace,
            kms_providers: kms_providers,
            schema_map: schema_map,
            bypass_auto_encryption: bypass_auto_encryption,
            extra_options: extra_options,
          }
        end

        let(:key_vault_client) { new_local_client_nmio(SpecConfig.instance.addresses) }

        let(:bypass_auto_encryption) { true }

        let(:extra_options) do
          {
            mongocryptd_uri: mongocryptd_uri,
            mongocryptd_bypass_spawn: mongocryptd_bypass_spawn,
            mongocryptd_spawn_path: mongocryptd_spawn_path,
            mongocryptd_spawn_args: mongocryptd_spawn_args,
          }
        end

        let(:mongocryptd_uri) { 'mongodb://localhost:27021' }
        let(:mongocryptd_bypass_spawn) { true }
        let(:mongocryptd_spawn_path) { '/spawn/path' }
        let(:mongocryptd_spawn_args) { [ '--idleShutdownTimeoutSecs=100' ] }

        shared_examples 'a functioning auto encryption client' do
          let(:encryption_options) { client.encrypter.options }

          context 'when auto_encrypt_opts are nil' do
            let(:auto_encryption_options) { nil }

            it 'does not raise an exception' do
              expect { client }.not_to raise_error
            end
          end

          context 'when key_vault_namespace is nil' do
            let(:key_vault_namespace) { nil }

            it 'raises an exception' do
              expect { client }.to raise_error(ArgumentError, /key_vault_namespace option cannot be nil/)
            end
          end

          context 'when key_vault_namespace is incorrectly formatted' do
            let(:key_vault_namespace) { 'not.good.formatting' }

            it 'raises an exception' do
              expect { client }.to raise_error(
                ArgumentError,
                /key_vault_namespace option must be in the format database.collection/
              )
            end
          end

          context 'when kms_providers is nil' do
            let(:kms_providers) { nil }

            it 'raises an exception' do
              expect { client }.to raise_error(ArgumentError, /KMS providers options must not be nil/)
            end
          end

          context 'when kms_providers doesn\'t have local or aws keys' do
            let(:kms_providers) { { random_key: 'hello' } }

            it 'raises an exception' do
              expect { client }.to raise_error(
                ArgumentError,
                /KMS providers options must have one of the following keys: :aws, :azure, :gcp, :kmip, :local/
              )
            end
          end

          context 'when local kms_provider is incorrectly formatted' do
            let(:kms_providers) { { local: { wrong_key: 'hello' } } }

            it 'raises an exception' do
              expect { client }.to raise_error(
                ArgumentError,
                /Local KMS provider options must be in the format: { key: 'MASTER-KEY' }/
              )
            end
          end

          context 'when aws kms_provider is incorrectly formatted' do
            let(:kms_providers) { { aws: { wrong_key: 'hello' } } }

            let(:expected_options_format) do
              "{ access_key_id: 'YOUR-ACCESS-KEY-ID', secret_access_key: 'SECRET-ACCESS-KEY' }"
            end

            it 'raises an exception' do
              expect { client }.to raise_error(
                ArgumentError,
                / AWS KMS provider options must be in the format: #{expected_options_format}/
              )
            end
          end

          context 'with an invalid schema map' do
            let(:schema_map) { '' }

            it 'raises an exception' do
              expect { client }.to raise_error(ArgumentError, /schema_map must be a Hash or nil/)
            end
          end

          context 'with valid options' do
            it 'does not raise an exception' do
              expect { client }.not_to raise_error
            end

            context 'with a nil schema_map' do
              let(:schema_map) { nil }

              it 'does not raise an exception' do
                expect { client }.not_to raise_error
              end
            end

            it 'sets options on the client' do
              expect(encryption_options[:key_vault_client]).to eq(key_vault_client)
              expect(encryption_options[:key_vault_namespace]).to eq(key_vault_namespace)
              # Don't explicitly expect kms_providers to avoid accidentally exposing
              # sensitive data in evergreen logs
              expect(encryption_options[:kms_providers]).to be_a(Hash)
              expect(encryption_options[:schema_map]).to eq(schema_map)
              expect(encryption_options[:bypass_auto_encryption]).to eq(bypass_auto_encryption)
              expect(encryption_options[:extra_options][:mongocryptd_uri]).to eq(mongocryptd_uri)
              expect(encryption_options[:extra_options][:mongocryptd_bypass_spawn]).to eq(mongocryptd_bypass_spawn)
              expect(encryption_options[:extra_options][:mongocryptd_spawn_path]).to eq(mongocryptd_spawn_path)
              expect(encryption_options[:extra_options][:mongocryptd_spawn_args]).to eq(mongocryptd_spawn_args)

              expect(client.encrypter.mongocryptd_client.options[:monitoring_io]).to be false
            end

            context 'with default extra options' do
              let(:auto_encryption_options) do
                {
                  key_vault_namespace: key_vault_namespace,
                  kms_providers: kms_providers,
                  schema_map: schema_map,
                }
              end

              it 'sets key_vault_client with no encryption options' do
                key_vault_client = client.encrypter.key_vault_client
                expect(key_vault_client.options['auto_encryption_options']).to be_nil
              end

              it 'sets bypass_auto_encryption to false' do
                expect(encryption_options[:bypass_auto_encryption]).to be false
              end

              it 'sets extra options to defaults' do
                expect(encryption_options[:extra_options][:mongocryptd_uri]).to eq('mongodb://localhost:27020')
                expect(encryption_options[:extra_options][:mongocryptd_bypass_spawn]).to be false
                expect(encryption_options[:extra_options][:mongocryptd_spawn_path]).to eq('mongocryptd')
                expect(encryption_options[:extra_options][:mongocryptd_spawn_args])
                  .to eq([ '--idleShutdownTimeoutSecs=60' ])
              end
            end

            context 'with mongocryptd_spawn_args that don\'t include idleShutdownTimeoutSecs' do
              let(:mongocryptd_spawn_args) { [ '--otherArgument=true' ] }

              it 'adds a default value to mongocryptd_spawn_args' do
                expect(encryption_options[:extra_options][:mongocryptd_spawn_args])
                  .to eq(mongocryptd_spawn_args + [ '--idleShutdownTimeoutSecs=60' ])
              end
            end

            context 'with mongocryptd_spawn_args that has idleShutdownTimeoutSecs as two arguments' do
              let(:mongocryptd_spawn_args) { [ '--idleShutdownTimeoutSecs', 100 ] }

              it 'does not modify mongocryptd_spawn_args' do
                expect(encryption_options[:extra_options][:mongocryptd_spawn_args]).to eq(mongocryptd_spawn_args)
              end
            end

            context 'with default key_vault_client' do
              let(:key_vault_client) { nil }

              it 'creates a key_vault_client' do
                key_vault_client = encryption_options[:key_vault_client]

                expect(key_vault_client).to be_a(described_class)
              end
            end
          end
        end

        context 'with AWS KMS providers' do
          include_context 'with AWS kms_providers' do
            it_behaves_like 'a functioning auto encryption client'
          end
        end

        context 'with local KMS providers' do
          include_context 'with local kms_providers' do
            it_behaves_like 'a functioning auto encryption client'
          end
        end
      end

      context 'timeout options' do
        let(:client) do
          new_local_client(
            SpecConfig.instance.addresses,
            SpecConfig.instance.authorized_test_options.merge(options)
          )
        end

        context 'when network timeouts are zero' do
          let(:options) { { socket_timeout: 0, connect_timeout: 0 } }

          it 'sets options to zeros' do
            expect(client.options[:socket_timeout]).to be == 0
            expect(client.options[:connect_timeout]).to be == 0
          end

          it 'connects and performs operations successfully' do
            expect { client.database.command(ping: 1) }
              .not_to raise_error
          end
        end

        %i[ socket_timeout connect_timeout ].each do |option|
          context "when #{option} is negative" do
            let(:options) { { option => -1 } }

            it 'fails client creation' do
              expect { client }
                .to raise_error(ArgumentError, /#{option} must be a non-negative number/)
            end
          end

          context "when #{option} is of the wrong type" do
            let(:options) { { option => '42' } }

            it 'fails client creation' do
              expect { client }
                .to raise_error(ArgumentError, /#{option} must be a non-negative number/)
            end
          end
        end

        context 'when :connect_timeout is very small' do
          # The driver reads first and checks the deadline second.
          # This means the read (in a monitor) can technically take more than
          # the connect timeout. Restrict to TLS configurations to make
          # the network I/O take longer.
          require_tls

          let(:options) do
            { connect_timeout: 1e-6, server_selection_timeout: 2 }
          end

          it 'allows client creation' do
            expect { client }.not_to raise_error
          end

          context 'non-lb' do
            require_topology :single, :replica_set, :sharded

            it 'fails server selection due to very small timeout' do
              expect { client.database.command(ping: 1) }
                .to raise_error(Mongo::Error::NoServerAvailable)
            end
          end

          context 'lb' do
            require_topology :load_balanced

            it 'fails the operation after successful server selection' do
              expect { client.database.command(ping: 1) }
                .to raise_error(Mongo::Error::SocketTimeoutError, /socket took over.*to connect/)
            end
          end
        end

        context 'when :socket_timeout is very small' do
          # The driver reads first and checks the deadline second.
          # This means the read (in a monitor) can technically take more than
          # the connect timeout. Restrict to TLS configurations to make
          # the network I/O take longer.
          require_tls

          let(:options) do
            { socket_timeout: 1e-6, server_selection_timeout: 2 }
          end

          it 'allows client creation' do
            expect { client }.not_to raise_error
          end

          retry_test
          it 'fails operations due to very small timeout' do
            expect { client.database.command(ping: 1) }
              .to raise_error(Mongo::Error::SocketTimeoutError)
          end
        end
      end

      context 'retry_writes option' do
        let(:client) do
          new_local_client_nmio(SpecConfig.instance.addresses, options)
        end

        context 'when retry_writes is true' do
          let(:options) do
            { retry_writes: true }
          end

          it 'sets retry_writes to true' do
            expect(client.options['retry_writes']).to be true
          end
        end

        context 'when retry_writes is false' do
          let(:options) do
            { retry_writes: false }
          end

          it 'sets retry_writes to false' do
            expect(client.options['retry_writes']).to be false
          end
        end

        context 'when retry_writes is not given' do
          let(:options) { {} }

          it 'sets retry_writes to true' do
            expect(client.options['retry_writes']).to be true
          end
        end
      end

      context 'when compressors are provided' do
        let(:client) do
          new_local_client(
            SpecConfig.instance.addresses,
            SpecConfig.instance.all_test_options.merge(options)
          )
        end

        context 'when the compressor is not supported by the driver' do
          require_warning_clean

          let(:options) do
            { compressors: %w[ snoopy ] }
          end

          it 'does not set the compressor and warns' do
            expect(Mongo::Logger.logger).to receive(:warn).with(/Unsupported compressor/)
            expect(client.options['compressors']).to be_nil
          end

          it 'sets the compression key of the handshake document to an empty array' do
            expect(client.cluster.app_metadata.send(:document)[:compression]).to eq([])
          end

          context 'when one supported compressor and one unsupported compressor are provided' do
            require_compression
            min_server_fcv '3.6'

            let(:options) do
              { compressors: %w[ zlib snoopy ] }
            end

            it 'does not set the unsupported compressor and warns' do
              expect(Mongo::Logger.logger).to receive(:warn).at_least(:once)
              expect(client.options['compressors']).to eq(%w[ zlib ])
            end

            it 'sets the compression key of the handshake document to the list of supported compressors' do
              expect(client.cluster.app_metadata.send(:document)[:compression]).to eq(%w[ zlib ])
            end
          end
        end

        context 'when the compressor is not supported by the server' do
          max_server_version '3.4'

          let(:options) do
            { compressors: %w[ zlib ] }
          end

          it 'does not set the compressor and warns' do
            expect(Mongo::Logger.logger).to receive(:warn).at_least(:once)
            expect(client.cluster.next_primary.monitor.compressor).to be_nil
          end
        end

        context 'when zlib compression is requested' do
          require_zlib_compression

          let(:options) do
            { compressors: %w[ zlib ] }
          end

          it 'sets the compressor' do
            expect(client.options['compressors']).to eq(options[:compressors])
          end

          it 'sends the compressor in the compression key of the handshake document' do
            expect(client.cluster.app_metadata.send(:document)[:compression]).to eq(options[:compressors])
          end

          context 'when server supports compression' do
            min_server_fcv '3.6'

            it 'uses compression for messages' do
              expect(Mongo::Protocol::Compressed).to receive(:new).at_least(:once).and_call_original
              client[TEST_COLL].find({}, limit: 1).first
            end
          end

          it 'does not use compression for authentication messages' do
            expect(Mongo::Protocol::Compressed).not_to receive(:new)
            client.cluster.next_primary.send(:with_connection, &:connect!)
          end
        end

        context 'when snappy compression is requested and supported by the server' do
          min_server_version '3.6'

          let(:options) do
            { compressors: %w[ snappy ] }
          end

          context 'when snappy gem is installed' do
            require_snappy_compression

            it 'creates the client' do
              expect(client.options['compressors']).to eq(%w[ snappy ])
            end
          end

          context 'when snappy gem is not installed' do
            require_no_snappy_compression

            it 'raises an exception' do
              expect do
                client
              end.to raise_error(Mongo::Error::UnmetDependency, /Cannot enable snappy compression/)
            end
          end
        end

        context 'when zstd compression is requested and supported by the server' do
          min_server_version '4.2'

          let(:options) do
            { compressors: %w[ zstd ] }
          end

          context 'when zstd gem is installed' do
            require_zstd_compression

            it 'creates the client' do
              expect(client.options['compressors']).to eq(%w[ zstd ])
            end
          end

          context 'when zstd gem is not installed' do
            require_no_zstd_compression

            it 'raises an exception' do
              expect do
                client
              end.to raise_error(Mongo::Error::UnmetDependency, /Cannot enable zstd compression/)
            end
          end
        end
      end

      context 'when compressors are not provided' do
        require_no_compression

        let(:client) do
          authorized_client
        end

        it 'does not set the compressor' do
          expect(client.options['compressors']).to be_nil
        end

        it 'sets the compression key of the handshake document to an empty array' do
          expect(client.cluster.app_metadata.send(:document)[:compression]).to eq([])
        end

        it 'does not use compression for messages' do
          client[TEST_COLL].find({}, limit: 1).first
          expect(Mongo::Protocol::Compressed).not_to receive(:new)
        end
      end

      context 'when a zlib_compression_level option is provided' do
        require_compression
        min_server_fcv '3.6'

        let(:client) do
          new_local_client_nmio(
            SpecConfig.instance.addresses,
            SpecConfig.instance.test_options.merge(zlib_compression_level: 1)
          )
        end

        it 'sets the option on the client' do
          expect(client.options[:zlib_compression_level]).to eq(1)
        end
      end

      context 'when ssl options are provided' do
        let(:options) do
          {
            ssl: true,
            ssl_ca_cert: SpecConfig.instance.ca_cert_path,
            ssl_ca_cert_string: 'ca cert string',
            ssl_ca_cert_object: 'ca cert object',
            ssl_cert: SpecConfig.instance.client_cert_path,
            ssl_cert_string: 'cert string',
            ssl_cert_object: 'cert object',
            ssl_key: SpecConfig.instance.client_key_path,
            ssl_key_string: 'key string',
            ssl_key_object: 'key object',
            ssl_key_pass_phrase: 'passphrase',
            ssl_verify: true,
          }
        end

        let(:client) do
          new_local_client_nmio(SINGLE_CLIENT, options)
        end

        it 'sets the ssl option' do
          expect(client.options[:ssl]).to eq(options[:ssl])
        end

        it 'sets the ssl_ca_cert option' do
          expect(client.options[:ssl_ca_cert]).to eq(options[:ssl_ca_cert])
        end

        it 'sets the ssl_ca_cert_string option' do
          expect(client.options[:ssl_ca_cert_string]).to eq(options[:ssl_ca_cert_string])
        end

        it 'sets the ssl_ca_cert_object option' do
          expect(client.options[:ssl_ca_cert_object]).to eq(options[:ssl_ca_cert_object])
        end

        it 'sets the ssl_cert option' do
          expect(client.options[:ssl_cert]).to eq(options[:ssl_cert])
        end

        it 'sets the ssl_cert_string option' do
          expect(client.options[:ssl_cert_string]).to eq(options[:ssl_cert_string])
        end

        it 'sets the ssl_cert_object option' do
          expect(client.options[:ssl_cert_object]).to eq(options[:ssl_cert_object])
        end

        it 'sets the ssl_key option' do
          expect(client.options[:ssl_key]).to eq(options[:ssl_key])
        end

        it 'sets the ssl_key_string option' do
          expect(client.options[:ssl_key_string]).to eq(options[:ssl_key_string])
        end

        it 'sets the ssl_key_object option' do
          expect(client.options[:ssl_key_object]).to eq(options[:ssl_key_object])
        end

        it 'sets the ssl_key_pass_phrase option' do
          expect(client.options[:ssl_key_pass_phrase]).to eq(options[:ssl_key_pass_phrase])
        end

        it 'sets the ssl_verify option' do
          expect(client.options[:ssl_verify]).to eq(options[:ssl_verify])
        end
      end

      context 'when no database is provided' do
        let(:client) do
          new_local_client_nmio(SINGLE_CLIENT, read: { mode: :secondary })
        end

        it 'defaults the database to admin' do
          expect(client.database.name).to eq('admin')
        end
      end

      context 'when a database is provided' do
        let(:client) do
          new_local_client_nmio(SINGLE_CLIENT, database: :testdb)
        end

        it 'sets the current database' do
          expect(client[:users].name).to eq('users')
        end
      end

      context 'when providing a custom logger' do
        let(:logger) do
          Logger.new($stdout).tap do |l|
            l.level = Logger::FATAL
          end
        end

        let(:client) do
          authorized_client.with(logger: logger)
        end

        it 'does not use the global logger' do
          expect(client.cluster.logger).not_to eq(Mongo::Logger.logger)
        end
      end

      context 'when providing a heartbeat_frequency' do
        let(:client) do
          new_local_client_nmio(SINGLE_CLIENT, heartbeat_frequency: 2)
        end

        it 'sets the heartbeat frequency' do
          expect(client.cluster.options[:heartbeat_frequency]).to eq(client.options[:heartbeat_frequency])
        end
      end

      context 'when max_connecting is provided' do
        let(:client) do
          new_local_client_nmio(SINGLE_CLIENT, options)
        end

        context 'when max_connecting is a positive integer' do
          let(:options) do
            { max_connecting: 5 }
          end

          it 'sets the max connecting' do
            expect(client.options[:max_connecting]).to eq(options[:max_connecting])
          end
        end

        context 'when max_connecting is a negative integer' do
          let(:options) do
            { max_connecting: -5 }
          end

          it 'raises an exception' do
            expect { client }.to raise_error(Mongo::Error::InvalidMaxConnecting)
          end
        end
      end

      context 'when min_pool_size is provided' do
        let(:client) { new_local_client_nmio(SINGLE_CLIENT, options) }

        context 'when max_pool_size is provided' do
          context 'when the min_pool_size is greater than the max_pool_size' do
            let(:options) { { min_pool_size: 20, max_pool_size: 10 } }

            it 'raises an Exception' do
              expect { client }
                .to raise_exception(Mongo::Error::InvalidMinPoolSize)
            end
          end

          context 'when the min_pool_size is less than the max_pool_size' do
            let(:options) { { min_pool_size: 10, max_pool_size: 20 } }

            it 'sets the option' do
              expect(client.options[:min_pool_size]).to eq(options[:min_pool_size])
              expect(client.options[:max_pool_size]).to eq(options[:max_pool_size])
            end
          end

          context 'when the min_pool_size is equal to the max_pool_size' do
            let(:options) { { min_pool_size: 10, max_pool_size: 10 } }

            it 'sets the option' do
              expect(client.options[:min_pool_size]).to eq(options[:min_pool_size])
              expect(client.options[:max_pool_size]).to eq(options[:max_pool_size])
            end
          end

          context 'when max_pool_size is zero (unlimited)' do
            let(:options) { { min_pool_size: 10, max_pool_size: 0 } }

            it 'sets the option' do
              expect(client.options[:min_pool_size]).to eq(options[:min_pool_size])
              expect(client.options[:max_pool_size]).to eq(options[:max_pool_size])
            end
          end
        end

        context 'when max_pool_size is not provided' do
          context 'when the min_pool_size is greater than the default max_pool_size' do
            let(:options) { { min_pool_size: 30 } }

            it 'raises an Exception' do
              expect { client }
                .to raise_exception(Mongo::Error::InvalidMinPoolSize)
            end
          end

          context 'when the min_pool_size is less than the default max_pool_size' do
            let(:options) { { min_pool_size: 3 } }

            it 'sets the option' do
              expect(client.options[:min_pool_size]).to eq(options[:min_pool_size])
            end
          end

          context 'when the min_pool_size is equal to the max_pool_size' do
            let(:options) do
              {
                min_pool_size: Mongo::Server::ConnectionPool::DEFAULT_MAX_SIZE
              }
            end

            it 'sets the option' do
              expect(client.options[:min_pool_size]).to eq(options[:min_pool_size])
            end
          end
        end
      end

      context 'when max_pool_size is 0 (unlimited)' do
        let(:client) { new_local_client_nmio(SINGLE_CLIENT, options) }
        let(:options) { { max_pool_size: 0 } }

        it 'sets the option' do
          expect(client.options[:max_pool_size]).to eq(options[:max_pool_size])
        end
      end

      context 'when max_pool_size and min_pool_size are both nil' do
        let(:options) { { min_pool_size: nil, max_pool_size: nil } }
        let(:client) { new_local_client_nmio(SINGLE_CLIENT, options) }

        it 'does not set either option' do
          expect(client.options[:max_pool_size]).to be_nil
          expect(client.options[:min_pool_size]).to be_nil
        end
      end

      context 'when platform details are specified' do
        let(:app_metadata) do
          client.cluster.app_metadata
        end

        let(:client) do
          new_local_client_nmio(SINGLE_CLIENT, platform: 'mongoid-6.0.2')
        end

        it 'includes the platform info in the app metadata' do
          expect(app_metadata.client_document[:platform]).to match(/mongoid-6\.0\.2/)
        end
      end

      context 'when platform details are not specified' do
        let(:app_metadata) do
          client.cluster.app_metadata
        end

        let(:client) do
          new_local_client_nmio(SINGLE_CLIENT)
        end

        context 'mri' do
          require_mri

          let(:platform_string) do
            [
              "Ruby #{RUBY_VERSION}",
              RUBY_PLATFORM,
              RbConfig::CONFIG['build'],
              'A',
            ].join(', ')
          end

          it 'does not include the platform info in the app metadata' do
            expect(app_metadata.client_document[:platform]).to eq(platform_string)
          end
        end

        context 'jruby' do
          require_jruby

          let(:platform_string) do
            [
              "JRuby #{JRUBY_VERSION}",
              "like Ruby #{RUBY_VERSION}",
              RUBY_PLATFORM,
              "JVM #{java.lang.System.get_property('java.version')}",
              RbConfig::CONFIG['build'],
              'A',
            ].join(', ')
          end

          it 'does not include the platform info in the app metadata' do
            expect(app_metadata.client_document[:platform]).to eq(platform_string)
          end
        end
      end
    end

    context 'when providing a connection string' do
      context 'when the string uses the SRV Protocol' do
        require_external_connectivity

        let(:uri) { 'mongodb+srv://test5.test.build.10gen.cc/testdb' }
        let(:client) { new_local_client_nmio(uri) }

        it 'sets the database' do
          expect(client.options[:database]).to eq('testdb')
        end
      end

      context 'when a database is provided' do
        let(:uri) { 'mongodb://127.0.0.1:27017/testdb' }
        let(:client) { new_local_client_nmio(uri) }

        it 'sets the database' do
          expect { client[:users] }.not_to raise_error
        end
      end

      context 'when a database is not provided' do
        let(:uri) { 'mongodb://127.0.0.1:27017' }
        let(:client) { new_local_client_nmio(uri) }

        it 'defaults the database to admin' do
          expect(client.database.name).to eq('admin')
        end
      end

      context 'when URI options are provided' do
        let(:uri) { 'mongodb://127.0.0.1:27017/testdb?w=3' }
        let(:client) { new_local_client_nmio(uri) }

        let(:expected_options) do
          Mongo::Options::Redacted.new(
            write_concern: { w: 3 },
            monitoring_io: false,
            database: 'testdb',
            retry_writes: true,
            retry_reads: true
          )
        end

        it 'sets the options' do
          expect(client.options).to eq(expected_options)
        end

        context 'when max_connecting is provided' do
          context 'when max_connecting is a positive integer' do
            let(:uri) do
              'mongodb://127.0.0.1:27017/?maxConnecting=10'
            end

            it 'sets the max connecting' do
              expect(client.options[:max_connecting]).to eq(10)
            end
          end

          context 'when max_connecting is a negative integer' do
            let(:uri) do
              'mongodb://127.0.0.1:27017/?maxConnecting=0'
            end

            it 'raises an exception' do
              expect { client }.to raise_error(Mongo::Error::InvalidMaxConnecting)
            end
          end
        end

        context 'when min_pool_size is provided' do
          context 'when max_pool_size is provided' do
            context 'when the min_pool_size is greater than the max_pool_size' do
              let(:uri) do
                'mongodb://127.0.0.1:27017/?minPoolSize=20&maxPoolSize=10'
              end

              it 'raises an Exception' do
                expect { client }
                  .to raise_exception(Mongo::Error::InvalidMinPoolSize)
              end
            end

            context 'when the min_pool_size is less than the max_pool_size' do
              let(:uri) do
                'mongodb://127.0.0.1:27017/?minPoolSize=10&maxPoolSize=20'
              end

              it 'sets the option' do
                expect(client.options[:min_pool_size]).to eq(10)
                expect(client.options[:max_pool_size]).to eq(20)
              end
            end

            context 'when the min_pool_size is equal to the max_pool_size' do
              let(:uri) do
                'mongodb://127.0.0.1:27017/?minPoolSize=10&maxPoolSize=10'
              end

              it 'sets the option' do
                expect(client.options[:min_pool_size]).to eq(10)
                expect(client.options[:max_pool_size]).to eq(10)
              end
            end

            context 'when max_pool_size is 0 (unlimited)' do
              let(:uri) do
                'mongodb://127.0.0.1:27017/?minPoolSize=10&maxPoolSize=0'
              end

              it 'sets the option' do
                expect(client.options[:min_pool_size]).to eq(10)
                expect(client.options[:max_pool_size]).to eq(0)
              end
            end
          end

          context 'when max_pool_size is not provided' do
            context 'when the min_pool_size is greater than the default max_pool_size' do
              let(:uri) { 'mongodb://127.0.0.1:27017/?minPoolSize=30' }

              it 'raises an Exception' do
                expect { client }
                  .to raise_exception(Mongo::Error::InvalidMinPoolSize)
              end
            end

            context 'when the min_pool_size is less than the default max_pool_size' do
              let(:uri) { 'mongodb://127.0.0.1:27017/?minPoolSize=3' }

              it 'sets the option' do
                expect(client.options[:min_pool_size]).to eq(3)
              end
            end

            context 'when the min_pool_size is equal to the max_pool_size' do
              let(:uri) { 'mongodb://127.0.0.1:27017/?minPoolSize=5' }

              it 'sets the option' do
                expect(client.options[:min_pool_size]).to eq(5)
              end
            end
          end
        end

        context 'when retryReads URI option is given' do
          context 'it is false' do
            let(:uri) { 'mongodb://127.0.0.1:27017/testdb?retryReads=false' }

            it 'sets the option on the client' do
              expect(client.options[:retry_reads]).to be false
            end
          end

          context 'it is true' do
            let(:uri) { 'mongodb://127.0.0.1:27017/testdb?retryReads=true' }

            it 'sets the option on the client' do
              expect(client.options[:retry_reads]).to be true
            end
          end
        end

        context 'when retryWrites URI option is given' do
          context 'it is false' do
            let(:uri) { 'mongodb://127.0.0.1:27017/testdb?retryWrites=false' }

            it 'sets the option on the client' do
              expect(client.options[:retry_writes]).to be false
            end
          end

          context 'it is true' do
            let(:uri) { 'mongodb://127.0.0.1:27017/testdb?retryWrites=true' }

            it 'sets the option on the client' do
              expect(client.options[:retry_writes]).to be true
            end
          end
        end
      end

      context 'when options are provided not in the string' do
        let(:uri) { 'mongodb://127.0.0.1:27017/testdb' }

        let(:client) do
          new_local_client_nmio(uri, write: { w: 3 })
        end

        let(:expected_options) do
          Mongo::Options::Redacted.new(
            write: { w: 3 },
            monitoring_io: false,
            database: 'testdb',
            retry_writes: true,
            retry_reads: true
          )
        end

        it 'sets the options' do
          expect(client.options).to eq(expected_options)
        end
      end

      context 'when options are provided in the URI and as Ruby options' do
        let(:uri) { 'mongodb://127.0.0.1:27017/testdb?w=3' }

        let(:client) do
          new_local_client_nmio(uri, option_name => { w: 4 })
        end

        let(:expected_options) do
          Mongo::Options::Redacted.new(
            option_name => { w: 4 },
            monitoring_io: false,
            database: 'testdb',
            retry_writes: true,
            retry_reads: true
          )
        end

        shared_examples_for 'allows explicit options to take preference' do
          it 'allows explicit options to take preference' do
            expect(client.options).to eq(expected_options)
          end
        end

        context 'when using :write' do
          let(:option_name) { :write }

          it_behaves_like 'allows explicit options to take preference'
        end

        context 'when using :write_concern' do
          let(:option_name) { :write_concern }

          it_behaves_like 'allows explicit options to take preference'
        end
      end

      context 'when a replica set name is provided' do
        let(:uri) { 'mongodb://127.0.0.1:27017/testdb?replicaSet=testing' }
        let(:client) { new_local_client_nmio(uri) }

        it 'sets the correct cluster topology' do
          expect(client.cluster.topology).to be_a(Mongo::Cluster::Topology::ReplicaSetNoPrimary)
        end
      end
    end

    context 'when Ruby options are provided' do
      let(:client) do
        new_local_client_nmio(SINGLE_CLIENT, options)
      end

      describe 'connection option conflicts' do
        context 'direct_connection: true and multiple seeds' do
          let(:client) do
            new_local_client_nmio([ '127.0.0.1:27017', '127.0.0.2:27017' ], direct_connection: true)
          end

          it 'is rejected' do
            expect { client }
              .to raise_error(ArgumentError, /direct_connection=true cannot be used with multiple seeds/)
          end
        end

        context 'direct_connection: true and connect: :direct' do
          let(:options) do
            { direct_connection: true, connect: :direct }
          end

          it 'is accepted' do
            expect(client.options[:direct_connection]).to be true
            expect(client.options[:connect]).to be :direct
          end
        end

        context 'direct_connection: true and connect: :replica_set' do
          let(:options) do
            { direct_connection: true, connect: :replica_set }
          end

          it 'is rejected' do
            expect { client }
              .to raise_error(
                ArgumentError,
                /Conflicting client options: direct_connection=true and connect=replica_set/
              )
          end
        end

        context 'direct_connection: true and connect: :sharded' do
          let(:options) do
            { direct_connection: true, connect: :sharded }
          end

          it 'is rejected' do
            expect { client }
              .to raise_error(ArgumentError, /Conflicting client options: direct_connection=true and connect=sharded/)
          end
        end

        context 'direct_connection: false and connect: :direct' do
          let(:options) do
            { direct_connection: false, connect: :direct }
          end

          it 'is rejected' do
            expect { client }
              .to raise_error(ArgumentError, /Conflicting client options: direct_connection=false and connect=direct/)
          end
        end

        context 'direct_connection: false and connect: :replica_set' do
          let(:options) do
            { direct_connection: false, connect: :replica_set, replica_set: 'foo' }
          end

          it 'is accepted' do
            expect(client.options[:direct_connection]).to be false
            expect(client.options[:connect]).to be :replica_set
          end
        end

        context 'direct_connection: false and connect: :sharded' do
          let(:options) do
            { direct_connection: false, connect: :sharded }
          end

          it 'is accepted' do
            expect(client.options[:direct_connection]).to be false
            expect(client.options[:connect]).to be :sharded
          end
        end

        context 'load_balanced: true and multiple seeds' do
          let(:client) do
            new_local_client_nmio([ '127.0.0.1:27017', '127.0.0.2:27017' ], load_balanced: true)
          end

          it 'is rejected' do
            expect { client }
              .to raise_error(ArgumentError, /load_balanced=true cannot be used with multiple seeds/)
          end
        end

        context 'load_balanced: false and multiple seeds' do
          let(:client) do
            new_local_client_nmio([ '127.0.0.1:27017', '127.0.0.2:27017' ], load_balanced: false)
          end

          it 'is accepted' do
            expect { client }.not_to raise_error
            expect(client.options[:load_balanced]).to be false
          end
        end

        context 'load_balanced: true and direct_connection: true' do
          let(:client) do
            new_local_client_nmio(SINGLE_CLIENT, load_balanced: true, direct_connection: true)
          end

          it 'is rejected' do
            expect { client }
              .to raise_error(ArgumentError, /direct_connection=true cannot be used with load_balanced=true/)
          end
        end

        context 'load_balanced: true and direct_connection: false' do
          let(:client) do
            new_local_client_nmio(SINGLE_CLIENT, load_balanced: true, direct_connection: false)
          end

          it 'is accepted' do
            expect { client }.not_to raise_error
            expect(client.options[:load_balanced]).to be true
            expect(client.options[:direct_connection]).to be false
          end
        end

        context 'load_balanced: false and direct_connection: true' do
          let(:client) do
            new_local_client_nmio(SINGLE_CLIENT, load_balanced: false, direct_connection: true)
          end

          it 'is accepted' do
            expect { client }.not_to raise_error
            expect(client.options[:load_balanced]).to be false
            expect(client.options[:direct_connection]).to be true
          end
        end

        [ :direct, 'direct', :sharded, 'sharded' ].each do |v|
          context "load_balanced: true and connect: #{v.inspect}" do
            let(:client) do
              new_local_client_nmio(SINGLE_CLIENT, load_balanced: true, connect: v)
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, /connect=#{v} cannot be used with load_balanced=true/)
            end
          end
        end

        [ nil ].each do |v|
          context "load_balanced: true and connect: #{v.inspect}" do
            let(:client) do
              new_local_client_nmio(SINGLE_CLIENT, load_balanced: true, connect: v)
            end

            it 'is accepted' do
              expect { client }.not_to raise_error
              expect(client.options[:load_balanced]).to be true
              expect(client.options[:connect]).to eq v
            end
          end
        end

        [ :load_balanced, 'load_balanced' ].each do |v|
          context "load_balanced: true and connect: #{v.inspect}" do
            let(:client) do
              new_local_client_nmio(SINGLE_CLIENT, load_balanced: true, connect: v)
            end

            it 'is accepted' do
              expect { client }.not_to raise_error
              expect(client.options[:load_balanced]).to be true
              expect(client.options[:connect]).to eq v
            end
          end

          context "replica_set and connect: #{v.inspect}" do
            let(:client) do
              new_local_client_nmio(SINGLE_CLIENT, replica_set: 'foo', connect: v)
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, /connect=load_balanced cannot be used with replica_set option/)
            end
          end

          context "direct_connection=true and connect: #{v.inspect}" do
            let(:client) do
              new_local_client_nmio(SINGLE_CLIENT, direct_connection: true, connect: v)
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(
                  ArgumentError,
                  /Conflicting client options: direct_connection=true and connect=load_balanced/
                )
            end
          end

          context "multiple seed addresses and connect: #{v.inspect}" do
            let(:client) do
              new_local_client_nmio([ '127.0.0.1:27017', '127.0.0.1:1234' ], connect: v)
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, /connect=load_balanced cannot be used with multiple seeds/)
            end
          end
        end

        [ :replica_set, 'replica_set' ].each do |v|
          context "load_balanced: true and connect: #{v.inspect}" do
            let(:client) do
              new_local_client_nmio(SINGLE_CLIENT, load_balanced: true, connect: v, replica_set: 'x')
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, /connect=replica_set cannot be used with load_balanced=true/)
            end
          end

          context "load_balanced: true and #{v.inspect} option" do
            let(:client) do
              new_local_client_nmio(SINGLE_CLIENT, load_balanced: true, v => 'rs')
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, /load_balanced=true cannot be used with replica_set option/)
            end
          end
        end

        context 'srv_max_hosts > 0 and load_balanced: true' do
          let(:client) do
            new_local_client_nmio(SINGLE_CLIENT, srv_max_hosts: 1, load_balanced: true)
          end

          it 'it is rejected' do
            expect { client }
              .to raise_error(ArgumentError, /:srv_max_hosts > 0 cannot be used with :load_balanced=true/)
          end
        end

        context 'srv_max_hosts > 0 and replica_set' do
          let(:client) do
            new_local_client_nmio(SINGLE_CLIENT, srv_max_hosts: 1, replica_set: 'rs')
          end

          it 'it is rejected' do
            expect do
              client
            end.to raise_error(ArgumentError, /:srv_max_hosts > 0 cannot be used with :replica_set option/)
          end
        end

        context 'srv_max_hosts < 0' do
          let(:client) do
            new_local_client_nmio(SINGLE_CLIENT, srv_max_hosts: -1)
          end

          it 'is accepted and does not add the srv_max_hosts to uri_options' do
            expect { client }.not_to raise_error
            expect(client.options).not_to have_key(:srv_max_hosts)
          end
        end

        context 'srv_max_hosts invalid type' do
          let(:client) do
            new_local_client_nmio(SINGLE_CLIENT, srv_max_hosts: 'foo')
          end

          it 'is accepted and does not add the srv_max_hosts to uri_options' do
            expect { client }.not_to raise_error
            expect(client.options).not_to have_key(:srv_max_hosts)
          end
        end

        context 'srv_max_hosts with non-SRV URI' do
          let(:client) do
            new_local_client_nmio(SINGLE_CLIENT, srv_max_hosts: 1)
          end

          it 'is rejected' do
            expect { client }
              .to raise_error(ArgumentError, /:srv_max_hosts cannot be used on non-SRV URI/)
          end
        end

        context 'srv_service_name with non-SRV URI' do
          let(:client) do
            new_local_client_nmio(SINGLE_CLIENT, srv_service_name: 'customname')
          end

          it 'is rejected' do
            expect { client }
              .to raise_error(ArgumentError, /:srv_service_name cannot be used on non-SRV URI/)
          end
        end
      end

      context 'with SRV lookups mocked at Resolver' do
        let(:srv_result) do
          double('srv result').tap do |result|
            allow(result).to receive(:empty?).and_return(false)
            allow(result).to receive(:address_strs).and_return(
              [ ClusterConfig.instance.primary_address_str ]
            )
          end
        end

        let(:client) do
          allow_any_instance_of(Mongo::Srv::Resolver).to receive(:get_records).and_return(srv_result)
          allow_any_instance_of(Mongo::Srv::Resolver).to receive(:get_txt_options_string)

          new_local_client_nmio('mongodb+srv://foo.a.b', options)
        end

        context 'when setting srv_max_hosts' do
          let(:srv_max_hosts) { 1 }
          let(:options) { { srv_max_hosts: srv_max_hosts } }

          it 'is accepted and sets srv_max_hosts' do
            expect { client }.not_to raise_error
            expect(client.options[:srv_max_hosts]).to eq(srv_max_hosts)
          end
        end

        context 'when setting srv_max_hosts to 0' do
          let(:srv_max_hosts) { 0 }
          let(:options) { { srv_max_hosts: srv_max_hosts } }

          it 'is accepted sets srv_max_hosts' do
            expect { client }.not_to raise_error
            expect(client.options[:srv_max_hosts]).to eq(srv_max_hosts)
          end
        end

        context 'when setting srv_service_name' do
          let(:srv_service_name) { 'customname' }
          let(:options) { { srv_service_name: srv_service_name } }

          it 'is accepted and sets srv_service_name' do
            expect { client }.not_to raise_error
            expect(client.options[:srv_service_name]).to eq(srv_service_name)
          end
        end
      end

      context ':bg_error_backtrace option' do
        [ true, false, nil, 42 ].each do |valid_value|
          context "valid value: #{valid_value.inspect}" do
            let(:options) do
              { bg_error_backtrace: valid_value }
            end

            it 'is accepted' do
              expect(client.options[:bg_error_backtrace]).to be == valid_value
            end
          end
        end

        context 'invalid value type' do
          let(:options) do
            { bg_error_backtrace: 'yes' }
          end

          it 'is rejected' do
            expect { client }
              .to raise_error(
                ArgumentError,
                /:bg_error_backtrace option value must be true, false, nil or a positive integer/
              )
          end
        end

        context 'invalid value' do
          [ 0, -1, 42.0 ].each do |invalid_value|
            context "invalid value: #{invalid_value.inspect}" do
              let(:options) do
                { bg_error_backtrace: invalid_value }
              end

              it 'is rejected' do
                expect { client }
                  .to raise_error(
                    ArgumentError,
                    /:bg_error_backtrace option value must be true, false, nil or a positive integer/
                  )
              end
            end
          end
        end
      end

      describe ':read option' do
        %i[ primary primary_preferred secondary secondary_preferred nearest ].each do |sym|
          describe sym.to_s do
            context 'when given as symbol' do
              let(:options) do
                { read: { mode: sym } }
              end

              it 'is accepted' do
                # the key got converted to a string here
                expect(client.read_preference).to eq({ 'mode' => sym })
              end
            end

            context 'when given as string' do
              let(:options) do
                { read: { mode: sym.to_s } }
              end

              # string keys are not documented as being allowed
              # but the code accepts them
              it 'is accepted' do
                # the key got converted to a string here
                # the value remains a string
                expect(client.read_preference).to eq({ 'mode' => sym.to_s })
              end
            end
          end
        end

        context 'when not linting' do
          require_no_linting

          it 'rejects bogus read preference as symbol' do
            expect do
              new_local_client_nmio(SINGLE_CLIENT, read: { mode: :bogus })
            end.to raise_error(
              Mongo::Error::InvalidReadOption,
              'Invalid read preference value: {"mode"=>:bogus}: ' \
              'mode bogus is not one of recognized modes'
            )
          end

          it 'rejects bogus read preference as string' do
            expect do
              new_local_client_nmio(SINGLE_CLIENT, read: { mode: 'bogus' })
            end.to raise_error(
              Mongo::Error::InvalidReadOption,
              'Invalid read preference value: {"mode"=>"bogus"}: mode bogus is not one of recognized modes'
            )
          end

          it 'rejects read option specified as a string' do
            expect do
              new_local_client_nmio(SINGLE_CLIENT, read: 'primary')
            end.to raise_error(
              Mongo::Error::InvalidReadOption,
              'Invalid read preference value: "primary": ' \
              'the read preference must be specified as a hash: { mode: "primary" }'
            )
          end

          it 'rejects read option specified as a symbol' do
            expect do
              new_local_client_nmio(SINGLE_CLIENT, read: :primary)
            end.to raise_error(
              Mongo::Error::InvalidReadOption,
              'Invalid read preference value: :primary: ' \
              'the read preference must be specified as a hash: { mode: :primary }'
            )
          end
        end
      end

      context 'when setting read concern options' do
        min_server_fcv '3.2'

        context 'when read concern is valid' do
          let(:options) do
            { read_concern: { level: :local } }
          end

          it 'does not warn' do
            expect(Mongo::Logger.logger).not_to receive(:warn)
            new_local_client_nmio(SpecConfig.instance.addresses, options)
          end
        end

        context 'when read concern has an invalid key' do
          require_no_linting

          let(:options) do
            { read_concern: { hello: :local } }
          end

          it 'logs a warning' do
            expect(Mongo::Logger.logger).to receive(:warn).with(/Read concern has invalid keys: hello/)
            new_local_client_nmio(SpecConfig.instance.addresses, options)
          end
        end

        context 'when read concern has a non-user-settable key' do
          let(:options) do
            { read_concern: { after_cluster_time: 100 } }
          end

          it 'raises an exception' do
            expect do
              new_local_client_nmio(SpecConfig.instance.addresses, options)
            end.to raise_error(
              Mongo::Error::InvalidReadConcern,
              'The after_cluster_time read_concern option cannot be specified by the user'
            )
          end
        end
      end

      context 'when an invalid option is provided' do
        let(:options) do
          { ssl: false, invalid: :test }
        end

        it 'does not set the option' do
          expect(client.options.keys).not_to include('invalid')
        end

        it 'sets the valid options' do
          expect(client.options.keys).to include('ssl')
        end

        it 'warns that an invalid option has been specified' do
          expect(Mongo::Logger.logger).to receive(:warn)
          expect(client.options.keys).not_to include('invalid')
        end
      end

=begin WriteConcern object support
      context 'when write concern is provided via a WriteConcern object' do
        let(:options) do
          { write_concern: wc }
        end

        let(:wc) { Mongo::WriteConcern.get(w: 2) }

        it 'stores write concern options in client options' do
          expect(client.options[:write_concern]).to eq(
            Mongo::Options::Redacted.new(w: 2))
        end

        it 'caches write concern object' do
          expect(client.write_concern).to be wc
        end
      end
=end

      context ':wrapping_libraries option' do
        let(:options) do
          { wrapping_libraries: wrapping_libraries }
        end

        context 'valid input' do
          context 'symbol keys' do
            let(:wrapping_libraries) do
              [ { name: 'Mongoid', version: '7.1.2' } ].freeze
            end

            it 'works' do
              expect(client.options[:wrapping_libraries]).to be == [ { 'name' => 'Mongoid', 'version' => '7.1.2' } ]
            end
          end

          context 'string keys' do
            let(:wrapping_libraries) do
              [ { 'name' => 'Mongoid', 'version' => '7.1.2' } ].freeze
            end

            it 'works' do
              expect(client.options[:wrapping_libraries]).to be == [ { 'name' => 'Mongoid', 'version' => '7.1.2' } ]
            end
          end

          context 'Redacted keys' do
            let(:wrapping_libraries) do
              [ Mongo::Options::Redacted.new(name: 'Mongoid', version: '7.1.2') ].freeze
            end

            it 'works' do
              expect(client.options[:wrapping_libraries]).to be == [ { 'name' => 'Mongoid', 'version' => '7.1.2' } ]
            end
          end

          context 'two libraries' do
            let(:wrapping_libraries) do
              [
                { name: 'Mongoid', version: '7.1.2' },
                { name: 'Rails', version: '4.0', platform: 'Foobar' },
              ].freeze
            end

            it 'works' do
              expect(client.options[:wrapping_libraries]).to be == [
                { 'name' => 'Mongoid', 'version' => '7.1.2' },
                { 'name' => 'Rails', 'version' => '4.0', 'platform' => 'Foobar' },
              ]
            end
          end

          context 'empty array' do
            let(:wrapping_libraries) do
              []
            end

            it 'works' do
              expect(client.options[:wrapping_libraries]).to be == []
            end
          end

          context 'empty array' do
            let(:wrapping_libraries) do
              nil
            end

            it 'works' do
              expect(client.options[:wrapping_libraries]).to be_nil
            end
          end
        end

        context 'valid input' do
          context 'hash given instead of an array' do
            let(:wrapping_libraries) do
              { name: 'Mongoid', version: '7.1.2' }.freeze
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, /:wrapping_libraries must be an array of hashes/)
            end
          end

          context 'invalid keys' do
            let(:wrapping_libraries) do
              [ { name: 'Mongoid', invalid: '7.1.2' } ].freeze
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, /:wrapping_libraries element has invalid keys/)
            end
          end

          context 'value includes |' do
            let(:wrapping_libraries) do
              [ { name: 'Mongoid|on|Rails', version: '7.1.2' } ].freeze
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, /:wrapping_libraries element value cannot include '|'/)
            end
          end
        end
      end

      context ':auth_mech_properties option' do
        context 'is nil' do
          let(:options) { { auth_mech_properties: nil } }

          it 'creates the client without the option' do
            expect(client.options).not_to have_key(:auth_mech_properties)
          end
        end
      end

      context ':server_api parameter' do
        context 'is a hash with symbol keys' do
          context 'using known keys' do
            let(:options) do
              {
                server_api: {
                  version: '1',
                  strict: true,
                  deprecation_errors: false,
                }
              }
            end

            it 'is accepted' do
              expect(client.options[:server_api]).to be == {
                'version' => '1',
                'strict' => true,
                'deprecation_errors' => false,
              }
            end
          end

          context 'using an unknown version' do
            let(:options) do
              { server_api: { version: '42' } }
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, 'Unknown server API version: 42')
            end
          end

          context 'using an unknown option' do
            let(:options) do
              { server_api: { vversion: '1' } }
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, 'Unknown keys under :server_api: "vversion"')
            end
          end

          context 'using a value which is not a hash' do
            let(:options) do
              { server_api: 42 }
            end

            it 'is rejected' do
              expect { client }
                .to raise_error(ArgumentError, ':server_api value must be a hash: 42')
            end
          end
        end

        context 'when connected to a pre-OP_MSG server' do
          max_server_version '3.4'

          let(:options) do
            { server_api: { version: 1 } }
          end

          let(:client) do
            new_local_client(
              SpecConfig.instance.addresses,
              SpecConfig.instance.all_test_options.merge(options)
            )
          end

          it 'constructs the client' do
            expect(client).to be_a(described_class)
          end

          it 'does not discover servers' do
            client.cluster.servers_list.each do |s|
              expect(s.status).to eq('UNKNOWN')
            end
          end

          it 'fails operations' do
            expect { client.command(ping: 1) }
              .to raise_error(Mongo::Error::NoServerAvailable)
          end
        end
      end
    end

    context 'when making a block client' do
      context 'when the block doesn\'t raise an error' do
        let(:block_client) do
          c = nil
          described_class.new(
            SpecConfig.instance.addresses,
            SpecConfig.instance.test_options.merge(database: SpecConfig.instance.test_db)
          ) do |client|
            c = client
          end
          c
        end

        it 'is closed after block' do
          expect(block_client.cluster.connected?).to be false
        end

        context 'with auto encryption options' do
          require_libmongocrypt
          min_server_fcv '4.2'
          require_enterprise
          clean_slate

          include_context 'define shared FLE helpers'
          include_context 'with local kms_providers'

          let(:auto_encryption_options) do
            {
              key_vault_client: key_vault_client,
              key_vault_namespace: key_vault_namespace,
              kms_providers: kms_providers,
              schema_map: schema_map,
              extra_options: extra_options,
            }
          end

          let(:key_vault_client) { new_local_client_nmio(SpecConfig.instance.addresses) }

          let(:block_client) do
            c = nil
            described_class.new(
              SpecConfig.instance.addresses,
              SpecConfig.instance.test_options.merge(
                auto_encryption_options: auto_encryption_options,
                database: SpecConfig.instance.test_db
              )
            ) do |client|
              c = client
            end
            c
          end

          it 'closes all clients after block' do
            expect(block_client.cluster.connected?).to be false
            [
              block_client.encrypter.mongocryptd_client,
              block_client.encrypter.key_vault_client,
              block_client.encrypter.metadata_client
            ].each do |crypt_client|
              expect(crypt_client.cluster.connected?).to be false
            end
          end
        end
      end

      context 'when the block raises an error' do
        it 'is closed after the block' do
          block_client_raise = nil
          expect do
            described_class.new(
              SpecConfig.instance.addresses,
              SpecConfig.instance.test_options.merge(database: SpecConfig.instance.test_db)
            ) do |client|
              block_client_raise = client
              raise 'This is an error!'
            end
          end.to raise_error(StandardError, 'This is an error!')
          expect(block_client_raise.cluster.connected?).to be false
        end
      end

      context 'when the hosts given include the protocol' do
        it 'raises an error on mongodb://' do
          expect do
            described_class.new([ 'mongodb://127.0.0.1:27017/test' ])
          end.to raise_error(ArgumentError,
                             "Host 'mongodb://127.0.0.1:27017/test' should not contain protocol. " \
                             'Did you mean to not use an array?')
        end

        it 'raises an error on mongodb+srv://' do
          expect do
            described_class.new([ 'mongodb+srv://127.0.0.1:27017/test' ])
          end.to raise_error(ArgumentError,
                             "Host 'mongodb+srv://127.0.0.1:27017/test' should not contain protocol. " \
                             'Did you mean to not use an array?')
        end

        it 'raises an error on multiple items' do
          expect do
            described_class.new([ '127.0.0.1:27017', 'mongodb+srv://127.0.0.1:27017/test' ])
          end.to raise_error(ArgumentError,
                             "Host 'mongodb+srv://127.0.0.1:27017/test' should not contain protocol. " \
                             'Did you mean to not use an array?')
        end

        it 'raises an error only at beginning of string' do
          expect do
            described_class
              .new([ 'somethingmongodb://127.0.0.1:27017/test', 'mongodb+srv://127.0.0.1:27017/test' ])
          end.to raise_error(ArgumentError,
                             "Host 'mongodb+srv://127.0.0.1:27017/test' should not contain protocol. " \
                             'Did you mean to not use an array?')
        end

        it 'raises an error with different case' do
          expect { described_class.new([ 'MongOdB://127.0.0.1:27017/test' ]) }
            .to raise_error(ArgumentError,
                            "Host 'MongOdB://127.0.0.1:27017/test' should not contain protocol. " \
                            'Did you mean to not use an array?')
        end
      end
    end
  end

  shared_examples_for 'duplicated client with duplicated monitoring' do
    let(:monitoring) { client.send(:monitoring) }
    let(:new_monitoring) { new_client.send(:monitoring) }

    it 'duplicates monitoring' do
      expect(new_monitoring).not_to eql(monitoring)
    end

    it 'copies monitoring subscribers' do
      monitoring.subscribers.clear
      client.subscribe(Mongo::Monitoring::SERVER_HEARTBEAT, subscriber)
      expect(monitoring.present_subscribers.length).to eq(1)
      expect(monitoring.subscribers[Mongo::Monitoring::SERVER_HEARTBEAT].length).to eq(1)

      # this duplicates the client
      expect(new_monitoring.present_subscribers.length).to eq(1)
      expect(new_monitoring.subscribers[Mongo::Monitoring::SERVER_HEARTBEAT].length).to eq(1)
    end

    it 'does not change subscribers on original client' do
      monitoring.subscribers.clear
      client.subscribe(Mongo::Monitoring::SERVER_HEARTBEAT, subscriber)
      expect(monitoring.present_subscribers.length).to eq(1)
      expect(monitoring.subscribers[Mongo::Monitoring::SERVER_HEARTBEAT].length).to eq(1)

      new_client.subscribe(Mongo::Monitoring::SERVER_HEARTBEAT, subscriber)
      new_client.subscribe(Mongo::Monitoring::SERVER_HEARTBEAT, subscriber)
      expect(new_monitoring.present_subscribers.length).to eq(1)
      expect(new_monitoring.subscribers[Mongo::Monitoring::SERVER_HEARTBEAT].length).to eq(3)
      # original client should not have gotten any of the new subscribers
      expect(monitoring.present_subscribers.length).to eq(1)
      expect(monitoring.subscribers[Mongo::Monitoring::SERVER_HEARTBEAT].length).to eq(1)
    end
  end

  shared_examples_for 'duplicated client with reused monitoring' do
    let(:monitoring) { client.send(:monitoring) }
    let(:new_monitoring) { new_client.send(:monitoring) }

    it 'reuses monitoring' do
      expect(new_monitoring).to eql(monitoring)
    end
  end

  shared_examples_for 'duplicated client with clean slate monitoring' do
    let(:monitoring) { client.send(:monitoring) }
    let(:new_monitoring) { new_client.send(:monitoring) }

    it 'does not reuse monitoring' do
      expect(new_monitoring).not_to eql(monitoring)
    end

    it 'resets monitoring subscribers' do
      monitoring.subscribers.clear
      client.subscribe(Mongo::Monitoring::SERVER_HEARTBEAT, subscriber)
      expect(monitoring.present_subscribers.length).to eq(1)
      expect(monitoring.subscribers[Mongo::Monitoring::SERVER_HEARTBEAT].length).to eq(1)

      # this duplicates the client
      # 7 is how many subscribers driver sets up by default
      expect(new_monitoring.present_subscribers.length).to eq(7)
      # ... none of which are for heartbeats
      expect(new_monitoring.subscribers[Mongo::Monitoring::SERVER_HEARTBEAT].length).to eq(0)
    end

    it 'does not change subscribers on original client' do
      monitoring.subscribers.clear
      client.subscribe(Mongo::Monitoring::SERVER_HEARTBEAT, subscriber)
      expect(monitoring.present_subscribers.length).to eq(1)
      expect(monitoring.subscribers[Mongo::Monitoring::SERVER_HEARTBEAT].length).to eq(1)

      new_client.subscribe(Mongo::Monitoring::SERVER_HEARTBEAT, subscriber)
      new_client.subscribe(Mongo::Monitoring::SERVER_HEARTBEAT, subscriber)
      # 7 default subscribers + heartbeat
      expect(new_monitoring.present_subscribers.length).to eq(8)
      # the heartbeat subscriber on the original client is not inherited
      expect(new_monitoring.subscribers[Mongo::Monitoring::SERVER_HEARTBEAT].length).to eq(2)
      # original client should not have gotten any of the new subscribers
      expect(monitoring.present_subscribers.length).to eq(1)
      expect(monitoring.subscribers[Mongo::Monitoring::SERVER_HEARTBEAT].length).to eq(1)
    end
  end

  describe '#use' do
    let(:client) do
      new_local_client_nmio(SINGLE_CLIENT, database: SpecConfig.instance.test_db)
    end

    shared_examples_for 'a database switching object' do
      it 'returns the new client' do
        expect(client.send(:database).name).to eq('ruby-driver')
      end

      it 'keeps the same cluster' do
        expect(database.cluster).to equal(client.cluster)
      end
    end

    context 'when provided a string' do
      let(:database) do
        client.use('testdb')
      end

      it_behaves_like 'a database switching object'
    end

    context 'when provided a symbol' do
      let(:database) do
        client.use(:testdb)
      end

      it_behaves_like 'a database switching object'
    end

    context 'when providing nil' do
      it 'raises an exception' do
        expect { client.use(nil) }
          .to raise_error(Mongo::Error::InvalidDatabaseName)
      end
    end
  end

  describe '#with' do
    let(:client) do
      new_local_client_nmio(SINGLE_CLIENT, database: SpecConfig.instance.test_db)
    end

    context 'when providing nil' do
      it 'returns the cloned client' do
        expect(client.with(nil)).to eq(client)
      end
    end

    context 'when the app_name is changed' do
      let(:client) { authorized_client }
      let(:original_options) { client.options }
      let(:new_options) { { app_name: 'client_test' } }
      let(:new_client) { authorized_client.with(new_options) }

      it 'returns a new client' do
        expect(new_client).not_to equal(client)
      end

      it 'replaces the existing options' do
        expect(new_client.options).to eq(client.options.merge(new_options))
      end

      it 'does not modify the original client' do
        expect(client.options).to eq(original_options)
      end

      it 'does not keep the same cluster' do
        expect(new_client.cluster).not_to be(client.cluster)
      end
    end

    context 'when direct_connection option is given' do
      let(:client) do
        options = SpecConfig.instance.test_options
        options.delete(:connect)
        new_local_client(SpecConfig.instance.addresses, options)
      end

      let(:new_client) do
        client.with(new_options)
      end

      before do
        expect(client.options[:direct_connection]).to be_nil
      end

      context 'direct_connection set to false' do
        let(:new_options) do
          { direct_connection: false }
        end

        it 'is accepted' do
          expect(new_client.options[:direct_connection]).to be false
        end
      end

      context 'direct_connection set to true' do
        let(:new_options) do
          { direct_connection: true }
        end

        context 'in single topology' do
          require_topology :single

          it 'is accepted' do
            expect(new_client.options[:direct_connection]).to be true
            expect(new_client.cluster.topology).to be_a(Mongo::Cluster::Topology::Single)
          end
        end

        context 'in replica set or sharded cluster topology' do
          require_topology :replica_set, :sharded

          it 'is rejected' do
            expect { new_client }
              .to raise_error(ArgumentError, /direct_connection=true cannot be used with topologies other than Single/)
          end

          context 'when a new cluster is created' do
            let(:new_options) do
              { direct_connection: true, app_name: 'new-client' }
            end

            it 'is rejected' do
              expect { new_client }
                .to raise_error(ArgumentError,
                                /direct_connection=true cannot be used with topologies other than Single/)
            end
          end
        end
      end
    end

    context 'when the write concern is not changed' do
      let(:client) do
        new_local_client_nmio(
          SINGLE_CLIENT,
          read: { mode: :secondary },
          write: { w: 1 },
          database: SpecConfig.instance.test_db
        )
      end

      let(:new_client) { client.with(read: { mode: :primary }) }

      let(:new_options) do
        Mongo::Options::Redacted.new(
          read: { mode: :primary },
          write: { w: 1 },
          monitoring_io: false,
          database: SpecConfig.instance.test_db,
          retry_writes: true,
          retry_reads: true
        )
      end

      let(:original_options) do
        Mongo::Options::Redacted.new(
          read: { mode: :secondary },
          write: { w: 1 },
          monitoring_io: false,
          database: SpecConfig.instance.test_db,
          retry_writes: true,
          retry_reads: true
        )
      end

      it 'returns a new client' do
        expect(new_client).not_to equal(client)
      end

      it 'replaces the existing options' do
        expect(new_client.options).to eq(new_options)
      end

      it 'does not modify the original client' do
        expect(client.options).to eq(original_options)
      end

      it 'keeps the same cluster' do
        expect(new_client.cluster).to be(client.cluster)
      end
    end

    context 'when the write concern is changed' do
      let(:client) do
        new_local_client(
          SINGLE_CLIENT,
          { monitoring_io: false }.merge(client_options)
        )
      end

      let(:client_options) do
        { write: { w: 1 } }
      end

      context 'when the write concern has not been accessed' do
        let(:new_client) { client.with(write: { w: 0 }) }

        let(:get_last_error) do
          new_client.write_concern.get_last_error
        end

        it 'returns the correct write concern' do
          expect(get_last_error).to be_nil
        end
      end

      context 'when the write concern has been accessed' do
        let(:new_client) do
          client.write_concern
          client.with(write: { w: 0 })
        end

        let(:get_last_error) do
          new_client.write_concern.get_last_error
        end

        it 'returns the correct write concern' do
          expect(get_last_error).to be_nil
        end
      end

      context 'when write concern is given as :write' do
        let(:client_options) do
          { write: { w: 1 } }
        end

        it 'sets :write option' do
          expect(client.options[:write]).to eq(Mongo::Options::Redacted.new(w: 1))
        end

        it 'does not set :write_concern option' do
          expect(client.options[:write_concern]).to be_nil
        end

        it 'returns correct write concern' do
          expect(client.write_concern).to be_a(Mongo::WriteConcern::Acknowledged)
          expect(client.write_concern.options).to eq(w: 1)
        end
      end

      context 'when write concern is given as :write_concern' do
        let(:client_options) do
          { write_concern: { w: 1 } }
        end

        it 'sets :write_concern option' do
          expect(client.options[:write_concern]).to eq(Mongo::Options::Redacted.new(w: 1))
        end

        it 'does not set :write option' do
          expect(client.options[:write]).to be_nil
        end

        it 'returns correct write concern' do
          expect(client.write_concern).to be_a(Mongo::WriteConcern::Acknowledged)
          expect(client.write_concern.options).to eq(w: 1)
        end
      end

      context 'when write concern is given as both :write and :write_concern' do
        context 'with identical values' do
          let(:client_options) do
            { write: { w: 1 }, write_concern: { w: 1 } }
          end

          it 'sets :write_concern option' do
            expect(client.options[:write_concern]).to eq(Mongo::Options::Redacted.new(w: 1))
          end

          it 'sets :write option' do
            expect(client.options[:write]).to eq(Mongo::Options::Redacted.new(w: 1))
          end

          it 'returns correct write concern' do
            expect(client.write_concern).to be_a(Mongo::WriteConcern::Acknowledged)
            expect(client.write_concern.options).to eq(w: 1)
          end
        end

        context 'with different values' do
          let(:client_options) do
            { write: { w: 1 }, write_concern: { w: 2 } }
          end

          it 'raises an exception' do
            expect do
              client
            end.to raise_error(ArgumentError, /If :write and :write_concern are both given, they must be identical/)
          end
        end
      end

      context 'when #with uses a different write concern option name' do
        context 'from :write_concern to :write' do
          let(:client_options) do
            { write_concern: { w: 1 } }
          end

          let(:new_client) { client.with(write: { w: 2 }) }

          it 'uses the new option' do
            expect(new_client.options[:write]).to eq(Mongo::Options::Redacted.new(w: 2))
            expect(new_client.options[:write_concern]).to be_nil
          end
        end

        context 'from :write to :write_concern' do
          let(:client_options) do
            { write: { w: 1 } }
          end

          let(:new_client) { client.with(write_concern: { w: 2 }) }

          it 'uses the new option' do
            expect(new_client.options[:write_concern]).to eq(Mongo::Options::Redacted.new(w: 2))
            expect(new_client.options[:write]).to be_nil
          end
        end
      end
    end

    context 'when an invalid option is provided' do
      let(:new_client) do
        client.with(invalid: :option, ssl: false)
      end

      it 'does not set the invalid option' do
        expect(new_client.options.keys).not_to include('invalid')
      end

      it 'sets the valid options' do
        expect(new_client.options.keys).to include('ssl')
      end

      it 'warns that an invalid option has been specified' do
        expect(Mongo::Logger.logger).to receive(:warn)
        expect(new_client.options.keys).not_to include('invalid')
      end
    end

    context 'when client is created with ipv6 address' do
      let(:client) do
        new_local_client_nmio([ '[::1]:27017' ], database: SpecConfig.instance.test_db)
      end

      context 'when providing nil' do
        it 'returns the cloned client' do
          expect(client.with(nil)).to eq(client)
        end
      end

      context 'when changing options' do
        let(:new_options) { { app_name: 'client_test' } }
        let(:new_client) { client.with(new_options) }

        it 'returns a new client' do
          expect(new_client).not_to equal(client)
        end
      end
    end

    context 'when new client has a new cluster' do
      let(:client) do
        new_local_client(
          SINGLE_CLIENT,
          database: SpecConfig.instance.test_db,
          server_selection_timeout: 0.5,
          socket_timeout: 0.1, connect_timeout: 0.1, populator_io: false
        )
      end

      let(:new_client) do
        client.with(app_name: 'client_construction_spec').tap do |new_client|
          expect(new_client.cluster).not_to eql(client.cluster)
        end
      end

      it_behaves_like 'duplicated client with clean slate monitoring'
    end

    context 'when new client shares cluster with original client' do
      let(:new_client) do
        client.with(database: 'client_construction_spec').tap do |new_client|
          expect(new_client.cluster).to eql(client.cluster)
        end
      end

      it_behaves_like 'duplicated client with reused monitoring'
    end

    # Since we either reuse monitoring or reset it to a clean slate
    # in #with, the consistent behavior is to never transfer sdam_proc to
    # the new client.
    context 'when sdam_proc is given on original client' do
      let(:sdam_proc) do
        proc do |client|
          client.subscribe(Mongo::Monitoring::SERVER_HEARTBEAT, subscriber)
        end
      end

      let(:client) do
        new_local_client(
          SpecConfig.instance.addresses,
          SpecConfig.instance.test_options.merge(
            sdam_proc: sdam_proc,
            connect_timeout: 3.08, socket_timeout: 3.09,
            server_selection_timeout: 2.92,
            heartbeat_frequency: 100,
            database: SpecConfig.instance.test_db
          )
        )
      end

      let(:new_client) do
        client.with(app_name: 'foo').tap do |new_client|
          expect(new_client.cluster).not_to be == client.cluster
        end
      end

      before do
        client.cluster.next_primary
        events = subscriber.select_started_events(Mongo::Monitoring::Event::ServerHeartbeatStarted)
        if ClusterConfig.instance.topology == :load_balanced
          # No server monitoring in LB topology
          expect(events.length).to be == 0
        else
          expect(events.length).to be > 0
        end
      end

      it 'does not copy sdam_proc option to new client' do
        expect(new_client.options[:sdam_proc]).to be_nil
      end

      it 'does not notify subscribers set up by sdam_proc' do
        # On 4.4, the push monitor also is receiving heartbeats.
        # Give those some time to be processed.
        sleep 2

        if ClusterConfig.instance.topology == :load_balanced
          # No server monitoring in LB topology
          expect(subscriber.started_events.length).to eq 0
        else
          expect(subscriber.started_events.length).to be > 0
        end
        subscriber.started_events.clear

        # If this test takes longer than heartbeat interval,
        # subscriber may receive events from the original client.

        new_client.cluster.next_primary

        # Diagnostics
        # rubocop:disable Style/IfUnlessModifier, Lint/Debugger
        unless subscriber.started_events.empty?
          p subscriber.started_events
        end
        # rubocop:enable Style/IfUnlessModifier, Lint/Debugger

        expect(subscriber.started_events.length).to eq 0
        expect(new_client.cluster.topology.class).not_to be Mongo::Cluster::Topology::Unknown
      end
    end

    context 'when :server_api is changed' do
      let(:client) do
        new_local_client_nmio(SINGLE_CLIENT)
      end

      let(:new_client) do
        client.with(server_api: { version: '1' })
      end

      it 'changes :server_api' do
        expect(new_client.options[:server_api]).to be == { 'version' => '1' }
      end
    end

    context 'when :server_api is cleared' do
      let(:client) do
        new_local_client_nmio(SINGLE_CLIENT, server_api: { version: '1' })
      end

      let(:new_client) do
        client.with(server_api: nil)
      end

      it 'clears :server_api' do
        expect(new_client.options[:server_api]).to be_nil
      end
    end
  end

  describe '#dup' do
    let(:client) do
      new_local_client_nmio(
        SINGLE_CLIENT,
        read: { mode: :primary },
        database: SpecConfig.instance.test_db
      )
    end

    let(:new_client) { client.dup }

    it 'creates a client with Redacted options' do
      expect(new_client.options).to be_a(Mongo::Options::Redacted)
    end

    it_behaves_like 'duplicated client with reused monitoring'
  end
end
# rubocop:enable RSpec/ExpectInHook, RSpec/ExampleLength
# rubocop:enable RSpec/ContextWording, RSpec/RepeatedExampleGroupDescription
# rubocop:enable RSpec/ExampleWording, Style/BlockComments, RSpec/AnyInstance
# rubocop:enable RSpec/VerifiedDoubles