forked from bayandin/chromedriver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_handler_unittest.cc
1296 lines (1195 loc) · 52 KB
/
http_handler_unittest.cc
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
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/chromedriver/server/http_handler.h"
#include <memory>
#include <string>
#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/task_environment.h"
#include "base/threading/thread.h"
#include "base/values.h"
#include "chrome/test/chromedriver/chrome/status.h"
#include "chrome/test/chromedriver/command.h"
#include "chrome/test/chromedriver/server/http_server.h"
#include "net/http/http_status_code.h"
#include "net/server/http_server_request_info.h"
#include "net/server/http_server_response_info.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::ContainsRegex;
using testing::Eq;
using testing::Field;
using testing::Optional;
using testing::Pointee;
using testing::Property;
namespace {
void DummyCommand(const Status& status,
const base::Value::Dict& params,
const std::string& session_id,
const CommandCallback& callback) {
callback.Run(status, std::make_unique<base::Value>(1), "session_id", false);
}
void OnResponse(net::HttpServerResponseInfo* response_to_set,
std::unique_ptr<net::HttpServerResponseInfo> response) {
*response_to_set = *response;
}
template <int Code>
testing::AssertionResult StatusCodeIs(const Status& status) {
if (status.code() == Code) {
return testing::AssertionSuccess();
} else {
return testing::AssertionFailure() << status.message();
}
}
testing::AssertionResult StatusOk(const Status& status) {
return StatusCodeIs<kOk>(status);
}
std::string ToString(const base::Value::Dict& dict) {
std::string json;
EXPECT_TRUE(base::JSONWriter::Write(dict, &json));
return json;
}
class MockHttpServer : public virtual HttpServerInterface {
public:
MOCK_METHOD(void, Close, (int connection_id), (override));
MOCK_METHOD(void,
AcceptWebSocket,
(int connection_id, const net::HttpServerRequestInfo& request),
(override));
MOCK_METHOD(void,
SendOverWebSocket,
(int connection_id, const std::string& data),
(override));
MOCK_METHOD(void,
SendResponse,
(int connection_id,
const net::HttpServerResponseInfo& response,
const net::NetworkTrafficAnnotationTag& traffic_annotation),
(override));
};
} // namespace
TEST(HttpHandlerTest, HandleOutsideOfBaseUrl) {
HttpHandler handler("base/url/");
net::HttpServerRequestInfo request;
request.method = "get";
request.path = "base/path";
request.data = "body";
net::HttpServerResponseInfo response;
handler.Handle(request, base::BindRepeating(&OnResponse, &response));
ASSERT_EQ(net::HTTP_BAD_REQUEST, response.status_code());
}
TEST(HttpHandlerTest, HandleUnknownCommand) {
HttpHandler handler("/");
net::HttpServerRequestInfo request;
request.method = "get";
request.path = "/path";
net::HttpServerResponseInfo response;
handler.Handle(request, base::BindRepeating(&OnResponse, &response));
ASSERT_EQ(net::HTTP_NOT_FOUND, response.status_code());
}
TEST(HttpHandlerTest, HandleNewSession) {
HttpHandler handler("/base/");
handler.command_map_ = std::make_unique<HttpHandler::CommandMap>();
handler.command_map_->push_back(
CommandMapping(kPost, internal::kNewSessionPathPattern,
base::BindRepeating(&DummyCommand, Status(kOk))));
net::HttpServerRequestInfo request;
request.method = "post";
request.path = "/base/session";
request.data = "{}";
net::HttpServerResponseInfo response;
handler.Handle(request, base::BindRepeating(&OnResponse, &response));
ASSERT_EQ(net::HTTP_OK, response.status_code());
base::Value::Dict body;
body.Set("status", kOk);
body.Set("value", 1);
body.Set("sessionId", "session_id");
std::string json;
base::JSONWriter::Write(body, &json);
ASSERT_EQ(json, response.body());
}
TEST(HttpHandlerTest, HandleInvalidPost) {
HttpHandler handler("/");
handler.command_map_->push_back(CommandMapping(
kPost, "path", base::BindRepeating(&DummyCommand, Status(kOk))));
net::HttpServerRequestInfo request;
request.method = "post";
request.path = "/path";
request.data = "should be a dictionary";
net::HttpServerResponseInfo response;
handler.Handle(request, base::BindRepeating(&OnResponse, &response));
ASSERT_EQ(net::HTTP_BAD_REQUEST, response.status_code());
}
TEST(HttpHandlerTest, HandleUnimplementedCommand) {
HttpHandler handler("/");
handler.command_map_->push_back(CommandMapping(
kPost, "path",
base::BindRepeating(&DummyCommand, Status(kUnknownCommand))));
net::HttpServerRequestInfo request;
request.method = "post";
request.path = "/path";
request.data = "{}";
net::HttpServerResponseInfo response;
handler.Handle(request, base::BindRepeating(&OnResponse, &response));
ASSERT_EQ(net::HTTP_NOT_IMPLEMENTED, response.status_code());
}
TEST(HttpHandlerTest, HandleCommand) {
HttpHandler handler("/");
handler.command_map_->push_back(CommandMapping(
kPost, "path", base::BindRepeating(&DummyCommand, Status(kOk))));
net::HttpServerRequestInfo request;
request.method = "post";
request.path = "/path";
request.data = "{}";
net::HttpServerResponseInfo response;
handler.Handle(request, base::BindRepeating(&OnResponse, &response));
ASSERT_EQ(net::HTTP_OK, response.status_code());
base::Value::Dict body;
body.Set("status", kOk);
body.Set("value", 1);
body.Set("sessionId", "session_id");
std::string json;
base::JSONWriter::Write(body, &json);
ASSERT_EQ(json, response.body());
}
TEST(HttpHandlerTest, StandardResponse_ErrorNoMessage) {
HttpHandler handler("/");
Status status = Status(kUnexpectedAlertOpen);
ASSERT_NO_FATAL_FAILURE(handler.PrepareStandardResponse(
"not used", status, std::make_unique<base::Value>(), "1234"));
}
TEST(MatchesCommandTest, DiffMethod) {
CommandMapping command(kPost, "path",
base::BindRepeating(&DummyCommand, Status(kOk)));
std::string session_id;
base::Value::Dict params;
ASSERT_FALSE(internal::MatchesCommand(
"get", "path", command, &session_id, ¶ms));
ASSERT_TRUE(session_id.empty());
ASSERT_EQ(0u, params.size());
}
TEST(MatchesCommandTest, DiffPathLength) {
CommandMapping command(kPost, "path/path",
base::BindRepeating(&DummyCommand, Status(kOk)));
std::string session_id;
base::Value::Dict params;
ASSERT_FALSE(internal::MatchesCommand(
"post", "path", command, &session_id, ¶ms));
ASSERT_FALSE(internal::MatchesCommand(
"post", std::string(), command, &session_id, ¶ms));
ASSERT_FALSE(
internal::MatchesCommand("post", "/", command, &session_id, ¶ms));
ASSERT_FALSE(internal::MatchesCommand(
"post", "path/path/path", command, &session_id, ¶ms));
}
TEST(MatchesCommandTest, DiffPaths) {
CommandMapping command(kPost, "path/apath",
base::BindRepeating(&DummyCommand, Status(kOk)));
std::string session_id;
base::Value::Dict params;
ASSERT_FALSE(internal::MatchesCommand(
"post", "path/bpath", command, &session_id, ¶ms));
}
TEST(MatchesCommandTest, Substitution) {
CommandMapping command(kPost, "path/:sessionId/space/:a/:b",
base::BindRepeating(&DummyCommand, Status(kOk)));
std::string session_id;
base::Value::Dict params;
ASSERT_TRUE(internal::MatchesCommand(
"post", "path/1/space/2/3", command, &session_id, ¶ms));
ASSERT_EQ("1", session_id);
ASSERT_EQ(2u, params.size());
const std::string* param = params.FindString("a");
ASSERT_TRUE(param);
ASSERT_EQ("2", *param);
param = params.FindString("b");
ASSERT_TRUE(param);
ASSERT_EQ("3", *param);
}
TEST(MatchesCommandTest, DecodeEscape) {
CommandMapping command(kPost, "path/:sessionId/attribute/:xyz",
base::BindRepeating(&DummyCommand, Status(kOk)));
std::string session_id;
base::Value::Dict params;
ASSERT_TRUE(internal::MatchesCommand(
"post", "path/123/attribute/xyz%2Furl%7Ce%3A%40v",
command, &session_id, ¶ms));
const std::string* param = params.FindString("xyz");
ASSERT_TRUE(param);
ASSERT_EQ("xyz/url|e:@v", *param);
}
TEST(MatchesCommandTest, DecodePercent) {
CommandMapping command(kPost, "path/:xyz",
base::BindRepeating(&DummyCommand, Status(kOk)));
std::string session_id;
base::Value::Dict params;
ASSERT_TRUE(internal::MatchesCommand(
"post", "path/%40a%%b%%c%%%%", command, &session_id, ¶ms));
const std::string* param = params.FindString("xyz");
ASSERT_TRUE(param);
ASSERT_EQ("@a%b%c%%", *param);
}
TEST(ParseBidiCommandTest, WellFormed) {
std::string data =
"{\"id\": 12, \"method\": \"some\", \"params\":{\"one\": 2}}";
base::Value::Dict parsed;
EXPECT_TRUE(StatusOk(internal::ParseBidiCommand(data, parsed)));
EXPECT_THAT(parsed.FindInt("id"), Optional(Eq(12)));
EXPECT_THAT(parsed.FindString("method"), Pointee(Eq("some")));
base::Value::Dict* params = parsed.FindDict("params");
ASSERT_NE(nullptr, params);
ASSERT_THAT(params->FindInt("one"), Optional(Eq(2)));
}
TEST(ParseBidiCommandTest, MaxId) {
std::string data =
"{\"id\": 9007199254740991, \"method\": \"some\", \"params\":{}}";
base::Value::Dict parsed;
EXPECT_TRUE(StatusOk(internal::ParseBidiCommand(data, parsed)));
EXPECT_THAT(parsed.FindDouble("id"), Optional(Eq(9007199254740991L)));
EXPECT_THAT(parsed.FindString("method"), Pointee(Eq("some")));
EXPECT_NE(nullptr, parsed.FindDict("params"));
}
TEST(ParseBidiCommandTest, MalformedJson) {
std::string data =
"{\"id\": 9007199254740991, \"method\": \"some\", \"params\":{";
base::Value::Dict parsed;
Status status = internal::ParseBidiCommand(data, parsed);
EXPECT_EQ(kInvalidArgument, status.code());
EXPECT_THAT(status.message(), ContainsRegex("unable\\s+to\\s+parse"));
EXPECT_TRUE(parsed.empty());
}
TEST(ParseBidiCommandTest, NotDictionary) {
std::string data = "\"some string\"";
base::Value::Dict parsed;
Status status = internal::ParseBidiCommand(data, parsed);
EXPECT_EQ(kInvalidArgument, status.code());
EXPECT_THAT(status.message(), ContainsRegex("dictionary\\s+is\\s+expected"));
EXPECT_TRUE(parsed.empty());
}
TEST(ParseBidiCommandTest, NoId) {
std::string data = "{\"method\": \"some\", \"params\":{}}";
base::Value::Dict parsed;
Status status = internal::ParseBidiCommand(data, parsed);
EXPECT_EQ(kInvalidArgument, status.code());
EXPECT_THAT(status.message(), ContainsRegex("no\\s+'id'"));
}
TEST(ParseBidiCommandTest, WrongIdType) {
std::string data = "{\"id\": {}, \"method\": \"some\", \"params\":{}}";
base::Value::Dict parsed;
Status status = internal::ParseBidiCommand(data, parsed);
EXPECT_EQ(kInvalidArgument, status.code());
EXPECT_THAT(status.message(), ContainsRegex("no\\s+'id'"));
}
TEST(ParseBidiCommandTest, NoMethod) {
std::string data = "{\"id\": 625, \"params\":{}}";
base::Value::Dict parsed;
Status status = internal::ParseBidiCommand(data, parsed);
EXPECT_EQ(kInvalidArgument, status.code());
EXPECT_THAT(status.message(), ContainsRegex("no\\s+'method'"));
}
TEST(ParseBidiCommandTest, WrongMethodType) {
std::string data = "{\"id\": 4, \"method\": {}, \"params\":{}}";
base::Value::Dict parsed;
Status status = internal::ParseBidiCommand(data, parsed);
EXPECT_EQ(kInvalidArgument, status.code());
EXPECT_THAT(status.message(), ContainsRegex("no\\s+'method'"));
}
TEST(ParseBidiCommandTest, NoParams) {
std::string data = "{\"id\": 625, \"method\":\"some\"}";
base::Value::Dict parsed;
Status status = internal::ParseBidiCommand(data, parsed);
EXPECT_EQ(kInvalidArgument, status.code());
EXPECT_THAT(status.message(), ContainsRegex("no\\s+'params'"));
}
TEST(ParseBidiCommandTest, WrongParamsType) {
std::string data = "{\"id\": 4, \"method\": \"some\", \"params\": 5}";
base::Value::Dict parsed;
Status status = internal::ParseBidiCommand(data, parsed);
EXPECT_EQ(kInvalidArgument, status.code());
EXPECT_THAT(status.message(), ContainsRegex("no\\s+'params'"));
}
TEST(CreateBidiErrorResponse, WithId) {
Status error_status{kUnknownCommand, "this game has no name"};
base::Value::Dict response =
internal::CreateBidiErrorResponse(error_status, base::Value(121));
EXPECT_THAT(response.FindString("type"), Pointee(Eq("error")));
EXPECT_THAT(response.FindInt("id"), Optional(Eq(121)));
EXPECT_THAT(response.FindString("error"), Pointee(Eq("unknown command")));
EXPECT_THAT(response.FindString("message"),
Pointee(ContainsRegex("this game has no name")));
EXPECT_EQ(nullptr, response.Find("dropped_key"));
}
TEST(CreateBidiErrorResponse, NoId) {
Status error_status{kUnknownCommand, "this game has no name"};
base::Value::Dict response = internal::CreateBidiErrorResponse(error_status);
EXPECT_THAT(response.FindString("type"), Pointee(Eq("error")));
EXPECT_THAT(response.FindInt("id"), Eq(std::nullopt));
EXPECT_THAT(response.FindString("error"), Pointee(Eq("unknown command")));
EXPECT_THAT(response.FindString("message"),
Pointee(ContainsRegex("this game has no name")));
}
class WebSocketMessageTest : public testing::Test {
public:
void Echo(const base::Value::Dict& params,
const std::string& session_id,
const CommandCallback& callback) {
base::Value::Dict response = params.Clone();
response.Set("is_response", true);
callback.Run(Status{kOk},
std::make_unique<base::Value>(std::move(response)), session_id,
true);
}
Command EchoClosure() {
return base::BindRepeating(&WebSocketMessageTest::Echo,
base::Unretained(this));
}
Command FailClosure(StatusCode code, const std::string& message) {
return base::BindRepeating(
[](StatusCode code, std::string message,
const base::Value::Dict& params, const std::string& session_id,
const CommandCallback& callback) {
callback.Run(Status{code, message}, nullptr, session_id, true);
},
code, message);
}
Command SuccessNoResultClosure() {
return base::BindRepeating([](const base::Value::Dict& params,
const std::string& session_id,
const CommandCallback& callback) {
callback.Run(Status{kOk}, nullptr, session_id, true);
});
}
Command SuccessEmptyResultClosure() {
return base::BindRepeating([](const base::Value::Dict& params,
const std::string& session_id,
const CommandCallback& callback) {
callback.Run(Status{kOk},
std::make_unique<base::Value>(base::Value::Type::DICT),
session_id, true);
});
}
Command SessionCreatedClosure(std::string session_id) {
return base::BindRepeating(
[](std::string created_session_id, const base::Value::Dict& params,
const std::string& session_id, const CommandCallback& callback) {
callback.Run(Status{kOk},
std::make_unique<base::Value>(base::Value::Type::DICT),
created_session_id, true);
},
std::move(session_id));
}
protected:
void SetUp() override {
handler = std::make_unique<HttpHandler>("/");
handler->io_task_runner_ = task_environment.GetMainThreadTaskRunner();
handler->cmd_task_runner_ = task_environment.GetMainThreadTaskRunner();
}
void TearDown() override { handler.reset(); }
// Register connection in HttpHandler
// If session_id is omitted the connection is registered as unbound.
void AddConnection(int connection_id, const std::string& session_id = "") {
handler->connection_session_map_.insert(
std::make_pair(connection_id, session_id));
handler->session_connection_map_[session_id].push_back(connection_id);
}
void AddStaticCommand(std::string name, Command command) {
handler->static_bidi_command_map_.emplace(std::move(name),
std::move(command));
}
void AddSessionCommand(std::string name, Command command) {
handler->session_bidi_command_map_.emplace(std::move(name),
std::move(command));
}
void SetForwardingCommand(Command command) {
handler->forward_session_command_ = std::move(command);
}
base::test::SingleThreadTaskEnvironment task_environment;
std::unique_ptr<HttpHandler> handler;
};
TEST_F(WebSocketMessageTest, UnknownSessionNoId) {
// Verify that the unknow session error is handled first.
base::RunLoop run_loop;
MockHttpServer http_server;
Status expected_error{kInvalidSessionId, "session not found"};
std::string expected_response =
ToString(internal::CreateBidiErrorResponse(expected_error));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(1), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 1, "not used");
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, UnknownSessionNoIdIsPostedToIO) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
handler->OnWebSocketMessage(&http_server, 1, "not used");
}
TEST_F(WebSocketMessageTest, UnknownSessionWithId) {
// Verify that the unknow session error is handled first.
// The response must contain the id of the corresponding command.
base::RunLoop run_loop;
MockHttpServer http_server;
Status expected_error{kInvalidSessionId, "session not found"};
std::string expected_response = ToString(
internal::CreateBidiErrorResponse(expected_error, base::Value(15)));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(3), Eq(expected_response)));
std::string incoming = "{\"method\": \"some\", \"id\": 15, \"params\": {}}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, UnknownSessionWithIdIsPostedToIO) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
std::string incoming = "{\"method\": \"some\", \"id\": 15, \"params\": {}}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, SessionCommandWithIdUnboundConnection) {
// Well formed session command arriving over an unbound connection must be
// handled with "invalid session id" error.
base::RunLoop run_loop;
MockHttpServer http_server;
Status expected_error{kInvalidSessionId, "session not found"};
std::string expected_response = ToString(
internal::CreateBidiErrorResponse(expected_error, base::Value(15)));
// The connection is unbound
AddConnection(3);
EXPECT_CALL(http_server, SendOverWebSocket(Eq(3), Eq(expected_response)));
std::string incoming =
"{\"method\": \"script.evaluate\", \"id\": 15, \"params\": {}}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, SessionCommandWithIdPostedToIOUnboundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3);
std::string incoming =
"{\"method\": \"script.evaluate\", \"id\": 15, \"params\": {}}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, SessionCommandNoIdUnboundConnection) {
// Verify that missing "id" is checked before connection affinity with any
// session.
base::RunLoop run_loop;
MockHttpServer http_server;
std::string incoming = "{\"method\": \"script.evaluate\", \"params\": {}}";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
// missing "id" is an "invalid argument" error
EXPECT_EQ(kInvalidArgument, expected_error.code());
std::string expected_response =
ToString(internal::CreateBidiErrorResponse(expected_error));
AddConnection(3);
EXPECT_CALL(http_server, SendOverWebSocket(Eq(3), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 3, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, SessionCommandNoIdPostedToIOUnboundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3);
std::string incoming = "{\"method\": \"script.evaluate\", \"params\": {}}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, SessionCommandNoIdBoundConnection) {
// Verify that the missing command "id" is treated as an error.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(4, "some_session");
std::string incoming = "{\"method\": \"script.evaluate\", \"params\": {}}";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
EXPECT_EQ(kInvalidArgument, expected_error.code());
std::string expected_response =
ToString(internal::CreateBidiErrorResponse(expected_error));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(4), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 4, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, SessionCommandNoIdPostedToIOBoundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3, "some_session");
std::string incoming = "{\"method\": \"script.evaluate\", \"params\": {}}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, NoMethodUnboundConnection) {
// Verify that the missing "method" is treated as an error.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(5);
std::string incoming = "{\"id\": 61, \"params\": {}}";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
EXPECT_EQ(kInvalidArgument, expected_error.code());
std::string expected_response = ToString(
internal::CreateBidiErrorResponse(expected_error, base::Value(61)));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(5), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 5, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, NoMethodPostedToIOUnboundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3);
std::string incoming = "{\"id\": 61, \"params\": {}}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, NoMethodBoundConnection) {
// Verify that the missing "method" is treated as an error.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(5, "some_session");
std::string incoming = "{\"id\": 61, \"params\": {}}";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
EXPECT_EQ(kInvalidArgument, expected_error.code());
std::string expected_response = ToString(
internal::CreateBidiErrorResponse(expected_error, base::Value(61)));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(5), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 5, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, NoMethodPostedToIOBoundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3, "some_session");
std::string incoming = "{\"id\": 61, \"params\": {}}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, SessionCommandNoParamsUnboundConnection) {
// Verify that the missing command params are treated as an error.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(6);
std::string incoming = "{\"method\": \"script.evaluate\", \"id\": 18}";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
EXPECT_EQ(kInvalidArgument, expected_error.code());
std::string expected_response = ToString(
internal::CreateBidiErrorResponse(expected_error, base::Value(18)));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(6), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 6, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest,
SessionCommandNoParamsPostedToIOUnboundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3);
std::string incoming = "{\"method\": \"script.evaluate\", \"id\": 18}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, SessionCommandNoParamsBoundConnection) {
// Verify that the missing command params are treated as an error.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(6, "some_session");
std::string incoming = "{\"method\": \"script.evaluate\", \"id\": 18}";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
EXPECT_EQ(kInvalidArgument, expected_error.code());
std::string expected_response = ToString(
internal::CreateBidiErrorResponse(expected_error, base::Value(18)));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(6), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 6, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, SessionCommandNoParamsPostedToIOBoundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3, "some_session");
std::string incoming = "{\"method\": \"script.evaluate\", \"id\": 18}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, MalformedJson) {
// Verify that the malformed JSON is treated as an error.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(6, "some_session");
std::string incoming = "}{";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
EXPECT_TRUE(expected_error.IsError());
std::string expected_response =
ToString(internal::CreateBidiErrorResponse(expected_error));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(6), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 6, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, MalformedJsonPostedToIO) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(6, "some_session");
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
// The message contains no id, no method and no params
handler->OnWebSocketMessage(&http_server, 6, "}{");
}
TEST_F(WebSocketMessageTest, UnknownCommandUnboundConnection) {
// Verify that any unknown static command is treated as an error.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(7);
std::string incoming =
"{\"method\": \"abracadabra\", \"id\": 19, \"params\": {}}";
Status expected_error = {kUnknownCommand, "abracadabra"};
std::string expected_response = ToString(
internal::CreateBidiErrorResponse(expected_error, base::Value(19)));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(7), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 7, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, UnknownCommandIsPostedToIOUnboundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(7);
std::string incoming =
"{\"method\": \"abracadabra\", \"id\": 19, \"params\": {}}";
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
handler->OnWebSocketMessage(&http_server, 7, incoming);
}
TEST_F(WebSocketMessageTest, UnknownCommandBoundConnection) {
// Verify that any unknown command is forwarded to BiDiMapper in the case if
// the connection is bound to a BiDi session.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(7, "some_session");
std::string incoming =
"{\"method\": \"abracadabra\", \"id\": 19, \"params\": {}}";
bool invoked = false;
SetForwardingCommand(base::BindRepeating(
[](bool* invoked, const base::Value::Dict& params,
const std::string& session_id, const CommandCallback&) {
*invoked = true;
EXPECT_EQ("some_session", session_id);
EXPECT_EQ(7, params.FindDouble("connectionId").value_or(-1));
EXPECT_THAT(params.FindStringByDottedPath("bidiCommand.method"),
Pointee(Eq("abracadabra")));
EXPECT_THAT(params.FindDoubleByDottedPath("bidiCommand.id"),
Optional(Eq(19)));
},
base::Unretained(&invoked)));
handler->OnWebSocketMessage(&http_server, 7, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
EXPECT_TRUE(invoked);
}
TEST_F(WebSocketMessageTest, StaticCommandNoIdUnboundConnection) {
// Verify that missing "id" is checked before static command invocation
base::RunLoop run_loop;
AddStaticCommand("echo", EchoClosure());
std::string incoming = "{\"method\": \"echo\", \"params\": {}}";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
// missing "id" is an "invalid argument" error
EXPECT_EQ(kInvalidArgument, expected_error.code());
std::string expected_response =
ToString(internal::CreateBidiErrorResponse(expected_error));
AddConnection(3);
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(Eq(3), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 3, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, StaticCommandNoIdPostedToIOUnboundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
AddStaticCommand("echo", EchoClosure());
std::string incoming = "{\"method\": \"echo\", \"params\": {}}";
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3);
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, StaticCommandNoIdBoundConnection) {
// Verify that missing "id" is checked before static command invocation
base::RunLoop run_loop;
AddStaticCommand("echo", EchoClosure());
std::string incoming = "{\"method\": \"echo\", \"params\": {}}";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
// missing "id" is an "invalid argument" error
EXPECT_EQ(kInvalidArgument, expected_error.code());
std::string expected_response =
ToString(internal::CreateBidiErrorResponse(expected_error));
AddConnection(3, "some_session");
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(Eq(3), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 3, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, StaticCommandNoIdPostedToBoundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
AddStaticCommand("echo", EchoClosure());
std::string incoming = "{\"method\": \"echo\", \"params\": {}}";
MockHttpServer http_server;
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3, "some_session");
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, StaticCommandNoParamsUnboundConnection) {
// Verify that the missing command params are treated as an error.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(6);
AddStaticCommand("echo", EchoClosure());
std::string incoming = "{\"method\": \"echo\", \"id\": 18}";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
EXPECT_EQ(kInvalidArgument, expected_error.code());
std::string expected_response = ToString(
internal::CreateBidiErrorResponse(expected_error, base::Value(18)));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(6), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 6, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, StaticCommandNoParamsPostedToIOUnboundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(6);
AddStaticCommand("echo", EchoClosure());
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3);
std::string incoming = "{\"method\": \"echo\", \"id\": 18}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, StaticCommandNoParamsBoundConnection) {
// Verify that the missing command params are treated as an error.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(6, "some_session");
AddStaticCommand("echo", EchoClosure());
std::string incoming = "{\"method\": \"echo\", \"id\": 18}";
base::Value::Dict parsed;
Status expected_error = internal::ParseBidiCommand(incoming, parsed);
EXPECT_EQ(kInvalidArgument, expected_error.code());
std::string expected_response = ToString(
internal::CreateBidiErrorResponse(expected_error, base::Value(18)));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(6), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 6, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, StaticCommandNoParamsPostedToIOBoundConnection) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(3, "some_session");
AddStaticCommand("echo", EchoClosure());
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
AddConnection(3, "some_session");
std::string incoming = "{\"method\": \"echo\", \"id\": 18}";
handler->OnWebSocketMessage(&http_server, 3, incoming);
}
TEST_F(WebSocketMessageTest, KnownStaticCommandReturnsSuccess) {
// Verify that the response from a successful static command is sent over the
// web socket.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(8);
AddStaticCommand("echo", EchoClosure());
std::string incoming =
"{\"method\": \"echo\", \"id\": 20, \"params\": {\"a\": 1}}";
base::Value::Dict expected_response;
base::Value::Dict parsed;
EXPECT_TRUE(StatusOk(internal::ParseBidiCommand(incoming, parsed)));
parsed.Set("is_response", true);
expected_response.Set("type", "success");
expected_response.Set("id", parsed.FindInt("id").value_or(-1));
expected_response.Set("result", std::move(parsed));
std::string expected_response_message = ToString(expected_response);
EXPECT_CALL(http_server,
SendOverWebSocket(Eq(8), Eq(expected_response_message)));
handler->OnWebSocketMessage(&http_server, 8, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, KnownStaticCommandReturnsError) {
// Verify that the error message from a failed static command is sent over the
// web socket.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(9);
AddStaticCommand("fail",
FailClosure(kInvalidSelector, "this game has no name"));
std::string incoming =
"{\"method\": \"fail\", \"id\": 21, \"params\": {\"a\": 1}}";
Status expected_error = Status{kInvalidSelector, "this game has no name"};
std::string expected_response = ToString(
internal::CreateBidiErrorResponse(expected_error, base::Value(21)));
EXPECT_CALL(http_server, SendOverWebSocket(Eq(9), Eq(expected_response)));
handler->OnWebSocketMessage(&http_server, 9, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, KnownStaticCommandResponseIsPostedToIO) {
// Verify that the response is properly posted to the IO thread.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(8);
AddStaticCommand("echo", EchoClosure());
std::string incoming =
"{\"method\": \"echo\", \"id\": 20, \"params\": {\"a\": 1}}";
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
handler->OnWebSocketMessage(&http_server, 8, incoming);
}
TEST_F(WebSocketMessageTest, SessionCommandReturnsSuccess) {
// Verify that the response from a successful session command is sent over
// the web socket.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(8, "some_session");
SetForwardingCommand(SuccessNoResultClosure());
std::string incoming =
"{\"method\": \"echo\", \"id\": 20, \"params\": {\"a\": 1}}";
EXPECT_CALL(http_server, SendOverWebSocket(_, _)).Times(0);
handler->OnWebSocketMessage(&http_server, 8, incoming);
task_environment.GetMainThreadTaskRunner()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
TEST_F(WebSocketMessageTest, SessionCommandNoReturnValue) {
// Verify that no response is sent to the user if the session command was
// forwarded to BiDiMapper.
base::RunLoop run_loop;
MockHttpServer http_server;
AddConnection(8, "some_session");