File: test_rest_mock_server.cc

package info (click to toggle)
mysql-8.0 8.0.43-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,273,924 kB
  • sloc: cpp: 4,684,605; ansic: 412,450; pascal: 108,398; java: 83,641; perl: 30,221; cs: 27,067; sql: 26,594; sh: 24,181; python: 21,816; yacc: 17,169; php: 11,522; xml: 7,388; javascript: 7,076; makefile: 2,194; lex: 1,075; awk: 670; asm: 520; objc: 183; ruby: 97; lisp: 86
file content (1261 lines) | stat: -rw-r--r-- 43,285 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
/*
  Copyright (c) 2017, 2025, Oracle and/or its affiliates.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License, version 2.0,
  as published by the Free Software Foundation.

  This program is designed to work with certain software (including
  but not limited to OpenSSL) that is licensed under separate terms,
  as designated in a particular file or component or in included license
  documentation.  The authors of MySQL hereby grant you an additional
  permission to link the program and your derivative works with the
  separately licensed software that they have either included with
  the program or referenced in the documentation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <thread>

#ifdef RAPIDJSON_NO_SIZETYPEDEFINE
#include "my_rapidjson_size_t.h"
#endif

#include <gmock/gmock.h>
#include <rapidjson/document.h>

#include "dim.h"
#include "mock_server_rest_client.h"
#include "mysql/harness/logging/registry.h"
#include "mysqlrouter/http_request.h"
#include "mysqlrouter/mysql_session.h"
#include "mysqlrouter/rest_client.h"
#include "rest_api_testutils.h"
#include "router_component_test.h"
#include "router_component_testutils.h"
#include "tcp_port_pool.h"

Path g_origin_path;

static constexpr const char kMockServerConnectionsRestUri[] =
    "/api/v1/mock_server/connections/";
static constexpr const char kMockServerInvalidRestUri[] =
    "/api/v1/mock_server/global/";

// AddressSanitizer gets confused by the default, MemoryPoolAllocator
// Solaris sparc also gets crashes
using JsonDocument =
    rapidjson::GenericDocument<rapidjson::UTF8<>, rapidjson::CrtAllocator>;
using JsonValue =
    rapidjson::GenericValue<rapidjson::UTF8<>, rapidjson::CrtAllocator>;

class RestMockServerTest : public RouterComponentTest {};

/**
 * base class.
 *
 * starts mock-server with named script and waits for it to startup
 */
class RestMockServerScriptTest : public RestMockServerTest {
 protected:
  RestMockServerScriptTest(const std::string &stmt_file)
      : server_port_{port_pool_.get_next_available()},
        http_port_{port_pool_.get_next_available()},
        json_stmts_{get_data_dir().join(stmt_file).str()},
        server_mock_{launch_mysql_server_mock(
            json_stmts_, server_port_, EXIT_SUCCESS, false, http_port_)} {
    SCOPED_TRACE("// start mock-server with http-port");

    const std::string http_hostname{"127.0.0.1"};

    check_port_ready(server_mock_, server_port_);
  }

  const uint16_t server_port_;
  const uint16_t http_port_;
  const std::string json_stmts_;

  ProcessWrapper &server_mock_;
};

class RestMockServerScriptsWorkTest
    : public RestMockServerTest,
      public ::testing::WithParamInterface<std::string> {};

class RestMockServerScriptsThrowsTest
    : public RestMockServerTest,
      public ::testing::WithParamInterface<
          std::tuple<const char *, const char *>> {};

class RestMockServerConnectThrowsTest
    : public RestMockServerTest,
      public ::testing::WithParamInterface<
          std::tuple<const char *, const char *>> {};

class RestMockServerRestServerMockTest : public RestMockServerScriptTest {
 public:
  RestMockServerRestServerMockTest()
      : RestMockServerScriptTest("rest_server_mock.js") {}
};

/**
 * test mock-server loaded the REST bridge.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 *
 * verifies:
 *
 * - WL12118
 *   - TS_1-6
 */
TEST_F(RestMockServerRestServerMockTest, get_globals_empty) {
  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  SCOPED_TRACE("// make a http connections");
  auto req = rest_client.request_sync(HttpMethod::Get, http_uri);

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 200u);
  EXPECT_THAT(req.get_input_headers().get("Content-Type"),
              ::testing::StrEq("application/json"));

  auto resp_body = req.get_input_buffer();
  EXPECT_GT(resp_body.length(), 0u);
  auto resp_body_content = resp_body.pop_front(resp_body.length());

  // parse json

  std::string json_payload(resp_body_content.begin(), resp_body_content.end());

  JsonDocument json_doc;
  json_doc.Parse(json_payload.c_str());

  EXPECT_TRUE(!json_doc.HasParseError()) << json_payload;
}

template <typename T>
std::string unit();

template <>
std::string unit<std::chrono::seconds>() {
  return "s";
}

template <>
std::string unit<std::chrono::milliseconds>() {
  return "ms";
}

template <>
std::string unit<std::chrono::microseconds>() {
  return "us";
}

template <>
std::string unit<std::chrono::nanoseconds>() {
  return "ns";
}

// must be defined in the same namespace as the type we want to convert
namespace std {

// add to-stream method for all durations for pretty printing
template <class Rep, class Per>
void PrintTo(const chrono::duration<Rep, Per> &span, std::ostream *os) {
  *os << span.count() << unit<typename std::decay<decltype(span)>::type>();
}

}  // namespace std

/**
 * test handshake's exec_time can be set via globals.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 */
TEST_F(RestMockServerRestServerMockTest, handshake_exec_time_via_global) {
  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;

  // handshake exec_time to test
  const auto kDelay = std::chrono::milliseconds{100};

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  SCOPED_TRACE("// make a http connections");
  auto req = rest_client.request_sync(
      HttpMethod::Put, http_uri,
      "{\"connect_exec_time\": " + std::to_string(kDelay.count()) + "}");

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 204u);

  auto resp_body = req.get_input_buffer();
  EXPECT_EQ(resp_body.length(), 0u);

  SCOPED_TRACE("// slow connect");
  auto start_tp = std::chrono::steady_clock::now();
  {
    mysqlrouter::MySQLSession client;

    SCOPED_TRACE("// connecting via mysql protocol");
    ASSERT_NO_THROW(client.connect("127.0.0.1", server_port_, "username",
                                   "password", "", ""));
  }

  // this test is very vague on how to write a stable test:
  //
  // on a slow box creating the TCP connection itself may be slow
  // which may make the test positive even though exec_time was not honoured.
  //
  // On the other side we can't compare the timespan against
  // a non-delayed connect as the external connect time depends
  // on what else happens on the system while the tests are running
  EXPECT_GT(std::chrono::steady_clock::now() - start_tp, kDelay);
}

/**
 * test mock-server's REST bridge denies unknown URLs.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 *
 * verifies:
 *
 * - WL12118
 *   - TS_1-7
 */
TEST_F(RestMockServerRestServerMockTest, unknown_url_fails) {
  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerInvalidRestUri;

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for HTTP server listening");
  ASSERT_NO_FATAL_FAILURE(check_port_ready(server_mock_, http_port_));

  SCOPED_TRACE("// make a http connections");
  auto req = rest_client.request_sync(HttpMethod::Get, http_uri);

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg() << std::endl;

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg()
      << std::endl;

  EXPECT_EQ(req.get_response_code(), 404u);
  EXPECT_THAT(req.get_input_headers().get("Content-Type"),
              ::testing::StrEq("text/html"));

  auto resp_body = req.get_input_buffer();
  EXPECT_GT(resp_body.length(), 0u);
  auto resp_body_content = resp_body.pop_front(resp_body.length());
}

/**
 * test storing globals in mock_server via REST bridge.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 */
TEST_F(RestMockServerRestServerMockTest, put_globals_no_json) {
  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  SCOPED_TRACE("// make a http connections");
  auto req = rest_client.request_sync(HttpMethod::Put, http_uri);

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg() << std::endl;

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 415u);

  auto resp_body = req.get_input_buffer();
  EXPECT_EQ(resp_body.length(), 0u);
}

/**
 * ensure PUT against / fails.
 *
 * verifies:
 *
 *   - WL12118
 *     - TS_1-10
 */
TEST_F(RestMockServerRestServerMockTest, put_root_fails) {
  const std::string http_hostname{"127.0.0.1"};

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(
      wait_for_rest_endpoint_ready(kMockServerGlobalsRestUri, http_port_));

  SCOPED_TRACE("// make a http connections");
  auto req = rest_client.request_sync(HttpMethod::Put, "/", "{}");

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 404u);

  auto resp_body = req.get_input_buffer();
  EXPECT_NE(resp_body.length(), 0u);
}

class RestMockServerRequireTest : public RestMockServerScriptTest {
 protected:
  RestMockServerRequireTest()
      : RestMockServerScriptTest("js_test_require.js") {}
};

class RestMockServerRequirePTest : public RestMockServerRequireTest,
                                   public ::testing::WithParamInterface<
                                       std::tuple<const char *, const char *>> {
};

/**
 * ensure require() honours load-order.
 *
 * verifies:
 *
 *   - WL11861
 *     - TS_1-8
 */
TEST_P(RestMockServerRequirePTest, require) {
  // mysql query
  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");
  ASSERT_NO_THROW(client.connect("127.0.0.1", server_port_, "username",
                                 "password", "", ""));

  EXPECT_NO_THROW({
    std::unique_ptr<mysqlrouter::MySQLSession::ResultRow> result{
        client.query_one(std::get<0>(GetParam()))};
    ASSERT_NE(nullptr, result.get());
    ASSERT_EQ(1u, result->size());
    EXPECT_EQ(std::string((*result)[0]), std::get<1>(GetParam()));
  });
}

INSTANTIATE_TEST_SUITE_P(
    js_require_paths, RestMockServerRequirePTest,
    ::testing::Values(std::make_tuple("direct", "direct"),
                      std::make_tuple("dir-with-indexjs", "dir-with-index.js"),
                      std::make_tuple("dir-with-packagejson",
                                      "dir-with-package.json")));

/**
 * ensure require() only loads and evaluates modules once.
 *
 * js_test_require.js requires the same module twice which exposes
 * a counter function.
 *
 * calling the counter via the first module, and via the 2nd module
 * should both increment the same counter if a module is only
 * loaded once.
 *
 * verifies:
 *
 *   - WL11861
 *     - TS_1-7
 */
TEST_F(RestMockServerRequireTest, no_reload) {
  SCOPED_TRACE("// connecting via mysql protocol");

  // mysql query
  mysqlrouter::MySQLSession client;

  ASSERT_NO_THROW(client.connect("127.0.0.1", server_port_, "username",
                                 "password", "", ""));

  SCOPED_TRACE("// via first module");
  EXPECT_NO_THROW({
    std::unique_ptr<mysqlrouter::MySQLSession::ResultRow> result{
        client.query_one("no-reload-0")};
    ASSERT_NE(nullptr, result.get());
    ASSERT_EQ(1u, result->size());
    EXPECT_EQ(std::string((*result)[0]), "0");
  });

  SCOPED_TRACE("// via 2nd module");
  EXPECT_NO_THROW({
    std::unique_ptr<mysqlrouter::MySQLSession::ResultRow> result{
        client.query_one("no-reload-1")};
    ASSERT_NE(nullptr, result.get());
    ASSERT_EQ(1u, result->size());
    EXPECT_EQ(std::string((*result)[0]), "1");
  });
}

class RestMockServerNestingTest : public RestMockServerScriptTest {
 protected:
  RestMockServerNestingTest()
      : RestMockServerScriptTest("js_test_nesting.js") {}
};

/**
 * ensure require() can be deeply nested.
 *
 *
 *
 * verifies:
 *
 *   - WL11861
 *     - TS_1-10
 */
TEST_F(RestMockServerNestingTest, nesting) {
  SCOPED_TRACE("// connecting via mysql protocol");

  // mysql query
  mysqlrouter::MySQLSession client;

  ASSERT_THROW_LIKE(
      client.connect("127.0.0.1", server_port_, "username", "password", "", ""),
      mysqlrouter::MySQLSession::Error,
      "test-require-nesting-5.js:5: SyntaxError: parse error");
}

class RestMockServerMethodsTest
    : public RestMockServerRestServerMockTest,
      public ::testing::WithParamInterface<
          std::tuple<unsigned int, std::string, unsigned int>> {};

/**
 * ensure OPTIONS, HEAD and others work.
 *
 * verifies:
 *
 *   - WL12118
 *     - TS_1-11
 */
TEST_P(RestMockServerMethodsTest, methods_avail) {
  const std::string http_hostname{"127.0.0.1"};

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  const std::string uri = std::get<1>(GetParam());

  SCOPED_TRACE("// wait for REST endpoint: " + uri);
  ASSERT_TRUE(wait_for_rest_endpoint_ready(uri, http_port_));

  SCOPED_TRACE("// make a http connections");
  auto req = rest_client.request_sync(std::get<0>(GetParam()), uri);

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(std::get<2>(GetParam()), req.get_response_code());
}

INSTANTIATE_TEST_SUITE_P(
    api__v1__mock_server__globals, RestMockServerMethodsTest,
    ::testing::Values(
        std::make_tuple(HttpMethod::Get, kMockServerGlobalsRestUri,
                        HttpStatusCode::Ok),
        std::make_tuple(HttpMethod::Put, kMockServerGlobalsRestUri,
                        HttpStatusCode::UnsupportedMediaType),
        std::make_tuple(HttpMethod::Delete, kMockServerGlobalsRestUri,
                        HttpStatusCode::MethodNotAllowed),
        std::make_tuple(HttpMethod::Trace, kMockServerGlobalsRestUri,
                        HttpStatusCode::MethodNotAllowed),
        std::make_tuple(HttpMethod::Options, kMockServerGlobalsRestUri,
                        HttpStatusCode::MethodNotAllowed),
        std::make_tuple(HttpMethod::Head, kMockServerGlobalsRestUri,
                        HttpStatusCode::MethodNotAllowed)));

INSTANTIATE_TEST_SUITE_P(
    api__v1__mock_server__connections, RestMockServerMethodsTest,
    ::testing::Values(
        std::make_tuple(HttpMethod::Get, kMockServerConnectionsRestUri,
                        HttpStatusCode::MethodNotAllowed),
        std::make_tuple(HttpMethod::Put, kMockServerConnectionsRestUri,
                        HttpStatusCode::MethodNotAllowed),
        std::make_tuple(HttpMethod::Delete, kMockServerConnectionsRestUri,
                        HttpStatusCode::Ok),
        std::make_tuple(HttpMethod::Trace, kMockServerConnectionsRestUri,
                        HttpStatusCode::MethodNotAllowed),
        std::make_tuple(HttpMethod::Options, kMockServerConnectionsRestUri,
                        HttpStatusCode::MethodNotAllowed),
        std::make_tuple(HttpMethod::Head, kMockServerConnectionsRestUri,
                        HttpStatusCode::MethodNotAllowed)),
    [](const auto &info) {
      return http_method_to_string(std::get<0>(info.param)) + "_" +
             std::to_string(std::get<2>(info.param));
    });

/**
 * test storing globals in mock_server via REST bridge.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 */
TEST_F(RestMockServerRestServerMockTest, put_globals_ok) {
  SCOPED_TRACE("// start mock-server with http-port");

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  SCOPED_TRACE("// make a http connections");
  auto req = rest_client.request_sync(HttpMethod::Put, http_uri, "{}");

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 204u);

  auto resp_body = req.get_input_buffer();
  EXPECT_EQ(resp_body.length(), 0u);
}

class RestMockServerRequestTest
    : public RestMockServerRestServerMockTest,
      public ::testing::WithParamInterface<
          std::tuple<int, const char *, const char *, unsigned int>> {};

/**
 * ensure valid and invalid JSON results in the correct behaviour.
 *
 * verifies:
 *
 * - WL12118
 *   - TS_1-8
 */
TEST_P(RestMockServerRequestTest, request) {
  SCOPED_TRACE("// start mock-server with http-port");

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  SCOPED_TRACE("// make a http connections");
  auto req =
      rest_client.request_sync(std::get<0>(GetParam()), std::get<1>(GetParam()),
                               std::get<2>(GetParam()));

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), std::get<3>(GetParam()));

  // if we executed a PUT against globals which was not meant to succeed,
  // check the globals are unchanged.
  if (std::get<0>(GetParam()) == HttpMethod::Put &&
      std::get<1>(GetParam()) == std::string(kMockServerGlobalsRestUri) &&
      std::get<3>(GetParam()) != HttpStatusCode::NoContent) {
    auto get_req = rest_client.request_sync(HttpMethod::Get, http_uri);
    SCOPED_TRACE("// checking GET response");
    ASSERT_TRUE(get_req) << "HTTP Request to " << http_hostname << ":"
                         << std::to_string(http_port_)
                         << " failed (early): " << get_req.error_msg();

    ASSERT_GT(get_req.get_response_code(), 0u)
        << "HTTP Request to " << http_hostname << ":"
        << std::to_string(http_port_) << " failed: " << get_req.error_msg();

    EXPECT_EQ(get_req.get_response_code(), 200u);
    EXPECT_THAT(get_req.get_input_headers().get("Content-Type"),
                ::testing::StrEq("application/json"));

    auto get_resp_body = get_req.get_input_buffer();
    EXPECT_GT(get_resp_body.length(), 0u);
    auto get_resp_body_content =
        get_resp_body.pop_front(get_resp_body.length());

    // parse json

    std::string json_payload(get_resp_body_content.begin(),
                             get_resp_body_content.end());

    JsonDocument json_doc;
    json_doc.Parse(json_payload.c_str());

    EXPECT_TRUE(!json_doc.HasParseError());
    EXPECT_THAT(json_payload, ::testing::StrEq("{}"));
  }
}

INSTANTIATE_TEST_SUITE_P(
    api__v1__mock_server__globals, RestMockServerRequestTest,
    ::testing::Values(
        // parse error
        std::make_tuple(HttpMethod::Put, kMockServerGlobalsRestUri, "[",
                        HttpStatusCode::UnprocessableEntity),

        // not an object
        std::make_tuple(HttpMethod::Put, kMockServerGlobalsRestUri, "[]",
                        HttpStatusCode::UnprocessableEntity),

        // parse-error
        std::make_tuple(HttpMethod::Put, kMockServerGlobalsRestUri, "{1}",
                        HttpStatusCode::UnprocessableEntity),

        // not-an-object
        std::make_tuple(HttpMethod::Put, kMockServerGlobalsRestUri, "1",
                        HttpStatusCode::UnprocessableEntity)));

/**
 * test storing globals in mock_server via REST bridge.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 *
 * verifies:
 *
 * - WL12118
 *   - TS_1-6
 *   - TS_1-9
 */
TEST_F(RestMockServerRestServerMockTest, put_globals_and_read_back) {
  SCOPED_TRACE("// start mock-server with http-port");

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;

  SCOPED_TRACE("// make a http connections");
  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  auto put_req = rest_client.request_sync(HttpMethod::Put, http_uri,
                                          "{\"key\": [ [1, 2, 3 ] ]}");

  SCOPED_TRACE("// checking PUT response");
  ASSERT_TRUE(put_req) << "HTTP Request to " << http_hostname << ":"
                       << std::to_string(http_port_)
                       << " failed (early): " << put_req.error_msg();

  ASSERT_GT(put_req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << put_req.error_msg();

  EXPECT_EQ(put_req.get_response_code(), 204u);

  auto put_resp_body = put_req.get_input_buffer();
  EXPECT_EQ(put_resp_body.length(), 0u);

  // GET request

  auto get_req = rest_client.request_sync(HttpMethod::Get, http_uri);
  SCOPED_TRACE("// checking GET response");
  ASSERT_TRUE(get_req) << "HTTP Request to " << http_hostname << ":"
                       << std::to_string(http_port_)
                       << " failed (early): " << get_req.error_msg();

  ASSERT_GT(get_req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << get_req.error_msg();

  EXPECT_EQ(get_req.get_response_code(), 200u);
  EXPECT_THAT(get_req.get_input_headers().get("Content-Type"),
              ::testing::StrEq("application/json"));

  auto get_resp_body = get_req.get_input_buffer();
  EXPECT_GT(get_resp_body.length(), 0u);
  auto get_resp_body_content = get_resp_body.pop_front(get_resp_body.length());

  // parse json

  std::string json_payload(get_resp_body_content.begin(),
                           get_resp_body_content.end());

  JsonDocument json_doc;
  json_doc.Parse(json_payload.c_str());

  EXPECT_TRUE(!json_doc.HasParseError());
  EXPECT_THAT(json_payload, ::testing::StrEq("{\"key\":[[1,2,3]]}"));
}

/**
 * test DELETE connections.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 *
 * verifies:
 *
 * - WL12118
 *   - TS_1-2
 */
TEST_F(RestMockServerRestServerMockTest, delete_all_connections) {
  SCOPED_TRACE("// start mock-server with http-port");

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerConnectionsRestUri;

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  // mysql query
  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");
  ASSERT_NO_THROW(client.connect("127.0.0.1", server_port_, "username",
                                 "password", "", ""));

  SCOPED_TRACE("// check connection works");
  std::unique_ptr<mysqlrouter::MySQLSession::ResultRow> result{
      client.query_one("select @@port")};
  ASSERT_NE(nullptr, result.get());
  ASSERT_EQ(1u, result->size());
  EXPECT_EQ(std::to_string(server_port_), std::string((*result)[0]));

  SCOPED_TRACE("// make a http connections");
  auto req = rest_client.request_sync(HttpMethod::Delete, http_uri, "{}");

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 200u);

  auto resp_body = req.get_input_buffer();
  EXPECT_EQ(resp_body.length(), 0u);

  SCOPED_TRACE("// check connection is killed");
  wait_connection_dropped(client);
}

TEST_F(RestMockServerRestServerMockTest, auth_succeeds_require_user_and_pass) {
  SCOPED_TRACE("// start mock-server with http-port");

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;
  std::string rest_username = "foobar";
  std::string rest_password = "somepass";
  std::string mysql_username = rest_username;
  std::string mysql_password = rest_password;

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  SCOPED_TRACE("// set username/password");
  auto req = rest_client.request_sync(HttpMethod::Put, http_uri,
                                      R"({"username": ")" + rest_username +
                                          R"(", "password": ")" +
                                          rest_password + R"("})");

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 204u);

  auto resp_body = req.get_input_buffer();
  EXPECT_EQ(resp_body.length(), 0u);

  // mysql query
  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");
  ASSERT_NO_THROW(client.connect("127.0.0.1", server_port_, mysql_username,
                                 mysql_password, "", ""));
}

TEST_F(RestMockServerRestServerMockTest, auth_succeeds_require_user) {
  SCOPED_TRACE("// start mock-server with http-port");

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;
  std::string rest_username = "foobar";
  std::string mysql_username = rest_username;
  std::string mysql_password = "somepass";

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  SCOPED_TRACE("// set username/password");
  auto req = rest_client.request_sync(
      HttpMethod::Put, http_uri, R"({"username": ")" + rest_username + R"("})");

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 204u);

  auto resp_body = req.get_input_buffer();
  EXPECT_EQ(resp_body.length(), 0u);

  // mysql query
  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");
  ASSERT_NO_THROW(client.connect("127.0.0.1", server_port_, mysql_username,
                                 mysql_password, "", ""));
}

TEST_F(RestMockServerRestServerMockTest, auth_fails_wrong_password) {
  SCOPED_TRACE("// start mock-server with http-port");

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;
  std::string rest_username = "foobar";
  std::string rest_password = "somepass";
  std::string mysql_username = rest_username;
  std::string mysql_password = "wrongpass";

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  SCOPED_TRACE("// set username/password");
  auto req = rest_client.request_sync(HttpMethod::Put, http_uri,
                                      R"({"username": ")" + rest_username +
                                          R"(", "password": ")" +
                                          rest_password + R"("})");

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 204u);

  // mysql query
  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");

  // wrong password should fail
  ASSERT_THROW(client.connect("127.0.0.1", server_port_, mysql_username,
                              mysql_password, "", ""),
               std::runtime_error);
}

/**
 * check authentication checks fails with empty password.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 *
 * Empty passwords have a different hashing scheme.
 */
TEST_F(RestMockServerRestServerMockTest, auth_fails_empty_password) {
  SCOPED_TRACE("// start mock-server with http-port");

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;
  std::string rest_username = "foobar";
  std::string rest_password = "somepass";
  std::string mysql_username = rest_username;
  std::string mysql_password = "";

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  SCOPED_TRACE("// set username/password");
  auto req = rest_client.request_sync(HttpMethod::Put, http_uri,
                                      R"({"username": ")" + rest_username +
                                          R"(", "password": ")" +
                                          rest_password + R"("})");

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 204u);

  auto resp_body = req.get_input_buffer();
  EXPECT_EQ(resp_body.length(), 0u);

  // mysql query
  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");

  // wrong password should fail
  ASSERT_THROW(client.connect("127.0.0.1", server_port_, mysql_username,
                              mysql_password, "", ""),
               std::runtime_error);
}

/**
 * check authentication checks fails with wrong username.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 */
TEST_F(RestMockServerRestServerMockTest, auth_fails_wrong_username) {
  SCOPED_TRACE("// start mock-server with http-port");

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;
  std::string rest_username = "foobar";
  std::string rest_password = "somepass";
  std::string mysql_username = "wronguser";
  std::string mysql_password = rest_password;

  IOContext io_ctx;
  RestClient rest_client(io_ctx, http_hostname, http_port_);

  SCOPED_TRACE("// wait for REST endpoint");
  ASSERT_TRUE(wait_for_rest_endpoint_ready(http_uri, http_port_));

  SCOPED_TRACE("// set username/password");
  auto req = rest_client.request_sync(HttpMethod::Put, http_uri,
                                      R"({"username": ")" + rest_username +
                                          R"(", "password": ")" +
                                          rest_password + R"("})");

  SCOPED_TRACE("// checking HTTP response");
  ASSERT_TRUE(req) << "HTTP Request to " << http_hostname << ":"
                   << std::to_string(http_port_)
                   << " failed (early): " << req.error_msg();

  ASSERT_GT(req.get_response_code(), 0u)
      << "HTTP Request to " << http_hostname << ":"
      << std::to_string(http_port_) << " failed: " << req.error_msg();

  EXPECT_EQ(req.get_response_code(), 204u);

  auto resp_body = req.get_input_buffer();
  EXPECT_EQ(resp_body.length(), 0u);

  // mysql query
  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");

  // wrong password should fail
  ASSERT_THROW(client.connect("127.0.0.1", server_port_, mysql_username,
                              mysql_password, "", ""),
               std::runtime_error);
}

/**
 * ensure @@port reported by mock is real port.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 */
TEST_F(RestMockServerRestServerMockTest, select_port) {
  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;

  // mysql query
  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");
  ASSERT_NO_THROW(client.connect("127.0.0.1", server_port_, "username",
                                 "password", "", ""));

  EXPECT_NO_THROW({
    std::unique_ptr<mysqlrouter::MySQLSession::ResultRow> result{
        client.query_one("select @@port")};
    ASSERT_NE(nullptr, result.get());
    ASSERT_EQ(1u, result->size());
    EXPECT_EQ(std::to_string(server_port_), std::string((*result)[0]));
  });
}

// make pretty param-names
static std::string sanitize_param_name(const std::string &name) {
  std::string p{name};
  for (auto &c : p) {
    if (!isalpha(c) && !isdigit(c)) c = '_';
  }
  return p;
}

/**
 * ensure connect returns error.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 */
TEST_P(RestMockServerConnectThrowsTest, js_test_stmts_is_string) {
  SCOPED_TRACE("// start mock-server with http-port");

  const auto server_port = port_pool_.get_next_available();
  const auto http_port = port_pool_.get_next_available();
  const std::string json_stmts =
      get_data_dir().join(std::get<0>(GetParam())).str();
  auto &server_mock = launch_mysql_server_mock(json_stmts, server_port,
                                               EXIT_SUCCESS, false, http_port);

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;

  ASSERT_NO_FATAL_FAILURE(check_port_ready(server_mock, server_port));

  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");
  ASSERT_THROW_LIKE(
      client.connect("127.0.0.1", server_port, "username", "password", "", ""),
      mysqlrouter::MySQLSession::Error, std::get<1>(GetParam()));
}

INSTANTIATE_TEST_SUITE_P(
    ScriptsFails, RestMockServerConnectThrowsTest,
    ::testing::Values(
        std::make_tuple("js_test_parse_error.js",
                        "parse error"),  // WL11861 TS-1_2
        std::make_tuple("js_test_stmts_is_string.js",
                        "expected 'stmts' to be"),  // WL11861 TS-1_4
        std::make_tuple("js_test_empty_file.js",
                        "expected statement handler to return an object, got "
                        "primitive, undefined"),  // WL11861 TS-1_4
        std::make_tuple("js_test_handshake_greeting_exec_time_is_empty.js",
                        "exec_time must be a number, if set. Is object"),
        std::make_tuple(
            "js_test_handshake_is_string.js",
            "handshake must be an object, if set. Is primitive, string")),
    [](const ::testing::TestParamInfo<std::tuple<const char *, const char *>>
           &info) -> std::string {
      return sanitize_param_name(std::get<0>(info.param));
    });

/**
 * ensure int fields in 'columns' can't be negative.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 * - run a query which triggers the server-side exception
 */
TEST_P(RestMockServerScriptsThrowsTest, scripts_throws) {
  SCOPED_TRACE("// start mock-server with http-port");

  const unsigned server_port = port_pool_.get_next_available();
  const unsigned http_port = port_pool_.get_next_available();
  const std::string json_stmts =
      get_data_dir().join(std::get<0>(GetParam())).str();
  auto &server_mock = launch_mysql_server_mock(json_stmts, server_port,
                                               EXIT_SUCCESS, false, http_port);

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;

  ASSERT_NO_FATAL_FAILURE(check_port_ready(server_mock, server_port));

  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");
  ASSERT_NO_THROW(
      client.connect("127.0.0.1", server_port, "username", "password", "", ""));

  SCOPED_TRACE("// select @@port");
  ASSERT_THROW_LIKE(client.query_one("select @@port"),
                    mysqlrouter::MySQLSession::Error, std::get<1>(GetParam()));
}

INSTANTIATE_TEST_SUITE_P(
    ScriptsFails, RestMockServerScriptsThrowsTest,
    ::testing::Values(
        std::make_tuple("js_test_stmts_result_has_negative_int.js",
                        "value out-of-range for field \"decimals\""),
        std::make_tuple(
            "js_test_stmts_result_has_infinity.js",
            "value out-of-range for field \"decimals\""),  // WL11861 TS-1_11
        std::make_tuple("js_test_stmts_result_has_repeat.js",
                        "repeat is not supported"),  // WL11861 TS-1_5
        std::make_tuple("js_test_stmts_is_empty.js",
                        "Unknown statement. (end of stmts)")),
    [](const ::testing::TestParamInfo<std::tuple<const char *, const char *>>
           &info) -> std::string {
      return sanitize_param_name(std::get<0>(info.param));
    });

/**
 * ensure script works.
 *
 * - start the mock-server
 * - make a client connect to the mock-server
 */
TEST_P(RestMockServerScriptsWorkTest, scripts_work) {
  SCOPED_TRACE("// start mock-server with http-port");

  const auto server_port = port_pool_.get_next_available();
  const auto http_port = port_pool_.get_next_available();
  const std::string json_stmts = get_data_dir().join(GetParam()).str();
  auto &server_mock = launch_mysql_server_mock(json_stmts, server_port,
                                               EXIT_SUCCESS, false, http_port);

  std::string http_hostname = "127.0.0.1";
  std::string http_uri = kMockServerGlobalsRestUri;

  ASSERT_NO_FATAL_FAILURE(check_port_ready(server_mock, server_port));

  mysqlrouter::MySQLSession client;

  SCOPED_TRACE("// connecting via mysql protocol");
  ASSERT_NO_THROW(
      client.connect("127.0.0.1", server_port, "username", "password", "", ""));

  SCOPED_TRACE("// select @@port");
  ASSERT_NO_THROW(client.execute("select @@port"));
}

INSTANTIATE_TEST_SUITE_P(
    ScriptsWork, RestMockServerScriptsWorkTest,
    ::testing::Values("simple-client.js", "js_test_handshake_is_empty.js",
                      "js_test_handshake_greeting_is_empty.js",
                      "js_test_handshake_greeting_exec_time_is_number.js",
                      "js_test_stmts_is_array.js",
                      "js_test_stmts_is_coroutine.js",
                      "js_test_stmts_is_function.js"),
    [](const ::testing::TestParamInfo<std::string> &info) -> std::string {
      return sanitize_param_name(info.param);
    });

static void init_DIM() {
  mysql_harness::DIM &dim = mysql_harness::DIM::instance();

  // logging facility
  dim.set_LoggingRegistry(
      []() {
        static mysql_harness::logging::Registry registry;
        return &registry;
      },
      [](mysql_harness::logging::Registry *) {}  // don't delete our static!
  );
  mysql_harness::logging::Registry &registry = dim.get_LoggingRegistry();

  mysql_harness::logging::create_module_loggers(
      registry, mysql_harness::logging::LogLevel::kWarning,
      {mysql_harness::logging::kMainLogger, "sql"},
      mysql_harness::logging::kMainLogger);
  mysql_harness::logging::create_main_log_handler(registry, "", "", true);

  registry.set_ready();
}

int main(int argc, char *argv[]) {
  init_windows_sockets();
  init_DIM();
  ProcessManager::set_origin(Path(argv[0]).dirname());
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}