forked from coreos/update_engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_fetcher_unittest.cc
1116 lines (949 loc) · 34.8 KB
/
http_fetcher_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 OS 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 <unistd.h>
#include <string>
#include <utility>
#include <vector>
#include <base/logging.h>
#include <base/memory/scoped_ptr.h>
#include <base/string_util.h>
#include <base/stringprintf.h>
#include <base/time.h>
#include <chromeos/dbus/service_constants.h>
#include <glib.h>
#include <gtest/gtest.h>
#include "update_engine/http_common.h"
#include "update_engine/http_fetcher_unittest.h"
#include "update_engine/libcurl_http_fetcher.h"
#include "update_engine/mock_connection_manager.h"
#include "update_engine/mock_http_fetcher.h"
#include "update_engine/mock_system_state.h"
#include "update_engine/multi_range_http_fetcher.h"
#include "update_engine/utils.h"
using std::make_pair;
using std::pair;
using std::string;
using std::vector;
using base::TimeDelta;
using testing::_;
using testing::SetArgumentPointee;
using testing::DoAll;
using testing::Return;
namespace {
const int kBigLength = 100000;
const int kMediumLength = 1000;
const int kFlakyTruncateLength = 29000;
const int kFlakySleepEvery = 3;
const int kFlakySleepSecs = 10;
} // namespace
namespace chromeos_update_engine {
static const char *kUnusedUrl = "unused://unused";
static inline string LocalServerUrlForPath(const string& path) {
return base::StringPrintf("http://127.0.0.1:%d%s", kServerPort, path.c_str());
}
//
// Class hierarchy for HTTP server implementations.
//
class HttpServer {
public:
// This makes it an abstract class (dirty but works).
virtual ~HttpServer() = 0;
bool started_;
};
HttpServer::~HttpServer() {}
class NullHttpServer : public HttpServer {
public:
NullHttpServer() {
started_ = true;
}
};
class PythonHttpServer : public HttpServer {
public:
PythonHttpServer() {
char *argv[2] = {strdup("./test_http_server"), NULL};
GError *err;
started_ = false;
validate_quit_ = true;
if (!g_spawn_async(NULL,
argv,
NULL,
G_SPAWN_DO_NOT_REAP_CHILD,
NULL,
NULL,
&pid_,
&err)) {
LOG(INFO) << "unable to spawn http server process";
return;
}
LOG(INFO) << "started http server with pid " << pid_;
int rc = 1;
const TimeDelta kMaxSleep = TimeDelta::FromMinutes(60);
TimeDelta timeout = TimeDelta::FromMilliseconds(15);
started_ = true;
while (rc && timeout < kMaxSleep) {
// Wait before the first attempt also as it takes a while for the
// test_http_server to be ready.
LOG(INFO) << "waiting for " << utils::FormatTimeDelta(timeout);
g_usleep(timeout.InMicroseconds());
timeout *= 2;
LOG(INFO) << "running wget to start";
// rc should be 0 if we're able to successfully talk to the server.
rc = system((string("wget --output-document=/dev/null ") +
LocalServerUrlForPath("/test")).c_str());
LOG(INFO) << "done running wget to start, rc = " << rc;
}
if (rc) {
LOG(ERROR) << "Http server is not responding to wget.";
// TODO(jaysri): Currently we're overloading two things in
// started_ flag. One is that the process is running and other
// is that the process is responsive. We should separate these
// two so that we can do cleanup appropriately in each case.
started_ = false;
}
free(argv[0]);
LOG(INFO) << "gdb attach now!";
}
~PythonHttpServer() {
if (!started_) {
LOG(INFO) << "not waiting for http server with pid " << pid_
<< " to terminate, as it's not responding.";
// TODO(jaysri): Kill the process if it's really running but
// wgets or failing for some reason. Or if it's not running,
// add code to get rid of the defunct process.
return;
}
// request that the server exit itself
LOG(INFO) << "running wget to exit";
int rc = system((string("wget -t 1 --output-document=/dev/null ") +
LocalServerUrlForPath("/quitquitquit")).c_str());
LOG(INFO) << "done running wget to exit";
if (validate_quit_)
EXPECT_EQ(0, rc);
LOG(INFO) << "waiting for http server with pid " << pid_ << " to terminate";
int status;
waitpid(pid_, &status, 0);
LOG(INFO) << "http server with pid " << pid_
<< " terminated with status " << status;
}
GPid pid_;
bool validate_quit_;
};
//
// Class hierarchy for HTTP fetcher test wrappers.
//
class AnyHttpFetcherTest {
public:
AnyHttpFetcherTest()
: mock_connection_manager_(&mock_system_state_) {
mock_system_state_.set_connection_manager(&mock_connection_manager_);
}
virtual HttpFetcher* NewLargeFetcher() = 0;
virtual HttpFetcher* NewSmallFetcher() = 0;
virtual string BigUrl() const { return kUnusedUrl; }
virtual string SmallUrl() const { return kUnusedUrl; }
virtual string ErrorUrl() const { return kUnusedUrl; }
virtual bool IsMock() const = 0;
virtual bool IsMulti() const = 0;
virtual void IgnoreServerAborting(HttpServer* server) const {}
virtual HttpServer *CreateServer() = 0;
protected:
MockSystemState mock_system_state_;
MockConnectionManager mock_connection_manager_;
};
class MockHttpFetcherTest : public AnyHttpFetcherTest {
public:
// Necessary to unhide the definition in the base class.
using AnyHttpFetcherTest::NewLargeFetcher;
virtual HttpFetcher* NewLargeFetcher() {
vector<char> big_data(1000000);
return new MockHttpFetcher(big_data.data(), big_data.size());
}
// Necessary to unhide the definition in the base class.
using AnyHttpFetcherTest::NewSmallFetcher;
virtual HttpFetcher* NewSmallFetcher() {
return new MockHttpFetcher("x", 1);
}
virtual bool IsMock() const { return true; }
virtual bool IsMulti() const { return false; }
virtual HttpServer *CreateServer() {
return new NullHttpServer;
}
};
class LibcurlHttpFetcherTest : public AnyHttpFetcherTest {
public:
// Necessary to unhide the definition in the base class.
using AnyHttpFetcherTest::NewLargeFetcher;
virtual HttpFetcher* NewLargeFetcher() {
LibcurlHttpFetcher *ret = new
LibcurlHttpFetcher(&mock_system_state_, false);
// Speed up test execution.
ret->set_idle_seconds(1);
ret->set_retry_seconds(1);
ret->SetBuildType(false);
return ret;
}
// Necessary to unhide the definition in the base class.
using AnyHttpFetcherTest::NewSmallFetcher;
virtual HttpFetcher* NewSmallFetcher() {
return NewLargeFetcher();
}
virtual string BigUrl() const {
return LocalServerUrlForPath(base::StringPrintf("/download/%d",
kBigLength));
}
virtual string SmallUrl() const {
return LocalServerUrlForPath("/foo");
}
virtual string ErrorUrl() const {
return LocalServerUrlForPath("/error");
}
virtual bool IsMock() const { return false; }
virtual bool IsMulti() const { return false; }
virtual void IgnoreServerAborting(HttpServer* server) const {
PythonHttpServer *pyserver = reinterpret_cast<PythonHttpServer*>(server);
pyserver->validate_quit_ = false;
}
virtual HttpServer *CreateServer() {
return new PythonHttpServer;
}
};
class MultiRangeHttpFetcherTest : public LibcurlHttpFetcherTest {
public:
// Necessary to unhide the definition in the base class.
using AnyHttpFetcherTest::NewLargeFetcher;
virtual HttpFetcher* NewLargeFetcher() {
MultiRangeHttpFetcher *ret =
new MultiRangeHttpFetcher(
new LibcurlHttpFetcher(&mock_system_state_, false));
ret->ClearRanges();
ret->AddRange(0);
// Speed up test execution.
ret->set_idle_seconds(1);
ret->set_retry_seconds(1);
ret->SetBuildType(false);
return ret;
}
// Necessary to unhide the definition in the base class.
using AnyHttpFetcherTest::NewSmallFetcher;
virtual HttpFetcher* NewSmallFetcher() {
return NewLargeFetcher();
}
virtual bool IsMulti() const { return true; }
};
//
// Infrastructure for type tests of HTTP fetcher.
// See: http://code.google.com/p/googletest/wiki/AdvancedGuide#Typed_Tests
//
// Fixture class template. We use an explicit constraint to guarantee that it
// can only be instantiated with an AnyHttpFetcherTest type, see:
// http://www2.research.att.com/~bs/bs_faq2.html#constraints
template <typename T>
class HttpFetcherTest : public ::testing::Test {
public:
T test_;
private:
static void TypeConstraint(T *a) {
AnyHttpFetcherTest *b = a;
}
};
// Test case types list.
typedef ::testing::Types<LibcurlHttpFetcherTest,
MockHttpFetcherTest,
MultiRangeHttpFetcherTest> HttpFetcherTestTypes;
TYPED_TEST_CASE(HttpFetcherTest, HttpFetcherTestTypes);
namespace {
class HttpFetcherTestDelegate : public HttpFetcherDelegate {
public:
HttpFetcherTestDelegate() :
is_expect_error_(false), times_transfer_complete_called_(0),
times_transfer_terminated_called_(0), times_received_bytes_called_(0) {}
virtual void ReceivedBytes(HttpFetcher* fetcher,
const char* bytes, int length) {
char str[length + 1];
memset(str, 0, length + 1);
memcpy(str, bytes, length);
// Update counters
times_received_bytes_called_++;
}
virtual void TransferComplete(HttpFetcher* fetcher, bool successful) {
if (is_expect_error_)
EXPECT_EQ(kHttpResponseNotFound, fetcher->http_response_code());
else
EXPECT_EQ(kHttpResponseOk, fetcher->http_response_code());
g_main_loop_quit(loop_);
// Update counter
times_transfer_complete_called_++;
}
virtual void TransferTerminated(HttpFetcher* fetcher) {
ADD_FAILURE();
times_transfer_terminated_called_++;
}
GMainLoop* loop_;
// Are we expecting an error response? (default: no)
bool is_expect_error_;
// Counters for callback invocations.
int times_transfer_complete_called_;
int times_transfer_terminated_called_;
int times_received_bytes_called_;
};
struct StartTransferArgs {
HttpFetcher *http_fetcher;
string url;
};
gboolean StartTransfer(gpointer data) {
StartTransferArgs *args = reinterpret_cast<StartTransferArgs*>(data);
args->http_fetcher->BeginTransfer(args->url);
return FALSE;
}
} // namespace {}
TYPED_TEST(HttpFetcherTest, SimpleTest) {
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
{
HttpFetcherTestDelegate delegate;
delegate.loop_ = loop;
scoped_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
fetcher->set_delegate(&delegate);
MockConnectionManager* mock_cm = dynamic_cast<MockConnectionManager*>(
fetcher->GetSystemState()->connection_manager());
EXPECT_CALL(*mock_cm, GetConnectionType(_,_))
.WillRepeatedly(DoAll(SetArgumentPointee<1>(kNetWifi), Return(true)));
EXPECT_CALL(*mock_cm, IsUpdateAllowedOver(kNetWifi))
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cm, StringForConnectionType(kNetWifi))
.WillRepeatedly(Return(flimflam::kTypeWifi));
scoped_ptr<HttpServer> server(this->test_.CreateServer());
ASSERT_TRUE(server->started_);
StartTransferArgs start_xfer_args = {fetcher.get(), this->test_.SmallUrl()};
g_timeout_add(0, StartTransfer, &start_xfer_args);
g_main_loop_run(loop);
}
g_main_loop_unref(loop);
}
TYPED_TEST(HttpFetcherTest, SimpleBigTest) {
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
{
HttpFetcherTestDelegate delegate;
delegate.loop_ = loop;
scoped_ptr<HttpFetcher> fetcher(this->test_.NewLargeFetcher());
fetcher->set_delegate(&delegate);
MockConnectionManager* mock_cm = dynamic_cast<MockConnectionManager*>(
fetcher->GetSystemState()->connection_manager());
EXPECT_CALL(*mock_cm, GetConnectionType(_,_))
.WillRepeatedly(DoAll(SetArgumentPointee<1>(kNetEthernet), Return(true)));
EXPECT_CALL(*mock_cm, IsUpdateAllowedOver(kNetEthernet))
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cm, StringForConnectionType(kNetEthernet))
.WillRepeatedly(Return(flimflam::kTypeEthernet));
scoped_ptr<HttpServer> server(this->test_.CreateServer());
ASSERT_TRUE(server->started_);
StartTransferArgs start_xfer_args = {fetcher.get(), this->test_.BigUrl()};
g_timeout_add(0, StartTransfer, &start_xfer_args);
g_main_loop_run(loop);
}
g_main_loop_unref(loop);
}
// Issue #9648: when server returns an error HTTP response, the fetcher needs to
// terminate transfer prematurely, rather than try to process the error payload.
TYPED_TEST(HttpFetcherTest, ErrorTest) {
if (this->test_.IsMock() || this->test_.IsMulti())
return;
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
{
HttpFetcherTestDelegate delegate;
delegate.loop_ = loop;
// Delegate should expect an error response.
delegate.is_expect_error_ = true;
scoped_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
fetcher->set_delegate(&delegate);
MockConnectionManager* mock_cm = dynamic_cast<MockConnectionManager*>(
fetcher->GetSystemState()->connection_manager());
EXPECT_CALL(*mock_cm, GetConnectionType(_,_))
.WillRepeatedly(DoAll(SetArgumentPointee<1>(kNetWimax), Return(true)));
EXPECT_CALL(*mock_cm, IsUpdateAllowedOver(kNetWimax))
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cm, StringForConnectionType(kNetWimax))
.WillRepeatedly(Return(flimflam::kTypeWimax));
scoped_ptr<HttpServer> server(this->test_.CreateServer());
ASSERT_TRUE(server->started_);
StartTransferArgs start_xfer_args = {
fetcher.get(),
this->test_.ErrorUrl()
};
g_timeout_add(0, StartTransfer, &start_xfer_args);
g_main_loop_run(loop);
// Make sure that no bytes were received.
CHECK_EQ(delegate.times_received_bytes_called_, 0);
CHECK_EQ(fetcher->GetBytesDownloaded(), static_cast<size_t>(0));
// Make sure that transfer completion was signaled once, and no termination
// was signaled.
CHECK_EQ(delegate.times_transfer_complete_called_, 1);
CHECK_EQ(delegate.times_transfer_terminated_called_, 0);
}
g_main_loop_unref(loop);
}
namespace {
class PausingHttpFetcherTestDelegate : public HttpFetcherDelegate {
public:
virtual void ReceivedBytes(HttpFetcher* fetcher,
const char* bytes, int length) {
char str[length + 1];
memset(str, 0, length + 1);
memcpy(str, bytes, length);
CHECK(!paused_);
paused_ = true;
fetcher->Pause();
}
virtual void TransferComplete(HttpFetcher* fetcher, bool successful) {
g_main_loop_quit(loop_);
}
virtual void TransferTerminated(HttpFetcher* fetcher) {
ADD_FAILURE();
}
void Unpause() {
CHECK(paused_);
paused_ = false;
fetcher_->Unpause();
}
bool paused_;
HttpFetcher* fetcher_;
GMainLoop* loop_;
};
gboolean UnpausingTimeoutCallback(gpointer data) {
PausingHttpFetcherTestDelegate *delegate =
reinterpret_cast<PausingHttpFetcherTestDelegate*>(data);
if (delegate->paused_)
delegate->Unpause();
return TRUE;
}
} // namespace {}
TYPED_TEST(HttpFetcherTest, PauseTest) {
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
{
PausingHttpFetcherTestDelegate delegate;
scoped_ptr<HttpFetcher> fetcher(this->test_.NewLargeFetcher());
delegate.paused_ = false;
delegate.loop_ = loop;
delegate.fetcher_ = fetcher.get();
fetcher->set_delegate(&delegate);
MockConnectionManager* mock_cm = dynamic_cast<MockConnectionManager*>(
fetcher->GetSystemState()->connection_manager());
EXPECT_CALL(*mock_cm, GetConnectionType(_,_))
.WillRepeatedly(DoAll(SetArgumentPointee<1>(kNetCellular), Return(true)));
EXPECT_CALL(*mock_cm, IsUpdateAllowedOver(kNetCellular))
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cm, StringForConnectionType(kNetCellular))
.WillRepeatedly(Return(flimflam::kTypeCellular));
scoped_ptr<HttpServer> server(this->test_.CreateServer());
ASSERT_TRUE(server->started_);
guint callback_id = g_timeout_add(kHttpResponseInternalServerError,
UnpausingTimeoutCallback, &delegate);
fetcher->BeginTransfer(this->test_.BigUrl());
g_main_loop_run(loop);
g_source_remove(callback_id);
}
g_main_loop_unref(loop);
}
namespace {
class AbortingHttpFetcherTestDelegate : public HttpFetcherDelegate {
public:
virtual void ReceivedBytes(HttpFetcher* fetcher,
const char* bytes, int length) {}
virtual void TransferComplete(HttpFetcher* fetcher, bool successful) {
ADD_FAILURE(); // We should never get here
g_main_loop_quit(loop_);
}
virtual void TransferTerminated(HttpFetcher* fetcher) {
EXPECT_EQ(fetcher, fetcher_.get());
EXPECT_FALSE(once_);
EXPECT_TRUE(callback_once_);
callback_once_ = false;
// |fetcher| can be destroyed during this callback.
fetcher_.reset(NULL);
}
void TerminateTransfer() {
CHECK(once_);
once_ = false;
fetcher_->TerminateTransfer();
}
void EndLoop() {
g_main_loop_quit(loop_);
}
bool once_;
bool callback_once_;
scoped_ptr<HttpFetcher> fetcher_;
GMainLoop* loop_;
};
gboolean AbortingTimeoutCallback(gpointer data) {
AbortingHttpFetcherTestDelegate *delegate =
reinterpret_cast<AbortingHttpFetcherTestDelegate*>(data);
if (delegate->once_) {
delegate->TerminateTransfer();
return TRUE;
} else {
delegate->EndLoop();
return FALSE;
}
}
} // namespace {}
TYPED_TEST(HttpFetcherTest, AbortTest) {
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
{
AbortingHttpFetcherTestDelegate delegate;
delegate.fetcher_.reset(this->test_.NewLargeFetcher());
delegate.once_ = true;
delegate.callback_once_ = true;
delegate.loop_ = loop;
delegate.fetcher_->set_delegate(&delegate);
MockConnectionManager* mock_cm = dynamic_cast<MockConnectionManager*>(
delegate.fetcher_->GetSystemState()->connection_manager());
EXPECT_CALL(*mock_cm, GetConnectionType(_,_))
.WillRepeatedly(DoAll(SetArgumentPointee<1>(kNetWifi), Return(true)));
EXPECT_CALL(*mock_cm, IsUpdateAllowedOver(kNetWifi))
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cm, StringForConnectionType(kNetWifi))
.WillRepeatedly(Return(flimflam::kTypeWifi));
scoped_ptr<HttpServer> server(this->test_.CreateServer());
this->test_.IgnoreServerAborting(server.get());
ASSERT_TRUE(server->started_);
GSource* timeout_source_;
timeout_source_ = g_timeout_source_new(0); // ms
g_source_set_callback(timeout_source_, AbortingTimeoutCallback, &delegate,
NULL);
g_source_attach(timeout_source_, NULL);
delegate.fetcher_->BeginTransfer(this->test_.BigUrl());
g_main_loop_run(loop);
CHECK(!delegate.once_);
CHECK(!delegate.callback_once_);
g_source_destroy(timeout_source_);
}
g_main_loop_unref(loop);
}
namespace {
class FlakyHttpFetcherTestDelegate : public HttpFetcherDelegate {
public:
virtual void ReceivedBytes(HttpFetcher* fetcher,
const char* bytes, int length) {
data.append(bytes, length);
}
virtual void TransferComplete(HttpFetcher* fetcher, bool successful) {
EXPECT_TRUE(successful);
EXPECT_EQ(kHttpResponsePartialContent, fetcher->http_response_code());
g_main_loop_quit(loop_);
}
virtual void TransferTerminated(HttpFetcher* fetcher) {
ADD_FAILURE();
}
string data;
GMainLoop* loop_;
};
} // namespace {}
TYPED_TEST(HttpFetcherTest, FlakyTest) {
if (this->test_.IsMock())
return;
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
{
FlakyHttpFetcherTestDelegate delegate;
delegate.loop_ = loop;
scoped_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
fetcher->set_delegate(&delegate);
MockConnectionManager* mock_cm = dynamic_cast<MockConnectionManager*>(
fetcher->GetSystemState()->connection_manager());
EXPECT_CALL(*mock_cm, GetConnectionType(_,_))
.WillRepeatedly(DoAll(SetArgumentPointee<1>(kNetWifi), Return(true)));
EXPECT_CALL(*mock_cm, IsUpdateAllowedOver(kNetWifi))
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cm, StringForConnectionType(kNetWifi))
.WillRepeatedly(Return(flimflam::kTypeWifi));
scoped_ptr<HttpServer> server(this->test_.CreateServer());
ASSERT_TRUE(server->started_);
StartTransferArgs start_xfer_args = {
fetcher.get(),
LocalServerUrlForPath(StringPrintf("/flaky/%d/%d/%d/%d", kBigLength,
kFlakyTruncateLength,
kFlakySleepEvery,
kFlakySleepSecs))
};
g_timeout_add(0, StartTransfer, &start_xfer_args);
g_main_loop_run(loop);
// verify the data we get back
ASSERT_EQ(kBigLength, delegate.data.size());
for (int i = 0; i < kBigLength; i += 10) {
// Assert so that we don't flood the screen w/ EXPECT errors on failure.
ASSERT_EQ(delegate.data.substr(i, 10), "abcdefghij");
}
}
g_main_loop_unref(loop);
}
namespace {
class FailureHttpFetcherTestDelegate : public HttpFetcherDelegate {
public:
FailureHttpFetcherTestDelegate(PythonHttpServer* server)
: loop_(NULL),
server_(server) {}
virtual ~FailureHttpFetcherTestDelegate() {
if (server_) {
LOG(INFO) << "Stopping server in destructor";
delete server_;
LOG(INFO) << "server stopped";
}
}
virtual void ReceivedBytes(HttpFetcher* fetcher,
const char* bytes, int length) {
if (server_) {
LOG(INFO) << "Stopping server in ReceivedBytes";
delete server_;
LOG(INFO) << "server stopped";
server_ = NULL;
}
}
virtual void TransferComplete(HttpFetcher* fetcher, bool successful) {
EXPECT_FALSE(successful);
EXPECT_EQ(0, fetcher->http_response_code());
g_main_loop_quit(loop_);
}
virtual void TransferTerminated(HttpFetcher* fetcher) {
ADD_FAILURE();
}
GMainLoop* loop_;
PythonHttpServer* server_;
};
} // namespace {}
TYPED_TEST(HttpFetcherTest, FailureTest) {
if (this->test_.IsMock())
return;
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
{
FailureHttpFetcherTestDelegate delegate(NULL);
delegate.loop_ = loop;
scoped_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
fetcher->set_delegate(&delegate);
MockConnectionManager* mock_cm = dynamic_cast<MockConnectionManager*>(
fetcher->GetSystemState()->connection_manager());
EXPECT_CALL(*mock_cm, GetConnectionType(_,_))
.WillRepeatedly(DoAll(SetArgumentPointee<1>(kNetEthernet), Return(true)));
EXPECT_CALL(*mock_cm, IsUpdateAllowedOver(kNetEthernet))
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cm, StringForConnectionType(kNetEthernet))
.WillRepeatedly(Return(flimflam::kTypeEthernet));
StartTransferArgs start_xfer_args = {
fetcher.get(),
LocalServerUrlForPath(this->test_.SmallUrl())
};
g_timeout_add(0, StartTransfer, &start_xfer_args);
g_main_loop_run(loop);
// Exiting and testing happens in the delegate
}
g_main_loop_unref(loop);
}
TYPED_TEST(HttpFetcherTest, ServerDiesTest) {
if (this->test_.IsMock())
return;
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
{
FailureHttpFetcherTestDelegate delegate(new PythonHttpServer);
delegate.loop_ = loop;
scoped_ptr<HttpFetcher> fetcher(this->test_.NewSmallFetcher());
fetcher->set_delegate(&delegate);
StartTransferArgs start_xfer_args = {
fetcher.get(),
LocalServerUrlForPath(StringPrintf("/flaky/%d/%d/%d/%d", kBigLength,
kFlakyTruncateLength,
kFlakySleepEvery,
kFlakySleepSecs))
};
g_timeout_add(0, StartTransfer, &start_xfer_args);
g_main_loop_run(loop);
// Exiting and testing happens in the delegate
}
g_main_loop_unref(loop);
}
namespace {
const HttpResponseCode kRedirectCodes[] = {
kHttpResponseMovedPermanently, kHttpResponseFound, kHttpResponseSeeOther,
kHttpResponseTempRedirect
};
class RedirectHttpFetcherTestDelegate : public HttpFetcherDelegate {
public:
RedirectHttpFetcherTestDelegate(bool expected_successful)
: expected_successful_(expected_successful) {}
virtual void ReceivedBytes(HttpFetcher* fetcher,
const char* bytes, int length) {
data.append(bytes, length);
}
virtual void TransferComplete(HttpFetcher* fetcher, bool successful) {
EXPECT_EQ(expected_successful_, successful);
if (expected_successful_)
EXPECT_EQ(kHttpResponseOk, fetcher->http_response_code());
else {
EXPECT_GE(fetcher->http_response_code(), kHttpResponseMovedPermanently);
EXPECT_LE(fetcher->http_response_code(), kHttpResponseTempRedirect);
}
g_main_loop_quit(loop_);
}
virtual void TransferTerminated(HttpFetcher* fetcher) {
ADD_FAILURE();
}
bool expected_successful_;
string data;
GMainLoop* loop_;
};
// RedirectTest takes ownership of |http_fetcher|.
void RedirectTest(bool expected_successful,
const string& url,
HttpFetcher* http_fetcher) {
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
{
RedirectHttpFetcherTestDelegate delegate(expected_successful);
delegate.loop_ = loop;
scoped_ptr<HttpFetcher> fetcher(http_fetcher);
fetcher->set_delegate(&delegate);
MockConnectionManager* mock_cm = dynamic_cast<MockConnectionManager*>(
fetcher->GetSystemState()->connection_manager());
EXPECT_CALL(*mock_cm, GetConnectionType(_,_))
.WillRepeatedly(DoAll(SetArgumentPointee<1>(kNetEthernet), Return(true)));
EXPECT_CALL(*mock_cm, IsUpdateAllowedOver(kNetEthernet))
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cm, StringForConnectionType(kNetEthernet))
.WillRepeatedly(Return(flimflam::kTypeEthernet));
StartTransferArgs start_xfer_args =
{ fetcher.get(), LocalServerUrlForPath(url) };
g_timeout_add(0, StartTransfer, &start_xfer_args);
g_main_loop_run(loop);
if (expected_successful) {
// verify the data we get back
ASSERT_EQ(kMediumLength, delegate.data.size());
for (int i = 0; i < kMediumLength; i += 10) {
// Assert so that we don't flood the screen w/ EXPECT errors on failure.
ASSERT_EQ(delegate.data.substr(i, 10), "abcdefghij");
}
}
}
g_main_loop_unref(loop);
}
} // namespace {}
TYPED_TEST(HttpFetcherTest, SimpleRedirectTest) {
if (this->test_.IsMock())
return;
scoped_ptr<HttpServer> server(this->test_.CreateServer());
ASSERT_TRUE(server->started_);
for (size_t c = 0; c < arraysize(kRedirectCodes); ++c) {
const string url = base::StringPrintf("/redirect/%d/download/%d",
kRedirectCodes[c],
kMediumLength);
RedirectTest(true, url, this->test_.NewLargeFetcher());
}
}
TYPED_TEST(HttpFetcherTest, MaxRedirectTest) {
if (this->test_.IsMock())
return;
scoped_ptr<HttpServer> server(this->test_.CreateServer());
ASSERT_TRUE(server->started_);
string url;
for (int r = 0; r < LibcurlHttpFetcher::kMaxRedirects; r++) {
url += base::StringPrintf("/redirect/%d",
kRedirectCodes[r % arraysize(kRedirectCodes)]);
}
url += base::StringPrintf("/download/%d", kMediumLength);
RedirectTest(true, url, this->test_.NewLargeFetcher());
}
TYPED_TEST(HttpFetcherTest, BeyondMaxRedirectTest) {
if (this->test_.IsMock())
return;
scoped_ptr<HttpServer> server(this->test_.CreateServer());
ASSERT_TRUE(server->started_);
string url;
for (int r = 0; r < LibcurlHttpFetcher::kMaxRedirects + 1; r++) {
url += base::StringPrintf("/redirect/%d",
kRedirectCodes[r % arraysize(kRedirectCodes)]);
}
url += base::StringPrintf("/download/%d", kMediumLength);
RedirectTest(false, url, this->test_.NewLargeFetcher());
}
namespace {
class MultiHttpFetcherTestDelegate : public HttpFetcherDelegate {
public:
MultiHttpFetcherTestDelegate(int expected_response_code)
: expected_response_code_(expected_response_code) {}
virtual void ReceivedBytes(HttpFetcher* fetcher,
const char* bytes, int length) {
EXPECT_EQ(fetcher, fetcher_.get());
data.append(bytes, length);
}
virtual void TransferComplete(HttpFetcher* fetcher, bool successful) {
EXPECT_EQ(fetcher, fetcher_.get());
EXPECT_EQ(expected_response_code_ != kHttpResponseUndefined, successful);
if (expected_response_code_ != 0)
EXPECT_EQ(expected_response_code_, fetcher->http_response_code());
// Destroy the fetcher (because we're allowed to).
fetcher_.reset(NULL);
g_main_loop_quit(loop_);
}
virtual void TransferTerminated(HttpFetcher* fetcher) {
ADD_FAILURE();
}
scoped_ptr<HttpFetcher> fetcher_;
int expected_response_code_;
string data;
GMainLoop* loop_;
};
void MultiTest(HttpFetcher* fetcher_in,
const string& url,
const vector<pair<off_t, off_t> >& ranges,
const string& expected_prefix,
off_t expected_size,
HttpResponseCode expected_response_code) {
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
{
MultiHttpFetcherTestDelegate delegate(expected_response_code);
delegate.loop_ = loop;
delegate.fetcher_.reset(fetcher_in);
MockConnectionManager* mock_cm = dynamic_cast<MockConnectionManager*>(
fetcher_in->GetSystemState()->connection_manager());
EXPECT_CALL(*mock_cm, GetConnectionType(_,_))
.WillRepeatedly(DoAll(SetArgumentPointee<1>(kNetWifi), Return(true)));
EXPECT_CALL(*mock_cm, IsUpdateAllowedOver(kNetWifi))
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_cm, StringForConnectionType(kNetWifi))
.WillRepeatedly(Return(flimflam::kTypeWifi));
MultiRangeHttpFetcher* multi_fetcher =
dynamic_cast<MultiRangeHttpFetcher*>(fetcher_in);
ASSERT_TRUE(multi_fetcher);
multi_fetcher->ClearRanges();
for (vector<pair<off_t, off_t> >::const_iterator it = ranges.begin(),
e = ranges.end(); it != e; ++it) {
std::string tmp_str = StringPrintf("%jd+", it->first);
if (it->second > 0) {
base::StringAppendF(&tmp_str, "%jd", it->second);
multi_fetcher->AddRange(it->first, it->second);
} else {
base::StringAppendF(&tmp_str, "?");
multi_fetcher->AddRange(it->first);
}
LOG(INFO) << "added range: " << tmp_str;
}
multi_fetcher->SetBuildType(false);
multi_fetcher->set_delegate(&delegate);
StartTransferArgs start_xfer_args = {multi_fetcher, url};
g_timeout_add(0, StartTransfer, &start_xfer_args);
g_main_loop_run(loop);
EXPECT_EQ(expected_size, delegate.data.size());
EXPECT_EQ(expected_prefix,
string(delegate.data.data(), expected_prefix.size()));
}
g_main_loop_unref(loop);
}
} // namespace {}
TYPED_TEST(HttpFetcherTest, MultiHttpFetcherSimpleTest) {
if (!this->test_.IsMulti())
return;
scoped_ptr<HttpServer> server(this->test_.CreateServer());
ASSERT_TRUE(server->started_);
vector<pair<off_t, off_t> > ranges;
ranges.push_back(make_pair(0, 25));
ranges.push_back(make_pair(99, 0));
MultiTest(this->test_.NewLargeFetcher(),
this->test_.BigUrl(),
ranges,
"abcdefghijabcdefghijabcdejabcdefghijabcdef",
kBigLength - (99 - 25),
kHttpResponsePartialContent);
}