forked from Pissandshittium/pissandshittium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground_sync_manager_unittest.cc
2479 lines (2043 loc) · 89.9 KB
/
background_sync_manager_unittest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/background_sync/background_sync_manager.h"
#include <stdint.h>
#include <memory>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/check.h"
#include "base/containers/cxx20_erase.h"
#include "base/files/scoped_temp_dir.h"
#include "base/location.h"
#include "base/metrics/field_trial.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/simple_test_clock.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "content/browser/background_sync/background_sync_launcher.h"
#include "content/browser/background_sync/background_sync_network_observer.h"
#include "content/browser/background_sync/background_sync_status.h"
#include "content/browser/devtools/devtools_background_services_context_impl.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_container_host.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_registration_object_host.h"
#include "content/browser/storage_partition_impl.h"
#include "content/public/browser/background_sync_parameters.h"
#include "content/public/browser/permission_type.h"
#include "content/public/test/background_sync_test_util.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/mock_permission_manager.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_utils.h"
#include "content/test/mock_background_sync_controller.h"
#include "content/test/test_background_sync_context.h"
#include "content/test/test_background_sync_manager.h"
#include "content/test/test_background_sync_proxy.h"
#include "services/network/test/test_network_connection_tracker.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "third_party/blink/public/mojom/permissions/permission_status.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_registration_options.mojom.h"
namespace content {
namespace {
using ::testing::_;
using ::testing::Return;
const char kScope1[] = "https://example.com/a/";
const char kScope2[] = "https://example.com/b/";
const char kScript1[] = "https://example.com/a/script.js";
const char kScript2[] = "https://example.com/b/script.js";
void RegisterServiceWorkerCallback(bool* called,
int64_t* store_registration_id,
blink::ServiceWorkerStatusCode status,
const std::string& status_message,
int64_t registration_id) {
EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, status)
<< blink::ServiceWorkerStatusToString(status);
*called = true;
*store_registration_id = registration_id;
}
void FindServiceWorkerRegistrationCallback(
scoped_refptr<ServiceWorkerRegistration>* out_registration,
blink::ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerRegistration> registration) {
EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, status)
<< blink::ServiceWorkerStatusToString(status);
*out_registration = std::move(registration);
}
void UnregisterServiceWorkerCallback(bool* called,
blink::ServiceWorkerStatusCode code) {
EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, code);
*called = true;
}
blink::mojom::BackgroundSyncType GetBackgroundSyncType(
const blink::mojom::SyncRegistrationOptions& options) {
return options.min_interval == -1
? blink::mojom::BackgroundSyncType::ONE_SHOT
: blink::mojom::BackgroundSyncType::PERIODIC;
}
} // namespace
class BackgroundSyncManagerTest
: public testing::Test,
public DevToolsBackgroundServicesContextImpl::EventObserver {
public:
BackgroundSyncManagerTest()
: task_environment_(BrowserTaskEnvironment::IO_MAINLOOP) {
sync_options_1_.tag = "foo";
sync_options_2_.tag = "bar";
}
void SetUp() override {
// Don't let the tests be confused by the real-world device connectivity
background_sync_test_util::SetIgnoreNetworkChanges(true);
// TODO(jkarlin): Create a new object with all of the necessary SW calls
// so that we can inject test versions instead of bringing up all of this
// extra SW stuff.
helper_ = std::make_unique<EmbeddedWorkerTestHelper>(base::FilePath());
std::unique_ptr<MockPermissionManager> mock_permission_manager(
new testing::NiceMock<MockPermissionManager>());
ON_CALL(*mock_permission_manager,
GetPermissionStatus(PermissionType::BACKGROUND_SYNC, _, _))
.WillByDefault(Return(blink::mojom::PermissionStatus::GRANTED));
ON_CALL(*mock_permission_manager,
GetPermissionStatus(PermissionType::PERIODIC_BACKGROUND_SYNC, _, _))
.WillByDefault(Return(blink::mojom::PermissionStatus::GRANTED));
ON_CALL(*mock_permission_manager,
GetPermissionStatus(PermissionType::NOTIFICATIONS, _, _))
.WillByDefault(Return(blink::mojom::PermissionStatus::DENIED));
helper_->browser_context()->SetPermissionControllerDelegate(
std::move(mock_permission_manager));
// Create a StoragePartition with the correct BrowserContext so that the
// BackgroundSyncManager can find the BrowserContext through it.
storage_partition_impl_ = static_cast<StoragePartitionImpl*>(
helper_->browser_context()->GetStoragePartitionForUrl(
GURL("https://example.com")));
helper_->context_wrapper()->set_storage_partition(storage_partition_impl_);
SetMaxSyncAttemptsAndRestartManager(1);
// Wait for storage to finish initializing before registering service
// workers.
base::RunLoop().RunUntilIdle();
RegisterServiceWorkers();
storage_partition_impl_->GetDevToolsBackgroundServicesContext()
->AddObserver(this);
}
void TearDown() override {
storage_partition_impl_->GetDevToolsBackgroundServicesContext()
->RemoveObserver(this);
// Restore the network observer functionality for subsequent tests.
background_sync_test_util::SetIgnoreNetworkChanges(false);
background_sync_context_->Shutdown();
}
void RegisterServiceWorkers() {
bool called_1 = false;
bool called_2 = false;
blink::mojom::ServiceWorkerRegistrationOptions options1;
options1.scope = GURL(kScope1);
blink::StorageKey key1(url::Origin::Create(GURL(kScope1)));
blink::mojom::ServiceWorkerRegistrationOptions options2;
options2.scope = GURL(kScope2);
blink::StorageKey key2(url::Origin::Create(GURL(kScope2)));
helper_->context()->RegisterServiceWorker(
GURL(kScript1), key1, options1,
blink::mojom::FetchClientSettingsObject::New(),
base::BindOnce(&RegisterServiceWorkerCallback, &called_1,
&sw_registration_id_1_),
/*requesting_frame_id=*/GlobalRenderFrameHostId());
helper_->context()->RegisterServiceWorker(
GURL(kScript2), key2, options2,
blink::mojom::FetchClientSettingsObject::New(),
base::BindOnce(&RegisterServiceWorkerCallback, &called_2,
&sw_registration_id_2_),
/*requesting_frame_id=*/GlobalRenderFrameHostId());
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called_1);
EXPECT_TRUE(called_2);
// Hang onto the registrations as they need to be "live" when
// calling BackgroundSyncManager::Register.
helper_->context_wrapper()->FindReadyRegistrationForId(
sw_registration_id_1_, key1,
base::BindOnce(FindServiceWorkerRegistrationCallback,
&sw_registration_1_));
helper_->context_wrapper()->FindReadyRegistrationForId(
sw_registration_id_2_, key1,
base::BindOnce(FindServiceWorkerRegistrationCallback,
&sw_registration_2_));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(sw_registration_1_);
EXPECT_TRUE(sw_registration_2_);
}
void SetNetwork(network::mojom::ConnectionType connection_type) {
network::TestNetworkConnectionTracker::GetInstance()->SetConnectionType(
connection_type);
if (test_background_sync_manager()) {
BackgroundSyncNetworkObserver* network_observer =
test_background_sync_manager()->GetNetworkObserverForTesting();
network_observer->NotifyManagerIfConnectionChangedForTesting(
connection_type);
base::RunLoop().RunUntilIdle();
}
}
void StatusAndOneShotSyncRegistrationCallback(
bool* was_called,
BackgroundSyncStatus status,
std::unique_ptr<BackgroundSyncRegistration> registration) {
*was_called = true;
one_shot_sync_callback_status_ = status;
callback_one_shot_sync_registration_ = std::move(registration);
}
void StatusAndPeriodicSyncRegistrationCallback(
bool* was_called,
BackgroundSyncStatus status,
std::unique_ptr<BackgroundSyncRegistration> registration) {
*was_called = true;
periodic_sync_callback_status_ = status;
callback_periodic_sync_registration_ = std::move(registration);
}
void StatusAndOneShotSyncRegistrationsCallback(
bool* was_called,
BackgroundSyncStatus status,
std::vector<std::unique_ptr<BackgroundSyncRegistration>> registrations) {
*was_called = true;
one_shot_sync_callback_status_ = status;
callback_one_shot_sync_registrations_ = std::move(registrations);
}
void StatusAndPeriodicSyncRegistrationsCallback(
bool* was_called,
BackgroundSyncStatus status,
std::vector<std::unique_ptr<BackgroundSyncRegistration>> registrations) {
*was_called = true;
periodic_sync_callback_status_ = status;
callback_periodic_sync_registrations_ = std::move(registrations);
}
void StatusCallback(bool* was_called, BackgroundSyncStatus status) {
*was_called = true;
callback_status_ = status;
}
TestBackgroundSyncManager* test_background_sync_manager() {
return static_cast<TestBackgroundSyncManager*>(
background_sync_context_->background_sync_manager());
}
TestBackgroundSyncProxy* test_proxy() {
return static_cast<TestBackgroundSyncProxy*>(
test_background_sync_manager()->proxy_.get());
}
base::TimeDelta GetSoonestWakeupDelta(
blink::mojom::BackgroundSyncType sync_type,
base::Time last_browser_wakeup_for_periodic_sync) {
return test_background_sync_manager()->GetSoonestWakeupDelta(
sync_type, last_browser_wakeup_for_periodic_sync);
}
void SuspendPeriodicSyncRegistrations(std::set<url::Origin> origins) {
GetController()->NoteSuspendedPeriodicSyncOrigins(std::move(origins));
}
void RevivePeriodicSyncRegistrations(url::Origin origin) {
GetController()->ReviveSuspendedPeriodicSyncOrigin(origin);
test_background_sync_manager()->RevivePeriodicSyncRegistrations(origin);
}
void BlockContentSettingFor(url::Origin origin) {
GetController()->RemoveFromTrackedOrigins(origin);
test_background_sync_manager()->UnregisterPeriodicSyncForOrigin(origin);
}
protected:
MOCK_METHOD1(OnEventReceived,
void(const devtools::proto::BackgroundServiceEvent&));
MOCK_METHOD2(OnRecordingStateChanged,
void(bool, devtools::proto::BackgroundService));
void CreateBackgroundSyncManager() {
if (background_sync_context_) {
background_sync_context_->Shutdown();
base::RunLoop().RunUntilIdle();
}
background_sync_context_ =
base::MakeRefCounted<TestBackgroundSyncContext>();
background_sync_context_->Init(
helper_->context_wrapper(),
storage_partition_impl_->GetDevToolsBackgroundServicesContext());
base::RunLoop().RunUntilIdle();
storage_partition_impl_->ShutdownBackgroundSyncContextForTesting();
base::RunLoop().RunUntilIdle();
storage_partition_impl_->OverrideBackgroundSyncContextForTesting(
background_sync_context_.get());
test_background_sync_manager()->set_clock(&test_clock_);
test_background_sync_manager()->set_proxy_for_testing(
std::make_unique<TestBackgroundSyncProxy>(helper_->context_wrapper()));
// Many tests do not expect the sync event to fire immediately after
// register (and cleanup up the sync registrations). Tests can control when
// the sync event fires by manipulating the network state as needed.
// NOTE: The setup of the network connection must happen after the
// BackgroundSyncManager has been created.
SetNetwork(network::mojom::ConnectionType::CONNECTION_NONE);
}
void InitBackgroundSyncManager() {
test_background_sync_manager()->DoInit();
base::RunLoop().RunUntilIdle();
}
void SetupBackgroundSyncManager() {
CreateBackgroundSyncManager();
InitBackgroundSyncManager();
}
void SetupCorruptBackgroundSyncManager() {
CreateBackgroundSyncManager();
test_background_sync_manager()->set_corrupt_backend(true);
InitBackgroundSyncManager();
}
void SetupDelayedBackgroundSyncManager() {
CreateBackgroundSyncManager();
test_background_sync_manager()->set_delay_backend(true);
InitBackgroundSyncManager();
}
void DeleteBackgroundSyncManager() {
storage_partition_impl_->GetBackgroundSyncContext()
->set_background_sync_manager_for_testing(nullptr);
}
bool Register(blink::mojom::SyncRegistrationOptions sync_options) {
return RegisterWithServiceWorkerId(sw_registration_id_1_,
std::move(sync_options));
}
bool Unregister(blink::mojom::SyncRegistrationOptions sync_options) {
return UnregisterWithServiceWorkerId(sw_registration_id_1_,
std::move(sync_options));
}
bool RegisterWithServiceWorkerId(
int64_t sw_registration_id,
blink::mojom::SyncRegistrationOptions options) {
bool was_called = false;
BackgroundSyncStatus* callback_status;
if (GetBackgroundSyncType(options) ==
blink::mojom::BackgroundSyncType::ONE_SHOT) {
test_background_sync_manager()->Register(
sw_registration_id, options,
base::BindOnce(&BackgroundSyncManagerTest::
StatusAndOneShotSyncRegistrationCallback,
base::Unretained(this), &was_called));
callback_status = &one_shot_sync_callback_status_;
} else {
test_background_sync_manager()->Register(
sw_registration_id, options,
base::BindOnce(&BackgroundSyncManagerTest::
StatusAndPeriodicSyncRegistrationCallback,
base::Unretained(this), &was_called));
callback_status = &periodic_sync_callback_status_;
}
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(was_called);
// Mock the client receiving the response and calling
// DidResolveRegistration.
if (*callback_status == BACKGROUND_SYNC_STATUS_OK) {
test_background_sync_manager()->DidResolveRegistration(
blink::mojom::BackgroundSyncRegistrationInfo::New(
sw_registration_id, options.tag, GetBackgroundSyncType(options)));
base::RunLoop().RunUntilIdle();
}
return *callback_status == BACKGROUND_SYNC_STATUS_OK;
}
bool UnregisterWithServiceWorkerId(
int64_t sw_registration_id,
blink::mojom::SyncRegistrationOptions options) {
if (GetBackgroundSyncType(options) ==
blink::mojom::BackgroundSyncType::ONE_SHOT) {
// Not supported for one-shot sync.
return false;
}
bool was_called = false;
test_background_sync_manager()->UnregisterPeriodicSync(
sw_registration_id, options.tag,
base::BindOnce(&BackgroundSyncManagerTest::StatusCallback,
base::Unretained(this), &was_called));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(was_called);
return callback_status_ == BACKGROUND_SYNC_STATUS_OK;
}
MockPermissionManager* GetPermissionControllerDelegate() {
return static_cast<MockPermissionManager*>(
helper_->browser_context()->GetPermissionControllerDelegate());
}
bool GetRegistration(
blink::mojom::SyncRegistrationOptions registration_options) {
if (GetBackgroundSyncType(registration_options) ==
blink::mojom::BackgroundSyncType::ONE_SHOT) {
return GetOneShotSyncRegistrationWithServiceWorkerId(
sw_registration_id_1_, std::move(registration_options));
}
return GetPeriodicSyncRegistrationWithServiceWorkerId(
sw_registration_id_1_, std::move(registration_options));
}
bool GetOneShotSyncRegistrationWithServiceWorkerId(
int64_t sw_registration_id,
blink::mojom::SyncRegistrationOptions registration_options) {
bool was_called = false;
test_background_sync_manager()->GetOneShotSyncRegistrations(
sw_registration_id,
base::BindOnce(&BackgroundSyncManagerTest::
StatusAndOneShotSyncRegistrationsCallback,
base::Unretained(this), &was_called));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(was_called);
if (one_shot_sync_callback_status_ == BACKGROUND_SYNC_STATUS_OK) {
for (auto& one_shot_sync_registration :
callback_one_shot_sync_registrations_) {
if (one_shot_sync_registration->options()->Equals(
registration_options)) {
// Transfer the matching registration out of the vector into
// |callback_one_shot_sync_registration_| for testing.
callback_one_shot_sync_registration_ =
std::move(one_shot_sync_registration);
base::Erase(callback_one_shot_sync_registrations_,
one_shot_sync_registration);
return true;
}
}
}
return false;
}
bool GetPeriodicSyncRegistrationWithServiceWorkerId(
int64_t sw_registration_id,
blink::mojom::SyncRegistrationOptions registration_options) {
bool was_called = false;
test_background_sync_manager()->GetPeriodicSyncRegistrations(
sw_registration_id,
base::BindOnce(&BackgroundSyncManagerTest::
StatusAndPeriodicSyncRegistrationsCallback,
base::Unretained(this), &was_called));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(was_called);
if (periodic_sync_callback_status_ == BACKGROUND_SYNC_STATUS_OK) {
for (auto& periodic_sync_registration :
callback_periodic_sync_registrations_) {
if (periodic_sync_registration->options()->Equals(
registration_options)) {
// Transfer the matching registration out of the vector into
// |callback_periodic_sync_registration_| for testing.
callback_periodic_sync_registration_ =
std::move(periodic_sync_registration);
base::Erase(callback_periodic_sync_registrations_,
periodic_sync_registration);
return true;
}
}
}
return false;
}
url::Origin GetOriginForPeriodicSyncRegistration() {
DCHECK(callback_periodic_sync_registration_);
return callback_periodic_sync_registration_->origin();
}
bool GetOneShotSyncRegistrations() {
bool was_called = false;
test_background_sync_manager()->GetOneShotSyncRegistrations(
sw_registration_id_1_,
base::BindOnce(&BackgroundSyncManagerTest::
StatusAndOneShotSyncRegistrationsCallback,
base::Unretained(this), &was_called));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(was_called);
return one_shot_sync_callback_status_ == BACKGROUND_SYNC_STATUS_OK;
}
bool GetPeriodicSyncRegistrations() {
bool was_called = false;
test_background_sync_manager()->GetPeriodicSyncRegistrations(
sw_registration_id_1_,
base::BindOnce(&BackgroundSyncManagerTest::
StatusAndPeriodicSyncRegistrationsCallback,
base::Unretained(this), &was_called));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(was_called);
return periodic_sync_callback_status_ == BACKGROUND_SYNC_STATUS_OK;
}
MockBackgroundSyncController* GetController() {
return static_cast<MockBackgroundSyncController*>(
helper_->browser_context()->GetBackgroundSyncController());
}
void StorageRegistrationCallback(blink::ServiceWorkerStatusCode result) {
callback_sw_status_code_ = result;
}
void UnregisterServiceWorker(uint64_t sw_registration_id) {
bool called = false;
const GURL scope = ScopeForSWId(sw_registration_id);
helper_->context()->UnregisterServiceWorker(
scope, blink::StorageKey(url::Origin::Create(scope)),
/*is_immediate=*/false,
base::BindOnce(&UnregisterServiceWorkerCallback, &called));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
}
GURL ScopeForSWId(int64_t sw_id) {
EXPECT_TRUE(sw_id == sw_registration_id_1_ ||
sw_id == sw_registration_id_2_);
return sw_id == sw_registration_id_1_ ? GURL(kScope1) : GURL(kScope2);
}
void SetupForSyncEvent(
const TestBackgroundSyncManager::DispatchSyncCallback& callback) {
test_background_sync_manager()->set_dispatch_sync_callback(callback);
SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
}
void SetupForPeriodicSyncEvent(
const TestBackgroundSyncManager::DispatchSyncCallback& callback) {
test_background_sync_manager()->set_dispatch_periodic_sync_callback(
callback);
SetNetwork(network::mojom::ConnectionType::CONNECTION_WIFI);
}
void DispatchSyncStatusCallback(
blink::ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerVersion> active_version,
ServiceWorkerVersion::StatusCallback callback) {
sync_events_called_++;
std::move(callback).Run(status);
}
void DispatchPeriodicSyncStatusCallback(
blink::ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerVersion> active_version,
ServiceWorkerVersion::StatusCallback callback) {
periodic_sync_events_called_++;
std::move(callback).Run(status);
}
void InitSyncEventTest() {
SetupForSyncEvent(base::BindRepeating(
&BackgroundSyncManagerTest::DispatchSyncStatusCallback,
base::Unretained(this), blink::ServiceWorkerStatusCode::kOk));
}
void InitPeriodicSyncEventTest() {
SetupForPeriodicSyncEvent(base::BindRepeating(
&BackgroundSyncManagerTest::DispatchPeriodicSyncStatusCallback,
base::Unretained(this), blink::ServiceWorkerStatusCode::kOk));
}
void InitFailedSyncEventTest() {
SetupForSyncEvent(base::BindRepeating(
&BackgroundSyncManagerTest::DispatchSyncStatusCallback,
base::Unretained(this),
blink::ServiceWorkerStatusCode::kErrorEventWaitUntilRejected));
}
void InitFailedPeriodicSyncEventTest() {
SetupForPeriodicSyncEvent(base::BindRepeating(
&BackgroundSyncManagerTest::DispatchPeriodicSyncStatusCallback,
base::Unretained(this),
blink::ServiceWorkerStatusCode::kErrorEventWaitUntilRejected));
}
void DispatchSyncDelayedCallback(
scoped_refptr<ServiceWorkerVersion> active_version,
ServiceWorkerVersion::StatusCallback callback) {
sync_events_called_++;
sync_fired_callback_ = std::move(callback);
}
void DispatchPeriodicSyncDelayedCallback(
scoped_refptr<ServiceWorkerVersion> active_version,
ServiceWorkerVersion::StatusCallback callback) {
periodic_sync_events_called_++;
periodic_sync_fired_callback_ = std::move(callback);
}
void InitDelayedSyncEventTest() {
SetupForSyncEvent(base::BindRepeating(
&BackgroundSyncManagerTest::DispatchSyncDelayedCallback,
base::Unretained(this)));
}
void InitDelayedPeriodicSyncEventTest() {
SetupForPeriodicSyncEvent(base::BindRepeating(
&BackgroundSyncManagerTest::DispatchPeriodicSyncDelayedCallback,
base::Unretained(this)));
}
void RegisterAndVerifySyncEventDelayed(
blink::mojom::SyncRegistrationOptions sync_options) {
int count_sync_events = sync_events_called_;
EXPECT_FALSE(sync_fired_callback_);
EXPECT_TRUE(Register(sync_options));
EXPECT_EQ(count_sync_events + 1, sync_events_called_);
EXPECT_TRUE(GetRegistration(std::move(sync_options)));
EXPECT_TRUE(sync_fired_callback_);
}
void DeleteServiceWorkerAndStartOver() {
helper_->context()->ScheduleDeleteAndStartOver();
content::RunAllTasksUntilIdle();
}
int MaxTagLength() const { return BackgroundSyncManager::kMaxTagLength; }
void SetMaxSyncAttemptsAndRestartManager(int max_sync_attempts) {
BackgroundSyncParameters* parameters =
GetController()->background_sync_parameters();
parameters->max_sync_attempts = max_sync_attempts;
parameters->max_sync_attempts_with_notification_permission =
max_sync_attempts + 1;
// Restart the BackgroundSyncManager so that it updates its parameters.
SetupBackgroundSyncManager();
}
void SetRelyOnAndroidNetworkDetectionAndRestartManager(
bool rely_on_android_network_detection) {
#if defined(OS_ANDROID)
BackgroundSyncParameters* parameters =
GetController()->background_sync_parameters();
parameters->rely_on_android_network_detection =
rely_on_android_network_detection;
// Restart BackgroundSyncManager so that it updates its parameters.
SetupBackgroundSyncManager();
#endif
}
void SetPeriodicSyncEventsMinIntervalAndRestartManager(
base::TimeDelta periodic_sync_events_min_interval) {
BackgroundSyncParameters* parameters =
GetController()->background_sync_parameters();
parameters->min_periodic_sync_events_interval =
periodic_sync_events_min_interval;
// Restart the BackgroundSyncManager so that it updates its parameters.
SetupBackgroundSyncManager();
}
void SetKeepBrowserAwakeTillEventsCompleteAndRestartManager(
bool keep_browser_awake_till_events_complete) {
BackgroundSyncParameters* parameters =
GetController()->background_sync_parameters();
parameters->keep_browser_awake_till_events_complete =
keep_browser_awake_till_events_complete;
SetupBackgroundSyncManager();
}
void FireReadyEvents() { test_background_sync_manager()->OnNetworkChanged(); }
bool AreOptionConditionsMet() {
return test_background_sync_manager()->AreOptionConditionsMet();
}
bool IsDelayedTaskScheduledOneShotSync() {
return test_proxy()->IsDelayedTaskSet(
blink::mojom::BackgroundSyncType::ONE_SHOT);
}
bool IsDelayedTaskScheduledPeriodicSync() {
return test_proxy()->IsDelayedTaskSet(
blink::mojom::BackgroundSyncType::PERIODIC);
}
bool IsBrowserWakeupForOneShotSyncScheduled() {
return IsDelayedTaskScheduledOneShotSync();
}
bool IsBrowserWakeupForPeriodicSyncScheduled() {
return IsDelayedTaskScheduledPeriodicSync();
}
base::TimeDelta delayed_one_shot_sync_task_delta() {
return test_proxy()->GetDelay(blink::mojom::BackgroundSyncType::ONE_SHOT);
}
base::TimeDelta delayed_periodic_sync_task_delta() {
return test_proxy()->GetDelay(blink::mojom::BackgroundSyncType::PERIODIC);
}
bool EqualsSoonestOneShotWakeupDelta(base::TimeDelta compare_to) {
return delayed_one_shot_sync_task_delta() == compare_to;
}
bool EqualsSoonestPeriodicSyncWakeupDelta(base::TimeDelta compare_to) {
return delayed_periodic_sync_task_delta() == compare_to;
}
void RunOneShotSyncDelayedTask() {
test_proxy()->RunDelayedTask(blink::mojom::BackgroundSyncType::ONE_SHOT);
}
void RunPeriodicSyncDelayedTask() {
test_proxy()->RunDelayedTask(blink::mojom::BackgroundSyncType::PERIODIC);
}
BrowserTaskEnvironment task_environment_;
std::unique_ptr<EmbeddedWorkerTestHelper> helper_;
StoragePartitionImpl* storage_partition_impl_;
scoped_refptr<BackgroundSyncContextImpl> background_sync_context_;
base::SimpleTestClock test_clock_;
std::unique_ptr<TestBackgroundSyncProxy> test_proxy_;
int64_t sw_registration_id_1_;
int64_t sw_registration_id_2_;
scoped_refptr<ServiceWorkerRegistration> sw_registration_1_;
scoped_refptr<ServiceWorkerRegistration> sw_registration_2_;
blink::mojom::SyncRegistrationOptions sync_options_1_;
blink::mojom::SyncRegistrationOptions sync_options_2_;
// Callback values.
BackgroundSyncStatus one_shot_sync_callback_status_ =
BACKGROUND_SYNC_STATUS_OK;
BackgroundSyncStatus periodic_sync_callback_status_ =
BACKGROUND_SYNC_STATUS_OK;
BackgroundSyncStatus callback_status_ = BACKGROUND_SYNC_STATUS_OK;
std::unique_ptr<BackgroundSyncRegistration>
callback_one_shot_sync_registration_;
std::unique_ptr<BackgroundSyncRegistration>
callback_periodic_sync_registration_;
std::vector<std::unique_ptr<BackgroundSyncRegistration>>
callback_one_shot_sync_registrations_;
std::vector<std::unique_ptr<BackgroundSyncRegistration>>
callback_periodic_sync_registrations_;
blink::ServiceWorkerStatusCode callback_sw_status_code_ =
blink::ServiceWorkerStatusCode::kOk;
int sync_events_called_ = 0;
int periodic_sync_events_called_ = 0;
ServiceWorkerVersion::StatusCallback sync_fired_callback_;
ServiceWorkerVersion::StatusCallback periodic_sync_fired_callback_;
};
TEST_F(BackgroundSyncManagerTest, Register) {
EXPECT_TRUE(Register(sync_options_1_));
}
TEST_F(BackgroundSyncManagerTest, Unregister) {
// Not supported for One-shot syncs.
EXPECT_TRUE(Register(sync_options_1_));
EXPECT_FALSE(Unregister(sync_options_1_));
sync_options_1_.min_interval = 36000;
EXPECT_TRUE(Register(sync_options_1_));
// Don't fail for non-existent Periodic Sync registrations.
sync_options_2_.min_interval = 36000;
EXPECT_TRUE(Unregister(sync_options_2_));
// Unregistering one periodic sync doesn't affect another.
EXPECT_TRUE(Register(sync_options_2_));
EXPECT_TRUE(Unregister(sync_options_1_));
EXPECT_FALSE(GetRegistration(sync_options_1_));
EXPECT_TRUE(GetRegistration(sync_options_2_));
// Disable manager. Unregister should fail.
test_background_sync_manager()->set_corrupt_backend(true);
EXPECT_FALSE(Unregister(sync_options_2_));
SetupBackgroundSyncManager();
EXPECT_TRUE(Unregister(sync_options_2_));
}
TEST_F(BackgroundSyncManagerTest, UnregistrationStopsPeriodicTasks) {
InitPeriodicSyncEventTest();
int thirteen_hours_ms = 13 * 60 * 60 * 1000;
sync_options_2_.min_interval = thirteen_hours_ms;
EXPECT_TRUE(Register(sync_options_2_));
EXPECT_EQ(0, periodic_sync_events_called_);
// Advance clock.
test_clock_.Advance(base::Milliseconds(thirteen_hours_ms));
FireReadyEvents();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, periodic_sync_events_called_);
EXPECT_TRUE(Unregister(sync_options_2_));
// Advance clock. Expect no increase in periodicSync events fired.
test_clock_.Advance(base::Milliseconds(thirteen_hours_ms));
FireReadyEvents();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, periodic_sync_events_called_);
}
TEST_F(BackgroundSyncManagerTest, RegisterAndWaitToFireUntilResolved) {
InitSyncEventTest();
bool was_called = false;
test_background_sync_manager()->Register(
sw_registration_id_1_, sync_options_1_,
base::BindOnce(
&BackgroundSyncManagerTest::StatusAndOneShotSyncRegistrationCallback,
base::Unretained(this), &was_called));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(was_called);
// Verify that the sync event hasn't fired yet, as it should wait for the
// client to acknowledge with DidResolveRegistration.
EXPECT_EQ(0, sync_events_called_);
test_background_sync_manager()->DidResolveRegistration(
blink::mojom::BackgroundSyncRegistrationInfo::New(
sw_registration_id_1_, sync_options_1_.tag,
GetBackgroundSyncType(sync_options_1_)));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, sync_events_called_);
}
TEST_F(BackgroundSyncManagerTest, ResolveInvalidRegistration) {
InitSyncEventTest();
bool was_called = false;
test_background_sync_manager()->Register(
sw_registration_id_1_, sync_options_1_,
base::BindOnce(
&BackgroundSyncManagerTest::StatusAndOneShotSyncRegistrationCallback,
base::Unretained(this), &was_called));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(was_called);
// Verify that the sync event hasn't fired yet, as it should wait for the
// client to acknowledge with DidResolveRegistration.
EXPECT_EQ(0, sync_events_called_);
// Resolve a non-existing registration.
test_background_sync_manager()->DidResolveRegistration(
blink::mojom::BackgroundSyncRegistrationInfo::New(
sw_registration_id_1_, "unknown_tag",
GetBackgroundSyncType(sync_options_1_)));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, sync_events_called_);
}
TEST_F(BackgroundSyncManagerTest, RegistrationIntact) {
EXPECT_TRUE(Register(sync_options_1_));
EXPECT_EQ(sync_options_1_.tag,
callback_one_shot_sync_registration_->options()->tag);
sync_options_2_.min_interval = 3600;
EXPECT_TRUE(Register(sync_options_2_));
EXPECT_EQ(sync_options_2_.tag,
callback_periodic_sync_registration_->options()->tag);
}
TEST_F(BackgroundSyncManagerTest, RegisterWithoutLiveSWRegistration) {
// Get a worker host which is used to install the service worker.
ASSERT_TRUE(sw_registration_1_->active_version());
ASSERT_FALSE(sw_registration_1_->waiting_version());
ASSERT_FALSE(sw_registration_1_->installing_version());
ServiceWorkerHost* worker_host =
sw_registration_1_->active_version()->worker_host();
ASSERT_TRUE(worker_host);
// Remove the registration object host.
worker_host->container_host()->registration_object_hosts_.clear();
// Ensure |sw_registration_1_| is the last reference to the registration.
ASSERT_TRUE(sw_registration_1_->HasOneRef());
sw_registration_1_ = nullptr;
EXPECT_FALSE(Register(sync_options_1_));
EXPECT_EQ(BACKGROUND_SYNC_STATUS_NO_SERVICE_WORKER,
one_shot_sync_callback_status_);
}
TEST_F(BackgroundSyncManagerTest, RegisterWithoutActiveSWRegistration) {
sw_registration_1_->UnsetVersion(sw_registration_1_->active_version());
EXPECT_FALSE(Register(sync_options_1_));
EXPECT_EQ(BACKGROUND_SYNC_STATUS_NO_SERVICE_WORKER,
one_shot_sync_callback_status_);
}
TEST_F(BackgroundSyncManagerTest, RegisterBadBackend) {
test_background_sync_manager()->set_corrupt_backend(true);
EXPECT_FALSE(Register(sync_options_1_));
test_background_sync_manager()->set_corrupt_backend(false);
EXPECT_FALSE(Register(sync_options_1_));
EXPECT_FALSE(GetRegistration(sync_options_1_));
}
TEST_F(BackgroundSyncManagerTest, RegisterPermissionDenied) {
GURL expected_origin = GURL(kScope1).DeprecatedGetOriginAsURL();
MockPermissionManager* mock_permission_manager =
GetPermissionControllerDelegate();
EXPECT_CALL(*mock_permission_manager,
GetPermissionStatus(PermissionType::NOTIFICATIONS,
expected_origin, expected_origin))
.Times(2);
EXPECT_CALL(*mock_permission_manager,
GetPermissionStatus(PermissionType::BACKGROUND_SYNC,
expected_origin, expected_origin))
.WillOnce(testing::Return(blink::mojom::PermissionStatus::DENIED));
EXPECT_FALSE(Register(sync_options_1_));
sync_options_2_.min_interval = 36000;
EXPECT_CALL(*mock_permission_manager,
GetPermissionStatus(PermissionType::PERIODIC_BACKGROUND_SYNC,
expected_origin, expected_origin))
.WillOnce(testing::Return(blink::mojom::PermissionStatus::DENIED));
EXPECT_FALSE(Register(sync_options_2_));
}
TEST_F(BackgroundSyncManagerTest, RegisterPermissionGranted) {
GURL expected_origin = GURL(kScope1).DeprecatedGetOriginAsURL();
MockPermissionManager* mock_permission_manager =
GetPermissionControllerDelegate();
EXPECT_CALL(*mock_permission_manager,
GetPermissionStatus(PermissionType::NOTIFICATIONS,
expected_origin, expected_origin))
.Times(2);
EXPECT_CALL(*mock_permission_manager,
GetPermissionStatus(PermissionType::BACKGROUND_SYNC,
expected_origin, expected_origin))
.WillOnce(testing::Return(blink::mojom::PermissionStatus::GRANTED));
EXPECT_TRUE(Register(sync_options_1_));
sync_options_2_.min_interval = 36000;
EXPECT_CALL(*mock_permission_manager,
GetPermissionStatus(PermissionType::PERIODIC_BACKGROUND_SYNC,
expected_origin, expected_origin))
.WillOnce(testing::Return(blink::mojom::PermissionStatus::GRANTED));
EXPECT_TRUE(Register(sync_options_2_));
}
TEST_F(BackgroundSyncManagerTest, TwoRegistrations) {
EXPECT_TRUE(Register(sync_options_1_));
EXPECT_TRUE(Register(sync_options_2_));
}
TEST_F(BackgroundSyncManagerTest, GetRegistrationNonExisting) {
EXPECT_FALSE(GetRegistration(sync_options_1_));
}
TEST_F(BackgroundSyncManagerTest, GetRegistrationExisting) {
EXPECT_TRUE(Register(sync_options_1_));
EXPECT_TRUE(GetRegistration(sync_options_1_));
EXPECT_FALSE(GetRegistration(sync_options_2_));
}
TEST_F(BackgroundSyncManagerTest, GetRegistrationBadBackend) {
EXPECT_TRUE(Register(sync_options_1_));
test_background_sync_manager()->set_corrupt_backend(true);
EXPECT_TRUE(GetRegistration(sync_options_1_));
EXPECT_FALSE(Register(sync_options_2_));
// Registration should have discovered the bad backend and disabled the
// BackgroundSyncManager.
EXPECT_FALSE(GetRegistration(sync_options_1_));
test_background_sync_manager()->set_corrupt_backend(false);