File: client_spec.rb

package info (click to toggle)
ruby-elasticsearch 7.17.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 7,712 kB
  • sloc: ruby: 44,120; sh: 16; makefile: 2
file content (2072 lines) | stat: -rw-r--r-- 63,412 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
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

require 'spec_helper'

describe Elasticsearch::Transport::Client do
  let(:client) do
    described_class.new.tap do |_client|
      allow(_client).to receive(:__build_connections)
    end
  end

  it 'has a default transport' do
    expect(client.transport).to be_a(Elasticsearch::Transport::Client::DEFAULT_TRANSPORT_CLASS)
  end

  it 'preserves the Faraday default user agent header' do
    expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/Faraday/)
  end

  it 'identifies the Ruby client in the User-Agent header' do
    expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/elasticsearch-ruby\/#{Elasticsearch::Transport::VERSION}/)
  end

  it 'identifies the Ruby version in the User-Agent header' do
    expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RUBY_VERSION}/)
  end

  it 'identifies the host_os in the User-Agent header' do
    expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RbConfig::CONFIG['host_os'].split('_').first[/[a-z]+/i].downcase}/)
  end

  it 'identifies the target_cpu in the User-Agent header' do
    expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RbConfig::CONFIG['target_cpu']}/)
  end

  it 'sets the \'Content-Type\' header to \'application/json\' by default' do
    expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')
  end

  it 'uses localhost by default' do
    expect(client.transport.hosts[0][:host]).to eq('localhost')
  end

  context 'when a User-Agent header is specified as client option' do
    let(:client) do
      described_class.new(transport_options: { headers: { 'User-Agent' => 'testing' } })
    end

    it 'sets the specified User-Agent header' do
      expect(client.transport.connections.first.connection.headers['User-Agent']).to eq('testing')
    end
  end

  context 'when an encoded api_key is provided' do
    let(:client) do
      described_class.new(api_key: 'an_api_key')
    end
    let(:authorization_header) do
      client.transport.connections.first.connection.headers['Authorization']
    end

    it 'Adds the ApiKey header to the connection' do
      expect(authorization_header).to eq('ApiKey an_api_key')
    end
  end

  context 'when an un-encoded api_key is provided' do
    let(:client) do
      described_class.new(api_key: { id: 'my_id', api_key: 'my_api_key' })
    end
    let(:authorization_header) do
      client.transport.connections.first.connection.headers['Authorization']
    end

    it 'Adds the ApiKey header to the connection' do
      expect(authorization_header).to eq("ApiKey #{Base64.strict_encode64('my_id:my_api_key')}")
    end
  end

  context 'when basic auth and api_key are provided' do
    let(:client) do
      described_class.new(
        api_key: { id: 'my_id', api_key: 'my_api_key' },
        host: 'http://elastic:password@localhost:9200'
      )
    end
    let(:authorization_header) do
      client.transport.connections.first.connection.headers['Authorization']
    end

    it 'removes basic auth credentials' do
      expect(authorization_header).not_to match(/^Basic/)
      expect(authorization_header).to match(/^ApiKey/)
    end
  end

  context 'when a user-agent header is specified as client option in lower-case' do

    let(:client) do
      described_class.new(transport_options: { headers: { 'user-agent' => 'testing' } })
    end

    it 'sets the specified User-Agent header' do
      expect(client.transport.connections.first.connection.headers['User-Agent']).to eq('testing')
    end
  end

  context 'when a Content-Type header is specified as client option' do

    let(:client) do
      described_class.new(transport_options: { headers: { 'Content-Type' => 'testing' } })
    end

    it 'sets the specified Content-Type header' do
      expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('testing')
    end
  end

  context 'when a content-type header is specified as client option in lower-case' do

    let(:client) do
      described_class.new(transport_options: { headers: { 'content-type' => 'testing' } })
    end

    it 'sets the specified Content-Type header' do
      expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('testing')
    end
  end

  context 'when the Curb transport class is used', unless: jruby? do

    let(:client) do
      described_class.new(transport_class: Elasticsearch::Transport::Transport::HTTP::Curb)
    end

    it 'preserves the Curb default user agent header' do
      expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/Curb/)
    end

    it 'identifies the Ruby client in the User-Agent header' do
      expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/elasticsearch-ruby\/#{Elasticsearch::Transport::VERSION}/)
    end

    it 'identifies the Ruby version in the User-Agent header' do
      expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RUBY_VERSION}/)
    end

    it 'identifies the host_os in the User-Agent header' do
      expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RbConfig::CONFIG['host_os'].split('_').first[/[a-z]+/i].downcase}/)
    end

    it 'identifies the target_cpu in the User-Agent header' do
      expect(client.transport.connections.first.connection.headers['User-Agent']).to match(/#{RbConfig::CONFIG['target_cpu']}/)
    end

    it 'sets the \'Content-Type\' header to \'application/json\' by default' do
      expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')
    end

    it 'uses localhost by default' do
      expect(client.transport.hosts[0][:host]).to eq('localhost')
    end

    context 'when a User-Agent header is specified as a client option' do

      let(:client) do
        described_class.new(transport_class: Elasticsearch::Transport::Transport::HTTP::Curb,
                            transport_options: { headers: { 'User-Agent' => 'testing' } })
      end

      it 'sets the specified User-Agent header' do
        expect(client.transport.connections.first.connection.headers['User-Agent']).to eq('testing')
      end
    end

    context 'when a user-agent header is specified as a client option as lower-case' do

      let(:client) do
        described_class.new(transport_class: Elasticsearch::Transport::Transport::HTTP::Curb,
                            transport_options: { headers: { 'user-agent' => 'testing' } })
      end

      it 'sets the specified User-Agent header' do
        expect(client.transport.connections.first.connection.headers['User-Agent']).to eq('testing')
      end
    end

    context 'when a Content-Type header is specified as client option' do

      let(:client) do
        described_class.new(transport_class: Elasticsearch::Transport::Transport::HTTP::Curb,
                            transport_options: { headers: { 'Content-Type' => 'testing' } })
      end

      it 'sets the specified Content-Type header' do
        expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('testing')
      end
    end

    context 'when a content-type header is specified as client option in lower-case' do

      let(:client) do
        described_class.new(transport_class: Elasticsearch::Transport::Transport::HTTP::Curb,
                            transport_options: { headers: { 'content-type' => 'testing' } })
      end

      it 'sets the specified Content-Type header' do
        expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('testing')
      end
    end
  end

  describe 'adapter' do
    context 'when no adapter is specified' do
      fork do
        let(:client) { described_class.new }
        let(:adapter) { client.transport.connections.all.first.connection.builder.adapter }

        it 'uses Faraday NetHttp' do
          expect(adapter).to eq Faraday::Adapter::NetHttp
        end
      end unless jruby?
    end

    context 'when the adapter is patron' do
      let(:adapter) do
        client.transport.connections.all.first.connection.builder.adapter
      end

      let(:client) do
        described_class.new(adapter: :patron, enable_meta_header: false)
      end

      it 'uses Faraday with the adapter' do
        expect(adapter).to eq Faraday::Adapter::Patron
      end
    end

    context 'when the adapter is typhoeus' do
      let(:adapter) do
        client.transport.connections.all.first.connection.builder.adapter
      end

      let(:client) do
        described_class.new(adapter: :typhoeus, enable_meta_header: false)
      end

      it 'uses Faraday with the adapter' do
        expect(adapter).to eq Faraday::Adapter::Typhoeus
      end
    end unless jruby?

    context 'when the adapter is specified as a string key' do
      let(:adapter) do
        client.transport.connections.all.first.connection.builder.adapter
      end

      let(:client) do
        described_class.new(adapter: :patron, enable_meta_header: false)
      end

      it 'uses Faraday with the adapter' do
        expect(adapter).to eq Faraday::Adapter::Patron
      end
    end

    context 'when the adapter can be detected', unless: jruby? do

      around do |example|
        require 'patron'; load 'patron.rb'
        example.run
      end

      let(:adapter) do
        client.transport.connections.all.first.connection.builder.adapter
      end

      it 'uses the detected adapter' do
        expect(adapter).to eq Faraday::Adapter::Patron
      end
    end

    context 'when the Faraday adapter is configured' do

      let(:client) do
        described_class.new do |faraday|
          faraday.adapter :patron
          faraday.response :logger
        end
      end

      let(:adapter) do
        client.transport.connections.all.first.connection.builder.adapter
      end

      let(:handlers) do
        client.transport.connections.all.first.connection.builder.handlers
      end

      it 'sets the adapter' do
        expect(adapter).to eq Faraday::Adapter::Patron
      end

      it 'sets the logger' do
        expect(handlers).to include(Faraday::Response::Logger)
      end
    end
  end

  context 'when cloud credentials are provided' do

    let(:client) do
      described_class.new(
        cloud_id: 'name:bG9jYWxob3N0JGFiY2QkZWZnaA==',
        user: 'elastic',
        password: 'changeme'
      )
    end

    let(:hosts) do
      client.transport.hosts
    end

    it 'extracts the cloud credentials' do
      expect(hosts[0][:host]).to eq('abcd.localhost')
      expect(hosts[0][:protocol]).to eq('https')
      expect(hosts[0][:user]).to eq('elastic')
      expect(hosts[0][:password]).to eq('changeme')
      expect(hosts[0][:port]).to eq(443)
    end

    it 'creates the correct full url' do
      expect(
        client.transport.__full_url(client.transport.hosts[0])
      ).to eq('https://elastic:changeme@abcd.localhost:443')
    end

    context 'when a port is specified' do

      let(:client) do
        described_class.new(cloud_id: 'name:bG9jYWxob3N0JGFiY2QkZWZnaA==', user: 'elastic', password: 'changeme', port: 9250)
      end

      it 'sets the specified port along with the cloud credentials' do
        expect(hosts[0][:host]).to eq('abcd.localhost')
        expect(hosts[0][:protocol]).to eq('https')
        expect(hosts[0][:user]).to eq('elastic')
        expect(hosts[0][:password]).to eq('changeme')
        expect(hosts[0][:port]).to eq(9250)
      end

      it 'creates the correct full url' do
        expect(client.transport.__full_url(client.transport.hosts[0])).to eq('https://elastic:changeme@abcd.localhost:9250')
      end
    end

    context 'when the cluster has alternate names' do

      let(:client) do
        described_class.new(
          cloud_id: 'myCluster:bG9jYWxob3N0JGFiY2QkZWZnaA==',
          user: 'elasticfantastic',
          password: 'tobechanged'
        )
      end

      let(:hosts) do
        client.transport.hosts
      end

      it 'extracts the cloud credentials' do
        expect(hosts[0][:host]).to eq('abcd.localhost')
        expect(hosts[0][:protocol]).to eq('https')
        expect(hosts[0][:user]).to eq('elasticfantastic')
        expect(hosts[0][:password]).to eq('tobechanged')
        expect(hosts[0][:port]).to eq(443)
      end

      it 'creates the correct full url' do
        expect(
          client.transport.__full_url(client.transport.hosts[0])
        ).to eq('https://elasticfantastic:tobechanged@abcd.localhost:443')
      end
    end

    context 'when decoded cloud id has a trailing dollar sign' do
      let(:client) do
        described_class.new(
          cloud_id: 'a_cluster:bG9jYWxob3N0JGFiY2Qk',
          user: 'elasticfantastic',
          password: 'changeme'
        )
      end

      let(:hosts) do
        client.transport.hosts
      end

      it 'extracts the cloud credentials' do
        expect(hosts[0][:host]).to eq('abcd.localhost')
        expect(hosts[0][:protocol]).to eq('https')
        expect(hosts[0][:user]).to eq('elasticfantastic')
        expect(hosts[0][:password]).to eq('changeme')
        expect(hosts[0][:port]).to eq(443)
      end

      it 'creates the correct full url' do
        expect(
          client.transport.__full_url(client.transport.hosts[0])
        ).to eq('https://elasticfantastic:changeme@abcd.localhost:443')
      end
    end

    context 'when the cloud host provides a port' do
      let(:client) do
        described_class.new(
          cloud_id: 'name:ZWxhc3RpY19zZXJ2ZXI6OTI0MyRlbGFzdGljX2lk',
          user: 'elastic',
          password: 'changeme'
        )
      end

      let(:hosts) do
        client.transport.hosts
      end

      it 'creates the correct full url' do
        expect(hosts[0][:host]).to eq('elastic_id.elastic_server')
        expect(hosts[0][:protocol]).to eq('https')
        expect(hosts[0][:user]).to eq('elastic')
        expect(hosts[0][:password]).to eq('changeme')
        expect(hosts[0][:port]).to eq(9243)
      end
    end

    context 'when the cloud host provides a port and the port is also specified' do
      let(:client) do
        described_class.new(
          cloud_id: 'name:ZWxhc3RpY19zZXJ2ZXI6OTI0MyRlbGFzdGljX2lk',
          user: 'elastic',
          password: 'changeme',
          port: 9200
        )
      end

      let(:hosts) do
        client.transport.hosts
      end

      it 'creates the correct full url' do
        expect(hosts[0][:host]).to eq('elastic_id.elastic_server')
        expect(hosts[0][:protocol]).to eq('https')
        expect(hosts[0][:user]).to eq('elastic')
        expect(hosts[0][:password]).to eq('changeme')
        expect(hosts[0][:port]).to eq(9243)
      end
    end
  end

  shared_examples_for 'a client that extracts hosts' do

    context 'when the host is a String' do

      context 'when there is a protocol specified' do

        context 'when credentials are specified \'http://USERNAME:PASSWORD@myhost:8080\'' do

          let(:host) do
            'http://USERNAME:PASSWORD@myhost:8080'
          end

          it 'extracts the credentials' do
            expect(hosts[0][:user]).to eq('USERNAME')
            expect(hosts[0][:password]).to eq('PASSWORD')
          end

          it 'extracts the host' do
            expect(hosts[0][:host]).to eq('myhost')
          end

          it 'extracts the port' do
            expect(hosts[0][:port]).to be(8080)
          end
        end

        context 'when there is a trailing slash \'http://myhost/\'' do

          let(:host) do
            'http://myhost/'
          end

          it 'extracts the host' do
            expect(hosts[0][:host]).to eq('myhost')
            expect(hosts[0][:scheme]).to eq('http')
            expect(hosts[0][:path]).to eq('')
          end

          it 'extracts the scheme' do
            expect(hosts[0][:scheme]).to eq('http')
          end

          it 'extracts the path' do
            expect(hosts[0][:path]).to eq('')
          end
        end

        context 'when there is a trailing slash with a path \'http://myhost/foo/bar/\'' do

          let(:host) do
            'http://myhost/foo/bar/'
          end

          it 'extracts the host' do
            expect(hosts[0][:host]).to eq('myhost')
            expect(hosts[0][:scheme]).to eq('http')
            expect(hosts[0][:path]).to eq('/foo/bar')
          end
        end

        context 'when the protocol is http' do

          context 'when there is no port specified \'http://myhost\'' do

            let(:host) do
              'http://myhost'
            end

            it 'extracts the host' do
              expect(hosts[0][:host]).to eq('myhost')
            end

            it 'extracts the protocol' do
              expect(hosts[0][:protocol]).to eq('http')
            end

            it 'defaults to port 9200' do
              expect(hosts[0][:port]).to be(9200)
            end
          end

          context 'when there is a port specified \'http://myhost:7101\'' do

            let(:host) do
              'http://myhost:7101'
            end

            it 'extracts the host' do
              expect(hosts[0][:host]).to eq('myhost')
            end

            it 'extracts the protocol' do
              expect(hosts[0][:protocol]).to eq('http')
            end

            it 'extracts the port' do
              expect(hosts[0][:port]).to be(7101)
            end

            context 'when there is a path specified \'http://myhost:7101/api\'' do

              let(:host) do
                'http://myhost:7101/api'
              end

              it 'sets the path' do
                expect(hosts[0][:host]).to eq('myhost')
                expect(hosts[0][:protocol]).to eq('http')
                expect(hosts[0][:path]).to eq('/api')
                expect(hosts[0][:port]).to be(7101)
              end

              it 'extracts the host' do
                expect(hosts[0][:host]).to eq('myhost')
              end

              it 'extracts the protocol' do
                expect(hosts[0][:protocol]).to eq('http')
              end

              it 'extracts the port' do
                expect(hosts[0][:port]).to be(7101)
              end

              it 'extracts the path' do
                expect(hosts[0][:path]).to eq('/api')
              end
            end
          end
        end

        context 'when the protocol is https' do

          context 'when there is no port specified \'https://myhost\'' do

            let(:host) do
              'https://myhost'
            end

            it 'extracts the host' do
              expect(hosts[0][:host]).to eq('myhost')
            end

            it 'extracts the protocol' do
              expect(hosts[0][:protocol]).to eq('https')
            end

            it 'defaults to port 443' do
              expect(hosts[0][:port]).to be(443)
            end
          end

          context 'when there is a port specified \'https://myhost:7101\'' do

            let(:host) do
              'https://myhost:7101'
            end

            it 'extracts the host' do
              expect(hosts[0][:host]).to eq('myhost')
            end

            it 'extracts the protocol' do
              expect(hosts[0][:protocol]).to eq('https')
            end

            it 'extracts the port' do
              expect(hosts[0][:port]).to be(7101)
            end

            context 'when there is a path specified \'https://myhost:7101/api\'' do

              let(:host) do
                'https://myhost:7101/api'
              end

              it 'extracts the host' do
                expect(hosts[0][:host]).to eq('myhost')
              end

              it 'extracts the protocol' do
                expect(hosts[0][:protocol]).to eq('https')
              end

              it 'extracts the port' do
                expect(hosts[0][:port]).to be(7101)
              end

              it 'extracts the path' do
                expect(hosts[0][:path]).to eq('/api')
              end
            end
          end

          context 'when IPv6 format is used' do

            around do |example|
              original_setting = Faraday.ignore_env_proxy
              Faraday.ignore_env_proxy = true
              example.run
              Faraday.ignore_env_proxy = original_setting
            end

            let(:host) do
              'https://[2090:db8:85a3:9811::1f]:8080'
            end

            it 'extracts the host' do
              expect(hosts[0][:host]).to eq('[2090:db8:85a3:9811::1f]')
            end

            it 'extracts the protocol' do
              expect(hosts[0][:protocol]).to eq('https')
            end

            it 'extracts the port' do
              expect(hosts[0][:port]).to be(8080)
            end

            it 'creates the correct full url' do
              expect(client.transport.__full_url(client.transport.hosts[0])).to eq('https://[2090:db8:85a3:9811::1f]:8080')
            end
          end
        end
      end

      context 'when no protocol is specified \'myhost\'' do

        let(:host) do
          'myhost'
        end

        it 'defaults to http' do
          expect(hosts[0][:host]).to eq('myhost')
          expect(hosts[0][:protocol]).to eq('http')
        end

        it 'uses port 9200' do
          expect(hosts[0][:port]).to be(9200)
        end
      end
    end

    context 'when the host is a Hash' do

      let(:host) do
        { :host => 'myhost', :scheme => 'https' }
      end

      it 'extracts the host' do
        expect(hosts[0][:host]).to eq('myhost')
      end

      it 'extracts the protocol' do
        expect(hosts[0][:protocol]).to eq('https')
      end

      it 'extracts the port' do
        expect(hosts[0][:port]).to be(9200)
      end

      context 'when IPv6 format is used' do

        around do |example|
          original_setting = Faraday.ignore_env_proxy
          Faraday.ignore_env_proxy = true
          example.run
          Faraday.ignore_env_proxy = original_setting
        end

        let(:host) do
          { host: '[2090:db8:85a3:9811::1f]', scheme: 'https', port: '443' }
        end

        it 'extracts the host' do
          expect(hosts[0][:host]).to eq('[2090:db8:85a3:9811::1f]')
          expect(hosts[0][:scheme]).to eq('https')
          expect(hosts[0][:port]).to be(443)
        end

        it 'creates the correct full url' do
          expect(client.transport.__full_url(client.transport.hosts[0])).to eq('https://[2090:db8:85a3:9811::1f]:443')
        end
      end

      context 'when the host is localhost as a IPv6 address' do

        around do |example|
          original_setting = Faraday.ignore_env_proxy
          Faraday.ignore_env_proxy = true
          example.run
          Faraday.ignore_env_proxy = original_setting
        end

        let(:host) do
          { host: '[::1]' }
        end

        it 'extracts the host' do
          expect(hosts[0][:host]).to eq('[::1]')
          expect(hosts[0][:port]).to be(9200)
        end

        it 'creates the correct full url' do
          expect(client.transport.__full_url(client.transport.hosts[0])).to eq('http://[::1]:9200')
        end
      end

      context 'when the port is specified as a String' do

        let(:host) do
          { host: 'myhost', scheme: 'https', port: '443' }
        end

        it 'extracts the host' do
          expect(hosts[0][:host]).to eq('myhost')
        end

        it 'extracts the protocol' do
          expect(hosts[0][:scheme]).to eq('https')
        end

        it 'converts the port to an integer' do
          expect(hosts[0][:port]).to be(443)
        end
      end

      context 'when the port is specified as an Integer' do

        let(:host) do
          { host: 'myhost', scheme: 'https', port: 443 }
        end

        it 'extracts the host' do
          expect(hosts[0][:host]).to eq('myhost')
        end

        it 'extracts the protocol' do
          expect(hosts[0][:scheme]).to eq('https')
        end

        it 'extracts port as an integer' do
          expect(hosts[0][:port]).to be(443)
        end
      end
    end

    context 'when the hosts are a Hashie:Mash' do

      let(:host) do
        Hashie::Mash.new(host: 'myhost', scheme: 'https')
      end

      it 'extracts the host' do
        expect(hosts[0][:host]).to eq('myhost')
      end

      it 'extracts the protocol' do
        expect(hosts[0][:scheme]).to eq('https')
      end

      it 'converts the port to an integer' do
        expect(hosts[0][:port]).to be(9200)
      end

      context 'when the port is specified as a String' do

        let(:host) do
          Hashie::Mash.new(host: 'myhost', scheme: 'https', port: '443')
        end

        it 'extracts the host' do
          expect(hosts[0][:host]).to eq('myhost')
        end

        it 'extracts the protocol' do
          expect(hosts[0][:scheme]).to eq('https')
        end

        it 'converts the port to an integer' do
          expect(hosts[0][:port]).to be(443)
        end
      end

      context 'when the port is specified as an Integer' do

        let(:host) do
          Hashie::Mash.new(host: 'myhost', scheme: 'https', port: 443)
        end

        it 'extracts the host' do
          expect(hosts[0][:host]).to eq('myhost')
        end

        it 'extracts the protocol' do
          expect(hosts[0][:scheme]).to eq('https')
        end

        it 'extracts port as an integer' do
          expect(hosts[0][:port]).to be(443)
        end
      end
    end

    context 'when the hosts are an array' do

      context 'when there is one host' do

        let(:host) do
          ['myhost']
        end

        it 'extracts the host' do
          expect(hosts[0][:host]).to eq('myhost')
        end

        it 'extracts the protocol' do
          expect(hosts[0][:protocol]).to eq('http')
        end

        it 'defaults to port 9200' do
          expect(hosts[0][:port]).to be(9200)
        end
      end

      context 'when there is one host with a protocol and no port' do

        let(:host) do
          ['http://myhost']
        end

        it 'extracts the host' do
          expect(hosts[0][:host]).to eq('myhost')
        end

        it 'extracts the protocol' do
          expect(hosts[0][:scheme]).to eq('http')
        end

        it 'defaults to port 9200' do
          expect(hosts[0][:port]).to be(9200)
        end
      end

      context 'when there is one host with a protocol and the default http port explicitly provided' do
        let(:host) do
          ['http://myhost:80']
        end

        it 'respects the explicit port' do
          expect(hosts[0][:port]).to be(80)
        end
      end

      context 'when there is one host with a protocol and the default https port explicitly provided' do
        let(:host) do
          ['https://myhost:443']
        end

        it 'respects the explicit port' do
          expect(hosts[0][:port]).to be(443)
        end
      end

      context 'when there is one host with a protocol and no port' do

        let(:host) do
          ['https://myhost']
        end

        it 'extracts the host' do
          expect(hosts[0][:host]).to eq('myhost')
        end

        it 'extracts the protocol' do
          expect(hosts[0][:scheme]).to eq('https')
        end

        it 'defaults to port 443' do
          expect(hosts[0][:port]).to be(443)
        end
      end

      context 'when there is one host with a protocol, path, and no port' do

        let(:host) do
          ['http://myhost/foo/bar']
        end

        it 'extracts the host' do
          expect(hosts[0][:host]).to eq('myhost')
        end

        it 'extracts the protocol' do
          expect(hosts[0][:scheme]).to eq('http')
        end

        it 'defaults to port 9200' do
          expect(hosts[0][:port]).to be(9200)
        end

        it 'extracts the path' do
          expect(hosts[0][:path]).to eq('/foo/bar')
        end
      end

      context 'when there is more than one host' do

        let(:host) do
          ['host1', 'host2']
        end

        it 'extracts the hosts' do
          expect(hosts[0][:host]).to eq('host1')
          expect(hosts[0][:protocol]).to eq('http')
          expect(hosts[0][:port]).to be(9200)
          expect(hosts[1][:host]).to eq('host2')
          expect(hosts[1][:protocol]).to eq('http')
          expect(hosts[1][:port]).to be(9200)
        end
      end

      context 'when ports are also specified' do

        let(:host) do
          ['host1:1000', 'host2:2000']
        end

        it 'extracts the hosts' do
          expect(hosts[0][:host]).to eq('host1')
          expect(hosts[0][:protocol]).to eq('http')
          expect(hosts[0][:port]).to be(1000)
          expect(hosts[1][:host]).to eq('host2')
          expect(hosts[1][:protocol]).to eq('http')
          expect(hosts[1][:port]).to be(2000)
        end
      end
    end

    context 'when the hosts is an instance of URI' do

      let(:host) do
        URI.parse('https://USERNAME:PASSWORD@myhost:4430')
      end

      it 'extracts the host' do
        expect(hosts[0][:host]).to eq('myhost')
        expect(hosts[0][:scheme]).to eq('https')
        expect(hosts[0][:port]).to be(4430)
        expect(hosts[0][:user]).to eq('USERNAME')
        expect(hosts[0][:password]).to eq('PASSWORD')
      end
    end

    context 'when the hosts is invalid' do

      let(:host) do
        123
      end

      it 'extracts the host' do
        expect {
          hosts
        }.to raise_exception(ArgumentError)
      end
    end
  end

  context 'when hosts are specified with the \'host\' key' do

    let(:client) do
      described_class.new(host: ['host1', 'host2', 'host3', 'host4'], randomize_hosts: true)
    end

    let(:hosts) do
      client.transport.hosts
    end

    it 'sets the hosts in random order' do
      expect(hosts.all? { |host| client.transport.hosts.include?(host) }).to be(true)
    end
  end

  context 'when hosts are specified with the \'host\' key as a String' do

    let(:client) do
      described_class.new('host' => ['host1', 'host2', 'host3', 'host4'], 'randomize_hosts' => true)
    end

    let(:hosts) do
      client.transport.hosts
    end

    it 'sets the hosts in random order' do
      expect(hosts.all? { |host| client.transport.hosts.include?(host) }).to be(true)
    end
  end

  context 'when hosts are specified with the \'hosts\' key' do

    let(:client) do
      described_class.new(hosts: host)
    end

    let(:hosts) do
      client.transport.hosts
    end

    it_behaves_like 'a client that extracts hosts'
  end

  context 'when hosts are specified with the \'hosts\' key as a String' do

    let(:client) do
      described_class.new('hosts' => host)
    end

    let(:hosts) do
      client.transport.hosts
    end

    it_behaves_like 'a client that extracts hosts'
  end

  context 'when hosts are specified with the \'url\' key' do

    let(:client) do
      described_class.new(url: host)
    end

    let(:hosts) do
      client.transport.hosts
    end

    it_behaves_like 'a client that extracts hosts'
  end

  context 'when hosts are specified with the \'url\' key as a String' do

    let(:client) do
      described_class.new('url' => host)
    end

    let(:hosts) do
      client.transport.hosts
    end

    it_behaves_like 'a client that extracts hosts'
  end

  context 'when hosts are specified with the \'urls\' key' do

    let(:client) do
      described_class.new(urls: host)
    end

    let(:hosts) do
      client.transport.hosts
    end

    it_behaves_like 'a client that extracts hosts'
  end

  context 'when hosts are specified with the \'urls\' key as a String' do

    let(:client) do
      described_class.new('urls' => host)
    end

    let(:hosts) do
      client.transport.hosts
    end

    it_behaves_like 'a client that extracts hosts'
  end

  context 'when the URL is set in the ELASTICSEARCH_URL environment variable' do

    context 'when there is only one host specified' do

      around do |example|
        before_url = ENV['ELASTICSEARCH_URL']
        ENV['ELASTICSEARCH_URL'] = 'example.com'
        example.run
        ENV['ELASTICSEARCH_URL'] = before_url
      end

      it 'sets the host' do
        expect(client.transport.hosts[0][:host]).to eq('example.com')
        expect(client.transport.hosts.size).to eq(1)
      end
    end

    context 'when mutliple hosts are specified as a comma-separated String list' do

      around do |example|
        before_url = ENV['ELASTICSEARCH_URL']
        ENV['ELASTICSEARCH_URL'] = 'example.com, other.com'
        example.run
        ENV['ELASTICSEARCH_URL'] = before_url
      end

      it 'sets the hosts' do
        expect(client.transport.hosts[0][:host]).to eq('example.com')
        expect(client.transport.hosts[1][:host]).to eq('other.com')
        expect(client.transport.hosts.size).to eq(2)
      end
    end
  end

  context 'when options are defined' do

    context 'when scheme is specified' do

      let(:client) do
        described_class.new(scheme: 'https')
      end

      it 'sets the scheme' do
        expect(client.transport.connections[0].full_url('')).to match(/https/)
      end
    end

    context 'when scheme is specified as a String key' do

      let(:client) do
        described_class.new('scheme' => 'https')
      end

      it 'sets the scheme' do
        expect(client.transport.connections[0].full_url('')).to match(/https/)
      end
    end

    context 'when user and password are specified' do

      let(:client) do
        described_class.new(user: 'USERNAME', password: 'PASSWORD')
      end

      it 'sets the user and password' do
        expect(client.transport.connections[0].full_url('')).to match(/USERNAME/)
        expect(client.transport.connections[0].full_url('')).to match(/PASSWORD/)
      end

      context 'when the connections are reloaded' do

        before do
          allow(client.transport.sniffer).to receive(:hosts).and_return([{ host: 'foobar', port: 4567, id: 'foobar4567' }])
          client.transport.reload_connections!
        end

        it 'sets keeps user and password' do
          expect(client.transport.connections[0].full_url('')).to match(/USERNAME/)
          expect(client.transport.connections[0].full_url('')).to match(/PASSWORD/)
          expect(client.transport.connections[0].full_url('')).to match(/foobar/)
        end
      end
    end

    context 'when user and password are specified as String keys' do

      let(:client) do
        described_class.new('user' => 'USERNAME', 'password' => 'PASSWORD')
      end

      it 'sets the user and password' do
        expect(client.transport.connections[0].full_url('')).to match(/USERNAME/)
        expect(client.transport.connections[0].full_url('')).to match(/PASSWORD/)
      end

      context 'when the connections are reloaded' do

        before do
          allow(client.transport.sniffer).to receive(:hosts).and_return([{ host: 'foobar', port: 4567, id: 'foobar4567' }])
          client.transport.reload_connections!
        end

        it 'sets keeps user and password' do
          expect(client.transport.connections[0].full_url('')).to match(/USERNAME/)
          expect(client.transport.connections[0].full_url('')).to match(/PASSWORD/)
          expect(client.transport.connections[0].full_url('')).to match(/foobar/)
        end
      end
    end

    context 'when port is specified' do

      let(:client) do
        described_class.new(host: 'node1', port: 1234)
      end

      it 'sets the port' do
        expect(client.transport.connections[0].full_url('')).to match(/1234/)
      end
    end

    context 'when the log option is true' do

      let(:client) do
        described_class.new(log: true)
      end

      it 'has a default logger for transport' do
        expect(client.transport.logger.info).to eq(described_class::DEFAULT_LOGGER.call.info)
      end
    end

    context 'when the trace option is true' do

      let(:client) do
        described_class.new(trace: true)
      end

      it 'has a default logger for transport' do
        expect(client.transport.tracer.info).to eq(described_class::DEFAULT_TRACER.call.info)
      end
    end

    context 'when a custom transport class is specified' do

      let(:transport_class) do
        Class.new { def initialize(*); end }
      end

      let(:client) do
        described_class.new(transport_class: transport_class)
      end

      it 'allows the custom transport class to be defined' do
        expect(client.transport).to be_a(transport_class)
      end
    end

    context 'when a custom transport instance is specified' do

      let(:transport_instance) do
        Class.new { def initialize(*); end }.new
      end

      let(:client) do
        described_class.new(transport: transport_instance)
      end

      it 'allows the custom transport class to be defined' do
        expect(client.transport).to be(transport_instance)
      end
    end

    context 'when \'transport_options\' are defined' do

      let(:client) do
        described_class.new(transport_options: { request: { timeout: 1 } })
      end

      it 'sets the options on the transport' do
        expect(client.transport.options[:transport_options][:request]).to eq(timeout: 1)
      end
    end

    context 'when \'request_timeout\' is defined' do

      let(:client) do
        described_class.new(request_timeout: 120)
      end

      it 'sets the options on the transport' do
        expect(client.transport.options[:transport_options][:request]).to eq(timeout: 120)
      end
    end

    context 'when \'request_timeout\' is defined as a String key' do

      let(:client) do
        described_class.new('request_timeout' => 120)
      end

      it 'sets the options on the transport' do
        expect(client.transport.options[:transport_options][:request]).to eq(timeout: 120)
      end
    end
  end

  describe '#perform_request' do

    let(:transport_instance) do
      Class.new { def initialize(*); end }.new
    end

    let(:client) do
      described_class.new(transport: transport_instance)
    end

    it 'delegates performing requests to the transport' do
      expect(transport_instance).to receive(:perform_request).and_return(true)
      expect(client.perform_request('GET', '/')).to be(true)
    end

    context 'when the \'send_get_body_as\' option is specified' do

      let(:client) do
        described_class.new(transport: transport_instance, :send_get_body_as => 'POST')
      end

      before do
        expect(transport_instance).to receive(:perform_request).with('POST', '/', {},
                                                                     '{"foo":"bar"}',
                                                                     '{"Content-Type":"application/x-ndjson"}').and_return(true)
      end

      let(:request) do
        client.perform_request('POST', '/', {}, '{"foo":"bar"}', '{"Content-Type":"application/x-ndjson"}')
      end

      it 'sets the option' do
        expect(request).to be(true)
      end
    end

    context 'when x-opaque-id is set' do
      let(:client) { described_class.new(host: hosts) }

      it 'uses x-opaque-id on a request' do
        expect(client.perform_request('GET', '/', { opaque_id: '12345' }).headers['x-opaque-id']).to eq('12345')
      end
    end

    context 'when an x-opaque-id prefix is set on initialization' do
      let(:prefix) { 'elastic_cloud' }
      let(:client) do
        described_class.new(host: hosts, opaque_id_prefix: prefix)
      end

      it 'uses x-opaque-id on a request' do
        expect(client.perform_request('GET', '/', { opaque_id: '12345' }).headers['x-opaque-id']).to eq("#{prefix}12345")
      end

      context 'when using an API call' do
        let(:client) { described_class.new(host: hosts) }

        it 'doesnae raise an ArgumentError' do
          expect { client.perform_request('GET', '_search', opaque_id: 'no_error') }.not_to raise_error
        end

        it 'uses X-Opaque-Id in the header' do
          allow(client).to receive(:perform_request) { OpenStruct.new(body: '') }
          expect { client.perform_request('GET', '_search', {}, nil, opaque_id: 'opaque_id') }.not_to raise_error
          expect(client).to have_received(:perform_request)
                              .with('GET', '_search', {}, nil, { opaque_id: 'opaque_id' })
        end
      end
    end

    context 'when using the API Compatibility Header' do
      it 'sets the API compatibility headers' do
        ENV['ELASTIC_CLIENT_APIVERSIONING'] = 'true'
        client = described_class.new(host: hosts)
        headers = client.transport.connections.first.connection.headers

        expect(headers['Content-Type']).to eq('application/vnd.elasticsearch+json; compatible-with=7')
        expect(headers['Accept']).to eq('application/vnd.elasticsearch+json; compatible-with=7')

        ENV.delete('ELASTIC_CLIENT_APIVERSIONING')
      end

      it 'does not use API compatibility headers' do
        val = ENV.delete('ELASTIC_CLIENT_APIVERSIONING')
        client = described_class.new(host: hosts)
        expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')
        ENV['ELASTIC_CLIENT_APIVERSIONING'] = val
      end

      it 'does not use API compatibility headers when it is set to unsupported values' do
        val = ENV.delete('ELASTIC_CLIENT_APIVERSIONING')

        ENV['ELASTIC_CLIENT_APIVERSIONING'] = 'test'
        client = described_class.new(host: hosts)
        expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')

        ENV['ELASTIC_CLIENT_APIVERSIONING'] = 'false'
        client = described_class.new(host: hosts)
        expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')

        ENV['ELASTIC_CLIENT_APIVERSIONING'] = '3'
        client = described_class.new(host: hosts)
        expect(client.transport.connections.first.connection.headers['Content-Type']).to eq('application/json')
        ENV['ELASTIC_CLIENT_APIVERSIONING'] = val
      end
    end

    context 'when Elasticsearch response includes a warning header' do
      let(:logger) { double('logger', warn: '', warn?: '', info?: '', info: '', debug?: '', debug: '') }
      let(:client) do
        Elasticsearch::Transport::Client.new(hosts: hosts, logger: logger)
      end

      let(:warning) { 'Elasticsearch warning: "deprecation warning"' }

      it 'prints a warning' do
        expect_any_instance_of(Faraday::Connection).to receive(:run_request) do
          Elasticsearch::Transport::Transport::Response.new(200, {}, { 'warning' => warning })
        end
        client.perform_request('GET', '/')
        expect(logger).to have_received(:warn).with(warning)
      end
    end

    context 'when a header is set on an endpoint request' do
      let(:client) { described_class.new(host: hosts) }
      let(:headers) { { 'user-agent' => 'my ruby app' } }

      it 'performs the request with the header' do
        allow(client).to receive(:perform_request) { OpenStruct.new(body: '') }
        expect { client.perform_request('GET', '_search', {}, nil, headers) }.not_to raise_error
        expect(client).to have_received(:perform_request)
                            .with('GET', '_search', {}, nil, headers)
      end
    end

    context 'when a header is set on an endpoint request and on initialization' do
      let!(:client) do
        described_class.new(
          host: hosts,
          transport_options: { headers: instance_headers }
        )
      end
      let(:instance_headers) { { set_in_instantiation: 'header value' } }
      let(:param_headers) { {'user-agent' => 'My Ruby Tests', 'set-on-method-call' => 'header value'} }

      it 'performs the request with the header' do
        expected_headers = client.transport.connections.connections.first.connection.headers.merge(param_headers)

        expect_any_instance_of(Faraday::Connection)
          .to receive(:run_request)
                .with(:get, "http://#{hosts[0]}/_search", nil, expected_headers) { OpenStruct.new(body: '')}

        client.perform_request('GET', '_search', {}, nil, param_headers)
      end
    end
  end

  context 'when the client connects to Elasticsearch' do
    let(:logger) do
      Logger.new(STDERR).tap do |logger|
        logger.formatter = proc do |severity, datetime, progname, msg|
          color = case severity
                  when /INFO/ then :green
                  when /ERROR|WARN|FATAL/ then :red
                  when /DEBUG/ then :cyan
                  else :white
                  end
          ANSI.ansi(severity[0] + ' ', color, :faint) + ANSI.ansi(msg, :white, :faint) + "\n"
        end
      end unless ENV['QUIET']
    end

    let(:port) do
      TEST_PORT
    end

    let(:transport_options) do
      {}
    end

    let(:options) do
      {}
    end

    let(:client) do
      described_class.new({ host: hosts, logger: logger }.merge!(transport_options: transport_options).merge!(options))
    end

    context 'when a request is made' do
      let!(:response) do
        client.perform_request('GET', '_cluster/health')
      end

      it 'connects to the cluster' do
        expect(response.body['number_of_nodes']).to be >= (1)
      end
    end

    describe '#initialize' do
      context 'when options are specified' do
        let(:transport_options) do
          { headers: { accept: 'application/yaml', content_type: 'application/yaml' } }
        end

        let(:response) do
          client.perform_request('GET', '_cluster/health')
        end

        it 'applies the options to the client' do
          expect(response.body).to match(/---\n/)
          expect(response.headers['content-type']).to eq('application/yaml')
        end
      end

      context 'when a block is provided' do
        let(:client) do
          described_class.new(host: ELASTICSEARCH_HOSTS.first, logger: logger) do |client|
            client.headers['Accept'] = 'application/yaml'
          end
        end

        let(:response) do
          client.perform_request('GET', '_cluster/health')
        end

        it 'executes the block' do
          expect(response.body).to match(/---\n/)
          expect(response.headers['content-type']).to eq('application/yaml')
        end

        context 'when the Faraday adapter is set in the block' do
          let(:client) do
            described_class.new(host: ELASTICSEARCH_HOSTS.first, logger: logger) do |client|
              client.adapter(:net_http_persistent)
            end
          end

          let(:handler_name) do
            client.transport.connections.first.connection.builder.adapter.name
          end

          let(:response) do
            client.perform_request('GET', '_cluster/health')
          end

          it 'sets the adapter' do
            expect(handler_name).to eq('Faraday::Adapter::NetHttpPersistent')
          end

          it 'uses the adapter to connect' do
            expect(response.status).to eq(200)
          end
        end
      end
    end

    describe '#options' do

      context 'when retry_on_failure is true' do

        context 'when a node is unreachable' do

          let(:hosts) do
            [ELASTICSEARCH_HOSTS.first, "foobar1", "foobar2"]
          end

          let(:options) do
            { retry_on_failure: true }
          end

          let(:responses) do
            5.times.collect do
              client.perform_request('GET', '_nodes/_local')
            end
          end

          it 'retries on failure' do
            expect(responses.all? { true }).to be(true)
          end
        end
      end

      context 'when retry_on_failure is an integer' do

        let(:hosts) do
          [ELASTICSEARCH_HOSTS.first, 'foobar1', 'foobar2', 'foobar3']
        end

        let(:options) do
          { retry_on_failure: 1 }
        end

        it 'retries only the specified number of times' do
          expect(client.perform_request('GET', '_nodes/_local'))
          expect {
            client.perform_request('GET', '_nodes/_local')
          }.to raise_exception(Faraday::ConnectionFailed)
        end
      end

      context 'when retry_on_failure is true and delay_on_retry is specified' do
        context 'when a node is unreachable' do
          let(:hosts) do
            [ELASTICSEARCH_HOSTS.first, "foobar1", "foobar2"]
          end

          let(:options) do
            { retry_on_failure: true, delay_on_retry: 3000 }
          end

          let(:responses) do
            5.times.collect do
              client.perform_request('GET', '_nodes/_local')
            end
          end

          it 'retries on failure' do
            allow_any_instance_of(Object).to receive(:sleep).with(3000 / 1000)
            expect(responses.all? { true }).to be(true)
          end
        end
      end

      context 'when reload_on_failure is true' do

        let(:hosts) do
          [ELASTICSEARCH_HOSTS.first, 'foobar1', 'foobar2']
        end

        let(:options) do
          { reload_on_failure: true }
        end

        let(:responses) do
          5.times.collect do
            client.perform_request('GET', '_nodes/_local')
          end
        end

        it 'reloads the connections' do
          expect(client.transport.connections.size).to eq(3)
          expect(responses.all? { true }).to be(true)
          expect(client.transport.connections.size).to be >= (1)
        end
      end

      context 'when retry_on_status is specified' do

        let(:options) do
          { retry_on_status: 400 }
        end

        let(:logger) do
          double('logger', :debug? => false, :warn? => true, :fatal? => false, :error? => false)
        end

        before do
          expect(logger).to receive(:warn).exactly(4).times
        end

        it 'retries when the status matches' do
          expect {
            client.perform_request('PUT', '_foobar')
          }.to raise_exception(Elasticsearch::Transport::Transport::Errors::BadRequest)
        end
      end

      context 'when the \'compression\' option is set to true' do

        context 'when using Faraday as the transport' do

          context 'when using the Net::HTTP adapter' do

            let(:client) do
              described_class.new(hosts: ELASTICSEARCH_HOSTS, compression: true, adapter: :net_http)
            end

            it 'compresses the request and decompresses the response' do
              expect(client.perform_request('GET', '/').body).to be_a(Hash)
            end

            it 'sets the Accept-Encoding header' do
              expect(client.transport.connections[0].connection.headers['Accept-Encoding']).to eq 'gzip'
            end

            it 'preserves the other headers' do
              expect(client.transport.connections[0].connection.headers['User-Agent'])
            end
          end

          context 'when using the HTTPClient adapter' do

            let(:client) do
              described_class.new(hosts: ELASTICSEARCH_HOSTS, compression: true, adapter: :httpclient, enable_meta_header: false)
            end

            it 'compresses the request and decompresses the response' do
              expect(client.perform_request('GET', '/').body).to be_a(Hash)
            end

            it 'sets the Accept-Encoding header' do
              expect(client.transport.connections[0].connection.headers['Accept-Encoding']).to eq 'gzip'
            end

            it 'preserves the other headers' do
              expect(client.transport.connections[0].connection.headers['User-Agent'])
            end
          end

          context 'when using the Patron adapter', unless: jruby? do

            let(:client) do
              described_class.new(hosts: ELASTICSEARCH_HOSTS, compression: true, adapter: :patron)
            end

            it 'compresses the request and decompresses the response' do
              expect(client.perform_request('GET', '/').body).to be_a(Hash)
            end

            it 'sets the Accept-Encoding header' do
              expect(client.transport.connections[0].connection.headers['Accept-Encoding']).to eq 'gzip'
            end

            it 'preserves the other headers' do
              expect(client.transport.connections[0].connection.headers['User-Agent'])
            end
          end

          context 'when using the Net::HTTP::Persistent adapter' do

            let(:client) do
              described_class.new(hosts: ELASTICSEARCH_HOSTS, compression: true, adapter: :net_http_persistent)
            end

            it 'compresses the request and decompresses the response' do
              expect(client.perform_request('GET', '/').body).to be_a(Hash)
            end

            it 'sets the Accept-Encoding header' do
              expect(client.transport.connections[0].connection.headers['Accept-Encoding']).to eq 'gzip'
            end

            it 'preserves the other headers' do
              expect(client.transport.connections[0].connection.headers['User-Agent'])
            end
          end

          context 'when using the Typhoeus adapter' do

            let(:client) do
              described_class.new(hosts: ELASTICSEARCH_HOSTS, compression: true, adapter: :typhoeus)
            end

            it 'compresses the request and decompresses the response' do
              expect(client.perform_request('GET', '/').body).to be_a(Hash)
            end

            it 'sets the Accept-Encoding header' do
              expect(client.transport.connections[0].connection.headers['Accept-Encoding']).to eq 'gzip'
            end

            it 'preserves the other headers' do
              expect(client.transport.connections[0].connection.headers['User-Agent'])
            end
          end unless jruby?
        end
      end

      context 'when using Curb as the transport', unless: jruby? do
        let(:client) do
          described_class.new(
            hosts: ELASTICSEARCH_HOSTS,
            compression: true,
            transport_class: Elasticsearch::Transport::Transport::HTTP::Curb
          )
        end

        it 'compresses the request and decompresses the response' do
          expect(client.perform_request('GET', '/').body).to be_a(Hash)
        end

        it 'sets the Accept-Encoding header' do
          expect(client.transport.connections[0].connection.headers['Accept-Encoding']).to eq 'gzip'
        end

        it 'preserves the other headers' do
          expect(client.transport.connections[0].connection.headers['User-Agent'])
        end
      end

      context 'when using Manticore as the transport', if: jruby? do
        let(:client) do
          described_class.new(hosts: ELASTICSEARCH_HOSTS,
                              compression: true,
                              transport_class: Elasticsearch::Transport::Transport::HTTP::Manticore)
        end

        it 'compresses the request and decompresses the response' do
          expect(client.perform_request('GET', '/').body).to be_a(Hash)
        end
      end
    end

    describe '#perform_request' do
      context 'when a request is made' do
        before do
          client.perform_request('DELETE', '_all')
          client.perform_request('DELETE', 'myindex') rescue
          client.perform_request('PUT', 'myindex', {}, { settings: { number_of_shards: 2, number_of_replicas: 0 } })
          client.perform_request('PUT', 'myindex/mydoc/1', { routing: 'XYZ', timeout: '1s' }, { foo: 'bar' })
          client.perform_request('GET', '_cluster/health?wait_for_status=green&timeout=2s', {})
        end

        let(:response) do
          client.perform_request('GET', 'myindex/mydoc/1?routing=XYZ')
        end

        it 'handles paths and URL paramters' do
          expect(response.status).to eq(200)
        end

        it 'returns response body' do
          expect(response.body['_source']).to eq('foo' => 'bar')
        end
      end

      context 'when an invalid url is specified' do
        it 'raises an exception' do
          expect {
            client.perform_request('GET', 'myindex/mydoc/1?routing=FOOBARBAZ')
          }.to raise_exception(Elasticsearch::Transport::Transport::Errors::NotFound)
        end
      end

      context 'when the \'ignore\' parameter is specified' do
        let(:response) do
          client.perform_request('PUT', '_foobar', ignore: 400)
        end

        it 'exposes the status in the response' do
          expect(response.status).to eq(400)
        end

        it 'exposes the body of the response' do
          expect(response.body).to be_a(Hash)
          expect(response.body.inspect).to match(/invalid_index_name_exception/)
        end
      end

      context 'when request headers are specified' do
        let(:response) do
          client.perform_request('GET', '/', {}, nil, { 'Content-Type' => 'application/yaml' })
        end

        it 'passes them to the transport' do
          expect(response.body).to match(/---/)
        end
      end

      describe 'selector' do
        context 'when the round-robin selector is used' do
          let(:nodes) do
            3.times.collect do
              client.perform_request('GET', '_nodes/_local').body['nodes'].to_a[0][1]['name']
            end
          end

          let(:node_names) do
            client.perform_request('GET', '_nodes/stats').body('nodes').collect do |name, stats|
              stats['name']
            end
          end

          let(:expected_names) do
            3.times.collect do |i|
              node_names[i % node_names.size]
            end
          end

          # it 'rotates nodes' do
          #   pending 'Better way to detect rotating nodes'
          #   expect(nodes).to eq(expected_names)
          # end
        end
      end

      context 'when patron is used as an adapter', unless: jruby? do
        before do
          require 'patron'
        end

        let(:options) do
          { adapter: :patron }
        end

        let(:adapter) do
          client.transport.connections.first.connection.builder.adapter
        end

        it 'uses the patron connection handler' do
          expect(adapter).to eq('Faraday::Adapter::Patron')
        end

        it 'keeps connections open' do
          response = client.perform_request('GET', '_nodes/stats/http')
          connections_before = response.body['nodes'].values.find { |n| n['name'] == node_names.first }['http']['total_opened']
          client.transport.reload_connections!
          response = client.perform_request('GET', '_nodes/stats/http')
          connections_after = response.body['nodes'].values.find { |n| n['name'] == node_names.first }['http']['total_opened']
          expect(connections_after).to be >= (connections_before)
        end
      end

      context 'when typhoeus is used as an adapter', unless: jruby? do
        before do
          require 'typhoeus'
        end

        let(:options) do
          { adapter: :typhoeus }
        end

        let(:adapter) do
          client.transport.connections.first.connection.builder.adapter
        end

        it 'uses the patron connection handler' do
          expect(adapter).to eq('Faraday::Adapter::Typhoeus')
        end

        it 'keeps connections open' do
          response = client.perform_request('GET', '_nodes/stats/http')
          connections_before = response.body['nodes'].values.find { |n| n['name'] == node_names.first }['http']['total_opened']
          client.transport.reload_connections!
          response = client.perform_request('GET', '_nodes/stats/http')
          connections_after = response.body['nodes'].values.find { |n| n['name'] == node_names.first }['http']['total_opened']
          expect(connections_after).to be >= (connections_before)
        end
      end
    end
  end

  context 'CA Fingerprinting' do
    context 'when setting a ca_fingerprint' do
      after do
        File.delete('./certificate.crt')
        File.delete('./certificate.key')
      end

      let(:certificate) do
        system(
          'openssl req -new -newkey rsa:4096 -days 3650 -nodes -x509 -subj "/C=BE/O=Test/CN=Test"' \
          ' -keyout certificate.key -out certificate.crt',
          err: File::NULL
        )
        OpenSSL::X509::Certificate.new File.read('./certificate.crt')
      end

      let(:client) do
        Elasticsearch::Transport::Client.new(
          host: 'https://elastic:changeme@localhost:9200',
          ca_fingerprint: OpenSSL::Digest::SHA256.hexdigest(certificate.to_der)
        )
      end

      it 'validates CA fingerprints on perform request' do
        expect(client.transport.connections.connections.map(&:verified).uniq).to eq [false]
        allow(client.transport).to receive(:perform_request) { 'Hello' }

        server = double('server').as_null_object
        allow(TCPSocket).to receive(:new) { server }
        socket = double('socket')
        allow(OpenSSL::SSL::SSLSocket).to receive(:new) { socket }
        allow(socket).to receive(:connect) { nil }
        allow(socket).to receive(:peer_cert_chain) { [certificate] }

        response = client.perform_request('GET', '/')
        expect(client.transport.connections.connections.map(&:verified).uniq).to eq [true]
        expect(response).to eq 'Hello'
      end
    end

    context 'when using an http host' do
      let(:client) do
        Elasticsearch::Transport::Client.new(
          host: 'http://elastic:changeme@localhost:9200',
          ca_fingerprint: 'test'
        )
      end

      it 'raises an error' do
        expect do
          client.perform_request('GET', '/')
        end.to raise_exception(Elasticsearch::Transport::Transport::Error)
      end
    end

    context 'when not setting a ca_fingerprint' do
      let(:client) do
        Elasticsearch::Transport::Client.new(
          host: 'http://elastic:changeme@localhost:9200'
        )
      end

      it 'has unvalidated connections' do
        allow(client).to receive(:validate_ca_fingerprints) { nil }
        allow(client.transport).to receive(:perform_request) { nil }

        client.perform_request('GET', '/')
        expect(client).to_not have_received(:validate_ca_fingerprints)
      end
    end
  end
end