summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/drive/file_system_unittest.cc
blob: fdd5f37c5f7c543b582a557144d1908b890f72b6 (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
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
// 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_system.h"

#include <string>
#include <vector>

#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_file_value_serializer.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/stringprintf.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/values.h"
#include "chrome/browser/chromeos/drive/change_list_loader.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/drive_webapps_registry.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/job_scheduler.h"
#include "chrome/browser/chromeos/drive/mock_directory_change_observer.h"
#include "chrome/browser/chromeos/drive/mock_file_cache_observer.h"
#include "chrome/browser/chromeos/drive/test_util.h"
#include "chrome/browser/google_apis/drive_api_parser.h"
#include "chrome/browser/google_apis/fake_drive_service.h"
#include "chrome/browser/google_apis/test_util.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/browser/browser_thread.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::AtLeast;
using ::testing::Eq;
using ::testing::StrictMock;
using ::testing::_;

namespace drive {
namespace {

const int64 kLotsOfSpace = internal::kMinFreeSpace * 10;

struct SearchResultPair {
  const char* path;
  const bool is_directory;
};

// Callback to FileSystem::Search used in ContentSearch tests.
// Verifies returned vector of results and next feed url.
void DriveSearchCallback(
    MessageLoop* message_loop,
    const SearchResultPair* expected_results,
    size_t expected_results_size,
    const GURL& expected_next_feed,
    FileError error,
    const GURL& next_feed,
    scoped_ptr<std::vector<SearchResultInfo> > results) {
  ASSERT_TRUE(results);
  ASSERT_EQ(expected_results_size, results->size());

  for (size_t i = 0; i < results->size(); i++) {
    EXPECT_EQ(base::FilePath(expected_results[i].path),
              results->at(i).path);
    EXPECT_EQ(expected_results[i].is_directory,
              results->at(i).entry.file_info().is_directory());
  }

  EXPECT_EQ(expected_next_feed, next_feed);

  message_loop->Quit();
}

// Counts the number of files (not directories) in |entries|.
int CountFiles(const ResourceEntryVector& entries) {
  int num_files = 0;
  for (size_t i = 0; i < entries.size(); ++i) {
    if (!entries[i].file_info().is_directory())
      ++num_files;
  }
  return num_files;
}

// Counts the number of invocation, and if it increased up to |expected_counter|
// quits the current message loop.
void AsyncInitializationCallback(
    int* counter, int expected_counter, MessageLoop* message_loop,
    FileError error, scoped_ptr<ResourceEntry> entry) {
  if (error != FILE_ERROR_OK || !entry) {
    // If we hit an error case, quit the message loop immediately.
    // Then the expectation in the test case can find it because the actual
    // value of |counter| is different from the expected one.
    message_loop->Quit();
    return;
  }

  (*counter)++;
  if (*counter >= expected_counter)
    message_loop->Quit();
}

void AppendContent(std::vector<std::string>* buffer,
                   google_apis::GDataErrorCode error,
                   scoped_ptr<std::string> content) {
  DCHECK_EQ(error, google_apis::HTTP_SUCCESS);
  buffer->push_back(*content);
}

}  // namespace

class DriveFileSystemTest : public testing::Test {
 protected:
  DriveFileSystemTest()
      : ui_thread_(content::BrowserThread::UI, &message_loop_),
        // |root_feed_changestamp_| should be set to the largest changestamp in
        // account metadata feed. But we fake it by some non-zero positive
        // increasing value.  See |LoadFeed()|.
        root_feed_changestamp_(1) {
  }

  virtual void SetUp() OVERRIDE {
    profile_.reset(new TestingProfile);

    // The fake object will be manually deleted in TearDown().
    fake_drive_service_.reset(new google_apis::FakeDriveService);
    fake_drive_service_->LoadResourceListForWapi(
        "chromeos/gdata/root_feed.json");
    fake_drive_service_->LoadAccountMetadataForWapi(
        "chromeos/gdata/account_metadata.json");
    fake_drive_service_->LoadAppListForDriveApi("chromeos/drive/applist.json");

    fake_free_disk_space_getter_.reset(new FakeFreeDiskSpaceGetter);

    scheduler_.reset(new JobScheduler(profile_.get(),
                                      fake_drive_service_.get()));

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

    cache_.reset(new internal::FileCache(util::GetCacheRootPath(profile_.get()),
                                         blocking_task_runner_,
                                         fake_free_disk_space_getter_.get()));

    drive_webapps_registry_.reset(new DriveWebAppsRegistry);

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

    mock_directory_observer_.reset(new StrictMock<MockDirectoryChangeObserver>);

    cache_->RequestInitializeForTesting();
    google_apis::test_util::RunBlockingPoolTask();

    SetUpResourceMetadataAndFileSystem();
  }

  void SetUpResourceMetadataAndFileSystem() {
    resource_metadata_.reset(new internal::ResourceMetadata(
        cache_->GetCacheDirectoryPath(internal::FileCache::CACHE_TYPE_META),
        blocking_task_runner_));

    file_system_.reset(new FileSystem(profile_.get(),
                                      cache_.get(),
                                      fake_drive_service_.get(),
                                      scheduler_.get(),
                                      drive_webapps_registry_.get(),
                                      resource_metadata_.get(),
                                      blocking_task_runner_));
    file_system_->AddObserver(mock_directory_observer_.get());
    file_system_->Initialize();

    FileError error = FILE_ERROR_FAILED;
    resource_metadata_->Initialize(
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    ASSERT_EQ(FILE_ERROR_OK, error);
  }

  virtual void TearDown() OVERRIDE {
    ASSERT_TRUE(file_system_);
    file_system_.reset();
    scheduler_.reset();
    fake_drive_service_.reset();
    cache_.reset();
    profile_.reset(NULL);
  }

  // Loads test json file as root ("/drive") element.
  bool LoadRootFeedDocument() {
    FileError error = FILE_ERROR_FAILED;
    file_system_->change_list_loader()->LoadIfNeeded(
        DirectoryFetchInfo(),
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    return error == FILE_ERROR_OK;
  }

  bool LoadChangeFeed(const std::string& filename) {
    if (!test_util::LoadChangeFeed(filename,
                                   file_system_->change_list_loader(),
                                   true,  // is_delta_feed
                                   fake_drive_service_->GetRootResourceId(),
                                   root_feed_changestamp_)) {
      return false;
    }
    root_feed_changestamp_++;
    return true;
  }

  FileError AddDirectory(const base::FilePath& directory_path) {
    FileError error = FILE_ERROR_FAILED;
    file_system_->CreateDirectory(
        directory_path,
        false,  // is_exclusive
        false,  // is_recursive
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    return error;
  }

  bool RemoveEntry(const base::FilePath& file_path) {
    FileError error = FILE_ERROR_FAILED;
    file_system_->Remove(
        file_path, false,
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    return error == FILE_ERROR_OK;
  }

  // Gets entry info by path synchronously.
  scoped_ptr<ResourceEntry> GetEntryInfoByPathSync(
      const base::FilePath& file_path) {
    FileError error = FILE_ERROR_FAILED;
    scoped_ptr<ResourceEntry> entry;
    file_system_->GetEntryInfoByPath(
        file_path,
        google_apis::test_util::CreateCopyResultCallback(&error, &entry));
    google_apis::test_util::RunBlockingPoolTask();

    return entry.Pass();
  }

  // Gets directory info by path synchronously.
  scoped_ptr<ResourceEntryVector> ReadDirectoryByPathSync(
      const base::FilePath& file_path) {
    FileError error = FILE_ERROR_FAILED;
    bool unused_hide_hosted_documents;
    scoped_ptr<ResourceEntryVector> entries;
    file_system_->ReadDirectoryByPath(
        file_path,
        google_apis::test_util::CreateCopyResultCallback(
            &error, &unused_hide_hosted_documents, &entries));
    google_apis::test_util::RunBlockingPoolTask();

    return entries.Pass();
  }

  // Returns true if an entry exists at |file_path|.
  bool EntryExists(const base::FilePath& file_path) {
    return GetEntryInfoByPathSync(file_path);
  }

  // Gets the resource ID of |file_path|. Returns an empty string if not found.
  std::string GetResourceIdByPath(const base::FilePath& file_path) {
    scoped_ptr<ResourceEntry> entry =
        GetEntryInfoByPathSync(file_path);
    if (entry)
      return entry->resource_id();
    else
      return "";
  }

  // 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);
  }

  // Flag for specifying the timestamp of the test filesystem cache.
  enum SetUpTestFileSystemParam {
    USE_OLD_TIMESTAMP,
    USE_SERVER_TIMESTAMP,
  };

  // Sets up a filesystem with directories: drive/root, drive/root/Dir1,
  // drive/root/Dir1/SubDir2 and files drive/root/File1, drive/root/Dir1/File2,
  // drive/root/Dir1/SubDir2/File3. If |use_up_to_date_timestamp| is true, sets
  // the changestamp to 654321, equal to that of "account_metadata.json" test
  // data, indicating the cache is holding the latest file system info.
  bool SetUpTestFileSystem(SetUpTestFileSystemParam param) {
    // Destroy the existing resource metadata to close DB.
    resource_metadata_.reset();

    const std::string root_resource_id =
        fake_drive_service_->GetRootResourceId();
    scoped_ptr<internal::ResourceMetadata, test_util::DestroyHelperForTests>
        resource_metadata(new internal::ResourceMetadata(
            cache_->GetCacheDirectoryPath(internal::FileCache::CACHE_TYPE_META),
            blocking_task_runner_));

    FileError error = FILE_ERROR_FAILED;
    resource_metadata->Initialize(
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    if (error != FILE_ERROR_OK)
      return false;

    resource_metadata->SetLargestChangestamp(
        param == USE_SERVER_TIMESTAMP ? 654321 : 1,
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    if (error != FILE_ERROR_OK)
      return false;

    // drive/root is already prepared by ResourceMetadata.
    base::FilePath file_path;

    // drive/root
    resource_metadata->AddEntry(
        util::CreateMyDriveRootEntry(root_resource_id),
        google_apis::test_util::CreateCopyResultCallback(&error, &file_path));
    google_apis::test_util::RunBlockingPoolTask();
    if (error != FILE_ERROR_OK)
      return false;

    // drive/root/File1
    ResourceEntry file1;
    file1.set_title("File1");
    file1.set_resource_id("resource_id:File1");
    file1.set_parent_resource_id(root_resource_id);
    file1.mutable_file_specific_info()->set_file_md5("md5");
    file1.mutable_file_info()->set_is_directory(false);
    file1.mutable_file_info()->set_size(1048576);
    resource_metadata->AddEntry(
        file1,
        google_apis::test_util::CreateCopyResultCallback(&error, &file_path));
    google_apis::test_util::RunBlockingPoolTask();
    if (error != FILE_ERROR_OK)
      return false;

    // drive/root/Dir1
    ResourceEntry dir1;
    dir1.set_title("Dir1");
    dir1.set_resource_id("resource_id:Dir1");
    dir1.set_parent_resource_id(root_resource_id);
    dir1.mutable_file_info()->set_is_directory(true);
    resource_metadata->AddEntry(
        dir1,
        google_apis::test_util::CreateCopyResultCallback(&error, &file_path));
    google_apis::test_util::RunBlockingPoolTask();
    if (error != FILE_ERROR_OK)
      return false;

    // drive/root/Dir1/File2
    ResourceEntry file2;
    file2.set_title("File2");
    file2.set_resource_id("resource_id:File2");
    file2.set_parent_resource_id(dir1.resource_id());
    file2.mutable_file_specific_info()->set_file_md5("md5");
    file2.mutable_file_info()->set_is_directory(false);
    file2.mutable_file_info()->set_size(555);
    resource_metadata->AddEntry(
        file2,
        google_apis::test_util::CreateCopyResultCallback(&error, &file_path));
    google_apis::test_util::RunBlockingPoolTask();
    if (error != FILE_ERROR_OK)
      return false;

    // drive/root/Dir1/SubDir2
    ResourceEntry dir2;
    dir2.set_title("SubDir2");
    dir2.set_resource_id("resource_id:SubDir2");
    dir2.set_parent_resource_id(dir1.resource_id());
    dir2.mutable_file_info()->set_is_directory(true);
    resource_metadata->AddEntry(
        dir2,
        google_apis::test_util::CreateCopyResultCallback(&error, &file_path));
    google_apis::test_util::RunBlockingPoolTask();
    if (error != FILE_ERROR_OK)
      return false;

    // drive/root/Dir1/SubDir2/File3
    ResourceEntry file3;
    file3.set_title("File3");
    file3.set_resource_id("resource_id:File3");
    file3.set_parent_resource_id(dir2.resource_id());
    file3.mutable_file_specific_info()->set_file_md5("md5");
    file3.mutable_file_info()->set_is_directory(false);
    file3.mutable_file_info()->set_size(12345);
    resource_metadata->AddEntry(
        file3,
        google_apis::test_util::CreateCopyResultCallback(&error, &file_path));
    google_apis::test_util::RunBlockingPoolTask();
    if (error != FILE_ERROR_OK)
      return false;

    // Recreate resource metadata.
    SetUpResourceMetadataAndFileSystem();

    return true;
  }

  // Verifies that |file_path| is a valid JSON file for the hosted document
  // associated with |entry| (i.e. |url| and |resource_id| match).
  void VerifyHostedDocumentJSONFile(const ResourceEntry& entry,
                                    const base::FilePath& file_path) {
    std::string error;
    JSONFileValueSerializer serializer(file_path);
    scoped_ptr<Value> value(serializer.Deserialize(NULL, &error));
    ASSERT_TRUE(value) << "Parse error " << file_path.value() << ": " << error;
    DictionaryValue* dict_value = NULL;
    ASSERT_TRUE(value->GetAsDictionary(&dict_value));

    std::string edit_url, resource_id;
    EXPECT_TRUE(dict_value->GetString("url", &edit_url));
    EXPECT_TRUE(dict_value->GetString("resource_id", &resource_id));

    EXPECT_EQ(entry.file_specific_info().alternate_url(),
              edit_url);
    EXPECT_EQ(entry.resource_id(), resource_id);
  }

  MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
  scoped_ptr<TestingProfile> profile_;

  scoped_ptr<internal::FileCache, test_util::DestroyHelperForTests> cache_;
  scoped_ptr<FileSystem> file_system_;
  scoped_ptr<google_apis::FakeDriveService> fake_drive_service_;
  scoped_ptr<JobScheduler> scheduler_;
  scoped_ptr<DriveWebAppsRegistry> drive_webapps_registry_;
  scoped_ptr<internal::ResourceMetadata, test_util::DestroyHelperForTests>
      resource_metadata_;
  scoped_ptr<FakeFreeDiskSpaceGetter> fake_free_disk_space_getter_;
  scoped_ptr<StrictMock<MockCacheObserver> > mock_cache_observer_;
  scoped_ptr<StrictMock<MockDirectoryChangeObserver> > mock_directory_observer_;

  int root_feed_changestamp_;
};

TEST_F(DriveFileSystemTest, DuplicatedAsyncInitialization) {
  // "Fast fetch" will fire an OnirectoryChanged event.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive"))))).Times(1);

  int counter = 0;
  const GetEntryInfoCallback& callback = base::Bind(
      &AsyncInitializationCallback, &counter, 2, &message_loop_);

  file_system_->GetEntryInfoByPath(
      base::FilePath(FILE_PATH_LITERAL("drive/root")), callback);
  file_system_->GetEntryInfoByPath(
      base::FilePath(FILE_PATH_LITERAL("drive/root")), callback);
  message_loop_.Run();  // Wait to get our result
  EXPECT_EQ(2, counter);

  // Although GetEntryInfoByPath() was called twice, the account metadata
  // should only be loaded once. In the past, there was a bug that caused
  // it to be loaded twice.
  EXPECT_EQ(1, fake_drive_service_->resource_list_load_count());
  // See the comment in GetMyDriveRoot test case why this is 2.
  EXPECT_EQ(2, fake_drive_service_->about_resource_load_count());
}

TEST_F(DriveFileSystemTest, GetGrandRootEntry) {
  const base::FilePath kFilePath(FILE_PATH_LITERAL("drive"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath);
  ASSERT_TRUE(entry);
  EXPECT_EQ(util::kDriveGrandRootSpecialResourceId, entry->resource_id());

  // Getting the grand root entry should not cause the resource load to happen.
  EXPECT_EQ(0, fake_drive_service_->about_resource_load_count());
  EXPECT_EQ(0, fake_drive_service_->resource_list_load_count());
}

TEST_F(DriveFileSystemTest, GetOtherDirEntry) {
  const base::FilePath kFilePath(FILE_PATH_LITERAL("drive/other"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath);
  ASSERT_TRUE(entry);
  EXPECT_EQ(util::kDriveOtherDirSpecialResourceId, entry->resource_id());

  // Getting the "other" directory entry should not cause the resource load to
  // happen.
  EXPECT_EQ(0, fake_drive_service_->about_resource_load_count());
  EXPECT_EQ(0, fake_drive_service_->resource_list_load_count());
}

TEST_F(DriveFileSystemTest, GetMyDriveRoot) {
  // "Fast fetch" will fire an OnirectoryChanged event.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive"))))).Times(1);

  const base::FilePath kFilePath(FILE_PATH_LITERAL("drive/root"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath);
  ASSERT_TRUE(entry);
  EXPECT_EQ(fake_drive_service_->GetRootResourceId(), entry->resource_id());

  // Absence of "drive/root" in the local metadata triggers the "fast fetch"
  // of "drive" directory. Fetch of "drive" grand root directory has a special
  // implementation. Instead of normal GetResourceListInDirectory(), it is
  // emulated by calling GetAboutResource() so that the resource_id of
  // "drive/root" is listed.
  // Together with the normal GetAboutResource() call to retrieve the largest
  // changestamp, the method is called twice.
  EXPECT_EQ(2, fake_drive_service_->about_resource_load_count());

  // After "fast fetch" is done, full resource list is fetched.
  EXPECT_EQ(1, fake_drive_service_->resource_list_load_count());
}

TEST_F(DriveFileSystemTest, GetExistingFile) {
  const base::FilePath kFilePath(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath);
  ASSERT_TRUE(entry);
  EXPECT_EQ("file:2_file_resource_id", entry->resource_id());

  EXPECT_EQ(1, fake_drive_service_->about_resource_load_count());
  EXPECT_EQ(1, fake_drive_service_->resource_list_load_count());
}

TEST_F(DriveFileSystemTest, GetExistingDocument) {
  const base::FilePath kFilePath(
      FILE_PATH_LITERAL("drive/root/Document 1 excludeDir-test.gdoc"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath);
  ASSERT_TRUE(entry);
  EXPECT_EQ("document:5_document_resource_id", entry->resource_id());
}

TEST_F(DriveFileSystemTest, GetNonExistingFile) {
  const base::FilePath kFilePath(
      FILE_PATH_LITERAL("drive/root/nonexisting.file"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath);
  EXPECT_FALSE(entry);
}

TEST_F(DriveFileSystemTest, GetEncodedFileNames) {
  const base::FilePath kFilePath1(
      FILE_PATH_LITERAL("drive/root/Slash / in file 1.txt"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath1);
  ASSERT_FALSE(entry);

  const base::FilePath kFilePath2 = base::FilePath::FromUTF8Unsafe(
      "drive/root/Slash \xE2\x88\x95 in file 1.txt");
  entry = GetEntryInfoByPathSync(kFilePath2);
  ASSERT_TRUE(entry);
  EXPECT_EQ("file:slash_file_resource_id", entry->resource_id());

  const base::FilePath kFilePath3 = base::FilePath::FromUTF8Unsafe(
      "drive/root/Slash \xE2\x88\x95 in directory/Slash SubDir File.txt");
  entry = GetEntryInfoByPathSync(kFilePath3);
  ASSERT_TRUE(entry);
  EXPECT_EQ("file:slash_subdir_file", entry->resource_id());
}

TEST_F(DriveFileSystemTest, GetDuplicateNames) {
  const base::FilePath kFilePath1(
      FILE_PATH_LITERAL("drive/root/Duplicate Name.txt"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath1);
  ASSERT_TRUE(entry);
  const std::string resource_id1 = entry->resource_id();

  const base::FilePath kFilePath2(
      FILE_PATH_LITERAL("drive/root/Duplicate Name (2).txt"));
  entry = GetEntryInfoByPathSync(kFilePath2);
  ASSERT_TRUE(entry);
  const std::string resource_id2 = entry->resource_id();

  // The entries are de-duped non-deterministically, so we shouldn't rely on the
  // names matching specific resource ids.
  const std::string file3_resource_id = "file:3_file_resource_id";
  const std::string file4_resource_id = "file:4_file_resource_id";
  EXPECT_TRUE(file3_resource_id == resource_id1 ||
              file3_resource_id == resource_id2);
  EXPECT_TRUE(file4_resource_id == resource_id1 ||
              file4_resource_id == resource_id2);
}

TEST_F(DriveFileSystemTest, GetExistingDirectory) {
  const base::FilePath kFilePath(FILE_PATH_LITERAL("drive/root/Directory 1"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath);
  ASSERT_TRUE(entry);
  ASSERT_EQ("folder:1_folder_resource_id", entry->resource_id());

  // The changestamp should be propagated to the directory.
  EXPECT_EQ(fake_drive_service_->largest_changestamp(),
            entry->directory_specific_info().changestamp());
}

TEST_F(DriveFileSystemTest, GetInSubSubdir) {
  const base::FilePath kFilePath(
      FILE_PATH_LITERAL("drive/root/Directory 1/Sub Directory Folder/"
                        "Sub Sub Directory Folder"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath);
  ASSERT_TRUE(entry);
  ASSERT_EQ("folder:sub_sub_directory_folder_id", entry->resource_id());
}

TEST_F(DriveFileSystemTest, GetOrphanFile) {
  const base::FilePath kFilePath(
      FILE_PATH_LITERAL("drive/other/Orphan File 1.txt"));
  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(kFilePath);
  ASSERT_TRUE(entry);
  EXPECT_EQ("file:1_orphanfile_resource_id", entry->resource_id());
}

TEST_F(DriveFileSystemTest, ReadDirectoryByPath_Root) {
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive"))))).Times(1);

  // ReadDirectoryByPath() should kick off the resource list loading.
  scoped_ptr<ResourceEntryVector> entries(
      ReadDirectoryByPathSync(base::FilePath::FromUTF8Unsafe("drive")));
  // The root directory should be read correctly.
  ASSERT_TRUE(entries);
  ASSERT_EQ(2U, entries->size());

  // The found two directories should be /drive/root and /drive/other.
  bool found_other = false;
  bool found_my_drive = false;
  for (size_t i = 0; i < entries->size(); ++i) {
    const base::FilePath title =
        base::FilePath::FromUTF8Unsafe((*entries)[i].title());
    if (title == base::FilePath(util::kDriveOtherDirName)) {
      found_other = true;
    } else if (title == base::FilePath(util::kDriveMyDriveRootDirName)) {
      found_my_drive = true;
    }
  }

  EXPECT_TRUE(found_other);
  EXPECT_TRUE(found_my_drive);
}

TEST_F(DriveFileSystemTest, ReadDirectoryByPath_NonRootDirectory) {
  // ReadDirectoryByPath() should kick off the resource list loading.
  scoped_ptr<ResourceEntryVector> entries(
      ReadDirectoryByPathSync(
          base::FilePath::FromUTF8Unsafe("drive/root/Directory 1")));
  // The non root directory should also be read correctly.
  // There was a bug (crbug.com/181487), which broke this behavior.
  // Make sure this is fixed.
  ASSERT_TRUE(entries);
  EXPECT_EQ(3U, entries->size());
}

TEST_F(DriveFileSystemTest, ChangeFeed_AddAndDeleteFileInRoot) {
  ASSERT_TRUE(LoadRootFeedDocument());

  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(2);

  ASSERT_TRUE(LoadChangeFeed("chromeos/gdata/delta_file_added_in_root.json"));
  EXPECT_TRUE(EntryExists(
      base::FilePath(FILE_PATH_LITERAL("drive/root/Added file.gdoc"))));

  ASSERT_TRUE(LoadChangeFeed("chromeos/gdata/delta_file_deleted_in_root.json"));
  EXPECT_FALSE(EntryExists(
      base::FilePath(FILE_PATH_LITERAL("drive/root/Added file.gdoc"))));
}

TEST_F(DriveFileSystemTest, ChangeFeed_AddAndDeleteFileFromExistingDirectory) {
  ASSERT_TRUE(LoadRootFeedDocument());

  EXPECT_TRUE(
      EntryExists(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1"))));

  // Add file to an existing directory.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1")))))
      .Times(1);
  ASSERT_TRUE(
      LoadChangeFeed("chromeos/gdata/delta_file_added_in_directory.json"));
  EXPECT_TRUE(EntryExists(base::FilePath(
      FILE_PATH_LITERAL("drive/root/Directory 1/Added file.gdoc"))));

  // Remove that file from the directory.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1")))))
      .Times(1);
  ASSERT_TRUE(
      LoadChangeFeed("chromeos/gdata/delta_file_deleted_in_directory.json"));
  EXPECT_TRUE(
      EntryExists(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1"))));
  EXPECT_FALSE(EntryExists(base::FilePath(
      FILE_PATH_LITERAL("drive/root/Directory 1/Added file.gdoc"))));
}

TEST_F(DriveFileSystemTest, ChangeFeed_AddFileToNewDirectory) {
  ASSERT_TRUE(LoadRootFeedDocument());
  // Add file to a new directory.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/New Directory")))))
      .Times(1);

  ASSERT_TRUE(
      LoadChangeFeed("chromeos/gdata/delta_file_added_in_new_directory.json"));

  EXPECT_TRUE(
      EntryExists(base::FilePath(
          FILE_PATH_LITERAL("drive/root/New Directory"))));
  EXPECT_TRUE(EntryExists(base::FilePath(
      FILE_PATH_LITERAL("drive/root/New Directory/File in new dir.gdoc"))));
}

TEST_F(DriveFileSystemTest, ChangeFeed_AddFileToNewButDeletedDirectory) {
  ASSERT_TRUE(LoadRootFeedDocument());

  // This feed contains the following updates:
  // 1) A new PDF file is added to a new directory
  // 2) but the new directory is marked "deleted" (i.e. moved to Trash)
  // Hence, the PDF file should be just ignored.
  ASSERT_TRUE(LoadChangeFeed(
      "chromeos/gdata/delta_file_added_in_new_but_deleted_directory.json"));
}

TEST_F(DriveFileSystemTest, ChangeFeed_DirectoryMovedFromRootToDirectory) {
  ASSERT_TRUE(LoadRootFeedDocument());

  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 2 excludeDir-test"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/SubDirectory File 1.txt"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/Sub Directory Folder"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/Sub Directory Folder/"
      "Sub Sub Directory Folder"))));

  // This will move "Directory 1" from "drive/root/" to
  // "drive/root/Directory 2/".
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1")))))
      .Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL(
          "drive/root/Directory 2 excludeDir-test"))))).Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL(
          "drive/root/Directory 2 excludeDir-test/Directory 1"))))).Times(1);
  ASSERT_TRUE(LoadChangeFeed(
      "chromeos/gdata/delta_dir_moved_from_root_to_directory.json"));

  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 2 excludeDir-test"))));
  EXPECT_FALSE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 2 excludeDir-test/Directory 1"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 2 excludeDir-test/Directory 1/"
      "SubDirectory File 1.txt"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 2 excludeDir-test/Directory 1/"
      "Sub Directory Folder"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 2 excludeDir-test/Directory 1/Sub Directory Folder/"
      "Sub Sub Directory Folder"))));
}

TEST_F(DriveFileSystemTest, ChangeFeed_FileMovedFromDirectoryToRoot) {
  ASSERT_TRUE(LoadRootFeedDocument());

  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/Sub Directory Folder"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/Sub Directory Folder/"
      "Sub Sub Directory Folder"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/SubDirectory File 1.txt"))));

  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1")))))
      .Times(1);
  ASSERT_TRUE(LoadChangeFeed(
      "chromeos/gdata/delta_file_moved_from_directory_to_root.json"));

  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/Sub Directory Folder"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/Sub Directory Folder/"
      "Sub Sub Directory Folder"))));
  EXPECT_FALSE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/SubDirectory File 1.txt"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/SubDirectory File 1.txt"))));
}

TEST_F(DriveFileSystemTest, ChangeFeed_FileRenamedInDirectory) {
  ASSERT_TRUE(LoadRootFeedDocument());

  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/SubDirectory File 1.txt"))));

  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1")))))
      .Times(1);
  ASSERT_TRUE(LoadChangeFeed(
      "chromeos/gdata/delta_file_renamed_in_directory.json"));

  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1"))));
  EXPECT_FALSE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/SubDirectory File 1.txt"))));
  EXPECT_TRUE(EntryExists(base::FilePath(FILE_PATH_LITERAL(
      "drive/root/Directory 1/New SubDirectory File 1.txt"))));
}

TEST_F(DriveFileSystemTest, CachedFeedLoadingThenServerFeedLoading) {
  ASSERT_TRUE(SetUpTestFileSystem(USE_SERVER_TIMESTAMP));

  // Kicks loading of cached file system and query for server update.
  EXPECT_TRUE(ReadDirectoryByPathSync(util::GetDriveMyDriveRootPath()));

  // SetUpTestFileSystem and "account_metadata.json" have the same changestamp,
  // so no request for new feeds (i.e., call to GetResourceList) should happen.
  EXPECT_EQ(1, fake_drive_service_->about_resource_load_count());
  EXPECT_EQ(0, fake_drive_service_->resource_list_load_count());

  // Since the file system has verified that it holds the latest snapshot,
  // it should change its state to "loaded", which admits periodic refresh.
  // To test it, call CheckForUpdates and verify it does try to check updates.
  file_system_->CheckForUpdates();
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(2, fake_drive_service_->about_resource_load_count());
}

TEST_F(DriveFileSystemTest, OfflineCachedFeedLoading) {
  ASSERT_TRUE(SetUpTestFileSystem(USE_OLD_TIMESTAMP));

  // Make GetResourceList fail for simulating offline situation. This will leave
  // the file system "loaded from cache, but not synced with server" state.
  fake_drive_service_->set_offline(true);

  // Kicks loading of cached file system and query for server update.
  EXPECT_TRUE(ReadDirectoryByPathSync(util::GetDriveMyDriveRootPath()));
  // Loading of account metadata should not happen as it's offline.
  EXPECT_EQ(0, fake_drive_service_->account_metadata_load_count());

  // Tests that cached data can be loaded even if the server is not reachable.
  EXPECT_TRUE(EntryExists(base::FilePath(
      FILE_PATH_LITERAL("drive/root/File1"))));
  EXPECT_TRUE(EntryExists(base::FilePath(
      FILE_PATH_LITERAL("drive/root/Dir1"))));
  EXPECT_TRUE(
      EntryExists(base::FilePath(FILE_PATH_LITERAL("drive/root/Dir1/File2"))));
  EXPECT_TRUE(EntryExists(base::FilePath(
      FILE_PATH_LITERAL("drive/root/Dir1/SubDir2"))));
  EXPECT_TRUE(EntryExists(
      base::FilePath(FILE_PATH_LITERAL("drive/root/Dir1/SubDir2/File3"))));

  // Since the file system has at least succeeded to load cached snapshot,
  // the file system should be able to start periodic refresh.
  // To test it, call CheckForUpdates and verify it does try to check
  // updates, which will cause directory changes.
  fake_drive_service_->set_offline(false);

  file_system_->CheckForUpdates();
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(_))
      .Times(AtLeast(1));

  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(1, fake_drive_service_->about_resource_load_count());
  EXPECT_EQ(1, fake_drive_service_->change_list_load_count());
}

TEST_F(DriveFileSystemTest, ReadDirectoryWhileRefreshing) {
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(_))
      .Times(AtLeast(1));

  // Enter the "refreshing" state so the fast fetch will be performed.
  ASSERT_TRUE(SetUpTestFileSystem(USE_OLD_TIMESTAMP));
  file_system_->CheckForUpdates();

  // The list of resources in "drive/root/Dir1" should be fetched.
  EXPECT_TRUE(ReadDirectoryByPathSync(base::FilePath(
      FILE_PATH_LITERAL("drive/root/Dir1"))));
  EXPECT_EQ(1, fake_drive_service_->directory_load_count());
}

TEST_F(DriveFileSystemTest, GetEntryInfoExistingWhileRefreshing) {
  // Enter the "refreshing" state.
  ASSERT_TRUE(SetUpTestFileSystem(USE_OLD_TIMESTAMP));
  file_system_->CheckForUpdates();

  // If an entry is already found in local metadata, no directory fetch happens.
  EXPECT_TRUE(GetEntryInfoByPathSync(base::FilePath(
      FILE_PATH_LITERAL("drive/root/Dir1/File2"))));
  EXPECT_EQ(0, fake_drive_service_->directory_load_count());
}

TEST_F(DriveFileSystemTest, GetEntryInfoNonExistentWhileRefreshing) {
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(_))
      .Times(AtLeast(1));

  // Enter the "refreshing" state so the fast fetch will be performed.
  ASSERT_TRUE(SetUpTestFileSystem(USE_OLD_TIMESTAMP));
  file_system_->CheckForUpdates();

  // If an entry is not found, parent directory's resource list is fetched.
  EXPECT_FALSE(GetEntryInfoByPathSync(base::FilePath(
      FILE_PATH_LITERAL("drive/root/Dir1/NonExistentFile"))));
  EXPECT_EQ(1, fake_drive_service_->directory_load_count());
}

TEST_F(DriveFileSystemTest, TransferFileFromLocalToRemote_RegularFile) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  ASSERT_TRUE(LoadRootFeedDocument());

  // We'll add a file to the Drive root directory.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);

  // Prepare a local file.
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath local_src_file_path =
      temp_dir.path().AppendASCII("local.txt");
  ASSERT_TRUE(
      google_apis::test_util::WriteStringToFile(local_src_file_path, "hello"));

  // Confirm that the remote file does not exist.
  const base::FilePath remote_dest_file_path(
      FILE_PATH_LITERAL("drive/root/remote.txt"));
  EXPECT_FALSE(EntryExists(remote_dest_file_path));

  // What TransferFileFromLocalToRemote does is to store the local file in
  // the Drive file cache, and mark it as dirty+committed. Here we test that
  // the "cache committed" event is indeed fired as a result of this test case.
  //
  // In the production environment, SyncClient listens this event and uploads
  // the file to the remote server in background. This part should be tested in
  // sync_client_unittest.cc
  EXPECT_CALL(*mock_cache_observer_, OnCacheCommitted(_)).Times(1);

  // Transfer the local file to Drive.
  FileError error = FILE_ERROR_FAILED;
  file_system_->TransferFileFromLocalToRemote(
      local_src_file_path,
      remote_dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);

  // Now the remote file should exist.
  EXPECT_TRUE(EntryExists(remote_dest_file_path));
}

TEST_F(DriveFileSystemTest, TransferFileFromLocalToRemote_HostedDocument) {
  ASSERT_TRUE(LoadRootFeedDocument());

  // Prepare a local file, which is a json file of a hosted document, which
  // matches "Document 1" in root_feed.json.
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath local_src_file_path =
      temp_dir.path().AppendASCII("local.gdoc");
  const std::string kEditUrl =
      "https://3_document_self_link/document:5_document_resource_id";
  const std::string kResourceId = "document:5_document_resource_id";
  ASSERT_TRUE(google_apis::test_util::WriteStringToFile(
      local_src_file_path,
      base::StringPrintf("{\"url\": \"%s\", \"resource_id\": \"%s\"}",
                         kEditUrl.c_str(), kResourceId.c_str())));

  // Confirm that the remote file does not exist.
  const base::FilePath remote_dest_file_path(FILE_PATH_LITERAL(
      "drive/root/Directory 1/Document 1 excludeDir-test.gdoc"));
  EXPECT_FALSE(EntryExists(remote_dest_file_path));

  // We'll add a file to the Drive root and then move to "Directory 1".
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1")))))
      .Times(1);

  // Transfer the local file to Drive.
  FileError error = FILE_ERROR_FAILED;
  file_system_->TransferFileFromLocalToRemote(
      local_src_file_path,
      remote_dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);

  // Now the remote file should exist.
  EXPECT_TRUE(EntryExists(remote_dest_file_path));
}

TEST_F(DriveFileSystemTest, TransferFileFromRemoteToLocal_RegularFile) {
  ASSERT_TRUE(LoadRootFeedDocument());

  // The transfered file is cached and the change of "offline available"
  // attribute is notified.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);

  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  base::FilePath local_dest_file_path =
      temp_dir.path().AppendASCII("local_copy.txt");

  base::FilePath remote_src_file_path(
      FILE_PATH_LITERAL("drive/root/File 1.txt"));
  scoped_ptr<ResourceEntry> file = GetEntryInfoByPathSync(
      remote_src_file_path);
  const int64 file_size = file->file_info().size();

  // Pretend we have enough space.
  fake_free_disk_space_getter_->set_fake_free_disk_space(
      file_size + internal::kMinFreeSpace);

  FileError error = FILE_ERROR_FAILED;
  file_system_->TransferFileFromRemoteToLocal(
      remote_src_file_path,
      local_dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);

  // The content is "x"s of the file size.
  base::FilePath cache_file_path;
  cache_->GetFile(file->resource_id(),
                  file->file_specific_info().file_md5(),
                  google_apis::test_util::CreateCopyResultCallback(
                      &error, &cache_file_path));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  const std::string kExpectedContent = "xxxxxxxxxx";
  std::string cache_file_data;
  EXPECT_TRUE(file_util::ReadFileToString(cache_file_path, &cache_file_data));
  EXPECT_EQ(kExpectedContent, cache_file_data);

  std::string local_dest_file_data;
  EXPECT_TRUE(file_util::ReadFileToString(local_dest_file_path,
                                          &local_dest_file_data));
  EXPECT_EQ(kExpectedContent, local_dest_file_data);
}

TEST_F(DriveFileSystemTest, TransferFileFromRemoteToLocal_HostedDocument) {
  ASSERT_TRUE(LoadRootFeedDocument());

  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  base::FilePath local_dest_file_path =
      temp_dir.path().AppendASCII("local_copy.txt");
  base::FilePath remote_src_file_path(
      FILE_PATH_LITERAL("drive/root/Document 1 excludeDir-test.gdoc"));
  FileError error = FILE_ERROR_FAILED;
  file_system_->TransferFileFromRemoteToLocal(
      remote_src_file_path,
      local_dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);

  scoped_ptr<ResourceEntry> entry = GetEntryInfoByPathSync(
      remote_src_file_path);
  ASSERT_TRUE(entry);
  VerifyHostedDocumentJSONFile(*entry, local_dest_file_path);
}

TEST_F(DriveFileSystemTest, CopyNotExistingFile) {
  base::FilePath src_file_path(FILE_PATH_LITERAL("drive/root/Dummy file.txt"));
  base::FilePath dest_file_path(FILE_PATH_LITERAL("drive/root/Test.log"));

  ASSERT_TRUE(LoadRootFeedDocument());

  EXPECT_FALSE(EntryExists(src_file_path));

  FileError error = FILE_ERROR_OK;
  file_system_->Copy(
      src_file_path,
      dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, error);

  EXPECT_FALSE(EntryExists(src_file_path));
  EXPECT_FALSE(EntryExists(dest_file_path));
}

TEST_F(DriveFileSystemTest, CopyFileToNonExistingDirectory) {
  base::FilePath src_file_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath dest_parent_path(FILE_PATH_LITERAL("drive/root/Dummy"));
  base::FilePath dest_file_path(FILE_PATH_LITERAL("drive/root/Dummy/Test.log"));

  ASSERT_TRUE(LoadRootFeedDocument());

  ASSERT_TRUE(EntryExists(src_file_path));
  scoped_ptr<ResourceEntry> src_entry = GetEntryInfoByPathSync(
      src_file_path);
  ASSERT_TRUE(src_entry);
  std::string src_file_path_resource_id =
      src_entry->resource_id();
  EXPECT_FALSE(src_entry->edit_url().empty());

  EXPECT_FALSE(EntryExists(dest_parent_path));

  FileError error = FILE_ERROR_OK;
  file_system_->Move(
      src_file_path,
      dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, error);

  EXPECT_TRUE(EntryExists(src_file_path));
  EXPECT_FALSE(EntryExists(dest_parent_path));
  EXPECT_FALSE(EntryExists(dest_file_path));
}

// Test the case where the parent of |dest_file_path| is an existing file,
// not a directory.
TEST_F(DriveFileSystemTest, CopyFileToInvalidPath) {
  base::FilePath src_file_path(FILE_PATH_LITERAL(
      "drive/root/Document 1 excludeDir-test.gdoc"));
  base::FilePath dest_parent_path(
      FILE_PATH_LITERAL("drive/root/Duplicate Name.txt"));
  base::FilePath dest_file_path(FILE_PATH_LITERAL(
      "drive/root/Duplicate Name.txt/Document 1 excludeDir-test.gdoc"));

  ASSERT_TRUE(LoadRootFeedDocument());

  ASSERT_TRUE(EntryExists(src_file_path));
  scoped_ptr<ResourceEntry> src_entry = GetEntryInfoByPathSync(
      src_file_path);
  ASSERT_TRUE(src_entry);
  std::string src_file_resource_id =
      src_entry->resource_id();
  EXPECT_FALSE(src_entry->edit_url().empty());

  ASSERT_TRUE(EntryExists(dest_parent_path));
  scoped_ptr<ResourceEntry> dest_entry = GetEntryInfoByPathSync(
      dest_parent_path);
  ASSERT_TRUE(dest_entry);

  FileError error = FILE_ERROR_OK;
  file_system_->Copy(
      src_file_path,
      dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_NOT_A_DIRECTORY, error);

  EXPECT_TRUE(EntryExists(src_file_path));
  EXPECT_TRUE(EntryExists(src_file_path));
  EXPECT_TRUE(EntryExists(dest_parent_path));

  EXPECT_FALSE(EntryExists(dest_file_path));
}

TEST_F(DriveFileSystemTest, RenameFile) {
  const base::FilePath src_file_path(
      FILE_PATH_LITERAL("drive/root/Directory 1/SubDirectory File 1.txt"));
  const base::FilePath src_parent_path(
      FILE_PATH_LITERAL("drive/root/Directory 1"));
  const base::FilePath dest_file_path(
      FILE_PATH_LITERAL("drive/root/Directory 1/Test.log"));

  ASSERT_TRUE(LoadRootFeedDocument());

  ASSERT_TRUE(EntryExists(src_file_path));
  scoped_ptr<ResourceEntry> src_entry = GetEntryInfoByPathSync(
      src_file_path);
  ASSERT_TRUE(src_entry);
  std::string src_file_resource_id =
      src_entry->resource_id();

  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1")))))
      .Times(1);

  FileError error = FILE_ERROR_FAILED;
  file_system_->Move(
      src_file_path,
      dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  EXPECT_FALSE(EntryExists(src_file_path));
  EXPECT_TRUE(EntryExists(dest_file_path));
  EXPECT_EQ(src_file_resource_id, GetResourceIdByPath(dest_file_path));
}

TEST_F(DriveFileSystemTest, MoveFileFromRootToSubDirectory) {
  base::FilePath src_file_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath dest_parent_path(FILE_PATH_LITERAL("drive/root/Directory 1"));
  base::FilePath dest_file_path(
      FILE_PATH_LITERAL("drive/root/Directory 1/Test.log"));

  ASSERT_TRUE(LoadRootFeedDocument());

  ASSERT_TRUE(EntryExists(src_file_path));
  scoped_ptr<ResourceEntry> src_entry = GetEntryInfoByPathSync(
      src_file_path);
  ASSERT_TRUE(src_entry);
  std::string src_file_resource_id =
      src_entry->resource_id();
  EXPECT_FALSE(src_entry->edit_url().empty());

  ASSERT_TRUE(EntryExists(dest_parent_path));
  scoped_ptr<ResourceEntry> dest_parent_proto = GetEntryInfoByPathSync(
      dest_parent_path);
  ASSERT_TRUE(dest_parent_proto);
  ASSERT_TRUE(dest_parent_proto->file_info().is_directory());
  EXPECT_FALSE(dest_parent_proto->download_url().empty());

  // Expect notification for both source and destination directories.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1")))))
      .Times(1);

  FileError error = FILE_ERROR_FAILED;
  file_system_->Move(
      src_file_path,
      dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  EXPECT_FALSE(EntryExists(src_file_path));
  EXPECT_TRUE(EntryExists(dest_file_path));
  EXPECT_EQ(src_file_resource_id, GetResourceIdByPath(dest_file_path));
}

TEST_F(DriveFileSystemTest, MoveFileFromSubDirectoryToRoot) {
  base::FilePath src_parent_path(FILE_PATH_LITERAL("drive/root/Directory 1"));
  base::FilePath src_file_path(
      FILE_PATH_LITERAL("drive/root/Directory 1/SubDirectory File 1.txt"));
  base::FilePath dest_file_path(FILE_PATH_LITERAL("drive/root/Test.log"));

  ASSERT_TRUE(LoadRootFeedDocument());

  ASSERT_TRUE(EntryExists(src_file_path));
  scoped_ptr<ResourceEntry> src_entry = GetEntryInfoByPathSync(
      src_file_path);
  ASSERT_TRUE(src_entry);
  std::string src_file_resource_id =
      src_entry->resource_id();
  EXPECT_FALSE(src_entry->edit_url().empty());

  ASSERT_TRUE(EntryExists(src_parent_path));
  scoped_ptr<ResourceEntry> src_parent_proto = GetEntryInfoByPathSync(
      src_parent_path);
  ASSERT_TRUE(src_parent_proto);
  ASSERT_TRUE(src_parent_proto->file_info().is_directory());
  EXPECT_FALSE(src_parent_proto->download_url().empty());

  // Expect notification for both source and destination directories.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1")))))
      .Times(1);

  FileError error = FILE_ERROR_FAILED;
  file_system_->Move(
      src_file_path,
      dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  EXPECT_FALSE(EntryExists(src_file_path));
  ASSERT_TRUE(EntryExists(dest_file_path));
  EXPECT_EQ(src_file_resource_id, GetResourceIdByPath(dest_file_path));
}

TEST_F(DriveFileSystemTest, MoveFileBetweenSubDirectories) {
  base::FilePath src_parent_path(FILE_PATH_LITERAL("drive/root/Directory 1"));
  base::FilePath src_file_path(
      FILE_PATH_LITERAL("drive/root/Directory 1/SubDirectory File 1.txt"));
  base::FilePath dest_parent_path(FILE_PATH_LITERAL("drive/root/New Folder 1"));
  base::FilePath dest_file_path(
      FILE_PATH_LITERAL("drive/root/New Folder 1/Test.log"));
  base::FilePath interim_file_path(FILE_PATH_LITERAL("drive/root/Test.log"));

  ASSERT_TRUE(LoadRootFeedDocument());

  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);

  EXPECT_EQ(FILE_ERROR_OK, AddDirectory(dest_parent_path));

  ASSERT_TRUE(EntryExists(src_file_path));
  scoped_ptr<ResourceEntry> src_entry = GetEntryInfoByPathSync(
      src_file_path);
  ASSERT_TRUE(src_entry);
  std::string src_file_resource_id =
      src_entry->resource_id();
  EXPECT_FALSE(src_entry->edit_url().empty());

  ASSERT_TRUE(EntryExists(src_parent_path));
  scoped_ptr<ResourceEntry> src_parent_proto = GetEntryInfoByPathSync(
      src_parent_path);
  ASSERT_TRUE(src_parent_proto);
  ASSERT_TRUE(src_parent_proto->file_info().is_directory());
  EXPECT_FALSE(src_parent_proto->download_url().empty());

  ASSERT_TRUE(EntryExists(dest_parent_path));
  scoped_ptr<ResourceEntry> dest_parent_proto = GetEntryInfoByPathSync(
      dest_parent_path);
  ASSERT_TRUE(dest_parent_proto);
  ASSERT_TRUE(dest_parent_proto->file_info().is_directory());
  EXPECT_FALSE(dest_parent_proto->download_url().empty());

  EXPECT_FALSE(EntryExists(interim_file_path));

  // Expect notification for both source and destination directories.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/Directory 1")))))
      .Times(1);
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/New Folder 1")))))
      .Times(1);

  FileError error = FILE_ERROR_FAILED;
  file_system_->Move(
      src_file_path,
      dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  EXPECT_FALSE(EntryExists(src_file_path));
  EXPECT_FALSE(EntryExists(interim_file_path));

  EXPECT_FALSE(EntryExists(src_file_path));
  EXPECT_TRUE(EntryExists(dest_file_path));
  EXPECT_EQ(src_file_resource_id, GetResourceIdByPath(dest_file_path));
}

TEST_F(DriveFileSystemTest, MoveNotExistingFile) {
  base::FilePath src_file_path(FILE_PATH_LITERAL("drive/root/Dummy file.txt"));
  base::FilePath dest_file_path(FILE_PATH_LITERAL("drive/root/Test.log"));

  ASSERT_TRUE(LoadRootFeedDocument());

  EXPECT_FALSE(EntryExists(src_file_path));

  FileError error = FILE_ERROR_OK;
  file_system_->Move(
      src_file_path,
      dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, error);

  EXPECT_FALSE(EntryExists(src_file_path));
  EXPECT_FALSE(EntryExists(dest_file_path));
}

TEST_F(DriveFileSystemTest, MoveFileToNonExistingDirectory) {
  base::FilePath src_file_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath dest_parent_path(FILE_PATH_LITERAL("drive/root/Dummy"));
  base::FilePath dest_file_path(FILE_PATH_LITERAL("drive/root/Dummy/Test.log"));

  ASSERT_TRUE(LoadRootFeedDocument());

  ASSERT_TRUE(EntryExists(src_file_path));
  scoped_ptr<ResourceEntry> src_entry = GetEntryInfoByPathSync(
      src_file_path);
  ASSERT_TRUE(src_entry);
  std::string src_file_resource_id =
      src_entry->resource_id();
  EXPECT_FALSE(src_entry->edit_url().empty());

  EXPECT_FALSE(EntryExists(dest_parent_path));

  FileError error = FILE_ERROR_OK;
  file_system_->Move(
      src_file_path,
      dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, error);

  EXPECT_FALSE(EntryExists(dest_parent_path));
  EXPECT_FALSE(EntryExists(dest_file_path));
}

// Test the case where the parent of |dest_file_path| is a existing file,
// not a directory.
TEST_F(DriveFileSystemTest, MoveFileToInvalidPath) {
  base::FilePath src_file_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath dest_parent_path(
      FILE_PATH_LITERAL("drive/root/Duplicate Name.txt"));
  base::FilePath dest_file_path(FILE_PATH_LITERAL(
      "drive/root/Duplicate Name.txt/Test.log"));

  ASSERT_TRUE(LoadRootFeedDocument());

  ASSERT_TRUE(EntryExists(src_file_path));
  scoped_ptr<ResourceEntry> src_entry = GetEntryInfoByPathSync(
      src_file_path);
  ASSERT_TRUE(src_entry);
  std::string src_file_resource_id =
      src_entry->resource_id();
  EXPECT_FALSE(src_entry->edit_url().empty());

  ASSERT_TRUE(EntryExists(dest_parent_path));
  scoped_ptr<ResourceEntry> dest_parent_proto = GetEntryInfoByPathSync(
      dest_parent_path);
  ASSERT_TRUE(dest_parent_proto);

  FileError error = FILE_ERROR_OK;
  file_system_->Move(
      src_file_path,
      dest_file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_NOT_A_DIRECTORY, error);

  EXPECT_TRUE(EntryExists(src_file_path));
  EXPECT_TRUE(EntryExists(dest_parent_path));
  EXPECT_FALSE(EntryExists(dest_file_path));
}

TEST_F(DriveFileSystemTest, RemoveEntries) {
  ASSERT_TRUE(LoadRootFeedDocument());

  base::FilePath nonexisting_file(
      FILE_PATH_LITERAL("drive/root/Dummy file.txt"));
  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  base::FilePath dir_in_root(FILE_PATH_LITERAL("drive/root/Directory 1"));
  base::FilePath file_in_subdir(
      FILE_PATH_LITERAL("drive/root/Directory 1/SubDirectory File 1.txt"));

  ASSERT_TRUE(EntryExists(file_in_root));
  scoped_ptr<ResourceEntry> file_in_root_proto = GetEntryInfoByPathSync(
      file_in_root);
  ASSERT_TRUE(file_in_root_proto);

  ASSERT_TRUE(EntryExists(dir_in_root));
  scoped_ptr<ResourceEntry> dir_in_root_proto = GetEntryInfoByPathSync(
      dir_in_root);
  ASSERT_TRUE(dir_in_root_proto);
  ASSERT_TRUE(dir_in_root_proto->file_info().is_directory());

  ASSERT_TRUE(EntryExists(file_in_subdir));
  scoped_ptr<ResourceEntry> file_in_subdir_proto = GetEntryInfoByPathSync(
      file_in_subdir);
  ASSERT_TRUE(file_in_subdir_proto);

  // Once for file in root and once for file...
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(2);

  // Remove first file in root.
  EXPECT_TRUE(RemoveEntry(file_in_root));
  EXPECT_FALSE(EntryExists(file_in_root));
  EXPECT_TRUE(EntryExists(dir_in_root));
  EXPECT_TRUE(EntryExists(file_in_subdir));

  // Remove directory.
  EXPECT_TRUE(RemoveEntry(dir_in_root));
  EXPECT_FALSE(EntryExists(file_in_root));
  EXPECT_FALSE(EntryExists(dir_in_root));
  EXPECT_FALSE(EntryExists(file_in_subdir));

  // Try removing file in already removed subdirectory.
  EXPECT_FALSE(RemoveEntry(file_in_subdir));

  // Try removing non-existing file.
  EXPECT_FALSE(RemoveEntry(nonexisting_file));

  // Try removing root file element.
  EXPECT_FALSE(RemoveEntry(base::FilePath(FILE_PATH_LITERAL("drive/root"))));

  // Need this to ensure OnDirectoryChanged() is run.
  google_apis::test_util::RunBlockingPoolTask();
}

TEST_F(DriveFileSystemTest, CreateDirectory) {
  ASSERT_TRUE(LoadRootFeedDocument());

  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);

  // Create directory in root.
  base::FilePath dir_path(FILE_PATH_LITERAL("drive/root/New Folder 1"));
  EXPECT_FALSE(EntryExists(dir_path));
  EXPECT_EQ(FILE_ERROR_OK, AddDirectory(dir_path));
  EXPECT_TRUE(EntryExists(dir_path));

  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root/New Folder 1")))))
      .Times(1);

  // Create directory in a sub directory.
  base::FilePath subdir_path(
      FILE_PATH_LITERAL("drive/root/New Folder 1/New Folder 2"));
  EXPECT_FALSE(EntryExists(subdir_path));
  EXPECT_EQ(FILE_ERROR_OK, AddDirectory(subdir_path));
  EXPECT_TRUE(EntryExists(subdir_path));
}

TEST_F(DriveFileSystemTest, CreateDirectoryByImplicitLoad) {
  // Intentionally *not* calling LoadRootFeedDocument(), for testing that
  // CreateDirectory ensures feed loading before it runs.

  base::FilePath existing_directory(
      FILE_PATH_LITERAL("drive/root/Directory 1"));
  FileError error = FILE_ERROR_FAILED;
  file_system_->CreateDirectory(
      existing_directory,
      true,  // is_exclusive
      false,  // is_recursive
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();

  // It should fail because is_exclusive is set to true.
  EXPECT_EQ(FILE_ERROR_EXISTS, error);
}

TEST_F(DriveFileSystemTest, PinAndUnpin) {
  ASSERT_TRUE(LoadRootFeedDocument());

  base::FilePath file_path(FILE_PATH_LITERAL("drive/root/File 1.txt"));

  // Get the file info.
  scoped_ptr<ResourceEntry> entry(GetEntryInfoByPathSync(file_path));
  ASSERT_TRUE(entry);

  // Pin the file.
  FileError error = FILE_ERROR_FAILED;
  EXPECT_CALL(*mock_cache_observer_,
              OnCachePinned(entry->resource_id(),
                            entry->file_specific_info().file_md5())).Times(1);
  file_system_->Pin(file_path,
                    google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Unpin the file.
  error = FILE_ERROR_FAILED;
  EXPECT_CALL(*mock_cache_observer_,
              OnCacheUnpinned(entry->resource_id(),
                              entry->file_specific_info().file_md5())).Times(1);
  file_system_->Unpin(file_path,
                      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);
}

TEST_F(DriveFileSystemTest, GetFileByPath_FromGData_EnoughSpace) {
  ASSERT_TRUE(LoadRootFeedDocument());

  // The transfered file is cached and the change of "offline available"
  // attribute is notified.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);

  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  scoped_ptr<ResourceEntry> entry(GetEntryInfoByPathSync(file_in_root));
  const int64 file_size = entry->file_info().size();

  // Pretend we have enough space.
  fake_free_disk_space_getter_->set_fake_free_disk_space(
      file_size + internal::kMinFreeSpace);

  FileError error = FILE_ERROR_FAILED;
  base::FilePath file_path;
  entry.reset();
  file_system_->GetFileByPath(file_in_root,
                              google_apis::test_util::CreateCopyResultCallback(
                                  &error, &file_path, &entry));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(entry);
  EXPECT_FALSE(entry->file_specific_info().is_hosted_document());

  // Verify that readable permission is set.
  int permission = 0;
  EXPECT_TRUE(file_util::GetPosixFilePermissions(file_path, &permission));
  EXPECT_EQ(file_util::FILE_PERMISSION_READ_BY_USER |
            file_util::FILE_PERMISSION_WRITE_BY_USER |
            file_util::FILE_PERMISSION_READ_BY_GROUP |
            file_util::FILE_PERMISSION_READ_BY_OTHERS, permission);
}

TEST_F(DriveFileSystemTest, GetFileByPath_FromGData_NoSpaceAtAll) {
  ASSERT_TRUE(LoadRootFeedDocument());

  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));

  // Pretend we have no space at all.
  fake_free_disk_space_getter_->set_fake_free_disk_space(0);

  FileError error = FILE_ERROR_OK;
  base::FilePath file_path;
  scoped_ptr<ResourceEntry> entry;
  file_system_->GetFileByPath(file_in_root,
                              google_apis::test_util::CreateCopyResultCallback(
                                  &error, &file_path, &entry));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_NO_SPACE, error);
}

TEST_F(DriveFileSystemTest, GetFileByPath_FromGData_NoEnoughSpaceButCanFreeUp) {
  ASSERT_TRUE(LoadRootFeedDocument());

  // The transfered file is cached and the change of "offline available"
  // attribute is notified.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);

  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  scoped_ptr<ResourceEntry> entry(GetEntryInfoByPathSync(file_in_root));
  const int64 file_size = entry->file_info().size();

  // Pretend we have no space first (checked before downloading a file),
  // but then start reporting we have space. This is to emulate that
  // the disk space was freed up by removing temporary files.
  fake_free_disk_space_getter_->set_fake_free_disk_space(
      file_size + internal::kMinFreeSpace);
  fake_free_disk_space_getter_->set_fake_free_disk_space(0);
  fake_free_disk_space_getter_->set_fake_free_disk_space(
      file_size + internal::kMinFreeSpace);
  fake_free_disk_space_getter_->set_fake_free_disk_space(
      file_size + internal::kMinFreeSpace);

  // Store something of the file size in the temporary cache directory.
  const std::string content(file_size, 'x');
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath tmp_file =
      temp_dir.path().AppendASCII("something.txt");
  ASSERT_TRUE(google_apis::test_util::WriteStringToFile(tmp_file, content));

  FileError error = FILE_ERROR_FAILED;
  cache_->Store("<resource_id>", "<md5>", tmp_file,
                internal::FileCache::FILE_OPERATION_COPY,
                google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(CacheEntryExists("<resource_id>", "<md5>"));

  base::FilePath file_path;
  entry.reset();
  file_system_->GetFileByPath(file_in_root,
                              google_apis::test_util::CreateCopyResultCallback(
                                  &error, &file_path, &entry));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(entry);
  EXPECT_FALSE(entry->file_specific_info().is_hosted_document());

  // The cache entry should be removed in order to free up space.
  ASSERT_FALSE(CacheEntryExists("<resource_id>", "<md5>"));
}

TEST_F(DriveFileSystemTest, GetFileByPath_FromGData_EnoughSpaceButBecomeFull) {
  ASSERT_TRUE(LoadRootFeedDocument());

  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  scoped_ptr<ResourceEntry> entry(GetEntryInfoByPathSync(file_in_root));
  const int64 file_size = entry->file_info().size();

  // Pretend we have enough space first (checked before downloading a file),
  // but then start reporting we have not enough space. This is to emulate that
  // the disk space becomes full after the file is downloaded for some reason
  // (ex. the actual file was larger than the expected size).
  fake_free_disk_space_getter_->set_fake_free_disk_space(
      file_size + internal::kMinFreeSpace);
  fake_free_disk_space_getter_->set_fake_free_disk_space(
      internal::kMinFreeSpace - 1);
  fake_free_disk_space_getter_->set_fake_free_disk_space(
      internal::kMinFreeSpace - 1);

  FileError error = FILE_ERROR_OK;
  base::FilePath file_path;
  entry.reset();
  file_system_->GetFileByPath(file_in_root,
                              google_apis::test_util::CreateCopyResultCallback(
                                  &error, &file_path, &entry));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_NO_SPACE, error);
}

TEST_F(DriveFileSystemTest, GetFileByPath_FromCache) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  ASSERT_TRUE(LoadRootFeedDocument());

  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  scoped_ptr<ResourceEntry> entry(GetEntryInfoByPathSync(file_in_root));

  // Store something as cached version of this file.
  FileError error = FILE_ERROR_OK;
  cache_->Store(entry->resource_id(),
                entry->file_specific_info().file_md5(),
                google_apis::test_util::GetTestFilePath(
                    "chromeos/gdata/root_feed.json"),
                internal::FileCache::FILE_OPERATION_COPY,
                google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  base::FilePath file_path;
  entry.reset();
  file_system_->GetFileByPath(file_in_root,
                              google_apis::test_util::CreateCopyResultCallback(
                                  &error, &file_path, &entry));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(entry);
  EXPECT_FALSE(entry->file_specific_info().is_hosted_document());
}

TEST_F(DriveFileSystemTest, GetFileByPath_HostedDocument) {
  ASSERT_TRUE(LoadRootFeedDocument());

  base::FilePath file_in_root(FILE_PATH_LITERAL(
      "drive/root/Document 1 excludeDir-test.gdoc"));
  scoped_ptr<ResourceEntry> src_entry =
      GetEntryInfoByPathSync(file_in_root);
  ASSERT_TRUE(src_entry);

  FileError error = FILE_ERROR_FAILED;
  base::FilePath file_path;
  scoped_ptr<ResourceEntry> entry;
  file_system_->GetFileByPath(file_in_root,
                              google_apis::test_util::CreateCopyResultCallback(
                                  &error, &file_path, &entry));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(entry);
  EXPECT_TRUE(entry->file_specific_info().is_hosted_document());
  EXPECT_FALSE(file_path.empty());

  ASSERT_TRUE(src_entry);
  VerifyHostedDocumentJSONFile(*src_entry, file_path);
}

TEST_F(DriveFileSystemTest, GetFileByResourceId) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  // The transfered file is cached and the change of "offline available"
  // attribute is notified.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);

  ASSERT_TRUE(LoadRootFeedDocument());

  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  scoped_ptr<ResourceEntry> entry(GetEntryInfoByPathSync(file_in_root));
  std::string resource_id = entry->resource_id();

  FileError error = FILE_ERROR_OK;
  base::FilePath file_path;
  entry.reset();
  file_system_->GetFileByResourceId(
      resource_id,
      DriveClientContext(USER_INITIATED),
      google_apis::test_util::CreateCopyResultCallback(
          &error, &file_path, &entry),
      google_apis::GetContentCallback());
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(entry);
  EXPECT_FALSE(entry->file_specific_info().is_hosted_document());
}

TEST_F(DriveFileSystemTest, GetFileContentByPath) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  // The transfered file is cached and the change of "offline available"
  // attribute is notified.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);

  ASSERT_TRUE(LoadRootFeedDocument());

  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));

  {
    FileError initialized_error = FILE_ERROR_FAILED;
    scoped_ptr<ResourceEntry> entry;
    base::FilePath local_path;
    base::Closure cancel_download;

    std::vector<std::string> content_buffer;

    FileError completion_error = FILE_ERROR_FAILED;

    file_system_->GetFileContentByPath(
        file_in_root,
        google_apis::test_util::CreateCopyResultCallback(
            &initialized_error, &entry, &local_path, &cancel_download),
        base::Bind(&AppendContent, &content_buffer),
        google_apis::test_util::CreateCopyResultCallback(&completion_error));
    google_apis::test_util::RunBlockingPoolTask();

    // For the first time, file is downloaded from the remote server.
    // In this case, |local_path| is empty while |cancel_download| is not.
    EXPECT_EQ(FILE_ERROR_OK, initialized_error);
    ASSERT_TRUE(entry);
    ASSERT_TRUE(local_path.empty());
    EXPECT_TRUE(!cancel_download.is_null());
    // Content is available through the second callback arguemnt.
    size_t content_size = 0;
    for (size_t i = 0; i < content_buffer.size(); ++i) {
      content_size += content_buffer[i].size();
    }
    EXPECT_EQ(static_cast<size_t>(entry->file_info().size()),
              content_size);
    EXPECT_EQ(FILE_ERROR_OK, completion_error);
  }

  {
    FileError initialized_error = FILE_ERROR_FAILED;
    scoped_ptr<ResourceEntry> entry;
    base::FilePath local_path;
    base::Closure cancel_download;

    std::vector<std::string> content_buffer;

    FileError completion_error = FILE_ERROR_FAILED;

    file_system_->GetFileContentByPath(
        file_in_root,
        google_apis::test_util::CreateCopyResultCallback(
            &initialized_error, &entry, &local_path, &cancel_download),
        base::Bind(&AppendContent, &content_buffer),
        google_apis::test_util::CreateCopyResultCallback(&completion_error));
    google_apis::test_util::RunBlockingPoolTask();

    // Try second download. In this case, the file should be cached, so
    // |local_path| should not be empty while |cancel_download| is empty.
    EXPECT_EQ(FILE_ERROR_OK, initialized_error);
    ASSERT_TRUE(entry);
    ASSERT_TRUE(!local_path.empty());
    EXPECT_TRUE(cancel_download.is_null());
    // The content is available from the cache file.
    EXPECT_TRUE(content_buffer.empty());
    int64 local_file_size = 0;
    file_util::GetFileSize(local_path, &local_file_size);
    EXPECT_EQ(entry->file_info().size(), local_file_size);
    EXPECT_EQ(FILE_ERROR_OK, completion_error);
  }
}

TEST_F(DriveFileSystemTest, GetFileByResourceId_FromCache) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  ASSERT_TRUE(LoadRootFeedDocument());

  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  scoped_ptr<ResourceEntry> entry(GetEntryInfoByPathSync(file_in_root));

  // Store something as cached version of this file.
  FileError error = FILE_ERROR_FAILED;
  cache_->Store(entry->resource_id(),
                entry->file_specific_info().file_md5(),
                google_apis::test_util::GetTestFilePath(
                    "chromeos/gdata/root_feed.json"),
                internal::FileCache::FILE_OPERATION_COPY,
                google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // The file is obtained from the cache.
  // Hence the downloading should work even if the drive service is offline.
  fake_drive_service_->set_offline(true);

  std::string resource_id = entry->resource_id();
  base::FilePath file_path;
  entry.reset();
  file_system_->GetFileByResourceId(
      resource_id,
      DriveClientContext(USER_INITIATED),
      google_apis::test_util::CreateCopyResultCallback(
          &error, &file_path, &entry),
      google_apis::GetContentCallback());
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(entry);
  EXPECT_FALSE(entry->file_specific_info().is_hosted_document());
}

TEST_F(DriveFileSystemTest, UpdateFileByResourceId_PersistentFile) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);

  ASSERT_TRUE(LoadRootFeedDocument());

  // This is a file defined in root_feed.json.
  const base::FilePath kFilePath(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  const std::string kResourceId("file:2_file_resource_id");
  const std::string kMd5("3b4382ebefec6e743578c76bbd0575ce");

  // Pin the file so it'll be store in "persistent" directory.
  EXPECT_CALL(*mock_cache_observer_, OnCachePinned(kResourceId, kMd5)).Times(1);
  FileError error = FILE_ERROR_OK;
  cache_->Pin(kResourceId, kMd5,
              google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // First store a file to cache.
  cache_->Store(kResourceId,
                kMd5,
                // Anything works.
                google_apis::test_util::GetTestFilePath(
                    "chromeos/gdata/root_feed.json"),
                internal::FileCache::FILE_OPERATION_COPY,
                google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Add the dirty bit.
  cache_->MarkDirty(kResourceId, kMd5,
                    google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Commit the dirty bit.
  EXPECT_CALL(*mock_cache_observer_, OnCacheCommitted(kResourceId)).Times(1);
  cache_->CommitDirty(kResourceId, kMd5,
                      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // We'll notify the directory change to the observer upon completion.
  EXPECT_CALL(*mock_directory_observer_,
              OnDirectoryChanged(Eq(util::GetDriveMyDriveRootPath())))
      .Times(1);

  // Check the number of files in the root directory. We'll compare the
  // number after updating a file.
  scoped_ptr<ResourceEntryVector> root_directory_entries(
      ReadDirectoryByPathSync(base::FilePath::FromUTF8Unsafe("drive/root")));
  ASSERT_TRUE(root_directory_entries);
  const int num_files_in_root = CountFiles(*root_directory_entries);

  // The callback will be called upon completion of
  // UpdateFileByResourceId().
  file_system_->UpdateFileByResourceId(
      kResourceId,
      DriveClientContext(USER_INITIATED),
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Make sure that the number of files did not change (i.e. we updated an
  // existing file, rather than adding a new file. The number of files
  // increases if we don't handle the file update right).
  EXPECT_EQ(num_files_in_root, CountFiles(*root_directory_entries));
}

TEST_F(DriveFileSystemTest, UpdateFileByResourceId_NonexistentFile) {
  ASSERT_TRUE(LoadRootFeedDocument());

  // This is nonexistent in root_feed.json.
  const base::FilePath kFilePath(
      FILE_PATH_LITERAL("drive/root/Nonexistent.txt"));
  const std::string kResourceId("file:nonexistent_resource_id");
  const std::string kMd5("nonexistent_md5");

  // The callback will be called upon completion of
  // UpdateFileByResourceId().
  FileError error = FILE_ERROR_OK;
  file_system_->UpdateFileByResourceId(
      kResourceId,
      DriveClientContext(USER_INITIATED),
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, error);
}

TEST_F(DriveFileSystemTest, ContentSearch) {
  ASSERT_TRUE(LoadRootFeedDocument());

  const SearchResultPair kExpectedResults[] = {
    { "drive/root/Directory 1/Sub Directory Folder/Sub Sub Directory Folder",
      true },
    { "drive/root/Directory 1/Sub Directory Folder", true },
    { "drive/root/Directory 1/SubDirectory File 1.txt", false },
    { "drive/root/Directory 1", true },
    { "drive/root/Directory 2 excludeDir-test", true },
  };

  SearchCallback callback = base::Bind(
      &DriveSearchCallback,
      &message_loop_,
      kExpectedResults, ARRAYSIZE_UNSAFE(kExpectedResults),
      GURL());

  file_system_->Search("Directory", GURL(), callback);
  message_loop_.Run();  // Wait to get our result.
}

TEST_F(DriveFileSystemTest, ContentSearchWithNewEntry) {
  ASSERT_TRUE(LoadRootFeedDocument());

  // Create a new directory in the drive service.
  google_apis::GDataErrorCode error = google_apis::GDATA_OTHER_ERROR;
  scoped_ptr<google_apis::ResourceEntry> resource_entry;
  fake_drive_service_->AddNewDirectory(
      fake_drive_service_->GetRootResourceId(),  // Add to the root directory.
      "New Directory 1!",
      google_apis::test_util::CreateCopyResultCallback(
          &error, &resource_entry));
  message_loop_.RunUntilIdle();

  // As the result of the first Search(), only entries in the current file
  // system snapshot are expected to be returned (i.e. "New Directory 1!"
  // shouldn't be included in the search result even though it matches
  // "Directory 1".
  const SearchResultPair kExpectedResults[] = {
    { "drive/root/Directory 1", true }
  };

  // At the same time, unknown entry should trigger delta feed request.
  // This will cause notification to directory observers (e.g., File Browser)
  // so that they can request search again.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(_))
      .Times(AtLeast(1));

  SearchCallback callback = base::Bind(
      &DriveSearchCallback,
      &message_loop_,
      kExpectedResults, ARRAYSIZE_UNSAFE(kExpectedResults),
      GURL());

  file_system_->Search("\"Directory 1\"", GURL(), callback);
  // Make sure all the delayed tasks to complete.
  // message_loop_.Run() can return before the delta feed processing finishes.
  google_apis::test_util::RunBlockingPoolTask();
}

TEST_F(DriveFileSystemTest, ContentSearchEmptyResult) {
  ASSERT_TRUE(LoadRootFeedDocument());

  const SearchResultPair* expected_results = NULL;

  SearchCallback callback = base::Bind(
      &DriveSearchCallback,
      &message_loop_,
      expected_results,
      0u,
      GURL());

  file_system_->Search("\"no-match query\"", GURL(), callback);
  message_loop_.Run();  // Wait to get our result.
}

TEST_F(DriveFileSystemTest, GetAvailableSpace) {
  FileError error = FILE_ERROR_OK;
  int64 bytes_total;
  int64 bytes_used;
  file_system_->GetAvailableSpace(
      google_apis::test_util::CreateCopyResultCallback(
          &error, &bytes_total, &bytes_used));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(GG_LONGLONG(6789012345), bytes_used);
  EXPECT_EQ(GG_LONGLONG(9876543210), bytes_total);
}

TEST_F(DriveFileSystemTest, RefreshDirectory) {
  ASSERT_TRUE(LoadRootFeedDocument());

  // We'll notify the directory change to the observer.
  EXPECT_CALL(*mock_directory_observer_,
              OnDirectoryChanged(Eq(util::GetDriveMyDriveRootPath()))).Times(1);

  FileError error = FILE_ERROR_FAILED;
  file_system_->RefreshDirectory(
      util::GetDriveMyDriveRootPath(),
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);
}

TEST_F(DriveFileSystemTest, OpenAndCloseFile) {
  ASSERT_TRUE(LoadRootFeedDocument());

  // The transfered file is cached and the change of "offline available"
  // attribute is notified.
  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(base::FilePath(FILE_PATH_LITERAL("drive/root"))))).Times(1);

  const base::FilePath kFileInRoot(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  scoped_ptr<ResourceEntry> entry(GetEntryInfoByPathSync(kFileInRoot));
  const int64 file_size = entry->file_info().size();
  const std::string& file_resource_id =
      entry->resource_id();
  const std::string& file_md5 = entry->file_specific_info().file_md5();

  // A dirty file is created on close.
  EXPECT_CALL(*mock_cache_observer_, OnCacheCommitted(file_resource_id))
      .Times(1);

  // Pretend we have enough space.
  fake_free_disk_space_getter_->set_fake_free_disk_space(
      file_size + internal::kMinFreeSpace);

  // Open kFileInRoot ("drive/root/File 1.txt").
  FileError error = FILE_ERROR_FAILED;
  base::FilePath file_path;
  file_system_->OpenFile(
      kFileInRoot,
      google_apis::test_util::CreateCopyResultCallback(&error, &file_path));
  google_apis::test_util::RunBlockingPoolTask();
  const base::FilePath opened_file_path = file_path;

  // Verify that the file was properly opened.
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Try to open the already opened file.
  file_system_->OpenFile(
      kFileInRoot,
      google_apis::test_util::CreateCopyResultCallback(&error, &file_path));
  google_apis::test_util::RunBlockingPoolTask();

  // It must fail.
  EXPECT_EQ(FILE_ERROR_IN_USE, error);

  // Verify that the file contents match the expected contents.
  // The content is "x"s of the file size.
  const std::string kExpectedContent = "xxxxxxxxxx";
  std::string cache_file_data;
  EXPECT_TRUE(file_util::ReadFileToString(opened_file_path, &cache_file_data));
  EXPECT_EQ(kExpectedContent, cache_file_data);

  FileCacheEntry cache_entry;
  EXPECT_TRUE(GetCacheEntryFromOriginThread(file_resource_id, file_md5,
                                            &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());
  EXPECT_TRUE(cache_entry.is_dirty());
  EXPECT_TRUE(cache_entry.is_persistent());

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

  // Close kFileInRoot ("drive/root/File 1.txt").
  file_system_->CloseFile(
      kFileInRoot,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();

  // Verify that the file was properly closed.
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Verify that the cache state was changed as expected.
  EXPECT_TRUE(GetCacheEntryFromOriginThread(file_resource_id, file_md5,
                                            &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());
  EXPECT_TRUE(cache_entry.is_dirty());
  EXPECT_TRUE(cache_entry.is_persistent());

  // Try to close the same file twice.
  file_system_->CloseFile(
      kFileInRoot,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();

  // It must fail.
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, error);
}

// TODO(satorux): Testing if WebAppsRegistry is loaded here is awkward. We
// should move this to change_list_loader_unittest.cc. crbug.com/161703
TEST_F(DriveFileSystemTest, WebAppsRegistryIsLoaded) {
  ASSERT_TRUE(SetUpTestFileSystem(USE_SERVER_TIMESTAMP));

  // No apps should be found as the webapps registry is empty.
  ScopedVector<DriveWebAppInfo> apps;
  drive_webapps_registry_->GetWebAppsForFile(
      base::FilePath::FromUTF8Unsafe("foo.exe"),
      "" /* mime_type */,
      &apps);
  EXPECT_TRUE(apps.empty());

  // Kicks loading of cached file system and query for server update. This
  // will cause GetAccountMetadata() to be called, to check the server-side
  // changestamp, and the webapps registry will be loaded at the same time.
  EXPECT_TRUE(ReadDirectoryByPathSync(util::GetDriveMyDriveRootPath()));

  // An app for foo.exe should now be found, as the registry was loaded.
  drive_webapps_registry_->GetWebAppsForFile(
      base::FilePath(FILE_PATH_LITERAL("foo.exe")),
      "" /* mime_type */,
      &apps);
  EXPECT_EQ(1U, apps.size());
}

TEST_F(DriveFileSystemTest, MarkCacheFileAsMountedAndUnmounted) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);
  ASSERT_TRUE(LoadRootFeedDocument());

  base::FilePath file_in_root(FILE_PATH_LITERAL("drive/root/File 1.txt"));
  scoped_ptr<ResourceEntry> entry(GetEntryInfoByPathSync(file_in_root));
  ASSERT_TRUE(entry);

  // Write to cache.
  FileError error = FILE_ERROR_FAILED;
  cache_->Store(entry->resource_id(),
                entry->file_specific_info().file_md5(),
                google_apis::test_util::GetTestFilePath(
                    "chromeos/gdata/root_feed.json"),
                internal::FileCache::FILE_OPERATION_COPY,
                google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  ASSERT_EQ(FILE_ERROR_OK, error);

  // Test for mounting.
  base::FilePath file_path;
  file_system_->MarkCacheFileAsMounted(
      file_in_root,
      google_apis::test_util::CreateCopyResultCallback(&error, &file_path));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  bool success = false;
  FileCacheEntry cache_entry;
  cache_->GetCacheEntry(
      entry->resource_id(),
      entry->file_specific_info().file_md5(),
      google_apis::test_util::CreateCopyResultCallback(&success, &cache_entry));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_TRUE(success);
  EXPECT_TRUE(cache_entry.is_mounted());

  // Test for unmounting.
  error = FILE_ERROR_FAILED;
  file_system_->MarkCacheFileAsUnmounted(
      file_path,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_EQ(FILE_ERROR_OK, error);

  success = false;
  cache_->GetCacheEntry(
      entry->resource_id(),
      entry->file_specific_info().file_md5(),
      google_apis::test_util::CreateCopyResultCallback(&success, &cache_entry));
  google_apis::test_util::RunBlockingPoolTask();

  EXPECT_TRUE(success);
  EXPECT_FALSE(cache_entry.is_mounted());
}

// TODO(kinaba): crbug.com/237066
// Create and move to file_system/create create_file_operation_unittest.cc.
TEST_F(DriveFileSystemTest, CreateFile) {
  fake_free_disk_space_getter_->set_fake_free_disk_space(kLotsOfSpace);
  ASSERT_TRUE(LoadRootFeedDocument());

  const base::FilePath kExistingFile(
      FILE_PATH_LITERAL("drive/root/File 1.txt"));
  const base::FilePath kExistingDirectory(
      FILE_PATH_LITERAL("drive/root/Directory 1"));
  const base::FilePath kNonExistingFile(
      FILE_PATH_LITERAL("drive/root/Directory 1/not exist.png"));
  const base::FilePath kFileInNonExistingDirectory(
      FILE_PATH_LITERAL("drive/root/not exist/not exist.png"));

  EXPECT_CALL(*mock_directory_observer_, OnDirectoryChanged(
      Eq(kNonExistingFile.DirName()))).Times(1);

  // Create fails if is_exclusive = true and a file exists.
  FileError error = FILE_ERROR_FAILED;
  file_system_->CreateFile(
      kExistingFile,
      true /* is_exclusive */,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_EXISTS, error);

  // Create succeeds if is_exclusive = false and a file exists.
  file_system_->CreateFile(
      kExistingFile,
      false /* is_exclusive */,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Create fails if a directory existed even when is_exclusive = false.
  file_system_->CreateFile(
      kExistingDirectory,
      false /* is_exclusive */,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_EXISTS, error);

  // Create succeeds if no entry exists.
  file_system_->CreateFile(
      kNonExistingFile,
      true /* is_exclusive */,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_OK, error);

  // Create fails if the parent directory does not exist.
  file_system_->CreateFile(
      kFileInNonExistingDirectory, false,
      google_apis::test_util::CreateCopyResultCallback(&error));
  google_apis::test_util::RunBlockingPoolTask();
  EXPECT_EQ(FILE_ERROR_NOT_A_DIRECTORY, error);
}

}   // namespace drive