1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "content/browser/background_sync/background_sync_manager.h"
6 
7 #include <stdint.h>
8 
9 #include <memory>
10 #include <utility>
11 #include <vector>
12 
13 #include "base/bind.h"
14 #include "base/check.h"
15 #include "base/files/scoped_temp_dir.h"
16 #include "base/location.h"
17 #include "base/macros.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/run_loop.h"
20 #include "base/single_thread_task_runner.h"
21 #include "base/stl_util.h"
22 #include "base/test/metrics/histogram_tester.h"
23 #include "base/test/mock_entropy_provider.h"
24 #include "base/test/simple_test_clock.h"
25 #include "base/threading/thread_task_runner_handle.h"
26 #include "build/build_config.h"
27 #include "content/browser/background_sync/background_sync_launcher.h"
28 #include "content/browser/background_sync/background_sync_network_observer.h"
29 #include "content/browser/background_sync/background_sync_status.h"
30 #include "content/browser/devtools/devtools_background_services_context_impl.h"
31 #include "content/browser/service_worker/embedded_worker_test_helper.h"
32 #include "content/browser/service_worker/service_worker_container_host.h"
33 #include "content/browser/service_worker/service_worker_context_core.h"
34 #include "content/browser/service_worker/service_worker_context_wrapper.h"
35 #include "content/browser/service_worker/service_worker_registration_object_host.h"
36 #include "content/browser/service_worker/service_worker_storage.h"
37 #include "content/browser/storage_partition_impl.h"
38 #include "content/public/browser/background_sync_parameters.h"
39 #include "content/public/browser/permission_type.h"
40 #include "content/public/test/background_sync_test_util.h"
41 #include "content/public/test/browser_task_environment.h"
42 #include "content/public/test/mock_permission_manager.h"
43 #include "content/public/test/test_browser_context.h"
44 #include "content/public/test/test_utils.h"
45 #include "content/test/mock_background_sync_controller.h"
46 #include "content/test/test_background_sync_context.h"
47 #include "content/test/test_background_sync_manager.h"
48 #include "content/test/test_background_sync_proxy.h"
49 #include "services/network/test/test_network_connection_tracker.h"
50 #include "testing/gmock/include/gmock/gmock.h"
51 #include "testing/gtest/include/gtest/gtest.h"
52 #include "third_party/blink/public/mojom/permissions/permission_status.mojom.h"
53 #include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
54 
55 namespace content {
56 
57 namespace {
58 
59 using ::testing::_;
60 using ::testing::Return;
61 
62 const char kScope1[] = "https://example.com/a";
63 const char kScope2[] = "https://example.com/b";
64 const char kScript1[] = "https://example.com/a/script.js";
65 const char kScript2[] = "https://example.com/b/script.js";
66 
RegisterServiceWorkerCallback(bool * called,int64_t * store_registration_id,blink::ServiceWorkerStatusCode status,const std::string & status_message,int64_t registration_id)67 void RegisterServiceWorkerCallback(bool* called,
68                                    int64_t* store_registration_id,
69                                    blink::ServiceWorkerStatusCode status,
70                                    const std::string& status_message,
71                                    int64_t registration_id) {
72   EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, status)
73       << blink::ServiceWorkerStatusToString(status);
74   *called = true;
75   *store_registration_id = registration_id;
76 }
77 
FindServiceWorkerRegistrationCallback(scoped_refptr<ServiceWorkerRegistration> * out_registration,blink::ServiceWorkerStatusCode status,scoped_refptr<ServiceWorkerRegistration> registration)78 void FindServiceWorkerRegistrationCallback(
79     scoped_refptr<ServiceWorkerRegistration>* out_registration,
80     blink::ServiceWorkerStatusCode status,
81     scoped_refptr<ServiceWorkerRegistration> registration) {
82   EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, status)
83       << blink::ServiceWorkerStatusToString(status);
84   *out_registration = std::move(registration);
85 }
86 
UnregisterServiceWorkerCallback(bool * called,blink::ServiceWorkerStatusCode code)87 void UnregisterServiceWorkerCallback(bool* called,
88                                      blink::ServiceWorkerStatusCode code) {
89   EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, code);
90   *called = true;
91 }
92 
GetBackgroundSyncType(const blink::mojom::SyncRegistrationOptions & options)93 blink::mojom::BackgroundSyncType GetBackgroundSyncType(
94     const blink::mojom::SyncRegistrationOptions& options) {
95   return options.min_interval == -1
96              ? blink::mojom::BackgroundSyncType::ONE_SHOT
97              : blink::mojom::BackgroundSyncType::PERIODIC;
98 }
99 
100 }  // namespace
101 
102 class BackgroundSyncManagerTest
103     : public testing::Test,
104       public DevToolsBackgroundServicesContextImpl::EventObserver {
105  public:
BackgroundSyncManagerTest()106   BackgroundSyncManagerTest()
107       : task_environment_(BrowserTaskEnvironment::IO_MAINLOOP) {
108     sync_options_1_.tag = "foo";
109     sync_options_2_.tag = "bar";
110   }
111 
SetUp()112   void SetUp() override {
113     // Don't let the tests be confused by the real-world device connectivity
114     background_sync_test_util::SetIgnoreNetworkChanges(true);
115 
116     // TODO(jkarlin): Create a new object with all of the necessary SW calls
117     // so that we can inject test versions instead of bringing up all of this
118     // extra SW stuff.
119     helper_.reset(new EmbeddedWorkerTestHelper(base::FilePath()));
120 
121     std::unique_ptr<MockPermissionManager> mock_permission_manager(
122         new testing::NiceMock<MockPermissionManager>());
123     ON_CALL(*mock_permission_manager,
124             GetPermissionStatus(PermissionType::BACKGROUND_SYNC, _, _))
125         .WillByDefault(Return(blink::mojom::PermissionStatus::GRANTED));
126     ON_CALL(*mock_permission_manager,
127             GetPermissionStatus(PermissionType::PERIODIC_BACKGROUND_SYNC, _, _))
128         .WillByDefault(Return(blink::mojom::PermissionStatus::GRANTED));
129     ON_CALL(*mock_permission_manager,
130             GetPermissionStatus(PermissionType::NOTIFICATIONS, _, _))
131         .WillByDefault(Return(blink::mojom::PermissionStatus::DENIED));
132     helper_->browser_context()->SetPermissionControllerDelegate(
133         std::move(mock_permission_manager));
134 
135     // Create a StoragePartition with the correct BrowserContext so that the
136     // BackgroundSyncManager can find the BrowserContext through it.
137     storage_partition_impl_ = static_cast<StoragePartitionImpl*>(
138         BrowserContext::GetStoragePartitionForSite(
139             helper_->browser_context(), GURL("https://example.com")));
140     helper_->context_wrapper()->set_storage_partition(storage_partition_impl_);
141 
142     SetMaxSyncAttemptsAndRestartManager(1);
143 
144     // Wait for storage to finish initializing before registering service
145     // workers.
146     base::RunLoop().RunUntilIdle();
147     RegisterServiceWorkers();
148 
149     storage_partition_impl_->GetDevToolsBackgroundServicesContext()
150         ->AddObserver(this);
151   }
152 
TearDown()153   void TearDown() override {
154     storage_partition_impl_->GetDevToolsBackgroundServicesContext()
155         ->RemoveObserver(this);
156     // Restore the network observer functionality for subsequent tests.
157     background_sync_test_util::SetIgnoreNetworkChanges(false);
158     background_sync_context_->Shutdown();
159   }
160 
RegisterServiceWorkers()161   void RegisterServiceWorkers() {
162     bool called_1 = false;
163     bool called_2 = false;
164     blink::mojom::ServiceWorkerRegistrationOptions options1;
165     options1.scope = GURL(kScope1);
166     blink::mojom::ServiceWorkerRegistrationOptions options2;
167     options2.scope = GURL(kScope2);
168     helper_->context()->RegisterServiceWorker(
169         GURL(kScript1), options1,
170         blink::mojom::FetchClientSettingsObject::New(),
171         base::BindOnce(&RegisterServiceWorkerCallback, &called_1,
172                        &sw_registration_id_1_));
173 
174     helper_->context()->RegisterServiceWorker(
175         GURL(kScript2), options2,
176         blink::mojom::FetchClientSettingsObject::New(),
177         base::BindOnce(&RegisterServiceWorkerCallback, &called_2,
178                        &sw_registration_id_2_));
179     base::RunLoop().RunUntilIdle();
180     EXPECT_TRUE(called_1);
181     EXPECT_TRUE(called_2);
182 
183     // Hang onto the registrations as they need to be "live" when
184     // calling BackgroundSyncManager::Register.
185     helper_->context_wrapper()->FindReadyRegistrationForId(
186         sw_registration_id_1_, url::Origin::Create(GURL(kScope1)),
187         base::BindOnce(FindServiceWorkerRegistrationCallback,
188                        &sw_registration_1_));
189 
190     helper_->context_wrapper()->FindReadyRegistrationForId(
191         sw_registration_id_2_, url::Origin::Create(GURL(kScope1)),
192         base::BindOnce(FindServiceWorkerRegistrationCallback,
193                        &sw_registration_2_));
194     base::RunLoop().RunUntilIdle();
195     EXPECT_TRUE(sw_registration_1_);
196     EXPECT_TRUE(sw_registration_2_);
197   }
198 
SetNetwork(network::mojom::ConnectionType connection_type)199   void SetNetwork(network::mojom::ConnectionType connection_type) {
200     network::TestNetworkConnectionTracker::GetInstance()->SetConnectionType(
201         connection_type);
202     if (test_background_sync_manager()) {
203       BackgroundSyncNetworkObserver* network_observer =
204           test_background_sync_manager()->GetNetworkObserverForTesting();
205       network_observer->NotifyManagerIfConnectionChangedForTesting(
206           connection_type);
207       base::RunLoop().RunUntilIdle();
208     }
209   }
210 
StatusAndOneShotSyncRegistrationCallback(bool * was_called,BackgroundSyncStatus status,std::unique_ptr<BackgroundSyncRegistration> registration)211   void StatusAndOneShotSyncRegistrationCallback(
212       bool* was_called,
213       BackgroundSyncStatus status,
214       std::unique_ptr<BackgroundSyncRegistration> registration) {
215     *was_called = true;
216     one_shot_sync_callback_status_ = status;
217     callback_one_shot_sync_registration_ = std::move(registration);
218   }
219 
StatusAndPeriodicSyncRegistrationCallback(bool * was_called,BackgroundSyncStatus status,std::unique_ptr<BackgroundSyncRegistration> registration)220   void StatusAndPeriodicSyncRegistrationCallback(
221       bool* was_called,
222       BackgroundSyncStatus status,
223       std::unique_ptr<BackgroundSyncRegistration> registration) {
224     *was_called = true;
225     periodic_sync_callback_status_ = status;
226     callback_periodic_sync_registration_ = std::move(registration);
227   }
228 
StatusAndOneShotSyncRegistrationsCallback(bool * was_called,BackgroundSyncStatus status,std::vector<std::unique_ptr<BackgroundSyncRegistration>> registrations)229   void StatusAndOneShotSyncRegistrationsCallback(
230       bool* was_called,
231       BackgroundSyncStatus status,
232       std::vector<std::unique_ptr<BackgroundSyncRegistration>> registrations) {
233     *was_called = true;
234     one_shot_sync_callback_status_ = status;
235     callback_one_shot_sync_registrations_ = std::move(registrations);
236   }
237 
StatusAndPeriodicSyncRegistrationsCallback(bool * was_called,BackgroundSyncStatus status,std::vector<std::unique_ptr<BackgroundSyncRegistration>> registrations)238   void StatusAndPeriodicSyncRegistrationsCallback(
239       bool* was_called,
240       BackgroundSyncStatus status,
241       std::vector<std::unique_ptr<BackgroundSyncRegistration>> registrations) {
242     *was_called = true;
243     periodic_sync_callback_status_ = status;
244     callback_periodic_sync_registrations_ = std::move(registrations);
245   }
246 
StatusCallback(bool * was_called,BackgroundSyncStatus status)247   void StatusCallback(bool* was_called, BackgroundSyncStatus status) {
248     *was_called = true;
249     callback_status_ = status;
250   }
251 
test_background_sync_manager()252   TestBackgroundSyncManager* test_background_sync_manager() {
253     return static_cast<TestBackgroundSyncManager*>(
254         background_sync_context_->background_sync_manager());
255   }
256 
test_proxy()257   TestBackgroundSyncProxy* test_proxy() {
258     return static_cast<TestBackgroundSyncProxy*>(
259         test_background_sync_manager()->proxy_.get());
260   }
261 
GetSoonestWakeupDelta(blink::mojom::BackgroundSyncType sync_type,base::Time last_browser_wakeup_for_periodic_sync)262   base::TimeDelta GetSoonestWakeupDelta(
263       blink::mojom::BackgroundSyncType sync_type,
264       base::Time last_browser_wakeup_for_periodic_sync) {
265     return test_background_sync_manager()->GetSoonestWakeupDelta(
266         sync_type, last_browser_wakeup_for_periodic_sync);
267   }
268 
SuspendPeriodicSyncRegistrations(std::set<url::Origin> origins)269   void SuspendPeriodicSyncRegistrations(std::set<url::Origin> origins) {
270     GetController()->NoteSuspendedPeriodicSyncOrigins(std::move(origins));
271   }
272 
RevivePeriodicSyncRegistrations(url::Origin origin)273   void RevivePeriodicSyncRegistrations(url::Origin origin) {
274     GetController()->ReviveSuspendedPeriodicSyncOrigin(origin);
275     test_background_sync_manager()->RevivePeriodicSyncRegistrations(origin);
276   }
277 
BlockContentSettingFor(url::Origin origin)278   void BlockContentSettingFor(url::Origin origin) {
279     GetController()->RemoveFromTrackedOrigins(origin);
280     test_background_sync_manager()->UnregisterPeriodicSyncForOrigin(origin);
281   }
282 
283  protected:
284   MOCK_METHOD1(OnEventReceived,
285                void(const devtools::proto::BackgroundServiceEvent&));
286   MOCK_METHOD2(OnRecordingStateChanged,
287                void(bool, devtools::proto::BackgroundService));
288 
CreateBackgroundSyncManager()289   void CreateBackgroundSyncManager() {
290     if (background_sync_context_) {
291       background_sync_context_->Shutdown();
292       base::RunLoop().RunUntilIdle();
293     }
294 
295     background_sync_context_ =
296         base::MakeRefCounted<TestBackgroundSyncContext>();
297     background_sync_context_->Init(
298         helper_->context_wrapper(),
299         storage_partition_impl_->GetDevToolsBackgroundServicesContext());
300     base::RunLoop().RunUntilIdle();
301 
302     storage_partition_impl_->ShutdownBackgroundSyncContextForTesting();
303     base::RunLoop().RunUntilIdle();
304     storage_partition_impl_->OverrideBackgroundSyncContextForTesting(
305         background_sync_context_.get());
306 
307     test_background_sync_manager()->set_clock(&test_clock_);
308     test_background_sync_manager()->set_proxy_for_testing(
309         std::make_unique<TestBackgroundSyncProxy>(helper_->context_wrapper()));
310 
311     // Many tests do not expect the sync event to fire immediately after
312     // register (and cleanup up the sync registrations).  Tests can control when
313     // the sync event fires by manipulating the network state as needed.
314     // NOTE: The setup of the network connection must happen after the
315     //       BackgroundSyncManager has been created.
316     SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
317   }
318 
InitBackgroundSyncManager()319   void InitBackgroundSyncManager() {
320     test_background_sync_manager()->DoInit();
321     base::RunLoop().RunUntilIdle();
322   }
323 
SetupBackgroundSyncManager()324   void SetupBackgroundSyncManager() {
325     CreateBackgroundSyncManager();
326     InitBackgroundSyncManager();
327   }
328 
SetupCorruptBackgroundSyncManager()329   void SetupCorruptBackgroundSyncManager() {
330     CreateBackgroundSyncManager();
331     test_background_sync_manager()->set_corrupt_backend(true);
332     InitBackgroundSyncManager();
333   }
334 
SetupDelayedBackgroundSyncManager()335   void SetupDelayedBackgroundSyncManager() {
336     CreateBackgroundSyncManager();
337     test_background_sync_manager()->set_delay_backend(true);
338     InitBackgroundSyncManager();
339   }
340 
DeleteBackgroundSyncManager()341   void DeleteBackgroundSyncManager() {
342     storage_partition_impl_->GetBackgroundSyncContext()
343         ->set_background_sync_manager_for_testing(nullptr);
344   }
345 
Register(blink::mojom::SyncRegistrationOptions sync_options)346   bool Register(blink::mojom::SyncRegistrationOptions sync_options) {
347     return RegisterWithServiceWorkerId(sw_registration_id_1_,
348                                        std::move(sync_options));
349   }
350 
Unregister(blink::mojom::SyncRegistrationOptions sync_options)351   bool Unregister(blink::mojom::SyncRegistrationOptions sync_options) {
352     return UnregisterWithServiceWorkerId(sw_registration_id_1_,
353                                          std::move(sync_options));
354   }
355 
RegisterWithServiceWorkerId(int64_t sw_registration_id,blink::mojom::SyncRegistrationOptions options)356   bool RegisterWithServiceWorkerId(
357       int64_t sw_registration_id,
358       blink::mojom::SyncRegistrationOptions options) {
359     bool was_called = false;
360     BackgroundSyncStatus* callback_status;
361     if (GetBackgroundSyncType(options) ==
362         blink::mojom::BackgroundSyncType::ONE_SHOT) {
363       test_background_sync_manager()->Register(
364           sw_registration_id, options,
365           base::BindOnce(&BackgroundSyncManagerTest::
366                              StatusAndOneShotSyncRegistrationCallback,
367                          base::Unretained(this), &was_called));
368       callback_status = &one_shot_sync_callback_status_;
369     } else {
370       test_background_sync_manager()->Register(
371           sw_registration_id, options,
372           base::BindOnce(&BackgroundSyncManagerTest::
373                              StatusAndPeriodicSyncRegistrationCallback,
374                          base::Unretained(this), &was_called));
375       callback_status = &periodic_sync_callback_status_;
376     }
377 
378     base::RunLoop().RunUntilIdle();
379     EXPECT_TRUE(was_called);
380 
381     // Mock the client receiving the response and calling
382     // DidResolveRegistration.
383     if (*callback_status == BACKGROUND_SYNC_STATUS_OK) {
384       test_background_sync_manager()->DidResolveRegistration(
385           blink::mojom::BackgroundSyncRegistrationInfo::New(
386               sw_registration_id, options.tag, GetBackgroundSyncType(options)));
387       base::RunLoop().RunUntilIdle();
388     }
389 
390     return *callback_status == BACKGROUND_SYNC_STATUS_OK;
391   }
392 
UnregisterWithServiceWorkerId(int64_t sw_registration_id,blink::mojom::SyncRegistrationOptions options)393   bool UnregisterWithServiceWorkerId(
394       int64_t sw_registration_id,
395       blink::mojom::SyncRegistrationOptions options) {
396     if (GetBackgroundSyncType(options) ==
397         blink::mojom::BackgroundSyncType::ONE_SHOT) {
398       // Not supported for one-shot sync.
399       return false;
400     }
401 
402     bool was_called = false;
403     test_background_sync_manager()->UnregisterPeriodicSync(
404         sw_registration_id, options.tag,
405         base::BindOnce(&BackgroundSyncManagerTest::StatusCallback,
406                        base::Unretained(this), &was_called));
407     base::RunLoop().RunUntilIdle();
408     EXPECT_TRUE(was_called);
409 
410     return callback_status_ == BACKGROUND_SYNC_STATUS_OK;
411   }
412 
GetPermissionControllerDelegate()413   MockPermissionManager* GetPermissionControllerDelegate() {
414     return static_cast<MockPermissionManager*>(
415         helper_->browser_context()->GetPermissionControllerDelegate());
416   }
417 
GetRegistration(blink::mojom::SyncRegistrationOptions registration_options)418   bool GetRegistration(
419       blink::mojom::SyncRegistrationOptions registration_options) {
420     if (GetBackgroundSyncType(registration_options) ==
421         blink::mojom::BackgroundSyncType::ONE_SHOT) {
422       return GetOneShotSyncRegistrationWithServiceWorkerId(
423           sw_registration_id_1_, std::move(registration_options));
424     }
425     return GetPeriodicSyncRegistrationWithServiceWorkerId(
426         sw_registration_id_1_, std::move(registration_options));
427   }
428 
GetOneShotSyncRegistrationWithServiceWorkerId(int64_t sw_registration_id,blink::mojom::SyncRegistrationOptions registration_options)429   bool GetOneShotSyncRegistrationWithServiceWorkerId(
430       int64_t sw_registration_id,
431       blink::mojom::SyncRegistrationOptions registration_options) {
432     bool was_called = false;
433 
434     test_background_sync_manager()->GetOneShotSyncRegistrations(
435         sw_registration_id,
436         base::BindOnce(&BackgroundSyncManagerTest::
437                            StatusAndOneShotSyncRegistrationsCallback,
438                        base::Unretained(this), &was_called));
439 
440     base::RunLoop().RunUntilIdle();
441     EXPECT_TRUE(was_called);
442 
443     if (one_shot_sync_callback_status_ == BACKGROUND_SYNC_STATUS_OK) {
444       for (auto& one_shot_sync_registration :
445            callback_one_shot_sync_registrations_) {
446         if (one_shot_sync_registration->options()->Equals(
447                 registration_options)) {
448           // Transfer the matching registration out of the vector into
449           // |callback_one_shot_sync_registration_| for testing.
450           callback_one_shot_sync_registration_ =
451               std::move(one_shot_sync_registration);
452           base::Erase(callback_one_shot_sync_registrations_,
453                       one_shot_sync_registration);
454           return true;
455         }
456       }
457     }
458     return false;
459   }
460 
GetPeriodicSyncRegistrationWithServiceWorkerId(int64_t sw_registration_id,blink::mojom::SyncRegistrationOptions registration_options)461   bool GetPeriodicSyncRegistrationWithServiceWorkerId(
462       int64_t sw_registration_id,
463       blink::mojom::SyncRegistrationOptions registration_options) {
464     bool was_called = false;
465 
466     test_background_sync_manager()->GetPeriodicSyncRegistrations(
467         sw_registration_id,
468         base::BindOnce(&BackgroundSyncManagerTest::
469                            StatusAndPeriodicSyncRegistrationsCallback,
470                        base::Unretained(this), &was_called));
471 
472     base::RunLoop().RunUntilIdle();
473     EXPECT_TRUE(was_called);
474 
475     if (periodic_sync_callback_status_ == BACKGROUND_SYNC_STATUS_OK) {
476       for (auto& periodic_sync_registration :
477            callback_periodic_sync_registrations_) {
478         if (periodic_sync_registration->options()->Equals(
479                 registration_options)) {
480           // Transfer the matching registration out of the vector into
481           // |callback_periodic_sync_registration_| for testing.
482           callback_periodic_sync_registration_ =
483               std::move(periodic_sync_registration);
484           base::Erase(callback_periodic_sync_registrations_,
485                       periodic_sync_registration);
486           return true;
487         }
488       }
489     }
490     return false;
491   }
492 
GetOriginForPeriodicSyncRegistration()493   url::Origin GetOriginForPeriodicSyncRegistration() {
494     DCHECK(callback_periodic_sync_registration_);
495     return callback_periodic_sync_registration_->origin();
496   }
497 
GetOneShotSyncRegistrations()498   bool GetOneShotSyncRegistrations() {
499     bool was_called = false;
500     test_background_sync_manager()->GetOneShotSyncRegistrations(
501         sw_registration_id_1_,
502         base::BindOnce(&BackgroundSyncManagerTest::
503                            StatusAndOneShotSyncRegistrationsCallback,
504                        base::Unretained(this), &was_called));
505     base::RunLoop().RunUntilIdle();
506     EXPECT_TRUE(was_called);
507 
508     return one_shot_sync_callback_status_ == BACKGROUND_SYNC_STATUS_OK;
509   }
510 
GetPeriodicSyncRegistrations()511   bool GetPeriodicSyncRegistrations() {
512     bool was_called = false;
513     test_background_sync_manager()->GetPeriodicSyncRegistrations(
514         sw_registration_id_1_,
515         base::BindOnce(&BackgroundSyncManagerTest::
516                            StatusAndPeriodicSyncRegistrationsCallback,
517                        base::Unretained(this), &was_called));
518     base::RunLoop().RunUntilIdle();
519     EXPECT_TRUE(was_called);
520 
521     return periodic_sync_callback_status_ == BACKGROUND_SYNC_STATUS_OK;
522   }
523 
GetController()524   MockBackgroundSyncController* GetController() {
525     return static_cast<MockBackgroundSyncController*>(
526         helper_->browser_context()->GetBackgroundSyncController());
527   }
528 
StorageRegistrationCallback(blink::ServiceWorkerStatusCode result)529   void StorageRegistrationCallback(blink::ServiceWorkerStatusCode result) {
530     callback_sw_status_code_ = result;
531   }
532 
UnregisterServiceWorker(uint64_t sw_registration_id)533   void UnregisterServiceWorker(uint64_t sw_registration_id) {
534     bool called = false;
535     helper_->context()->UnregisterServiceWorker(
536         ScopeForSWId(sw_registration_id), /*is_immediate=*/false,
537         base::BindOnce(&UnregisterServiceWorkerCallback, &called));
538     base::RunLoop().RunUntilIdle();
539     EXPECT_TRUE(called);
540   }
541 
ScopeForSWId(int64_t sw_id)542   GURL ScopeForSWId(int64_t sw_id) {
543     EXPECT_TRUE(sw_id == sw_registration_id_1_ ||
544                 sw_id == sw_registration_id_2_);
545     return sw_id == sw_registration_id_1_ ? GURL(kScope1) : GURL(kScope2);
546   }
547 
SetupForSyncEvent(const TestBackgroundSyncManager::DispatchSyncCallback & callback)548   void SetupForSyncEvent(
549       const TestBackgroundSyncManager::DispatchSyncCallback& callback) {
550     test_background_sync_manager()->set_dispatch_sync_callback(callback);
551     SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
552   }
553 
SetupForPeriodicSyncEvent(const TestBackgroundSyncManager::DispatchSyncCallback & callback)554   void SetupForPeriodicSyncEvent(
555       const TestBackgroundSyncManager::DispatchSyncCallback& callback) {
556     test_background_sync_manager()->set_dispatch_periodic_sync_callback(
557         callback);
558     SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
559   }
560 
DispatchSyncStatusCallback(blink::ServiceWorkerStatusCode status,scoped_refptr<ServiceWorkerVersion> active_version,ServiceWorkerVersion::StatusCallback callback)561   void DispatchSyncStatusCallback(
562       blink::ServiceWorkerStatusCode status,
563       scoped_refptr<ServiceWorkerVersion> active_version,
564       ServiceWorkerVersion::StatusCallback callback) {
565     sync_events_called_++;
566     std::move(callback).Run(status);
567   }
568 
DispatchPeriodicSyncStatusCallback(blink::ServiceWorkerStatusCode status,scoped_refptr<ServiceWorkerVersion> active_version,ServiceWorkerVersion::StatusCallback callback)569   void DispatchPeriodicSyncStatusCallback(
570       blink::ServiceWorkerStatusCode status,
571       scoped_refptr<ServiceWorkerVersion> active_version,
572       ServiceWorkerVersion::StatusCallback callback) {
573     periodic_sync_events_called_++;
574     std::move(callback).Run(status);
575   }
576 
InitSyncEventTest()577   void InitSyncEventTest() {
578     SetupForSyncEvent(base::BindRepeating(
579         &BackgroundSyncManagerTest::DispatchSyncStatusCallback,
580         base::Unretained(this), blink::ServiceWorkerStatusCode::kOk));
581   }
582 
InitPeriodicSyncEventTest()583   void InitPeriodicSyncEventTest() {
584     SetupForPeriodicSyncEvent(base::BindRepeating(
585         &BackgroundSyncManagerTest::DispatchPeriodicSyncStatusCallback,
586         base::Unretained(this), blink::ServiceWorkerStatusCode::kOk));
587   }
588 
InitFailedSyncEventTest()589   void InitFailedSyncEventTest() {
590     SetupForSyncEvent(base::BindRepeating(
591         &BackgroundSyncManagerTest::DispatchSyncStatusCallback,
592         base::Unretained(this),
593         blink::ServiceWorkerStatusCode::kErrorEventWaitUntilRejected));
594   }
595 
InitFailedPeriodicSyncEventTest()596   void InitFailedPeriodicSyncEventTest() {
597     SetupForPeriodicSyncEvent(base::BindRepeating(
598         &BackgroundSyncManagerTest::DispatchPeriodicSyncStatusCallback,
599         base::Unretained(this),
600         blink::ServiceWorkerStatusCode::kErrorEventWaitUntilRejected));
601   }
602 
DispatchSyncDelayedCallback(scoped_refptr<ServiceWorkerVersion> active_version,ServiceWorkerVersion::StatusCallback callback)603   void DispatchSyncDelayedCallback(
604       scoped_refptr<ServiceWorkerVersion> active_version,
605       ServiceWorkerVersion::StatusCallback callback) {
606     sync_events_called_++;
607     sync_fired_callback_ = std::move(callback);
608   }
609 
DispatchPeriodicSyncDelayedCallback(scoped_refptr<ServiceWorkerVersion> active_version,ServiceWorkerVersion::StatusCallback callback)610   void DispatchPeriodicSyncDelayedCallback(
611       scoped_refptr<ServiceWorkerVersion> active_version,
612       ServiceWorkerVersion::StatusCallback callback) {
613     periodic_sync_events_called_++;
614     periodic_sync_fired_callback_ = std::move(callback);
615   }
616 
InitDelayedSyncEventTest()617   void InitDelayedSyncEventTest() {
618     SetupForSyncEvent(base::BindRepeating(
619         &BackgroundSyncManagerTest::DispatchSyncDelayedCallback,
620         base::Unretained(this)));
621   }
622 
InitDelayedPeriodicSyncEventTest()623   void InitDelayedPeriodicSyncEventTest() {
624     SetupForPeriodicSyncEvent(base::BindRepeating(
625         &BackgroundSyncManagerTest::DispatchPeriodicSyncDelayedCallback,
626         base::Unretained(this)));
627   }
628 
RegisterAndVerifySyncEventDelayed(blink::mojom::SyncRegistrationOptions sync_options)629   void RegisterAndVerifySyncEventDelayed(
630       blink::mojom::SyncRegistrationOptions sync_options) {
631     int count_sync_events = sync_events_called_;
632     EXPECT_FALSE(sync_fired_callback_);
633 
634     EXPECT_TRUE(Register(sync_options));
635 
636     EXPECT_EQ(count_sync_events + 1, sync_events_called_);
637     EXPECT_TRUE(GetRegistration(std::move(sync_options)));
638     EXPECT_TRUE(sync_fired_callback_);
639   }
640 
DeleteServiceWorkerAndStartOver()641   void DeleteServiceWorkerAndStartOver() {
642     helper_->context()->ScheduleDeleteAndStartOver();
643     content::RunAllTasksUntilIdle();
644   }
645 
MaxTagLength() const646   int MaxTagLength() const { return BackgroundSyncManager::kMaxTagLength; }
647 
SetMaxSyncAttemptsAndRestartManager(int max_sync_attempts)648   void SetMaxSyncAttemptsAndRestartManager(int max_sync_attempts) {
649     BackgroundSyncParameters* parameters =
650         GetController()->background_sync_parameters();
651     parameters->max_sync_attempts = max_sync_attempts;
652     parameters->max_sync_attempts_with_notification_permission =
653         max_sync_attempts + 1;
654 
655     // Restart the BackgroundSyncManager so that it updates its parameters.
656     SetupBackgroundSyncManager();
657   }
658 
SetRelyOnAndroidNetworkDetectionAndRestartManager(bool rely_on_android_network_detection)659   void SetRelyOnAndroidNetworkDetectionAndRestartManager(
660       bool rely_on_android_network_detection) {
661 #if defined(OS_ANDROID)
662     BackgroundSyncParameters* parameters =
663         GetController()->background_sync_parameters();
664     parameters->rely_on_android_network_detection =
665         rely_on_android_network_detection;
666 
667     // Restart BackgroundSyncManager so that it updates its parameters.
668     SetupBackgroundSyncManager();
669 #endif
670   }
671 
SetPeriodicSyncEventsMinIntervalAndRestartManager(base::TimeDelta periodic_sync_events_min_interval)672   void SetPeriodicSyncEventsMinIntervalAndRestartManager(
673       base::TimeDelta periodic_sync_events_min_interval) {
674     BackgroundSyncParameters* parameters =
675         GetController()->background_sync_parameters();
676     parameters->min_periodic_sync_events_interval =
677         periodic_sync_events_min_interval;
678 
679     // Restart the BackgroundSyncManager so that it updates its parameters.
680     SetupBackgroundSyncManager();
681   }
682 
SetKeepBrowserAwakeTillEventsCompleteAndRestartManager(bool keep_browser_awake_till_events_complete)683   void SetKeepBrowserAwakeTillEventsCompleteAndRestartManager(
684       bool keep_browser_awake_till_events_complete) {
685     BackgroundSyncParameters* parameters =
686         GetController()->background_sync_parameters();
687     parameters->keep_browser_awake_till_events_complete =
688         keep_browser_awake_till_events_complete;
689     SetupBackgroundSyncManager();
690   }
691 
FireReadyEvents()692   void FireReadyEvents() { test_background_sync_manager()->OnNetworkChanged(); }
693 
AreOptionConditionsMet()694   bool AreOptionConditionsMet() {
695     return test_background_sync_manager()->AreOptionConditionsMet();
696   }
697 
IsDelayedTaskScheduledOneShotSync()698   bool IsDelayedTaskScheduledOneShotSync() {
699     return test_proxy()->IsDelayedTaskSet(
700         blink::mojom::BackgroundSyncType::ONE_SHOT);
701   }
702 
IsDelayedTaskScheduledPeriodicSync()703   bool IsDelayedTaskScheduledPeriodicSync() {
704     return test_proxy()->IsDelayedTaskSet(
705         blink::mojom::BackgroundSyncType::PERIODIC);
706   }
707 
IsBrowserWakeupForOneShotSyncScheduled()708   bool IsBrowserWakeupForOneShotSyncScheduled() {
709     return IsDelayedTaskScheduledOneShotSync();
710   }
711 
IsBrowserWakeupForPeriodicSyncScheduled()712   bool IsBrowserWakeupForPeriodicSyncScheduled() {
713     return IsDelayedTaskScheduledPeriodicSync();
714   }
715 
delayed_one_shot_sync_task_delta()716   base::TimeDelta delayed_one_shot_sync_task_delta() {
717     return test_proxy()->GetDelay(blink::mojom::BackgroundSyncType::ONE_SHOT);
718   }
719 
delayed_periodic_sync_task_delta()720   base::TimeDelta delayed_periodic_sync_task_delta() {
721     return test_proxy()->GetDelay(blink::mojom::BackgroundSyncType::PERIODIC);
722   }
723 
EqualsSoonestOneShotWakeupDelta(base::TimeDelta compare_to)724   bool EqualsSoonestOneShotWakeupDelta(base::TimeDelta compare_to) {
725     return delayed_one_shot_sync_task_delta() == compare_to;
726   }
727 
EqualsSoonestPeriodicSyncWakeupDelta(base::TimeDelta compare_to)728   bool EqualsSoonestPeriodicSyncWakeupDelta(base::TimeDelta compare_to) {
729     return delayed_periodic_sync_task_delta() == compare_to;
730   }
731 
RunOneShotSyncDelayedTask()732   void RunOneShotSyncDelayedTask() {
733     test_proxy()->RunDelayedTask(blink::mojom::BackgroundSyncType::ONE_SHOT);
734   }
735 
RunPeriodicSyncDelayedTask()736   void RunPeriodicSyncDelayedTask() {
737     test_proxy()->RunDelayedTask(blink::mojom::BackgroundSyncType::PERIODIC);
738   }
739 
740   BrowserTaskEnvironment task_environment_;
741   std::unique_ptr<EmbeddedWorkerTestHelper> helper_;
742   StoragePartitionImpl* storage_partition_impl_;
743   scoped_refptr<BackgroundSyncContextImpl> background_sync_context_;
744   base::SimpleTestClock test_clock_;
745   std::unique_ptr<TestBackgroundSyncProxy> test_proxy_;
746 
747   int64_t sw_registration_id_1_;
748   int64_t sw_registration_id_2_;
749   scoped_refptr<ServiceWorkerRegistration> sw_registration_1_;
750   scoped_refptr<ServiceWorkerRegistration> sw_registration_2_;
751 
752   blink::mojom::SyncRegistrationOptions sync_options_1_;
753   blink::mojom::SyncRegistrationOptions sync_options_2_;
754 
755   // Callback values.
756   BackgroundSyncStatus one_shot_sync_callback_status_ =
757       BACKGROUND_SYNC_STATUS_OK;
758   BackgroundSyncStatus periodic_sync_callback_status_ =
759       BACKGROUND_SYNC_STATUS_OK;
760   BackgroundSyncStatus callback_status_ = BACKGROUND_SYNC_STATUS_OK;
761   std::unique_ptr<BackgroundSyncRegistration>
762       callback_one_shot_sync_registration_;
763   std::unique_ptr<BackgroundSyncRegistration>
764       callback_periodic_sync_registration_;
765   std::vector<std::unique_ptr<BackgroundSyncRegistration>>
766       callback_one_shot_sync_registrations_;
767   std::vector<std::unique_ptr<BackgroundSyncRegistration>>
768       callback_periodic_sync_registrations_;
769   blink::ServiceWorkerStatusCode callback_sw_status_code_ =
770       blink::ServiceWorkerStatusCode::kOk;
771   int sync_events_called_ = 0;
772   int periodic_sync_events_called_ = 0;
773   ServiceWorkerVersion::StatusCallback sync_fired_callback_;
774   ServiceWorkerVersion::StatusCallback periodic_sync_fired_callback_;
775 };
776 
TEST_F(BackgroundSyncManagerTest,Register)777 TEST_F(BackgroundSyncManagerTest, Register) {
778   EXPECT_TRUE(Register(sync_options_1_));
779 }
780 
TEST_F(BackgroundSyncManagerTest,Unregister)781 TEST_F(BackgroundSyncManagerTest, Unregister) {
782   // Not supported for One-shot syncs.
783   EXPECT_TRUE(Register(sync_options_1_));
784   EXPECT_FALSE(Unregister(sync_options_1_));
785 
786   sync_options_1_.min_interval = 36000;
787   EXPECT_TRUE(Register(sync_options_1_));
788 
789   // Don't fail for non-existent Periodic Sync registrations.
790   sync_options_2_.min_interval = 36000;
791   EXPECT_TRUE(Unregister(sync_options_2_));
792 
793   // Unregistering one periodic sync doesn't affect another.
794   EXPECT_TRUE(Register(sync_options_2_));
795   EXPECT_TRUE(Unregister(sync_options_1_));
796   EXPECT_FALSE(GetRegistration(sync_options_1_));
797   EXPECT_TRUE(GetRegistration(sync_options_2_));
798 
799   // Disable manager. Unregister should fail.
800   test_background_sync_manager()->set_corrupt_backend(true);
801   EXPECT_FALSE(Unregister(sync_options_2_));
802   SetupBackgroundSyncManager();
803   EXPECT_TRUE(Unregister(sync_options_2_));
804 }
805 
TEST_F(BackgroundSyncManagerTest,UnregistrationStopsPeriodicTasks)806 TEST_F(BackgroundSyncManagerTest, UnregistrationStopsPeriodicTasks) {
807   InitPeriodicSyncEventTest();
808   int thirteen_hours_ms = 13 * 60 * 60 * 1000;
809   sync_options_2_.min_interval = thirteen_hours_ms;
810 
811   EXPECT_TRUE(Register(sync_options_2_));
812   EXPECT_EQ(0, periodic_sync_events_called_);
813 
814   // Advance clock.
815   test_clock_.Advance(base::TimeDelta::FromMilliseconds(thirteen_hours_ms));
816   FireReadyEvents();
817   base::RunLoop().RunUntilIdle();
818 
819   EXPECT_EQ(1, periodic_sync_events_called_);
820 
821   EXPECT_TRUE(Unregister(sync_options_2_));
822 
823   // Advance clock. Expect no increase in periodicSync events fired.
824   test_clock_.Advance(base::TimeDelta::FromMilliseconds(thirteen_hours_ms));
825   FireReadyEvents();
826   base::RunLoop().RunUntilIdle();
827   EXPECT_EQ(1, periodic_sync_events_called_);
828 }
829 
TEST_F(BackgroundSyncManagerTest,RegisterAndWaitToFireUntilResolved)830 TEST_F(BackgroundSyncManagerTest, RegisterAndWaitToFireUntilResolved) {
831   InitSyncEventTest();
832   bool was_called = false;
833   test_background_sync_manager()->Register(
834       sw_registration_id_1_, sync_options_1_,
835       base::BindOnce(
836           &BackgroundSyncManagerTest::StatusAndOneShotSyncRegistrationCallback,
837           base::Unretained(this), &was_called));
838   base::RunLoop().RunUntilIdle();
839   EXPECT_TRUE(was_called);
840 
841   // Verify that the sync event hasn't fired yet, as it should wait for the
842   // client to acknowledge with DidResolveRegistration.
843   EXPECT_EQ(0, sync_events_called_);
844 
845   test_background_sync_manager()->DidResolveRegistration(
846       blink::mojom::BackgroundSyncRegistrationInfo::New(
847           sw_registration_id_1_, sync_options_1_.tag,
848           GetBackgroundSyncType(sync_options_1_)));
849   base::RunLoop().RunUntilIdle();
850   EXPECT_EQ(1, sync_events_called_);
851 }
852 
TEST_F(BackgroundSyncManagerTest,ResolveInvalidRegistration)853 TEST_F(BackgroundSyncManagerTest, ResolveInvalidRegistration) {
854   InitSyncEventTest();
855   bool was_called = false;
856   test_background_sync_manager()->Register(
857       sw_registration_id_1_, sync_options_1_,
858       base::BindOnce(
859           &BackgroundSyncManagerTest::StatusAndOneShotSyncRegistrationCallback,
860           base::Unretained(this), &was_called));
861   base::RunLoop().RunUntilIdle();
862   EXPECT_TRUE(was_called);
863 
864   // Verify that the sync event hasn't fired yet, as it should wait for the
865   // client to acknowledge with DidResolveRegistration.
866   EXPECT_EQ(0, sync_events_called_);
867 
868   // Resolve a non-existing registration.
869   test_background_sync_manager()->DidResolveRegistration(
870       blink::mojom::BackgroundSyncRegistrationInfo::New(
871           sw_registration_id_1_, "unknown_tag",
872           GetBackgroundSyncType(sync_options_1_)));
873   base::RunLoop().RunUntilIdle();
874   EXPECT_EQ(0, sync_events_called_);
875 }
876 
TEST_F(BackgroundSyncManagerTest,RegistrationIntact)877 TEST_F(BackgroundSyncManagerTest, RegistrationIntact) {
878   EXPECT_TRUE(Register(sync_options_1_));
879   EXPECT_EQ(sync_options_1_.tag,
880             callback_one_shot_sync_registration_->options()->tag);
881   sync_options_2_.min_interval = 3600;
882   EXPECT_TRUE(Register(sync_options_2_));
883   EXPECT_EQ(sync_options_2_.tag,
884             callback_periodic_sync_registration_->options()->tag);
885 }
886 
TEST_F(BackgroundSyncManagerTest,RegisterWithoutLiveSWRegistration)887 TEST_F(BackgroundSyncManagerTest, RegisterWithoutLiveSWRegistration) {
888   // Get a worker host which is used to install the service worker.
889   ASSERT_TRUE(sw_registration_1_->active_version());
890   ASSERT_FALSE(sw_registration_1_->waiting_version());
891   ASSERT_FALSE(sw_registration_1_->installing_version());
892   ServiceWorkerHost* worker_host =
893       sw_registration_1_->active_version()->worker_host();
894   ASSERT_TRUE(worker_host);
895 
896   // Remove the registration object host.
897   worker_host->container_host()->registration_object_hosts_.clear();
898 
899   // Ensure |sw_registration_1_| is the last reference to the registration.
900   ASSERT_TRUE(sw_registration_1_->HasOneRef());
901   sw_registration_1_ = nullptr;
902 
903   EXPECT_FALSE(Register(sync_options_1_));
904   EXPECT_EQ(BACKGROUND_SYNC_STATUS_NO_SERVICE_WORKER,
905             one_shot_sync_callback_status_);
906 }
907 
TEST_F(BackgroundSyncManagerTest,RegisterWithoutActiveSWRegistration)908 TEST_F(BackgroundSyncManagerTest, RegisterWithoutActiveSWRegistration) {
909   sw_registration_1_->UnsetVersion(sw_registration_1_->active_version());
910   EXPECT_FALSE(Register(sync_options_1_));
911   EXPECT_EQ(BACKGROUND_SYNC_STATUS_NO_SERVICE_WORKER,
912             one_shot_sync_callback_status_);
913 }
914 
TEST_F(BackgroundSyncManagerTest,RegisterBadBackend)915 TEST_F(BackgroundSyncManagerTest, RegisterBadBackend) {
916   test_background_sync_manager()->set_corrupt_backend(true);
917   EXPECT_FALSE(Register(sync_options_1_));
918   test_background_sync_manager()->set_corrupt_backend(false);
919   EXPECT_FALSE(Register(sync_options_1_));
920   EXPECT_FALSE(GetRegistration(sync_options_1_));
921 }
922 
TEST_F(BackgroundSyncManagerTest,RegisterPermissionDenied)923 TEST_F(BackgroundSyncManagerTest, RegisterPermissionDenied) {
924   GURL expected_origin = GURL(kScope1).GetOrigin();
925   MockPermissionManager* mock_permission_manager =
926       GetPermissionControllerDelegate();
927 
928   EXPECT_CALL(*mock_permission_manager,
929               GetPermissionStatus(PermissionType::NOTIFICATIONS,
930                                   expected_origin, expected_origin))
931       .Times(2);
932 
933   EXPECT_CALL(*mock_permission_manager,
934               GetPermissionStatus(PermissionType::BACKGROUND_SYNC,
935                                   expected_origin, expected_origin))
936       .WillOnce(testing::Return(blink::mojom::PermissionStatus::DENIED));
937   EXPECT_FALSE(Register(sync_options_1_));
938 
939   sync_options_2_.min_interval = 36000;
940   EXPECT_CALL(*mock_permission_manager,
941               GetPermissionStatus(PermissionType::PERIODIC_BACKGROUND_SYNC,
942                                   expected_origin, expected_origin))
943       .WillOnce(testing::Return(blink::mojom::PermissionStatus::DENIED));
944   EXPECT_FALSE(Register(sync_options_2_));
945 }
946 
TEST_F(BackgroundSyncManagerTest,RegisterPermissionGranted)947 TEST_F(BackgroundSyncManagerTest, RegisterPermissionGranted) {
948   GURL expected_origin = GURL(kScope1).GetOrigin();
949   MockPermissionManager* mock_permission_manager =
950       GetPermissionControllerDelegate();
951 
952   EXPECT_CALL(*mock_permission_manager,
953               GetPermissionStatus(PermissionType::NOTIFICATIONS,
954                                   expected_origin, expected_origin))
955       .Times(2);
956 
957   EXPECT_CALL(*mock_permission_manager,
958               GetPermissionStatus(PermissionType::BACKGROUND_SYNC,
959                                   expected_origin, expected_origin))
960       .WillOnce(testing::Return(blink::mojom::PermissionStatus::GRANTED));
961   EXPECT_TRUE(Register(sync_options_1_));
962 
963   sync_options_2_.min_interval = 36000;
964   EXPECT_CALL(*mock_permission_manager,
965               GetPermissionStatus(PermissionType::PERIODIC_BACKGROUND_SYNC,
966                                   expected_origin, expected_origin))
967       .WillOnce(testing::Return(blink::mojom::PermissionStatus::GRANTED));
968   EXPECT_TRUE(Register(sync_options_2_));
969 }
970 
TEST_F(BackgroundSyncManagerTest,TwoRegistrations)971 TEST_F(BackgroundSyncManagerTest, TwoRegistrations) {
972   EXPECT_TRUE(Register(sync_options_1_));
973   EXPECT_TRUE(Register(sync_options_2_));
974 }
975 
TEST_F(BackgroundSyncManagerTest,GetRegistrationNonExisting)976 TEST_F(BackgroundSyncManagerTest, GetRegistrationNonExisting) {
977   EXPECT_FALSE(GetRegistration(sync_options_1_));
978 }
979 
TEST_F(BackgroundSyncManagerTest,GetRegistrationExisting)980 TEST_F(BackgroundSyncManagerTest, GetRegistrationExisting) {
981   EXPECT_TRUE(Register(sync_options_1_));
982   EXPECT_TRUE(GetRegistration(sync_options_1_));
983   EXPECT_FALSE(GetRegistration(sync_options_2_));
984 }
985 
TEST_F(BackgroundSyncManagerTest,GetRegistrationBadBackend)986 TEST_F(BackgroundSyncManagerTest, GetRegistrationBadBackend) {
987   EXPECT_TRUE(Register(sync_options_1_));
988   test_background_sync_manager()->set_corrupt_backend(true);
989   EXPECT_TRUE(GetRegistration(sync_options_1_));
990   EXPECT_FALSE(Register(sync_options_2_));
991   // Registration should have discovered the bad backend and disabled the
992   // BackgroundSyncManager.
993   EXPECT_FALSE(GetRegistration(sync_options_1_));
994   test_background_sync_manager()->set_corrupt_backend(false);
995   EXPECT_FALSE(GetRegistration(sync_options_1_));
996 }
997 
TEST_F(BackgroundSyncManagerTest,GetRegistrationsZero)998 TEST_F(BackgroundSyncManagerTest, GetRegistrationsZero) {
999   EXPECT_TRUE(GetOneShotSyncRegistrations());
1000   EXPECT_EQ(0u, callback_one_shot_sync_registrations_.size());
1001 }
1002 
TEST_F(BackgroundSyncManagerTest,GetRegistrationsOne)1003 TEST_F(BackgroundSyncManagerTest, GetRegistrationsOne) {
1004   EXPECT_TRUE(Register(sync_options_1_));
1005   EXPECT_TRUE(GetOneShotSyncRegistrations());
1006 
1007   ASSERT_EQ(1u, callback_one_shot_sync_registrations_.size());
1008   sync_options_1_.Equals(*callback_one_shot_sync_registrations_[0]->options());
1009 
1010   sync_options_1_.min_interval = 3600;
1011   EXPECT_TRUE(Register(sync_options_1_));
1012   EXPECT_TRUE(GetPeriodicSyncRegistrations());
1013 
1014   ASSERT_EQ(1u, callback_periodic_sync_registrations_.size());
1015   sync_options_1_.Equals(*callback_periodic_sync_registrations_[0]->options());
1016 }
1017 
TEST_F(BackgroundSyncManagerTest,GetRegistrationsTwo)1018 TEST_F(BackgroundSyncManagerTest, GetRegistrationsTwo) {
1019   EXPECT_TRUE(Register(sync_options_1_));
1020   EXPECT_TRUE(Register(sync_options_2_));
1021   EXPECT_TRUE(GetOneShotSyncRegistrations());
1022 
1023   ASSERT_EQ(2u, callback_one_shot_sync_registrations_.size());
1024   sync_options_1_.Equals(*callback_one_shot_sync_registrations_[0]->options());
1025   sync_options_2_.Equals(*callback_one_shot_sync_registrations_[1]->options());
1026 
1027   sync_options_1_.min_interval = 3600;
1028   sync_options_2_.min_interval = 3600;
1029   EXPECT_TRUE(Register(sync_options_1_));
1030   EXPECT_TRUE(Register(sync_options_2_));
1031   EXPECT_TRUE(GetPeriodicSyncRegistrations());
1032 
1033   ASSERT_EQ(2u, callback_periodic_sync_registrations_.size());
1034   sync_options_1_.Equals(*callback_periodic_sync_registrations_[0]->options());
1035   sync_options_2_.Equals(*callback_periodic_sync_registrations_[1]->options());
1036 }
1037 
TEST_F(BackgroundSyncManagerTest,GetRegistrationsBadBackend)1038 TEST_F(BackgroundSyncManagerTest, GetRegistrationsBadBackend) {
1039   EXPECT_TRUE(Register(sync_options_1_));
1040   test_background_sync_manager()->set_corrupt_backend(true);
1041   EXPECT_TRUE(GetOneShotSyncRegistrations());
1042   EXPECT_FALSE(Register(sync_options_2_));
1043   // Registration should have discovered the bad backend and disabled the
1044   // BackgroundSyncManager.
1045   EXPECT_FALSE(GetOneShotSyncRegistrations());
1046   test_background_sync_manager()->set_corrupt_backend(false);
1047   EXPECT_FALSE(GetOneShotSyncRegistrations());
1048 }
1049 
TEST_F(BackgroundSyncManagerTest,Reregister)1050 TEST_F(BackgroundSyncManagerTest, Reregister) {
1051   EXPECT_TRUE(Register(sync_options_1_));
1052   EXPECT_TRUE(Register(sync_options_1_));
1053   EXPECT_TRUE(GetRegistration(sync_options_1_));
1054 }
1055 
TEST_F(BackgroundSyncManagerTest,ReregisterSecond)1056 TEST_F(BackgroundSyncManagerTest, ReregisterSecond) {
1057   EXPECT_TRUE(Register(sync_options_1_));
1058   EXPECT_TRUE(Register(sync_options_2_));
1059   EXPECT_TRUE(Register(sync_options_2_));
1060 }
1061 
TEST_F(BackgroundSyncManagerTest,ReregisterPeriodicSync)1062 TEST_F(BackgroundSyncManagerTest, ReregisterPeriodicSync) {
1063   sync_options_1_.tag = sync_options_2_.tag;
1064   sync_options_1_.min_interval = 1000;
1065   sync_options_2_.min_interval = 2000;
1066 
1067   EXPECT_TRUE(Register(sync_options_1_));
1068   EXPECT_TRUE(GetRegistration(sync_options_1_));
1069 
1070   EXPECT_TRUE(Register(sync_options_2_));
1071   EXPECT_TRUE(GetRegistration(sync_options_2_));
1072   EXPECT_FALSE(GetRegistration(sync_options_1_));
1073 }
1074 
TEST_F(BackgroundSyncManagerTest,RegisterMaxTagLength)1075 TEST_F(BackgroundSyncManagerTest, RegisterMaxTagLength) {
1076   sync_options_1_.tag = std::string(MaxTagLength(), 'a');
1077   EXPECT_TRUE(Register(sync_options_1_));
1078 
1079   sync_options_2_.tag = std::string(MaxTagLength() + 1, 'b');
1080   EXPECT_FALSE(Register(sync_options_2_));
1081   EXPECT_EQ(BACKGROUND_SYNC_STATUS_NOT_ALLOWED, one_shot_sync_callback_status_);
1082 }
1083 
TEST_F(BackgroundSyncManagerTest,RebootRecovery)1084 TEST_F(BackgroundSyncManagerTest, RebootRecovery) {
1085   EXPECT_TRUE(Register(sync_options_1_));
1086 
1087   SetupBackgroundSyncManager();
1088 
1089   EXPECT_TRUE(GetRegistration(sync_options_1_));
1090   EXPECT_FALSE(GetRegistration(sync_options_2_));
1091 }
1092 
TEST_F(BackgroundSyncManagerTest,RebootRecoveryPeriodicSync)1093 TEST_F(BackgroundSyncManagerTest, RebootRecoveryPeriodicSync) {
1094   sync_options_1_.min_interval = 1000;
1095   EXPECT_TRUE(Register(sync_options_1_));
1096   EXPECT_TRUE(GetRegistration(sync_options_1_));
1097 
1098   // Restart the manager.
1099   SetupBackgroundSyncManager();
1100 
1101   EXPECT_TRUE(GetRegistration(sync_options_1_));
1102   EXPECT_EQ(GetOriginForPeriodicSyncRegistration(),
1103             url::Origin::Create(GURL(kScope1).GetOrigin()));
1104 }
1105 
TEST_F(BackgroundSyncManagerTest,RebootRecoveryTwoServiceWorkers)1106 TEST_F(BackgroundSyncManagerTest, RebootRecoveryTwoServiceWorkers) {
1107   EXPECT_TRUE(
1108       RegisterWithServiceWorkerId(sw_registration_id_1_, sync_options_1_));
1109   EXPECT_TRUE(
1110       RegisterWithServiceWorkerId(sw_registration_id_2_, sync_options_2_));
1111 
1112   SetupBackgroundSyncManager();
1113 
1114   EXPECT_TRUE(GetOneShotSyncRegistrationWithServiceWorkerId(
1115       sw_registration_id_1_, sync_options_1_));
1116   EXPECT_FALSE(GetOneShotSyncRegistrationWithServiceWorkerId(
1117       sw_registration_id_1_, sync_options_2_));
1118   EXPECT_FALSE(GetOneShotSyncRegistrationWithServiceWorkerId(
1119       sw_registration_id_2_, sync_options_1_));
1120   EXPECT_TRUE(GetOneShotSyncRegistrationWithServiceWorkerId(
1121       sw_registration_id_2_, sync_options_2_));
1122 
1123   EXPECT_TRUE(GetOneShotSyncRegistrationWithServiceWorkerId(
1124       sw_registration_id_1_, sync_options_1_));
1125   EXPECT_TRUE(GetOneShotSyncRegistrationWithServiceWorkerId(
1126       sw_registration_id_2_, sync_options_2_));
1127 
1128   EXPECT_TRUE(
1129       RegisterWithServiceWorkerId(sw_registration_id_1_, sync_options_2_));
1130   EXPECT_TRUE(
1131       RegisterWithServiceWorkerId(sw_registration_id_2_, sync_options_1_));
1132 }
1133 
TEST_F(BackgroundSyncManagerTest,InitWithBadBackend)1134 TEST_F(BackgroundSyncManagerTest, InitWithBadBackend) {
1135   SetupCorruptBackgroundSyncManager();
1136 
1137   EXPECT_FALSE(Register(sync_options_1_));
1138   EXPECT_FALSE(GetRegistration(sync_options_1_));
1139 }
1140 
TEST_F(BackgroundSyncManagerTest,SequentialOperations)1141 TEST_F(BackgroundSyncManagerTest, SequentialOperations) {
1142   // Schedule Init and all of the operations on a delayed backend. Verify that
1143   // the operations complete sequentially.
1144   SetupDelayedBackgroundSyncManager();
1145 
1146   bool register_called = false;
1147   bool get_registrations_called = false;
1148   test_background_sync_manager()->Register(
1149       sw_registration_id_1_, sync_options_1_,
1150       base::BindOnce(
1151           &BackgroundSyncManagerTest::StatusAndOneShotSyncRegistrationCallback,
1152           base::Unretained(this), &register_called));
1153   test_background_sync_manager()->GetOneShotSyncRegistrations(
1154       sw_registration_id_1_,
1155       base::BindOnce(
1156           &BackgroundSyncManagerTest::StatusAndOneShotSyncRegistrationsCallback,
1157           base::Unretained(this), &get_registrations_called));
1158 
1159   base::RunLoop().RunUntilIdle();
1160   // Init should be blocked while loading from the backend.
1161   EXPECT_FALSE(register_called);
1162   EXPECT_FALSE(get_registrations_called);
1163 
1164   test_background_sync_manager()->ResumeBackendOperation();
1165   base::RunLoop().RunUntilIdle();
1166   // Register should be blocked while storing to the backend.
1167   EXPECT_FALSE(register_called);
1168   EXPECT_FALSE(get_registrations_called);
1169 
1170   test_background_sync_manager()->ResumeBackendOperation();
1171   base::RunLoop().RunUntilIdle();
1172   EXPECT_TRUE(register_called);
1173   EXPECT_EQ(BACKGROUND_SYNC_STATUS_OK, one_shot_sync_callback_status_);
1174   // GetRegistrations should run immediately as it doesn't write to disk.
1175   EXPECT_TRUE(get_registrations_called);
1176 }
1177 
TEST_F(BackgroundSyncManagerTest,UnregisterServiceWorker)1178 TEST_F(BackgroundSyncManagerTest, UnregisterServiceWorker) {
1179   EXPECT_TRUE(Register(sync_options_1_));
1180   UnregisterServiceWorker(sw_registration_id_1_);
1181   EXPECT_FALSE(GetRegistration(sync_options_1_));
1182 }
1183 
TEST_F(BackgroundSyncManagerTest,UnregisterServiceWorkerDuringSyncRegistration)1184 TEST_F(BackgroundSyncManagerTest,
1185        UnregisterServiceWorkerDuringSyncRegistration) {
1186   EXPECT_TRUE(Register(sync_options_1_));
1187   sync_options_2_.min_interval = 3600;
1188 
1189   test_background_sync_manager()->set_delay_backend(true);
1190   bool callback_called = false;
1191   test_background_sync_manager()->Register(
1192       sw_registration_id_1_, sync_options_2_,
1193       base::BindOnce(
1194           &BackgroundSyncManagerTest::StatusAndPeriodicSyncRegistrationCallback,
1195           base::Unretained(this), &callback_called));
1196 
1197   base::RunLoop().RunUntilIdle();
1198   EXPECT_FALSE(callback_called);
1199   UnregisterServiceWorker(sw_registration_id_1_);
1200 
1201   test_background_sync_manager()->ResumeBackendOperation();
1202   base::RunLoop().RunUntilIdle();
1203   EXPECT_TRUE(callback_called);
1204   EXPECT_EQ(BACKGROUND_SYNC_STATUS_STORAGE_ERROR,
1205             periodic_sync_callback_status_);
1206 
1207   test_background_sync_manager()->set_delay_backend(false);
1208   EXPECT_FALSE(GetRegistration(sync_options_1_));
1209 }
1210 
TEST_F(BackgroundSyncManagerTest,DeleteAndStartOverServiceWorkerContext)1211 TEST_F(BackgroundSyncManagerTest, DeleteAndStartOverServiceWorkerContext) {
1212   EXPECT_TRUE(Register(sync_options_1_));
1213   DeleteServiceWorkerAndStartOver();
1214   EXPECT_FALSE(GetRegistration(sync_options_1_));
1215 }
1216 
TEST_F(BackgroundSyncManagerTest,DisabledManagerWorksAfterBrowserRestart)1217 TEST_F(BackgroundSyncManagerTest, DisabledManagerWorksAfterBrowserRestart) {
1218   EXPECT_TRUE(Register(sync_options_1_));
1219   test_background_sync_manager()->set_corrupt_backend(true);
1220   EXPECT_FALSE(Register(sync_options_2_));
1221 
1222   // The manager is now disabled and not accepting new requests until browser
1223   // restart or notification that the storage has been wiped.
1224   test_background_sync_manager()->set_corrupt_backend(false);
1225   EXPECT_FALSE(GetRegistration(sync_options_1_));
1226   EXPECT_FALSE(Register(sync_options_2_));
1227 
1228   // Simulate restarting the browser by creating a new BackgroundSyncManager.
1229   SetupBackgroundSyncManager();
1230   EXPECT_TRUE(GetRegistration(sync_options_1_));
1231   EXPECT_TRUE(Register(sync_options_2_));
1232 }
1233 
TEST_F(BackgroundSyncManagerTest,DisabledManagerWorksAfterDeleteAndStartOver)1234 TEST_F(BackgroundSyncManagerTest, DisabledManagerWorksAfterDeleteAndStartOver) {
1235   EXPECT_TRUE(Register(sync_options_1_));
1236   test_background_sync_manager()->set_corrupt_backend(true);
1237   EXPECT_FALSE(Register(sync_options_2_));
1238 
1239   // The manager is now disabled and not accepting new requests until browser
1240   // restart or notification that the storage has been wiped.
1241   test_background_sync_manager()->set_corrupt_backend(false);
1242   DeleteServiceWorkerAndStartOver();
1243 
1244   RegisterServiceWorkers();
1245 
1246   EXPECT_TRUE(Register(sync_options_2_));
1247   EXPECT_FALSE(GetRegistration(sync_options_1_));
1248   EXPECT_TRUE(GetRegistration(sync_options_2_));
1249 }
1250 
TEST_F(BackgroundSyncManagerTest,RegistrationEqualsTag)1251 TEST_F(BackgroundSyncManagerTest, RegistrationEqualsTag) {
1252   BackgroundSyncRegistration reg_1;
1253   BackgroundSyncRegistration reg_2;
1254   EXPECT_TRUE(reg_1.Equals(reg_2));
1255   reg_2.options()->tag = "bar";
1256   EXPECT_FALSE(reg_1.Equals(reg_2));
1257 }
1258 
TEST_F(BackgroundSyncManagerTest,StoreAndRetrievePreservesValues)1259 TEST_F(BackgroundSyncManagerTest, StoreAndRetrievePreservesValues) {
1260   InitDelayedSyncEventTest();
1261   blink::mojom::SyncRegistrationOptions options;
1262 
1263   // Set non-default values for each field.
1264   options.tag = "foo";
1265 
1266   // Store the registration.
1267   EXPECT_TRUE(Register(options));
1268 
1269   // Simulate restarting the sync manager, forcing the next read to come from
1270   // disk.
1271   SetupBackgroundSyncManager();
1272 
1273   EXPECT_TRUE(GetRegistration(options));
1274   EXPECT_TRUE(options.Equals(*callback_one_shot_sync_registration_->options()));
1275 }
1276 
TEST_F(BackgroundSyncManagerTest,EmptyTagSupported)1277 TEST_F(BackgroundSyncManagerTest, EmptyTagSupported) {
1278   sync_options_1_.tag = "";
1279   EXPECT_TRUE(Register(sync_options_1_));
1280   EXPECT_TRUE(GetRegistration(sync_options_1_));
1281   EXPECT_TRUE(
1282       sync_options_1_.Equals(*callback_one_shot_sync_registration_->options()));
1283 }
1284 
TEST_F(BackgroundSyncManagerTest,PeriodicSyncOptions)1285 TEST_F(BackgroundSyncManagerTest, PeriodicSyncOptions) {
1286   sync_options_1_.min_interval = 2;
1287   EXPECT_TRUE(Register(sync_options_1_));
1288   EXPECT_TRUE(GetRegistration(sync_options_1_));
1289   EXPECT_TRUE(
1290       sync_options_1_.Equals(*callback_periodic_sync_registration_->options()));
1291 }
1292 
TEST_F(BackgroundSyncManagerTest,BothTypesOfSyncShareATag)1293 TEST_F(BackgroundSyncManagerTest, BothTypesOfSyncShareATag) {
1294   sync_options_1_.tag = "foo";
1295   sync_options_2_.tag = "foo";
1296   // Make the registration periodic.
1297   sync_options_2_.min_interval = 36000;
1298 
1299   EXPECT_TRUE(Register(sync_options_1_));
1300   EXPECT_TRUE(GetRegistration(sync_options_1_));
1301   EXPECT_EQ(callback_one_shot_sync_registration_->options()->tag, "foo");
1302   EXPECT_TRUE(
1303       sync_options_1_.Equals(*callback_one_shot_sync_registration_->options()));
1304 
1305   EXPECT_TRUE(Register(sync_options_2_));
1306   EXPECT_TRUE(GetRegistration(sync_options_2_));
1307   EXPECT_TRUE(
1308       sync_options_2_.Equals(*callback_periodic_sync_registration_->options()));
1309   EXPECT_EQ(callback_periodic_sync_registration_->options()->tag, "foo");
1310 }
1311 
TEST_F(BackgroundSyncManagerTest,FiresOnRegistration)1312 TEST_F(BackgroundSyncManagerTest, FiresOnRegistration) {
1313   InitSyncEventTest();
1314 
1315   EXPECT_TRUE(Register(sync_options_1_));
1316   EXPECT_EQ(1, sync_events_called_);
1317   EXPECT_FALSE(GetRegistration(sync_options_1_));
1318 }
1319 
TEST_F(BackgroundSyncManagerTest,PeriodicSyncFiresWhenExpected)1320 TEST_F(BackgroundSyncManagerTest, PeriodicSyncFiresWhenExpected) {
1321   InitPeriodicSyncEventTest();
1322   base::TimeDelta thirteen_hours = base::TimeDelta::FromHours(13);
1323   sync_options_2_.min_interval = thirteen_hours.InMilliseconds();
1324 
1325   EXPECT_TRUE(Register(sync_options_2_));
1326   EXPECT_EQ(0, periodic_sync_events_called_);
1327   EXPECT_TRUE(GetRegistration(sync_options_2_));
1328 
1329   // Advance clock.
1330   test_clock_.Advance(thirteen_hours);
1331   FireReadyEvents();
1332   base::RunLoop().RunUntilIdle();
1333 
1334   EXPECT_EQ(1, periodic_sync_events_called_);
1335   EXPECT_TRUE(GetRegistration(sync_options_2_));
1336 
1337   // Advance clock again.
1338   test_clock_.Advance(thirteen_hours);
1339   FireReadyEvents();
1340   base::RunLoop().RunUntilIdle();
1341 
1342   EXPECT_EQ(2, periodic_sync_events_called_);
1343   EXPECT_TRUE(GetRegistration(sync_options_2_));
1344 }
1345 
TEST_F(BackgroundSyncManagerTest,TestSupensionAndRevival)1346 TEST_F(BackgroundSyncManagerTest, TestSupensionAndRevival) {
1347   InitPeriodicSyncEventTest();
1348   auto thirteen_hours = base::TimeDelta::FromHours(13);
1349   sync_options_2_.min_interval = thirteen_hours.InMilliseconds();
1350   sync_options_1_.min_interval = thirteen_hours.InMilliseconds();
1351 
1352   auto origin = url::Origin::Create(GURL(kScope1).GetOrigin());
1353 
1354   SuspendPeriodicSyncRegistrations({origin});
1355   EXPECT_TRUE(Register(sync_options_1_));
1356   EXPECT_TRUE(GetRegistration(sync_options_1_));
1357   EXPECT_TRUE(Register(sync_options_2_));
1358   EXPECT_TRUE(GetRegistration(sync_options_2_));
1359   EXPECT_EQ(0, periodic_sync_events_called_);
1360 
1361   // Advance clock.
1362   test_clock_.Advance(thirteen_hours);
1363   FireReadyEvents();
1364   base::RunLoop().RunUntilIdle();
1365   EXPECT_EQ(0, periodic_sync_events_called_);
1366   EXPECT_TRUE(GetRegistration(sync_options_1_));
1367   EXPECT_TRUE(GetRegistration(sync_options_2_));
1368 
1369   RevivePeriodicSyncRegistrations(std::move(origin));
1370   base::RunLoop().RunUntilIdle();
1371 
1372   // Advance clock.
1373   test_clock_.Advance(thirteen_hours);
1374   FireReadyEvents();
1375   base::RunLoop().RunUntilIdle();
1376   EXPECT_EQ(2, periodic_sync_events_called_);
1377   EXPECT_TRUE(GetRegistration(sync_options_1_));
1378   EXPECT_TRUE(GetRegistration(sync_options_2_));
1379   Unregister(sync_options_1_);
1380   Unregister(sync_options_2_);
1381 }
1382 
TEST_F(BackgroundSyncManagerTest,UnregisterForOrigin)1383 TEST_F(BackgroundSyncManagerTest, UnregisterForOrigin) {
1384   InitPeriodicSyncEventTest();
1385   auto thirteen_hours = base::TimeDelta::FromHours(13);
1386   sync_options_2_.min_interval = thirteen_hours.InMilliseconds();
1387   sync_options_1_.min_interval = thirteen_hours.InMilliseconds();
1388 
1389   auto origin = url::Origin::Create(GURL(kScope1).GetOrigin());
1390 
1391   EXPECT_TRUE(Register(sync_options_1_));
1392   EXPECT_TRUE(GetRegistration(sync_options_1_));
1393   EXPECT_TRUE(Register(sync_options_2_));
1394   EXPECT_TRUE(GetRegistration(sync_options_2_));
1395 
1396   BlockContentSettingFor(std::move(origin));
1397   base::RunLoop().RunUntilIdle();
1398 
1399   EXPECT_FALSE(GetRegistration(sync_options_1_));
1400   EXPECT_FALSE(GetRegistration(sync_options_2_));
1401 }
1402 
TEST_F(BackgroundSyncManagerTest,ReregisterMidSyncFirstAttemptFails)1403 TEST_F(BackgroundSyncManagerTest, ReregisterMidSyncFirstAttemptFails) {
1404   InitDelayedSyncEventTest();
1405   RegisterAndVerifySyncEventDelayed(sync_options_1_);
1406 
1407   // Reregister the event mid-sync
1408   EXPECT_TRUE(Register(sync_options_1_));
1409 
1410   // The first sync attempt fails.
1411   ASSERT_TRUE(sync_fired_callback_);
1412   std::move(sync_fired_callback_)
1413       .Run(blink::ServiceWorkerStatusCode::kErrorEventWaitUntilRejected);
1414   base::RunLoop().RunUntilIdle();
1415 
1416   // It should fire again since it was reregistered mid-sync.
1417   EXPECT_TRUE(GetRegistration(sync_options_1_));
1418   ASSERT_TRUE(sync_fired_callback_);
1419   std::move(sync_fired_callback_).Run(blink::ServiceWorkerStatusCode::kOk);
1420   EXPECT_FALSE(GetRegistration(sync_options_1_));
1421 }
1422 
TEST_F(BackgroundSyncManagerTest,RunCallbackAfterEventsComplete)1423 TEST_F(BackgroundSyncManagerTest, RunCallbackAfterEventsComplete) {
1424   SetKeepBrowserAwakeTillEventsCompleteAndRestartManager(
1425       /* keep_browser_awake_till_events_complete= */ true);
1426   InitDelayedSyncEventTest();
1427 
1428   // This ensures other invocations of FireReadyEvents won't complete the
1429   // registration.
1430   test_background_sync_manager()->SuspendFiringEvents();
1431 
1432   EXPECT_TRUE(Register(sync_options_1_));
1433 
1434   bool callback_called = false;
1435   test_background_sync_manager()->ResumeFiringEvents();
1436   test_background_sync_manager()->FireReadyEvents(
1437       blink::mojom::BackgroundSyncType::ONE_SHOT,
1438       /* reschedule= */ false,
1439       base::BindOnce([](bool* callback_called) { *callback_called = true; },
1440                      &callback_called));
1441 
1442   base::RunLoop().RunUntilIdle();
1443 
1444   ASSERT_FALSE(callback_called);
1445   std::move(sync_fired_callback_).Run(blink::ServiceWorkerStatusCode::kOk);
1446   base::RunLoop().RunUntilIdle();
1447   EXPECT_TRUE(callback_called);
1448 }
1449 
TEST_F(BackgroundSyncManagerTest,ReregisterMidSyncFirstAttemptSucceeds)1450 TEST_F(BackgroundSyncManagerTest, ReregisterMidSyncFirstAttemptSucceeds) {
1451   InitDelayedSyncEventTest();
1452   RegisterAndVerifySyncEventDelayed(sync_options_1_);
1453 
1454   // Reregister the event mid-sync
1455   EXPECT_TRUE(Register(sync_options_1_));
1456 
1457   // The first sync event succeeds.
1458   ASSERT_TRUE(sync_fired_callback_);
1459   std::move(sync_fired_callback_).Run(blink::ServiceWorkerStatusCode::kOk);
1460   base::RunLoop().RunUntilIdle();
1461 
1462   // It should fire again since it was reregistered mid-sync.
1463   EXPECT_TRUE(GetRegistration(sync_options_1_));
1464   ASSERT_TRUE(sync_fired_callback_);
1465   std::move(sync_fired_callback_).Run(blink::ServiceWorkerStatusCode::kOk);
1466   EXPECT_FALSE(GetRegistration(sync_options_1_));
1467 }
1468 
TEST_F(BackgroundSyncManagerTest,OverwritePendingRegistration)1469 TEST_F(BackgroundSyncManagerTest, OverwritePendingRegistration) {
1470   InitFailedSyncEventTest();
1471 
1472   // Prevent the first sync from running so that it stays in a pending state.
1473   SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
1474   EXPECT_TRUE(Register(sync_options_1_));
1475   EXPECT_TRUE(GetRegistration(sync_options_1_));
1476 
1477   // Overwrite the first sync. It should still be pending.
1478   EXPECT_TRUE(Register(sync_options_1_));
1479   EXPECT_TRUE(GetRegistration(sync_options_1_));
1480 
1481   // Verify that it only gets to run once.
1482   SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
1483   base::RunLoop().RunUntilIdle();
1484   EXPECT_EQ(1, sync_events_called_);
1485   EXPECT_FALSE(GetRegistration(sync_options_1_));
1486 }
1487 
TEST_F(BackgroundSyncManagerTest,DisableWhilePending)1488 TEST_F(BackgroundSyncManagerTest, DisableWhilePending) {
1489   InitDelayedSyncEventTest();
1490   SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
1491   base::RunLoop().RunUntilIdle();
1492   EXPECT_TRUE(Register(sync_options_1_));
1493 
1494   // Corrupting the backend should result in the manager disabling itself on the
1495   // next operation.
1496   test_background_sync_manager()->set_corrupt_backend(true);
1497   EXPECT_FALSE(Register(sync_options_2_));
1498 
1499   test_background_sync_manager()->set_corrupt_backend(false);
1500   SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
1501   base::RunLoop().RunUntilIdle();
1502   EXPECT_EQ(0, sync_events_called_);
1503 }
1504 
TEST_F(BackgroundSyncManagerTest,DisableWhileFiring)1505 TEST_F(BackgroundSyncManagerTest, DisableWhileFiring) {
1506   InitDelayedSyncEventTest();
1507 
1508   // Register a one-shot that pauses mid-fire.
1509   RegisterAndVerifySyncEventDelayed(sync_options_1_);
1510 
1511   // Corrupting the backend should result in the manager disabling itself on the
1512   // next operation.
1513   test_background_sync_manager()->set_corrupt_backend(true);
1514   EXPECT_FALSE(Register(sync_options_2_));
1515   test_background_sync_manager()->set_corrupt_backend(false);
1516 
1517   // Successfully complete the firing event. We can't verify that it actually
1518   // completed but at least we can test that it doesn't crash.
1519   ASSERT_TRUE(sync_fired_callback_);
1520   std::move(sync_fired_callback_).Run(blink::ServiceWorkerStatusCode::kOk);
1521   base::RunLoop().RunUntilIdle();
1522 }
1523 
TEST_F(BackgroundSyncManagerTest,FiresOnNetworkChange)1524 TEST_F(BackgroundSyncManagerTest, FiresOnNetworkChange) {
1525   InitSyncEventTest();
1526 
1527   SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
1528   EXPECT_TRUE(Register(sync_options_1_));
1529   EXPECT_EQ(0, sync_events_called_);
1530   EXPECT_TRUE(GetRegistration(sync_options_1_));
1531 
1532   SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
1533   base::RunLoop().RunUntilIdle();
1534   EXPECT_EQ(1, sync_events_called_);
1535   EXPECT_FALSE(GetRegistration(sync_options_1_));
1536 }
1537 
TEST_F(BackgroundSyncManagerTest,MultipleRegistrationsFireOnNetworkChange)1538 TEST_F(BackgroundSyncManagerTest, MultipleRegistrationsFireOnNetworkChange) {
1539   InitSyncEventTest();
1540 
1541   SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
1542   EXPECT_TRUE(Register(sync_options_1_));
1543   EXPECT_TRUE(Register(sync_options_2_));
1544   EXPECT_EQ(0, sync_events_called_);
1545   EXPECT_TRUE(GetRegistration(sync_options_1_));
1546   EXPECT_TRUE(GetRegistration(sync_options_2_));
1547 
1548   SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
1549 
1550   EXPECT_EQ(2, sync_events_called_);
1551   EXPECT_FALSE(GetRegistration(sync_options_1_));
1552   EXPECT_FALSE(GetRegistration(sync_options_2_));
1553 }
1554 
TEST_F(BackgroundSyncManagerTest,FiresOnManagerRestart)1555 TEST_F(BackgroundSyncManagerTest, FiresOnManagerRestart) {
1556   InitSyncEventTest();
1557 
1558   // Initially the event won't run because there is no network.
1559   SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
1560   EXPECT_TRUE(Register(sync_options_1_));
1561   EXPECT_EQ(0, sync_events_called_);
1562   EXPECT_TRUE(GetRegistration(sync_options_1_));
1563 
1564   // Simulate closing the browser.
1565   DeleteBackgroundSyncManager();
1566 
1567   // The next time the manager is started, the network is good.
1568   SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
1569   SetupBackgroundSyncManager();
1570   InitSyncEventTest();
1571 
1572   // The event should have fired.
1573   EXPECT_EQ(1, sync_events_called_);
1574   EXPECT_FALSE(GetRegistration(sync_options_1_));
1575 }
1576 
TEST_F(BackgroundSyncManagerTest,FailedRegistrationShouldBeRemoved)1577 TEST_F(BackgroundSyncManagerTest, FailedRegistrationShouldBeRemoved) {
1578   InitFailedSyncEventTest();
1579 
1580   EXPECT_TRUE(Register(sync_options_1_));
1581   EXPECT_EQ(1, sync_events_called_);
1582   EXPECT_FALSE(GetRegistration(sync_options_1_));
1583 }
1584 
TEST_F(BackgroundSyncManagerTest,FailedRegistrationReregisteredAndFires)1585 TEST_F(BackgroundSyncManagerTest, FailedRegistrationReregisteredAndFires) {
1586   InitFailedSyncEventTest();
1587 
1588   // The initial sync event fails.
1589   EXPECT_TRUE(Register(sync_options_1_));
1590   EXPECT_EQ(1, sync_events_called_);
1591   EXPECT_FALSE(GetRegistration(sync_options_1_));
1592 
1593   InitSyncEventTest();
1594 
1595   // Reregistering should cause the sync event to fire again, this time
1596   // succeeding.
1597   EXPECT_TRUE(Register(sync_options_1_));
1598   EXPECT_EQ(2, sync_events_called_);
1599   EXPECT_FALSE(GetRegistration(sync_options_1_));
1600 }
1601 
TEST_F(BackgroundSyncManagerTest,DelayMidSync)1602 TEST_F(BackgroundSyncManagerTest, DelayMidSync) {
1603   InitDelayedSyncEventTest();
1604 
1605   RegisterAndVerifySyncEventDelayed(sync_options_1_);
1606 
1607   // Finish firing the event and verify that the registration is removed.
1608   ASSERT_TRUE(sync_fired_callback_);
1609   std::move(sync_fired_callback_).Run(blink::ServiceWorkerStatusCode::kOk);
1610   base::RunLoop().RunUntilIdle();
1611   EXPECT_EQ(1, sync_events_called_);
1612   EXPECT_FALSE(GetRegistration(sync_options_1_));
1613 }
1614 
TEST_F(BackgroundSyncManagerTest,BadBackendMidSync)1615 TEST_F(BackgroundSyncManagerTest, BadBackendMidSync) {
1616   InitDelayedSyncEventTest();
1617 
1618   RegisterAndVerifySyncEventDelayed(sync_options_1_);
1619 
1620   test_background_sync_manager()->set_corrupt_backend(true);
1621   ASSERT_TRUE(sync_fired_callback_);
1622   std::move(sync_fired_callback_).Run(blink::ServiceWorkerStatusCode::kOk);
1623   base::RunLoop().RunUntilIdle();
1624 
1625   // The backend should now be disabled because it couldn't unregister the
1626   // one-shot.
1627   EXPECT_FALSE(Register(sync_options_2_));
1628   EXPECT_FALSE(
1629       RegisterWithServiceWorkerId(sw_registration_id_2_, sync_options_2_));
1630 }
1631 
TEST_F(BackgroundSyncManagerTest,UnregisterServiceWorkerMidSync)1632 TEST_F(BackgroundSyncManagerTest, UnregisterServiceWorkerMidSync) {
1633   InitDelayedSyncEventTest();
1634 
1635   RegisterAndVerifySyncEventDelayed(sync_options_1_);
1636   UnregisterServiceWorker(sw_registration_id_1_);
1637 
1638   ASSERT_TRUE(sync_fired_callback_);
1639   std::move(sync_fired_callback_).Run(blink::ServiceWorkerStatusCode::kOk);
1640 
1641   // The backend isn't disabled, but the first service worker registration is
1642   // gone.
1643   EXPECT_FALSE(GetRegistration(sync_options_1_));
1644   EXPECT_FALSE(Register(sync_options_1_));
1645   EXPECT_TRUE(
1646       RegisterWithServiceWorkerId(sw_registration_id_2_, sync_options_1_));
1647 }
1648 
TEST_F(BackgroundSyncManagerTest,KillManagerMidSync)1649 TEST_F(BackgroundSyncManagerTest, KillManagerMidSync) {
1650   InitDelayedSyncEventTest();
1651 
1652   RegisterAndVerifySyncEventDelayed(sync_options_1_);
1653 
1654   // Create a new manager which should fire the sync again on init.
1655   SetupBackgroundSyncManager();
1656   InitSyncEventTest();
1657   EXPECT_FALSE(GetRegistration(sync_options_1_));
1658   EXPECT_EQ(2, sync_events_called_);
1659 }
1660 
TEST_F(BackgroundSyncManagerTest,RegisterWithoutMainFrame)1661 TEST_F(BackgroundSyncManagerTest, RegisterWithoutMainFrame) {
1662   test_background_sync_manager()->set_has_main_frame_window_client(false);
1663   EXPECT_FALSE(Register(sync_options_1_));
1664 }
1665 
TEST_F(BackgroundSyncManagerTest,RegisterExistingWithoutMainFrame)1666 TEST_F(BackgroundSyncManagerTest, RegisterExistingWithoutMainFrame) {
1667   EXPECT_TRUE(Register(sync_options_1_));
1668   test_background_sync_manager()->set_has_main_frame_window_client(false);
1669   EXPECT_FALSE(Register(sync_options_1_));
1670 }
1671 
TEST_F(BackgroundSyncManagerTest,DefaultParameters)1672 TEST_F(BackgroundSyncManagerTest, DefaultParameters) {
1673   *GetController()->background_sync_parameters() = BackgroundSyncParameters();
1674   // Restart the BackgroundSyncManager so that it updates its parameters.
1675   SetupBackgroundSyncManager();
1676 
1677   EXPECT_EQ(BackgroundSyncParameters(),
1678             *test_background_sync_manager()->background_sync_parameters());
1679 }
1680 
TEST_F(BackgroundSyncManagerTest,OverrideParameters)1681 TEST_F(BackgroundSyncManagerTest, OverrideParameters) {
1682   BackgroundSyncParameters* parameters =
1683       GetController()->background_sync_parameters();
1684   parameters->disable = true;
1685   parameters->max_sync_attempts = 100;
1686   parameters->initial_retry_delay = base::TimeDelta::FromMinutes(200);
1687   parameters->retry_delay_factor = 300;
1688   parameters->min_sync_recovery_time = base::TimeDelta::FromMinutes(400);
1689   parameters->max_sync_event_duration = base::TimeDelta::FromMinutes(500);
1690 
1691   // Restart the BackgroundSyncManager so that it updates its parameters.
1692   SetupBackgroundSyncManager();
1693 
1694   // Check that the manager is disabled
1695   EXPECT_FALSE(Register(sync_options_1_));
1696   EXPECT_EQ(BACKGROUND_SYNC_STATUS_STORAGE_ERROR,
1697             one_shot_sync_callback_status_);
1698 
1699   const BackgroundSyncParameters* manager_parameters =
1700       test_background_sync_manager()->background_sync_parameters();
1701   EXPECT_EQ(*parameters, *manager_parameters);
1702 }
1703 
TEST_F(BackgroundSyncManagerTest,DisablingFromControllerKeepsRegistrations)1704 TEST_F(BackgroundSyncManagerTest, DisablingFromControllerKeepsRegistrations) {
1705   EXPECT_TRUE(Register(sync_options_1_));
1706 
1707   BackgroundSyncParameters* parameters =
1708       GetController()->background_sync_parameters();
1709   parameters->disable = true;
1710 
1711   // Restart the BackgroundSyncManager so that it updates its parameters.
1712   SetupBackgroundSyncManager();
1713   EXPECT_FALSE(GetRegistration(sync_options_1_));  // fails because disabled
1714 
1715   // Reenable the BackgroundSyncManager on next launch
1716   parameters->disable = false;
1717 
1718   // Restart the BackgroundSyncManager so that it updates its parameters.
1719   SetupBackgroundSyncManager();
1720   EXPECT_TRUE(GetRegistration(sync_options_1_));
1721 }
1722 
TEST_F(BackgroundSyncManagerTest,DisabledPermanently)1723 TEST_F(BackgroundSyncManagerTest, DisabledPermanently) {
1724   BackgroundSyncParameters* parameters =
1725       GetController()->background_sync_parameters();
1726   parameters->disable = true;
1727 
1728   // Restart the BackgroundSyncManager so that it updates its parameters.
1729   SetupBackgroundSyncManager();
1730 
1731   // Check that the manager is disabled
1732   EXPECT_FALSE(Register(sync_options_1_));
1733   EXPECT_EQ(BACKGROUND_SYNC_STATUS_STORAGE_ERROR,
1734             one_shot_sync_callback_status_);
1735 
1736   // If the service worker is wiped and the manager is restarted, the manager
1737   // should stay disabled.
1738   DeleteServiceWorkerAndStartOver();
1739   RegisterServiceWorkers();
1740   EXPECT_FALSE(Register(sync_options_1_));
1741   EXPECT_EQ(BACKGROUND_SYNC_STATUS_STORAGE_ERROR,
1742             one_shot_sync_callback_status_);
1743 }
1744 
TEST_F(BackgroundSyncManagerTest,NotifyBackgroundSyncRegistered)1745 TEST_F(BackgroundSyncManagerTest, NotifyBackgroundSyncRegistered) {
1746   // Verify that the BackgroundSyncController is informed of registrations.
1747   EXPECT_EQ(0, GetController()->registration_count());
1748   EXPECT_TRUE(Register(sync_options_1_));
1749   EXPECT_EQ(1, GetController()->registration_count());
1750   EXPECT_EQ(url::Origin::Create(GURL(kScope1)),
1751             GetController()->registration_origin());
1752 }
1753 
1754 // TODO(crbug.com/996166): Update and enable when browser wake up logic has been
1755 // updated to not schedule a wakeup with delay of 0.
TEST_F(BackgroundSyncManagerTest,DISABLED_WakeBrowserCalledForOneShotSync)1756 TEST_F(BackgroundSyncManagerTest, DISABLED_WakeBrowserCalledForOneShotSync) {
1757   SetupBackgroundSyncManager();
1758   InitDelayedSyncEventTest();
1759 
1760   // The BackgroundSyncManager should declare in initialization
1761   // that it doesn't need to be woken up since it has no registrations.
1762   EXPECT_EQ(0, GetController()->run_in_background_count());
1763   EXPECT_FALSE(IsBrowserWakeupForOneShotSyncScheduled());
1764 
1765   SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
1766   EXPECT_FALSE(IsBrowserWakeupForOneShotSyncScheduled());
1767 
1768   // Register a one-shot but it can't fire due to lack of network, wake up is
1769   // required.
1770   Register(sync_options_1_);
1771   EXPECT_TRUE(IsBrowserWakeupForOneShotSyncScheduled());
1772 
1773   // Start the event but it will pause mid-sync due to
1774   // InitDelayedSyncEventTest() above.
1775   SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
1776   EXPECT_TRUE(IsBrowserWakeupForOneShotSyncScheduled());
1777   EXPECT_TRUE(EqualsSoonestOneShotWakeupDelta(test_background_sync_manager()
1778                                                   ->background_sync_parameters()
1779                                                   ->min_sync_recovery_time));
1780 
1781   // Finish the sync.
1782   ASSERT_TRUE(sync_fired_callback_);
1783   std::move(sync_fired_callback_).Run(blink::ServiceWorkerStatusCode::kOk);
1784   base::RunLoop().RunUntilIdle();
1785   EXPECT_FALSE(IsBrowserWakeupForOneShotSyncScheduled());
1786 }
1787 
TEST_F(BackgroundSyncManagerTest,WakeBrowserCalledForPeriodicSync)1788 TEST_F(BackgroundSyncManagerTest, WakeBrowserCalledForPeriodicSync) {
1789   SetupBackgroundSyncManager();
1790   InitDelayedPeriodicSyncEventTest();
1791 
1792   // The BackgroundSyncManager should declare in initialization
1793   // that it doesn't need to be woken up since it has no registrations.
1794   EXPECT_EQ(0, GetController()->run_in_background_periodic_sync_count());
1795   EXPECT_FALSE(IsBrowserWakeupForPeriodicSyncScheduled());
1796 
1797   SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
1798 
1799   // Register a periodic Background Sync but it can't fire due to lack of
1800   // network, wake up is required.
1801   base::TimeDelta thirteen_hours = base::TimeDelta::FromHours(13);
1802   sync_options_1_.min_interval = thirteen_hours.InMilliseconds();
1803   Register(sync_options_1_);
1804   EXPECT_TRUE(IsBrowserWakeupForPeriodicSyncScheduled());
1805   EXPECT_TRUE(EqualsSoonestPeriodicSyncWakeupDelta(thirteen_hours));
1806 
1807   // Advance clock.
1808   test_clock_.Advance(
1809       base::TimeDelta::FromMilliseconds(thirteen_hours.InMilliseconds()));
1810 
1811   // Start the event but it will pause mid-sync due to
1812   // InitDelayedPeriodicSyncEventTest() above.
1813   SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
1814   EXPECT_TRUE(IsBrowserWakeupForPeriodicSyncScheduled());
1815   EXPECT_TRUE(
1816       EqualsSoonestPeriodicSyncWakeupDelta(test_background_sync_manager()
1817                                                ->background_sync_parameters()
1818                                                ->min_sync_recovery_time));
1819 
1820   // Finish the sync.
1821   ASSERT_TRUE(periodic_sync_fired_callback_);
1822   std::move(periodic_sync_fired_callback_)
1823       .Run(blink::ServiceWorkerStatusCode::kOk);
1824   base::RunLoop().RunUntilIdle();
1825   EXPECT_TRUE(IsBrowserWakeupForPeriodicSyncScheduled());
1826   EXPECT_TRUE(EqualsSoonestPeriodicSyncWakeupDelta(thirteen_hours));
1827 }
1828 
TEST_F(BackgroundSyncManagerTest,GetSoonestWakeupDeltaConsidersSyncType)1829 TEST_F(BackgroundSyncManagerTest, GetSoonestWakeupDeltaConsidersSyncType) {
1830   // Register a one-shot sync.
1831   EXPECT_TRUE(Register(sync_options_1_));
1832   EXPECT_TRUE(GetRegistration(sync_options_1_));
1833 
1834   // Also register a Periodic sync.
1835   sync_options_2_.min_interval = 13 * 60 * 60 * 1000;
1836   EXPECT_TRUE(Register(sync_options_2_));
1837   EXPECT_TRUE(GetRegistration(sync_options_2_));
1838 
1839   EXPECT_EQ(GetSoonestWakeupDelta(
1840                 blink::mojom::BackgroundSyncType::ONE_SHOT,
1841                 /* last_browser_wakeup_for_periodic_sync= */ base::Time()),
1842             base::TimeDelta());
1843   EXPECT_EQ(GetSoonestWakeupDelta(
1844                 blink::mojom::BackgroundSyncType::PERIODIC,
1845                 /* last_browser_wakeup_for_periodic_sync= */ base::Time()),
1846             base::TimeDelta::FromMilliseconds(sync_options_2_.min_interval));
1847 }
1848 
TEST_F(BackgroundSyncManagerTest,SoonestWakeupDeltaDecreasesWithTime)1849 TEST_F(BackgroundSyncManagerTest, SoonestWakeupDeltaDecreasesWithTime) {
1850   // Register a periodic sync.
1851   int thirteen_hours_ms = 13 * 60 * 60 * 1000;
1852   sync_options_2_.min_interval = thirteen_hours_ms * 4;
1853   EXPECT_TRUE(Register(sync_options_2_));
1854   EXPECT_TRUE(GetRegistration(sync_options_2_));
1855 
1856   base::TimeDelta soonest_wakeup_delta_1 = GetSoonestWakeupDelta(
1857       blink::mojom::BackgroundSyncType::PERIODIC,
1858       /* last_browser_wakeup_for_periodic_sync= */ base::Time());
1859 
1860   test_clock_.Advance(base::TimeDelta::FromMilliseconds(thirteen_hours_ms));
1861   base::TimeDelta soonest_wakeup_delta_2 = GetSoonestWakeupDelta(
1862       blink::mojom::BackgroundSyncType::PERIODIC,
1863       /* last_browser_wakeup_for_periodic_sync= */ base::Time());
1864 
1865   test_clock_.Advance(base::TimeDelta::FromMilliseconds(thirteen_hours_ms));
1866   base::TimeDelta soonest_wakeup_delta_3 = GetSoonestWakeupDelta(
1867       blink::mojom::BackgroundSyncType::PERIODIC,
1868       /* last_browser_wakeup_for_periodic_sync= */ base::Time());
1869 
1870   test_clock_.Advance(base::TimeDelta::FromMilliseconds(thirteen_hours_ms));
1871   base::TimeDelta soonest_wakeup_delta_4 = GetSoonestWakeupDelta(
1872       blink::mojom::BackgroundSyncType::PERIODIC,
1873       /* last_browser_wakeup_for_periodic_sync= */ base::Time());
1874 
1875   EXPECT_GT(soonest_wakeup_delta_1, soonest_wakeup_delta_2);
1876   EXPECT_GT(soonest_wakeup_delta_2, soonest_wakeup_delta_3);
1877   EXPECT_GT(soonest_wakeup_delta_3, soonest_wakeup_delta_4);
1878 }
1879 
TEST_F(BackgroundSyncManagerTest,SoonestWakeupDeltaAppliesBrowserWakeupLimit)1880 TEST_F(BackgroundSyncManagerTest, SoonestWakeupDeltaAppliesBrowserWakeupLimit) {
1881   base::TimeDelta twelve_hours = base::TimeDelta::FromHours(12);
1882   SetPeriodicSyncEventsMinIntervalAndRestartManager(twelve_hours);
1883 
1884   // Register a periodic sync.
1885   // Hour zero.
1886   base::TimeDelta thirteen_hours = base::TimeDelta::FromHours(13);
1887   sync_options_1_.min_interval = thirteen_hours.InMilliseconds();
1888   EXPECT_TRUE(Register(sync_options_1_));
1889   EXPECT_TRUE(GetRegistration(sync_options_1_));
1890   EXPECT_EQ(GetSoonestWakeupDelta(
1891                 blink::mojom::BackgroundSyncType::PERIODIC,
1892                 /* last_browser_wakeup_for_periodic_sync= */ base::Time()),
1893             thirteen_hours);
1894 
1895   // Advance the clock by an hour.
1896   // Hour 1. Expect soonest_wakeup_delta to now be 12.
1897   base::TimeDelta one_hour = base::TimeDelta::FromHours(1);
1898   test_clock_.Advance(one_hour);
1899   EXPECT_EQ(GetSoonestWakeupDelta(
1900                 blink::mojom::BackgroundSyncType::PERIODIC,
1901                 /* last_browser_wakeup_for_periodic_sync= */ base::Time()),
1902             twelve_hours);
1903   // Advance the clock by 12 hours. Hour 13.
1904   test_clock_.Advance(base::TimeDelta::FromHours(9));
1905   base::Time browser_wakeup_time = test_clock_.Now();
1906   test_clock_.Advance(base::TimeDelta::FromHours(3));
1907   EXPECT_EQ(
1908       GetSoonestWakeupDelta(
1909           blink::mojom::BackgroundSyncType::PERIODIC,
1910           /* last_browser_wakeup_for_periodic_sync= */ browser_wakeup_time),
1911       base::TimeDelta::FromHours(9));
1912   EXPECT_EQ(GetSoonestWakeupDelta(
1913                 blink::mojom::BackgroundSyncType::PERIODIC,
1914                 /* last_browser_wakeup_for_periodic_sync= */ base::Time()),
1915             base::TimeDelta());
1916   Unregister(sync_options_1_);
1917 }
1918 
TEST_F(BackgroundSyncManagerTest,StaggeredPeriodicSyncRegistrations)1919 TEST_F(BackgroundSyncManagerTest, StaggeredPeriodicSyncRegistrations) {
1920   base::TimeDelta twelve_hours = base::TimeDelta::FromHours(12);
1921   SetPeriodicSyncEventsMinIntervalAndRestartManager(twelve_hours);
1922   InitPeriodicSyncEventTest();
1923   SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
1924 
1925   // Register a periodic sync.
1926   base::TimeDelta thirteen_hours = base::TimeDelta::FromHours(13);
1927   sync_options_1_.min_interval = thirteen_hours.InMilliseconds();
1928   EXPECT_TRUE(Register(sync_options_1_));
1929   EXPECT_TRUE(GetRegistration(sync_options_1_));
1930 
1931   EXPECT_EQ(GetSoonestWakeupDelta(
1932                 blink::mojom::BackgroundSyncType::PERIODIC,
1933                 /* last_browser_wakeup_for_periodic_sync= */ base::Time()),
1934             thirteen_hours);
1935 
1936   // Advance the clock by an hour. Add another registration.
1937   base::TimeDelta one_hour = base::TimeDelta::FromHours(1);
1938   test_clock_.Advance(one_hour);
1939   sync_options_2_.min_interval = thirteen_hours.InMilliseconds();
1940   EXPECT_EQ(GetSoonestWakeupDelta(
1941                 blink::mojom::BackgroundSyncType::PERIODIC,
1942                 /* last_browser_wakeup_for_periodic_sync= */ base::Time()),
1943             twelve_hours);
1944 
1945   // Advance the clock by 12 hours, and enable network connectivity, so the
1946   // first registration fires. Expect the next wakeup time to be longer than 1
1947   // hour, which is the stagger interval between the two registrations.
1948   test_clock_.Advance(twelve_hours);
1949   SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
1950   base::RunLoop().RunUntilIdle();
1951   EXPECT_GT(GetSoonestWakeupDelta(
1952                 blink::mojom::BackgroundSyncType::PERIODIC,
1953                 /* last_browser_wakeup_for_periodic_sync= */ base::Time()),
1954             one_hour);
1955 }
1956 
TEST_F(BackgroundSyncManagerTest,RelyOnAndroidNetworkDetection)1957 TEST_F(BackgroundSyncManagerTest, RelyOnAndroidNetworkDetection) {
1958   SetRelyOnAndroidNetworkDetectionAndRestartManager(
1959       /* rely_on_android_network_detection= */ true);
1960   InitSyncEventTest();
1961   SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
1962   EXPECT_TRUE(Register(sync_options_1_));
1963   SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
1964   base::RunLoop().RunUntilIdle();
1965 #if defined(OS_ANDROID)
1966   EXPECT_EQ(0, sync_events_called_);
1967   EXPECT_TRUE(GetRegistration(sync_options_1_));
1968 #else
1969   EXPECT_EQ(1, sync_events_called_);
1970   EXPECT_FALSE(GetRegistration(sync_options_1_));
1971 #endif
1972 }
1973 
TEST_F(BackgroundSyncManagerTest,OneAttempt)1974 TEST_F(BackgroundSyncManagerTest, OneAttempt) {
1975   SetMaxSyncAttemptsAndRestartManager(1);
1976   InitFailedSyncEventTest();
1977 
1978   // It should permanently fail after failing once.
1979   EXPECT_TRUE(Register(sync_options_1_));
1980   EXPECT_FALSE(GetRegistration(sync_options_1_));
1981 }
1982 
TEST_F(BackgroundSyncManagerTest,TwoFailedAttemptsForPeriodicSync)1983 TEST_F(BackgroundSyncManagerTest, TwoFailedAttemptsForPeriodicSync) {
1984   SetMaxSyncAttemptsAndRestartManager(2);
1985   InitFailedPeriodicSyncEventTest();
1986 
1987   base::TimeDelta thirteen_hours = base::TimeDelta::FromHours(13);
1988   sync_options_2_.min_interval = thirteen_hours.InMilliseconds();
1989 
1990   EXPECT_TRUE(Register(sync_options_2_));
1991   EXPECT_TRUE(GetRegistration(sync_options_2_));
1992   EXPECT_EQ(0, periodic_sync_events_called_);
1993 
1994   // Advance clock.
1995   test_clock_.Advance(thirteen_hours);
1996   FireReadyEvents();
1997   base::RunLoop().RunUntilIdle();
1998 
1999   EXPECT_EQ(1, periodic_sync_events_called_);
2000   EXPECT_TRUE(GetRegistration(sync_options_2_));
2001 
2002   // Since this one failed, a wakeup/delayed task will be scheduled for retries
2003   // after five minutes.
2004   EXPECT_EQ(base::TimeDelta::FromMinutes(5),
2005             delayed_periodic_sync_task_delta());
2006   test_clock_.Advance(base::TimeDelta::FromMinutes(5));
2007   FireReadyEvents();
2008   base::RunLoop().RunUntilIdle();
2009 
2010   EXPECT_EQ(2, periodic_sync_events_called_);
2011   EXPECT_TRUE(GetRegistration(sync_options_2_));
2012 
2013   // Second attempt would also fail, resetting to next thirteen_hours.
2014   // Expect nothing after just another hour.
2015   test_clock_.Advance(base::TimeDelta::FromHours(1));
2016   FireReadyEvents();
2017   base::RunLoop().RunUntilIdle();
2018 
2019   EXPECT_EQ(2, periodic_sync_events_called_);
2020 
2021   // Expect the next event after another twelve hours.
2022   test_clock_.Advance(base::TimeDelta::FromHours(12));
2023   FireReadyEvents();
2024   base::RunLoop().RunUntilIdle();
2025 
2026   EXPECT_EQ(3, periodic_sync_events_called_);
2027   EXPECT_TRUE(GetRegistration(sync_options_2_));
2028 }
2029 
TEST_F(BackgroundSyncManagerTest,TwoAttempts)2030 TEST_F(BackgroundSyncManagerTest, TwoAttempts) {
2031   SetMaxSyncAttemptsAndRestartManager(2);
2032   InitFailedSyncEventTest();
2033 
2034   // The first run will fail but it will setup a timer to try again.
2035   EXPECT_TRUE(Register(sync_options_1_));
2036   EXPECT_TRUE(GetRegistration(sync_options_1_));
2037   EXPECT_TRUE(IsDelayedTaskScheduledOneShotSync());
2038 
2039   // Make sure the delay is reasonable.
2040   EXPECT_LT(base::TimeDelta::FromMinutes(1),
2041             delayed_one_shot_sync_task_delta());
2042   EXPECT_GT(base::TimeDelta::FromHours(1), delayed_one_shot_sync_task_delta());
2043 
2044   // Fire again and this time it should permanently fail.
2045   test_clock_.Advance(delayed_one_shot_sync_task_delta());
2046   RunOneShotSyncDelayedTask();
2047   base::RunLoop().RunUntilIdle();
2048   EXPECT_FALSE(GetRegistration(sync_options_1_));
2049 }
2050 
TEST_F(BackgroundSyncManagerTest,ThreeAttempts)2051 TEST_F(BackgroundSyncManagerTest, ThreeAttempts) {
2052   SetMaxSyncAttemptsAndRestartManager(3);
2053   InitFailedSyncEventTest();
2054 
2055   // The first run will fail but it will setup a timer to try again.
2056   EXPECT_TRUE(Register(sync_options_1_));
2057   EXPECT_TRUE(GetRegistration(sync_options_1_));
2058   EXPECT_TRUE(IsDelayedTaskScheduledOneShotSync());
2059 
2060   // The second run will fail but it will setup a timer to try again.
2061   base::TimeDelta first_delta = delayed_one_shot_sync_task_delta();
2062   test_clock_.Advance(delayed_one_shot_sync_task_delta());
2063   RunOneShotSyncDelayedTask();
2064   base::RunLoop().RunUntilIdle();
2065   EXPECT_TRUE(GetRegistration(sync_options_1_));
2066 
2067   // Verify that the delta grows for each attempt.
2068   EXPECT_LT(first_delta, delayed_one_shot_sync_task_delta());
2069 
2070   // The third run will permanently fail.
2071   test_clock_.Advance(delayed_one_shot_sync_task_delta());
2072   RunOneShotSyncDelayedTask();
2073   base::RunLoop().RunUntilIdle();
2074   EXPECT_FALSE(GetRegistration(sync_options_1_));
2075 }
2076 
TEST_F(BackgroundSyncManagerTest,WaitsFullDelayTime)2077 TEST_F(BackgroundSyncManagerTest, WaitsFullDelayTime) {
2078   SetMaxSyncAttemptsAndRestartManager(2);
2079   InitFailedSyncEventTest();
2080 
2081   // The first run will fail but it will setup a timer to try again.
2082   EXPECT_TRUE(Register(sync_options_1_));
2083   EXPECT_TRUE(GetRegistration(sync_options_1_));
2084   EXPECT_TRUE(IsDelayedTaskScheduledOneShotSync());
2085 
2086   // Fire again one second before it's ready to retry. Expect it to reschedule
2087   // the delay timer for one more second.
2088   test_clock_.Advance(delayed_one_shot_sync_task_delta() -
2089                       base::TimeDelta::FromSeconds(1));
2090   FireReadyEvents();
2091   base::RunLoop().RunUntilIdle();
2092   EXPECT_TRUE(GetRegistration(sync_options_1_));
2093   EXPECT_EQ(base::TimeDelta::FromSeconds(1),
2094             delayed_one_shot_sync_task_delta());
2095 
2096   // Fire one second later and it should fail permanently.
2097   test_clock_.Advance(base::TimeDelta::FromSeconds(1));
2098   RunOneShotSyncDelayedTask();
2099   base::RunLoop().RunUntilIdle();
2100   EXPECT_FALSE(GetRegistration(sync_options_1_));
2101 }
2102 
TEST_F(BackgroundSyncManagerTest,RetryOnBrowserRestart)2103 TEST_F(BackgroundSyncManagerTest, RetryOnBrowserRestart) {
2104   SetMaxSyncAttemptsAndRestartManager(2);
2105   InitFailedSyncEventTest();
2106 
2107   // The first run will fail but it will setup a timer to try again.
2108   EXPECT_TRUE(Register(sync_options_1_));
2109   EXPECT_TRUE(GetRegistration(sync_options_1_));
2110 
2111   // Simulate restarting the browser after sufficient time has passed.
2112   base::TimeDelta delta = delayed_one_shot_sync_task_delta();
2113   CreateBackgroundSyncManager();
2114   InitFailedSyncEventTest();
2115   test_clock_.Advance(delta);
2116   InitBackgroundSyncManager();
2117   base::RunLoop().RunUntilIdle();
2118   EXPECT_FALSE(GetRegistration(sync_options_1_));
2119 }
2120 
TEST_F(BackgroundSyncManagerTest,RescheduleOnBrowserRestart)2121 TEST_F(BackgroundSyncManagerTest, RescheduleOnBrowserRestart) {
2122   SetMaxSyncAttemptsAndRestartManager(2);
2123   InitFailedSyncEventTest();
2124 
2125   // The first run will fail but it will setup a timer to try again.
2126   EXPECT_TRUE(Register(sync_options_1_));
2127   EXPECT_TRUE(GetRegistration(sync_options_1_));
2128 
2129   // Simulate restarting the browser before the retry timer has expired.
2130   base::TimeDelta delta = delayed_one_shot_sync_task_delta();
2131   CreateBackgroundSyncManager();
2132   InitFailedSyncEventTest();
2133   test_clock_.Advance(delta - base::TimeDelta::FromSeconds(1));
2134   InitBackgroundSyncManager();
2135   base::RunLoop().RunUntilIdle();
2136   EXPECT_TRUE(GetRegistration(sync_options_1_));
2137   EXPECT_EQ(base::TimeDelta::FromSeconds(1),
2138             delayed_one_shot_sync_task_delta());
2139 }
2140 
TEST_F(BackgroundSyncManagerTest,RetryIfClosedMidSync)2141 TEST_F(BackgroundSyncManagerTest, RetryIfClosedMidSync) {
2142   InitDelayedSyncEventTest();
2143 
2144   RegisterAndVerifySyncEventDelayed(sync_options_1_);
2145   // The time delta is the recovery timer.
2146   base::TimeDelta delta = delayed_one_shot_sync_task_delta();
2147 
2148   // Simulate restarting the browser after the recovery time, the event should
2149   // fire once and then fail permanently.
2150   CreateBackgroundSyncManager();
2151   InitFailedSyncEventTest();
2152   test_clock_.Advance(delta);
2153   InitBackgroundSyncManager();
2154   base::RunLoop().RunUntilIdle();
2155   EXPECT_FALSE(GetRegistration(sync_options_1_));
2156 }
2157 
TEST_F(BackgroundSyncManagerTest,AllTestsEventuallyFire)2158 TEST_F(BackgroundSyncManagerTest, AllTestsEventuallyFire) {
2159   SetMaxSyncAttemptsAndRestartManager(3);
2160   InitFailedSyncEventTest();
2161 
2162   // The first run will fail but it will setup a timer to try again.
2163   EXPECT_TRUE(Register(sync_options_1_));
2164 
2165   // Run it a second time.
2166   test_clock_.Advance(delayed_one_shot_sync_task_delta());
2167   RunOneShotSyncDelayedTask();
2168   base::RunLoop().RunUntilIdle();
2169 
2170   base::TimeDelta delay_delta = delayed_one_shot_sync_task_delta();
2171 
2172   // Create a second registration, which will fail and setup a timer.
2173   EXPECT_TRUE(Register(sync_options_2_));
2174   EXPECT_GT(delay_delta, delayed_one_shot_sync_task_delta());
2175 
2176   while (IsDelayedTaskScheduledOneShotSync()) {
2177     test_clock_.Advance(delayed_one_shot_sync_task_delta());
2178     RunOneShotSyncDelayedTask();
2179     EXPECT_FALSE(IsDelayedTaskScheduledOneShotSync());
2180     base::RunLoop().RunUntilIdle();
2181   }
2182 
2183   EXPECT_FALSE(GetRegistration(sync_options_1_));
2184   EXPECT_FALSE(GetRegistration(sync_options_2_));
2185 }
2186 
TEST_F(BackgroundSyncManagerTest,LastChance)2187 TEST_F(BackgroundSyncManagerTest, LastChance) {
2188   SetMaxSyncAttemptsAndRestartManager(2);
2189   InitFailedSyncEventTest();
2190 
2191   EXPECT_TRUE(Register(sync_options_1_));
2192   EXPECT_FALSE(test_background_sync_manager()->last_chance());
2193   EXPECT_TRUE(GetRegistration(sync_options_1_));
2194 
2195   // Run it again.
2196   test_clock_.Advance(delayed_one_shot_sync_task_delta());
2197   RunOneShotSyncDelayedTask();
2198   base::RunLoop().RunUntilIdle();
2199   EXPECT_FALSE(GetRegistration(sync_options_1_));
2200   EXPECT_TRUE(test_background_sync_manager()->last_chance());
2201 }
2202 
TEST_F(BackgroundSyncManagerTest,EmulateOfflineSingleClient)2203 TEST_F(BackgroundSyncManagerTest, EmulateOfflineSingleClient) {
2204   InitSyncEventTest();
2205 
2206   test_background_sync_manager()->EmulateServiceWorkerOffline(
2207       sw_registration_id_1_, true);
2208   EXPECT_TRUE(Register(sync_options_1_));
2209   EXPECT_EQ(0, sync_events_called_);
2210   EXPECT_TRUE(GetRegistration(sync_options_1_));
2211 
2212   test_background_sync_manager()->EmulateServiceWorkerOffline(
2213       sw_registration_id_1_, false);
2214   base::RunLoop().RunUntilIdle();
2215   EXPECT_EQ(1, sync_events_called_);
2216   EXPECT_FALSE(GetRegistration(sync_options_1_));
2217 
2218   EXPECT_TRUE(Register(sync_options_2_));
2219   EXPECT_EQ(2, sync_events_called_);
2220   EXPECT_FALSE(GetRegistration(sync_options_2_));
2221 }
2222 
TEST_F(BackgroundSyncManagerTest,EmulateOfflineMultipleClients)2223 TEST_F(BackgroundSyncManagerTest, EmulateOfflineMultipleClients) {
2224   InitSyncEventTest();
2225 
2226   test_background_sync_manager()->EmulateServiceWorkerOffline(
2227       sw_registration_id_1_, true);
2228   EXPECT_TRUE(Register(sync_options_1_));
2229   EXPECT_EQ(0, sync_events_called_);
2230   EXPECT_TRUE(GetRegistration(sync_options_1_));
2231 
2232   test_background_sync_manager()->EmulateServiceWorkerOffline(
2233       sw_registration_id_1_, true);
2234 
2235   EXPECT_TRUE(Register(sync_options_2_));
2236   EXPECT_EQ(0, sync_events_called_);
2237   EXPECT_TRUE(GetRegistration(sync_options_2_));
2238 
2239   test_background_sync_manager()->EmulateServiceWorkerOffline(
2240       sw_registration_id_1_, false);
2241   base::RunLoop().RunUntilIdle();
2242   EXPECT_EQ(0, sync_events_called_);
2243   EXPECT_TRUE(GetRegistration(sync_options_1_));
2244   EXPECT_TRUE(GetRegistration(sync_options_2_));
2245 
2246   test_background_sync_manager()->EmulateServiceWorkerOffline(
2247       sw_registration_id_1_, false);
2248   base::RunLoop().RunUntilIdle();
2249 
2250   EXPECT_EQ(2, sync_events_called_);
2251   EXPECT_FALSE(GetRegistration(sync_options_1_));
2252   EXPECT_FALSE(GetRegistration(sync_options_2_));
2253 }
2254 
EmulateDispatchSyncEventCallback(bool * was_called,blink::ServiceWorkerStatusCode * code,blink::ServiceWorkerStatusCode status_code)2255 static void EmulateDispatchSyncEventCallback(
2256     bool* was_called,
2257     blink::ServiceWorkerStatusCode* code,
2258     blink::ServiceWorkerStatusCode status_code) {
2259   *was_called = true;
2260   *code = status_code;
2261 }
2262 
TEST_F(BackgroundSyncManagerTest,EmulateDispatchSyncEvent)2263 TEST_F(BackgroundSyncManagerTest, EmulateDispatchSyncEvent) {
2264   InitSyncEventTest();
2265   bool was_called = false;
2266   blink::ServiceWorkerStatusCode code =
2267       blink::ServiceWorkerStatusCode::kErrorEventWaitUntilRejected;
2268   test_background_sync_manager()->EmulateDispatchSyncEvent(
2269       "emulated_tag", sw_registration_1_->active_version(), false,
2270       base::BindOnce(EmulateDispatchSyncEventCallback, &was_called, &code));
2271   base::RunLoop().RunUntilIdle();
2272   EXPECT_TRUE(was_called);
2273   EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, code);
2274 
2275   EXPECT_EQ(1, sync_events_called_);
2276 
2277   test_background_sync_manager()->EmulateServiceWorkerOffline(
2278       sw_registration_id_1_, true);
2279 
2280   was_called = false;
2281   test_background_sync_manager()->EmulateDispatchSyncEvent(
2282       "emulated_tag", sw_registration_1_->active_version(), false,
2283       base::BindOnce(EmulateDispatchSyncEventCallback, &was_called, &code));
2284   base::RunLoop().RunUntilIdle();
2285   EXPECT_TRUE(was_called);
2286   EXPECT_EQ(blink::ServiceWorkerStatusCode::kErrorEventWaitUntilRejected, code);
2287 
2288   test_background_sync_manager()->EmulateServiceWorkerOffline(
2289       sw_registration_id_1_, false);
2290 
2291   SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
2292   was_called = false;
2293   code = blink::ServiceWorkerStatusCode::kOk;
2294   test_background_sync_manager()->EmulateDispatchSyncEvent(
2295       "emulated_tag", sw_registration_1_->active_version(), false,
2296       base::BindOnce(EmulateDispatchSyncEventCallback, &was_called, &code));
2297   base::RunLoop().RunUntilIdle();
2298   EXPECT_TRUE(was_called);
2299   EXPECT_EQ(blink::ServiceWorkerStatusCode::kErrorEventWaitUntilRejected, code);
2300 
2301   SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
2302   was_called = false;
2303   test_background_sync_manager()->EmulateDispatchSyncEvent(
2304       "emulated_tag", sw_registration_1_->active_version(), false,
2305       base::BindOnce(EmulateDispatchSyncEventCallback, &was_called, &code));
2306   base::RunLoop().RunUntilIdle();
2307   EXPECT_TRUE(was_called);
2308   EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, code);
2309 
2310   EXPECT_EQ(2, sync_events_called_);
2311 }
2312 
TEST_F(BackgroundSyncManagerTest,DispatchPeriodicSyncEvent)2313 TEST_F(BackgroundSyncManagerTest, DispatchPeriodicSyncEvent) {
2314   InitPeriodicSyncEventTest();
2315 
2316   EXPECT_TRUE(AreOptionConditionsMet());
2317 
2318   bool was_called = false;
2319   blink::ServiceWorkerStatusCode code =
2320       blink::ServiceWorkerStatusCode::kErrorEventWaitUntilRejected;
2321   test_background_sync_manager()->DispatchPeriodicSyncEvent(
2322       "test_tag", sw_registration_1_->active_version(),
2323       base::BindOnce(EmulateDispatchSyncEventCallback, &was_called, &code));
2324   base::RunLoop().RunUntilIdle();
2325   EXPECT_TRUE(was_called);
2326   EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, code);
2327 
2328   EXPECT_EQ(1, periodic_sync_events_called_);
2329 }
2330 
TEST_F(BackgroundSyncManagerTest,EventsLoggedForRegistration)2331 TEST_F(BackgroundSyncManagerTest, EventsLoggedForRegistration) {
2332   // Note that the dispatch is mocked out, so those events are not registered
2333   // by these tests.
2334   storage_partition_impl_->GetDevToolsBackgroundServicesContext()
2335       ->StartRecording(devtools::proto::BACKGROUND_SYNC);
2336 
2337   SetMaxSyncAttemptsAndRestartManager(3);
2338   InitFailedSyncEventTest();
2339 
2340   {
2341     // We expect a "Registered" event and a "Fail" event.
2342     EXPECT_CALL(*this, OnEventReceived(_)).Times(2);
2343     // The first run will fail but it will setup a timer to try again.
2344     EXPECT_TRUE(Register(sync_options_1_));
2345     EXPECT_TRUE(GetRegistration(sync_options_1_));
2346     EXPECT_TRUE(IsDelayedTaskScheduledOneShotSync());
2347   }
2348 
2349   test_clock_.Advance(delayed_one_shot_sync_task_delta());
2350   {
2351     // Expect another "Fail" event.
2352     RunOneShotSyncDelayedTask();
2353     EXPECT_CALL(*this, OnEventReceived(_)).Times(1);
2354     base::RunLoop().RunUntilIdle();
2355     EXPECT_TRUE(GetRegistration(sync_options_1_));
2356   }
2357 
2358   // The event should succeed now.
2359   InitSyncEventTest();
2360 
2361   test_clock_.Advance(delayed_one_shot_sync_task_delta());
2362   {
2363     // Expect a "Completion" event.
2364     EXPECT_CALL(*this, OnEventReceived(_)).Times(1);
2365     RunOneShotSyncDelayedTask();
2366     base::RunLoop().RunUntilIdle();
2367     EXPECT_FALSE(GetRegistration(sync_options_1_));
2368   }
2369 }
2370 
TEST_F(BackgroundSyncManagerTest,EventsLoggedForPeriodicSyncRegistration)2371 TEST_F(BackgroundSyncManagerTest, EventsLoggedForPeriodicSyncRegistration) {
2372   storage_partition_impl_->GetDevToolsBackgroundServicesContext()
2373       ->StartRecording(devtools::proto::PERIODIC_BACKGROUND_SYNC);
2374 
2375   SetMaxSyncAttemptsAndRestartManager(3);
2376   InitFailedPeriodicSyncEventTest();
2377 
2378   {
2379     // We expect a "Registered" event, and a "GotDelay" event.
2380     EXPECT_CALL(*this, OnEventReceived(_)).Times(2);
2381     int thirteen_hours_ms = 13 * 60 * 60 * 1000;
2382     sync_options_1_.min_interval = thirteen_hours_ms;
2383 
2384     EXPECT_TRUE(Register(sync_options_1_));
2385     EXPECT_TRUE(GetRegistration(sync_options_1_));
2386     EXPECT_TRUE(IsDelayedTaskScheduledPeriodicSync());
2387   }
2388 
2389   test_clock_.Advance(delayed_periodic_sync_task_delta());
2390   {
2391     // Expect a "Fired" event. Dispatch is mocked out, so that event is not
2392     // registered by this test.
2393     EXPECT_CALL(*this, OnEventReceived(_)).Times(1);
2394     RunPeriodicSyncDelayedTask();
2395     base::RunLoop().RunUntilIdle();
2396     EXPECT_TRUE(GetRegistration(sync_options_1_));
2397   }
2398 
2399   // The event should succeed now.
2400   InitSyncEventTest();
2401 
2402   test_clock_.Advance(delayed_periodic_sync_task_delta());
2403   {
2404     // Expect a "GotDelay" event.
2405     EXPECT_CALL(*this, OnEventReceived(_)).Times(1);
2406     RunPeriodicSyncDelayedTask();
2407     base::RunLoop().RunUntilIdle();
2408     EXPECT_TRUE(GetRegistration(sync_options_1_));
2409   }
2410 
2411   {
2412     // Expect a call for "Unregister" event.
2413     EXPECT_CALL(*this, OnEventReceived(_)).Times(1);
2414     Unregister(sync_options_1_);
2415   }
2416 }
2417 
TEST_F(BackgroundSyncManagerTest,UkmRecordedAtCompletion)2418 TEST_F(BackgroundSyncManagerTest, UkmRecordedAtCompletion) {
2419   InitSyncEventTest();
2420   {
2421     base::HistogramTester histogram_tester;
2422 
2423     EXPECT_TRUE(Register(sync_options_1_));
2424 
2425     base::RunLoop().RunUntilIdle();
2426 
2427     EXPECT_FALSE(GetRegistration(sync_options_1_));
2428 
2429     histogram_tester.ExpectBucketCount(
2430         "BackgroundSync.Registration.OneShot.EventSucceededAtCompletion", true,
2431         1);
2432     histogram_tester.ExpectBucketCount(
2433         "BackgroundSync.Registration.OneShot.NumAttemptsForSuccessfulEvent", 1,
2434         1);
2435   }
2436 
2437   SetMaxSyncAttemptsAndRestartManager(1);
2438   InitFailedSyncEventTest();
2439   {
2440     base::HistogramTester histogram_tester;
2441 
2442     EXPECT_TRUE(Register(sync_options_2_));
2443 
2444     base::RunLoop().RunUntilIdle();
2445 
2446     EXPECT_FALSE(GetRegistration(sync_options_2_));
2447 
2448     histogram_tester.ExpectBucketCount(
2449         "BackgroundSync.Registration.OneShot.EventSucceededAtCompletion", false,
2450         1);
2451     histogram_tester.ExpectBucketCount(
2452         "BackgroundSync.Registration.OneShot.NumAttemptsForSuccessfulEvent", 1,
2453         0);
2454   }
2455 }
2456 
TEST_F(BackgroundSyncManagerTest,MaxSyncAttemptsWithNotificationPermission)2457 TEST_F(BackgroundSyncManagerTest, MaxSyncAttemptsWithNotificationPermission) {
2458   const int max_attempts = 5;
2459   SetMaxSyncAttemptsAndRestartManager(max_attempts);
2460   MockPermissionManager* mock_permission_manager =
2461       GetPermissionControllerDelegate();
2462 
2463   {
2464     EXPECT_TRUE(Register(sync_options_1_));
2465     EXPECT_EQ(callback_one_shot_sync_registration_->max_attempts(),
2466               max_attempts);
2467   }
2468 
2469   {
2470     ON_CALL(*mock_permission_manager,
2471             GetPermissionStatus(PermissionType::NOTIFICATIONS, _, _))
2472         .WillByDefault(Return(blink::mojom::PermissionStatus::GRANTED));
2473     EXPECT_TRUE(Register(sync_options_2_));
2474     EXPECT_EQ(callback_one_shot_sync_registration_->max_attempts(),
2475               max_attempts + 1);
2476   }
2477 }
2478 
2479 }  // namespace content
2480