summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/drive/file_cache_unittest.cc
blob: 6f70aca03a1577efb68d887d17668cd280ca04e3 (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
// 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/md5.h"
#include "base/run_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_cache_metadata.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/resource_metadata_storage.h"
#include "chrome/browser/chromeos/drive/test_util.h"
#include "chrome/browser/google_apis/test_util.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace drive {
namespace internal {
namespace {

// Bitmask of cache states in FileCacheEntry.
enum TestFileCacheState {
  TEST_CACHE_STATE_NONE       = 0,
  TEST_CACHE_STATE_PINNED     = 1 << 0,
  TEST_CACHE_STATE_PRESENT    = 1 << 1,
  TEST_CACHE_STATE_DIRTY      = 1 << 2,
};

// 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

// Tests FileCache methods from UI thread. It internally uses a real blocking
// pool and tests the interaction among threads.
// TODO(hashimoto): remove this class. crbug.com/231221.
class FileCacheTestOnUIThread : public testing::Test {
 protected:
  FileCacheTestOnUIThread() : expected_error_(FILE_ERROR_OK),
                              expected_cache_state_(0) {
  }

  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
    ASSERT_TRUE(file_util::CreateDirectory(
        temp_dir_.path().Append(util::kMetadataDirectory)));
    ASSERT_TRUE(file_util::CreateDirectory(
        temp_dir_.path().Append(util::kCacheFileDirectory)));

    ASSERT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir_.path(),
                                                    &dummy_file_path_));
    fake_free_disk_space_getter_.reset(new FakeFreeDiskSpaceGetter);

    scoped_refptr<base::SequencedWorkerPool> pool =
        content::BrowserThread::GetBlockingPool();
    blocking_task_runner_ =
        pool->GetSequencedTaskRunner(pool->GetSequenceToken());

    metadata_storage_.reset(new ResourceMetadataStorage(
        temp_dir_.path(), blocking_task_runner_.get()));

    bool success = false;
    base::PostTaskAndReplyWithResult(
        blocking_task_runner_.get(),
        FROM_HERE,
        base::Bind(&ResourceMetadataStorage::Initialize,
                   base::Unretained(metadata_storage_.get())),
        google_apis::test_util::CreateCopyResultCallback(&success));
    test_util::RunBlockingPoolTask();
    ASSERT_TRUE(success);

    cache_.reset(new FileCache(
        metadata_storage_.get(),
        temp_dir_.path().Append(util::kCacheFileDirectory),
        blocking_task_runner_.get(),
        fake_free_disk_space_getter_.get()));

    success = false;
    base::PostTaskAndReplyWithResult(
        blocking_task_runner_.get(),
        FROM_HERE,
        base::Bind(&FileCache::Initialize, base::Unretained(cache_.get())),
        google_apis::test_util::CreateCopyResultCallback(&success));
    test_util::RunBlockingPoolTask();
    ASSERT_TRUE(success);
  }

  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_->GetFileOnUIThread(resource_id, md5,
                              google_apis::test_util::CreateCopyResultCallback(
                                  &error, &cache_file_path));
    test_util::RunBlockingPoolTask();

    EXPECT_EQ(expected_error, error);
    if (error == FILE_ERROR_OK) {
      // Verify filename of |cache_file_path|.
      EXPECT_EQ(util::EscapeCacheFileName(resource_id),
                cache_file_path.BaseName().AsUTF8Unsafe());
    } 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) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;

    FileError error = FILE_ERROR_OK;
    cache_->StoreOnUIThread(
        resource_id, md5, source_path,
        FileCache::FILE_OPERATION_COPY,
        google_apis::test_util::CreateCopyResultCallback(&error));
    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_->RemoveOnUIThread(
        resource_id,
        google_apis::test_util::CreateCopyResultCallback(&error));
    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);

    FileCacheEntry cache_entry;
    if (!GetCacheEntryFromOriginThread(resource_id, md5, &cache_entry)) {
      EXPECT_EQ(FILE_ERROR_OK, error);

      const base::FilePath path = cache_->GetCacheFilePath(resource_id);
      EXPECT_FALSE(base::PathExists(path));
    }
  }

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

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

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

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

  void TestMarkDirty(const std::string& resource_id,
                     const std::string& md5,
                     FileError expected_error,
                     int expected_cache_state) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;

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

    VerifyCacheFileState(error, resource_id, md5);

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

      EXPECT_EQ(FILE_ERROR_OK, error);
      EXPECT_EQ(util::EscapeCacheFileName(resource_id),
                cache_file_path.BaseName().AsUTF8Unsafe());
    }
  }

  void TestClearDirty(const std::string& resource_id,
                      const std::string& md5,
                      FileError expected_error,
                      int expected_cache_state) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;

    FileError error = FILE_ERROR_OK;
    PostTaskAndReplyWithResult(
        blocking_task_runner_.get(),
        FROM_HERE,
        base::Bind(&FileCache::ClearDirty,
                   base::Unretained(cache_.get()),
                   resource_id,
                   md5),
        google_apis::test_util::CreateCopyResultCallback(&error));
    test_util::RunBlockingPoolTask();
    VerifyCacheFileState(error, resource_id, md5);
  }

  void TestMarkAsMounted(const std::string& resource_id,
                         FileError expected_error,
                         int expected_cache_state) {
    expected_error_ = expected_error;
    expected_cache_state_ = expected_cache_state;

    FileCacheEntry entry;
    EXPECT_TRUE(GetCacheEntryFromOriginThread(resource_id, std::string(),
                                              &entry));

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

    EXPECT_TRUE(base::PathExists(cache_file_path));
    EXPECT_EQ(cache_file_path, cache_->GetCacheFilePath(resource_id));
  }

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

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

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

    EXPECT_TRUE(base::PathExists(cache_file_path));
    EXPECT_EQ(cache_file_path, cache_->GetCacheFilePath(resource_id));
  }

  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 ((expected_cache_state_ & TEST_CACHE_STATE_PRESENT) ||
        (expected_cache_state_ & TEST_CACHE_STATE_PINNED)) {
      ASSERT_TRUE(cache_entry_found);
      EXPECT_EQ((expected_cache_state_ & TEST_CACHE_STATE_PINNED) != 0,
                cache_entry.is_pinned());
      EXPECT_EQ((expected_cache_state_ & TEST_CACHE_STATE_PRESENT) != 0,
                cache_entry.is_present());
      EXPECT_EQ((expected_cache_state_ & TEST_CACHE_STATE_DIRTY) != 0,
                cache_entry.is_dirty());
    } else {
      EXPECT_FALSE(cache_entry_found);
    }

    // Verify actual cache file.
    base::FilePath dest_path = cache_->GetCacheFilePath(resource_id);
    EXPECT_EQ((expected_cache_state_ & TEST_CACHE_STATE_PRESENT) != 0,
              base::PathExists(dest_path));
  }

  // 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_->GetCacheEntryOnUIThread(
        resource_id, md5,
        google_apis::test_util::CreateCopyResultCallback(&result, cache_entry));
    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);
  }

  // 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 = cache_->GetCacheFilePath(resource_id);
    base::FileEnumerator enumerator(path.DirName(),
                                    false,  // recursive
                                    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),
                current.BaseName().AsUTF8Unsafe());
    }
    return num_files_found;
  }

  content::TestBrowserThreadBundle thread_bundle_;
  scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
  base::ScopedTempDir temp_dir_;
  base::FilePath dummy_file_path_;

  scoped_ptr<ResourceMetadataStorage, test_util::DestroyHelperForTests>
      metadata_storage_;
  scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_;
  scoped_ptr<FakeFreeDiskSpaceGetter> fake_free_disk_space_getter_;

  FileError expected_error_;
  int expected_cache_state_;
  std::string expected_file_extension_;
};

TEST_F(FileCacheTestOnUIThread, StoreToCacheSimple) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // Store an existing file.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

  // Store a non-existent file to the same |resource_id| and |md5|.
  TestStoreToCache(resource_id, md5,
                   base::FilePath::FromUTF8Unsafe("non_existent_file"),
                   FILE_ERROR_FAILED,
                   TEST_CACHE_STATE_PRESENT);

  // Store a different existing file to the same |resource_id| but different
  // |md5|.
  md5 = "new_md5";
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

  // 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(FileCacheTestOnUIThread, GetFromCacheSimple) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  // First store a file to cache.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

  // 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(FileCacheTestOnUIThread, RemoveFromCacheSimple) {
  // 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, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

  // 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, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

  TestRemoveFromCache(resource_id, FILE_ERROR_OK);
}

TEST_F(FileCacheTestOnUIThread, PinAndUnpin) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // First store a file to cache.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

  // Pin the existing file in cache.
  TestPin(resource_id, FILE_ERROR_OK,
          TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);

  // Unpin the existing file in cache.
  TestUnpin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

  // Pin back the same existing file in cache.
  TestPin(resource_id, FILE_ERROR_OK,
          TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);

  // Pin a non-existent file in cache.
  resource_id = "document:1a2b";

  TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PINNED);

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

  // 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";

  TestUnpin(resource_id, FILE_ERROR_NOT_FOUND, TEST_CACHE_STATE_NONE);
}

TEST_F(FileCacheTestOnUIThread, StoreToCachePinned) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // Pin a non-existent file.
  TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PINNED);

  // Store an existing file to a previously pinned file.
  TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK,
                   TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);

  // Store a non-existent file to a previously pinned and stored file.
  TestStoreToCache(resource_id, md5,
                   base::FilePath::FromUTF8Unsafe("non_existent_file"),
                   FILE_ERROR_FAILED,
                   TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);
}

TEST_F(FileCacheTestOnUIThread, GetFromCachePinned) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // Pin a non-existent file.
  TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PINNED);

  // 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, dummy_file_path_, FILE_ERROR_OK,
                   TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);

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

TEST_F(FileCacheTestOnUIThread, RemoveFromCachePinned) {
  // Use alphanumeric characters for resource_id.
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // Store a file to cache, and pin it.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);
  TestPin(resource_id, FILE_ERROR_OK,
          TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);

  // 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:`~!@#$%^&*()-_=+[{|]}\\;',<.>/?";

  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);
  TestPin(resource_id, FILE_ERROR_OK,
          TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);

  TestRemoveFromCache(resource_id, FILE_ERROR_OK);
}

TEST_F(FileCacheTestOnUIThread, DirtyCacheSimple) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // First store a file to cache.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

  // Mark the file dirty.
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY);

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

TEST_F(FileCacheTestOnUIThread, DirtyCachePinned) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // First store a file to cache and pin it.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);
  TestPin(resource_id, FILE_ERROR_OK,
          TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);

  // Mark the file dirty.
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                TEST_CACHE_STATE_PRESENT |
                TEST_CACHE_STATE_DIRTY |
                TEST_CACHE_STATE_PINNED);

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

TEST_F(FileCacheTestOnUIThread, PinAndUnpinDirtyCache) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // First store a file to cache and mark it as dirty.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY);

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

  // Pin the dirty file.
  TestPin(resource_id, FILE_ERROR_OK,
          TEST_CACHE_STATE_PRESENT |
          TEST_CACHE_STATE_DIRTY |
          TEST_CACHE_STATE_PINNED);

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

  // Unpin the dirty file.
  TestUnpin(resource_id, FILE_ERROR_OK,
            TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY);

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

TEST_F(FileCacheTestOnUIThread, DirtyCacheRepetitive) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // First store a file to cache.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

  // Mark the file dirty.
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY);

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

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

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

TEST_F(FileCacheTestOnUIThread, DirtyCacheInvalid) {
  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_CACHE_STATE_NONE);

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

  // Store a file to cache.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

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

  // 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_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY);
  md5 = "new_md5";
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_IN_USE,
                   TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY);
}

TEST_F(FileCacheTestOnUIThread, RemoveFromDirtyCache) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // Store a file to cache, pin it, mark it dirty and commit it.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);
  TestPin(resource_id, FILE_ERROR_OK,
          TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);
  TestMarkDirty(resource_id, md5, FILE_ERROR_OK,
                TEST_CACHE_STATE_PRESENT |
                TEST_CACHE_STATE_PINNED |
                TEST_CACHE_STATE_DIRTY);

  // Try to remove the file.  Dirty caches can be removed at the level of
  // FileCache::Remove. Upper layer cache clearance functions like
  // FreeDiskSpaceIfNeededFor() and RemoveStaleCacheFiles() takes care of
  // securing dirty files.
  TestRemoveFromCache(resource_id, FILE_ERROR_OK);
}

TEST_F(FileCacheTestOnUIThread, MountUnmount) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // First store a file to cache.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

  // Mark the file mounted.
  TestMarkAsMounted(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);
  EXPECT_TRUE(CacheEntryExists(resource_id, md5));

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

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

  TestMarkAsUnmounted(resource_id, md5, file_path, FILE_ERROR_OK,
                      TEST_CACHE_STATE_PRESENT);
  EXPECT_TRUE(CacheEntryExists(resource_id, md5));

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

TEST_F(FileCacheTestOnUIThread, Iterate) {
  const std::vector<test_util::TestCacheResource> cache_resources(
      test_util::GetDefaultTestCacheResources());
  ASSERT_TRUE(test_util::PrepareTestCacheResources(cache_.get(),
                                                   cache_resources));

  std::vector<std::string> resource_ids;
  std::vector<FileCacheEntry> cache_entries;
  bool completed = false;
  cache_->IterateOnUIThread(
      base::Bind(&OnIterate, &resource_ids, &cache_entries),
      base::Bind(&OnIterateCompleted, &completed));
  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(FileCacheTestOnUIThread, ClearAll) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");

  // Store an existing file.
  TestStoreToCache(resource_id, md5, dummy_file_path_,
                   FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT);

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

  // Clear cache.
  bool success = false;
  cache_->ClearAllOnUIThread(
      google_apis::test_util::CreateCopyResultCallback(&success));
  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(FileCacheTestOnUIThread, StoreToCacheNoSpace) {
  fake_free_disk_space_getter_->set_default_value(0);

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

  // Try to store an existing file.
  TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_NO_SPACE,
                   TEST_CACHE_STATE_NONE);

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

TEST_F(FileCacheTestOnUIThread, UpdatePinnedCache) {
  std::string resource_id("pdf:1a2b");
  std::string md5("abcdef0123456789");
  std::string md5_modified("aaaaaa0000000000");

  // Store an existing file.
  TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK,
                   TEST_CACHE_STATE_PRESENT);

  // Pin the file.
  TestPin(resource_id, FILE_ERROR_OK,
          TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);

  // Store the file with a modified content and md5. It should stay pinned.
  TestStoreToCache(resource_id, md5_modified, dummy_file_path_, FILE_ERROR_OK,
                   TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED);
}

// Tests FileCache methods working with the blocking task runner.
class FileCacheTest : public testing::Test {
 protected:
  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
    ASSERT_TRUE(file_util::CreateDirectory(
        temp_dir_.path().Append(util::kMetadataDirectory)));
    ASSERT_TRUE(file_util::CreateDirectory(
        temp_dir_.path().Append(util::kCacheFileDirectory)));

    fake_free_disk_space_getter_.reset(new FakeFreeDiskSpaceGetter);

    metadata_storage_.reset(new ResourceMetadataStorage(
        temp_dir_.path().Append(util::kMetadataDirectory),
        base::MessageLoopProxy::current().get()));
    ASSERT_TRUE(metadata_storage_->Initialize());

    cache_.reset(new FileCache(
        metadata_storage_.get(),
        temp_dir_.path().Append(util::kCacheFileDirectory),
        base::MessageLoopProxy::current().get(),
        fake_free_disk_space_getter_.get()));
    ASSERT_TRUE(cache_->Initialize());
  }

  static bool ImportOldDB(FileCache* cache, const base::FilePath& old_db_path) {
    return cache->ImportOldDB(old_db_path);
  }

  static void RenameCacheFilesToNewFormat(FileCache* cache) {
    cache->RenameCacheFilesToNewFormat();
  }

  content::TestBrowserThreadBundle thread_bundle_;
  base::ScopedTempDir temp_dir_;

  scoped_ptr<ResourceMetadataStorage, test_util::DestroyHelperForTests>
      metadata_storage_;
  scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_;
  scoped_ptr<FakeFreeDiskSpaceGetter> fake_free_disk_space_getter_;
};

TEST_F(FileCacheTest, ScanCacheFile) {
  // Set up files in the cache directory.
  const base::FilePath file_directory =
      temp_dir_.path().Append(util::kCacheFileDirectory);
  ASSERT_TRUE(google_apis::test_util::WriteStringToFile(
      file_directory.AppendASCII("id_foo"), "foo"));

  // Remove the existing DB.
  const base::FilePath metadata_directory =
      temp_dir_.path().Append(util::kMetadataDirectory);
  ASSERT_TRUE(base::DeleteFile(metadata_directory, true /* recursive */));

  // Put an empty file with the same name as old DB.
  // This file cannot be opened by ImportOldDB() and will be dismissed.
  ASSERT_TRUE(file_util::CreateDirectory(metadata_directory));
  ASSERT_TRUE(google_apis::test_util::WriteStringToFile(
      metadata_directory.Append(FileCache::kOldCacheMetadataDBName), ""));

  // Create a new cache and initialize it.
  metadata_storage_.reset(new ResourceMetadataStorage(
      metadata_directory, base::MessageLoopProxy::current().get()));
  ASSERT_TRUE(metadata_storage_->Initialize());

  cache_.reset(new FileCache(metadata_storage_.get(),
                             temp_dir_.path().Append(util::kCacheFileDirectory),
                             base::MessageLoopProxy::current().get(),
                             fake_free_disk_space_getter_.get()));
  ASSERT_TRUE(cache_->Initialize());

  // Check contents of the cache.
  FileCacheEntry cache_entry;
  EXPECT_TRUE(cache_->GetCacheEntry("id_foo", std::string(), &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());
  EXPECT_EQ(base::MD5String("foo"), cache_entry.md5());
}

TEST_F(FileCacheTest, FreeDiskSpaceIfNeededFor) {
  base::FilePath src_file;
  ASSERT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir_.path(), &src_file));

  // Store a file as a 'temporary' file and remember the path.
  const std::string resource_id_tmp = "id_tmp", md5_tmp = "md5_tmp";
  ASSERT_EQ(FILE_ERROR_OK,
            cache_->Store(resource_id_tmp, md5_tmp, src_file,
                          FileCache::FILE_OPERATION_COPY));
  base::FilePath tmp_path;
  ASSERT_EQ(FILE_ERROR_OK,
            cache_->GetFile(resource_id_tmp, md5_tmp, &tmp_path));

  // Store a file as a pinned file and remember the path.
  const std::string resource_id_pinned = "id_pinned", md5_pinned = "md5_pinned";
  ASSERT_EQ(FILE_ERROR_OK,
            cache_->Store(resource_id_pinned, md5_pinned, src_file,
                          FileCache::FILE_OPERATION_COPY));
  ASSERT_EQ(FILE_ERROR_OK, cache_->Pin(resource_id_pinned));
  base::FilePath pinned_path;
  ASSERT_EQ(FILE_ERROR_OK,
            cache_->GetFile(resource_id_pinned, md5_pinned, &pinned_path));

  // Call FreeDiskSpaceIfNeededFor().
  fake_free_disk_space_getter_->set_default_value(test_util::kLotsOfSpace);
  fake_free_disk_space_getter_->PushFakeValue(0);
  const int64 kNeededBytes = 1;
  EXPECT_TRUE(cache_->FreeDiskSpaceIfNeededFor(kNeededBytes));

  // Only 'temporary' file gets removed.
  FileCacheEntry entry;
  EXPECT_FALSE(cache_->GetCacheEntry(resource_id_tmp, md5_tmp, &entry));
  EXPECT_FALSE(base::PathExists(tmp_path));

  EXPECT_TRUE(cache_->GetCacheEntry(resource_id_pinned, md5_pinned, &entry));
  EXPECT_TRUE(base::PathExists(pinned_path));

  // Returns false when disk space cannot be freed.
  fake_free_disk_space_getter_->set_default_value(0);
  EXPECT_FALSE(cache_->FreeDiskSpaceIfNeededFor(kNeededBytes));
}

TEST_F(FileCacheTest, ImportOldDB) {
  const base::FilePath old_db_path = temp_dir_.path().AppendASCII("old_db.db");

  const std::string key1 = "key1";
  const std::string md5_1 = "md5_1";
  const std::string key2 = "key2";
  const std::string md5_2 = "md5_2";

  // Set up data to be imported.
  {
    FileCacheMetadata old_metadata(NULL);
    ASSERT_TRUE(old_metadata.Initialize(old_db_path));

    FileCacheEntry entry;
    entry.set_md5(md5_1);
    old_metadata.AddOrUpdateCacheEntry(key1, entry);

    entry.set_md5(md5_2);
    old_metadata.AddOrUpdateCacheEntry(key2, entry);
  }
  EXPECT_TRUE(base::PathExists(old_db_path));

  // Do import.
  EXPECT_TRUE(ImportOldDB(cache_.get(), old_db_path));

  // Old DB should be removed.
  EXPECT_FALSE(base::PathExists(old_db_path));

  // Data is imported correctly.
  FileCacheEntry entry;
  EXPECT_TRUE(cache_->GetCacheEntry(key1, std::string(), &entry));
  EXPECT_EQ(md5_1, entry.md5());
  EXPECT_TRUE(cache_->GetCacheEntry(key2, std::string(), &entry));
  EXPECT_EQ(md5_2, entry.md5());
}

TEST_F(FileCacheTest, RenameCacheFilesToNewFormat) {
  const base::FilePath file_directory =
      temp_dir_.path().Append(util::kCacheFileDirectory);

  // File with an old style "<resource ID>.<MD5>" name.
  ASSERT_TRUE(google_apis::test_util::WriteStringToFile(
      file_directory.AppendASCII("id_koo.md5"), "koo"));

  // File with multiple extensions should be removed.
  ASSERT_TRUE(google_apis::test_util::WriteStringToFile(
      file_directory.AppendASCII("id_kyu.md5.mounted"), "kyu (mounted)"));
  ASSERT_TRUE(google_apis::test_util::WriteStringToFile(
      file_directory.AppendASCII("id_kyu.md5"), "kyu"));

  // Rename and verify the result.
  RenameCacheFilesToNewFormat(cache_.get());
  std::string contents;
  EXPECT_TRUE(file_util::ReadFileToString(file_directory.AppendASCII("id_koo"),
                                          &contents));
  EXPECT_EQ("koo", contents);
  contents.clear();
  EXPECT_TRUE(file_util::ReadFileToString(file_directory.AppendASCII("id_kyu"),
                                          &contents));
  EXPECT_EQ("kyu", contents);

  // Rename again.
  RenameCacheFilesToNewFormat(cache_.get());

  // Files with new style names are not affected.
  contents.clear();
  EXPECT_TRUE(file_util::ReadFileToString(file_directory.AppendASCII("id_koo"),
                                          &contents));
  EXPECT_EQ("koo", contents);
  contents.clear();
  EXPECT_TRUE(file_util::ReadFileToString(file_directory.AppendASCII("id_kyu"),
                                          &contents));
  EXPECT_EQ("kyu", contents);
}

}  // namespace internal
}  // namespace drive