File: drive_integration_service_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (810 lines) | stat: -rw-r--r-- 31,222 bytes parent folder | download | duplicates (3)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/drive/drive_integration_service.h"

#include <memory>
#include <optional>
#include <vector>

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_switches.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "chrome/browser/ash/drive/drive_integration_service_browser_test_base.h"
#include "chrome/browser/ash/drive/drive_integration_service_factory.h"
#include "chrome/browser/ash/file_manager/path_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chromeos/ash/components/drivefs/drivefs_search_query.h"
#include "chromeos/ash/components/drivefs/fake_drivefs.h"
#include "chromeos/ash/components/drivefs/mojom/drivefs.mojom.h"
#include "chromeos/components/drivefs/mojom/drivefs_native_messaging.mojom.h"
#include "components/drive/drive_pref_names.h"
#include "components/drive/file_errors.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/pref_test_utils.h"
#include "content/public/test/browser_test.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "storage/browser/file_system/external_mount_points.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace drive {

using ::base::test::RunClosure;
using ::base::test::RunOnceCallback;
using ::base::test::TestFuture;
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::Field;
using ::testing::FieldsAre;
using ::testing::Optional;
using ::testing::Pointee;
using ::testing::Property;

using DriveIntegrationServiceBrowserTest =
    DriveIntegrationServiceBrowserTestBase;

// Verify DriveIntegrationService is created during login.
IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceBrowserTest, CreatedDuringLogin) {
  EXPECT_TRUE(
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile()));
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceBrowserTest,
                       ClearCacheAndRemountFileSystem) {
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());
  base::FilePath cache_path = drive_service->GetDriveFsHost()->GetDataPath();
  base::FilePath log_folder_path = drive_service->GetDriveFsLogPath().DirName();
  base::FilePath cache_file;
  base::FilePath log_file;

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    ASSERT_TRUE(base::CreateDirectory(cache_path));
    ASSERT_TRUE(base::CreateDirectory(log_folder_path));
    ASSERT_TRUE(base::CreateTemporaryFileInDir(cache_path, &cache_file));
    ASSERT_TRUE(base::CreateTemporaryFileInDir(log_folder_path, &log_file));
  }

  base::RunLoop run_loop;
  auto quit_closure = run_loop.QuitClosure();
  drive_service->ClearCacheAndRemountFileSystem(
      base::BindLambdaForTesting([=](bool success) {
        base::ScopedAllowBlockingForTesting allow_blocking;
        EXPECT_TRUE(success);
        EXPECT_FALSE(base::PathExists(cache_file));
        EXPECT_TRUE(base::PathExists(log_file));
        quit_closure.Run();
      }));

  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceBrowserTest,
                       DisableDrivePolicyTest) {
  // First make sure the pref is set to its default value which should permit
  // drive.
  browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableDrive, false);

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::FindForProfile(
          browser()->profile());

  EXPECT_TRUE(integration_service);
  EXPECT_TRUE(integration_service->is_enabled());

  // ...next try to disable drive.
  browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableDrive, true);

  EXPECT_EQ(integration_service,
            drive::DriveIntegrationServiceFactory::FindForProfile(
                browser()->profile()));
  EXPECT_FALSE(integration_service->is_enabled());
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceBrowserTest,
                       SearchDriveByFileNameTest) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  drive::DriveIntegrationService* drive_service =
      drive::DriveIntegrationServiceFactory::FindForProfile(
          browser()->profile());

  base::FilePath mount_path = drive_service->GetMountPointPath();
  ASSERT_TRUE(base::WriteFile(mount_path.Append("bar"), ""));
  ASSERT_TRUE(base::WriteFile(mount_path.Append("baz"), ""));
  auto base_time = base::Time::Now() - base::Seconds(10);
  auto earlier_time = base_time - base::Seconds(10);
  ASSERT_TRUE(base::TouchFile(mount_path.Append("bar"), base_time, base_time));
  ASSERT_TRUE(
      base::TouchFile(mount_path.Append("baz"), earlier_time, earlier_time));

  base::RunLoop run_loop;
  auto quit_closure = run_loop.QuitClosure();
  drive_service->SearchDriveByFileName(
      "ba", 10, drivefs::mojom::QueryParameters::SortField::kLastViewedByMe,
      drivefs::mojom::QueryParameters::SortDirection::kAscending,
      drivefs::mojom::QueryParameters::QuerySource::kLocalOnly,
      base::BindLambdaForTesting(
          [=](FileError error,
              std::optional<std::vector<drivefs::mojom::QueryItemPtr>> items) {
            EXPECT_THAT(
                items,
                Optional(ElementsAre(
                    Pointee(Field(
                        "path", &drivefs::mojom::QueryItem::path,
                        Property(
                            "BaseName", &base::FilePath::BaseName,
                            Property("value", &base::FilePath::value, "baz")))),
                    Pointee(
                        Field("path", &drivefs::mojom::QueryItem::path,
                              Property("BaseName", &base::FilePath::BaseName,
                                       Property("value", &base::FilePath::value,
                                                "bar")))))));
            quit_closure.Run();
          }));
  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceBrowserTest,
                       CreateSearchQueryByFileNameTest) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  drive::DriveIntegrationService* drive_service =
      drive::DriveIntegrationServiceFactory::FindForProfile(
          browser()->profile());

  base::FilePath mount_path = drive_service->GetMountPointPath();
  ASSERT_TRUE(base::WriteFile(mount_path.Append("bar"), ""));
  ASSERT_TRUE(base::WriteFile(mount_path.Append("baz"), ""));
  base::Time base_time = base::Time::Now() - base::Seconds(10);
  base::Time earlier_time = base_time - base::Seconds(10);
  ASSERT_TRUE(base::TouchFile(mount_path.Append("bar"), base_time, base_time));
  ASSERT_TRUE(
      base::TouchFile(mount_path.Append("baz"), earlier_time, earlier_time));

  std::unique_ptr<drivefs::DriveFsSearchQuery> query =
      drive_service->CreateSearchQueryByFileName(
          "ba", 10, drivefs::mojom::QueryParameters::SortField::kLastViewedByMe,
          drivefs::mojom::QueryParameters::SortDirection::kAscending,
          drivefs::mojom::QueryParameters::QuerySource::kLocalOnly);
  ASSERT_TRUE(query);

  base::test::TestFuture<
      FileError, std::optional<std::vector<drivefs::mojom::QueryItemPtr>>>
      future;
  query->GetNextPage(future.GetCallback());

  EXPECT_THAT(
      future.Take(),
      FieldsAre(
          FILE_ERROR_OK,
          Optional(ElementsAre(
              Pointee(Field(
                  "path", &drivefs::mojom::QueryItem::path,
                  Property("BaseName", &base::FilePath::BaseName,
                           Property("value", &base::FilePath::value, "baz")))),
              Pointee(Field("path", &drivefs::mojom::QueryItem::path,
                            Property("BaseName", &base::FilePath::BaseName,
                                     Property("value", &base::FilePath::value,
                                              "bar"))))))));
  // TODO: b/277018122 - Fix repeated `GetNextPage` calls in
  // `drivefs::FakeDriveFs` and call `GetNextPage` again here with a smaller
  // page size.
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceBrowserTest, GetThumbnailTest) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  drive::DriveIntegrationService* drive_service =
      drive::DriveIntegrationServiceFactory::FindForProfile(
          browser()->profile());

  base::FilePath mount_path = drive_service->GetMountPointPath();
  ASSERT_TRUE(base::WriteFile(mount_path.Append("bar"), ""));

  base::RunLoop run_loop;
  auto quit_closure = run_loop.QuitClosure();
  drive_service->GetThumbnail(
      base::FilePath("/bar"), true,
      base::BindLambdaForTesting(
          [=](const std::optional<std::vector<uint8_t>>& image) {
            ASSERT_FALSE(image.has_value());
            quit_closure.Run();
          }));
  run_loop.Run();
}

class DriveIntegrationServiceWithGaiaDisabledBrowserTest
    : public DriveIntegrationServiceBrowserTest {
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(ash::switches::kDisableGaiaServices);
  }
};

IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceWithGaiaDisabledBrowserTest,
                       DriveDisabled) {
  // First make sure the pref is set to its default value which would normally
  // permit drive.
  browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableDrive, false);

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::FindForProfile(
          browser()->profile());

  ASSERT_TRUE(integration_service);
  EXPECT_FALSE(integration_service->is_enabled());
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceBrowserTest, GetMetadata) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());

  base::FilePath mount_path = drive_service->GetMountPointPath();
  base::FilePath file_path;
  base::CreateTemporaryFileInDir(mount_path, &file_path);

  {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    drive_service->GetMetadata(
        base::FilePath("/foo/bar"),
        base::BindLambdaForTesting(
            [=](FileError error, drivefs::mojom::FileMetadataPtr metadata_ptr) {
              EXPECT_EQ(FILE_ERROR_NOT_FOUND, error);
              quit_closure.Run();
            }));
    run_loop.Run();
  }

  {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    drive_service->GetMetadata(
        file_path,
        base::BindLambdaForTesting(
            [=](FileError error, drivefs::mojom::FileMetadataPtr metadata_ptr) {
              EXPECT_EQ(FILE_ERROR_OK, error);
              quit_closure.Run();
            }));
    run_loop.Run();
  }
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceBrowserTest,
                       LocateFilesByItemIds) {
  Profile* profile = browser()->profile();
  InitTestFileMountRoot(profile);
  AddDriveFileWithRelativePath(profile, /*drive_file_id=*/"abc123",
                               /*directory_path=*/base::FilePath(""),
                               /*new_file_relative_path=*/nullptr,
                               /*new_file_absolute_path=*/nullptr);
  base::FilePath relative_file_path;
  AddDriveFileWithRelativePath(profile, /*drive_file_id=*/"qwertyqwerty",
                               /*directory_path=*/base::FilePath("aa"),
                               &relative_file_path,
                               /*new_file_absolute_path=*/nullptr);
  {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    DriveIntegrationServiceFactory::FindForProfile(profile)
        ->LocateFilesByItemIds(
            {"qwertyqwerty", "foobar"},
            base::BindLambdaForTesting(
                [=](std::optional<
                    std::vector<drivefs::mojom::FilePathOrErrorPtr>> result) {
                  ASSERT_EQ(2u, result->size());
                  EXPECT_EQ(relative_file_path, base::FilePath("/").Append(
                                                    result->at(0)->get_path()));
                  EXPECT_EQ(FILE_ERROR_NOT_FOUND, result->at(1)->get_error());
                  quit_closure.Run();
                }));
    run_loop.Run();
  }
}

class DriveIntegrationServiceWithPrefDisabledBrowserTest
    : public DriveIntegrationServiceBrowserTest {
  drive::DriveIntegrationService* CreateDriveIntegrationService(
      Profile* profile) override {
    profile->GetPrefs()->SetBoolean(prefs::kDisableDrive, true);
    return DriveIntegrationServiceBrowserTest::CreateDriveIntegrationService(
        profile);
  }
};

IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceWithPrefDisabledBrowserTest,
                       RenableAndDisableDrive) {
  auto* profile = browser()->profile();
  auto* drive_service = DriveIntegrationServiceFactory::FindForProfile(profile);
  EXPECT_FALSE(drive_service->is_enabled());

  profile->GetPrefs()->SetBoolean(prefs::kDisableDrive, false);
  EXPECT_TRUE(drive_service->is_enabled());

  profile->GetPrefs()->SetBoolean(prefs::kDisableDrive, true);
  EXPECT_FALSE(drive_service->is_enabled());
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationServiceBrowserTest,
                       EnableMirrorSync_FeatureDisabled) {
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());

  {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    drive_service->ToggleMirroring(
        /*enabled=*/true,
        base::BindLambdaForTesting(
            [quit_closure](drivefs::mojom::MirrorSyncStatus status) {
              EXPECT_EQ(drivefs::mojom::MirrorSyncStatus::kFeatureNotEnabled,
                        status);
              quit_closure.Run();
            }));
    run_loop.Run();
  }

  {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    drive_service->ToggleMirroring(
        /*enabled=*/false,
        base::BindLambdaForTesting(
            [quit_closure](drivefs::mojom::MirrorSyncStatus status) {
              EXPECT_EQ(drivefs::mojom::MirrorSyncStatus::kFeatureNotEnabled,
                        status);
              quit_closure.Run();
            }));
    run_loop.Run();
  }
}

class DriveMirrorSyncStatusObserver : public DriveIntegrationService::Observer {
 public:
  explicit DriveMirrorSyncStatusObserver(bool expected_status)
      : expected_status_(expected_status) {
    quit_closure_ = run_loop_.QuitClosure();
  }

  void WaitForStatusChange() { run_loop_.Run(); }

  void OnMirroringEnabled() override {
    quit_closure_.Run();
    EXPECT_TRUE(expected_status_);
  }

  void OnMirroringDisabled() override {
    quit_closure_.Run();
    EXPECT_FALSE(expected_status_);
  }

 private:
  base::RunLoop run_loop_;
  base::RepeatingClosure quit_closure_;
  bool expected_status_ = false;
};

class DriveIntegrationBrowserTestWithMirrorSyncEnabled
    : public DriveIntegrationServiceBrowserTest {
 public:
  DriveIntegrationBrowserTestWithMirrorSyncEnabled() {
    scoped_feature_list_.InitWithFeatures({ash::features::kDriveFsMirroring},
                                          {});
  }

  DriveIntegrationBrowserTestWithMirrorSyncEnabled(
      const DriveIntegrationBrowserTestWithMirrorSyncEnabled&) = delete;
  DriveIntegrationBrowserTestWithMirrorSyncEnabled& operator=(
      const DriveIntegrationBrowserTestWithMirrorSyncEnabled&) = delete;

  ~DriveIntegrationBrowserTestWithMirrorSyncEnabled() override = default;

  void SetUpOnMainThread() override { MockGetSyncingPaths(); }

  void ToggleMirrorSync(bool status, bool expect_fail = false) {
    DriveMirrorSyncStatusObserver observer(expect_fail ? !status : status);
    Profile* const profile = browser()->profile();
    observer.Observe(DriveIntegrationServiceFactory::FindForProfile(profile));
    PrefService* const prefs = profile->GetPrefs();
    prefs->SetBoolean(prefs::kDriveFsEnableMirrorSync, status);
    observer.WaitForStatusChange();
    EXPECT_EQ(prefs->GetBoolean(prefs::kDriveFsEnableMirrorSync),
              expect_fail ? !status : status);
  }

  void MockGetSyncingPaths() {
    drivefs::FakeDriveFs* fake_drivefs =
        GetFakeDriveFsForProfile(browser()->profile());
    ON_CALL(*fake_drivefs, GetSyncingPaths(_))
        .WillByDefault(testing::Invoke(
            fake_drivefs, &drivefs::FakeDriveFs::GetSyncingPathsForTesting));
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

class DriveIntegrationBrowserTestWithBulkPinningEnabled
    : public DriveIntegrationServiceBrowserTest {
 public:
  DriveIntegrationBrowserTestWithBulkPinningEnabled() {
    scoped_feature_list_.InitWithFeatures(
        {ash::features::kFeatureManagementDriveFsBulkPinning}, {});
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithMirrorSyncEnabled,
                       EnableMirrorSync) {
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());

  // Ensure the mirror syncing service is disabled.
  EXPECT_FALSE(browser()->profile()->GetPrefs()->GetBoolean(
      prefs::kDriveFsEnableMirrorSync));
  EXPECT_FALSE(drive_service->IsMirroringEnabled());

  // Enable mirroring and ensure the integration service has it enabled.
  ToggleMirrorSync(true);
  EXPECT_TRUE(drive_service->IsMirroringEnabled());

  // Check MyFiles is being added as sync path.
  TestFuture<drive::FileError, const std::vector<base::FilePath>&> future;
  const base::FilePath my_files_path =
      file_manager::util::GetMyFilesFolderForProfile(browser()->profile());

  drive_service->GetSyncingPaths(future.GetCallback());

  EXPECT_EQ(future.Get<0>(), drive::FILE_ERROR_OK);
  EXPECT_THAT(future.Get<1>(), testing::ElementsAre(my_files_path));
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithMirrorSyncEnabled,
                       EnableMirrorSyncWithNonExistMyFiles) {
  Profile* profile = browser()->profile();
  auto* drive_service = DriveIntegrationServiceFactory::FindForProfile(profile);

  // Replace MyFiles mount point to something not exist.
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::ScopedTempDir temp_dir;
  EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath my_files_dir = temp_dir.GetPath().Append("NotExist");
  storage::ExternalMountPoints::GetSystemInstance()->RevokeAllFileSystems();
  storage::ExternalMountPoints::GetSystemInstance()->RegisterFileSystem(
      file_manager::util::GetDownloadsMountPointName(profile),
      storage::kFileSystemTypeLocal, storage::FileSystemMountOption(),
      my_files_dir);

  // Enable mirroring with non existed MyFiles won't turn the sync on.
  ToggleMirrorSync(true, true);
  EXPECT_FALSE(drive_service->IsMirroringEnabled());

  // Check nothing is added as sync path.
  drivefs::FakeDriveFs* fake_drivefs = GetFakeDriveFsForProfile(profile);
  TestFuture<drive::FileError, const std::vector<base::FilePath>&> future;
  fake_drivefs->GetSyncingPathsForTesting(future.GetCallback());

  EXPECT_THAT(future.Get<1>(), testing::IsEmpty());
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithMirrorSyncEnabled,
                       DisableMirrorSync) {
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());

  // Ensure the mirror syncing service is disabled.
  EXPECT_FALSE(browser()->profile()->GetPrefs()->GetBoolean(
      prefs::kDriveFsEnableMirrorSync));
  EXPECT_FALSE(drive_service->IsMirroringEnabled());

  // Enable mirror syncing.
  TestFuture<drive::FileError, const std::vector<base::FilePath>&> future;
  ToggleMirrorSync(true);
  EXPECT_TRUE(drive_service->IsMirroringEnabled());
  drive_service->GetSyncingPaths(future.GetCallback());
  const base::FilePath my_files_path =
      file_manager::util::GetMyFilesFolderForProfile(browser()->profile());
  EXPECT_THAT(future.Get<1>(), testing::ElementsAre(my_files_path));

  // Disable mirroring and ensure the integration service has it disabled.
  ToggleMirrorSync(false);
  EXPECT_FALSE(drive_service->IsMirroringEnabled());
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithMirrorSyncEnabled,
                       ToggleSyncForPath_MirroringDisabled) {
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());

  {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    drive_service->ToggleSyncForPath(
        base::FilePath("/fake/path"), drivefs::mojom::MirrorPathStatus::kStart,
        base::BindLambdaForTesting([quit_closure](FileError status) {
          EXPECT_EQ(FILE_ERROR_SERVICE_UNAVAILABLE, status);
          quit_closure.Run();
        }));
    run_loop.Run();
  }
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithMirrorSyncEnabled,
                       ToggleSyncForPath_MirroringEnabledFileNotFound) {
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());

  // Enable mirror sync.
  ToggleMirrorSync(true);

  {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    drive_service->ToggleSyncForPath(
        base::FilePath("/fake/path"), drivefs::mojom::MirrorPathStatus::kStart,
        base::BindLambdaForTesting([quit_closure](FileError status) {
          EXPECT_EQ(FILE_ERROR_NOT_FOUND, status);
          quit_closure.Run();
        }));
    run_loop.Run();
  }
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithMirrorSyncEnabled,
                       ToggleSyncForPath_MirroringEnabled) {
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());

  // Enable mirror sync.
  ToggleMirrorSync(true);

  base::ScopedTempDir temp_dir;
  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
  }

  {
    base::FilePath sync_path = temp_dir.GetPath();
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    drive_service->ToggleSyncForPath(
        sync_path, drivefs::mojom::MirrorPathStatus::kStart,
        base::BindLambdaForTesting([quit_closure](FileError status) {
          EXPECT_EQ(FILE_ERROR_OK, status);
          quit_closure.Run();
        }));
    run_loop.Run();
  }

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    EXPECT_TRUE(temp_dir.Delete());
  }
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithMirrorSyncEnabled,
                       ToggleSyncForPath_MirroringEnabledAddSamePath) {
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());

  // Enable mirror sync.
  ToggleMirrorSync(true);

  base::ScopedTempDir temp_dir;
  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
  }

  {
    base::FilePath sync_path = temp_dir.GetPath();
    TestFuture<drive::FileError> toggle_sync_future;
    drive_service->ToggleSyncForPath(sync_path,
                                     drivefs::mojom::MirrorPathStatus::kStart,
                                     toggle_sync_future.GetCallback());
    EXPECT_EQ(toggle_sync_future.Get(), drive::FILE_ERROR_OK);

    // GetSyncingPath should have 2 paths: "MyFiles" and the above sync path.
    TestFuture<drive::FileError, const std::vector<base::FilePath>&>
        get_syncing_paths_future;
    drive_service->GetSyncingPaths(get_syncing_paths_future.GetCallback());
    EXPECT_EQ(get_syncing_paths_future.Get<0>(), drive::FILE_ERROR_OK);
    EXPECT_EQ(get_syncing_paths_future.Get<1>().size(), 2u);

    // Toggle sync for the same path again.
    TestFuture<drive::FileError> toggle_sync_same_path_future;
    drive_service->ToggleSyncForPath(
        sync_path, drivefs::mojom::MirrorPathStatus::kStart,
        toggle_sync_same_path_future.GetCallback());
    EXPECT_EQ(toggle_sync_same_path_future.Get(), drive::FILE_ERROR_OK);

    // GetSyncingPath should still have 2 paths because it ignores the duplicate
    // path.
    TestFuture<drive::FileError, const std::vector<base::FilePath>&>
        get_syncing_paths_again_future;
    drive_service->GetSyncingPaths(
        get_syncing_paths_again_future.GetCallback());
    EXPECT_EQ(get_syncing_paths_again_future.Get<0>(), drive::FILE_ERROR_OK);
    EXPECT_EQ(get_syncing_paths_again_future.Get<1>().size(), 2u);
  }

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    EXPECT_TRUE(temp_dir.Delete());
  }
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithMirrorSyncEnabled,
                       GetSyncingPaths_MirroringDisabled) {
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());

  {
    base::RunLoop run_loop;
    auto quit_closure = run_loop.QuitClosure();
    drive_service->GetSyncingPaths(base::BindLambdaForTesting(
        [quit_closure](drive::FileError status,
                       const std::vector<base::FilePath>& paths) {
          EXPECT_EQ(drive::FILE_ERROR_SERVICE_UNAVAILABLE, status);
          EXPECT_EQ(0u, paths.size());
          quit_closure.Run();
        }));
    run_loop.Run();
  }
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithMirrorSyncEnabled,
                       GetSyncingPaths_MirroringEnabled) {
  auto* drive_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());

  // Enable mirror sync and add |sync_path| that we expect to return from
  // |GetSyncingPaths|.
  ToggleMirrorSync(true);

  base::ScopedTempDir temp_dir;
  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
  }

  {
    TestFuture<drive::FileError> toggle_sync_future;
    base::FilePath sync_path = temp_dir.GetPath();
    drive_service->ToggleSyncForPath(sync_path,
                                     drivefs::mojom::MirrorPathStatus::kStart,
                                     toggle_sync_future.GetCallback());
    EXPECT_EQ(toggle_sync_future.Get(), drive::FILE_ERROR_OK);

    TestFuture<drive::FileError, const std::vector<base::FilePath>&>
        get_syncing_paths_future;
    drive_service->GetSyncingPaths(get_syncing_paths_future.GetCallback());
    const base::FilePath my_files_path =
        file_manager::util::GetMyFilesFolderForProfile(browser()->profile());
    EXPECT_EQ(get_syncing_paths_future.Get<0>(), drive::FILE_ERROR_OK);
    EXPECT_THAT(get_syncing_paths_future.Get<1>(),
                testing::ElementsAre(my_files_path, sync_path));
  }

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    EXPECT_TRUE(temp_dir.Delete());
  }
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithMirrorSyncEnabled,
                       MachineRootIDPersistedAndAvailable) {
  ToggleMirrorSync(true);

  // Ensure the initial machine root ID is unset.
  EXPECT_EQ(browser()->profile()->GetPrefs()->GetString(
                prefs::kDriveFsMirrorSyncMachineRootId),
            "");

  // Invoke the delegate method to persist the machine root ID and wait for the
  // prefs key to change to the expected value.
  drivefs::FakeDriveFs* fake = GetFakeDriveFsForProfile(browser()->profile());
  fake->delegate()->PersistMachineRootID("test-machine-id");
  WaitForPrefValue(browser()->profile()->GetPrefs(),
                   prefs::kDriveFsMirrorSyncMachineRootId,
                   base::Value("test-machine-id"));

  // Setup the callback for the GetMachineRootID method to assert it gets run
  // with the "test-machine-id".
  base::RunLoop run_loop;
  base::MockOnceCallback<void(const std::string&)> machine_root_id_callback;
  EXPECT_CALL(machine_root_id_callback, Run("test-machine-id"))
      .WillOnce(RunClosure(run_loop.QuitClosure()));

  // Kick off the GetMachineRootID method and wait for it to return
  // successfully.
  fake->delegate()->GetMachineRootID(machine_root_id_callback.Get());
  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithBulkPinningEnabled,
                       GetTotalPinnedSizeWithErrorIgnoresReturnedSize) {
  auto* drive_integration_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());
  auto* fake_drivefs = GetFakeDriveFsForProfile(browser()->profile());

  EXPECT_CALL(*fake_drivefs, GetOfflineFilesSpaceUsage(_))
      .WillOnce(RunOnceCallback<0>(drive::FILE_ERROR_FAILED, 1000));

  base::RunLoop run_loop;
  base::MockOnceCallback<void(int64_t)> mock_callback;
  EXPECT_CALL(mock_callback, Run(-1))
      .WillOnce(RunClosure(run_loop.QuitClosure()));

  drive_integration_service->GetTotalPinnedSize(mock_callback.Get());
  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithBulkPinningEnabled,
                       GetTotalPinnedSizeReturnsCorrectSize) {
  auto* drive_integration_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());
  auto* fake_drivefs = GetFakeDriveFsForProfile(browser()->profile());

  EXPECT_CALL(*fake_drivefs, GetOfflineFilesSpaceUsage(_))
      .WillOnce(RunOnceCallback<0>(drive::FILE_ERROR_OK, 1024));

  base::RunLoop run_loop;
  base::MockOnceCallback<void(int64_t)> mock_callback;
  EXPECT_CALL(mock_callback, Run(1024))
      .WillOnce(RunClosure(run_loop.QuitClosure()));

  drive_integration_service->GetTotalPinnedSize(mock_callback.Get());
  run_loop.Run();
}

IN_PROC_BROWSER_TEST_F(DriveIntegrationBrowserTestWithBulkPinningEnabled,
                       GetTotalPinnedSizeReturnsCachedSizeOnNextRequest) {
  auto* drive_integration_service =
      DriveIntegrationServiceFactory::FindForProfile(browser()->profile());
  auto* fake_drivefs = GetFakeDriveFsForProfile(browser()->profile());

  EXPECT_CALL(*fake_drivefs, GetOfflineFilesSpaceUsage(_))
      .WillOnce(RunOnceCallback<0>(drive::FILE_ERROR_OK, 1024));

  // First invocation of `GetTotalPinnedSize` should invoke the fake drivefs.
  base::RunLoop run_loop;
  base::MockOnceCallback<void(int64_t)> mock_callback;
  EXPECT_CALL(mock_callback, Run(1024))
      .WillOnce(RunClosure(run_loop.QuitClosure()));

  drive_integration_service->GetTotalPinnedSize(mock_callback.Get());
  run_loop.Run();

  // Second invocation of `GetTotalPinnedSize` should reuse the same value but
  // cached not calling fake drivefs instead.
  base::RunLoop run_loop_2;
  base::MockOnceCallback<void(int64_t)> cached_mock_callback;
  EXPECT_CALL(cached_mock_callback, Run(1024))
      .WillOnce(RunClosure(run_loop_2.QuitClosure()));

  drive_integration_service->GetTotalPinnedSize(cached_mock_callback.Get());
  run_loop_2.Run();
}

}  // namespace drive