summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/drive/file_cache_unittest.cc
blob: 0b943e0487e05f98f560d6d4c041512a661d2b83 (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
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/drive/file_cache.h"

#include <string>
#include <vector>

#include "base/file_util.h"
#include "base/files/file_enumerator.h"
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/fake_free_disk_space_getter.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/mock_file_cache_observer.h"
#include "chrome/browser/chromeos/drive/test_util.h"
#include "chrome/browser/google_apis/test_util.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::StrictMock;

namespace drive {
namespace internal {
namespace {

struct TestCacheResource {
  const char* source_file;
  const char* resource_id;
  const char* md5;
  bool is_pinned;
  bool is_dirty;
} const test_cache_resources[] = {
  // Cache resource in tmp dir, i.e. not pinned or dirty.
  { "gdata/root_feed.json", "tmp:resource_id", "md5_tmp_alphanumeric",
    false, false },
  // Cache resource in tmp dir, i.e. not pinned or dirty, with resource_id
  // containing non-alphanumeric characters.
  { "gdata/empty_feed.json", "tmp:`~!@#$%^&*()-_=+[{|]}\\;',<.>/?",
    "md5_tmp_non_alphanumeric", false, false },
  // Cache resource that is pinned and persistent.
  { "gdata/directory_entry.json", "pinned:existing", "md5_pinned_existing",
    true, false },
  // Cache resource with a non-existent source file that is pinned.
  { "", "pinned:non-existent", "md5_pinned_non_existent", true, false },
  // Cache resource that is dirty.
  { "gdata/account_metadata.json", "dirty:existing", "md5_dirty_existing",
    false, true },
  // Cache resource that is pinned and dirty.
  { "gdata/basic_feed.json", "dirty_and_pinned:existing",
    "md5_dirty_and_pinned_existing", true, true },
};

const int64 kLotsOfSpace = kMinFreeSpace * 10;

struct PathToVerify {
  PathToVerify(const base::FilePath& in_path_to_scan,
               const base::FilePath& in_expected_existing_path) :
      path_to_scan(in_path_to_scan),
      expected_existing_path(in_expected_existing_path) {
  }

  base::FilePath path_to_scan;
  base::FilePath expected_existing_path;
};

// Copies results from Iterate().
void OnIterate(std::vector<std::string>* out_resource_ids,
               std::vector<FileCacheEntry>* out_cache_entries,
               const std::string& resource_id,
               const FileCacheEntry& cache_entry) {
  out_resource_ids->push_back(resource_id);
  out_cache_entries->push_back(cache_entry);
}

// Called upon completion of Iterate().
void OnIterateCompleted(bool* out_is_called) {
  *out_is_called = true;
}

}  // namespace

class FileCacheTest : public testing::Test {
 protected:
  FileCacheTest()
      : ui_thread_(content::BrowserThread::UI, &message_loop_),
        expected_error_(FILE_ERROR_OK),
        expected_cache_state_(0),
        expected_sub_dir_type_(FileCache::CACHE_TYPE_META),
        expected_success_(true),
        expect_outgoing_symlink_(false) {
  }

  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
    fake_free_disk_space_getter_.reset(new FakeFreeDiskSpaceGetter);

    scoped_refptr<base::SequencedWorkerPool> pool =
        content::BrowserThread::GetBlockingPool();
    blocking_task_runner_ =
        pool->GetSequencedTaskRunner(pool->GetSequenceToken());
    cache_.reset(new FileCache(temp_dir_.path(),
                                blocking_task_runner_,
                                fake_free_disk_space_getter_.get()));

    mock_cache_observer_.reset(new StrictMock<MockCacheObserver>);
    cache_->AddObserver(mock_cache_observer_.get());

    bool success = false;
    cache_->RequestInitialize(
        google_apis::test_util::CreateCopyResultCallback(&success));
    google_apis::test_util::RunBlockingPoolTask();
    ASSERT_TRUE(success);
  }

  virtual void TearDown() OVERRIDE {
    cache_.reset();
  }

  void PrepareTestCacheResources() {
    fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

    for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cache_resources); ++i) {
      const struct TestCacheResource& resource = test_cache_resources[i];
      // Copy file from data dir to cache.
      if (!std::string(resource.source_file).empty()) {
        base::FilePath source_path =
            google_apis::test_util::GetTestFilePath(
                std::string("chromeos/") + resource.source_file);

        FileError error = FILE_ERROR_OK;
        cache_->Store(
            resource.resource_id,
            resource.md5,
            source_path,
            FileCache::FILE_OPERATION_COPY,
            google_apis::test_util::CreateCopyResultCallback(&error));
        google_apis::test_util::RunBlockingPoolTask();
        EXPECT_EQ(FILE_ERROR_OK, error);
      }
      // Pin.
      if (resource.is_pinned) {
        FileError error = FILE_ERROR_OK;
        EXPECT_CALL(*mock_cache_observer_,
                    OnCachePinned(resource.resource_id, resource.md5)).Times(1);
        cache_->Pin(
            resource.resource_id,
            resource.md5,
            google_apis::test_util::CreateCopyResultCallback(&error));
        google_apis::test_util::RunBlockingPoolTask();
        EXPECT_EQ(FILE_ERROR_OK, error);
      }
      // Mark dirty.
      if (resource.is_dirty) {
        FileError error = FILE_ERROR_OK;
        cache_->MarkDirty(
            resource.resource_id,
            resource.md5,
            google_apis::test_util::CreateCopyResultCallback(&error));
        google_apis::test_util::RunBlockingPoolTask();
        EXPECT_EQ(FILE_ERROR_OK, error);

        EXPECT_CALL(*mock_cache_observer_,
                    OnCacheCommitted(resource.resource_id)).Times(1);
        cache_->CommitDirty(
            resource.resource_id,
            resource.md5,
            google_apis::test_util::CreateCopyResultCallback(&error));
        google_apis::test_util::RunBlockingPoolTask();
        EXPECT_EQ(FILE_ERROR_OK, error);
      }
    }
  }

  void TestGetFileFromCacheByResourceIdAndMd5(
      const std::string& resource_id,
      const std::string& md5,
      FileError expected_error,
      const std::string& expected_file_extension) {
    FileError error = FILE_ERROR_OK;
    base::FilePath cache_file_path;
    cache_->GetFile(resource_id, md5,
                    google_apis::test_util::CreateCopyResultCallback(
                        &error, &cache_file_path));
    google_apis::test_util::RunBlockingPoolTask();

    EXPECT_EQ(expected_error, error);
    if (error == FILE_ERROR_OK) {
      // Verify filename of |cache_file_path|.
      base::FilePath base_name = cache_file_path.BaseName();
      EXPECT_EQ(util::EscapeCacheFileName(resource_id) +
                base::FilePath::kExtensionSeparator +
                util::EscapeCacheFileName(
                    expected_file_extension.empty() ?
                    md5 : expected_file_extension),
                base_name.value());
    } else {
      EXPECT_TRUE(cache_file_path.empty());
    }
  }

  void TestStoreToCache(
      const std::string& resource_id,
      const std::string& md5,
      const base::FilePath& source_path,
      FileError expected_error,
      int expected_cache_state,
      FileCache::CacheSubDirectoryType expected_sub_dir_type) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;
    expected_sub_dir_type_ = expected_sub_dir_type;

    FileError error = FILE_ERROR_OK;
    cache_->Store(resource_id, md5, source_path,
                  FileCache::FILE_OPERATION_COPY,
                  google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    VerifyCacheFileState(error, resource_id, md5);
  }

  void TestStoreLocallyModifiedToCache(
      const std::string& resource_id,
      const std::string& md5,
      const base::FilePath& source_path,
      FileError expected_error,
      int expected_cache_state,
      FileCache::CacheSubDirectoryType expected_sub_dir_type,
      bool expected_outgoing_symlink) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;
    expected_sub_dir_type_ = expected_sub_dir_type;
    expect_outgoing_symlink_ = expected_outgoing_symlink;

    FileError error = FILE_ERROR_OK;
    cache_->StoreLocallyModified(
        resource_id, md5, source_path,
        FileCache::FILE_OPERATION_COPY,
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    VerifyCacheFileState(error, resource_id, md5);
  }

  void TestRemoveFromCache(const std::string& resource_id,
                           FileError expected_error) {
    expected_error_ = expected_error;

    FileError error = FILE_ERROR_OK;
    cache_->Remove(
        resource_id,
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    VerifyRemoveFromCache(error, resource_id, "");
  }

  void VerifyRemoveFromCache(FileError error,
                             const std::string& resource_id,
                             const std::string& md5) {
    EXPECT_EQ(expected_error_, error);

    // Verify cache map.
    FileCacheEntry cache_entry;
    const bool cache_entry_found =
        GetCacheEntryFromOriginThread(resource_id, md5, &cache_entry);
    if (cache_entry_found)
      EXPECT_TRUE(cache_entry.is_dirty());

    // If entry doesn't exist, verify that:
    // - no files with "<resource_id>.* exists in persistent and tmp dirs
    // - no "<resource_id>" symlink exists in pinned and outgoing dirs.
    std::vector<PathToVerify> paths_to_verify;
    paths_to_verify.push_back(  // Index 0: CACHE_TYPE_TMP.
        PathToVerify(cache_->GetCacheFilePath(resource_id, "*",
                     FileCache::CACHE_TYPE_TMP,
                     FileCache::CACHED_FILE_FROM_SERVER), base::FilePath()));
    paths_to_verify.push_back(  // Index 1: CACHE_TYPE_PERSISTENT.
        PathToVerify(cache_->GetCacheFilePath(resource_id, "*",
                     FileCache::CACHE_TYPE_PERSISTENT,
                     FileCache::CACHED_FILE_FROM_SERVER), base::FilePath()));
    paths_to_verify.push_back(  // Index 2: CACHE_TYPE_OUTGOING.
        PathToVerify(cache_->GetCacheFilePath(resource_id, "",
                     FileCache::CACHE_TYPE_OUTGOING,
                     FileCache::CACHED_FILE_FROM_SERVER), base::FilePath()));
    if (!cache_entry_found) {
      for (size_t i = 0; i < paths_to_verify.size(); ++i) {
        base::FileEnumerator enumerator(
            paths_to_verify[i].path_to_scan.DirName(), false /* not recursive*/,
            base::FileEnumerator::FILES | base::FileEnumerator::SHOW_SYM_LINKS,
            paths_to_verify[i].path_to_scan.BaseName().value());
        EXPECT_TRUE(enumerator.Next().empty());
      }
    } else {
      // Entry is dirty, verify that:
      // - no files with "<resource_id>.*" exist in tmp dir
      // - only 1 "<resource_id>.local" exists in persistent dir
      // - only 1 <resource_id> exists in outgoing dir
      // - if entry is pinned, only 1 <resource_id> exists in pinned dir.

      // Change expected_existing_path of CACHE_TYPE_PERSISTENT (index 1).
      paths_to_verify[1].expected_existing_path =
          GetCacheFilePath(resource_id,
                           std::string(),
                           FileCache::CACHE_TYPE_PERSISTENT,
                           FileCache::CACHED_FILE_LOCALLY_MODIFIED);

      // Change expected_existing_path of CACHE_TYPE_OUTGOING (index 2).
      paths_to_verify[2].expected_existing_path =
          GetCacheFilePath(resource_id,
                           std::string(),
                           FileCache::CACHE_TYPE_OUTGOING,
                           FileCache::CACHED_FILE_FROM_SERVER);

      for (size_t i = 0; i < paths_to_verify.size(); ++i) {
        const struct PathToVerify& verify = paths_to_verify[i];
        base::FileEnumerator enumerator(
            verify.path_to_scan.DirName(), false /* not recursive */,
            base::FileEnumerator::FILES | base::FileEnumerator::SHOW_SYM_LINKS,
            verify.path_to_scan.BaseName().value());
        size_t num_files_found = 0;
        for (base::FilePath current = enumerator.Next(); !current.empty();
             current = enumerator.Next()) {
          ++num_files_found;
          EXPECT_EQ(verify.expected_existing_path, current);
        }
        if (verify.expected_existing_path.empty())
          EXPECT_EQ(0U, num_files_found);
        else
          EXPECT_EQ(1U, num_files_found);
      }
    }
  }

  void TestPin(
      const std::string& resource_id,
      const std::string& md5,
      FileError expected_error,
      int expected_cache_state,
      FileCache::CacheSubDirectoryType expected_sub_dir_type) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;
    expected_sub_dir_type_ = expected_sub_dir_type;

    FileError error = FILE_ERROR_OK;
    cache_->Pin(resource_id, md5,
                google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    VerifyCacheFileState(error, resource_id, md5);
  }

  void TestUnpin(
      const std::string& resource_id,
      const std::string& md5,
      FileError expected_error,
      int expected_cache_state,
      FileCache::CacheSubDirectoryType expected_sub_dir_type) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;
    expected_sub_dir_type_ = expected_sub_dir_type;

    FileError error = FILE_ERROR_OK;
    cache_->Unpin(resource_id, md5,
                  google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    VerifyCacheFileState(error, resource_id, md5);
  }

  void TestMarkDirty(const std::string& resource_id,
                     const std::string& md5,
                     FileError expected_error,
                     int expected_cache_state,
                     FileCache::CacheSubDirectoryType expected_sub_dir_type) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;
    expected_sub_dir_type_ = expected_sub_dir_type;
    expect_outgoing_symlink_ = false;

    FileError error = FILE_ERROR_OK;
    cache_->MarkDirty(
        resource_id, md5,
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();

    VerifyCacheFileState(error, resource_id, md5);

    // Verify filename.
    if (error == FILE_ERROR_OK) {
      base::FilePath cache_file_path;
      cache_->GetFile(resource_id, md5,
                      google_apis::test_util::CreateCopyResultCallback(
                          &error, &cache_file_path));
      google_apis::test_util::RunBlockingPoolTask();

      EXPECT_EQ(FILE_ERROR_OK, error);
      base::FilePath base_name = cache_file_path.BaseName();
      EXPECT_EQ(util::EscapeCacheFileName(resource_id) +
                base::FilePath::kExtensionSeparator +
                "local",
                base_name.value());
    }
  }

  void TestCommitDirty(
      const std::string& resource_id,
      const std::string& md5,
      FileError expected_error,
      int expected_cache_state,
      FileCache::CacheSubDirectoryType expected_sub_dir_type) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;
    expected_sub_dir_type_ = expected_sub_dir_type;
    expect_outgoing_symlink_ = true;

    FileError error = FILE_ERROR_OK;
    cache_->CommitDirty(
        resource_id, md5,
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    VerifyCacheFileState(error, resource_id, md5);
  }

  void TestClearDirty(
      const std::string& resource_id,
      const std::string& md5,
      FileError expected_error,
      int expected_cache_state,
      FileCache::CacheSubDirectoryType expected_sub_dir_type) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;
    expected_sub_dir_type_ = expected_sub_dir_type;
    expect_outgoing_symlink_ = false;

    FileError error = FILE_ERROR_OK;
    cache_->ClearDirty(
        resource_id, md5,
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    VerifyCacheFileState(error, resource_id, md5);
  }

  void TestMarkAsMounted(
      const std::string& resource_id,
      const std::string& md5,
      FileError expected_error,
      int expected_cache_state,
      FileCache::CacheSubDirectoryType expected_sub_dir_type) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;
    expected_sub_dir_type_ = expected_sub_dir_type;
    expect_outgoing_symlink_ = false;

    FileError error = FILE_ERROR_OK;
    base::FilePath cache_file_path;
    cache_->MarkAsMounted(resource_id, md5,
                          google_apis::test_util::CreateCopyResultCallback(
                              &error, &cache_file_path));
    google_apis::test_util::RunBlockingPoolTask();

    EXPECT_TRUE(file_util::PathExists(cache_file_path));
    EXPECT_EQ(cache_file_path,
              cache_->GetCacheFilePath(resource_id,
                                       md5,
                                       expected_sub_dir_type_,
                                       FileCache::CACHED_FILE_MOUNTED));
  }

  void TestMarkAsUnmounted(
      const std::string& resource_id,
      const std::string& md5,
      const base::FilePath& file_path,
      FileError expected_error,
      int expected_cache_state,
      FileCache::CacheSubDirectoryType expected_sub_dir_type) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;
    expected_sub_dir_type_ = expected_sub_dir_type;
    expect_outgoing_symlink_ = false;

    FileError error = FILE_ERROR_OK;
    cache_->MarkAsUnmounted(
        file_path,
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();

    base::FilePath cache_file_path;
    cache_->GetFile(resource_id, md5,
                    google_apis::test_util::CreateCopyResultCallback(
                        &error, &cache_file_path));
    google_apis::test_util::RunBlockingPoolTask();
    EXPECT_EQ(FILE_ERROR_OK, error);

    EXPECT_TRUE(file_util::PathExists(cache_file_path));
    EXPECT_EQ(cache_file_path,
              cache_->GetCacheFilePath(resource_id,
                                       md5,
                                       expected_sub_dir_type_,
                                       FileCache::CACHED_FILE_FROM_SERVER));
  }

  void VerifyCacheFileState(FileError error,
                            const std::string& resource_id,
                            const std::string& md5) {
    EXPECT_EQ(expected_error_, error);

    // Verify cache map.
    FileCacheEntry cache_entry;
    const bool cache_entry_found =
        GetCacheEntryFromOriginThread(resource_id, md5, &cache_entry);
    if (test_util::ToCacheEntry(expected_cache_state_).is_present() ||
        test_util::ToCacheEntry(expected_cache_state_).is_pinned()) {
      ASSERT_TRUE(cache_entry_found);
      EXPECT_TRUE(test_util::CacheStatesEqual(
          test_util::ToCacheEntry(expected_cache_state_),
          cache_entry));
      EXPECT_EQ(expected_sub_dir_type_,
                FileCache::GetSubDirectoryType(cache_entry));
    } else {
      EXPECT_FALSE(cache_entry_found);
    }

    // Verify actual cache file.
    base::FilePath dest_path = cache_->GetCacheFilePath(
        resource_id,
        md5,
        test_util::ToCacheEntry(expected_cache_state_).is_pinned() ||
        test_util::ToCacheEntry(expected_cache_state_).is_dirty() ?
                FileCache::CACHE_TYPE_PERSISTENT :
                FileCache::CACHE_TYPE_TMP,
        test_util::ToCacheEntry(expected_cache_state_).is_dirty() ?
            FileCache::CACHED_FILE_LOCALLY_MODIFIED :
            FileCache::CACHED_FILE_FROM_SERVER);
    bool exists = file_util::PathExists(dest_path);
    if (test_util::ToCacheEntry(expected_cache_state_).is_present())
      EXPECT_TRUE(exists);
    else
      EXPECT_FALSE(exists);

    // Verify symlink in outgoing dir.
    base::FilePath symlink_path = cache_->GetCacheFilePath(
        resource_id,
        std::string(),
        FileCache::CACHE_TYPE_OUTGOING,
        FileCache::CACHED_FILE_FROM_SERVER);
    // Check that outgoing symlink exists, without dereferencing to target path.
    exists = file_util::IsLink(symlink_path);
    if (expect_outgoing_symlink_ &&
        test_util::ToCacheEntry(expected_cache_state_).is_dirty()) {
      EXPECT_TRUE(exists);
      base::FilePath target_path;
      EXPECT_TRUE(file_util::ReadSymbolicLink(symlink_path, &target_path));
      EXPECT_NE(util::kSymLinkToDevNull, target_path.value());
      if (test_util::ToCacheEntry(expected_cache_state_).is_present())
        EXPECT_EQ(dest_path, target_path);
    } else {
      EXPECT_FALSE(exists);
    }
  }

  base::FilePath GetCacheFilePath(const std::string& resource_id,
                            const std::string& md5,
                            FileCache::CacheSubDirectoryType sub_dir_type,
                            FileCache::CachedFileOrigin file_origin) {
    return cache_->GetCacheFilePath(resource_id, md5, sub_dir_type,
                                    file_origin);
  }

  // Helper function to call GetCacheEntry from origin thread.
  bool GetCacheEntryFromOriginThread(const std::string& resource_id,
                                     const std::string& md5,
                                     FileCacheEntry* cache_entry) {
    bool result = false;
    cache_->GetCacheEntry(resource_id, md5,
                          google_apis::test_util::CreateCopyResultCallback(
                              &result, cache_entry));
    google_apis::test_util::RunBlockingPoolTask();
    return result;
  }

  // Returns true if the cache entry exists for the given resource ID and MD5.
  bool CacheEntryExists(const std::string& resource_id,
                        const std::string& md5) {
    FileCacheEntry cache_entry;
    return GetCacheEntryFromOriginThread(resource_id, md5, &cache_entry);
  }

  void TestGetCacheFilePath(const std::string& resource_id,
                            const std::string& md5,
                            const std::string& expected_filename) {
    base::FilePath actual_path = cache_->GetCacheFilePath(
        resource_id,
        md5,
        FileCache::CACHE_TYPE_TMP,
        FileCache::CACHED_FILE_FROM_SERVER);
    base::FilePath expected_path =
        cache_->GetCacheDirectoryPath(FileCache::CACHE_TYPE_TMP);
    expected_path = expected_path.Append(
        base::FilePath::FromUTF8Unsafe(expected_filename));
    EXPECT_EQ(expected_path, actual_path);

    base::FilePath base_name = actual_path.BaseName();

    // base::FilePath::Extension returns ".", so strip it.
    std::string unescaped_md5 = util::UnescapeCacheFileName(
        base_name.Extension().substr(1));
    EXPECT_EQ(md5, unescaped_md5);
    std::string unescaped_resource_id = util::UnescapeCacheFileName(
        base_name.RemoveExtension().value());
    EXPECT_EQ(resource_id, unescaped_resource_id);
  }

  // Returns the number of the cache files with name <resource_id>, and Confirm
  // that they have the <md5>. This should return 1 or 0.
  size_t CountCacheFiles(const std::string& resource_id,
                         const std::string& md5) {
    base::FilePath path = GetCacheFilePath(
        resource_id, "*",
        (test_util::ToCacheEntry(expected_cache_state_).is_pinned() ?
         FileCache::CACHE_TYPE_PERSISTENT :
         FileCache::CACHE_TYPE_TMP),
        FileCache::CACHED_FILE_FROM_SERVER);
    base::FileEnumerator enumerator(path.DirName(), false,
                                    base::FileEnumerator::FILES,
                                    path.BaseName().value());
    size_t num_files_found = 0;
    for (base::FilePath current = enumerator.Next(); !current.empty();
         current = enumerator.Next()) {
      ++num_files_found;
      EXPECT_EQ(util::EscapeCacheFileName(resource_id) +
                base::FilePath::kExtensionSeparator +
                util::EscapeCacheFileName(md5),
                current.BaseName().value());
    }
    return num_files_found;
  }

  MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
  base::ScopedTempDir temp_dir_;

  scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_;
  scoped_ptr<FakeFreeDiskSpaceGetter> fake_free_disk_space_getter_;
  scoped_ptr<StrictMock<MockCacheObserver> > mock_cache_observer_;

  FileError expected_error_;
  int expected_cache_state_;
  FileCache::CacheSubDirectoryType expected_sub_dir_type_;
  bool expected_success_;
  bool expect_outgoing_symlink_;
  std::string expected_file_extension_;
};

TEST_F(FileCacheTest, GetCacheFilePath) {
  // Use alphanumeric characters for resource id.
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  TestGetCacheFilePath(resource_id, md5,
                       resource_id + base::FilePath::kExtensionSeparator + md5);

  // Use non-alphanumeric characters for resource id, including '.' which is an
  // extension separator, to test that the characters are escaped and unescaped
  // correctly, and '.' doesn't mess up the filename format and operations.
  resource_id = "pdf:`~!@#$%^&*()-_=+[{|]}\\;',<.>/?";
  std::string escaped_resource_id = util::EscapeCacheFileName(resource_id);
  std::string escaped_md5 = util::EscapeCacheFileName(md5);
  TestGetCacheFilePath(
      resource_id, md5, escaped_resource_id +
      base::FilePath::kExtensionSeparator + escaped_md5);
}

TEST_F(FileCacheTest, StoreToCacheSimple) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // Store an existing file.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Store a non-existent file to the same |resource_id| and |md5|.
  TestStoreToCache(resource_id, md5, base::FilePath("./non_existent.json"),
                   FILE_ERROR_FAILED,
                   test_util::TEST_CACHE_STATE_PRESENT,
                   FileCache::CACHE_TYPE_TMP);

  // Store a different existing file to the same |resource_id| but different
  // |md5|.
  md5 = "new_md5";
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/empty_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Verify that there's only one file with name <resource_id>, i.e. previously
  // cached file with the different md5 should be deleted.
  EXPECT_EQ(1U, CountCacheFiles(resource_id, md5));
}

TEST_F(FileCacheTest, LocallyModifiedSimple) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  const int kDirtyCacheState =
      test_util::TEST_CACHE_STATE_PRESENT |
      test_util::TEST_CACHE_STATE_DIRTY |
      test_util::TEST_CACHE_STATE_PERSISTENT;

  EXPECT_CALL(*mock_cache_observer_, OnCacheCommitted(resource_id)).Times(1);
  TestStoreLocallyModifiedToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, kDirtyCacheState, FileCache::CACHE_TYPE_PERSISTENT, true);
}

TEST_F(FileCacheTest, GetFromCacheSimple) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  // First store a file to cache.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Then try to get the existing file from cache.
  TestGetFileFromCacheByResourceIdAndMd5(
      resource_id, md5, FILE_ERROR_OK, md5);

  // Get file from cache with same resource id as existing file but different
  // md5.
  TestGetFileFromCacheByResourceIdAndMd5(
      resource_id, "9999", FILE_ERROR_NOT_FOUND, md5);

  // Get file from cache with different resource id from existing file but same
  // md5.
  resource_id = "document:1a2b";
  TestGetFileFromCacheByResourceIdAndMd5(
      resource_id, md5, FILE_ERROR_NOT_FOUND, md5);
}

TEST_F(FileCacheTest, RemoveFromCacheSimple) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  // Use alphanumeric characters for resource id.
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  // First store a file to cache.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Then try to remove existing file from cache.
  TestRemoveFromCache(resource_id, FILE_ERROR_OK);

  // Repeat using non-alphanumeric characters for resource id, including '.'
  // which is an extension separator.
  resource_id = "pdf:`~!@#$%^&*()-_=+[{|]}\\;',<.>/?";
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  TestRemoveFromCache(resource_id, FILE_ERROR_OK);
}

TEST_F(FileCacheTest, PinAndUnpin) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(resource_id, md5)).Times(2);
  EXPECT_CALL(*mock_cache_observer_, OnCacheUnpinned(resource_id, md5))
      .Times(1);

  // First store a file to cache.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Pin the existing file in cache.
  TestPin(resource_id, md5, FILE_ERROR_OK,
          test_util::TEST_CACHE_STATE_PRESENT |
          test_util::TEST_CACHE_STATE_PINNED |
          test_util::TEST_CACHE_STATE_PERSISTENT,
          FileCache::CACHE_TYPE_PERSISTENT);

  // Unpin the existing file in cache.
  TestUnpin(resource_id, md5, FILE_ERROR_OK,
            test_util::TEST_CACHE_STATE_PRESENT,
            FileCache::CACHE_TYPE_TMP);

  // Pin back the same existing file in cache.
  TestPin(resource_id, md5, FILE_ERROR_OK,
          test_util::TEST_CACHE_STATE_PRESENT |
          test_util::TEST_CACHE_STATE_PINNED |
          test_util::TEST_CACHE_STATE_PERSISTENT,
          FileCache::CACHE_TYPE_PERSISTENT);

  // Pin a non-existent file in cache.
  resource_id = "document:1a2b";
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(resource_id, md5)).Times(1);
  EXPECT_CALL(*mock_cache_observer_, OnCacheUnpinned(resource_id, md5))
      .Times(1);

  TestPin(resource_id, md5, FILE_ERROR_OK,
          test_util::TEST_CACHE_STATE_PINNED,
          FileCache::CACHE_TYPE_TMP);

  // Unpin the previously pinned non-existent file in cache.
  TestUnpin(resource_id, md5, FILE_ERROR_OK,
            test_util::TEST_CACHE_STATE_NONE,
            FileCache::CACHE_TYPE_TMP);

  // Unpin a file that doesn't exist in cache and is not pinned, i.e. cache
  // has zero knowledge of the file.
  resource_id = "not-in-cache:1a2b";
  // Because unpinning will fail, OnCacheUnpinned() won't be run.
  EXPECT_CALL(*mock_cache_observer_, OnCacheUnpinned(resource_id, md5))
      .Times(0);

  TestUnpin(resource_id, md5, FILE_ERROR_NOT_FOUND,
            test_util::TEST_CACHE_STATE_NONE,
            FileCache::CACHE_TYPE_TMP /* non-applicable */);
}

TEST_F(FileCacheTest, StoreToCachePinned) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(resource_id, md5)).Times(1);

  // Pin a non-existent file.
  TestPin(resource_id, md5, FILE_ERROR_OK,
          test_util::TEST_CACHE_STATE_PINNED,
          FileCache::CACHE_TYPE_TMP);

  // Store an existing file to a previously pinned file.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK,
      test_util::TEST_CACHE_STATE_PRESENT |
      test_util::TEST_CACHE_STATE_PINNED |
      test_util::TEST_CACHE_STATE_PERSISTENT,
      FileCache::CACHE_TYPE_PERSISTENT);

  // Store a non-existent file to a previously pinned and stored file.
  TestStoreToCache(resource_id, md5, base::FilePath("./non_existent.json"),
                   FILE_ERROR_FAILED,
                   test_util::TEST_CACHE_STATE_PRESENT |
                   test_util::TEST_CACHE_STATE_PINNED |
                   test_util::TEST_CACHE_STATE_PERSISTENT,
                   FileCache::CACHE_TYPE_PERSISTENT);
}

TEST_F(FileCacheTest, GetFromCachePinned) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(resource_id, md5)).Times(1);

  // Pin a non-existent file.
  TestPin(resource_id, md5, FILE_ERROR_OK,
          test_util::TEST_CACHE_STATE_PINNED,
          FileCache::CACHE_TYPE_TMP);

  // Get the non-existent pinned file from cache.
  TestGetFileFromCacheByResourceIdAndMd5(
      resource_id, md5, FILE_ERROR_NOT_FOUND, md5);

  // Store an existing file to the previously pinned non-existent file.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK,
      test_util::TEST_CACHE_STATE_PRESENT |
      test_util::TEST_CACHE_STATE_PINNED |
      test_util::TEST_CACHE_STATE_PERSISTENT,
      FileCache::CACHE_TYPE_PERSISTENT);

  // Get the previously pinned and stored file from cache.
  TestGetFileFromCacheByResourceIdAndMd5(
      resource_id, md5, FILE_ERROR_OK, md5);
}

TEST_F(FileCacheTest, RemoveFromCachePinned) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  // Use alphanumeric characters for resource_id.
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(resource_id, md5)).Times(1);

  // Store a file to cache, and pin it.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);
  TestPin(resource_id, md5, FILE_ERROR_OK,
          test_util::TEST_CACHE_STATE_PRESENT |
          test_util::TEST_CACHE_STATE_PINNED |
          test_util::TEST_CACHE_STATE_PERSISTENT,
          FileCache::CACHE_TYPE_PERSISTENT);

  // Remove |resource_id| from cache.
  TestRemoveFromCache(resource_id, FILE_ERROR_OK);

  // Repeat using non-alphanumeric characters for resource id, including '.'
  // which is an extension separator.
  resource_id = "pdf:`~!@#$%^&*()-_=+[{|]}\\;',<.>/?";
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(resource_id, md5)).Times(1);

  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);
  TestPin(resource_id, md5, FILE_ERROR_OK,
          test_util::TEST_CACHE_STATE_PRESENT |
          test_util::TEST_CACHE_STATE_PINNED |
          test_util::TEST_CACHE_STATE_PERSISTENT,
          FileCache::CACHE_TYPE_PERSISTENT);

  TestRemoveFromCache(resource_id, FILE_ERROR_OK);
}

TEST_F(FileCacheTest, DirtyCacheSimple) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  EXPECT_CALL(*mock_cache_observer_, OnCacheCommitted(resource_id)).Times(1);

  // First store a file to cache.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Mark the file dirty.
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                test_util::TEST_CACHE_STATE_PRESENT |
                test_util::TEST_CACHE_STATE_DIRTY |
                test_util::TEST_CACHE_STATE_PERSISTENT,
                FileCache::CACHE_TYPE_PERSISTENT);

  // Commit the file dirty.
  TestCommitDirty(resource_id, md5, FILE_ERROR_OK,
                  test_util::TEST_CACHE_STATE_PRESENT |
                  test_util::TEST_CACHE_STATE_DIRTY |
                  test_util::TEST_CACHE_STATE_PERSISTENT,
                  FileCache::CACHE_TYPE_PERSISTENT);

  // Clear dirty state of the file.
  TestClearDirty(resource_id, md5, FILE_ERROR_OK,
                 test_util::TEST_CACHE_STATE_PRESENT,
                 FileCache::CACHE_TYPE_TMP);
}

TEST_F(FileCacheTest, DirtyCachePinned) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(resource_id, md5)).Times(1);
  EXPECT_CALL(*mock_cache_observer_, OnCacheCommitted(resource_id)).Times(1);

  // First store a file to cache and pin it.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);
  TestPin(resource_id, md5, FILE_ERROR_OK,
          test_util::TEST_CACHE_STATE_PRESENT |
          test_util::TEST_CACHE_STATE_PINNED |
          test_util::TEST_CACHE_STATE_PERSISTENT,
          FileCache::CACHE_TYPE_PERSISTENT);

  // Mark the file dirty.
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                test_util::TEST_CACHE_STATE_PRESENT |
                test_util::TEST_CACHE_STATE_DIRTY |
                test_util::TEST_CACHE_STATE_PINNED |
                test_util::TEST_CACHE_STATE_PERSISTENT,
                FileCache::CACHE_TYPE_PERSISTENT);

  // Commit the file dirty.
  TestCommitDirty(resource_id, md5, FILE_ERROR_OK,
                  test_util::TEST_CACHE_STATE_PRESENT |
                  test_util::TEST_CACHE_STATE_DIRTY |
                  test_util::TEST_CACHE_STATE_PINNED |
                  test_util::TEST_CACHE_STATE_PERSISTENT,
                  FileCache::CACHE_TYPE_PERSISTENT);

  // Clear dirty state of the file.
  TestClearDirty(resource_id, md5, FILE_ERROR_OK,
                 test_util::TEST_CACHE_STATE_PRESENT |
                 test_util::TEST_CACHE_STATE_PINNED |
                 test_util::TEST_CACHE_STATE_PERSISTENT,
                 FileCache::CACHE_TYPE_PERSISTENT);
}

// Test is disabled because it is flaky (http://crbug.com/134146)
TEST_F(FileCacheTest, PinAndUnpinDirtyCache) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(resource_id, md5)).Times(1);
  EXPECT_CALL(*mock_cache_observer_, OnCacheUnpinned(resource_id, md5))
      .Times(1);

  // First store a file to cache and mark it as dirty.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                test_util::TEST_CACHE_STATE_PRESENT |
                test_util::TEST_CACHE_STATE_DIRTY |
                test_util::TEST_CACHE_STATE_PERSISTENT,
                FileCache::CACHE_TYPE_PERSISTENT);

  // Verifies dirty file exists.
  base::FilePath dirty_path;
  FileError error = FILE_ERROR_FAILED;
  cache_->GetFile(
      resource_id, md5,
      google_apis::test_util::CreateCopyResultCallback(&error, &dirty_path));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);
  EXPECT_TRUE(file_util::PathExists(dirty_path));

  // Pin the dirty file.
  TestPin(resource_id, md5, FILE_ERROR_OK,
          test_util::TEST_CACHE_STATE_PRESENT |
          test_util::TEST_CACHE_STATE_DIRTY |
          test_util::TEST_CACHE_STATE_PINNED |
          test_util::TEST_CACHE_STATE_PERSISTENT,
          FileCache::CACHE_TYPE_PERSISTENT);

  // Verify dirty file still exist at the same pathname.
  EXPECT_TRUE(file_util::PathExists(dirty_path));

  // Unpin the dirty file.
  TestUnpin(resource_id, md5, FILE_ERROR_OK,
            test_util::TEST_CACHE_STATE_PRESENT |
            test_util::TEST_CACHE_STATE_DIRTY |
            test_util::TEST_CACHE_STATE_PERSISTENT,
            FileCache::CACHE_TYPE_PERSISTENT);

  // Verify dirty file still exist at the same pathname.
  EXPECT_TRUE(file_util::PathExists(dirty_path));
}

TEST_F(FileCacheTest, DirtyCacheRepetitive) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  EXPECT_CALL(*mock_cache_observer_, OnCacheCommitted(resource_id)).Times(3);

  // First store a file to cache.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Mark the file dirty.
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                test_util::TEST_CACHE_STATE_PRESENT |
                test_util::TEST_CACHE_STATE_DIRTY |
                test_util::TEST_CACHE_STATE_PERSISTENT,
                FileCache::CACHE_TYPE_PERSISTENT);

  // Again, mark the file dirty.  Nothing should change.
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                test_util::TEST_CACHE_STATE_PRESENT |
                test_util::TEST_CACHE_STATE_DIRTY |
                test_util::TEST_CACHE_STATE_PERSISTENT,
                FileCache::CACHE_TYPE_PERSISTENT);

  // Commit the file dirty.  Outgoing symlink should be created.
  TestCommitDirty(resource_id, md5, FILE_ERROR_OK,
                  test_util::TEST_CACHE_STATE_PRESENT |
                  test_util::TEST_CACHE_STATE_DIRTY |
                  test_util::TEST_CACHE_STATE_PERSISTENT,
                  FileCache::CACHE_TYPE_PERSISTENT);

  // Again, commit the file dirty.  Nothing should change.
  TestCommitDirty(resource_id, md5, FILE_ERROR_OK,
                  test_util::TEST_CACHE_STATE_PRESENT |
                  test_util::TEST_CACHE_STATE_DIRTY |
                  test_util::TEST_CACHE_STATE_PERSISTENT,
                  FileCache::CACHE_TYPE_PERSISTENT);

  // Mark the file dirty again after it's being committed.  Outgoing symlink
  // should be deleted.
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                test_util::TEST_CACHE_STATE_PRESENT |
                test_util::TEST_CACHE_STATE_DIRTY |
                test_util::TEST_CACHE_STATE_PERSISTENT,
                FileCache::CACHE_TYPE_PERSISTENT);

  // Commit the file dirty.  Outgoing symlink should be created again.
  TestCommitDirty(resource_id, md5, FILE_ERROR_OK,
                  test_util::TEST_CACHE_STATE_PRESENT |
                  test_util::TEST_CACHE_STATE_DIRTY |
                  test_util::TEST_CACHE_STATE_PERSISTENT,
                  FileCache::CACHE_TYPE_PERSISTENT);

  // Clear dirty state of the file.
  TestClearDirty(resource_id, md5, FILE_ERROR_OK,
                 test_util::TEST_CACHE_STATE_PRESENT,
                 FileCache::CACHE_TYPE_TMP);

  // Again, clear dirty state of the file, which is no longer dirty.
  TestClearDirty(resource_id, md5, FILE_ERROR_INVALID_OPERATION,
                 test_util::TEST_CACHE_STATE_PRESENT,
                 FileCache::CACHE_TYPE_TMP);
}

TEST_F(FileCacheTest, DirtyCacheInvalid) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // Mark a non-existent file dirty.
  TestMarkDirty(resource_id, md5, FILE_ERROR_NOT_FOUND,
                test_util::TEST_CACHE_STATE_NONE,
                FileCache::CACHE_TYPE_TMP);

  // Commit a non-existent file dirty.
  TestCommitDirty(resource_id, md5, FILE_ERROR_NOT_FOUND,
                  test_util::TEST_CACHE_STATE_NONE,
                  FileCache::CACHE_TYPE_TMP);

  // Clear dirty state of a non-existent file.
  TestClearDirty(resource_id, md5, FILE_ERROR_NOT_FOUND,
                 test_util::TEST_CACHE_STATE_NONE,
                 FileCache::CACHE_TYPE_TMP);

  // Store a file to cache.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Commit a non-dirty existing file dirty.
  TestCommitDirty(resource_id, md5, FILE_ERROR_INVALID_OPERATION,
                 test_util::TEST_CACHE_STATE_PRESENT,
                 FileCache::CACHE_TYPE_TMP);

  // Clear dirty state of a non-dirty existing file.
  TestClearDirty(resource_id, md5, FILE_ERROR_INVALID_OPERATION,
                 test_util::TEST_CACHE_STATE_PRESENT,
                 FileCache::CACHE_TYPE_TMP);

  // Mark an existing file dirty, then store a new file to the same resource id
  // but different md5, which should fail.
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                test_util::TEST_CACHE_STATE_PRESENT |
                test_util::TEST_CACHE_STATE_DIRTY |
                test_util::TEST_CACHE_STATE_PERSISTENT,
                FileCache::CACHE_TYPE_PERSISTENT);
  md5 = "new_md5";
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath(
          "chromeos/gdata/empty_feed.json"),
      FILE_ERROR_IN_USE,
      test_util::TEST_CACHE_STATE_PRESENT |
      test_util::TEST_CACHE_STATE_DIRTY |
      test_util::TEST_CACHE_STATE_PERSISTENT,
      FileCache::CACHE_TYPE_PERSISTENT);
}

TEST_F(FileCacheTest, RemoveFromDirtyCache) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(resource_id, md5)).Times(1);
  EXPECT_CALL(*mock_cache_observer_, OnCacheCommitted(resource_id)).Times(1);

  // Store a file to cache, pin it, mark it dirty and commit it.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);
  TestPin(resource_id, md5, FILE_ERROR_OK,
          test_util::TEST_CACHE_STATE_PRESENT |
          test_util::TEST_CACHE_STATE_PINNED |
          test_util::TEST_CACHE_STATE_PERSISTENT,
          FileCache::CACHE_TYPE_PERSISTENT);
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                test_util::TEST_CACHE_STATE_PRESENT |
                test_util::TEST_CACHE_STATE_PINNED |
                test_util::TEST_CACHE_STATE_DIRTY |
                test_util::TEST_CACHE_STATE_PERSISTENT,
                FileCache::CACHE_TYPE_PERSISTENT);
  TestCommitDirty(resource_id, md5, FILE_ERROR_OK,
                  test_util::TEST_CACHE_STATE_PRESENT |
                  test_util::TEST_CACHE_STATE_PINNED |
                  test_util::TEST_CACHE_STATE_DIRTY |
                  test_util::TEST_CACHE_STATE_PERSISTENT,
                  FileCache::CACHE_TYPE_PERSISTENT);

  // Try to remove the file.  Since file is dirty, it and the corresponding
  // pinned and outgoing symlinks should not be removed.
  TestRemoveFromCache(resource_id, FILE_ERROR_OK);
}

TEST_F(FileCacheTest, MountUnmount) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // First store a file to cache in the tmp subdir.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Mark the file mounted.
  TestMarkAsMounted(resource_id,
                    md5,
                    FILE_ERROR_OK,
                    test_util::TEST_CACHE_STATE_PRESENT |
                    test_util::TEST_CACHE_STATE_MOUNTED |
                    test_util::TEST_CACHE_STATE_PERSISTENT,
                    FileCache::CACHE_TYPE_PERSISTENT);
  EXPECT_TRUE(CacheEntryExists(resource_id, md5));

  // Clear mounted state of the file.
  base::FilePath file_path;
  FileError error = FILE_ERROR_FAILED;
  cache_->GetFile(
      resource_id, md5,
      google_apis::test_util::CreateCopyResultCallback(&error, &file_path));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  TestMarkAsUnmounted(resource_id, md5, file_path,
                      FILE_ERROR_OK,
                      test_util::TEST_CACHE_STATE_PRESENT,
                      FileCache::CACHE_TYPE_TMP);
  EXPECT_TRUE(CacheEntryExists(resource_id, md5));

  // Try to remove the file.
  TestRemoveFromCache(resource_id, FILE_ERROR_OK);
}

TEST_F(FileCacheTest, Iterate) {
  PrepareTestCacheResources();

  std::vector<std::string> resource_ids;
  std::vector<FileCacheEntry> cache_entries;
  bool completed = false;
  cache_->Iterate(
      base::Bind(&OnIterate, &resource_ids, &cache_entries),
      base::Bind(&OnIterateCompleted, &completed));
  google_apis::test_util::RunBlockingPoolTask();

  ASSERT_TRUE(completed);

  sort(resource_ids.begin(), resource_ids.end());
  ASSERT_EQ(6U, resource_ids.size());
  EXPECT_EQ("dirty:existing", resource_ids[0]);
  EXPECT_EQ("dirty_and_pinned:existing", resource_ids[1]);
  EXPECT_EQ("pinned:existing", resource_ids[2]);
  EXPECT_EQ("pinned:non-existent", resource_ids[3]);
  EXPECT_EQ("tmp:`~!@#$%^&*()-_=+[{|]}\\;',<.>/?", resource_ids[4]);
  EXPECT_EQ("tmp:resource_id", resource_ids[5]);

  ASSERT_EQ(6U, cache_entries.size());
}


TEST_F(FileCacheTest, ClearAll) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // Store an existing file.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK, test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Verify that there's only one cached file.
  EXPECT_EQ(1U, CountCacheFiles(resource_id, md5));

  // Clear cache.
  bool success = false;
  cache_->ClearAll(google_apis::test_util::CreateCopyResultCallback(&success));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_TRUE(success);

  // Verify that all the cache is removed.
  expected_error_ = FILE_ERROR_OK;
  VerifyRemoveFromCache(FILE_ERROR_OK, resource_id, md5);
  EXPECT_EQ(0U, CountCacheFiles(resource_id, md5));
}

TEST_F(FileCacheTest, StoreToCacheNoSpace) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(0);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // Try to store an existing file.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_NO_SPACE,
      test_util::TEST_CACHE_STATE_NONE,
      FileCache::CACHE_TYPE_TMP);

  // Verify that there's no files added.
  EXPECT_EQ(0U, CountCacheFiles(resource_id, md5));
}

// Don't use TEST_F, as we don't want SetUp() and TearDown() for this test.
TEST(FileCacheExtraTest, InitializationFailure) {
  MessageLoopForUI message_loop;
  content::TestBrowserThread ui_thread(content::BrowserThread::UI,
                                       &message_loop);

  scoped_refptr<base::SequencedWorkerPool> pool =
      content::BrowserThread::GetBlockingPool();

  // Set the cache root to a non existent path, so the initialization fails.
  scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache(new FileCache(
      base::FilePath::FromUTF8Unsafe("/somewhere/nonexistent/blah/blah"),
      pool->GetSequencedTaskRunner(pool->GetSequenceToken()),
      NULL /* free_disk_space_getter */));

  bool success = true;
  cache->RequestInitialize(
      google_apis::test_util::CreateCopyResultCallback(&success));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_FALSE(success);
}

TEST_F(FileCacheTest, UpdatePinnedCache) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  std::string md5_modified("aaaaaa0000000000");

  // Store an existing file.
  TestStoreToCache(
      resource_id, md5,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/root_feed.json"),
      FILE_ERROR_OK,
      test_util::TEST_CACHE_STATE_PRESENT,
      FileCache::CACHE_TYPE_TMP);

  // Pin the file.
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(resource_id, md5)).Times(1);
  TestPin(
      resource_id, md5,
      FILE_ERROR_OK,
      test_util::TEST_CACHE_STATE_PRESENT |
      test_util::TEST_CACHE_STATE_PINNED |
      test_util::TEST_CACHE_STATE_PERSISTENT,
      FileCache::CACHE_TYPE_PERSISTENT);

  // Store the file with a modified content and md5. It should stay pinned.
  TestStoreToCache(
      resource_id, md5_modified,
      google_apis::test_util::GetTestFilePath("chromeos/gdata/empty_feed.json"),
      FILE_ERROR_OK,
      test_util::TEST_CACHE_STATE_PRESENT |
      test_util::TEST_CACHE_STATE_PINNED |
      test_util::TEST_CACHE_STATE_PERSISTENT,
      FileCache::CACHE_TYPE_PERSISTENT);
}

}  // namespace internal
}  // namespace drive