Ignore non-active fullscreen windows for shelf state.
[chromium-blink-merge.git] / net / socket / transport_client_socket_pool_unittest.cc
blobff85847979b692231b4b6558722ab78f47136cdc
1 // Copyright (c) 2012 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 "net/socket/transport_client_socket_pool.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/callback.h"
10 #include "base/compiler_specific.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/threading/platform_thread.h"
14 #include "net/base/capturing_net_log.h"
15 #include "net/base/ip_endpoint.h"
16 #include "net/base/load_timing_info.h"
17 #include "net/base/load_timing_info_test_util.h"
18 #include "net/base/net_errors.h"
19 #include "net/base/net_util.h"
20 #include "net/base/test_completion_callback.h"
21 #include "net/dns/mock_host_resolver.h"
22 #include "net/socket/client_socket_factory.h"
23 #include "net/socket/client_socket_handle.h"
24 #include "net/socket/client_socket_pool_histograms.h"
25 #include "net/socket/socket_test_util.h"
26 #include "net/socket/ssl_client_socket.h"
27 #include "net/socket/stream_socket.h"
28 #include "testing/gtest/include/gtest/gtest.h"
30 namespace net {
32 using internal::ClientSocketPoolBaseHelper;
34 namespace {
36 const int kMaxSockets = 32;
37 const int kMaxSocketsPerGroup = 6;
38 const net::RequestPriority kDefaultPriority = LOW;
40 // Make sure |handle| sets load times correctly when it has been assigned a
41 // reused socket.
42 void TestLoadTimingInfoConnectedReused(const ClientSocketHandle& handle) {
43 LoadTimingInfo load_timing_info;
44 // Only pass true in as |is_reused|, as in general, HttpStream types should
45 // have stricter concepts of reuse than socket pools.
46 EXPECT_TRUE(handle.GetLoadTimingInfo(true, &load_timing_info));
48 EXPECT_TRUE(load_timing_info.socket_reused);
49 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
51 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
52 ExpectLoadTimingHasOnlyConnectionTimes(load_timing_info);
55 // Make sure |handle| sets load times correctly when it has been assigned a
56 // fresh socket. Also runs TestLoadTimingInfoConnectedReused, since the owner
57 // of a connection where |is_reused| is false may consider the connection
58 // reused.
59 void TestLoadTimingInfoConnectedNotReused(const ClientSocketHandle& handle) {
60 EXPECT_FALSE(handle.is_reused());
62 LoadTimingInfo load_timing_info;
63 EXPECT_TRUE(handle.GetLoadTimingInfo(false, &load_timing_info));
65 EXPECT_FALSE(load_timing_info.socket_reused);
66 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
68 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
69 CONNECT_TIMING_HAS_DNS_TIMES);
70 ExpectLoadTimingHasOnlyConnectionTimes(load_timing_info);
72 TestLoadTimingInfoConnectedReused(handle);
75 void SetIPv4Address(IPEndPoint* address) {
76 IPAddressNumber number;
77 CHECK(ParseIPLiteralToNumber("1.1.1.1", &number));
78 *address = IPEndPoint(number, 80);
81 void SetIPv6Address(IPEndPoint* address) {
82 IPAddressNumber number;
83 CHECK(ParseIPLiteralToNumber("1:abcd::3:4:ff", &number));
84 *address = IPEndPoint(number, 80);
87 class MockClientSocket : public StreamSocket {
88 public:
89 MockClientSocket(const AddressList& addrlist, net::NetLog* net_log)
90 : connected_(false),
91 addrlist_(addrlist),
92 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_SOCKET)) {
95 // StreamSocket implementation.
96 virtual int Connect(const CompletionCallback& callback) OVERRIDE {
97 connected_ = true;
98 return OK;
100 virtual void Disconnect() OVERRIDE {
101 connected_ = false;
103 virtual bool IsConnected() const OVERRIDE {
104 return connected_;
106 virtual bool IsConnectedAndIdle() const OVERRIDE {
107 return connected_;
109 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE {
110 return ERR_UNEXPECTED;
112 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE {
113 if (!connected_)
114 return ERR_SOCKET_NOT_CONNECTED;
115 if (addrlist_.front().GetFamily() == ADDRESS_FAMILY_IPV4)
116 SetIPv4Address(address);
117 else
118 SetIPv6Address(address);
119 return OK;
121 virtual const BoundNetLog& NetLog() const OVERRIDE {
122 return net_log_;
125 virtual void SetSubresourceSpeculation() OVERRIDE {}
126 virtual void SetOmniboxSpeculation() OVERRIDE {}
127 virtual bool WasEverUsed() const OVERRIDE { return false; }
128 virtual bool UsingTCPFastOpen() const OVERRIDE { return false; }
129 virtual bool WasNpnNegotiated() const OVERRIDE {
130 return false;
132 virtual NextProto GetNegotiatedProtocol() const OVERRIDE {
133 return kProtoUnknown;
135 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE {
136 return false;
139 // Socket implementation.
140 virtual int Read(IOBuffer* buf, int buf_len,
141 const CompletionCallback& callback) OVERRIDE {
142 return ERR_FAILED;
144 virtual int Write(IOBuffer* buf, int buf_len,
145 const CompletionCallback& callback) OVERRIDE {
146 return ERR_FAILED;
148 virtual bool SetReceiveBufferSize(int32 size) OVERRIDE { return true; }
149 virtual bool SetSendBufferSize(int32 size) OVERRIDE { return true; }
151 private:
152 bool connected_;
153 const AddressList addrlist_;
154 BoundNetLog net_log_;
156 DISALLOW_COPY_AND_ASSIGN(MockClientSocket);
159 class MockFailingClientSocket : public StreamSocket {
160 public:
161 MockFailingClientSocket(const AddressList& addrlist, net::NetLog* net_log)
162 : addrlist_(addrlist),
163 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_SOCKET)) {
166 // StreamSocket implementation.
167 virtual int Connect(const CompletionCallback& callback) OVERRIDE {
168 return ERR_CONNECTION_FAILED;
171 virtual void Disconnect() OVERRIDE {}
173 virtual bool IsConnected() const OVERRIDE {
174 return false;
176 virtual bool IsConnectedAndIdle() const OVERRIDE {
177 return false;
179 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE {
180 return ERR_UNEXPECTED;
182 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE {
183 return ERR_UNEXPECTED;
185 virtual const BoundNetLog& NetLog() const OVERRIDE {
186 return net_log_;
189 virtual void SetSubresourceSpeculation() OVERRIDE {}
190 virtual void SetOmniboxSpeculation() OVERRIDE {}
191 virtual bool WasEverUsed() const OVERRIDE { return false; }
192 virtual bool UsingTCPFastOpen() const OVERRIDE { return false; }
193 virtual bool WasNpnNegotiated() const OVERRIDE {
194 return false;
196 virtual NextProto GetNegotiatedProtocol() const OVERRIDE {
197 return kProtoUnknown;
199 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE {
200 return false;
203 // Socket implementation.
204 virtual int Read(IOBuffer* buf, int buf_len,
205 const CompletionCallback& callback) OVERRIDE {
206 return ERR_FAILED;
209 virtual int Write(IOBuffer* buf, int buf_len,
210 const CompletionCallback& callback) OVERRIDE {
211 return ERR_FAILED;
213 virtual bool SetReceiveBufferSize(int32 size) OVERRIDE { return true; }
214 virtual bool SetSendBufferSize(int32 size) OVERRIDE { return true; }
216 private:
217 const AddressList addrlist_;
218 BoundNetLog net_log_;
220 DISALLOW_COPY_AND_ASSIGN(MockFailingClientSocket);
223 class MockPendingClientSocket : public StreamSocket {
224 public:
225 // |should_connect| indicates whether the socket should successfully complete
226 // or fail.
227 // |should_stall| indicates that this socket should never connect.
228 // |delay_ms| is the delay, in milliseconds, before simulating a connect.
229 MockPendingClientSocket(
230 const AddressList& addrlist,
231 bool should_connect,
232 bool should_stall,
233 base::TimeDelta delay,
234 net::NetLog* net_log)
235 : should_connect_(should_connect),
236 should_stall_(should_stall),
237 delay_(delay),
238 is_connected_(false),
239 addrlist_(addrlist),
240 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_SOCKET)),
241 weak_factory_(this) {
244 // StreamSocket implementation.
245 virtual int Connect(const CompletionCallback& callback) OVERRIDE {
246 base::MessageLoop::current()->PostDelayedTask(
247 FROM_HERE,
248 base::Bind(&MockPendingClientSocket::DoCallback,
249 weak_factory_.GetWeakPtr(), callback),
250 delay_);
251 return ERR_IO_PENDING;
254 virtual void Disconnect() OVERRIDE {}
256 virtual bool IsConnected() const OVERRIDE {
257 return is_connected_;
259 virtual bool IsConnectedAndIdle() const OVERRIDE {
260 return is_connected_;
262 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE {
263 return ERR_UNEXPECTED;
265 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE {
266 if (!is_connected_)
267 return ERR_SOCKET_NOT_CONNECTED;
268 if (addrlist_.front().GetFamily() == ADDRESS_FAMILY_IPV4)
269 SetIPv4Address(address);
270 else
271 SetIPv6Address(address);
272 return OK;
274 virtual const BoundNetLog& NetLog() const OVERRIDE {
275 return net_log_;
278 virtual void SetSubresourceSpeculation() OVERRIDE {}
279 virtual void SetOmniboxSpeculation() OVERRIDE {}
280 virtual bool WasEverUsed() const OVERRIDE { return false; }
281 virtual bool UsingTCPFastOpen() const OVERRIDE { return false; }
282 virtual bool WasNpnNegotiated() const OVERRIDE {
283 return false;
285 virtual NextProto GetNegotiatedProtocol() const OVERRIDE {
286 return kProtoUnknown;
288 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE {
289 return false;
292 // Socket implementation.
293 virtual int Read(IOBuffer* buf, int buf_len,
294 const CompletionCallback& callback) OVERRIDE {
295 return ERR_FAILED;
298 virtual int Write(IOBuffer* buf, int buf_len,
299 const CompletionCallback& callback) OVERRIDE {
300 return ERR_FAILED;
302 virtual bool SetReceiveBufferSize(int32 size) OVERRIDE { return true; }
303 virtual bool SetSendBufferSize(int32 size) OVERRIDE { return true; }
305 private:
306 void DoCallback(const CompletionCallback& callback) {
307 if (should_stall_)
308 return;
310 if (should_connect_) {
311 is_connected_ = true;
312 callback.Run(OK);
313 } else {
314 is_connected_ = false;
315 callback.Run(ERR_CONNECTION_FAILED);
319 bool should_connect_;
320 bool should_stall_;
321 base::TimeDelta delay_;
322 bool is_connected_;
323 const AddressList addrlist_;
324 BoundNetLog net_log_;
326 base::WeakPtrFactory<MockPendingClientSocket> weak_factory_;
328 DISALLOW_COPY_AND_ASSIGN(MockPendingClientSocket);
331 class MockClientSocketFactory : public ClientSocketFactory {
332 public:
333 enum ClientSocketType {
334 MOCK_CLIENT_SOCKET,
335 MOCK_FAILING_CLIENT_SOCKET,
336 MOCK_PENDING_CLIENT_SOCKET,
337 MOCK_PENDING_FAILING_CLIENT_SOCKET,
338 // A delayed socket will pause before connecting through the message loop.
339 MOCK_DELAYED_CLIENT_SOCKET,
340 // A stalled socket that never connects at all.
341 MOCK_STALLED_CLIENT_SOCKET,
344 explicit MockClientSocketFactory(NetLog* net_log)
345 : net_log_(net_log), allocation_count_(0),
346 client_socket_type_(MOCK_CLIENT_SOCKET), client_socket_types_(NULL),
347 client_socket_index_(0), client_socket_index_max_(0),
348 delay_(base::TimeDelta::FromMilliseconds(
349 ClientSocketPool::kMaxConnectRetryIntervalMs)) {}
351 virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
352 DatagramSocket::BindType bind_type,
353 const RandIntCallback& rand_int_cb,
354 NetLog* net_log,
355 const NetLog::Source& source) OVERRIDE {
356 NOTREACHED();
357 return scoped_ptr<DatagramClientSocket>();
360 virtual scoped_ptr<StreamSocket> CreateTransportClientSocket(
361 const AddressList& addresses,
362 NetLog* /* net_log */,
363 const NetLog::Source& /* source */) OVERRIDE {
364 allocation_count_++;
366 ClientSocketType type = client_socket_type_;
367 if (client_socket_types_ &&
368 client_socket_index_ < client_socket_index_max_) {
369 type = client_socket_types_[client_socket_index_++];
372 switch (type) {
373 case MOCK_CLIENT_SOCKET:
374 return scoped_ptr<StreamSocket>(
375 new MockClientSocket(addresses, net_log_));
376 case MOCK_FAILING_CLIENT_SOCKET:
377 return scoped_ptr<StreamSocket>(
378 new MockFailingClientSocket(addresses, net_log_));
379 case MOCK_PENDING_CLIENT_SOCKET:
380 return scoped_ptr<StreamSocket>(
381 new MockPendingClientSocket(
382 addresses, true, false, base::TimeDelta(), net_log_));
383 case MOCK_PENDING_FAILING_CLIENT_SOCKET:
384 return scoped_ptr<StreamSocket>(
385 new MockPendingClientSocket(
386 addresses, false, false, base::TimeDelta(), net_log_));
387 case MOCK_DELAYED_CLIENT_SOCKET:
388 return scoped_ptr<StreamSocket>(
389 new MockPendingClientSocket(
390 addresses, true, false, delay_, net_log_));
391 case MOCK_STALLED_CLIENT_SOCKET:
392 return scoped_ptr<StreamSocket>(
393 new MockPendingClientSocket(
394 addresses, true, true, base::TimeDelta(), net_log_));
395 default:
396 NOTREACHED();
397 return scoped_ptr<StreamSocket>(
398 new MockClientSocket(addresses, net_log_));
402 virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
403 scoped_ptr<ClientSocketHandle> transport_socket,
404 const HostPortPair& host_and_port,
405 const SSLConfig& ssl_config,
406 const SSLClientSocketContext& context) OVERRIDE {
407 NOTIMPLEMENTED();
408 return scoped_ptr<SSLClientSocket>();
411 virtual void ClearSSLSessionCache() OVERRIDE {
412 NOTIMPLEMENTED();
415 int allocation_count() const { return allocation_count_; }
417 // Set the default ClientSocketType.
418 void set_client_socket_type(ClientSocketType type) {
419 client_socket_type_ = type;
422 // Set a list of ClientSocketTypes to be used.
423 void set_client_socket_types(ClientSocketType* type_list, int num_types) {
424 DCHECK_GT(num_types, 0);
425 client_socket_types_ = type_list;
426 client_socket_index_ = 0;
427 client_socket_index_max_ = num_types;
430 void set_delay(base::TimeDelta delay) { delay_ = delay; }
432 private:
433 NetLog* net_log_;
434 int allocation_count_;
435 ClientSocketType client_socket_type_;
436 ClientSocketType* client_socket_types_;
437 int client_socket_index_;
438 int client_socket_index_max_;
439 base::TimeDelta delay_;
441 DISALLOW_COPY_AND_ASSIGN(MockClientSocketFactory);
444 class TransportClientSocketPoolTest : public testing::Test {
445 protected:
446 TransportClientSocketPoolTest()
447 : connect_backup_jobs_enabled_(
448 ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(true)),
449 params_(
450 new TransportSocketParams(HostPortPair("www.google.com", 80),
451 false, false,
452 OnHostResolutionCallback())),
453 histograms_(new ClientSocketPoolHistograms("TCPUnitTest")),
454 host_resolver_(new MockHostResolver),
455 client_socket_factory_(&net_log_),
456 pool_(kMaxSockets,
457 kMaxSocketsPerGroup,
458 histograms_.get(),
459 host_resolver_.get(),
460 &client_socket_factory_,
461 NULL) {
464 virtual ~TransportClientSocketPoolTest() {
465 internal::ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(
466 connect_backup_jobs_enabled_);
469 int StartRequest(const std::string& group_name, RequestPriority priority) {
470 scoped_refptr<TransportSocketParams> params(new TransportSocketParams(
471 HostPortPair("www.google.com", 80), false, false,
472 OnHostResolutionCallback()));
473 return test_base_.StartRequestUsingPool(
474 &pool_, group_name, priority, params);
477 int GetOrderOfRequest(size_t index) {
478 return test_base_.GetOrderOfRequest(index);
481 bool ReleaseOneConnection(ClientSocketPoolTest::KeepAlive keep_alive) {
482 return test_base_.ReleaseOneConnection(keep_alive);
485 void ReleaseAllConnections(ClientSocketPoolTest::KeepAlive keep_alive) {
486 test_base_.ReleaseAllConnections(keep_alive);
489 ScopedVector<TestSocketRequest>* requests() { return test_base_.requests(); }
490 size_t completion_count() const { return test_base_.completion_count(); }
492 bool connect_backup_jobs_enabled_;
493 CapturingNetLog net_log_;
494 scoped_refptr<TransportSocketParams> params_;
495 scoped_ptr<ClientSocketPoolHistograms> histograms_;
496 scoped_ptr<MockHostResolver> host_resolver_;
497 MockClientSocketFactory client_socket_factory_;
498 TransportClientSocketPool pool_;
499 ClientSocketPoolTest test_base_;
501 DISALLOW_COPY_AND_ASSIGN(TransportClientSocketPoolTest);
504 TEST(TransportConnectJobTest, MakeAddrListStartWithIPv4) {
505 IPAddressNumber ip_number;
506 ASSERT_TRUE(ParseIPLiteralToNumber("192.168.1.1", &ip_number));
507 IPEndPoint addrlist_v4_1(ip_number, 80);
508 ASSERT_TRUE(ParseIPLiteralToNumber("192.168.1.2", &ip_number));
509 IPEndPoint addrlist_v4_2(ip_number, 80);
510 ASSERT_TRUE(ParseIPLiteralToNumber("2001:4860:b006::64", &ip_number));
511 IPEndPoint addrlist_v6_1(ip_number, 80);
512 ASSERT_TRUE(ParseIPLiteralToNumber("2001:4860:b006::66", &ip_number));
513 IPEndPoint addrlist_v6_2(ip_number, 80);
515 AddressList addrlist;
517 // Test 1: IPv4 only. Expect no change.
518 addrlist.clear();
519 addrlist.push_back(addrlist_v4_1);
520 addrlist.push_back(addrlist_v4_2);
521 TransportConnectJob::MakeAddressListStartWithIPv4(&addrlist);
522 ASSERT_EQ(2u, addrlist.size());
523 EXPECT_EQ(ADDRESS_FAMILY_IPV4, addrlist[0].GetFamily());
524 EXPECT_EQ(ADDRESS_FAMILY_IPV4, addrlist[1].GetFamily());
526 // Test 2: IPv6 only. Expect no change.
527 addrlist.clear();
528 addrlist.push_back(addrlist_v6_1);
529 addrlist.push_back(addrlist_v6_2);
530 TransportConnectJob::MakeAddressListStartWithIPv4(&addrlist);
531 ASSERT_EQ(2u, addrlist.size());
532 EXPECT_EQ(ADDRESS_FAMILY_IPV6, addrlist[0].GetFamily());
533 EXPECT_EQ(ADDRESS_FAMILY_IPV6, addrlist[1].GetFamily());
535 // Test 3: IPv4 then IPv6. Expect no change.
536 addrlist.clear();
537 addrlist.push_back(addrlist_v4_1);
538 addrlist.push_back(addrlist_v4_2);
539 addrlist.push_back(addrlist_v6_1);
540 addrlist.push_back(addrlist_v6_2);
541 TransportConnectJob::MakeAddressListStartWithIPv4(&addrlist);
542 ASSERT_EQ(4u, addrlist.size());
543 EXPECT_EQ(ADDRESS_FAMILY_IPV4, addrlist[0].GetFamily());
544 EXPECT_EQ(ADDRESS_FAMILY_IPV4, addrlist[1].GetFamily());
545 EXPECT_EQ(ADDRESS_FAMILY_IPV6, addrlist[2].GetFamily());
546 EXPECT_EQ(ADDRESS_FAMILY_IPV6, addrlist[3].GetFamily());
548 // Test 4: IPv6, IPv4, IPv6, IPv4. Expect first IPv6 moved to the end.
549 addrlist.clear();
550 addrlist.push_back(addrlist_v6_1);
551 addrlist.push_back(addrlist_v4_1);
552 addrlist.push_back(addrlist_v6_2);
553 addrlist.push_back(addrlist_v4_2);
554 TransportConnectJob::MakeAddressListStartWithIPv4(&addrlist);
555 ASSERT_EQ(4u, addrlist.size());
556 EXPECT_EQ(ADDRESS_FAMILY_IPV4, addrlist[0].GetFamily());
557 EXPECT_EQ(ADDRESS_FAMILY_IPV6, addrlist[1].GetFamily());
558 EXPECT_EQ(ADDRESS_FAMILY_IPV4, addrlist[2].GetFamily());
559 EXPECT_EQ(ADDRESS_FAMILY_IPV6, addrlist[3].GetFamily());
561 // Test 5: IPv6, IPv6, IPv4, IPv4. Expect first two IPv6's moved to the end.
562 addrlist.clear();
563 addrlist.push_back(addrlist_v6_1);
564 addrlist.push_back(addrlist_v6_2);
565 addrlist.push_back(addrlist_v4_1);
566 addrlist.push_back(addrlist_v4_2);
567 TransportConnectJob::MakeAddressListStartWithIPv4(&addrlist);
568 ASSERT_EQ(4u, addrlist.size());
569 EXPECT_EQ(ADDRESS_FAMILY_IPV4, addrlist[0].GetFamily());
570 EXPECT_EQ(ADDRESS_FAMILY_IPV4, addrlist[1].GetFamily());
571 EXPECT_EQ(ADDRESS_FAMILY_IPV6, addrlist[2].GetFamily());
572 EXPECT_EQ(ADDRESS_FAMILY_IPV6, addrlist[3].GetFamily());
575 TEST_F(TransportClientSocketPoolTest, Basic) {
576 TestCompletionCallback callback;
577 ClientSocketHandle handle;
578 int rv = handle.Init("a", params_, LOW, callback.callback(), &pool_,
579 BoundNetLog());
580 EXPECT_EQ(ERR_IO_PENDING, rv);
581 EXPECT_FALSE(handle.is_initialized());
582 EXPECT_FALSE(handle.socket());
584 EXPECT_EQ(OK, callback.WaitForResult());
585 EXPECT_TRUE(handle.is_initialized());
586 EXPECT_TRUE(handle.socket());
587 TestLoadTimingInfoConnectedNotReused(handle);
590 // Make sure that TransportConnectJob passes on its priority to its
591 // HostResolver request on Init.
592 TEST_F(TransportClientSocketPoolTest, SetResolvePriorityOnInit) {
593 for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
594 RequestPriority priority = static_cast<RequestPriority>(i);
595 TestCompletionCallback callback;
596 ClientSocketHandle handle;
597 EXPECT_EQ(ERR_IO_PENDING,
598 handle.Init("a", params_, priority, callback.callback(), &pool_,
599 BoundNetLog()));
600 EXPECT_EQ(priority, host_resolver_->last_request_priority());
604 TEST_F(TransportClientSocketPoolTest, InitHostResolutionFailure) {
605 host_resolver_->rules()->AddSimulatedFailure("unresolvable.host.name");
606 TestCompletionCallback callback;
607 ClientSocketHandle handle;
608 HostPortPair host_port_pair("unresolvable.host.name", 80);
609 scoped_refptr<TransportSocketParams> dest(new TransportSocketParams(
610 host_port_pair, false, false,
611 OnHostResolutionCallback()));
612 EXPECT_EQ(ERR_IO_PENDING,
613 handle.Init("a", dest, kDefaultPriority, callback.callback(),
614 &pool_, BoundNetLog()));
615 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, callback.WaitForResult());
618 TEST_F(TransportClientSocketPoolTest, InitConnectionFailure) {
619 client_socket_factory_.set_client_socket_type(
620 MockClientSocketFactory::MOCK_FAILING_CLIENT_SOCKET);
621 TestCompletionCallback callback;
622 ClientSocketHandle handle;
623 EXPECT_EQ(ERR_IO_PENDING,
624 handle.Init("a", params_, kDefaultPriority, callback.callback(),
625 &pool_, BoundNetLog()));
626 EXPECT_EQ(ERR_CONNECTION_FAILED, callback.WaitForResult());
628 // Make the host resolutions complete synchronously this time.
629 host_resolver_->set_synchronous_mode(true);
630 EXPECT_EQ(ERR_CONNECTION_FAILED,
631 handle.Init("a", params_, kDefaultPriority, callback.callback(),
632 &pool_, BoundNetLog()));
635 TEST_F(TransportClientSocketPoolTest, PendingRequests) {
636 // First request finishes asynchronously.
637 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
638 EXPECT_EQ(OK, (*requests())[0]->WaitForResult());
640 // Make all subsequent host resolutions complete synchronously.
641 host_resolver_->set_synchronous_mode(true);
643 // Rest of them finish synchronously, until we reach the per-group limit.
644 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
645 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
646 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
647 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
648 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
650 // The rest are pending since we've used all active sockets.
651 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", HIGHEST));
652 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", LOWEST));
653 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", LOWEST));
654 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", MEDIUM));
655 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", LOW));
656 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", HIGHEST));
657 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", LOWEST));
658 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", MEDIUM));
659 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", MEDIUM));
660 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", HIGHEST));
662 ReleaseAllConnections(ClientSocketPoolTest::KEEP_ALIVE);
664 EXPECT_EQ(kMaxSocketsPerGroup, client_socket_factory_.allocation_count());
666 // One initial asynchronous request and then 10 pending requests.
667 EXPECT_EQ(11U, completion_count());
669 // First part of requests, all with the same priority, finishes in FIFO order.
670 EXPECT_EQ(1, GetOrderOfRequest(1));
671 EXPECT_EQ(2, GetOrderOfRequest(2));
672 EXPECT_EQ(3, GetOrderOfRequest(3));
673 EXPECT_EQ(4, GetOrderOfRequest(4));
674 EXPECT_EQ(5, GetOrderOfRequest(5));
675 EXPECT_EQ(6, GetOrderOfRequest(6));
677 // Make sure that rest of the requests complete in the order of priority.
678 EXPECT_EQ(7, GetOrderOfRequest(7));
679 EXPECT_EQ(14, GetOrderOfRequest(8));
680 EXPECT_EQ(15, GetOrderOfRequest(9));
681 EXPECT_EQ(10, GetOrderOfRequest(10));
682 EXPECT_EQ(13, GetOrderOfRequest(11));
683 EXPECT_EQ(8, GetOrderOfRequest(12));
684 EXPECT_EQ(16, GetOrderOfRequest(13));
685 EXPECT_EQ(11, GetOrderOfRequest(14));
686 EXPECT_EQ(12, GetOrderOfRequest(15));
687 EXPECT_EQ(9, GetOrderOfRequest(16));
689 // Make sure we test order of all requests made.
690 EXPECT_EQ(ClientSocketPoolTest::kIndexOutOfBounds, GetOrderOfRequest(17));
693 TEST_F(TransportClientSocketPoolTest, PendingRequests_NoKeepAlive) {
694 // First request finishes asynchronously.
695 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
696 EXPECT_EQ(OK, (*requests())[0]->WaitForResult());
698 // Make all subsequent host resolutions complete synchronously.
699 host_resolver_->set_synchronous_mode(true);
701 // Rest of them finish synchronously, until we reach the per-group limit.
702 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
703 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
704 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
705 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
706 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
708 // The rest are pending since we've used all active sockets.
709 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
710 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
711 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
712 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
713 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
715 ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE);
717 // The pending requests should finish successfully.
718 EXPECT_EQ(OK, (*requests())[6]->WaitForResult());
719 EXPECT_EQ(OK, (*requests())[7]->WaitForResult());
720 EXPECT_EQ(OK, (*requests())[8]->WaitForResult());
721 EXPECT_EQ(OK, (*requests())[9]->WaitForResult());
722 EXPECT_EQ(OK, (*requests())[10]->WaitForResult());
724 EXPECT_EQ(static_cast<int>(requests()->size()),
725 client_socket_factory_.allocation_count());
727 // First asynchronous request, and then last 5 pending requests.
728 EXPECT_EQ(6U, completion_count());
731 // This test will start up a RequestSocket() and then immediately Cancel() it.
732 // The pending host resolution will eventually complete, and destroy the
733 // ClientSocketPool which will crash if the group was not cleared properly.
734 TEST_F(TransportClientSocketPoolTest, CancelRequestClearGroup) {
735 TestCompletionCallback callback;
736 ClientSocketHandle handle;
737 EXPECT_EQ(ERR_IO_PENDING,
738 handle.Init("a", params_, kDefaultPriority, callback.callback(),
739 &pool_, BoundNetLog()));
740 handle.Reset();
743 TEST_F(TransportClientSocketPoolTest, TwoRequestsCancelOne) {
744 ClientSocketHandle handle;
745 TestCompletionCallback callback;
746 ClientSocketHandle handle2;
747 TestCompletionCallback callback2;
749 EXPECT_EQ(ERR_IO_PENDING,
750 handle.Init("a", params_, kDefaultPriority, callback.callback(),
751 &pool_, BoundNetLog()));
752 EXPECT_EQ(ERR_IO_PENDING,
753 handle2.Init("a", params_, kDefaultPriority, callback2.callback(),
754 &pool_, BoundNetLog()));
756 handle.Reset();
758 EXPECT_EQ(OK, callback2.WaitForResult());
759 handle2.Reset();
762 TEST_F(TransportClientSocketPoolTest, ConnectCancelConnect) {
763 client_socket_factory_.set_client_socket_type(
764 MockClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET);
765 ClientSocketHandle handle;
766 TestCompletionCallback callback;
767 EXPECT_EQ(ERR_IO_PENDING,
768 handle.Init("a", params_, kDefaultPriority, callback.callback(),
769 &pool_, BoundNetLog()));
771 handle.Reset();
773 TestCompletionCallback callback2;
774 EXPECT_EQ(ERR_IO_PENDING,
775 handle.Init("a", params_, kDefaultPriority, callback2.callback(),
776 &pool_, BoundNetLog()));
778 host_resolver_->set_synchronous_mode(true);
779 // At this point, handle has two ConnectingSockets out for it. Due to the
780 // setting the mock resolver into synchronous mode, the host resolution for
781 // both will return in the same loop of the MessageLoop. The client socket
782 // is a pending socket, so the Connect() will asynchronously complete on the
783 // next loop of the MessageLoop. That means that the first
784 // ConnectingSocket will enter OnIOComplete, and then the second one will.
785 // If the first one is not cancelled, it will advance the load state, and
786 // then the second one will crash.
788 EXPECT_EQ(OK, callback2.WaitForResult());
789 EXPECT_FALSE(callback.have_result());
791 handle.Reset();
794 TEST_F(TransportClientSocketPoolTest, CancelRequest) {
795 // First request finishes asynchronously.
796 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
797 EXPECT_EQ(OK, (*requests())[0]->WaitForResult());
799 // Make all subsequent host resolutions complete synchronously.
800 host_resolver_->set_synchronous_mode(true);
802 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
803 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
804 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
805 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
806 EXPECT_EQ(OK, StartRequest("a", kDefaultPriority));
808 // Reached per-group limit, queue up requests.
809 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", LOWEST));
810 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", HIGHEST));
811 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", HIGHEST));
812 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", MEDIUM));
813 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", MEDIUM));
814 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", LOW));
815 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", HIGHEST));
816 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", LOW));
817 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", LOW));
818 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", LOWEST));
820 // Cancel a request.
821 size_t index_to_cancel = kMaxSocketsPerGroup + 2;
822 EXPECT_FALSE((*requests())[index_to_cancel]->handle()->is_initialized());
823 (*requests())[index_to_cancel]->handle()->Reset();
825 ReleaseAllConnections(ClientSocketPoolTest::KEEP_ALIVE);
827 EXPECT_EQ(kMaxSocketsPerGroup,
828 client_socket_factory_.allocation_count());
829 EXPECT_EQ(requests()->size() - kMaxSocketsPerGroup, completion_count());
831 EXPECT_EQ(1, GetOrderOfRequest(1));
832 EXPECT_EQ(2, GetOrderOfRequest(2));
833 EXPECT_EQ(3, GetOrderOfRequest(3));
834 EXPECT_EQ(4, GetOrderOfRequest(4));
835 EXPECT_EQ(5, GetOrderOfRequest(5));
836 EXPECT_EQ(6, GetOrderOfRequest(6));
837 EXPECT_EQ(14, GetOrderOfRequest(7));
838 EXPECT_EQ(7, GetOrderOfRequest(8));
839 EXPECT_EQ(ClientSocketPoolTest::kRequestNotFound,
840 GetOrderOfRequest(9)); // Canceled request.
841 EXPECT_EQ(9, GetOrderOfRequest(10));
842 EXPECT_EQ(10, GetOrderOfRequest(11));
843 EXPECT_EQ(11, GetOrderOfRequest(12));
844 EXPECT_EQ(8, GetOrderOfRequest(13));
845 EXPECT_EQ(12, GetOrderOfRequest(14));
846 EXPECT_EQ(13, GetOrderOfRequest(15));
847 EXPECT_EQ(15, GetOrderOfRequest(16));
849 // Make sure we test order of all requests made.
850 EXPECT_EQ(ClientSocketPoolTest::kIndexOutOfBounds, GetOrderOfRequest(17));
853 class RequestSocketCallback : public TestCompletionCallbackBase {
854 public:
855 RequestSocketCallback(ClientSocketHandle* handle,
856 TransportClientSocketPool* pool)
857 : handle_(handle),
858 pool_(pool),
859 within_callback_(false),
860 callback_(base::Bind(&RequestSocketCallback::OnComplete,
861 base::Unretained(this))) {
864 virtual ~RequestSocketCallback() {}
866 const CompletionCallback& callback() const { return callback_; }
868 private:
869 void OnComplete(int result) {
870 SetResult(result);
871 ASSERT_EQ(OK, result);
873 if (!within_callback_) {
874 // Don't allow reuse of the socket. Disconnect it and then release it and
875 // run through the MessageLoop once to get it completely released.
876 handle_->socket()->Disconnect();
877 handle_->Reset();
879 base::MessageLoop::ScopedNestableTaskAllower allow(
880 base::MessageLoop::current());
881 base::MessageLoop::current()->RunUntilIdle();
883 within_callback_ = true;
884 scoped_refptr<TransportSocketParams> dest(new TransportSocketParams(
885 HostPortPair("www.google.com", 80), false, false,
886 OnHostResolutionCallback()));
887 int rv = handle_->Init("a", dest, LOWEST, callback(), pool_,
888 BoundNetLog());
889 EXPECT_EQ(OK, rv);
893 ClientSocketHandle* const handle_;
894 TransportClientSocketPool* const pool_;
895 bool within_callback_;
896 CompletionCallback callback_;
898 DISALLOW_COPY_AND_ASSIGN(RequestSocketCallback);
901 TEST_F(TransportClientSocketPoolTest, RequestTwice) {
902 ClientSocketHandle handle;
903 RequestSocketCallback callback(&handle, &pool_);
904 scoped_refptr<TransportSocketParams> dest(new TransportSocketParams(
905 HostPortPair("www.google.com", 80), false, false,
906 OnHostResolutionCallback()));
907 int rv = handle.Init("a", dest, LOWEST, callback.callback(), &pool_,
908 BoundNetLog());
909 ASSERT_EQ(ERR_IO_PENDING, rv);
911 // The callback is going to request "www.google.com". We want it to complete
912 // synchronously this time.
913 host_resolver_->set_synchronous_mode(true);
915 EXPECT_EQ(OK, callback.WaitForResult());
917 handle.Reset();
920 // Make sure that pending requests get serviced after active requests get
921 // cancelled.
922 TEST_F(TransportClientSocketPoolTest, CancelActiveRequestWithPendingRequests) {
923 client_socket_factory_.set_client_socket_type(
924 MockClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET);
926 // Queue up all the requests
927 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
928 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
929 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
930 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
931 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
932 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
933 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
934 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
935 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
937 // Now, kMaxSocketsPerGroup requests should be active. Let's cancel them.
938 ASSERT_LE(kMaxSocketsPerGroup, static_cast<int>(requests()->size()));
939 for (int i = 0; i < kMaxSocketsPerGroup; i++)
940 (*requests())[i]->handle()->Reset();
942 // Let's wait for the rest to complete now.
943 for (size_t i = kMaxSocketsPerGroup; i < requests()->size(); ++i) {
944 EXPECT_EQ(OK, (*requests())[i]->WaitForResult());
945 (*requests())[i]->handle()->Reset();
948 EXPECT_EQ(requests()->size() - kMaxSocketsPerGroup, completion_count());
951 // Make sure that pending requests get serviced after active requests fail.
952 TEST_F(TransportClientSocketPoolTest, FailingActiveRequestWithPendingRequests) {
953 client_socket_factory_.set_client_socket_type(
954 MockClientSocketFactory::MOCK_PENDING_FAILING_CLIENT_SOCKET);
956 const int kNumRequests = 2 * kMaxSocketsPerGroup + 1;
957 ASSERT_LE(kNumRequests, kMaxSockets); // Otherwise the test will hang.
959 // Queue up all the requests
960 for (int i = 0; i < kNumRequests; i++)
961 EXPECT_EQ(ERR_IO_PENDING, StartRequest("a", kDefaultPriority));
963 for (int i = 0; i < kNumRequests; i++)
964 EXPECT_EQ(ERR_CONNECTION_FAILED, (*requests())[i]->WaitForResult());
967 TEST_F(TransportClientSocketPoolTest, IdleSocketLoadTiming) {
968 TestCompletionCallback callback;
969 ClientSocketHandle handle;
970 int rv = handle.Init("a", params_, LOW, callback.callback(), &pool_,
971 BoundNetLog());
972 EXPECT_EQ(ERR_IO_PENDING, rv);
973 EXPECT_FALSE(handle.is_initialized());
974 EXPECT_FALSE(handle.socket());
976 EXPECT_EQ(OK, callback.WaitForResult());
977 EXPECT_TRUE(handle.is_initialized());
978 EXPECT_TRUE(handle.socket());
979 TestLoadTimingInfoConnectedNotReused(handle);
981 handle.Reset();
982 // Need to run all pending to release the socket back to the pool.
983 base::MessageLoop::current()->RunUntilIdle();
985 // Now we should have 1 idle socket.
986 EXPECT_EQ(1, pool_.IdleSocketCount());
988 rv = handle.Init("a", params_, LOW, callback.callback(), &pool_,
989 BoundNetLog());
990 EXPECT_EQ(OK, rv);
991 EXPECT_EQ(0, pool_.IdleSocketCount());
992 TestLoadTimingInfoConnectedReused(handle);
995 TEST_F(TransportClientSocketPoolTest, ResetIdleSocketsOnIPAddressChange) {
996 TestCompletionCallback callback;
997 ClientSocketHandle handle;
998 int rv = handle.Init("a", params_, LOW, callback.callback(), &pool_,
999 BoundNetLog());
1000 EXPECT_EQ(ERR_IO_PENDING, rv);
1001 EXPECT_FALSE(handle.is_initialized());
1002 EXPECT_FALSE(handle.socket());
1004 EXPECT_EQ(OK, callback.WaitForResult());
1005 EXPECT_TRUE(handle.is_initialized());
1006 EXPECT_TRUE(handle.socket());
1008 handle.Reset();
1010 // Need to run all pending to release the socket back to the pool.
1011 base::MessageLoop::current()->RunUntilIdle();
1013 // Now we should have 1 idle socket.
1014 EXPECT_EQ(1, pool_.IdleSocketCount());
1016 // After an IP address change, we should have 0 idle sockets.
1017 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1018 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1020 EXPECT_EQ(0, pool_.IdleSocketCount());
1023 TEST_F(TransportClientSocketPoolTest, BackupSocketConnect) {
1024 // Case 1 tests the first socket stalling, and the backup connecting.
1025 MockClientSocketFactory::ClientSocketType case1_types[] = {
1026 // The first socket will not connect.
1027 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET,
1028 // The second socket will connect more quickly.
1029 MockClientSocketFactory::MOCK_CLIENT_SOCKET
1032 // Case 2 tests the first socket being slow, so that we start the
1033 // second connect, but the second connect stalls, and we still
1034 // complete the first.
1035 MockClientSocketFactory::ClientSocketType case2_types[] = {
1036 // The first socket will connect, although delayed.
1037 MockClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET,
1038 // The second socket will not connect.
1039 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET
1042 MockClientSocketFactory::ClientSocketType* cases[2] = {
1043 case1_types,
1044 case2_types
1047 for (size_t index = 0; index < arraysize(cases); ++index) {
1048 client_socket_factory_.set_client_socket_types(cases[index], 2);
1050 EXPECT_EQ(0, pool_.IdleSocketCount());
1052 TestCompletionCallback callback;
1053 ClientSocketHandle handle;
1054 int rv = handle.Init("b", params_, LOW, callback.callback(), &pool_,
1055 BoundNetLog());
1056 EXPECT_EQ(ERR_IO_PENDING, rv);
1057 EXPECT_FALSE(handle.is_initialized());
1058 EXPECT_FALSE(handle.socket());
1060 // Create the first socket, set the timer.
1061 base::MessageLoop::current()->RunUntilIdle();
1063 // Wait for the backup socket timer to fire.
1064 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1065 ClientSocketPool::kMaxConnectRetryIntervalMs + 50));
1067 // Let the appropriate socket connect.
1068 base::MessageLoop::current()->RunUntilIdle();
1070 EXPECT_EQ(OK, callback.WaitForResult());
1071 EXPECT_TRUE(handle.is_initialized());
1072 EXPECT_TRUE(handle.socket());
1074 // One socket is stalled, the other is active.
1075 EXPECT_EQ(0, pool_.IdleSocketCount());
1076 handle.Reset();
1078 // Close all pending connect jobs and existing sockets.
1079 pool_.FlushWithError(ERR_NETWORK_CHANGED);
1083 // Test the case where a socket took long enough to start the creation
1084 // of the backup socket, but then we cancelled the request after that.
1085 TEST_F(TransportClientSocketPoolTest, BackupSocketCancel) {
1086 client_socket_factory_.set_client_socket_type(
1087 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET);
1089 enum { CANCEL_BEFORE_WAIT, CANCEL_AFTER_WAIT };
1091 for (int index = CANCEL_BEFORE_WAIT; index < CANCEL_AFTER_WAIT; ++index) {
1092 EXPECT_EQ(0, pool_.IdleSocketCount());
1094 TestCompletionCallback callback;
1095 ClientSocketHandle handle;
1096 int rv = handle.Init("c", params_, LOW, callback.callback(), &pool_,
1097 BoundNetLog());
1098 EXPECT_EQ(ERR_IO_PENDING, rv);
1099 EXPECT_FALSE(handle.is_initialized());
1100 EXPECT_FALSE(handle.socket());
1102 // Create the first socket, set the timer.
1103 base::MessageLoop::current()->RunUntilIdle();
1105 if (index == CANCEL_AFTER_WAIT) {
1106 // Wait for the backup socket timer to fire.
1107 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1108 ClientSocketPool::kMaxConnectRetryIntervalMs));
1111 // Let the appropriate socket connect.
1112 base::MessageLoop::current()->RunUntilIdle();
1114 handle.Reset();
1116 EXPECT_FALSE(callback.have_result());
1117 EXPECT_FALSE(handle.is_initialized());
1118 EXPECT_FALSE(handle.socket());
1120 // One socket is stalled, the other is active.
1121 EXPECT_EQ(0, pool_.IdleSocketCount());
1125 // Test the case where a socket took long enough to start the creation
1126 // of the backup socket and never completes, and then the backup
1127 // connection fails.
1128 TEST_F(TransportClientSocketPoolTest, BackupSocketFailAfterStall) {
1129 MockClientSocketFactory::ClientSocketType case_types[] = {
1130 // The first socket will not connect.
1131 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET,
1132 // The second socket will fail immediately.
1133 MockClientSocketFactory::MOCK_FAILING_CLIENT_SOCKET
1136 client_socket_factory_.set_client_socket_types(case_types, 2);
1138 EXPECT_EQ(0, pool_.IdleSocketCount());
1140 TestCompletionCallback callback;
1141 ClientSocketHandle handle;
1142 int rv = handle.Init("b", params_, LOW, callback.callback(), &pool_,
1143 BoundNetLog());
1144 EXPECT_EQ(ERR_IO_PENDING, rv);
1145 EXPECT_FALSE(handle.is_initialized());
1146 EXPECT_FALSE(handle.socket());
1148 // Create the first socket, set the timer.
1149 base::MessageLoop::current()->RunUntilIdle();
1151 // Wait for the backup socket timer to fire.
1152 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1153 ClientSocketPool::kMaxConnectRetryIntervalMs));
1155 // Let the second connect be synchronous. Otherwise, the emulated
1156 // host resolution takes an extra trip through the message loop.
1157 host_resolver_->set_synchronous_mode(true);
1159 // Let the appropriate socket connect.
1160 base::MessageLoop::current()->RunUntilIdle();
1162 EXPECT_EQ(ERR_CONNECTION_FAILED, callback.WaitForResult());
1163 EXPECT_FALSE(handle.is_initialized());
1164 EXPECT_FALSE(handle.socket());
1165 EXPECT_EQ(0, pool_.IdleSocketCount());
1166 handle.Reset();
1168 // Reset for the next case.
1169 host_resolver_->set_synchronous_mode(false);
1172 // Test the case where a socket took long enough to start the creation
1173 // of the backup socket and eventually completes, but the backup socket
1174 // fails.
1175 TEST_F(TransportClientSocketPoolTest, BackupSocketFailAfterDelay) {
1176 MockClientSocketFactory::ClientSocketType case_types[] = {
1177 // The first socket will connect, although delayed.
1178 MockClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET,
1179 // The second socket will not connect.
1180 MockClientSocketFactory::MOCK_FAILING_CLIENT_SOCKET
1183 client_socket_factory_.set_client_socket_types(case_types, 2);
1184 client_socket_factory_.set_delay(base::TimeDelta::FromSeconds(5));
1186 EXPECT_EQ(0, pool_.IdleSocketCount());
1188 TestCompletionCallback callback;
1189 ClientSocketHandle handle;
1190 int rv = handle.Init("b", params_, LOW, callback.callback(), &pool_,
1191 BoundNetLog());
1192 EXPECT_EQ(ERR_IO_PENDING, rv);
1193 EXPECT_FALSE(handle.is_initialized());
1194 EXPECT_FALSE(handle.socket());
1196 // Create the first socket, set the timer.
1197 base::MessageLoop::current()->RunUntilIdle();
1199 // Wait for the backup socket timer to fire.
1200 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
1201 ClientSocketPool::kMaxConnectRetryIntervalMs));
1203 // Let the second connect be synchronous. Otherwise, the emulated
1204 // host resolution takes an extra trip through the message loop.
1205 host_resolver_->set_synchronous_mode(true);
1207 // Let the appropriate socket connect.
1208 base::MessageLoop::current()->RunUntilIdle();
1210 EXPECT_EQ(ERR_CONNECTION_FAILED, callback.WaitForResult());
1211 EXPECT_FALSE(handle.is_initialized());
1212 EXPECT_FALSE(handle.socket());
1213 handle.Reset();
1215 // Reset for the next case.
1216 host_resolver_->set_synchronous_mode(false);
1219 // Test the case of the IPv6 address stalling, and falling back to the IPv4
1220 // socket which finishes first.
1221 TEST_F(TransportClientSocketPoolTest, IPv6FallbackSocketIPv4FinishesFirst) {
1222 // Create a pool without backup jobs.
1223 ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(false);
1224 TransportClientSocketPool pool(kMaxSockets,
1225 kMaxSocketsPerGroup,
1226 histograms_.get(),
1227 host_resolver_.get(),
1228 &client_socket_factory_,
1229 NULL);
1231 MockClientSocketFactory::ClientSocketType case_types[] = {
1232 // This is the IPv6 socket.
1233 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET,
1234 // This is the IPv4 socket.
1235 MockClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET
1238 client_socket_factory_.set_client_socket_types(case_types, 2);
1240 // Resolve an AddressList with a IPv6 address first and then a IPv4 address.
1241 host_resolver_->rules()
1242 ->AddIPLiteralRule("*", "2:abcd::3:4:ff,2.2.2.2", std::string());
1244 TestCompletionCallback callback;
1245 ClientSocketHandle handle;
1246 int rv = handle.Init("a", params_, LOW, callback.callback(), &pool,
1247 BoundNetLog());
1248 EXPECT_EQ(ERR_IO_PENDING, rv);
1249 EXPECT_FALSE(handle.is_initialized());
1250 EXPECT_FALSE(handle.socket());
1252 EXPECT_EQ(OK, callback.WaitForResult());
1253 EXPECT_TRUE(handle.is_initialized());
1254 EXPECT_TRUE(handle.socket());
1255 IPEndPoint endpoint;
1256 handle.socket()->GetLocalAddress(&endpoint);
1257 EXPECT_EQ(kIPv4AddressSize, endpoint.address().size());
1258 EXPECT_EQ(2, client_socket_factory_.allocation_count());
1261 // Test the case of the IPv6 address being slow, thus falling back to trying to
1262 // connect to the IPv4 address, but having the connect to the IPv6 address
1263 // finish first.
1264 TEST_F(TransportClientSocketPoolTest, IPv6FallbackSocketIPv6FinishesFirst) {
1265 // Create a pool without backup jobs.
1266 ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(false);
1267 TransportClientSocketPool pool(kMaxSockets,
1268 kMaxSocketsPerGroup,
1269 histograms_.get(),
1270 host_resolver_.get(),
1271 &client_socket_factory_,
1272 NULL);
1274 MockClientSocketFactory::ClientSocketType case_types[] = {
1275 // This is the IPv6 socket.
1276 MockClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET,
1277 // This is the IPv4 socket.
1278 MockClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET
1281 client_socket_factory_.set_client_socket_types(case_types, 2);
1282 client_socket_factory_.set_delay(base::TimeDelta::FromMilliseconds(
1283 TransportConnectJob::kIPv6FallbackTimerInMs + 50));
1285 // Resolve an AddressList with a IPv6 address first and then a IPv4 address.
1286 host_resolver_->rules()
1287 ->AddIPLiteralRule("*", "2:abcd::3:4:ff,2.2.2.2", std::string());
1289 TestCompletionCallback callback;
1290 ClientSocketHandle handle;
1291 int rv = handle.Init("a", params_, LOW, callback.callback(), &pool,
1292 BoundNetLog());
1293 EXPECT_EQ(ERR_IO_PENDING, rv);
1294 EXPECT_FALSE(handle.is_initialized());
1295 EXPECT_FALSE(handle.socket());
1297 EXPECT_EQ(OK, callback.WaitForResult());
1298 EXPECT_TRUE(handle.is_initialized());
1299 EXPECT_TRUE(handle.socket());
1300 IPEndPoint endpoint;
1301 handle.socket()->GetLocalAddress(&endpoint);
1302 EXPECT_EQ(kIPv6AddressSize, endpoint.address().size());
1303 EXPECT_EQ(2, client_socket_factory_.allocation_count());
1306 TEST_F(TransportClientSocketPoolTest, IPv6NoIPv4AddressesToFallbackTo) {
1307 // Create a pool without backup jobs.
1308 ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(false);
1309 TransportClientSocketPool pool(kMaxSockets,
1310 kMaxSocketsPerGroup,
1311 histograms_.get(),
1312 host_resolver_.get(),
1313 &client_socket_factory_,
1314 NULL);
1316 client_socket_factory_.set_client_socket_type(
1317 MockClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET);
1319 // Resolve an AddressList with only IPv6 addresses.
1320 host_resolver_->rules()
1321 ->AddIPLiteralRule("*", "2:abcd::3:4:ff,3:abcd::3:4:ff", std::string());
1323 TestCompletionCallback callback;
1324 ClientSocketHandle handle;
1325 int rv = handle.Init("a", params_, LOW, callback.callback(), &pool,
1326 BoundNetLog());
1327 EXPECT_EQ(ERR_IO_PENDING, rv);
1328 EXPECT_FALSE(handle.is_initialized());
1329 EXPECT_FALSE(handle.socket());
1331 EXPECT_EQ(OK, callback.WaitForResult());
1332 EXPECT_TRUE(handle.is_initialized());
1333 EXPECT_TRUE(handle.socket());
1334 IPEndPoint endpoint;
1335 handle.socket()->GetLocalAddress(&endpoint);
1336 EXPECT_EQ(kIPv6AddressSize, endpoint.address().size());
1337 EXPECT_EQ(1, client_socket_factory_.allocation_count());
1340 TEST_F(TransportClientSocketPoolTest, IPv4HasNoFallback) {
1341 // Create a pool without backup jobs.
1342 ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(false);
1343 TransportClientSocketPool pool(kMaxSockets,
1344 kMaxSocketsPerGroup,
1345 histograms_.get(),
1346 host_resolver_.get(),
1347 &client_socket_factory_,
1348 NULL);
1350 client_socket_factory_.set_client_socket_type(
1351 MockClientSocketFactory::MOCK_DELAYED_CLIENT_SOCKET);
1353 // Resolve an AddressList with only IPv4 addresses.
1354 host_resolver_->rules()->AddIPLiteralRule("*", "1.1.1.1", std::string());
1356 TestCompletionCallback callback;
1357 ClientSocketHandle handle;
1358 int rv = handle.Init("a", params_, LOW, callback.callback(), &pool,
1359 BoundNetLog());
1360 EXPECT_EQ(ERR_IO_PENDING, rv);
1361 EXPECT_FALSE(handle.is_initialized());
1362 EXPECT_FALSE(handle.socket());
1364 EXPECT_EQ(OK, callback.WaitForResult());
1365 EXPECT_TRUE(handle.is_initialized());
1366 EXPECT_TRUE(handle.socket());
1367 IPEndPoint endpoint;
1368 handle.socket()->GetLocalAddress(&endpoint);
1369 EXPECT_EQ(kIPv4AddressSize, endpoint.address().size());
1370 EXPECT_EQ(1, client_socket_factory_.allocation_count());
1373 } // namespace
1375 } // namespace net