forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_socket_pool_base_unittest.cc
4136 lines (3414 loc) · 162 KB
/
client_socket_pool_base_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 (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/socket/client_socket_pool_base.h"
#include <stdint.h>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "net/base/load_timing_info.h"
#include "net/base/load_timing_info_test_util.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/base/test_completion_callback.h"
#include "net/http/http_response_headers.h"
#include "net/log/net_log.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source.h"
#include "net/log/net_log_source_type.h"
#include "net/log/test_net_log.h"
#include "net/log/test_net_log_entry.h"
#include "net/log/test_net_log_util.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/datagram_client_socket.h"
#include "net/socket/socket_performance_watcher.h"
#include "net/socket/socket_tag.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/ssl_client_socket.h"
#include "net/socket/stream_socket.h"
#include "net/test/gtest_util.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using net::test::IsError;
using net::test::IsOk;
using ::testing::Invoke;
using ::testing::Return;
namespace net {
namespace {
const int kDefaultMaxSockets = 4;
const int kDefaultMaxSocketsPerGroup = 2;
// Make sure |handle| sets load times correctly when it has been assigned a
// reused socket.
void TestLoadTimingInfoConnectedReused(const ClientSocketHandle& handle) {
LoadTimingInfo load_timing_info;
// Only pass true in as |is_reused|, as in general, HttpStream types should
// have stricter concepts of reuse than socket pools.
EXPECT_TRUE(handle.GetLoadTimingInfo(true, &load_timing_info));
EXPECT_EQ(true, load_timing_info.socket_reused);
EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
ExpectLoadTimingHasOnlyConnectionTimes(load_timing_info);
}
// Make sure |handle| sets load times correctly when it has been assigned a
// fresh socket. Also runs TestLoadTimingInfoConnectedReused, since the owner
// of a connection where |is_reused| is false may consider the connection
// reused.
void TestLoadTimingInfoConnectedNotReused(const ClientSocketHandle& handle) {
EXPECT_FALSE(handle.is_reused());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(handle.GetLoadTimingInfo(false, &load_timing_info));
EXPECT_FALSE(load_timing_info.socket_reused);
EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
ExpectLoadTimingHasOnlyConnectionTimes(load_timing_info);
TestLoadTimingInfoConnectedReused(handle);
}
// Make sure |handle| sets load times correctly, in the case that it does not
// currently have a socket.
void TestLoadTimingInfoNotConnected(const ClientSocketHandle& handle) {
// Should only be set to true once a socket is assigned, if at all.
EXPECT_FALSE(handle.is_reused());
LoadTimingInfo load_timing_info;
EXPECT_FALSE(handle.GetLoadTimingInfo(false, &load_timing_info));
EXPECT_FALSE(load_timing_info.socket_reused);
EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
ExpectLoadTimingHasOnlyConnectionTimes(load_timing_info);
}
class TestSocketParams : public base::RefCounted<TestSocketParams> {
public:
explicit TestSocketParams() = default;
private:
friend class base::RefCounted<TestSocketParams>;
~TestSocketParams() = default;
};
typedef ClientSocketPoolBase<TestSocketParams> TestClientSocketPoolBase;
class MockClientSocket : public StreamSocket {
public:
explicit MockClientSocket(net::NetLog* net_log)
: connected_(false),
has_unread_data_(false),
net_log_(NetLogWithSource::Make(net_log, NetLogSourceType::SOCKET)),
was_used_to_convey_data_(false),
motivation_(HttpRequestInfo::NORMAL_MOTIVATION) {}
// Sets whether the socket has unread data. If true, the next call to Read()
// will return 1 byte and IsConnectedAndIdle() will return false.
void set_has_unread_data(bool has_unread_data) {
has_unread_data_ = has_unread_data;
}
HttpRequestInfo::RequestMotivation motivation() const { return motivation_; }
// Socket implementation.
int Read(IOBuffer* /* buf */,
int len,
CompletionOnceCallback /* callback */) override {
if (has_unread_data_ && len > 0) {
has_unread_data_ = false;
was_used_to_convey_data_ = true;
return 1;
}
return ERR_UNEXPECTED;
}
int Write(
IOBuffer* /* buf */,
int len,
CompletionOnceCallback /* callback */,
const NetworkTrafficAnnotationTag& /*traffic_annotation*/) override {
was_used_to_convey_data_ = true;
return len;
}
int SetReceiveBufferSize(int32_t size) override { return OK; }
int SetSendBufferSize(int32_t size) override { return OK; }
// StreamSocket implementation.
int Connect(CompletionOnceCallback callback) override {
connected_ = true;
return OK;
}
void Disconnect() override { connected_ = false; }
bool IsConnected() const override { return connected_; }
bool IsConnectedAndIdle() const override {
return connected_ && !has_unread_data_;
}
int GetPeerAddress(IPEndPoint* /* address */) const override {
return ERR_UNEXPECTED;
}
int GetLocalAddress(IPEndPoint* /* address */) const override {
return ERR_UNEXPECTED;
}
const NetLogWithSource& NetLog() const override { return net_log_; }
void SetSubresourceSpeculation() override {
motivation_ = HttpRequestInfo::PRECONNECT_MOTIVATED;
}
void SetOmniboxSpeculation() override {
motivation_ = HttpRequestInfo::OMNIBOX_MOTIVATED;
}
bool WasEverUsed() const override { return was_used_to_convey_data_; }
bool WasAlpnNegotiated() const override { return false; }
NextProto GetNegotiatedProtocol() const override { return kProtoUnknown; }
bool GetSSLInfo(SSLInfo* ssl_info) override { return false; }
void GetConnectionAttempts(ConnectionAttempts* out) const override {
out->clear();
}
void ClearConnectionAttempts() override {}
void AddConnectionAttempts(const ConnectionAttempts& attempts) override {}
int64_t GetTotalReceivedBytes() const override {
NOTIMPLEMENTED();
return 0;
}
void ApplySocketTag(const SocketTag& tag) override {}
private:
bool connected_;
bool has_unread_data_;
NetLogWithSource net_log_;
bool was_used_to_convey_data_;
HttpRequestInfo::RequestMotivation motivation_;
DISALLOW_COPY_AND_ASSIGN(MockClientSocket);
};
class TestConnectJob;
class MockClientSocketFactory : public ClientSocketFactory {
public:
MockClientSocketFactory() : allocation_count_(0) {}
std::unique_ptr<DatagramClientSocket> CreateDatagramClientSocket(
DatagramSocket::BindType bind_type,
NetLog* net_log,
const NetLogSource& source) override {
NOTREACHED();
return std::unique_ptr<DatagramClientSocket>();
}
std::unique_ptr<TransportClientSocket> CreateTransportClientSocket(
const AddressList& addresses,
std::unique_ptr<
SocketPerformanceWatcher> /* socket_performance_watcher */,
NetLog* /* net_log */,
const NetLogSource& /*source*/) override {
allocation_count_++;
return nullptr;
}
std::unique_ptr<SSLClientSocket> CreateSSLClientSocket(
std::unique_ptr<ClientSocketHandle> transport_socket,
const HostPortPair& host_and_port,
const SSLConfig& ssl_config,
const SSLClientSocketContext& context) override {
NOTIMPLEMENTED();
return std::unique_ptr<SSLClientSocket>();
}
std::unique_ptr<ProxyClientSocket> CreateProxyClientSocket(
std::unique_ptr<ClientSocketHandle> transport_socket,
const std::string& user_agent,
const HostPortPair& endpoint,
HttpAuthController* http_auth_controller,
bool tunnel,
bool using_spdy,
NextProto negotiated_protocol,
bool is_https_proxy,
const NetworkTrafficAnnotationTag& traffic_annotation) override {
NOTIMPLEMENTED();
return nullptr;
}
void ClearSSLSessionCache() override { NOTIMPLEMENTED(); }
void WaitForSignal(TestConnectJob* job) { waiting_jobs_.push_back(job); }
void SignalJobs();
void SignalJob(size_t job);
void SetJobLoadState(size_t job, LoadState load_state);
int allocation_count() const { return allocation_count_; }
private:
int allocation_count_;
std::vector<TestConnectJob*> waiting_jobs_;
};
class TestConnectJob : public ConnectJob {
public:
enum JobType {
kMockJob,
kMockFailingJob,
kMockPendingJob,
kMockPendingFailingJob,
kMockWaitingJob,
kMockRecoverableJob,
kMockPendingRecoverableJob,
kMockAdditionalErrorStateJob,
kMockPendingAdditionalErrorStateJob,
kMockUnreadDataJob,
};
// The kMockPendingJob uses a slight delay before allowing the connect
// to complete.
static const int kPendingConnectDelay = 2;
TestConnectJob(JobType job_type,
const std::string& group_name,
const TestClientSocketPoolBase::Request& request,
base::TimeDelta timeout_duration,
ConnectJob::Delegate* delegate,
MockClientSocketFactory* client_socket_factory,
NetLog* net_log)
: ConnectJob(
group_name,
timeout_duration,
request.priority(),
request.socket_tag(),
request.respect_limits(),
delegate,
NetLogWithSource::Make(net_log,
NetLogSourceType::TRANSPORT_CONNECT_JOB)),
job_type_(job_type),
client_socket_factory_(client_socket_factory),
load_state_(LOAD_STATE_IDLE),
store_additional_error_state_(false),
weak_factory_(this) {}
void Signal() {
DoConnect(waiting_success_, true /* async */, false /* recoverable */);
}
void set_load_state(LoadState load_state) { load_state_ = load_state; }
// From ConnectJob:
LoadState GetLoadState() const override { return load_state_; }
void GetAdditionalErrorState(ClientSocketHandle* handle) override {
if (store_additional_error_state_) {
// Set all of the additional error state fields in some way.
handle->set_is_ssl_error(true);
HttpResponseInfo info;
info.headers = new HttpResponseHeaders(std::string());
handle->set_ssl_error_response_info(info);
}
}
private:
// From ConnectJob:
int ConnectInternal() override {
AddressList ignored;
client_socket_factory_->CreateTransportClientSocket(ignored, NULL, NULL,
NetLogSource());
SetSocket(std::unique_ptr<StreamSocket>(
new MockClientSocket(net_log().net_log())));
switch (job_type_) {
case kMockJob:
return DoConnect(true /* successful */, false /* sync */,
false /* recoverable */);
case kMockFailingJob:
return DoConnect(false /* error */, false /* sync */,
false /* recoverable */);
case kMockPendingJob:
set_load_state(LOAD_STATE_CONNECTING);
// Depending on execution timings, posting a delayed task can result
// in the task getting executed the at the earliest possible
// opportunity or only after returning once from the message loop and
// then a second call into the message loop. In order to make behavior
// more deterministic, we change the default delay to 2ms. This should
// always require us to wait for the second call into the message loop.
//
// N.B. The correct fix for this and similar timing problems is to
// abstract time for the purpose of unittests. Unfortunately, we have
// a lot of third-party components that directly call the various
// time functions, so this change would be rather invasive.
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&TestConnectJob::DoConnect),
weak_factory_.GetWeakPtr(), true /* successful */,
true /* async */, false /* recoverable */),
base::TimeDelta::FromMilliseconds(kPendingConnectDelay));
return ERR_IO_PENDING;
case kMockPendingFailingJob:
set_load_state(LOAD_STATE_CONNECTING);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&TestConnectJob::DoConnect),
weak_factory_.GetWeakPtr(), false /* error */,
true /* async */, false /* recoverable */),
base::TimeDelta::FromMilliseconds(2));
return ERR_IO_PENDING;
case kMockWaitingJob:
set_load_state(LOAD_STATE_CONNECTING);
client_socket_factory_->WaitForSignal(this);
waiting_success_ = true;
return ERR_IO_PENDING;
case kMockRecoverableJob:
return DoConnect(false /* error */, false /* sync */,
true /* recoverable */);
case kMockPendingRecoverableJob:
set_load_state(LOAD_STATE_CONNECTING);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&TestConnectJob::DoConnect),
weak_factory_.GetWeakPtr(), false /* error */,
true /* async */, true /* recoverable */),
base::TimeDelta::FromMilliseconds(2));
return ERR_IO_PENDING;
case kMockAdditionalErrorStateJob:
store_additional_error_state_ = true;
return DoConnect(false /* error */, false /* sync */,
false /* recoverable */);
case kMockPendingAdditionalErrorStateJob:
set_load_state(LOAD_STATE_CONNECTING);
store_additional_error_state_ = true;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&TestConnectJob::DoConnect),
weak_factory_.GetWeakPtr(), false /* error */,
true /* async */, false /* recoverable */),
base::TimeDelta::FromMilliseconds(2));
return ERR_IO_PENDING;
case kMockUnreadDataJob: {
int ret = DoConnect(true /* successful */, false /* sync */,
false /* recoverable */);
static_cast<MockClientSocket*>(socket())->set_has_unread_data(true);
return ret;
}
default:
NOTREACHED();
SetSocket(std::unique_ptr<StreamSocket>());
return ERR_FAILED;
}
}
int DoConnect(bool succeed, bool was_async, bool recoverable) {
int result = OK;
if (succeed) {
socket()->Connect(CompletionCallback());
} else if (recoverable) {
result = ERR_PROXY_AUTH_REQUESTED;
} else {
result = ERR_CONNECTION_FAILED;
SetSocket(std::unique_ptr<StreamSocket>());
}
if (was_async)
NotifyDelegateOfCompletion(result);
return result;
}
bool waiting_success_;
const JobType job_type_;
MockClientSocketFactory* const client_socket_factory_;
LoadState load_state_;
bool store_additional_error_state_;
base::WeakPtrFactory<TestConnectJob> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(TestConnectJob);
};
class TestConnectJobFactory
: public TestClientSocketPoolBase::ConnectJobFactory {
public:
TestConnectJobFactory(MockClientSocketFactory* client_socket_factory,
NetLog* net_log)
: job_type_(TestConnectJob::kMockJob),
job_types_(NULL),
client_socket_factory_(client_socket_factory),
net_log_(net_log) {
}
~TestConnectJobFactory() override = default;
void set_job_type(TestConnectJob::JobType job_type) { job_type_ = job_type; }
void set_job_types(std::list<TestConnectJob::JobType>* job_types) {
job_types_ = job_types;
CHECK(!job_types_->empty());
}
void set_timeout_duration(base::TimeDelta timeout_duration) {
timeout_duration_ = timeout_duration;
}
// ConnectJobFactory implementation.
std::unique_ptr<ConnectJob> NewConnectJob(
const std::string& group_name,
const TestClientSocketPoolBase::Request& request,
ConnectJob::Delegate* delegate) const override {
EXPECT_TRUE(!job_types_ || !job_types_->empty());
TestConnectJob::JobType job_type = job_type_;
if (job_types_ && !job_types_->empty()) {
job_type = job_types_->front();
job_types_->pop_front();
}
return std::unique_ptr<ConnectJob>(
new TestConnectJob(job_type, group_name, request, timeout_duration_,
delegate, client_socket_factory_, net_log_));
}
base::TimeDelta ConnectionTimeout() const override {
return timeout_duration_;
}
private:
TestConnectJob::JobType job_type_;
std::list<TestConnectJob::JobType>* job_types_;
base::TimeDelta timeout_duration_;
MockClientSocketFactory* const client_socket_factory_;
NetLog* net_log_;
DISALLOW_COPY_AND_ASSIGN(TestConnectJobFactory);
};
class TestClientSocketPool : public ClientSocketPool {
public:
typedef TestSocketParams SocketParams;
TestClientSocketPool(
int max_sockets,
int max_sockets_per_group,
base::TimeDelta unused_idle_socket_timeout,
base::TimeDelta used_idle_socket_timeout,
TestClientSocketPoolBase::ConnectJobFactory* connect_job_factory)
: base_(NULL,
max_sockets,
max_sockets_per_group,
unused_idle_socket_timeout,
used_idle_socket_timeout,
connect_job_factory) {}
~TestClientSocketPool() override = default;
int RequestSocket(const std::string& group_name,
const void* params,
RequestPriority priority,
const SocketTag& socket_tag,
RespectLimits respect_limits,
ClientSocketHandle* handle,
const CompletionCallback& callback,
const NetLogWithSource& net_log) override {
const scoped_refptr<TestSocketParams>* casted_socket_params =
static_cast<const scoped_refptr<TestSocketParams>*>(params);
return base_.RequestSocket(group_name, *casted_socket_params, priority,
socket_tag, respect_limits, handle, callback,
net_log);
}
void RequestSockets(const std::string& group_name,
const void* params,
int num_sockets,
const NetLogWithSource& net_log,
HttpRequestInfo::RequestMotivation motivation) override {
const scoped_refptr<TestSocketParams>* casted_params =
static_cast<const scoped_refptr<TestSocketParams>*>(params);
base_.RequestSockets(group_name, *casted_params, num_sockets, net_log,
motivation);
}
void SetPriority(const std::string& group_name,
ClientSocketHandle* handle,
RequestPriority priority) override {
base_.SetPriority(group_name, handle, priority);
}
void CancelRequest(const std::string& group_name,
ClientSocketHandle* handle) override {
base_.CancelRequest(group_name, handle);
}
void ReleaseSocket(const std::string& group_name,
std::unique_ptr<StreamSocket> socket,
int id) override {
base_.ReleaseSocket(group_name, std::move(socket), id);
}
void FlushWithError(int error) override { base_.FlushWithError(error); }
bool IsStalled() const override { return base_.IsStalled(); }
void CloseIdleSockets() override { base_.CloseIdleSockets(); }
void CloseIdleSocketsInGroup(const std::string& group_name) override {
base_.CloseIdleSocketsInGroup(group_name);
}
int IdleSocketCount() const override { return base_.idle_socket_count(); }
int IdleSocketCountInGroup(const std::string& group_name) const override {
return base_.IdleSocketCountInGroup(group_name);
}
LoadState GetLoadState(const std::string& group_name,
const ClientSocketHandle* handle) const override {
return base_.GetLoadState(group_name, handle);
}
void AddHigherLayeredPool(HigherLayeredPool* higher_pool) override {
base_.AddHigherLayeredPool(higher_pool);
}
void RemoveHigherLayeredPool(HigherLayeredPool* higher_pool) override {
base_.RemoveHigherLayeredPool(higher_pool);
}
std::unique_ptr<base::DictionaryValue> GetInfoAsValue(
const std::string& name,
const std::string& type,
bool include_nested_pools) const override {
return base_.GetInfoAsValue(name, type);
}
base::TimeDelta ConnectionTimeout() const override {
return base_.ConnectionTimeout();
}
const TestClientSocketPoolBase* base() const { return &base_; }
int NumUnassignedConnectJobsInGroup(const std::string& group_name) const {
return base_.NumUnassignedConnectJobsInGroup(group_name);
}
int NumConnectJobsInGroup(const std::string& group_name) const {
return base_.NumConnectJobsInGroup(group_name);
}
int NumActiveSocketsInGroup(const std::string& group_name) const {
return base_.NumActiveSocketsInGroup(group_name);
}
bool HasGroup(const std::string& group_name) const {
return base_.HasGroup(group_name);
}
void CleanupTimedOutIdleSockets() { base_.CleanupIdleSockets(false); }
void EnableConnectBackupJobs() { base_.EnableConnectBackupJobs(); }
bool CloseOneIdleConnectionInHigherLayeredPool() {
return base_.CloseOneIdleConnectionInHigherLayeredPool();
}
private:
TestClientSocketPoolBase base_;
DISALLOW_COPY_AND_ASSIGN(TestClientSocketPool);
};
} // namespace
namespace {
void MockClientSocketFactory::SignalJobs() {
for (std::vector<TestConnectJob*>::iterator it = waiting_jobs_.begin();
it != waiting_jobs_.end(); ++it) {
(*it)->Signal();
}
waiting_jobs_.clear();
}
void MockClientSocketFactory::SignalJob(size_t job) {
ASSERT_LT(job, waiting_jobs_.size());
waiting_jobs_[job]->Signal();
waiting_jobs_.erase(waiting_jobs_.begin() + job);
}
void MockClientSocketFactory::SetJobLoadState(size_t job,
LoadState load_state) {
ASSERT_LT(job, waiting_jobs_.size());
waiting_jobs_[job]->set_load_state(load_state);
}
class TestConnectJobDelegate : public ConnectJob::Delegate {
public:
TestConnectJobDelegate()
: have_result_(false), waiting_for_result_(false), result_(OK) {}
~TestConnectJobDelegate() override = default;
void OnConnectJobComplete(int result, ConnectJob* job) override {
result_ = result;
std::unique_ptr<ConnectJob> owned_job(job);
std::unique_ptr<StreamSocket> socket = owned_job->PassSocket();
// socket.get() should be NULL iff result != OK
EXPECT_EQ(socket == NULL, result != OK);
have_result_ = true;
if (waiting_for_result_)
base::RunLoop::QuitCurrentWhenIdleDeprecated();
}
int WaitForResult() {
DCHECK(!waiting_for_result_);
while (!have_result_) {
waiting_for_result_ = true;
base::RunLoop().Run();
waiting_for_result_ = false;
}
have_result_ = false; // auto-reset for next callback
return result_;
}
private:
bool have_result_;
bool waiting_for_result_;
int result_;
};
class ClientSocketPoolBaseTest : public testing::Test {
protected:
ClientSocketPoolBaseTest() : params_(new TestSocketParams()) {
connect_backup_jobs_enabled_ =
internal::ClientSocketPoolBaseHelper::connect_backup_jobs_enabled();
internal::ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(true);
}
~ClientSocketPoolBaseTest() override {
internal::ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(
connect_backup_jobs_enabled_);
}
void CreatePool(int max_sockets, int max_sockets_per_group) {
CreatePoolWithIdleTimeouts(
max_sockets,
max_sockets_per_group,
ClientSocketPool::unused_idle_socket_timeout(),
ClientSocketPool::used_idle_socket_timeout());
}
void CreatePoolWithIdleTimeouts(
int max_sockets, int max_sockets_per_group,
base::TimeDelta unused_idle_socket_timeout,
base::TimeDelta used_idle_socket_timeout) {
DCHECK(!pool_.get());
connect_job_factory_ = new TestConnectJobFactory(&client_socket_factory_,
&net_log_);
pool_.reset(new TestClientSocketPool(max_sockets,
max_sockets_per_group,
unused_idle_socket_timeout,
used_idle_socket_timeout,
connect_job_factory_));
}
int StartRequestWithIgnoreLimits(
const std::string& group_name,
RequestPriority priority,
ClientSocketPool::RespectLimits respect_limits) {
return test_base_.StartRequestUsingPool(pool_.get(), group_name, priority,
respect_limits, params_);
}
int StartRequest(const std::string& group_name, RequestPriority priority) {
return StartRequestWithIgnoreLimits(
group_name, priority, ClientSocketPool::RespectLimits::ENABLED);
}
int GetOrderOfRequest(size_t index) const {
return test_base_.GetOrderOfRequest(index);
}
bool ReleaseOneConnection(ClientSocketPoolTest::KeepAlive keep_alive) {
return test_base_.ReleaseOneConnection(keep_alive);
}
void ReleaseAllConnections(ClientSocketPoolTest::KeepAlive keep_alive) {
test_base_.ReleaseAllConnections(keep_alive);
}
TestSocketRequest* request(int i) { return test_base_.request(i); }
size_t requests_size() const { return test_base_.requests_size(); }
std::vector<std::unique_ptr<TestSocketRequest>>* requests() {
return test_base_.requests();
}
// Only counts the requests that get sockets asynchronously;
// synchronous completions are not registered by this count.
size_t completion_count() const { return test_base_.completion_count(); }
TestNetLog net_log_;
bool connect_backup_jobs_enabled_;
MockClientSocketFactory client_socket_factory_;
TestConnectJobFactory* connect_job_factory_;
scoped_refptr<TestSocketParams> params_;
std::unique_ptr<TestClientSocketPool> pool_;
ClientSocketPoolTest test_base_;
};
// Even though a timeout is specified, it doesn't time out on a synchronous
// completion.
TEST_F(ClientSocketPoolBaseTest, ConnectJob_NoTimeoutOnSynchronousCompletion) {
TestConnectJobDelegate delegate;
ClientSocketHandle ignored;
TestClientSocketPoolBase::Request request(
&ignored, CompletionCallback(), DEFAULT_PRIORITY, SocketTag(),
ClientSocketPool::RespectLimits::ENABLED,
internal::ClientSocketPoolBaseHelper::NORMAL, params_,
NetLogWithSource());
std::unique_ptr<TestConnectJob> job(
new TestConnectJob(TestConnectJob::kMockJob, "a", request,
base::TimeDelta::FromMicroseconds(1), &delegate,
&client_socket_factory_, NULL));
EXPECT_THAT(job->Connect(), IsOk());
}
TEST_F(ClientSocketPoolBaseTest, ConnectJob_TimedOut) {
TestConnectJobDelegate delegate;
ClientSocketHandle ignored;
TestNetLog log;
TestClientSocketPoolBase::Request request(
&ignored, CompletionCallback(), DEFAULT_PRIORITY, SocketTag(),
ClientSocketPool::RespectLimits::ENABLED,
internal::ClientSocketPoolBaseHelper::NORMAL, params_,
NetLogWithSource());
// Deleted by TestConnectJobDelegate.
TestConnectJob* job =
new TestConnectJob(TestConnectJob::kMockPendingJob,
"a",
request,
base::TimeDelta::FromMicroseconds(1),
&delegate,
&client_socket_factory_,
&log);
ASSERT_THAT(job->Connect(), IsError(ERR_IO_PENDING));
base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(1));
EXPECT_THAT(delegate.WaitForResult(), IsError(ERR_TIMED_OUT));
TestNetLogEntry::List entries;
log.GetEntries(&entries);
EXPECT_EQ(6u, entries.size());
EXPECT_TRUE(LogContainsBeginEvent(entries, 0,
NetLogEventType::SOCKET_POOL_CONNECT_JOB));
EXPECT_TRUE(LogContainsBeginEvent(
entries, 1, NetLogEventType::SOCKET_POOL_CONNECT_JOB_CONNECT));
EXPECT_TRUE(LogContainsEvent(entries, 2,
NetLogEventType::CONNECT_JOB_SET_SOCKET,
NetLogEventPhase::NONE));
EXPECT_TRUE(LogContainsEvent(
entries, 3, NetLogEventType::SOCKET_POOL_CONNECT_JOB_TIMED_OUT,
NetLogEventPhase::NONE));
EXPECT_TRUE(LogContainsEndEvent(
entries, 4, NetLogEventType::SOCKET_POOL_CONNECT_JOB_CONNECT));
EXPECT_TRUE(LogContainsEndEvent(entries, 5,
NetLogEventType::SOCKET_POOL_CONNECT_JOB));
}
TEST_F(ClientSocketPoolBaseTest, BasicSynchronous) {
CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup);
TestCompletionCallback callback;
ClientSocketHandle handle;
BoundTestNetLog log;
TestLoadTimingInfoNotConnected(handle);
EXPECT_EQ(OK, handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(),
ClientSocketPool::RespectLimits::ENABLED,
callback.callback(), pool_.get(), log.bound()));
EXPECT_TRUE(handle.is_initialized());
EXPECT_TRUE(handle.socket());
TestLoadTimingInfoConnectedNotReused(handle);
handle.Reset();
TestLoadTimingInfoNotConnected(handle);
TestNetLogEntry::List entries;
log.GetEntries(&entries);
EXPECT_EQ(4u, entries.size());
EXPECT_TRUE(LogContainsBeginEvent(entries, 0, NetLogEventType::SOCKET_POOL));
EXPECT_TRUE(LogContainsEvent(
entries, 1, NetLogEventType::SOCKET_POOL_BOUND_TO_CONNECT_JOB,
NetLogEventPhase::NONE));
EXPECT_TRUE(LogContainsEvent(entries, 2,
NetLogEventType::SOCKET_POOL_BOUND_TO_SOCKET,
NetLogEventPhase::NONE));
EXPECT_TRUE(LogContainsEndEvent(entries, 3, NetLogEventType::SOCKET_POOL));
}
TEST_F(ClientSocketPoolBaseTest, InitConnectionFailure) {
CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup);
connect_job_factory_->set_job_type(TestConnectJob::kMockFailingJob);
BoundTestNetLog log;
ClientSocketHandle handle;
TestCompletionCallback callback;
// Set the additional error state members to ensure that they get cleared.
handle.set_is_ssl_error(true);
HttpResponseInfo info;
info.headers = new HttpResponseHeaders(std::string());
handle.set_ssl_error_response_info(info);
EXPECT_EQ(ERR_CONNECTION_FAILED,
handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(),
ClientSocketPool::RespectLimits::ENABLED,
callback.callback(), pool_.get(), log.bound()));
EXPECT_FALSE(handle.socket());
EXPECT_FALSE(handle.is_ssl_error());
EXPECT_TRUE(handle.ssl_error_response_info().headers.get() == NULL);
TestLoadTimingInfoNotConnected(handle);
TestNetLogEntry::List entries;
log.GetEntries(&entries);
EXPECT_EQ(3u, entries.size());
EXPECT_TRUE(LogContainsBeginEvent(entries, 0, NetLogEventType::SOCKET_POOL));
EXPECT_TRUE(LogContainsEvent(
entries, 1, NetLogEventType::SOCKET_POOL_BOUND_TO_CONNECT_JOB,
NetLogEventPhase::NONE));
EXPECT_TRUE(LogContainsEndEvent(entries, 2, NetLogEventType::SOCKET_POOL));
}
TEST_F(ClientSocketPoolBaseTest, TotalLimit) {
CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup);
// TODO(eroman): Check that the NetLog contains this event.
EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk());
EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsOk());
EXPECT_THAT(StartRequest("c", DEFAULT_PRIORITY), IsOk());
EXPECT_THAT(StartRequest("d", DEFAULT_PRIORITY), IsOk());
EXPECT_EQ(static_cast<int>(requests_size()),
client_socket_factory_.allocation_count());
EXPECT_EQ(requests_size() - kDefaultMaxSockets, completion_count());
EXPECT_THAT(StartRequest("e", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING));
EXPECT_THAT(StartRequest("f", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING));
EXPECT_THAT(StartRequest("g", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING));
ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE);
EXPECT_EQ(static_cast<int>(requests_size()),
client_socket_factory_.allocation_count());
EXPECT_EQ(requests_size() - kDefaultMaxSockets, completion_count());
EXPECT_EQ(1, GetOrderOfRequest(1));
EXPECT_EQ(2, GetOrderOfRequest(2));
EXPECT_EQ(3, GetOrderOfRequest(3));
EXPECT_EQ(4, GetOrderOfRequest(4));
EXPECT_EQ(5, GetOrderOfRequest(5));
EXPECT_EQ(6, GetOrderOfRequest(6));
EXPECT_EQ(7, GetOrderOfRequest(7));
// Make sure we test order of all requests made.
EXPECT_EQ(ClientSocketPoolTest::kIndexOutOfBounds, GetOrderOfRequest(8));
}
TEST_F(ClientSocketPoolBaseTest, TotalLimitReachedNewGroup) {
CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup);
// TODO(eroman): Check that the NetLog contains this event.
// Reach all limits: max total sockets, and max sockets per group.
EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk());
EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk());
EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsOk());
EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsOk());
EXPECT_EQ(static_cast<int>(requests_size()),
client_socket_factory_.allocation_count());
EXPECT_EQ(requests_size() - kDefaultMaxSockets, completion_count());
// Now create a new group and verify that we don't starve it.
EXPECT_THAT(StartRequest("c", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING));
ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE);
EXPECT_EQ(static_cast<int>(requests_size()),
client_socket_factory_.allocation_count());
EXPECT_EQ(requests_size() - kDefaultMaxSockets, completion_count());
EXPECT_EQ(1, GetOrderOfRequest(1));
EXPECT_EQ(2, GetOrderOfRequest(2));
EXPECT_EQ(3, GetOrderOfRequest(3));
EXPECT_EQ(4, GetOrderOfRequest(4));
EXPECT_EQ(5, GetOrderOfRequest(5));
// Make sure we test order of all requests made.
EXPECT_EQ(ClientSocketPoolTest::kIndexOutOfBounds, GetOrderOfRequest(6));
}
TEST_F(ClientSocketPoolBaseTest, TotalLimitRespectsPriority) {
CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup);
EXPECT_THAT(StartRequest("b", LOWEST), IsOk());
EXPECT_THAT(StartRequest("a", MEDIUM), IsOk());
EXPECT_THAT(StartRequest("b", HIGHEST), IsOk());
EXPECT_THAT(StartRequest("a", LOWEST), IsOk());
EXPECT_EQ(static_cast<int>(requests_size()),
client_socket_factory_.allocation_count());
EXPECT_THAT(StartRequest("c", LOWEST), IsError(ERR_IO_PENDING));
EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING));
EXPECT_THAT(StartRequest("b", HIGHEST), IsError(ERR_IO_PENDING));
ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE);
EXPECT_EQ(requests_size() - kDefaultMaxSockets, completion_count());