File: sync_file_system_service_unittest.cc

package info (click to toggle)
chromium 135.0.7049.95-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 5,959,392 kB
  • sloc: cpp: 34,198,526; ansic: 7,100,035; javascript: 3,985,800; python: 1,395,489; asm: 896,754; xml: 722,891; pascal: 180,504; sh: 94,909; perl: 88,388; objc: 79,739; sql: 53,020; cs: 41,358; fortran: 24,137; makefile: 22,501; php: 13,699; tcl: 10,142; yacc: 8,822; ruby: 7,350; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; awk: 197; sed: 36
file content (494 lines) | stat: -rw-r--r-- 17,130 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
// 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/sync_file_system/sync_file_system_service.h"

#include <stddef.h>

#include <memory>
#include <utility>
#include <vector>

#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "chrome/browser/sync_file_system/local/canned_syncable_file_system.h"
#include "chrome/browser/sync_file_system/local/local_file_sync_context.h"
#include "chrome/browser/sync_file_system/local/local_file_sync_service.h"
#include "chrome/browser/sync_file_system/local/mock_sync_status_observer.h"
#include "chrome/browser/sync_file_system/local/sync_file_system_backend.h"
#include "chrome/browser/sync_file_system/mock_remote_file_sync_service.h"
#include "chrome/browser/sync_file_system/sync_callbacks.h"
#include "chrome/browser/sync_file_system/sync_event_observer.h"
#include "chrome/browser/sync_file_system/sync_file_metadata.h"
#include "chrome/browser/sync_file_system/sync_file_system_test_util.h"
#include "chrome/browser/sync_file_system/sync_status_code.h"
#include "chrome/browser/sync_file_system/syncable_file_system_util.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_utils.h"
#include "storage/browser/file_system/file_system_context.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/leveldatabase/leveldb_chrome.h"

using ::testing::_;
using storage::FileSystemURL;
using storage::FileSystemURLSet;
using ::testing::AnyNumber;
using ::testing::AtLeast;
using ::testing::InSequence;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::StrictMock;
using ::testing::WithArg;

namespace sync_file_system {

namespace {

const char kOrigin[] = "http://example.com";

template <typename R> struct AssignTrait {
  typedef const R& ArgumentType;
};

template <> struct AssignTrait<SyncFileStatus> {
  typedef SyncFileStatus ArgumentType;
};

template <typename R>
void AssignValueAndQuit(base::RunLoop* run_loop,
                        SyncStatusCode* status_out, R* value_out,
                        SyncStatusCode status,
                        typename AssignTrait<R>::ArgumentType value) {
  DCHECK(status_out);
  DCHECK(value_out);
  DCHECK(run_loop);
  *status_out = status;
  *value_out = value;
  run_loop->Quit();
}

// This is called on IO thread. Posts |callback| to be called on UI thread.
void VerifyFileError(base::OnceClosure callback, base::File::Error error) {
  EXPECT_EQ(base::File::FILE_OK, error);
  content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(callback));
}

}  // namespace

class MockSyncEventObserver : public SyncEventObserver {
 public:
  MockSyncEventObserver() = default;
  ~MockSyncEventObserver() override = default;

  MOCK_METHOD3(OnSyncStateUpdated,
               void(const GURL& app_origin,
                    SyncServiceState state,
                    const std::string& description));
  MOCK_METHOD5(OnFileSynced,
               void(const storage::FileSystemURL& url,
                    SyncFileType file_type,
                    SyncFileStatus status,
                    SyncAction action,
                    SyncDirection direction));
};

ACTION_P(RecordState, states) {
  states->push_back(arg1);
}

struct PostSyncFileCallback {
  PostSyncFileCallback(SyncStatusCode status, const storage::FileSystemURL& url)
      : status_(status), url_(url) {}
  void operator()(SyncFileCallback callback) {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), status_, url_));
  }

 private:
  SyncStatusCode status_;
  storage::FileSystemURL url_;
};

struct PostOnceClosureFunctor {
  PostOnceClosureFunctor() = default;
  void operator()(base::OnceClosure callback) {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, std::move(callback));
  }
};

class SyncFileSystemServiceTest : public testing::Test {
 protected:
  SyncFileSystemServiceTest()
      : task_environment_(content::BrowserTaskEnvironment::REAL_IO_THREAD) {}

  void SetUp() override {
    in_memory_env_ = leveldb_chrome::NewMemEnv("SyncFileSystemServiceTest");
    file_system_ = std::make_unique<CannedSyncableFileSystem>(
        GURL(kOrigin), in_memory_env_.get(), content::GetIOThreadTaskRunner({}),
        base::ThreadPool::CreateSingleThreadTaskRunner({base::MayBlock()}));

    std::unique_ptr<LocalFileSyncService> local_service =
        LocalFileSyncService::CreateForTesting(&profile_, in_memory_env_.get());
    remote_service_ = new StrictMock<MockRemoteFileSyncService>;
    sync_service_.reset(new SyncFileSystemService(&profile_));

    EXPECT_CALL(*mock_remote_service(),
                AddServiceObserver(_)).Times(1);
    EXPECT_CALL(*mock_remote_service(),
                AddFileStatusObserver(sync_service_.get())).Times(1);
    EXPECT_CALL(*mock_remote_service(),
                GetLocalChangeProcessor())
        .WillRepeatedly(Return(&local_change_processor_));
    EXPECT_CALL(*mock_remote_service(),
                SetRemoteChangeProcessor(local_service.get())).Times(1);

    EXPECT_CALL(*mock_remote_service(), SetSyncEnabled(false)).Times(1);

    sync_service_->Initialize(
        std::move(local_service),
        std::unique_ptr<RemoteFileSyncService>(remote_service_));

    // Disable auto sync by default.
    EXPECT_CALL(*mock_remote_service(), SetSyncEnabled(false)).Times(1);
    sync_service_->SetSyncEnabledForTesting(false);

    file_system_->SetUp();
  }

  void TearDown() override {
    sync_service_->Shutdown();
    file_system_->TearDown();
    RevokeSyncableFileSystem();
    base::ThreadPoolInstance::Get()->FlushForTesting();
  }

  void InitializeApp() {
    base::RunLoop run_loop;
    SyncStatusCode status = SYNC_STATUS_UNKNOWN;

    EXPECT_CALL(*mock_remote_service(),
                RegisterOrigin(GURL(kOrigin), _)).Times(1);

    // GetCurrentState may be called when a remote or local sync is scheduled
    // by change notifications or by a timer.
    EXPECT_CALL(*mock_remote_service(), GetCurrentState())
        .Times(AnyNumber())
        .WillRepeatedly(Return(REMOTE_SERVICE_OK));

    sync_service_->InitializeForApp(
        file_system_->file_system_context(),
        GURL(kOrigin),
        AssignAndQuitCallback(&run_loop, &status));
    run_loop.Run();

    EXPECT_EQ(SYNC_STATUS_OK, status);
    EXPECT_EQ(base::File::FILE_OK, file_system_->OpenFileSystem());
  }

  // Calls InitializeForApp after setting up the mock remote service to
  // perform following when RegisterOrigin is called:
  //  1. Notify RemoteFileSyncService's observers of |state_to_notify|
  //  2. Run the given callback with |status_to_return|.
  //
  // ..and verifies if following conditions are met:
  //  1. The SyncEventObserver of the service is called with
  //     |expected_states| service state values.
  //  2. InitializeForApp's callback is called with |expected_status|
  void InitializeAppForObserverTest(
      RemoteServiceState state_to_notify,
      SyncStatusCode status_to_return,
      const std::vector<SyncServiceState>& expected_states,
      SyncStatusCode expected_status) {
    StrictMock<MockSyncEventObserver> event_observer;
    sync_service_->AddSyncEventObserver(&event_observer);

    EnableSync();

    EXPECT_CALL(*mock_remote_service(), GetCurrentState())
        .Times(AnyNumber())
        .WillRepeatedly(Return(state_to_notify));

    EXPECT_CALL(*mock_remote_service(), RegisterOrigin(GURL(kOrigin), _))
        .WillOnce(WithArg<1>([&](SyncStatusCallback callback) {
          mock_remote_service()->NotifyRemoteServiceStateUpdated(
              state_to_notify, "Test event.");
          base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
              FROM_HERE, base::BindOnce(std::move(callback), status_to_return));
        }));

    std::vector<SyncServiceState> actual_states;
    EXPECT_CALL(event_observer, OnSyncStateUpdated(GURL(), _, _))
        .WillRepeatedly(RecordState(&actual_states));

    SyncStatusCode actual_status = SYNC_STATUS_UNKNOWN;
    base::RunLoop run_loop;
    sync_service_->InitializeForApp(
        file_system_->file_system_context(),
        GURL(kOrigin),
        AssignAndQuitCallback(&run_loop, &actual_status));
    run_loop.Run();

    EXPECT_EQ(expected_status, actual_status);
    ASSERT_EQ(expected_states.size(), actual_states.size());
    for (size_t i = 0; i < actual_states.size(); ++i)
      EXPECT_EQ(expected_states[i], actual_states[i]);

    sync_service_->RemoveSyncEventObserver(&event_observer);
  }

  FileSystemURL URL(const std::string& path) const {
    return file_system_->URL(path);
  }

  StrictMock<MockRemoteFileSyncService>* mock_remote_service() {
    return remote_service_;
  }

  StrictMock<MockLocalChangeProcessor>* mock_local_change_processor() {
    return &local_change_processor_;
  }

  void EnableSync() {
    EXPECT_CALL(*mock_remote_service(), SetSyncEnabled(true)).Times(1);
    sync_service_->SetSyncEnabledForTesting(true);
  }

  content::BrowserTaskEnvironment task_environment_;
  std::unique_ptr<leveldb::Env> in_memory_env_;
  TestingProfile profile_;
  std::unique_ptr<CannedSyncableFileSystem> file_system_;

  // Their ownerships are transferred to SyncFileSystemService.
  raw_ptr<StrictMock<MockRemoteFileSyncService>, DanglingUntriaged>
      remote_service_;
  StrictMock<MockLocalChangeProcessor> local_change_processor_;

  std::unique_ptr<SyncFileSystemService> sync_service_;
};

TEST_F(SyncFileSystemServiceTest, InitializeForApp) {
  InitializeApp();
}

TEST_F(SyncFileSystemServiceTest, InitializeForAppSuccess) {
  std::vector<SyncServiceState> expected_states;
  expected_states.push_back(SYNC_SERVICE_RUNNING);

  InitializeAppForObserverTest(
      REMOTE_SERVICE_OK,
      SYNC_STATUS_OK,
      expected_states,
      SYNC_STATUS_OK);
}

TEST_F(SyncFileSystemServiceTest, InitializeForAppWithNetworkFailure) {
  std::vector<SyncServiceState> expected_states;
  expected_states.push_back(SYNC_SERVICE_TEMPORARY_UNAVAILABLE);

  // Notify REMOTE_SERVICE_TEMPORARY_UNAVAILABLE and callback with
  // SYNC_STATUS_NETWORK_ERROR.  This should let the
  // InitializeApp fail.
  InitializeAppForObserverTest(
      REMOTE_SERVICE_TEMPORARY_UNAVAILABLE,
      SYNC_STATUS_NETWORK_ERROR,
      expected_states,
      SYNC_STATUS_NETWORK_ERROR);
}

// Disabled due to flakiness: crbug.com/1222929
TEST_F(SyncFileSystemServiceTest, DISABLED_InitializeForAppWithError) {
  std::vector<SyncServiceState> expected_states;
  expected_states.push_back(SYNC_SERVICE_DISABLED);

  // Notify REMOTE_SERVICE_DISABLED and callback with
  // SYNC_STATUS_FAILED.  This should let the InitializeApp fail.
  InitializeAppForObserverTest(
      REMOTE_SERVICE_DISABLED,
      SYNC_STATUS_FAILED,
      expected_states,
      SYNC_STATUS_FAILED);
}

// Disabled due to flakiness: crbug.com/1345010
TEST_F(SyncFileSystemServiceTest, DISABLED_SimpleLocalSyncFlow) {
  InitializeApp();

  StrictMock<MockSyncStatusObserver> status_observer;

  EnableSync();
  file_system_->backend()->sync_context()->
      set_mock_notify_changes_duration_in_sec(0);
  file_system_->AddSyncStatusObserver(&status_observer);

  // We'll test one local sync for this file.
  const FileSystemURL kFile(file_system_->URL("foo"));

  base::RunLoop run_loop;

  // We should get called OnSyncEnabled and OnWriteEnabled on kFile as in:
  // 1. OnWriteEnabled when PrepareForSync(SYNC_SHARED) is finished and
  //    the target file is unlocked for writing
  // 2. OnSyncEnabled x 3 times; 1) when CreateFile is finished, 2) when
  //    file is unlocked after PrepareForSync, and 3) when the sync is
  //    finished.
  EXPECT_CALL(status_observer, OnWriteEnabled(kFile))
      .Times(AtLeast(1));

  {
    ::testing::InSequence sequence;
    EXPECT_CALL(status_observer, OnSyncEnabled(kFile))
        .Times(AtLeast(2));
    EXPECT_CALL(status_observer, OnSyncEnabled(kFile))
        .WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
  }

  // The local_change_processor's ApplyLocalChange should be called once
  // with ADD_OR_UPDATE change for TYPE_FILE.
  const FileChange change(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
                          SYNC_FILE_TYPE_FILE);
  EXPECT_CALL(*mock_local_change_processor(),
              ApplyLocalChange(change, _, _, kFile, _))
      .WillOnce(WithArg<4>([](SyncStatusCallback callback) {
        base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
            FROM_HERE, base::BindOnce(std::move(callback), SYNC_STATUS_OK));
      }));
  EXPECT_CALL(*mock_remote_service(), ProcessRemoteChange(_))
      .WillRepeatedly(
          PostSyncFileCallback(SYNC_STATUS_NO_CHANGE_TO_SYNC, FileSystemURL()));

  EXPECT_CALL(*mock_remote_service(), PromoteDemotedChanges(_))
      .WillRepeatedly(PostOnceClosureFunctor());

  EXPECT_EQ(base::File::FILE_OK, file_system_->CreateFile(kFile));

  run_loop.Run();

  file_system_->RemoveSyncStatusObserver(&status_observer);
}

TEST_F(SyncFileSystemServiceTest, SimpleRemoteSyncFlow) {
  InitializeApp();

  EnableSync();

  base::RunLoop run_loop;

  // We expect a set of method calls for starting a remote sync.
  EXPECT_CALL(*mock_remote_service(), ProcessRemoteChange(_))
      .WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));

  // This should trigger a remote sync.
  mock_remote_service()->NotifyRemoteChangeQueueUpdated(1);

  run_loop.Run();
}

TEST_F(SyncFileSystemServiceTest, SimpleSyncFlowWithFileBusy) {
  InitializeApp();

  EnableSync();
  file_system_->backend()->sync_context()->
      set_mock_notify_changes_duration_in_sec(0);

  const FileSystemURL kFile(file_system_->URL("foo"));

  base::RunLoop run_loop;

  {
    InSequence sequence;

    // Return with SYNC_STATUS_FILE_BUSY once.
    EXPECT_CALL(*mock_remote_service(), ProcessRemoteChange(_))
        .WillOnce(PostSyncFileCallback(SYNC_STATUS_FILE_BUSY, kFile));

    // ProcessRemoteChange should be called again when the becomes
    // not busy.
    EXPECT_CALL(*mock_remote_service(), ProcessRemoteChange(_))
        .WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
  }

  EXPECT_CALL(*mock_remote_service(), PromoteDemotedChanges(_))
      .WillRepeatedly(PostOnceClosureFunctor());

  // We might also see an activity for local sync as we're going to make
  // a local write operation on kFile.
  EXPECT_CALL(*mock_local_change_processor(),
              ApplyLocalChange(_, _, _, kFile, _))
      .Times(AnyNumber());

  // This should trigger a remote sync.
  mock_remote_service()->NotifyRemoteChangeQueueUpdated(1);

  // Start a local operation on the same file (to make it BUSY).
  base::RunLoop verify_file_error_run_loop;
  content::GetIOThreadTaskRunner({})->PostTask(
      FROM_HERE,
      base::BindOnce(&CannedSyncableFileSystem::DoCreateFile,
                     base::Unretained(file_system_.get()), kFile,
                     base::BindOnce(&VerifyFileError,
                                    verify_file_error_run_loop.QuitClosure())));

  run_loop.Run();

  mock_remote_service()->NotifyRemoteChangeQueueUpdated(0);

  verify_file_error_run_loop.Run();
}

#if defined(THREAD_SANITIZER)
// SyncFileSystemServiceTest.GetFileSyncStatus fails under ThreadSanitizer,
// see http://crbug.com/294904.
#define MAYBE_GetFileSyncStatus DISABLED_GetFileSyncStatus
#else
#define MAYBE_GetFileSyncStatus GetFileSyncStatus
#endif
TEST_F(SyncFileSystemServiceTest, MAYBE_GetFileSyncStatus) {
  InitializeApp();

  const FileSystemURL kFile(file_system_->URL("foo"));

  SyncStatusCode status;
  SyncFileStatus sync_file_status;

  // 1. The file is synced state.
  {
    base::RunLoop run_loop;
    status = SYNC_STATUS_UNKNOWN;
    sync_file_status = SYNC_FILE_STATUS_UNKNOWN;
    sync_service_->GetFileSyncStatus(
        kFile, base::BindOnce(&AssignValueAndQuit<SyncFileStatus>, &run_loop,
                              &status, &sync_file_status));
    run_loop.Run();

    EXPECT_EQ(SYNC_STATUS_OK, status);
    EXPECT_EQ(SYNC_FILE_STATUS_SYNCED, sync_file_status);
  }

  // 2. The file has pending local changes.
  {
    base::RunLoop run_loop;
    EXPECT_EQ(base::File::FILE_OK, file_system_->CreateFile(kFile));

    status = SYNC_STATUS_UNKNOWN;
    sync_file_status = SYNC_FILE_STATUS_UNKNOWN;
    sync_service_->GetFileSyncStatus(
        kFile, base::BindOnce(&AssignValueAndQuit<SyncFileStatus>, &run_loop,
                              &status, &sync_file_status));
    run_loop.Run();

    EXPECT_EQ(SYNC_STATUS_OK, status);
    EXPECT_EQ(SYNC_FILE_STATUS_HAS_PENDING_CHANGES, sync_file_status);
  }
}

}  // namespace sync_file_system