Revert 285173 "Removed InProcessBrowserTest::CleanUpOnMainThread()"
[chromium-blink-merge.git] / chrome / browser / extensions / api / cast_channel / cast_socket_unittest.cc
blobd9e4aee5f49dbc0b3e828c00602002a071065b54
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/api/cast_channel/cast_socket.h"
7 #include "base/message_loop/message_loop.h"
8 #include "base/run_loop.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "base/sys_byteorder.h"
11 #include "chrome/browser/extensions/api/cast_channel/cast_channel.pb.h"
12 #include "chrome/browser/extensions/api/cast_channel/cast_message_util.h"
13 #include "net/base/address_list.h"
14 #include "net/base/capturing_net_log.h"
15 #include "net/base/net_errors.h"
16 #include "net/base/net_util.h"
17 #include "net/socket/socket_test_util.h"
18 #include "net/socket/ssl_client_socket.h"
19 #include "net/socket/tcp_client_socket.h"
20 #include "net/ssl/ssl_info.h"
21 #include "testing/gmock/include/gmock/gmock.h"
22 #include "testing/gtest/include/gtest/gtest.h"
24 using ::testing::_;
25 using ::testing::A;
26 using ::testing::DoAll;
27 using ::testing::Return;
28 using ::testing::SaveArg;
30 namespace {
31 const char* kTestData[4] = {
32 "Hello, World!",
33 "Goodbye, World!",
34 "Hello, Sky!",
35 "Goodbye, Volcano!",
37 } // namespace
39 namespace extensions {
40 namespace api {
41 namespace cast_channel {
43 // Fills in |message| with a string message.
44 static void CreateStringMessage(const std::string& namespace_,
45 const std::string& source_id,
46 const std::string& destination_id,
47 const std::string& data,
48 MessageInfo* message) {
49 message->namespace_ = namespace_;
50 message->source_id = source_id;
51 message->destination_id = destination_id;
52 message->data.reset(new base::StringValue(data));
55 // Fills in |message| with a binary message.
56 static void CreateBinaryMessage(const std::string& namespace_,
57 const std::string& source_id,
58 const std::string& destination_id,
59 const std::string& data,
60 MessageInfo* message) {
61 message->namespace_ = namespace_;
62 message->source_id = source_id;
63 message->destination_id = destination_id;
64 message->data.reset(base::BinaryValue::CreateWithCopiedBuffer(
65 data.c_str(), data.size()));
68 class MockCastSocketDelegate : public CastSocket::Delegate {
69 public:
70 MOCK_METHOD2(OnError, void(const CastSocket* socket,
71 ChannelError error));
72 MOCK_METHOD2(OnMessage, void(const CastSocket* socket,
73 const MessageInfo& message));
76 class MockTCPSocket : public net::TCPClientSocket {
77 public:
78 explicit MockTCPSocket(const net::MockConnect& connect_data) :
79 TCPClientSocket(net::AddressList(), NULL, net::NetLog::Source()),
80 connect_data_(connect_data) { }
82 virtual int Connect(const net::CompletionCallback& callback) OVERRIDE {
83 if (connect_data_.mode == net::ASYNC) {
84 CHECK_NE(connect_data_.result, net::ERR_IO_PENDING);
85 base::MessageLoop::current()->PostTask(
86 FROM_HERE,
87 base::Bind(callback, connect_data_.result));
88 return net::ERR_IO_PENDING;
89 } else {
90 return connect_data_.result;
94 virtual bool SetKeepAlive(bool enable, int delay) OVERRIDE {
95 // Always return true in tests
96 return true;
99 virtual bool SetNoDelay(bool no_delay) OVERRIDE {
100 // Always return true in tests
101 return true;
104 MOCK_METHOD3(Read,
105 int(net::IOBuffer*, int, const net::CompletionCallback&));
106 MOCK_METHOD3(Write,
107 int(net::IOBuffer*, int, const net::CompletionCallback&));
109 virtual void Disconnect() OVERRIDE {
110 // Do nothing in tests
113 private:
114 net::MockConnect connect_data_;
117 class CompleteHandler {
118 public:
119 CompleteHandler() {}
120 MOCK_METHOD1(OnCloseComplete, void(int result));
121 MOCK_METHOD1(OnConnectComplete, void(int result));
122 MOCK_METHOD1(OnWriteComplete, void(int result));
123 private:
124 DISALLOW_COPY_AND_ASSIGN(CompleteHandler);
127 class TestCastSocket : public CastSocket {
128 public:
129 static scoped_ptr<TestCastSocket> Create(
130 MockCastSocketDelegate* delegate) {
131 return scoped_ptr<TestCastSocket>(
132 new TestCastSocket(delegate, CreateIPEndPoint(),
133 CHANNEL_AUTH_TYPE_SSL));
136 static scoped_ptr<TestCastSocket> CreateSecure(
137 MockCastSocketDelegate* delegate) {
138 return scoped_ptr<TestCastSocket>(
139 new TestCastSocket(delegate, CreateIPEndPoint(),
140 CHANNEL_AUTH_TYPE_SSL_VERIFIED));
143 explicit TestCastSocket(MockCastSocketDelegate* delegate,
144 const net::IPEndPoint& ip_endpoint,
145 ChannelAuthType channel_auth) :
146 CastSocket("abcdefg", ip_endpoint, channel_auth, delegate,
147 &capturing_net_log_),
148 ip_(ip_endpoint),
149 connect_index_(0),
150 extract_cert_result_(true),
151 verify_challenge_result_(true) {
154 static net::IPEndPoint CreateIPEndPoint() {
155 net::IPAddressNumber number;
156 number.push_back(192);
157 number.push_back(0);
158 number.push_back(0);
159 number.push_back(1);
160 return net::IPEndPoint(number, 8009);
163 // Returns the size of the body (in bytes) of the given serialized message.
164 static size_t ComputeBodySize(const std::string& msg) {
165 return msg.length() - CastSocket::MessageHeader::header_size();
168 virtual ~TestCastSocket() {
171 // Helpers to set mock results for various operations.
172 void SetupTcp1Connect(net::IoMode mode, int result) {
173 tcp_connect_data_[0].reset(new net::MockConnect(mode, result));
175 void SetupSsl1Connect(net::IoMode mode, int result) {
176 ssl_connect_data_[0].reset(new net::MockConnect(mode, result));
178 void SetupTcp2Connect(net::IoMode mode, int result) {
179 tcp_connect_data_[1].reset(new net::MockConnect(mode, result));
181 void SetupSsl2Connect(net::IoMode mode, int result) {
182 ssl_connect_data_[1].reset(new net::MockConnect(mode, result));
184 void AddWriteResult(const net::MockWrite& write) {
185 writes_.push_back(write);
187 void AddWriteResult(net::IoMode mode, int result) {
188 AddWriteResult(net::MockWrite(mode, result));
190 void AddWriteResultForMessage(net::IoMode mode, const std::string& msg) {
191 AddWriteResult(mode, msg.size());
193 void AddWriteResultForMessage(net::IoMode mode,
194 const std::string& msg,
195 size_t ch_size) {
196 size_t msg_size = msg.size();
197 for (size_t offset = 0; offset < msg_size; offset += ch_size) {
198 if (offset + ch_size > msg_size)
199 ch_size = msg_size - offset;
200 AddWriteResult(mode, ch_size);
204 void AddReadResult(const net::MockRead& read) {
205 reads_.push_back(read);
207 void AddReadResult(net::IoMode mode, int result) {
208 AddReadResult(net::MockRead(mode, result));
210 void AddReadResult(net::IoMode mode, const char* data, int data_len) {
211 AddReadResult(net::MockRead(mode, data, data_len));
213 void AddReadResultForMessage(net::IoMode mode, const std::string& msg) {
214 size_t body_size = ComputeBodySize(msg);
215 const char* data = msg.c_str();
216 AddReadResult(mode, data, MessageHeader::header_size());
217 AddReadResult(mode, data + MessageHeader::header_size(), body_size);
219 void AddReadResultForMessage(net::IoMode mode,
220 const std::string& msg,
221 size_t ch_size) {
222 size_t msg_size = msg.size();
223 const char* data = msg.c_str();
224 for (size_t offset = 0; offset < msg_size; offset += ch_size) {
225 if (offset + ch_size > msg_size)
226 ch_size = msg_size - offset;
227 AddReadResult(mode, data + offset, ch_size);
231 void SetExtractCertResult(bool value) {
232 extract_cert_result_ = value;
234 void SetVerifyChallengeResult(bool value) {
235 verify_challenge_result_ = value;
238 private:
239 virtual scoped_ptr<net::TCPClientSocket> CreateTcpSocket() OVERRIDE {
240 net::MockConnect* connect_data = tcp_connect_data_[connect_index_].get();
241 connect_data->peer_addr = ip_;
242 return scoped_ptr<net::TCPClientSocket>(new MockTCPSocket(*connect_data));
245 virtual scoped_ptr<net::SSLClientSocket> CreateSslSocket(
246 scoped_ptr<net::StreamSocket> socket) OVERRIDE {
247 net::MockConnect* connect_data = ssl_connect_data_[connect_index_].get();
248 connect_data->peer_addr = ip_;
249 ++connect_index_;
251 ssl_data_.reset(new net::StaticSocketDataProvider(
252 reads_.data(), reads_.size(), writes_.data(), writes_.size()));
253 ssl_data_->set_connect_data(*connect_data);
254 // NOTE: net::MockTCPClientSocket inherits from net::SSLClientSocket !!
255 return scoped_ptr<net::SSLClientSocket>(
256 new net::MockTCPClientSocket(
257 net::AddressList(), &capturing_net_log_, ssl_data_.get()));
260 virtual bool ExtractPeerCert(std::string* cert) OVERRIDE {
261 if (extract_cert_result_)
262 cert->assign("dummy_test_cert");
263 return extract_cert_result_;
266 virtual bool VerifyChallengeReply() OVERRIDE {
267 return verify_challenge_result_;
270 net::CapturingNetLog capturing_net_log_;
271 net::IPEndPoint ip_;
272 // Simulated connect data
273 scoped_ptr<net::MockConnect> tcp_connect_data_[2];
274 scoped_ptr<net::MockConnect> ssl_connect_data_[2];
275 // Simulated read / write data
276 std::vector<net::MockWrite> writes_;
277 std::vector<net::MockRead> reads_;
278 scoped_ptr<net::SocketDataProvider> ssl_data_;
279 // Number of times Connect method is called
280 size_t connect_index_;
281 // Simulated result of peer cert extraction.
282 bool extract_cert_result_;
283 // Simulated result of verifying challenge reply.
284 bool verify_challenge_result_;
287 class CastSocketTest : public testing::Test {
288 public:
289 CastSocketTest() {}
290 virtual ~CastSocketTest() {}
292 virtual void SetUp() OVERRIDE {
293 // Create a few test messages
294 for (size_t i = 0; i < arraysize(test_messages_); i++) {
295 CreateStringMessage("urn:cast", "1", "2", kTestData[i],
296 &test_messages_[i]);
297 ASSERT_TRUE(MessageInfoToCastMessage(
298 test_messages_[i], &test_protos_[i]));
299 ASSERT_TRUE(CastSocket::Serialize(test_protos_[i], &test_proto_strs_[i]));
302 // Create a test auth request.
303 CastMessage request;
304 CreateAuthChallengeMessage(&request);
305 ASSERT_TRUE(CastSocket::Serialize(request, &auth_request_));
307 // Create a test auth reply.
308 MessageInfo reply;
309 CreateBinaryMessage("urn:x-cast:com.google.cast.tp.deviceauth",
310 "sender-0",
311 "receiver-0",
312 "abcd",
313 &reply);
314 CastMessage reply_msg;
315 ASSERT_TRUE(MessageInfoToCastMessage(reply, &reply_msg));
316 ASSERT_TRUE(CastSocket::Serialize(reply_msg, &auth_reply_));
319 virtual void TearDown() OVERRIDE {
320 EXPECT_CALL(handler_, OnCloseComplete(net::OK));
321 socket_->Close(base::Bind(&CompleteHandler::OnCloseComplete,
322 base::Unretained(&handler_)));
325 void CreateCastSocket() {
326 socket_ = TestCastSocket::Create(&mock_delegate_);
329 void CreateCastSocketSecure() {
330 socket_ = TestCastSocket::CreateSecure(&mock_delegate_);
333 // Sets up CastSocket::Connect to succeed.
334 // Connecting the socket also starts the read loop; so we add a mock
335 // read result that returns IO_PENDING and callback is never fired.
336 void ConnectHelper() {
337 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
338 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::OK);
339 socket_->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
341 EXPECT_CALL(handler_, OnConnectComplete(net::OK));
342 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
343 base::Unretained(&handler_)));
344 RunPendingTasks();
347 protected:
348 // Runs all pending tasks in the message loop.
349 void RunPendingTasks() {
350 base::RunLoop run_loop;
351 run_loop.RunUntilIdle();
354 base::MessageLoop message_loop_;
355 MockCastSocketDelegate mock_delegate_;
356 scoped_ptr<TestCastSocket> socket_;
357 CompleteHandler handler_;
358 MessageInfo test_messages_[arraysize(kTestData)];
359 CastMessage test_protos_[arraysize(kTestData)];
360 std::string test_proto_strs_[arraysize(kTestData)];
361 std::string auth_request_;
362 std::string auth_reply_;
365 // Tests connecting and closing the socket.
366 TEST_F(CastSocketTest, TestConnectAndClose) {
367 CreateCastSocket();
368 ConnectHelper();
369 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
370 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
372 EXPECT_CALL(handler_, OnCloseComplete(net::OK));
373 socket_->Close(base::Bind(&CompleteHandler::OnCloseComplete,
374 base::Unretained(&handler_)));
375 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
376 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
379 // Tests that the following connection flow works:
380 // - TCP connection succeeds (async)
381 // - SSL connection succeeds (async)
382 TEST_F(CastSocketTest, TestConnect) {
383 CreateCastSocket();
384 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
385 socket_->SetupSsl1Connect(net::ASYNC, net::OK);
386 socket_->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
388 EXPECT_CALL(handler_, OnConnectComplete(net::OK));
389 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
390 base::Unretained(&handler_)));
391 RunPendingTasks();
393 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
394 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
397 // Test that the following connection flow works:
398 // - TCP connection succeeds (async)
399 // - SSL connection fails with cert error (async)
400 // - Cert is extracted successfully
401 // - Second TCP connection succeeds (async)
402 // - Second SSL connection succeeds (async)
403 TEST_F(CastSocketTest, TestConnectTwoStep) {
404 CreateCastSocket();
405 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
406 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
407 socket_->SetupTcp2Connect(net::ASYNC, net::OK);
408 socket_->SetupSsl2Connect(net::ASYNC, net::OK);
409 socket_->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
411 EXPECT_CALL(handler_, OnConnectComplete(net::OK));
412 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
413 base::Unretained(&handler_)));
414 RunPendingTasks();
416 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
417 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
420 // Test that the following connection flow works:
421 // - TCP connection succeeds (async)
422 // - SSL connection fails with cert error (async)
423 // - Cert is extracted successfully
424 // - Second TCP connection succeeds (async)
425 // - Second SSL connection fails (async)
426 // - The flow should NOT be tried again
427 TEST_F(CastSocketTest, TestConnectMaxTwoAttempts) {
428 CreateCastSocket();
429 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
430 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
431 socket_->SetupTcp2Connect(net::ASYNC, net::OK);
432 socket_->SetupSsl2Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
434 EXPECT_CALL(handler_, OnConnectComplete(net::ERR_CERT_AUTHORITY_INVALID));
435 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
436 base::Unretained(&handler_)));
437 RunPendingTasks();
439 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
440 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
443 // Tests that the following connection flow works:
444 // - TCP connection succeeds (async)
445 // - SSL connection fails with cert error (async)
446 // - Cert is extracted successfully
447 // - Second TCP connection succeeds (async)
448 // - Second SSL connection succeeds (async)
449 // - Challenge request is sent (async)
450 // - Challenge response is received (async)
451 // - Credentials are verified successfuly
452 TEST_F(CastSocketTest, TestConnectFullSecureFlowAsync) {
453 CreateCastSocketSecure();
455 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
456 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
457 socket_->SetupTcp2Connect(net::ASYNC, net::OK);
458 socket_->SetupSsl2Connect(net::ASYNC, net::OK);
459 socket_->AddWriteResultForMessage(net::ASYNC, auth_request_);
460 socket_->AddReadResultForMessage(net::ASYNC, auth_reply_);
461 socket_->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
463 EXPECT_CALL(handler_, OnConnectComplete(net::OK));
464 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
465 base::Unretained(&handler_)));
466 RunPendingTasks();
468 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
469 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
472 // Same as TestFullSecureConnectionFlowAsync, but operations are synchronous.
473 TEST_F(CastSocketTest, TestConnectFullSecureFlowSync) {
474 CreateCastSocketSecure();
476 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
477 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::ERR_CERT_AUTHORITY_INVALID);
478 socket_->SetupTcp2Connect(net::SYNCHRONOUS, net::OK);
479 socket_->SetupSsl2Connect(net::SYNCHRONOUS, net::OK);
480 socket_->AddWriteResultForMessage(net::SYNCHRONOUS, auth_request_);
481 socket_->AddReadResultForMessage(net::SYNCHRONOUS, auth_reply_);
482 socket_->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
484 EXPECT_CALL(handler_, OnConnectComplete(net::OK));
485 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
486 base::Unretained(&handler_)));
487 RunPendingTasks();
489 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
490 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
493 // Test connection error - TCP connect fails (async)
494 TEST_F(CastSocketTest, TestConnectTcpConnectErrorAsync) {
495 CreateCastSocketSecure();
497 socket_->SetupTcp1Connect(net::ASYNC, net::ERR_FAILED);
499 EXPECT_CALL(handler_, OnConnectComplete(net::ERR_FAILED));
500 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
501 base::Unretained(&handler_)));
502 RunPendingTasks();
504 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
505 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
508 // Test connection error - TCP connect fails (sync)
509 TEST_F(CastSocketTest, TestConnectTcpConnectErrorSync) {
510 CreateCastSocketSecure();
512 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::ERR_FAILED);
514 EXPECT_CALL(handler_, OnConnectComplete(net::ERR_FAILED));
515 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
516 base::Unretained(&handler_)));
517 RunPendingTasks();
519 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
520 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
523 // Test connection error - SSL connect fails (async)
524 TEST_F(CastSocketTest, TestConnectSslConnectErrorAsync) {
525 CreateCastSocketSecure();
527 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
528 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::ERR_FAILED);
530 EXPECT_CALL(handler_, OnConnectComplete(net::ERR_FAILED));
531 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
532 base::Unretained(&handler_)));
533 RunPendingTasks();
535 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
536 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
539 // Test connection error - SSL connect fails (async)
540 TEST_F(CastSocketTest, TestConnectSslConnectErrorSync) {
541 CreateCastSocketSecure();
543 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
544 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_FAILED);
546 EXPECT_CALL(handler_, OnConnectComplete(net::ERR_FAILED));
547 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
548 base::Unretained(&handler_)));
549 RunPendingTasks();
551 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
552 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
555 // Test connection error - cert extraction error (async)
556 TEST_F(CastSocketTest, TestConnectCertExtractionErrorAsync) {
557 CreateCastSocket();
558 socket_->SetupTcp1Connect(net::ASYNC, net::OK);
559 socket_->SetupSsl1Connect(net::ASYNC, net::ERR_CERT_AUTHORITY_INVALID);
560 // Set cert extraction to fail
561 socket_->SetExtractCertResult(false);
563 EXPECT_CALL(handler_, OnConnectComplete(net::ERR_CERT_AUTHORITY_INVALID));
564 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
565 base::Unretained(&handler_)));
566 RunPendingTasks();
568 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
569 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
572 // Test connection error - cert extraction error (sync)
573 TEST_F(CastSocketTest, TestConnectCertExtractionErrorSync) {
574 CreateCastSocket();
575 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
576 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::ERR_CERT_AUTHORITY_INVALID);
577 // Set cert extraction to fail
578 socket_->SetExtractCertResult(false);
580 EXPECT_CALL(handler_, OnConnectComplete(net::ERR_CERT_AUTHORITY_INVALID));
581 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
582 base::Unretained(&handler_)));
583 RunPendingTasks();
585 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
586 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
589 // Test connection error - challenge send fails
590 TEST_F(CastSocketTest, TestConnectChallengeSendError) {
591 CreateCastSocketSecure();
593 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
594 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::OK);
595 socket_->AddWriteResult(net::SYNCHRONOUS, net::ERR_FAILED);
597 EXPECT_CALL(handler_, OnConnectComplete(net::ERR_FAILED));
598 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
599 base::Unretained(&handler_)));
600 RunPendingTasks();
602 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
603 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
606 // Test connection error - challenge reply receive fails
607 TEST_F(CastSocketTest, TestConnectChallengeReplyReceiveError) {
608 CreateCastSocketSecure();
610 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
611 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::OK);
612 socket_->AddWriteResultForMessage(net::ASYNC, auth_request_);
613 socket_->AddReadResult(net::SYNCHRONOUS, net::ERR_FAILED);
615 EXPECT_CALL(handler_, OnConnectComplete(net::ERR_FAILED));
616 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
617 base::Unretained(&handler_)));
618 RunPendingTasks();
620 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
621 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
624 // Test connection error - challenge reply verification fails
625 TEST_F(CastSocketTest, TestConnectChallengeVerificationFails) {
626 CreateCastSocketSecure();
628 socket_->SetupTcp1Connect(net::SYNCHRONOUS, net::OK);
629 socket_->SetupSsl1Connect(net::SYNCHRONOUS, net::OK);
630 socket_->AddWriteResultForMessage(net::ASYNC, auth_request_);
631 socket_->AddReadResultForMessage(net::ASYNC, auth_reply_);
632 socket_->AddReadResult(net::ASYNC, net::ERR_IO_PENDING);
633 socket_->SetVerifyChallengeResult(false);
635 EXPECT_CALL(handler_, OnConnectComplete(net::ERR_FAILED));
636 socket_->Connect(base::Bind(&CompleteHandler::OnConnectComplete,
637 base::Unretained(&handler_)));
638 RunPendingTasks();
640 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
641 EXPECT_EQ(cast_channel::CHANNEL_ERROR_CONNECT_ERROR, socket_->error_state());
644 // Test write success - single message (async)
645 TEST_F(CastSocketTest, TestWriteAsync) {
646 CreateCastSocket();
647 socket_->AddWriteResultForMessage(net::ASYNC, test_proto_strs_[0]);
648 ConnectHelper();
650 EXPECT_CALL(handler_, OnWriteComplete(test_proto_strs_[0].size()));
651 socket_->SendMessage(test_messages_[0],
652 base::Bind(&CompleteHandler::OnWriteComplete,
653 base::Unretained(&handler_)));
654 RunPendingTasks();
656 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
657 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
660 // Test write success - single message (sync)
661 TEST_F(CastSocketTest, TestWriteSync) {
662 CreateCastSocket();
663 socket_->AddWriteResultForMessage(net::SYNCHRONOUS, test_proto_strs_[0]);
664 ConnectHelper();
666 EXPECT_CALL(handler_, OnWriteComplete(test_proto_strs_[0].size()));
667 socket_->SendMessage(test_messages_[0],
668 base::Bind(&CompleteHandler::OnWriteComplete,
669 base::Unretained(&handler_)));
670 RunPendingTasks();
672 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
673 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
676 // Test write success - single message sent in multiple chunks (async)
677 TEST_F(CastSocketTest, TestWriteChunkedAsync) {
678 CreateCastSocket();
679 socket_->AddWriteResultForMessage(net::ASYNC, test_proto_strs_[0], 2);
680 ConnectHelper();
682 EXPECT_CALL(handler_, OnWriteComplete(test_proto_strs_[0].size()));
683 socket_->SendMessage(test_messages_[0],
684 base::Bind(&CompleteHandler::OnWriteComplete,
685 base::Unretained(&handler_)));
686 RunPendingTasks();
688 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
689 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
692 // Test write success - single message sent in multiple chunks (sync)
693 TEST_F(CastSocketTest, TestWriteChunkedSync) {
694 CreateCastSocket();
695 socket_->AddWriteResultForMessage(net::SYNCHRONOUS, test_proto_strs_[0], 2);
696 ConnectHelper();
698 EXPECT_CALL(handler_, OnWriteComplete(test_proto_strs_[0].size()));
699 socket_->SendMessage(test_messages_[0],
700 base::Bind(&CompleteHandler::OnWriteComplete,
701 base::Unretained(&handler_)));
702 RunPendingTasks();
704 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
705 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
708 // Test write success - multiple messages (async)
709 TEST_F(CastSocketTest, TestWriteManyAsync) {
710 CreateCastSocket();
711 for (size_t i = 0; i < arraysize(test_messages_); i++) {
712 size_t msg_size = test_proto_strs_[i].size();
713 socket_->AddWriteResult(net::ASYNC, msg_size);
714 EXPECT_CALL(handler_, OnWriteComplete(msg_size));
716 ConnectHelper();
718 for (size_t i = 0; i < arraysize(test_messages_); i++) {
719 socket_->SendMessage(test_messages_[i],
720 base::Bind(&CompleteHandler::OnWriteComplete,
721 base::Unretained(&handler_)));
723 RunPendingTasks();
725 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
726 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
729 // Test write success - multiple messages (sync)
730 TEST_F(CastSocketTest, TestWriteManySync) {
731 CreateCastSocket();
732 for (size_t i = 0; i < arraysize(test_messages_); i++) {
733 size_t msg_size = test_proto_strs_[i].size();
734 socket_->AddWriteResult(net::SYNCHRONOUS, msg_size);
735 EXPECT_CALL(handler_, OnWriteComplete(msg_size));
737 ConnectHelper();
739 for (size_t i = 0; i < arraysize(test_messages_); i++) {
740 socket_->SendMessage(test_messages_[i],
741 base::Bind(&CompleteHandler::OnWriteComplete,
742 base::Unretained(&handler_)));
744 RunPendingTasks();
746 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
747 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
750 // Test write error - not connected
751 TEST_F(CastSocketTest, TestWriteErrorNotConnected) {
752 CreateCastSocket();
754 EXPECT_CALL(handler_, OnWriteComplete(net::ERR_FAILED));
755 socket_->SendMessage(test_messages_[0],
756 base::Bind(&CompleteHandler::OnWriteComplete,
757 base::Unretained(&handler_)));
759 EXPECT_EQ(cast_channel::READY_STATE_NONE, socket_->ready_state());
760 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
763 // Test write error - very large message
764 TEST_F(CastSocketTest, TestWriteErrorLargeMessage) {
765 CreateCastSocket();
766 ConnectHelper();
768 EXPECT_CALL(handler_, OnWriteComplete(net::ERR_FAILED));
769 size_t size = CastSocket::MessageHeader::max_message_size() + 1;
770 test_messages_[0].data.reset(
771 new base::StringValue(std::string(size, 'a')));
772 socket_->SendMessage(test_messages_[0],
773 base::Bind(&CompleteHandler::OnWriteComplete,
774 base::Unretained(&handler_)));
776 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
777 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
781 // Test write error - network error (sync)
782 TEST_F(CastSocketTest, TestWriteNetworkErrorSync) {
783 CreateCastSocket();
784 socket_->AddWriteResult(net::SYNCHRONOUS, net::ERR_FAILED);
785 ConnectHelper();
787 EXPECT_CALL(handler_, OnWriteComplete(net::ERR_FAILED));
788 EXPECT_CALL(mock_delegate_,
789 OnError(socket_.get(), cast_channel::CHANNEL_ERROR_SOCKET_ERROR));
790 socket_->SendMessage(test_messages_[0],
791 base::Bind(&CompleteHandler::OnWriteComplete,
792 base::Unretained(&handler_)));
793 RunPendingTasks();
795 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
796 EXPECT_EQ(cast_channel::CHANNEL_ERROR_SOCKET_ERROR, socket_->error_state());
799 // Test write error - network error (async)
800 TEST_F(CastSocketTest, TestWriteErrorAsync) {
801 CreateCastSocket();
802 socket_->AddWriteResult(net::ASYNC, net::ERR_FAILED);
803 ConnectHelper();
805 EXPECT_CALL(handler_, OnWriteComplete(net::ERR_FAILED));
806 EXPECT_CALL(mock_delegate_,
807 OnError(socket_.get(), cast_channel::CHANNEL_ERROR_SOCKET_ERROR));
808 socket_->SendMessage(test_messages_[0],
809 base::Bind(&CompleteHandler::OnWriteComplete,
810 base::Unretained(&handler_)));
811 RunPendingTasks();
813 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
814 EXPECT_EQ(cast_channel::CHANNEL_ERROR_SOCKET_ERROR, socket_->error_state());
817 // Test write error - 0 bytes written should be considered an error
818 TEST_F(CastSocketTest, TestWriteErrorZeroBytesWritten) {
819 CreateCastSocket();
820 socket_->AddWriteResult(net::SYNCHRONOUS, 0);
821 ConnectHelper();
823 EXPECT_CALL(handler_, OnWriteComplete(net::ERR_FAILED));
824 EXPECT_CALL(mock_delegate_,
825 OnError(socket_.get(), cast_channel::CHANNEL_ERROR_SOCKET_ERROR));
826 socket_->SendMessage(test_messages_[0],
827 base::Bind(&CompleteHandler::OnWriteComplete,
828 base::Unretained(&handler_)));
829 RunPendingTasks();
831 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
832 EXPECT_EQ(cast_channel::CHANNEL_ERROR_SOCKET_ERROR, socket_->error_state());
835 // Test that when an error occurrs in one write, write callback is invoked for
836 // all pending writes with the error
837 TEST_F(CastSocketTest, TestWriteErrorWithMultiplePendingWritesAsync) {
838 CreateCastSocket();
839 socket_->AddWriteResult(net::ASYNC, net::ERR_SOCKET_NOT_CONNECTED);
840 ConnectHelper();
842 const int num_writes = arraysize(test_messages_);
843 EXPECT_CALL(handler_, OnWriteComplete(net::ERR_SOCKET_NOT_CONNECTED))
844 .Times(num_writes);
845 EXPECT_CALL(mock_delegate_,
846 OnError(socket_.get(), cast_channel::CHANNEL_ERROR_SOCKET_ERROR));
847 for (int i = 0; i < num_writes; i++) {
848 socket_->SendMessage(test_messages_[i],
849 base::Bind(&CompleteHandler::OnWriteComplete,
850 base::Unretained(&handler_)));
852 RunPendingTasks();
854 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
855 EXPECT_EQ(cast_channel::CHANNEL_ERROR_SOCKET_ERROR, socket_->error_state());
858 // Test read success - single message (async)
859 TEST_F(CastSocketTest, TestReadAsync) {
860 CreateCastSocket();
861 socket_->AddReadResultForMessage(net::ASYNC, test_proto_strs_[0]);
862 EXPECT_CALL(mock_delegate_,
863 OnMessage(socket_.get(), A<const MessageInfo&>()));
864 ConnectHelper();
866 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
867 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
870 // Test read success - single message (sync)
871 TEST_F(CastSocketTest, TestReadSync) {
872 CreateCastSocket();
873 socket_->AddReadResultForMessage(net::SYNCHRONOUS, test_proto_strs_[0]);
874 EXPECT_CALL(mock_delegate_,
875 OnMessage(socket_.get(), A<const MessageInfo&>()));
876 ConnectHelper();
878 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
879 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
882 // Test read success - single message received in multiple chunks (async)
883 TEST_F(CastSocketTest, TestReadChunkedAsync) {
884 CreateCastSocket();
885 socket_->AddReadResultForMessage(net::ASYNC, test_proto_strs_[0], 2);
886 EXPECT_CALL(mock_delegate_,
887 OnMessage(socket_.get(), A<const MessageInfo&>()));
888 ConnectHelper();
890 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
891 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
894 // Test read success - single message received in multiple chunks (sync)
895 TEST_F(CastSocketTest, TestReadChunkedSync) {
896 CreateCastSocket();
897 socket_->AddReadResultForMessage(net::SYNCHRONOUS, test_proto_strs_[0], 2);
898 EXPECT_CALL(mock_delegate_,
899 OnMessage(socket_.get(), A<const MessageInfo&>()));
900 ConnectHelper();
902 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
903 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
906 // Test read success - multiple messages (async)
907 TEST_F(CastSocketTest, TestReadManyAsync) {
908 CreateCastSocket();
909 size_t num_reads = arraysize(test_proto_strs_);
910 for (size_t i = 0; i < num_reads; i++)
911 socket_->AddReadResultForMessage(net::ASYNC, test_proto_strs_[i]);
912 EXPECT_CALL(mock_delegate_,
913 OnMessage(socket_.get(), A<const MessageInfo&>()))
914 .Times(num_reads);
915 ConnectHelper();
917 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
918 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
921 // Test read success - multiple messages (sync)
922 TEST_F(CastSocketTest, TestReadManySync) {
923 CreateCastSocket();
924 size_t num_reads = arraysize(test_proto_strs_);
925 for (size_t i = 0; i < num_reads; i++)
926 socket_->AddReadResultForMessage(net::SYNCHRONOUS, test_proto_strs_[i]);
927 EXPECT_CALL(mock_delegate_,
928 OnMessage(socket_.get(), A<const MessageInfo&>()))
929 .Times(num_reads);
930 ConnectHelper();
932 EXPECT_EQ(cast_channel::READY_STATE_OPEN, socket_->ready_state());
933 EXPECT_EQ(cast_channel::CHANNEL_ERROR_NONE, socket_->error_state());
936 // Test read error - network error (async)
937 TEST_F(CastSocketTest, TestReadErrorAsync) {
938 CreateCastSocket();
939 socket_->AddReadResult(net::ASYNC, net::ERR_SOCKET_NOT_CONNECTED);
940 EXPECT_CALL(mock_delegate_,
941 OnError(socket_.get(),
942 cast_channel::CHANNEL_ERROR_SOCKET_ERROR));
943 ConnectHelper();
945 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
946 EXPECT_EQ(cast_channel::CHANNEL_ERROR_SOCKET_ERROR, socket_->error_state());
949 // Test read error - network error (sync)
950 TEST_F(CastSocketTest, TestReadErrorSync) {
951 CreateCastSocket();
952 socket_->AddReadResult(net::SYNCHRONOUS, net::ERR_SOCKET_NOT_CONNECTED);
953 EXPECT_CALL(mock_delegate_,
954 OnError(socket_.get(),
955 cast_channel::CHANNEL_ERROR_SOCKET_ERROR));
956 ConnectHelper();
958 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
959 EXPECT_EQ(cast_channel::CHANNEL_ERROR_SOCKET_ERROR, socket_->error_state());
962 // Test read error - header parse error
963 TEST_F(CastSocketTest, TestReadHeaderParseError) {
964 CreateCastSocket();
965 uint32 body_size = base::HostToNet32(
966 CastSocket::MessageHeader::max_message_size() + 1);
967 // TODO(munjal): Add a method to cast_message_util.h to serialize messages
968 char header[sizeof(body_size)];
969 memcpy(&header, &body_size, arraysize(header));
970 socket_->AddReadResult(net::SYNCHRONOUS, header, arraysize(header));
971 EXPECT_CALL(mock_delegate_,
972 OnError(socket_.get(),
973 cast_channel::CHANNEL_ERROR_INVALID_MESSAGE));
974 ConnectHelper();
976 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
977 EXPECT_EQ(cast_channel::CHANNEL_ERROR_INVALID_MESSAGE,
978 socket_->error_state());
981 // Test read error - body parse error
982 TEST_F(CastSocketTest, TestReadBodyParseError) {
983 CreateCastSocket();
984 char body[] = "some body";
985 uint32 body_size = base::HostToNet32(arraysize(body));
986 char header[sizeof(body_size)];
987 memcpy(&header, &body_size, arraysize(header));
988 socket_->AddReadResult(net::SYNCHRONOUS, header, arraysize(header));
989 socket_->AddReadResult(net::SYNCHRONOUS, body, arraysize(body));
990 EXPECT_CALL(mock_delegate_,
991 OnError(socket_.get(),
992 cast_channel::CHANNEL_ERROR_INVALID_MESSAGE));
993 ConnectHelper();
995 EXPECT_EQ(cast_channel::READY_STATE_CLOSED, socket_->ready_state());
996 EXPECT_EQ(cast_channel::CHANNEL_ERROR_INVALID_MESSAGE,
997 socket_->error_state());
1000 } // namespace cast_channel
1001 } // namespace api
1002 } // namespace extensions