summaryrefslogtreecommitdiffstats
path: root/chrome/browser/download/download_manager_unittest.cc
blob: 3f2c66937a6254961527c0f2f7083d7ea68ab310 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
// Copyright (c) 2011 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 <set>
#include <string>

#include "base/bind.h"
#include "base/file_util.h"
#include "base/i18n/number_formatting.h"
#include "base/i18n/rtl.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/scoped_temp_dir.h"
#include "base/stl_util.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_profile.h"
#include "content/browser/download/download_buffer.h"
#include "content/browser/download/download_create_info.h"
#include "content/browser/download/download_file_impl.h"
#include "content/browser/download/download_file_manager.h"
#include "content/browser/download/download_id_factory.h"
#include "content/browser/download/download_request_handle.h"
#include "content/browser/download/download_status_updater.h"
#include "content/browser/download/interrupt_reasons.h"
#include "content/browser/download/mock_download_file.h"
#include "content/browser/download/mock_download_manager.h"
#include "content/public/browser/download_item.h"
#include "content/public/browser/download_manager.h"
#include "content/test/test_browser_thread.h"
#include "grit/generated_resources.h"
#include "net/base/io_buffer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gmock_mutant.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/text/bytes_formatting.h"

#if defined(USE_AURA) && defined(OS_WIN)
// http://crbug.com/105200
#define MAYBE_StartDownload DISABLED_StartDownload
#define MAYBE_DownloadOverwriteTest DISABLED_DownloadOverwriteTest
#define MAYBE_DownloadRemoveTest DISABLED_DownloadRemoveTest
#else
#define MAYBE_StartDownload StartDownload
#define MAYBE_DownloadOverwriteTest DownloadOverwriteTest
#define MAYBE_DownloadRemoveTest DownloadRemoveTest
#endif

using content::BrowserThread;
using content::DownloadFile;
using content::DownloadItem;
using content::DownloadManager;
using content::WebContents;

namespace {

class MockDownloadFileFactory
    : public DownloadFileManager::DownloadFileFactory {
 public:
  MockDownloadFileFactory() {}

  virtual DownloadFile* CreateFile(DownloadCreateInfo* info,
                                   const DownloadRequestHandle& request_handle,
                                   DownloadManager* download_manager,
                                   bool calculate_hash) OVERRIDE;
};

DownloadFile* MockDownloadFileFactory::CreateFile(
    DownloadCreateInfo* info,
    const DownloadRequestHandle& request_handle,
    DownloadManager* download_manager,
    bool calculate_hash) {
  NOTREACHED();
  return NULL;
}

DownloadId::Domain kValidIdDomain = "valid DownloadId::Domain";

class TestDownloadManagerDelegate : public ChromeDownloadManagerDelegate {
 public:
  explicit TestDownloadManagerDelegate(Profile* profile)
      : ChromeDownloadManagerDelegate(profile),
        mark_content_dangerous_(false) {
  }

  virtual void ChooseDownloadPath(WebContents* web_contents,
                                  const FilePath& suggested_path,
                                  void* data) OVERRIDE {
    if (!expected_suggested_path_.empty()) {
      EXPECT_STREQ(expected_suggested_path_.value().c_str(),
                   suggested_path.value().c_str());
    }
    if (file_selection_response_.empty()) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          base::Bind(&DownloadManager::FileSelectionCanceled,
                     download_manager_.get(),
                     base::Unretained(data)));
    } else {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          base::Bind(&DownloadManager::FileSelected,
                     download_manager_.get(),
                     file_selection_response_,
                     base::Unretained(data)));
    }
    expected_suggested_path_.clear();
    file_selection_response_.clear();
  }

  void SetFileSelectionExpectation(const FilePath& suggested_path,
                                   const FilePath& response) {
    expected_suggested_path_ = suggested_path;
    file_selection_response_ = response;
  }

  void SetMarkContentsDangerous(bool dangerous) {
    mark_content_dangerous_ = dangerous;
  }

  virtual bool ShouldCompleteDownload(DownloadItem* item) {
    if (mark_content_dangerous_) {
      BrowserThread::PostTask(
          BrowserThread::UI, FROM_HERE,
          base::Bind(&TestDownloadManagerDelegate::MarkContentDangerous,
                     this, item->GetId()));
      mark_content_dangerous_ = false;
      return false;
    } else {
      return true;
    }
  }

 private:
  void MarkContentDangerous(int32 download_id) {
    DownloadItem* item = download_manager_->GetActiveDownloadItem(download_id);
    if (!item)
      return;
    item->MarkContentDangerous();
    item->MaybeCompleteDownload();
  }

  FilePath expected_suggested_path_;
  FilePath file_selection_response_;
  bool mark_content_dangerous_;
};

} // namespace

class DownloadManagerTest : public testing::Test {
 public:
  static const char* kTestData;
  static const size_t kTestDataLen;

  DownloadManagerTest()
      : profile_(new TestingProfile()),
        download_manager_delegate_(new TestDownloadManagerDelegate(
            profile_.get())),
        id_factory_(new DownloadIdFactory(kValidIdDomain)),
        download_manager_(DownloadManager::Create(
            download_manager_delegate_,
            id_factory_,
            &download_status_updater_)),
        ui_thread_(BrowserThread::UI, &message_loop_),
        file_thread_(BrowserThread::FILE, &message_loop_),
        download_buffer_(new content::DownloadBuffer) {
    download_manager_->Init(profile_.get());
    download_manager_delegate_->SetDownloadManager(download_manager_);
  }

  ~DownloadManagerTest() {
    download_manager_->Shutdown();
    // profile_ must outlive download_manager_, so we explicitly delete
    // download_manager_ first.
    download_manager_ = NULL;
    download_manager_delegate_ = NULL;
    profile_.reset(NULL);
    message_loop_.RunAllPending();
  }

  void AddDownloadToFileManager(int id, DownloadFile* download_file) {
    file_manager()->downloads_[DownloadId(kValidIdDomain, id)] =
      download_file;
  }

  void OnResponseCompleted(int32 download_id, int64 size,
                           const std::string& hash) {
    download_manager_->OnResponseCompleted(download_id, size, hash);
  }

  void FileSelected(const FilePath& path, void* params) {
    download_manager_->FileSelected(path, params);
  }

  void ContinueDownloadWithPath(DownloadItem* download, const FilePath& path) {
    download_manager_->ContinueDownloadWithPath(download, path);
  }

  void UpdateData(int32 id, const char* data, size_t length) {
    // We are passing ownership of this buffer to the download file manager.
    net::IOBuffer* io_buffer = new net::IOBuffer(length);
    // We need |AddRef()| because we do a |Release()| in |UpdateDownload()|.
    io_buffer->AddRef();
    memcpy(io_buffer->data(), data, length);

    download_buffer_->AddData(io_buffer, length);

    BrowserThread::PostTask(
        BrowserThread::FILE, FROM_HERE,
        base::Bind(&DownloadFileManager::UpdateDownload, file_manager_.get(),
                   DownloadId(kValidIdDomain, id), download_buffer_));

    message_loop_.RunAllPending();
  }

  void OnDownloadInterrupted(int32 download_id, int64 size,
                             const std::string& hash_state,
                             InterruptReason reason) {
    download_manager_->OnDownloadInterrupted(download_id, size,
                                             hash_state, reason);
  }

  // Get the download item with ID |id|.
  DownloadItem* GetActiveDownloadItem(int32 id) {
    return download_manager_->GetActiveDownload(id);
  }

 protected:
  DownloadStatusUpdater download_status_updater_;
  scoped_ptr<TestingProfile> profile_;
  scoped_refptr<TestDownloadManagerDelegate> download_manager_delegate_;
  scoped_refptr<DownloadIdFactory> id_factory_;
  scoped_refptr<DownloadManager> download_manager_;
  scoped_refptr<DownloadFileManager> file_manager_;
  MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread file_thread_;
  scoped_refptr<content::DownloadBuffer> download_buffer_;

  DownloadFileManager* file_manager() {
    if (!file_manager_) {
      file_manager_ = new DownloadFileManager(NULL,
                                              new MockDownloadFileFactory);
      download_manager_->SetFileManager(file_manager_);
    }
    return file_manager_;
  }

  DISALLOW_COPY_AND_ASSIGN(DownloadManagerTest);
};

const char* DownloadManagerTest::kTestData = "a;sdlfalsdfjalsdkfjad";
const size_t DownloadManagerTest::kTestDataLen =
    strlen(DownloadManagerTest::kTestData);

// A DownloadFile that we can inject errors into.
class DownloadFileWithErrors : public DownloadFileImpl {
 public:
  DownloadFileWithErrors(DownloadCreateInfo* info,
                         DownloadManager* manager,
                         bool calculate_hash);
  virtual ~DownloadFileWithErrors() {}

  // BaseFile delegated functions.
  virtual net::Error Initialize();
  virtual net::Error AppendDataToFile(const char* data, size_t data_len);
  virtual net::Error Rename(const FilePath& full_path);

  void set_forced_error(net::Error error) { forced_error_ = error; }
  void clear_forced_error() { forced_error_ = net::OK; }
  net::Error forced_error() const { return forced_error_; }

 private:
  net::Error ReturnError(net::Error function_error) {
    if (forced_error_ != net::OK) {
      net::Error ret = forced_error_;
      clear_forced_error();
      return ret;
    }

    return function_error;
  }

  net::Error forced_error_;
};

DownloadFileWithErrors::DownloadFileWithErrors(DownloadCreateInfo* info,
                                               DownloadManager* manager,
                                               bool calculate_hash)
    : DownloadFileImpl(info,
                       new DownloadRequestHandle(),
                       manager,
                       calculate_hash),
      forced_error_(net::OK) {
}

net::Error DownloadFileWithErrors::Initialize() {
  return ReturnError(DownloadFileImpl::Initialize());
}

net::Error DownloadFileWithErrors::AppendDataToFile(const char* data,
                                                    size_t data_len) {
  return ReturnError(DownloadFileImpl::AppendDataToFile(data, data_len));
}

net::Error DownloadFileWithErrors::Rename(const FilePath& full_path) {
  return ReturnError(DownloadFileImpl::Rename(full_path));
}

namespace {

const struct {
  const char* url;
  const char* mime_type;
  bool save_as;
  bool prompt_for_download;
  bool expected_save_as;
} kStartDownloadCases[] = {
  { "http://www.foo.com/dont-open.html",
    "text/html",
    false,
    false,
    false, },
  { "http://www.foo.com/save-as.html",
    "text/html",
    true,
    false,
    true, },
  { "http://www.foo.com/always-prompt.html",
    "text/html",
    false,
    true,
    true, },
  { "http://www.foo.com/user-script-text-html-mimetype.user.js",
    "text/html",
    false,
    false,
    false, },
  { "http://www.foo.com/extensionless-extension",
    "application/x-chrome-extension",
    true,
    false,
    true, },
  { "http://www.foo.com/save-as.pdf",
    "application/pdf",
    true,
    false,
    true, },
  { "http://www.foo.com/sometimes_prompt.pdf",
    "application/pdf",
    false,
    true,
    false, },
  { "http://www.foo.com/always_prompt.jar",
    "application/jar",
    false,
    true,
    true, },
};

const struct {
  FilePath::StringType suggested_path;
  DownloadStateInfo::DangerType danger;
  bool finish_before_rename;
  int expected_rename_count;
} kDownloadRenameCases[] = {
  // Safe download, download finishes BEFORE file name determined.
  // Renamed twice (linear path through UI).  Crdownload file does not need
  // to be deleted.
  { FILE_PATH_LITERAL("foo.zip"), DownloadStateInfo::NOT_DANGEROUS, true, 2, },
  // Potentially dangerous download (e.g., file is dangerous), download finishes
  // BEFORE file name determined. Needs to be renamed only once.
  { FILE_PATH_LITERAL("Unconfirmed xxx.crdownload"),
    DownloadStateInfo::MAYBE_DANGEROUS_CONTENT, true, 1, },
  { FILE_PATH_LITERAL("Unconfirmed xxx.crdownload"),
    DownloadStateInfo::DANGEROUS_FILE, true, 1, },
  // Safe download, download finishes AFTER file name determined.
  // Needs to be renamed twice.
  { FILE_PATH_LITERAL("foo.zip"), DownloadStateInfo::NOT_DANGEROUS, false, 2, },
  // Potentially dangerous download, download finishes AFTER file name
  // determined. Needs to be renamed only once.
  { FILE_PATH_LITERAL("Unconfirmed xxx.crdownload"),
    DownloadStateInfo::MAYBE_DANGEROUS_CONTENT, false, 1, },
  { FILE_PATH_LITERAL("Unconfirmed xxx.crdownload"),
    DownloadStateInfo::DANGEROUS_FILE, false, 1, },
};

// This is an observer that records what download IDs have opened a select
// file dialog.
class SelectFileObserver : public content::DownloadManager::Observer {
 public:
  explicit SelectFileObserver(DownloadManager* download_manager)
      : download_manager_(download_manager) {
    DCHECK(download_manager_.get());
    download_manager_->AddObserver(this);
  }

  ~SelectFileObserver() {
    download_manager_->RemoveObserver(this);
  }

  // Downloadmanager::Observer functions.
  virtual void ModelChanged() {}
  virtual void ManagerGoingDown() {}
  virtual void SelectFileDialogDisplayed(int32 id) {
    file_dialog_ids_.insert(id);
  }

  bool ShowedFileDialogForId(int32 id) {
    return file_dialog_ids_.find(id) != file_dialog_ids_.end();
  }

 private:
  std::set<int32> file_dialog_ids_;
  scoped_refptr<DownloadManager> download_manager_;
};

// This observer tracks the progress of |DownloadItem|s.
class ItemObserver : public DownloadItem::Observer {
 public:
  explicit ItemObserver(DownloadItem* tracked)
      : tracked_(tracked), states_hit_(0),
        was_updated_(false), was_opened_(false) {
    DCHECK(tracked_);
    tracked_->AddObserver(this);
    // Record the initial state.
    OnDownloadUpdated(tracked_);
  }
  ~ItemObserver() {
    tracked_->RemoveObserver(this);
  }

  bool hit_state(int state) const {
    return (1 << state) & states_hit_;
  }
  bool was_updated() const { return was_updated_; }
  bool was_opened() const { return was_opened_; }

 private:
  // DownloadItem::Observer methods
  virtual void OnDownloadUpdated(DownloadItem* download) {
    DCHECK_EQ(tracked_, download);
    states_hit_ |= (1 << download->GetState());
    was_updated_ = true;
  }
  virtual void OnDownloadOpened(DownloadItem* download) {
    DCHECK_EQ(tracked_, download);
    states_hit_ |= (1 << download->GetState());
    was_opened_ = true;
  }

  DownloadItem* tracked_;
  int states_hit_;
  bool was_updated_;
  bool was_opened_;
};

}  // namespace

TEST_F(DownloadManagerTest, MAYBE_StartDownload) {
  content::TestBrowserThread io_thread(BrowserThread::IO, &message_loop_);
  PrefService* prefs = profile_->GetPrefs();
  prefs->SetFilePath(prefs::kDownloadDefaultDirectory, FilePath());
  DownloadPrefs* download_prefs =
      DownloadPrefs::FromDownloadManager(download_manager_);
  download_prefs->EnableAutoOpenBasedOnExtension(
      FilePath(FILE_PATH_LITERAL("example.pdf")));

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kStartDownloadCases); ++i) {
    prefs->SetBoolean(prefs::kPromptForDownload,
                      kStartDownloadCases[i].prompt_for_download);

    SelectFileObserver observer(download_manager_);
    // Normally, the download system takes ownership of info, and is
    // responsible for deleting it.  In these unit tests, however, we
    // don't call the function that deletes it, so we do so ourselves.
    scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
    info->download_id = DownloadId(kValidIdDomain, static_cast<int>(i));
    info->prompt_user_for_save_location = kStartDownloadCases[i].save_as;
    info->url_chain.push_back(GURL(kStartDownloadCases[i].url));
    info->mime_type = kStartDownloadCases[i].mime_type;
    download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());

    DownloadFile* download_file(
        new DownloadFileImpl(info.get(), new DownloadRequestHandle(),
                             download_manager_, false));
    AddDownloadToFileManager(info->download_id.local(), download_file);
    download_file->Initialize();
    download_manager_->StartDownload(info->download_id.local());
    message_loop_.RunAllPending();

    // SelectFileObserver will have recorded any attempt to open the
    // select file dialog.
    // Note that DownloadManager::FileSelectionCanceled() is never called.
    EXPECT_EQ(kStartDownloadCases[i].expected_save_as,
              observer.ShowedFileDialogForId(i));
  }
}

namespace {

enum PromptForSaveLocation {
  DONT_PROMPT,
  PROMPT
};

enum ValidateDangerousDownload {
  DONT_VALIDATE,
  VALIDATE
};

// Test cases to be used with DownloadFilenameTest.  The paths that are used in
// test cases can contain "$dl" and "$alt" tokens which are replaced by a
// default download path, and an alternate download path in
// ExpandFilenameTestPath() below.
const struct DownloadFilenameTestCase {

  // Fields to be set in DownloadStateInfo when calling SetFileCheckResults().
  const FilePath::CharType*     suggested_path;
  const FilePath::CharType*     target_name;
  PromptForSaveLocation         prompt_user_for_save_location;
  DownloadStateInfo::DangerType danger_type;

  // If we receive a ChooseDownloadPath() call to prompt the user for a download
  // location, |prompt_path| is the expected prompt path. The
  // TestDownloadManagerDelegate will respond with |final_path|. If |final_path|
  // is empty, then the file choose dialog be cancelled.
  const FilePath::CharType*     prompt_path;

  // The expected intermediate path for the download.
  const FilePath::CharType*     intermediate_path;

  // The expected final path for the download.
  const FilePath::CharType*     final_path;

  // If this is a dangerous download, then we will either validate the download
  // or delete it depending on the value of |validate_dangerous_download|.
  ValidateDangerousDownload     validate_dangerous_download;
} kDownloadFilenameTestCases[] = {
  {
    // 0: A safe file is downloaded with no prompting.
    FILE_PATH_LITERAL("$dl/foo.txt"),
    FILE_PATH_LITERAL(""),
    DONT_PROMPT,
    DownloadStateInfo::NOT_DANGEROUS,
    FILE_PATH_LITERAL(""),
    FILE_PATH_LITERAL("$dl/foo.txt.crdownload"),
    FILE_PATH_LITERAL("$dl/foo.txt"),
    DONT_VALIDATE
  },
  {
    // 1: A safe file is downloaded with prompting.
    FILE_PATH_LITERAL("$dl/foo.txt"),
    FILE_PATH_LITERAL(""),
    PROMPT,
    DownloadStateInfo::NOT_DANGEROUS,
    FILE_PATH_LITERAL("$dl/foo.txt"),
    FILE_PATH_LITERAL("$dl/foo.txt.crdownload"),
    FILE_PATH_LITERAL("$dl/foo.txt"),
    DONT_VALIDATE
  },
  {
    // 2: A safe file is downloaded. The filename is changed before the dialog
    // completes.
    FILE_PATH_LITERAL("$dl/foo.txt"),
    FILE_PATH_LITERAL(""),
    PROMPT,
    DownloadStateInfo::NOT_DANGEROUS,
    FILE_PATH_LITERAL("$dl/foo.txt"),
    FILE_PATH_LITERAL("$dl/bar.txt.crdownload"),
    FILE_PATH_LITERAL("$dl/bar.txt"),
    DONT_VALIDATE
  },
  {
    // 3: A safe file is downloaded. The download path is changed before the
    // dialog completes.
    FILE_PATH_LITERAL("$dl/foo.txt"),
    FILE_PATH_LITERAL(""),
    PROMPT,
    DownloadStateInfo::NOT_DANGEROUS,
    FILE_PATH_LITERAL("$dl/foo.txt"),
    FILE_PATH_LITERAL("$alt/bar.txt.crdownload"),
    FILE_PATH_LITERAL("$alt/bar.txt"),
    DONT_VALIDATE
  },
  {
    // 4: Potentially dangerous content.
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("foo.exe"),
    DONT_PROMPT,
    DownloadStateInfo::MAYBE_DANGEROUS_CONTENT,
    FILE_PATH_LITERAL(""),
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("$dl/foo.exe"),
    DONT_VALIDATE
  },
  {
    // 5: Potentially dangerous content. Uses "Save as."
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("foo.exe"),
    PROMPT,
    DownloadStateInfo::MAYBE_DANGEROUS_CONTENT,
    FILE_PATH_LITERAL("$dl/foo.exe"),
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("$dl/foo.exe"),
    DONT_VALIDATE
  },
  {
    // 6: Potentially dangerous content. Uses "Save as." The download filename
    // is changed before the dialog completes.
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("foo.exe"),
    PROMPT,
    DownloadStateInfo::MAYBE_DANGEROUS_CONTENT,
    FILE_PATH_LITERAL("$dl/foo.exe"),
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("$dl/bar.exe"),
    DONT_VALIDATE
  },
  {
    // 7: Potentially dangerous content. Uses "Save as." The download directory
    // is changed before the dialog completes.
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("foo.exe"),
    PROMPT,
    DownloadStateInfo::MAYBE_DANGEROUS_CONTENT,
    FILE_PATH_LITERAL("$dl/foo.exe"),
    FILE_PATH_LITERAL("$alt/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("$alt/bar.exe"),
    DONT_VALIDATE
  },
  {
    // 8: Dangerous content. Saved directly.
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("foo.exe"),
    PROMPT,
    DownloadStateInfo::DANGEROUS_URL,
    FILE_PATH_LITERAL(""),
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("$dl/foo.exe"),
    VALIDATE
  },
  {
    // 9: Dangerous content. Saved directly. Not validated.
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("foo.exe"),
    DONT_PROMPT,
    DownloadStateInfo::DANGEROUS_URL,
    FILE_PATH_LITERAL(""),
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL(""),
    DONT_VALIDATE
  },
  {
    // 10: Dangerous content. Uses "Save as." The download directory is changed
    // before the dialog completes.
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("foo.exe"),
    PROMPT,
    DownloadStateInfo::DANGEROUS_URL,
    FILE_PATH_LITERAL("$dl/foo.exe"),
    FILE_PATH_LITERAL("$alt/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("$alt/bar.exe"),
    VALIDATE
  },
  {
    // 11: A safe file is download. The target file exists, but we don't
    // uniquify. Safe downloads are uniquified in ChromeDownloadManagerDelegate
    // instead of DownloadManagerImpl.
    FILE_PATH_LITERAL("$dl/exists.txt"),
    FILE_PATH_LITERAL(""),
    DONT_PROMPT,
    DownloadStateInfo::NOT_DANGEROUS,
    FILE_PATH_LITERAL(""),
    FILE_PATH_LITERAL("$dl/exists.txt.crdownload"),
    FILE_PATH_LITERAL("$dl/exists.txt"),
    DONT_VALIDATE
  },
  {
    // 12: A potentially dangerous file is download. The target file exists. The
    // target path is uniquified.
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("exists.exe"),
    DONT_PROMPT,
    DownloadStateInfo::MAYBE_DANGEROUS_CONTENT,
    FILE_PATH_LITERAL(""),
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("$dl/exists (1).exe"),
    DONT_VALIDATE
  },
  {
    // 13: A dangerous file is download. The target file exists. The target path
    // is uniquified.
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("exists.exe"),
    DONT_PROMPT,
    DownloadStateInfo::DANGEROUS_CONTENT,
    FILE_PATH_LITERAL(""),
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("$dl/exists (1).exe"),
    VALIDATE
  },
  {
    // 14: A potentially dangerous file is download with prompting. The target
    // file exists. The target path is not uniquified because the filename was
    // given to us by the user.
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("exists.exe"),
    PROMPT,
    DownloadStateInfo::MAYBE_DANGEROUS_CONTENT,
    FILE_PATH_LITERAL("$dl/exists.exe"),
    FILE_PATH_LITERAL("$dl/Unconfirmed xxx.download"),
    FILE_PATH_LITERAL("$dl/exists.exe"),
    DONT_VALIDATE
  },
};

FilePath ExpandFilenameTestPath(const FilePath::CharType* template_path,
                                const FilePath& downloads_dir,
                                const FilePath& alternate_dir) {
  FilePath::StringType path(template_path);
  ReplaceSubstringsAfterOffset(&path, 0, FILE_PATH_LITERAL("$dl"),
                               downloads_dir.value());
  ReplaceSubstringsAfterOffset(&path, 0, FILE_PATH_LITERAL("$alt"),
                               alternate_dir.value());
  FilePath file_path(path);
#if defined(FILE_PATH_USES_WIN_SEPARATORS)
  file_path = file_path.NormalizeWindowsPathSeparators();
#endif
  return file_path;
}

} // namespace

TEST_F(DownloadManagerTest, DownloadFilenameTest) {
  ScopedTempDir scoped_dl_dir;
  ASSERT_TRUE(scoped_dl_dir.CreateUniqueTempDir());

  FilePath downloads_dir(scoped_dl_dir.path());
  FilePath alternate_dir(downloads_dir.Append(FILE_PATH_LITERAL("Foo")));

  // We create a known file to test file uniquification.
  file_util::WriteFile(downloads_dir.Append(FILE_PATH_LITERAL("exists.txt")),
                       "", 0);
  file_util::WriteFile(downloads_dir.Append(FILE_PATH_LITERAL("exists.exe")),
                       "", 0);

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDownloadFilenameTestCases); ++i) {
    scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
    info->download_id = DownloadId(kValidIdDomain, i);
    info->url_chain.push_back(GURL());

    MockDownloadFile::StatisticsRecorder recorder;
    MockDownloadFile* download_file(new MockDownloadFile(
        info.get(), DownloadRequestHandle(), download_manager_, &recorder));
    FilePath suggested_path(ExpandFilenameTestPath(
        kDownloadFilenameTestCases[i].suggested_path,
        downloads_dir, alternate_dir));
    FilePath prompt_path(ExpandFilenameTestPath(
        kDownloadFilenameTestCases[i].prompt_path,
        downloads_dir, alternate_dir));
    FilePath intermediate_path(ExpandFilenameTestPath(
        kDownloadFilenameTestCases[i].intermediate_path,
        downloads_dir, alternate_dir));
    FilePath final_path(ExpandFilenameTestPath(
        kDownloadFilenameTestCases[i].final_path,
        downloads_dir, alternate_dir));
    // If |final_path| is empty, its a signal that the download doesn't
    // complete.  Therefore it will only go through a single rename.
    int expected_rename_count = (final_path.empty() ? 1 : 2);

    AddDownloadToFileManager(info->download_id.local(), download_file);

    download_file->SetExpectedPath(0, intermediate_path);
    if (!final_path.empty())
      download_file->SetExpectedPath(1, final_path);

    download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());
    DownloadItem* download = GetActiveDownloadItem(i);
    ASSERT_TRUE(download != NULL);

    DownloadStateInfo state = download->GetStateInfo();
    state.suggested_path = suggested_path;
    state.danger = kDownloadFilenameTestCases[i].danger_type;
    state.prompt_user_for_save_location =
        (kDownloadFilenameTestCases[i].prompt_user_for_save_location == PROMPT);
    state.target_name = FilePath(kDownloadFilenameTestCases[i].target_name);
    if (state.danger == DownloadStateInfo::DANGEROUS_CONTENT) {
      // DANGEROUS_CONTENT will only be known once we have all the data. We let
      // our TestDownloadManagerDelegate handle it.
      state.danger = DownloadStateInfo::MAYBE_DANGEROUS_CONTENT;
      download_manager_delegate_->SetMarkContentsDangerous(true);
    }
    download->SetFileCheckResults(state);
    download_manager_delegate_->SetFileSelectionExpectation(
        prompt_path, final_path);
    download_manager_->RestartDownload(i);
    message_loop_.RunAllPending();

    OnResponseCompleted(i, 1024, std::string("fake_hash"));
    message_loop_.RunAllPending();

    if (download->GetSafetyState() == DownloadItem::DANGEROUS) {
      if (kDownloadFilenameTestCases[i].validate_dangerous_download == VALIDATE)
        download->DangerousDownloadValidated();
      else
        download->Delete(DownloadItem::DELETE_DUE_TO_USER_DISCARD);
      message_loop_.RunAllPending();
      // |download| might be deleted when we get here.
    }

    EXPECT_EQ(
        expected_rename_count,
        recorder.Count(MockDownloadFile::StatisticsRecorder::STAT_RENAME))
        << "For test run " << i;
  }
}

TEST_F(DownloadManagerTest, DownloadRenameTest) {
  using ::testing::_;
  using ::testing::CreateFunctor;
  using ::testing::Invoke;
  using ::testing::Return;

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDownloadRenameCases); ++i) {
    // Normally, the download system takes ownership of info, and is
    // responsible for deleting it.  In these unit tests, however, we
    // don't call the function that deletes it, so we do so ourselves.
    scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
    info->download_id = DownloadId(kValidIdDomain, static_cast<int>(i));
    info->prompt_user_for_save_location = false;
    info->url_chain.push_back(GURL());
    const FilePath new_path(kDownloadRenameCases[i].suggested_path);

    MockDownloadFile::StatisticsRecorder recorder;
    MockDownloadFile* download_file(
        new MockDownloadFile(info.get(),
                             DownloadRequestHandle(),
                             download_manager_,
                             &recorder));
    AddDownloadToFileManager(info->download_id.local(), download_file);

    // |download_file| is owned by DownloadFileManager.
    if (kDownloadRenameCases[i].expected_rename_count == 1) {
      download_file->SetExpectedPath(0, new_path);
    } else {
      ASSERT_EQ(2, kDownloadRenameCases[i].expected_rename_count);
      FilePath crdownload(download_util::GetCrDownloadPath(new_path));
      download_file->SetExpectedPath(0, crdownload);
      download_file->SetExpectedPath(1, new_path);
    }
    download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());
    DownloadItem* download = GetActiveDownloadItem(i);
    ASSERT_TRUE(download != NULL);
    DownloadStateInfo state = download->GetStateInfo();
    state.danger = kDownloadRenameCases[i].danger;
    download->SetFileCheckResults(state);

    int32* id_ptr = new int32;
    *id_ptr = i;  // Deleted in FileSelected().
    if (kDownloadRenameCases[i].finish_before_rename) {
      OnResponseCompleted(i, 1024, std::string("fake_hash"));
      message_loop_.RunAllPending();
      FileSelected(new_path, id_ptr);
    } else {
      FileSelected(new_path, id_ptr);
      message_loop_.RunAllPending();
      OnResponseCompleted(i, 1024, std::string("fake_hash"));
    }
    message_loop_.RunAllPending();
    EXPECT_EQ(
        kDownloadRenameCases[i].expected_rename_count,
        recorder.Count(MockDownloadFile::StatisticsRecorder::STAT_RENAME));
  }
}

TEST_F(DownloadManagerTest, DownloadInterruptTest) {
  using ::testing::_;
  using ::testing::CreateFunctor;
  using ::testing::Invoke;
  using ::testing::Return;

  // Normally, the download system takes ownership of info, and is
  // responsible for deleting it.  In these unit tests, however, we
  // don't call the function that deletes it, so we do so ourselves.
  scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
  info->download_id = DownloadId(kValidIdDomain, 0);
  info->prompt_user_for_save_location = false;
  info->url_chain.push_back(GURL());
  info->total_bytes = static_cast<int64>(kTestDataLen);
  const FilePath new_path(FILE_PATH_LITERAL("foo.zip"));
  const FilePath cr_path(download_util::GetCrDownloadPath(new_path));

  MockDownloadFile::StatisticsRecorder recorder;
  MockDownloadFile* download_file(
      new MockDownloadFile(info.get(),
                           DownloadRequestHandle(),
                           download_manager_,
                           &recorder));
  AddDownloadToFileManager(info->download_id.local(), download_file);

  // |download_file| is owned by DownloadFileManager.
  download_file->SetExpectedPath(0, cr_path);

  download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());

  DownloadItem* download = GetActiveDownloadItem(0);
  ASSERT_TRUE(download != NULL);
  scoped_ptr<DownloadItemModel> download_item_model(
      new DownloadItemModel(download));

  EXPECT_EQ(DownloadItem::IN_PROGRESS, download->GetState());
  scoped_ptr<ItemObserver> observer(new ItemObserver(download));

  download_file->AppendDataToFile(kTestData, kTestDataLen);

  ContinueDownloadWithPath(download, new_path);
  message_loop_.RunAllPending();
  EXPECT_EQ(1,
            recorder.Count(MockDownloadFile::StatisticsRecorder::STAT_RENAME));
  EXPECT_TRUE(GetActiveDownloadItem(0) != NULL);

  int64 error_size = 3;
  OnDownloadInterrupted(0, error_size, "",
                        DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED);
  message_loop_.RunAllPending();

  EXPECT_TRUE(GetActiveDownloadItem(0) == NULL);
  EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
  EXPECT_TRUE(observer->hit_state(DownloadItem::INTERRUPTED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::COMPLETE));
  EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
  EXPECT_TRUE(observer->was_updated());
  EXPECT_FALSE(observer->was_opened());
  EXPECT_FALSE(download->GetFileExternallyRemoved());
  EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());
  ui::DataUnits amount_units = ui::GetByteDisplayUnits(kTestDataLen);
  string16 simple_size =
      ui::FormatBytesWithUnits(error_size, amount_units, false);
  string16 simple_total = base::i18n::GetDisplayStringInLTRDirectionality(
      ui::FormatBytesWithUnits(kTestDataLen, amount_units, true));
  EXPECT_EQ(download_item_model->GetStatusText(),
            l10n_util::GetStringFUTF16(IDS_DOWNLOAD_STATUS_INTERRUPTED,
                                       simple_size,
                                       simple_total));

  download->Cancel(true);

  EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
  EXPECT_TRUE(observer->hit_state(DownloadItem::INTERRUPTED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::COMPLETE));
  EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
  EXPECT_TRUE(observer->was_updated());
  EXPECT_FALSE(observer->was_opened());
  EXPECT_FALSE(download->GetFileExternallyRemoved());
  EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());
  EXPECT_EQ(download->GetReceivedBytes(), error_size);
  EXPECT_EQ(download->GetTotalBytes(), static_cast<int64>(kTestDataLen));
}

// Test the behavior of DownloadFileManager and DownloadManager in the event
// of a file error while writing the download to disk.
TEST_F(DownloadManagerTest, DownloadFileErrorTest) {
  // Create a temporary file and a mock stream.
  FilePath path;
  ASSERT_TRUE(file_util::CreateTemporaryFile(&path));

  // This file stream will be used, until the first rename occurs.
  net::FileStream* stream = new net::FileStream;
  ASSERT_EQ(0, stream->Open(
      path,
      base::PLATFORM_FILE_OPEN_ALWAYS | base::PLATFORM_FILE_WRITE));

  // Normally, the download system takes ownership of info, and is
  // responsible for deleting it.  In these unit tests, however, we
  // don't call the function that deletes it, so we do so ourselves.
  scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
  static const int32 local_id = 0;
  info->download_id = DownloadId(kValidIdDomain, local_id);
  info->prompt_user_for_save_location = false;
  info->url_chain.push_back(GURL());
  info->total_bytes = static_cast<int64>(kTestDataLen * 3);
  info->save_info.file_path = path;
  info->save_info.file_stream.reset(stream);

  // Create a download file that we can insert errors into.
  DownloadFileWithErrors* download_file(new DownloadFileWithErrors(
      info.get(), download_manager_, false));
  download_file->Initialize();
  AddDownloadToFileManager(local_id, download_file);

  // |download_file| is owned by DownloadFileManager.
  download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());

  DownloadItem* download = GetActiveDownloadItem(0);
  ASSERT_TRUE(download != NULL);
  // This will keep track of what should be displayed on the shelf.
  scoped_ptr<DownloadItemModel> download_item_model(
      new DownloadItemModel(download));

  EXPECT_EQ(DownloadItem::IN_PROGRESS, download->GetState());
  scoped_ptr<ItemObserver> observer(new ItemObserver(download));

  // Add some data before finalizing the file name.
  UpdateData(local_id, kTestData, kTestDataLen);

  // Finalize the file name.
  ContinueDownloadWithPath(download, path);
  message_loop_.RunAllPending();
  EXPECT_TRUE(GetActiveDownloadItem(0) != NULL);

  // Add more data.
  UpdateData(local_id, kTestData, kTestDataLen);

  // Add more data, but an error occurs.
  download_file->set_forced_error(net::ERR_FAILED);
  UpdateData(local_id, kTestData, kTestDataLen);

  // Check the state.  The download should have been interrupted.
  EXPECT_TRUE(GetActiveDownloadItem(0) == NULL);
  EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
  EXPECT_TRUE(observer->hit_state(DownloadItem::INTERRUPTED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::COMPLETE));
  EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
  EXPECT_TRUE(observer->was_updated());
  EXPECT_FALSE(observer->was_opened());
  EXPECT_FALSE(download->GetFileExternallyRemoved());
  EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());

  // Check the download shelf's information.
  size_t error_size = kTestDataLen * 3;
  size_t total_size = kTestDataLen * 3;
  ui::DataUnits amount_units = ui::GetByteDisplayUnits(kTestDataLen);
  string16 simple_size =
      ui::FormatBytesWithUnits(error_size, amount_units, false);
  string16 simple_total = base::i18n::GetDisplayStringInLTRDirectionality(
      ui::FormatBytesWithUnits(total_size, amount_units, true));
  EXPECT_EQ(l10n_util::GetStringFUTF16(IDS_DOWNLOAD_STATUS_INTERRUPTED,
                                       simple_size,
                                       simple_total),
            download_item_model->GetStatusText());

  // Clean up.
  download->Cancel(true);
  message_loop_.RunAllPending();
}

TEST_F(DownloadManagerTest, DownloadCancelTest) {
  using ::testing::_;
  using ::testing::CreateFunctor;
  using ::testing::Invoke;
  using ::testing::Return;

  // Normally, the download system takes ownership of info, and is
  // responsible for deleting it.  In these unit tests, however, we
  // don't call the function that deletes it, so we do so ourselves.
  scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
  info->download_id = DownloadId(kValidIdDomain, 0);
  info->prompt_user_for_save_location = false;
  info->url_chain.push_back(GURL());
  const FilePath new_path(FILE_PATH_LITERAL("foo.zip"));
  const FilePath cr_path(download_util::GetCrDownloadPath(new_path));

  MockDownloadFile* download_file(
      new MockDownloadFile(info.get(),
                           DownloadRequestHandle(),
                           download_manager_,
                           NULL));
  AddDownloadToFileManager(info->download_id.local(), download_file);

  // |download_file| is owned by DownloadFileManager.
  download_file->SetExpectedPath(0, cr_path);

  download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());

  DownloadItem* download = GetActiveDownloadItem(0);
  ASSERT_TRUE(download != NULL);
  scoped_ptr<DownloadItemModel> download_item_model(
      new DownloadItemModel(download));

  EXPECT_EQ(DownloadItem::IN_PROGRESS, download->GetState());
  scoped_ptr<ItemObserver> observer(new ItemObserver(download));

  ContinueDownloadWithPath(download, new_path);
  message_loop_.RunAllPending();
  EXPECT_TRUE(GetActiveDownloadItem(0) != NULL);

  download_file->AppendDataToFile(kTestData, kTestDataLen);

  download->Cancel(false);
  message_loop_.RunAllPending();

  EXPECT_TRUE(GetActiveDownloadItem(0) != NULL);
  EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
  EXPECT_TRUE(observer->hit_state(DownloadItem::CANCELLED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::INTERRUPTED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::COMPLETE));
  EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
  EXPECT_TRUE(observer->was_updated());
  EXPECT_FALSE(observer->was_opened());
  EXPECT_FALSE(download->GetFileExternallyRemoved());
  EXPECT_EQ(DownloadItem::CANCELLED, download->GetState());
  EXPECT_EQ(download_item_model->GetStatusText(),
            l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_CANCELED));

  EXPECT_FALSE(file_util::PathExists(new_path));
  EXPECT_FALSE(file_util::PathExists(cr_path));
}

TEST_F(DownloadManagerTest, MAYBE_DownloadOverwriteTest) {
  using ::testing::_;
  using ::testing::CreateFunctor;
  using ::testing::Invoke;
  using ::testing::Return;

  // Create a temporary directory.
  ScopedTempDir temp_dir_;
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

  // File names we're using.
  const FilePath new_path(temp_dir_.path().AppendASCII("foo.txt"));
  const FilePath cr_path(download_util::GetCrDownloadPath(new_path));
  EXPECT_FALSE(file_util::PathExists(new_path));

  // Create the file that we will overwrite.  Will be automatically cleaned
  // up when temp_dir_ is destroyed.
  FILE* fp = file_util::OpenFile(new_path, "w");
  file_util::CloseFile(fp);
  EXPECT_TRUE(file_util::PathExists(new_path));

  // Construct the unique file name that normally would be created, but
  // which we will override.
  int uniquifier = DownloadFile::GetUniquePathNumber(new_path);
  FilePath unique_new_path = new_path;
  EXPECT_NE(0, uniquifier);
  DownloadFile::AppendNumberToPath(&unique_new_path, uniquifier);

  // Normally, the download system takes ownership of info, and is
  // responsible for deleting it.  In these unit tests, however, we
  // don't call the function that deletes it, so we do so ourselves.
  scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
  info->download_id = DownloadId(kValidIdDomain, 0);
  info->prompt_user_for_save_location = true;
  info->url_chain.push_back(GURL());

  download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());

  DownloadItem* download = GetActiveDownloadItem(0);
  ASSERT_TRUE(download != NULL);
  scoped_ptr<DownloadItemModel> download_item_model(
      new DownloadItemModel(download));

  EXPECT_EQ(DownloadItem::IN_PROGRESS, download->GetState());
  scoped_ptr<ItemObserver> observer(new ItemObserver(download));

  // Create and initialize the download file.  We're bypassing the first part
  // of the download process and skipping to the part after the final file
  // name has been chosen, so we need to initialize the download file
  // properly.
  DownloadFile* download_file(
      new DownloadFileImpl(info.get(), new DownloadRequestHandle(),
                           download_manager_, false));
  download_file->Rename(cr_path);
  // This creates the .crdownload version of the file.
  download_file->Initialize();
  // |download_file| is owned by DownloadFileManager.
  AddDownloadToFileManager(info->download_id.local(), download_file);

  ContinueDownloadWithPath(download, new_path);
  message_loop_.RunAllPending();
  EXPECT_TRUE(GetActiveDownloadItem(0) != NULL);

  download_file->AppendDataToFile(kTestData, kTestDataLen);

  // Finish the download.
  OnResponseCompleted(0, kTestDataLen, "");
  message_loop_.RunAllPending();

  // Download is complete.
  EXPECT_TRUE(GetActiveDownloadItem(0) == NULL);
  EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
  EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::INTERRUPTED));
  EXPECT_TRUE(observer->hit_state(DownloadItem::COMPLETE));
  EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
  EXPECT_TRUE(observer->was_updated());
  EXPECT_FALSE(observer->was_opened());
  EXPECT_FALSE(download->GetFileExternallyRemoved());
  EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
  EXPECT_EQ(download_item_model->GetStatusText(), string16());

  EXPECT_TRUE(file_util::PathExists(new_path));
  EXPECT_FALSE(file_util::PathExists(cr_path));
  EXPECT_FALSE(file_util::PathExists(unique_new_path));
  std::string file_contents;
  EXPECT_TRUE(file_util::ReadFileToString(new_path, &file_contents));
  EXPECT_EQ(std::string(kTestData), file_contents);
}

TEST_F(DownloadManagerTest, MAYBE_DownloadRemoveTest) {
  using ::testing::_;
  using ::testing::CreateFunctor;
  using ::testing::Invoke;
  using ::testing::Return;

  // Create a temporary directory.
  ScopedTempDir temp_dir_;
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

  // File names we're using.
  const FilePath new_path(temp_dir_.path().AppendASCII("foo.txt"));
  const FilePath cr_path(download_util::GetCrDownloadPath(new_path));
  EXPECT_FALSE(file_util::PathExists(new_path));

  // Normally, the download system takes ownership of info, and is
  // responsible for deleting it.  In these unit tests, however, we
  // don't call the function that deletes it, so we do so ourselves.
  scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
  info->download_id = DownloadId(kValidIdDomain, 0);
  info->prompt_user_for_save_location = true;
  info->url_chain.push_back(GURL());

  download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());

  DownloadItem* download = GetActiveDownloadItem(0);
  ASSERT_TRUE(download != NULL);
  scoped_ptr<DownloadItemModel> download_item_model(
      new DownloadItemModel(download));

  EXPECT_EQ(DownloadItem::IN_PROGRESS, download->GetState());
  scoped_ptr<ItemObserver> observer(new ItemObserver(download));

  // Create and initialize the download file.  We're bypassing the first part
  // of the download process and skipping to the part after the final file
  // name has been chosen, so we need to initialize the download file
  // properly.
  DownloadFile* download_file(
      new DownloadFileImpl(info.get(), new DownloadRequestHandle(),
                           download_manager_, false));
  download_file->Rename(cr_path);
  // This creates the .crdownload version of the file.
  download_file->Initialize();
  // |download_file| is owned by DownloadFileManager.
  AddDownloadToFileManager(info->download_id.local(), download_file);

  ContinueDownloadWithPath(download, new_path);
  message_loop_.RunAllPending();
  EXPECT_TRUE(GetActiveDownloadItem(0) != NULL);

  download_file->AppendDataToFile(kTestData, kTestDataLen);

  // Finish the download.
  OnResponseCompleted(0, kTestDataLen, "");
  message_loop_.RunAllPending();

  // Download is complete.
  EXPECT_TRUE(GetActiveDownloadItem(0) == NULL);
  EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
  EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::INTERRUPTED));
  EXPECT_TRUE(observer->hit_state(DownloadItem::COMPLETE));
  EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
  EXPECT_TRUE(observer->was_updated());
  EXPECT_FALSE(observer->was_opened());
  EXPECT_FALSE(download->GetFileExternallyRemoved());
  EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
  EXPECT_EQ(download_item_model->GetStatusText(), string16());

  EXPECT_TRUE(file_util::PathExists(new_path));
  EXPECT_FALSE(file_util::PathExists(cr_path));

  // Remove the downloaded file.
  ASSERT_TRUE(file_util::Delete(new_path, false));
  download->OnDownloadedFileRemoved();
  message_loop_.RunAllPending();

  EXPECT_TRUE(GetActiveDownloadItem(0) == NULL);
  EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
  EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
  EXPECT_FALSE(observer->hit_state(DownloadItem::INTERRUPTED));
  EXPECT_TRUE(observer->hit_state(DownloadItem::COMPLETE));
  EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
  EXPECT_TRUE(observer->was_updated());
  EXPECT_FALSE(observer->was_opened());
  EXPECT_TRUE(download->GetFileExternallyRemoved());
  EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
  EXPECT_EQ(download_item_model->GetStatusText(),
            l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_REMOVED));

  EXPECT_FALSE(file_util::PathExists(new_path));
}