forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdownload_session_task_impl_unittest.mm
759 lines (670 loc) · 31.1 KB
/
download_session_task_impl_unittest.mm
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
// Copyright 2021 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.
#import "ios/web/download/download_session_task_impl.h"
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
#include <memory>
#include "base/bind.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/utf_string_conversions.h"
#import "base/test/ios/wait_util.h"
#import "ios/web/net/cookies/wk_cookie_util.h"
#import "ios/web/public/download/download_task_observer.h"
#include "ios/web/public/test/fakes/fake_cookie_store.h"
#import "ios/web/public/test/fakes/fake_web_state.h"
#include "ios/web/public/test/web_test.h"
#import "ios/web/test/fakes/crw_fake_nsurl_session_task.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_fetcher_response_writer.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gtest_mac.h"
#include "testing/platform_test.h"
#import "third_party/ocmock/OCMock/OCMock.h"
#include "url/gurl.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
using base::test::ios::kWaitForCookiesTimeout;
using base::test::ios::kWaitForDownloadTimeout;
using base::test::ios::kWaitForFileOperationTimeout;
using base::test::ios::WaitUntilConditionOrTimeout;
namespace web {
namespace {
const char kUrl[] = "chromium://download.test/";
const char kContentDisposition[] = "attachment; filename=file.test";
const char kMimeType[] = "application/pdf";
NSString* const kHttpMethod = @"POST";
class MockDownloadTaskObserver : public DownloadTaskObserver {
public:
MOCK_METHOD1(OnDownloadUpdated, void(DownloadTask* task));
void OnDownloadDestroyed(DownloadTask* task) override {
// Removing observer here works as a test that
// DownloadTaskObserver::OnDownloadDestroyed is actually called.
// DownloadTask DCHECKs if it is destroyed without observer removal.
task->RemoveObserver(this);
}
};
// Allows waiting for DownloadTaskObserver::OnDownloadUpdated callback.
class OnDownloadUpdatedWaiter : public DownloadTaskObserver {
public:
bool Wait() {
return WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
base::RunLoop().RunUntilIdle();
return download_updated_;
});
}
private:
void OnDownloadUpdated(DownloadTask* task) override {
download_updated_ = true;
}
bool download_updated_ = false;
};
// Mocks DownloadTaskImpl::Delegate's OnTaskUpdated and OnTaskDestroyed methods
// and stubs DownloadTaskImpl::Delegate::CreateSession with session mock.
class FakeDownloadSessionTaskImplDelegate : public DownloadTaskImpl::Delegate {
public:
FakeDownloadSessionTaskImplDelegate()
: configuration_([NSURLSessionConfiguration
backgroundSessionConfigurationWithIdentifier:
[NSUUID UUID].UUIDString]),
session_(OCMStrictClassMock([NSURLSession class])) {
OCMStub([session_ configuration]).andReturn(configuration_);
}
MOCK_METHOD1(OnTaskDestroyed, void(DownloadTaskImpl* task));
// Returns mock, which can be accessed via session() method.
NSURLSession* CreateSession(NSString* identifier,
NSArray<NSHTTPCookie*>* cookies,
id<NSURLSessionDataDelegate> delegate,
NSOperationQueue* delegate_queue) {
// Make sure this method is called only once.
EXPECT_FALSE(session_delegate_);
session_delegate_ = delegate;
cookies_ = [cookies copy];
return session_;
}
// These methods return session objects injected into DownloadTaskImpl.
NSURLSessionConfiguration* configuration() { return configuration_; }
id session() { return session_; }
id<NSURLSessionDataDelegate> session_delegate() { return session_delegate_; }
// Returns the cookies passed to Create session method.
NSArray<NSHTTPCookie*>* cookies() { return cookies_; }
private:
id<NSURLSessionDataDelegate> session_delegate_;
id configuration_;
NSArray<NSHTTPCookie*>* cookies_ = nil;
id session_;
};
} // namespace
// Test fixture for testing DownloadTaskImplTest class.
class DownloadSessionTaskImplTest : public PlatformTest {
protected:
DownloadSessionTaskImplTest()
: task_(std::make_unique<DownloadSessionTaskImpl>(
&web_state_,
GURL(kUrl),
kHttpMethod,
kContentDisposition,
/*total_bytes=*/-1,
kMimeType,
task_delegate_.configuration().identifier,
&task_delegate_)),
session_delegate_callbacks_queue_(
dispatch_queue_create(nullptr, DISPATCH_QUEUE_SERIAL)) {
browser_state_.SetOffTheRecord(true);
browser_state_.SetCookieStore(std::make_unique<FakeCookieStore>());
web_state_.SetBrowserState(&browser_state_);
task_->AddObserver(&task_observer_);
}
// Starts the download and return NSURLSessionDataTask fake for this task.
CRWFakeNSURLSessionTask* Start(const base::FilePath& path,
DownloadTask::Destination destination_hint) {
// Inject fake NSURLSessionDataTask into DownloadTaskImpl.
NSURL* url = [NSURL URLWithString:@(kUrl)];
CRWFakeNSURLSessionTask* session_task =
[[CRWFakeNSURLSessionTask alloc] initWithURL:url];
EXPECT_TRUE(task_delegate_.session());
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = kHttpMethod;
OCMExpect([task_delegate_.session() dataTaskWithRequest:request])
.andReturn(session_task);
// Start the download.
task_->Start(path, destination_hint);
bool success = WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
base::RunLoop().RunUntilIdle();
return session_task.state == NSURLSessionTaskStateRunning;
});
return success ? session_task : nil;
}
FakeCookieStore* cookie_store() {
auto* context = browser_state_.GetRequestContext()->GetURLRequestContext();
// This cast is safe because we set a FakeCookieStore in the constructor.
return static_cast<FakeCookieStore*>(context->cookie_store());
}
// Starts the download and return NSURLSessionDataTask fake for this task.
// Same as above, but uses URLFetcherStringWriter as response writer.
CRWFakeNSURLSessionTask* Start() {
return Start(base::FilePath(), DownloadTask::Destination::kToMemory);
}
// Session and session delegate injected into DownloadTaskImpl for testing.
NSURLSession* session() { return task_delegate_.session(); }
id<NSURLSessionDataDelegate> session_delegate() {
return task_delegate_.session_delegate();
}
// Updates NSURLSessionTask.countOfBytesReceived and calls
// URLSession:dataTask:didReceiveData: callback. |data_str| is null terminated
// C-string that represents the downloaded data.
void SimulateDataDownload(CRWFakeNSURLSessionTask* session_task,
const char data_str[]) {
OnDownloadUpdatedWaiter callback_waiter;
task_->AddObserver(&callback_waiter);
session_task.countOfBytesReceived += strlen(data_str);
NSData* data = [NSData dataWithBytes:data_str length:strlen(data_str)];
dispatch_async(session_delegate_callbacks_queue_, ^{
[session_delegate() URLSession:session()
dataTask:session_task
didReceiveData:data];
});
EXPECT_TRUE(callback_waiter.Wait());
task_->RemoveObserver(&callback_waiter);
}
// Sets NSURLSessionTask.state to NSURLSessionTaskStateCompleted and calls
// URLSession:dataTask:didCompleteWithError: callback.
void SimulateDownloadCompletion(CRWFakeNSURLSessionTask* session_task,
NSError* error = nil) {
OnDownloadUpdatedWaiter callback_waiter;
task_->AddObserver(&callback_waiter);
session_task.state = NSURLSessionTaskStateCompleted;
dispatch_async(session_delegate_callbacks_queue_, ^{
[session_delegate() URLSession:session()
task:session_task
didCompleteWithError:error];
});
EXPECT_TRUE(callback_waiter.Wait());
task_->RemoveObserver(&callback_waiter);
}
web::WebTaskEnvironment task_environment_;
FakeBrowserState browser_state_;
FakeWebState web_state_;
testing::StrictMock<FakeDownloadSessionTaskImplDelegate> task_delegate_;
std::unique_ptr<DownloadSessionTaskImpl> task_;
MockDownloadTaskObserver task_observer_;
// NSURLSessionDataDelegate callbacks are called on background serial queue.
dispatch_queue_t session_delegate_callbacks_queue_ = 0;
};
// Tests DownloadSessionTaskImpl default state after construction.
TEST_F(DownloadSessionTaskImplTest, DefaultState) {
EXPECT_EQ(&web_state_, task_->GetWebState());
EXPECT_EQ(DownloadTask::State::kNotStarted, task_->GetState());
EXPECT_NSEQ(task_delegate_.configuration().identifier,
task_->GetIndentifier());
EXPECT_EQ(kUrl, task_->GetOriginalUrl());
EXPECT_FALSE(task_->IsDone());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(-1, task_->GetHttpCode());
EXPECT_EQ(-1, task_->GetTotalBytes());
EXPECT_EQ(0, task_->GetReceivedBytes());
EXPECT_EQ(-1, task_->GetPercentComplete());
EXPECT_EQ(kContentDisposition, task_->GetContentDisposition());
EXPECT_EQ(kMimeType, task_->GetMimeType());
EXPECT_EQ(kMimeType, task_->GetOriginalMimeType());
EXPECT_EQ("file.test", base::UTF16ToUTF8(task_->GetSuggestedFilename()));
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests sucessfull download of response without content.
// (No URLSession:dataTask:didReceiveData: callback).
TEST_F(DownloadSessionTaskImplTest, EmptyContentDownload) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
// Download has finished.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
SimulateDownloadCompletion(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
EXPECT_EQ(DownloadTask::State::kComplete, task_->GetState());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(0, task_->GetTotalBytes());
EXPECT_EQ(0, task_->GetReceivedBytes());
EXPECT_EQ(100, task_->GetPercentComplete());
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests sucessfull download of response when content length is unknown until
// the download completes.
TEST_F(DownloadSessionTaskImplTest, UnknownLengthContentDownload) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
// The response has arrived.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
const char kData[] = "foo";
session_task.countOfBytesExpectedToReceive = -1;
SimulateDataDownload(session_task, kData);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
EXPECT_EQ(DownloadTask::State::kInProgress, task_->GetState());
EXPECT_FALSE(task_->IsDone());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(-1, task_->GetTotalBytes());
EXPECT_EQ(-1, task_->GetPercentComplete());
EXPECT_NSEQ(@(kData), [[NSString alloc] initWithData:task_->GetResponseData()
encoding:NSUTF8StringEncoding]);
// Download has finished.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
int64_t kDataSize = strlen(kData);
session_task.countOfBytesExpectedToReceive = kDataSize;
SimulateDownloadCompletion(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
EXPECT_EQ(DownloadTask::State::kComplete, task_->GetState());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(kDataSize, task_->GetTotalBytes());
EXPECT_EQ(100, task_->GetPercentComplete());
EXPECT_NSEQ(@(kData), [[NSString alloc] initWithData:task_->GetResponseData()
encoding:NSUTF8StringEncoding]);
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests cancelling the download task.
TEST_F(DownloadSessionTaskImplTest, Cancelling) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
// Cancel the download.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
task_->Cancel();
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
testing::Mock::VerifyAndClearExpectations(&task_observer_);
EXPECT_EQ(DownloadTask::State::kCancelled, task_->GetState());
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests restarting failed download task.
TEST_F(DownloadSessionTaskImplTest, Restarting) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
// Download has failed.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
NSError* error = [NSError errorWithDomain:NSURLErrorDomain
code:NSURLErrorNotConnectedToInternet
userInfo:nil];
SimulateDownloadCompletion(session_task, error);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
EXPECT_EQ(100, task_->GetPercentComplete());
// Restart the task.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
session_task = Start();
EXPECT_EQ(0, task_->GetPercentComplete());
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
// Download has finished.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
SimulateDownloadCompletion(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
EXPECT_EQ(DownloadTask::State::kComplete, task_->GetState());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(100, task_->GetPercentComplete());
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests sucessfull download of response with only one
// URLSession:dataTask:didReceiveData: callback.
TEST_F(DownloadSessionTaskImplTest, SmallResponseDownload) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
// The response has arrived.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
const char kData[] = "foo";
int64_t kDataSize = strlen(kData);
session_task.countOfBytesExpectedToReceive = kDataSize;
SimulateDataDownload(session_task, kData);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
EXPECT_EQ(DownloadTask::State::kInProgress, task_->GetState());
EXPECT_FALSE(task_->IsDone());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(kDataSize, task_->GetTotalBytes());
EXPECT_EQ(kDataSize, task_->GetReceivedBytes());
EXPECT_EQ(100, task_->GetPercentComplete());
EXPECT_NSEQ(@(kData), [[NSString alloc] initWithData:task_->GetResponseData()
encoding:NSUTF8StringEncoding]);
// Download has finished.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
SimulateDownloadCompletion(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
EXPECT_EQ(DownloadTask::State::kComplete, task_->GetState());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(kDataSize, task_->GetTotalBytes());
EXPECT_EQ(kDataSize, task_->GetReceivedBytes());
EXPECT_EQ(100, task_->GetPercentComplete());
EXPECT_NSEQ(@(kData), [[NSString alloc] initWithData:task_->GetResponseData()
encoding:NSUTF8StringEncoding]);
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests sucessfull download of response with multiple
// URLSession:dataTask:didReceiveData: callbacks.
TEST_F(DownloadSessionTaskImplTest, LargeResponseDownload) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
// The first part of the response has arrived.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
const char kData1[] = "foo";
const char kData2[] = "buzz";
int64_t kData1Size = strlen(kData1);
int64_t kData2Size = strlen(kData2);
session_task.countOfBytesExpectedToReceive = kData1Size + kData2Size;
SimulateDataDownload(session_task, kData1);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
EXPECT_EQ(DownloadTask::State::kInProgress, task_->GetState());
EXPECT_FALSE(task_->IsDone());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(kData1Size + kData2Size, task_->GetTotalBytes());
EXPECT_EQ(kData1Size, task_->GetReceivedBytes());
EXPECT_EQ(42, task_->GetPercentComplete());
EXPECT_NSEQ(@(kData1), [[NSString alloc] initWithData:task_->GetResponseData()
encoding:NSUTF8StringEncoding]);
// The second part of the response has arrived.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
SimulateDataDownload(session_task, kData2);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
EXPECT_EQ(DownloadTask::State::kInProgress, task_->GetState());
EXPECT_FALSE(task_->IsDone());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(kData1Size + kData2Size, task_->GetTotalBytes());
EXPECT_EQ(kData1Size + kData2Size, task_->GetReceivedBytes());
EXPECT_EQ(100, task_->GetPercentComplete());
EXPECT_NSEQ([@(kData1) stringByAppendingString:@(kData2)],
[[NSString alloc] initWithData:task_->GetResponseData()
encoding:NSUTF8StringEncoding]);
// Download has finished.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
SimulateDownloadCompletion(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
EXPECT_EQ(DownloadTask::State::kComplete, task_->GetState());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(kData1Size + kData2Size, task_->GetTotalBytes());
EXPECT_EQ(kData1Size + kData2Size, task_->GetReceivedBytes());
EXPECT_EQ(100, task_->GetPercentComplete());
EXPECT_NSEQ([@(kData1) stringByAppendingString:@(kData2)],
[[NSString alloc] initWithData:task_->GetResponseData()
encoding:NSUTF8StringEncoding]);
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests failed download when URLSession:dataTask:didReceiveData: callback was
// not even called.
TEST_F(DownloadSessionTaskImplTest, FailureInTheBeginning) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
// Download has failed.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
NSError* error = [NSError errorWithDomain:NSURLErrorDomain
code:NSURLErrorNotConnectedToInternet
userInfo:nil];
SimulateDownloadCompletion(session_task, error);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
EXPECT_EQ(DownloadTask::State::kFailed, task_->GetState());
EXPECT_TRUE(task_->GetErrorCode() == net::ERR_INTERNET_DISCONNECTED);
EXPECT_EQ(0, task_->GetTotalBytes());
EXPECT_EQ(0, task_->GetReceivedBytes());
EXPECT_EQ(100, task_->GetPercentComplete());
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests failed download when URLSession:dataTask:didReceiveData: callback was
// called once.
TEST_F(DownloadSessionTaskImplTest, FailureInTheMiddle) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
// A part of the response has arrived.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
const char kReceivedData[] = "foo";
int64_t kReceivedDataSize = strlen(kReceivedData);
int64_t kExpectedDataSize = kReceivedDataSize + 10;
session_task.countOfBytesExpectedToReceive = kExpectedDataSize;
SimulateDataDownload(session_task, kReceivedData);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
EXPECT_EQ(DownloadTask::State::kInProgress, task_->GetState());
EXPECT_FALSE(task_->IsDone());
EXPECT_EQ(0, task_->GetErrorCode());
EXPECT_EQ(kExpectedDataSize, task_->GetTotalBytes());
EXPECT_EQ(kReceivedDataSize, task_->GetReceivedBytes());
EXPECT_EQ(23, task_->GetPercentComplete());
EXPECT_NSEQ(@(kReceivedData),
[[NSString alloc] initWithData:task_->GetResponseData()
encoding:NSUTF8StringEncoding]);
// Download has failed.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
NSError* error = [NSError errorWithDomain:NSURLErrorDomain
code:NSURLErrorNotConnectedToInternet
userInfo:nil];
session_task.countOfBytesExpectedToReceive = 0; // This is 0 when offline.
SimulateDownloadCompletion(session_task, error);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
EXPECT_EQ(DownloadTask::State::kFailed, task_->GetState());
EXPECT_TRUE(task_->GetErrorCode() == net::ERR_INTERNET_DISCONNECTED);
EXPECT_EQ(kExpectedDataSize, task_->GetTotalBytes());
EXPECT_EQ(kReceivedDataSize, task_->GetReceivedBytes());
EXPECT_EQ(100, task_->GetPercentComplete());
EXPECT_NSEQ(@(kReceivedData),
[[NSString alloc] initWithData:task_->GetResponseData()
encoding:NSUTF8StringEncoding]);
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests that CreateSession is called with the correct cookies from the cookie
// store.
TEST_F(DownloadSessionTaskImplTest, Cookie) {
GURL cookie_url(kUrl);
base::Time now = base::Time::Now();
std::unique_ptr<net::CanonicalCookie> expected_cookie =
net::CanonicalCookie::CreateUnsafeCookieForTesting(
"name", "value", cookie_url.host(), cookie_url.path(),
/*creation=*/now,
/*expire_date=*/now + base::Hours(2),
/*last_access=*/now,
/*secure=*/false,
/*httponly=*/false, net::CookieSameSite::UNSPECIFIED,
net::COOKIE_PRIORITY_DEFAULT, /*same_party=*/false);
cookie_store()->SetAllCookies({*expected_cookie});
// Start the download and make sure that all cookie from BrowserState were
// picked up.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
ASSERT_TRUE(Start());
EXPECT_EQ(1U, task_delegate_.cookies().count);
NSHTTPCookie* actual_cookie = task_delegate_.cookies().firstObject;
EXPECT_NSEQ(@"name", actual_cookie.name);
EXPECT_NSEQ(@"value", actual_cookie.value);
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests that URLFetcherFileWriter deletes the file if download has failed with
// error.
TEST_F(DownloadSessionTaskImplTest, FileDeletion) {
// Create URLFetcherFileWriter.
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
base::FilePath temp_file = temp_dir.GetPath().AppendASCII("DownloadTaskImpl");
base::DeleteFile(temp_file);
ASSERT_FALSE(base::PathExists(temp_file));
// Start the download.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task =
Start(temp_file, web::DownloadTask::Destination::kToDisk);
ASSERT_TRUE(session_task);
// Deliver the response and verify that download file exists.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
const char kReceivedData[] = "foo";
SimulateDataDownload(session_task, kReceivedData);
ASSERT_TRUE(base::PathExists(temp_file));
// Fail the download and verify that the file was deleted.
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
NSError* error = [NSError errorWithDomain:NSURLErrorDomain
code:NSURLErrorNotConnectedToInternet
userInfo:nil];
SimulateDownloadCompletion(session_task, error);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForFileOperationTimeout, ^{
base::RunLoop().RunUntilIdle();
return !base::PathExists(temp_file);
}));
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests changing MIME type during the download.
TEST_F(DownloadSessionTaskImplTest, MimeTypeChange) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
ASSERT_EQ(kMimeType, task_->GetOriginalMimeType());
ASSERT_EQ(kMimeType, task_->GetMimeType());
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
const char kOtherMimeType[] = "application/foo";
session_task.response =
[[NSURLResponse alloc] initWithURL:[NSURL URLWithString:@(kUrl)]
MIMEType:@(kOtherMimeType)
expectedContentLength:0
textEncodingName:nil];
SimulateDownloadCompletion(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
EXPECT_EQ(kMimeType, task_->GetOriginalMimeType());
EXPECT_EQ(kOtherMimeType, task_->GetMimeType());
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests updating HTTP response code.
TEST_F(DownloadSessionTaskImplTest, HttpResponseCode) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
int kHttpCode = 303;
session_task.response =
[[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@(kUrl)]
statusCode:303
HTTPVersion:nil
headerFields:nil];
SimulateDownloadCompletion(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
return task_->IsDone();
}));
EXPECT_EQ(kHttpCode, task_->GetHttpCode());
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
}
// Tests that destructing DownloadTaskImpl calls -[NSURLSessionDataTask cancel]
// and OnTaskDestroyed().
TEST_F(DownloadSessionTaskImplTest, DownloadTaskDestruction) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
task_ = nullptr; // Destruct DownloadTaskImpl.
EXPECT_TRUE(session_task.state = NSURLSessionTaskStateCanceling);
}
// Tests that shutting down DownloadTaskImpl calls
// -[NSURLSessionDataTask cancel], but does not call OnTaskDestroyed().
TEST_F(DownloadSessionTaskImplTest, DownloadTaskShutdown) {
EXPECT_CALL(task_observer_, OnDownloadUpdated(task_.get()));
CRWFakeNSURLSessionTask* session_task = Start();
ASSERT_TRUE(session_task);
testing::Mock::VerifyAndClearExpectations(&task_observer_);
task_->ShutDown();
EXPECT_TRUE(session_task.state = NSURLSessionTaskStateCanceling);
}
// Tests valid data:// url downloads.
TEST_F(DownloadSessionTaskImplTest, ValidDataUrl) {
// Create data:// url download task.
char kDataUrl[] = "data:text/plain;base64,Q2hyb21pdW0=";
auto task = std::make_unique<DownloadSessionTaskImpl>(
&web_state_, GURL(kDataUrl), @"GET", kContentDisposition,
/*total_bytes=*/-1, kMimeType, task_delegate_.configuration().identifier,
&task_delegate_);
// Start and wait until the download is complete.
task->Start(base::FilePath(), web::DownloadTask::Destination::kToMemory);
DownloadSessionTaskImpl* task_ptr = task.get();
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
base::RunLoop().RunUntilIdle();
return task_ptr->IsDone();
}));
// Verify the state of downloaded task.
const char kTestData[] = "Chromium";
EXPECT_EQ(DownloadTask::State::kComplete, task->GetState());
EXPECT_EQ(0, task->GetErrorCode());
EXPECT_EQ(strlen(kTestData), static_cast<size_t>(task->GetTotalBytes()));
EXPECT_EQ(strlen(kTestData), static_cast<size_t>(task->GetReceivedBytes()));
EXPECT_EQ(100, task->GetPercentComplete());
EXPECT_EQ("text/plain", task->GetMimeType());
EXPECT_NSEQ(@(kTestData),
[[NSString alloc] initWithData:task->GetResponseData()
encoding:NSUTF8StringEncoding]);
// One OnTaskDestroyed for |task_| and one for |task|.
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task.get()));
}
// Tests empty data:// url downloads.
TEST_F(DownloadSessionTaskImplTest, EmptyDataUrl) {
// Create data:// url download task.
char kDataUrl[] = "data://";
auto task = std::make_unique<DownloadSessionTaskImpl>(
&web_state_, GURL(kDataUrl), @"GET", kContentDisposition,
/*total_bytes=*/-1, kMimeType, task_delegate_.configuration().identifier,
&task_delegate_);
// Start and wait until the download is complete.
task->Start(base::FilePath(), DownloadTask::Destination::kToMemory);
DownloadSessionTaskImpl* task_ptr = task.get();
ASSERT_TRUE(WaitUntilConditionOrTimeout(kWaitForDownloadTimeout, ^{
base::RunLoop().RunUntilIdle();
return task_ptr->IsDone();
}));
// Verify the state of downloaded task.
EXPECT_EQ(DownloadTask::State::kFailed, task->GetState());
EXPECT_EQ(net::ERR_INVALID_URL, task->GetErrorCode());
EXPECT_EQ(-1, task->GetTotalBytes());
EXPECT_EQ(0, task->GetReceivedBytes());
EXPECT_EQ(0, task->GetPercentComplete());
EXPECT_EQ("", task->GetMimeType());
EXPECT_NSEQ(@"", [[NSString alloc] initWithData:task->GetResponseData()
encoding:NSUTF8StringEncoding]);
// One OnTaskDestroyed for |task_| and one for |task|.
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task_.get()));
EXPECT_CALL(task_delegate_, OnTaskDestroyed(task.get()));
}
} // namespace web