forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspdy_network_transaction_unittest.cc
8172 lines (6932 loc) · 317 KB
/
spdy_network_transaction_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 <cmath>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/run_loop.h"
#include "base/strings/string_piece.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/test_file_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "net/base/auth.h"
#include "net/base/chunked_upload_data_stream.h"
#include "net/base/completion_once_callback.h"
#include "net/base/elements_upload_data_stream.h"
#include "net/base/proxy_delegate.h"
#include "net/base/proxy_server.h"
#include "net/base/request_priority.h"
#include "net/base/test_proxy_delegate.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/dns/mock_host_resolver.h"
#include "net/http/http_auth_scheme.h"
#include "net/http/http_network_session.h"
#include "net/http/http_network_session_peer.h"
#include "net/http/http_network_transaction.h"
#include "net/http/http_response_info.h"
#include "net/http/http_server_properties.h"
#include "net/http/http_transaction_test_util.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_with_source.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_pool_base.h"
#include "net/socket/next_proto.h"
#include "net/socket/socket_tag.h"
#include "net/spdy/buffered_spdy_framer.h"
#include "net/spdy/spdy_http_stream.h"
#include "net/spdy/spdy_http_utils.h"
#include "net/spdy/spdy_session.h"
#include "net/spdy/spdy_session_pool.h"
#include "net/spdy/spdy_test_util_common.h"
#include "net/ssl/ssl_connection_status_flags.h"
#include "net/test/cert_test_util.h"
#include "net/test/gtest_util.h"
#include "net/test/test_data_directory.h"
#include "net/test/test_with_scoped_task_environment.h"
#include "net/third_party/spdy/core/spdy_protocol.h"
#include "net/third_party/spdy/core/spdy_test_utils.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/url_request_test_util.h"
#include "net/websockets/websocket_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/platform_test.h"
using net::test::IsError;
using net::test::IsOk;
//-----------------------------------------------------------------------------
namespace net {
namespace {
using testing::Each;
using testing::Eq;
const int32_t kBufferSize = SpdyHttpStream::kRequestBodyBufferSize;
} // namespace
const char kPushedUrl[] = "https://www.example.org/foo.dat";
class SpdyNetworkTransactionTest : public TestWithScopedTaskEnvironment {
protected:
SpdyNetworkTransactionTest()
: default_url_(kDefaultUrl),
host_port_pair_(HostPortPair::FromURL(default_url_)) {}
~SpdyNetworkTransactionTest() override {
// UploadDataStream may post a deletion task back to the message loop on
// destruction.
upload_data_stream_.reset();
base::RunLoop().RunUntilIdle();
}
void SetUp() override {
request_.method = "GET";
request_.url = GURL(kDefaultUrl);
request_.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
}
struct TransactionHelperResult {
int rv;
std::string status_line;
std::string response_data;
HttpResponseInfo response_info;
};
// A helper class that handles all the initial npn/ssl setup.
class NormalSpdyTransactionHelper {
public:
NormalSpdyTransactionHelper(
const HttpRequestInfo& request,
RequestPriority priority,
const NetLogWithSource& log,
std::unique_ptr<SpdySessionDependencies> session_deps)
: request_(request),
priority_(priority),
session_deps_(session_deps.get() == nullptr
? std::make_unique<SpdySessionDependencies>()
: std::move(session_deps)),
log_(log) {
session_deps_->net_log = log.net_log();
session_ =
SpdySessionDependencies::SpdyCreateSession(session_deps_.get());
}
~NormalSpdyTransactionHelper() {
// Any test which doesn't close the socket by sending it an EOF will
// have a valid session left open, which leaks the entire session pool.
// This is just fine - in fact, some of our tests intentionally do this
// so that we can check consistency of the SpdySessionPool as the test
// finishes. If we had put an EOF on the socket, the SpdySession would
// have closed and we wouldn't be able to check the consistency.
// Forcefully close existing sessions here.
session()->spdy_session_pool()->CloseAllSessions();
}
void RunPreTestSetup() {
// We're now ready to use SSL-npn SPDY.
trans_ =
std::make_unique<HttpNetworkTransaction>(priority_, session_.get());
}
// Start the transaction, read some data, finish.
void RunDefaultTest() {
if (!StartDefaultTest())
return;
FinishDefaultTest();
}
bool StartDefaultTest() {
output_.rv = trans_->Start(&request_, callback_.callback(), log_);
// We expect an IO Pending or some sort of error.
EXPECT_LT(output_.rv, 0);
return output_.rv == ERR_IO_PENDING;
}
void FinishDefaultTest() {
output_.rv = callback_.WaitForResult();
// Finish async network reads/writes.
base::RunLoop().RunUntilIdle();
if (output_.rv != OK) {
session_->spdy_session_pool()->CloseCurrentSessions(ERR_ABORTED);
return;
}
// Verify responses.
const HttpResponseInfo* response = trans_->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(HttpResponseInfo::CONNECTION_INFO_HTTP2,
response->connection_info);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
EXPECT_EQ("127.0.0.1", response->socket_address.host());
EXPECT_EQ(443, response->socket_address.port());
output_.status_line = response->headers->GetStatusLine();
output_.response_info = *response; // Make a copy so we can verify.
output_.rv = ReadTransaction(trans_.get(), &output_.response_data);
}
void FinishDefaultTestWithoutVerification() {
output_.rv = callback_.WaitForResult();
// Finish async network reads/writes.
base::RunLoop().RunUntilIdle();
if (output_.rv != OK)
session_->spdy_session_pool()->CloseCurrentSessions(ERR_ABORTED);
}
void WaitForCallbackToComplete() { output_.rv = callback_.WaitForResult(); }
// Most tests will want to call this function. In particular, the MockReads
// should end with an empty read, and that read needs to be processed to
// ensure proper deletion of the spdy_session_pool.
void VerifyDataConsumed() {
for (const SocketDataProvider* provider : data_vector_) {
EXPECT_TRUE(provider->AllReadDataConsumed());
EXPECT_TRUE(provider->AllWriteDataConsumed());
}
}
// Occasionally a test will expect to error out before certain reads are
// processed. In that case we want to explicitly ensure that the reads were
// not processed.
void VerifyDataNotConsumed() {
for (const SocketDataProvider* provider : data_vector_) {
EXPECT_FALSE(provider->AllReadDataConsumed());
EXPECT_FALSE(provider->AllWriteDataConsumed());
}
}
void RunToCompletion(SocketDataProvider* data) {
RunPreTestSetup();
AddData(data);
RunDefaultTest();
VerifyDataConsumed();
}
void RunToCompletionWithSSLData(
SocketDataProvider* data,
std::unique_ptr<SSLSocketDataProvider> ssl_provider) {
RunPreTestSetup();
AddDataWithSSLSocketDataProvider(data, std::move(ssl_provider));
RunDefaultTest();
VerifyDataConsumed();
}
void AddData(SocketDataProvider* data) {
auto ssl_provider = std::make_unique<SSLSocketDataProvider>(ASYNC, OK);
ssl_provider->ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem");
AddDataWithSSLSocketDataProvider(data, std::move(ssl_provider));
}
void AddDataWithSSLSocketDataProvider(
SocketDataProvider* data,
std::unique_ptr<SSLSocketDataProvider> ssl_provider) {
data_vector_.push_back(data);
if (ssl_provider->next_proto == kProtoUnknown)
ssl_provider->next_proto = kProtoHTTP2;
session_deps_->socket_factory->AddSSLSocketDataProvider(
ssl_provider.get());
ssl_vector_.push_back(std::move(ssl_provider));
session_deps_->socket_factory->AddSocketDataProvider(data);
}
HttpNetworkTransaction* trans() { return trans_.get(); }
void ResetTrans() { trans_.reset(); }
const TransactionHelperResult& output() { return output_; }
HttpNetworkSession* session() const { return session_.get(); }
SpdySessionDependencies* session_deps() { return session_deps_.get(); }
private:
typedef std::vector<SocketDataProvider*> DataVector;
typedef std::vector<std::unique_ptr<SSLSocketDataProvider>> SSLVector;
typedef std::vector<std::unique_ptr<SocketDataProvider>> AlternateVector;
const HttpRequestInfo request_;
const RequestPriority priority_;
std::unique_ptr<SpdySessionDependencies> session_deps_;
std::unique_ptr<HttpNetworkSession> session_;
TransactionHelperResult output_;
SSLVector ssl_vector_;
TestCompletionCallback callback_;
std::unique_ptr<HttpNetworkTransaction> trans_;
DataVector data_vector_;
const NetLogWithSource log_;
};
void ConnectStatusHelperWithExpectedStatus(const MockRead& status,
int expected_status);
void ConnectStatusHelper(const MockRead& status);
HttpRequestInfo CreateGetPushRequest() const WARN_UNUSED_RESULT {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL(kPushedUrl);
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
return request;
}
void UsePostRequest() {
ASSERT_FALSE(upload_data_stream_);
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(std::make_unique<UploadBytesElementReader>(
kUploadData, kUploadDataSize));
upload_data_stream_ = std::make_unique<ElementsUploadDataStream>(
std::move(element_readers), 0);
request_.method = "POST";
request_.upload_data_stream = upload_data_stream_.get();
}
void UseFilePostRequest() {
ASSERT_FALSE(upload_data_stream_);
base::FilePath file_path;
CHECK(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &file_path));
CHECK_EQ(static_cast<int>(kUploadDataSize),
base::WriteFile(file_path, kUploadData, kUploadDataSize));
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(std::make_unique<UploadFileElementReader>(
base::ThreadTaskRunnerHandle::Get().get(), file_path, 0,
kUploadDataSize, base::Time()));
upload_data_stream_ = std::make_unique<ElementsUploadDataStream>(
std::move(element_readers), 0);
request_.method = "POST";
request_.upload_data_stream = upload_data_stream_.get();
request_.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
}
void UseUnreadableFilePostRequest() {
ASSERT_FALSE(upload_data_stream_);
base::FilePath file_path;
CHECK(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &file_path));
CHECK_EQ(static_cast<int>(kUploadDataSize),
base::WriteFile(file_path, kUploadData, kUploadDataSize));
CHECK(base::MakeFileUnreadable(file_path));
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(std::make_unique<UploadFileElementReader>(
base::ThreadTaskRunnerHandle::Get().get(), file_path, 0,
kUploadDataSize, base::Time()));
upload_data_stream_ = std::make_unique<ElementsUploadDataStream>(
std::move(element_readers), 0);
request_.method = "POST";
request_.upload_data_stream = upload_data_stream_.get();
}
void UseComplexPostRequest() {
ASSERT_FALSE(upload_data_stream_);
const int kFileRangeOffset = 1;
const int kFileRangeLength = 3;
CHECK_LT(kFileRangeOffset + kFileRangeLength, kUploadDataSize);
base::FilePath file_path;
CHECK(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &file_path));
CHECK_EQ(static_cast<int>(kUploadDataSize),
base::WriteFile(file_path, kUploadData, kUploadDataSize));
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(std::make_unique<UploadBytesElementReader>(
kUploadData, kFileRangeOffset));
element_readers.push_back(std::make_unique<UploadFileElementReader>(
base::ThreadTaskRunnerHandle::Get().get(), file_path, kFileRangeOffset,
kFileRangeLength, base::Time()));
element_readers.push_back(std::make_unique<UploadBytesElementReader>(
kUploadData + kFileRangeOffset + kFileRangeLength,
kUploadDataSize - (kFileRangeOffset + kFileRangeLength)));
upload_data_stream_ = std::make_unique<ElementsUploadDataStream>(
std::move(element_readers), 0);
request_.method = "POST";
request_.upload_data_stream = upload_data_stream_.get();
}
void UseChunkedPostRequest() {
ASSERT_FALSE(upload_chunked_data_stream_);
upload_chunked_data_stream_ = std::make_unique<ChunkedUploadDataStream>(0);
request_.method = "POST";
request_.upload_data_stream = upload_chunked_data_stream_.get();
}
// Read the result of a particular transaction, knowing that we've got
// multiple transactions in the read pipeline; so as we read, we may have
// to skip over data destined for other transactions while we consume
// the data for |trans|.
int ReadResult(HttpNetworkTransaction* trans, std::string* result) {
const int kSize = 3000;
int bytes_read = 0;
scoped_refptr<IOBufferWithSize> buf =
base::MakeRefCounted<IOBufferWithSize>(kSize);
TestCompletionCallback callback;
while (true) {
int rv = trans->Read(buf.get(), kSize, callback.callback());
if (rv == ERR_IO_PENDING) {
rv = callback.WaitForResult();
} else if (rv <= 0) {
break;
}
result->append(buf->data(), rv);
bytes_read += rv;
}
return bytes_read;
}
void VerifyStreamsClosed(const NormalSpdyTransactionHelper& helper) {
// This lengthy block is reaching into the pool to dig out the active
// session. Once we have the session, we verify that the streams are
// all closed and not leaked at this point.
SpdySessionKey key(HostPortPair::FromURL(request_.url),
ProxyServer::Direct(), PRIVACY_MODE_DISABLED,
SocketTag());
HttpNetworkSession* session = helper.session();
base::WeakPtr<SpdySession> spdy_session =
session->spdy_session_pool()->FindAvailableSession(
key, /* enable_ip_based_pooling = */ true,
/* is_websocket = */ false, log_);
ASSERT_TRUE(spdy_session);
EXPECT_EQ(0u, num_active_streams(spdy_session));
EXPECT_EQ(0u, num_unclaimed_pushed_streams(spdy_session));
}
void RunServerPushTest(SequencedSocketData* data,
HttpResponseInfo* response,
HttpResponseInfo* push_response,
const std::string& expected) {
NormalSpdyTransactionHelper helper(request_, DEFAULT_PRIORITY, log_,
nullptr);
helper.RunPreTestSetup();
helper.AddData(data);
HttpNetworkTransaction* trans = helper.trans();
// Start the transaction with basic parameters.
TestCompletionCallback callback;
int rv = trans->Start(&request_, callback.callback(), log_);
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
// Finish async network reads/writes.
base::RunLoop().RunUntilIdle();
// Request the pushed path.
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, helper.session());
HttpRequestInfo request = CreateGetPushRequest();
rv = trans2.Start(&request, callback.callback(), log_);
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
base::RunLoop().RunUntilIdle();
// The data for the pushed path may be coming in more than 1 frame. Compile
// the results into a single string.
// Read the server push body.
std::string result2;
ReadResult(&trans2, &result2);
// Read the response body.
std::string result;
ReadResult(trans, &result);
// Verify that we consumed all test data.
EXPECT_TRUE(data->AllReadDataConsumed());
EXPECT_TRUE(data->AllWriteDataConsumed());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
EXPECT_TRUE(load_timing_info.push_start.is_null());
EXPECT_TRUE(load_timing_info.push_end.is_null());
LoadTimingInfo load_timing_info2;
EXPECT_TRUE(trans2.GetLoadTimingInfo(&load_timing_info2));
EXPECT_FALSE(load_timing_info2.push_start.is_null());
EXPECT_FALSE(load_timing_info2.push_end.is_null());
// Verify that the received push data is same as the expected push data.
EXPECT_EQ(result2.compare(expected), 0) << "Received data: "
<< result2
<< "||||| Expected data: "
<< expected;
// Verify the response HEADERS.
// Copy the response info, because trans goes away.
*response = *trans->GetResponseInfo();
*push_response = *trans2.GetResponseInfo();
VerifyStreamsClosed(helper);
}
void RunBrokenPushTest(SequencedSocketData* data, int expected_rv) {
NormalSpdyTransactionHelper helper(request_, DEFAULT_PRIORITY, log_,
nullptr);
helper.RunPreTestSetup();
helper.AddData(data);
HttpNetworkTransaction* trans = helper.trans();
// Start the transaction with basic parameters.
TestCompletionCallback callback;
int rv = trans->Start(&request_, callback.callback(), log_);
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_EQ(expected_rv, rv);
// Finish async network reads/writes.
base::RunLoop().RunUntilIdle();
// Verify that we consumed all test data.
EXPECT_TRUE(data->AllReadDataConsumed());
EXPECT_TRUE(data->AllWriteDataConsumed());
if (expected_rv == OK) {
// Expected main request to succeed, even if push failed.
HttpResponseInfo response = *trans->GetResponseInfo();
EXPECT_TRUE(response.headers);
EXPECT_EQ("HTTP/1.1 200", response.headers->GetStatusLine());
}
}
static void DeleteSessionCallback(NormalSpdyTransactionHelper* helper,
int result) {
helper->ResetTrans();
}
static void StartTransactionCallback(HttpNetworkSession* session,
GURL url,
NetLogWithSource log,
int result) {
HttpRequestInfo request;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session);
TestCompletionCallback callback;
request.method = "GET";
request.url = url;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
int rv = trans.Start(&request, callback.callback(), log);
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
callback.WaitForResult();
}
ChunkedUploadDataStream* upload_chunked_data_stream() {
return upload_chunked_data_stream_.get();
}
size_t num_active_streams(base::WeakPtr<SpdySession> session) {
return session->active_streams_.size();
}
static size_t num_unclaimed_pushed_streams(
base::WeakPtr<SpdySession> session) {
return session->pool_->push_promise_index()->CountStreamsForSession(
session.get());
}
static bool has_unclaimed_pushed_stream_for_url(
base::WeakPtr<SpdySession> session,
const GURL& url) {
return session->pool_->push_promise_index()->FindStream(
url, session.get()) != kNoPushedStreamFound;
}
static spdy::SpdyStreamId spdy_stream_hi_water_mark(
base::WeakPtr<SpdySession> session) {
return session->stream_hi_water_mark_;
}
const GURL default_url_;
const HostPortPair host_port_pair_;
HttpRequestInfo request_;
SpdyTestUtil spdy_util_;
const NetLogWithSource log_;
private:
std::unique_ptr<ChunkedUploadDataStream> upload_chunked_data_stream_;
std::unique_ptr<UploadDataStream> upload_data_stream_;
base::ScopedTempDir temp_dir_;
};
// Verify HttpNetworkTransaction constructor.
TEST_F(SpdyNetworkTransactionTest, Constructor) {
auto session_deps = std::make_unique<SpdySessionDependencies>();
std::unique_ptr<HttpNetworkSession> session(
SpdySessionDependencies::SpdyCreateSession(session_deps.get()));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
}
TEST_F(SpdyNetworkTransactionTest, Get) {
// Construct the request.
spdy::SpdySerializedFrame req(
spdy_util_.ConstructSpdyGet(nullptr, 0, 1, LOWEST));
MockWrite writes[] = {CreateMockWrite(req, 0)};
spdy::SpdySerializedFrame resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead reads[] = {
CreateMockRead(resp, 1), CreateMockRead(body, 2),
MockRead(ASYNC, 0, 3) // EOF
};
SequencedSocketData data(reads, writes);
NormalSpdyTransactionHelper helper(request_, DEFAULT_PRIORITY, log_, nullptr);
helper.RunToCompletion(&data);
TransactionHelperResult out = helper.output();
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200", out.status_line);
EXPECT_EQ("hello!", out.response_data);
}
TEST_F(SpdyNetworkTransactionTest, SetPriority) {
for (bool set_priority_before_starting_transaction : {true, false}) {
SpdyTestUtil spdy_test_util;
spdy::SpdySerializedFrame req(
spdy_test_util.ConstructSpdyGet(nullptr, 0, 1, LOWEST));
MockWrite writes[] = {CreateMockWrite(req, 0)};
spdy::SpdySerializedFrame resp(
spdy_test_util.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body(
spdy_test_util.ConstructSpdyDataFrame(1, true));
MockRead reads[] = {CreateMockRead(resp, 1), CreateMockRead(body, 2),
MockRead(ASYNC, 0, 3)};
SequencedSocketData data(reads, writes);
NormalSpdyTransactionHelper helper(request_, HIGHEST, log_, nullptr);
helper.RunPreTestSetup();
helper.AddData(&data);
if (set_priority_before_starting_transaction) {
helper.trans()->SetPriority(LOWEST);
EXPECT_TRUE(helper.StartDefaultTest());
} else {
EXPECT_TRUE(helper.StartDefaultTest());
helper.trans()->SetPriority(LOWEST);
}
helper.FinishDefaultTest();
helper.VerifyDataConsumed();
TransactionHelperResult out = helper.output();
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200", out.status_line);
EXPECT_EQ("hello!", out.response_data);
}
}
// Test that changing the request priority of an existing stream triggers
// sending PRIORITY frames in case there are multiple open streams and their
// relative priorities change.
TEST_F(SpdyNetworkTransactionTest, SetPriorityOnExistingStream) {
const char* kUrl2 = "https://www.example.org/bar";
spdy::SpdySerializedFrame req1(
spdy_util_.ConstructSpdyGet(nullptr, 0, 1, HIGHEST));
spdy::SpdySerializedFrame req2(spdy_util_.ConstructSpdyGet(kUrl2, 3, MEDIUM));
spdy::SpdySerializedFrame priority1(
spdy_util_.ConstructSpdyPriority(3, 0, MEDIUM, true));
spdy::SpdySerializedFrame priority2(
spdy_util_.ConstructSpdyPriority(1, 3, LOWEST, true));
MockWrite writes[] = {CreateMockWrite(req1, 0), CreateMockWrite(req2, 2),
CreateMockWrite(priority1, 4),
CreateMockWrite(priority2, 5)};
spdy::SpdySerializedFrame resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame body1(spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame body2(spdy_util_.ConstructSpdyDataFrame(3, true));
MockRead reads[] = {CreateMockRead(resp1, 1), CreateMockRead(resp2, 3),
CreateMockRead(body1, 6), CreateMockRead(body2, 7),
MockRead(ASYNC, 0, 8)};
SequencedSocketData data(reads, writes);
NormalSpdyTransactionHelper helper(request_, HIGHEST, log_, nullptr);
helper.RunPreTestSetup();
helper.AddData(&data);
EXPECT_TRUE(helper.StartDefaultTest());
// Open HTTP/2 connection and create first stream.
base::RunLoop().RunUntilIdle();
HttpNetworkTransaction trans2(MEDIUM, helper.session());
HttpRequestInfo request2;
request2.url = GURL(kUrl2);
request2.method = "GET";
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback2;
int rv = trans2.Start(&request2, callback2.callback(), log_);
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Create second stream.
base::RunLoop().RunUntilIdle();
// First request has HIGHEST priority, second request has MEDIUM priority.
// Changing the priority of the first request to LOWEST changes their order,
// and therefore triggers sending PRIORITY frames.
helper.trans()->SetPriority(LOWEST);
helper.FinishDefaultTest();
helper.VerifyDataConsumed();
TransactionHelperResult out = helper.output();
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200", out.status_line);
EXPECT_EQ("hello!", out.response_data);
rv = callback2.WaitForResult();
ASSERT_THAT(rv, IsOk());
const HttpResponseInfo* response2 = trans2.GetResponseInfo();
ASSERT_TRUE(response2);
ASSERT_TRUE(response2->headers);
EXPECT_EQ(HttpResponseInfo::CONNECTION_INFO_HTTP2,
response2->connection_info);
EXPECT_EQ("HTTP/1.1 200", response2->headers->GetStatusLine());
}
// Create two requests: a lower priority one first, then a higher priority one.
// Test that the second request gets sent out first.
TEST_F(SpdyNetworkTransactionTest, RequestsOrderedByPriority) {
const char* kUrl2 = "https://www.example.org/foo";
// First send second request on stream 1, then first request on stream 3.
spdy::SpdySerializedFrame req2(
spdy_util_.ConstructSpdyGet(kUrl2, 1, HIGHEST));
spdy::SpdySerializedFrame req1(
spdy_util_.ConstructSpdyGet(nullptr, 0, 3, LOW));
MockWrite writes[] = {CreateMockWrite(req2, 0), CreateMockWrite(req1, 1)};
spdy::SpdySerializedFrame resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame body2(
spdy_util_.ConstructSpdyDataFrame(1, "stream 1", true));
spdy::SpdySerializedFrame body1(
spdy_util_.ConstructSpdyDataFrame(3, "stream 3", true));
MockRead reads[] = {CreateMockRead(resp2, 2), CreateMockRead(body2, 3),
CreateMockRead(resp1, 4), CreateMockRead(body1, 5),
MockRead(ASYNC, 0, 6)};
SequencedSocketData data(reads, writes);
NormalSpdyTransactionHelper helper(request_, LOW, log_, nullptr);
helper.RunPreTestSetup();
helper.AddData(&data);
// Create HTTP/2 connection. This is necessary because starting the first
// transaction does not create the connection yet, so the second request
// could not use the same connection, whereas running the message loop after
// starting the first transaction would call Socket::Write() with the first
// HEADERS frame, so the second transaction could not get ahead of it.
SpdySessionKey key(HostPortPair("www.example.org", 443),
ProxyServer::Direct(), PRIVACY_MODE_DISABLED, SocketTag());
auto spdy_session = CreateSpdySession(helper.session(), key, log_);
EXPECT_TRUE(spdy_session);
// Start first transaction.
EXPECT_TRUE(helper.StartDefaultTest());
// Start second transaction.
HttpNetworkTransaction trans2(HIGHEST, helper.session());
HttpRequestInfo request2;
request2.url = GURL(kUrl2);
request2.method = "GET";
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback2;
int rv = trans2.Start(&request2, callback2.callback(), log_);
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Complete first transaction and verify results.
helper.FinishDefaultTest();
helper.VerifyDataConsumed();
TransactionHelperResult out = helper.output();
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200", out.status_line);
EXPECT_EQ("stream 3", out.response_data);
// Complete second transaction and verify results.
rv = callback2.WaitForResult();
ASSERT_THAT(rv, IsOk());
const HttpResponseInfo* response2 = trans2.GetResponseInfo();
ASSERT_TRUE(response2);
ASSERT_TRUE(response2->headers);
EXPECT_EQ(HttpResponseInfo::CONNECTION_INFO_HTTP2,
response2->connection_info);
EXPECT_EQ("HTTP/1.1 200", response2->headers->GetStatusLine());
std::string response_data;
ReadTransaction(&trans2, &response_data);
EXPECT_EQ("stream 1", response_data);
}
// Test that already enqueued HEADERS frames are reordered if their relative
// priority changes.
TEST_F(SpdyNetworkTransactionTest, QueuedFramesReorderedOnPriorityChange) {
const char* kUrl2 = "https://www.example.org/foo";
const char* kUrl3 = "https://www.example.org/bar";
spdy::SpdySerializedFrame req1(
spdy_util_.ConstructSpdyGet(nullptr, 0, 1, DEFAULT_PRIORITY));
spdy::SpdySerializedFrame req3(spdy_util_.ConstructSpdyGet(kUrl3, 3, MEDIUM));
spdy::SpdySerializedFrame req2(spdy_util_.ConstructSpdyGet(kUrl2, 5, LOWEST));
MockWrite writes[] = {MockWrite(ASYNC, ERR_IO_PENDING, 0),
CreateMockWrite(req1, 1), CreateMockWrite(req3, 2),
CreateMockWrite(req2, 3)};
spdy::SpdySerializedFrame resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame resp3(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 5));
spdy::SpdySerializedFrame body1(
spdy_util_.ConstructSpdyDataFrame(1, "stream 1", true));
spdy::SpdySerializedFrame body3(
spdy_util_.ConstructSpdyDataFrame(3, "stream 3", true));
spdy::SpdySerializedFrame body2(
spdy_util_.ConstructSpdyDataFrame(5, "stream 5", true));
MockRead reads[] = {CreateMockRead(resp1, 4), CreateMockRead(body1, 5),
CreateMockRead(resp3, 6), CreateMockRead(body3, 7),
CreateMockRead(resp2, 8), CreateMockRead(body2, 9),
MockRead(ASYNC, 0, 10)};
SequencedSocketData data(reads, writes);
// Priority of first request does not matter, because Socket::Write() will be
// called with its HEADERS frame before the other requests start.
NormalSpdyTransactionHelper helper(request_, DEFAULT_PRIORITY, log_, nullptr);
helper.RunPreTestSetup();
helper.AddData(&data);
EXPECT_TRUE(helper.StartDefaultTest());
// Open HTTP/2 connection, create HEADERS frame for first request, and call
// Socket::Write() with that frame. After this, no other request can get
// ahead of the first one.
base::RunLoop().RunUntilIdle();
HttpNetworkTransaction trans2(HIGHEST, helper.session());
HttpRequestInfo request2;
request2.url = GURL(kUrl2);
request2.method = "GET";
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback2;
int rv = trans2.Start(&request2, callback2.callback(), log_);
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
HttpNetworkTransaction trans3(MEDIUM, helper.session());
HttpRequestInfo request3;
request3.url = GURL(kUrl3);
request3.method = "GET";
request3.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback3;
rv = trans3.Start(&request3, callback3.callback(), log_);
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Create HEADERS frames for second and third request and enqueue them in
// SpdyWriteQueue with their original priorities. Writing of the first
// HEADERS frame to the socked still has not completed.
base::RunLoop().RunUntilIdle();
// Second request is of HIGHEST, third of MEDIUM priority. Changing second
// request to LOWEST changes their relative order. This should result in
// already enqueued frames being reordered within SpdyWriteQueue.
trans2.SetPriority(LOWEST);
// Complete async write of the first HEADERS frame.
data.Resume();
helper.FinishDefaultTest();
TransactionHelperResult out = helper.output();
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200", out.status_line);
EXPECT_EQ("stream 1", out.response_data);
rv = callback2.WaitForResult();
ASSERT_THAT(rv, IsOk());
const HttpResponseInfo* response2 = trans2.GetResponseInfo();
ASSERT_TRUE(response2);
ASSERT_TRUE(response2->headers);
EXPECT_EQ(HttpResponseInfo::CONNECTION_INFO_HTTP2,
response2->connection_info);
EXPECT_EQ("HTTP/1.1 200", response2->headers->GetStatusLine());
std::string response_data;
ReadTransaction(&trans2, &response_data);
EXPECT_EQ("stream 5", response_data);
rv = callback3.WaitForResult();
ASSERT_THAT(rv, IsOk());
const HttpResponseInfo* response3 = trans3.GetResponseInfo();
ASSERT_TRUE(response3);
ASSERT_TRUE(response3->headers);
EXPECT_EQ(HttpResponseInfo::CONNECTION_INFO_HTTP2,
response3->connection_info);
EXPECT_EQ("HTTP/1.1 200", response3->headers->GetStatusLine());
ReadTransaction(&trans3, &response_data);
EXPECT_EQ("stream 3", response_data);
helper.VerifyDataConsumed();
}
TEST_F(SpdyNetworkTransactionTest, GetAtEachPriority) {
for (RequestPriority p = MINIMUM_PRIORITY; p <= MAXIMUM_PRIORITY;
p = RequestPriority(p + 1)) {
SpdyTestUtil spdy_test_util;
// Construct the request.
spdy::SpdySerializedFrame req(
spdy_test_util.ConstructSpdyGet(nullptr, 0, 1, p));
MockWrite writes[] = {CreateMockWrite(req, 0)};
spdy::SpdyPriority spdy_prio = 0;
EXPECT_TRUE(GetSpdyPriority(req, &spdy_prio));
// this repeats the RequestPriority-->spdy::SpdyPriority mapping from
// spdy::SpdyFramer::ConvertRequestPriorityToSpdyPriority to make
// sure it's being done right.
switch (p) {
case HIGHEST:
EXPECT_EQ(0, spdy_prio);
break;
case MEDIUM:
EXPECT_EQ(1, spdy_prio);
break;
case LOW:
EXPECT_EQ(2, spdy_prio);
break;
case LOWEST:
EXPECT_EQ(3, spdy_prio);
break;
case IDLE:
EXPECT_EQ(4, spdy_prio);
break;
case THROTTLED:
EXPECT_EQ(5, spdy_prio);
break;
default:
FAIL();
}
spdy::SpdySerializedFrame resp(
spdy_test_util.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body(
spdy_test_util.ConstructSpdyDataFrame(1, true));
MockRead reads[] = {
CreateMockRead(resp, 1), CreateMockRead(body, 2),
MockRead(ASYNC, 0, 3) // EOF
};
SequencedSocketData data(reads, writes);
NormalSpdyTransactionHelper helper(request_, p, log_, nullptr);
helper.RunToCompletion(&data);
TransactionHelperResult out = helper.output();
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200", out.status_line);
EXPECT_EQ("hello!", out.response_data);
}
}
// Start three gets simultaniously; making sure that multiplexed
// streams work properly.
// This can't use the TransactionHelper method, since it only
// handles a single transaction, and finishes them as soon
// as it launches them.
// TODO(gavinp): create a working generalized TransactionHelper that
// can allow multiple streams in flight.
TEST_F(SpdyNetworkTransactionTest, ThreeGets) {
spdy::SpdySerializedFrame req(
spdy_util_.ConstructSpdyGet(nullptr, 0, 1, LOWEST));
spdy::SpdySerializedFrame resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body(spdy_util_.ConstructSpdyDataFrame(1, false));
spdy::SpdySerializedFrame fbody(spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame req2(
spdy_util_.ConstructSpdyGet(nullptr, 0, 3, LOWEST));
spdy::SpdySerializedFrame resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame body2(spdy_util_.ConstructSpdyDataFrame(3, false));
spdy::SpdySerializedFrame fbody2(spdy_util_.ConstructSpdyDataFrame(3, true));
spdy::SpdySerializedFrame req3(
spdy_util_.ConstructSpdyGet(nullptr, 0, 5, LOWEST));
spdy::SpdySerializedFrame resp3(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 5));
spdy::SpdySerializedFrame body3(spdy_util_.ConstructSpdyDataFrame(5, false));
spdy::SpdySerializedFrame fbody3(spdy_util_.ConstructSpdyDataFrame(5, true));
MockWrite writes[] = {
CreateMockWrite(req, 0), CreateMockWrite(req2, 3),
CreateMockWrite(req3, 6),
};
MockRead reads[] = {
CreateMockRead(resp, 1), CreateMockRead(body, 2),
CreateMockRead(resp2, 4), CreateMockRead(body2, 5),
CreateMockRead(resp3, 7), CreateMockRead(body3, 8),
CreateMockRead(fbody, 9), CreateMockRead(fbody2, 10),
CreateMockRead(fbody3, 11),
MockRead(ASYNC, 0, 12), // EOF
};
SequencedSocketData data(reads, writes);