1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
content / browser / background_fetch / background_fetch_service_unittest.cc [blame]
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <map>
#include <memory>
#include <utility>
#include "base/auto_reset.h"
#include "base/functional/bind.h"
#include "base/ranges/algorithm.h"
#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "content/browser/background_fetch/background_fetch_context.h"
#include "content/browser/background_fetch/background_fetch_data_manager_observer.h"
#include "content/browser/background_fetch/background_fetch_job_controller.h"
#include "content/browser/background_fetch/background_fetch_registration_id.h"
#include "content/browser/background_fetch/background_fetch_service_impl.h"
#include "content/browser/background_fetch/background_fetch_test_base.h"
#include "content/browser/background_fetch/background_fetch_test_data_manager.h"
#include "content/browser/background_fetch/background_fetch_test_service_worker.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/storage_partition_impl.h"
#include "content/common/background_fetch/background_fetch_types.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_renderer_host.h"
#include "content/public/test/web_contents_tester.h"
#include "mojo/core/embedder/embedder.h"
#include "mojo/public/cpp/bindings/message.h"
#include "mojo/public/cpp/test_support/fake_message_dispatch_context.h"
#include "mojo/public/cpp/test_support/test_utils.h"
#include "services/network/public/mojom/fetch_api.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/manifest/manifest.h"
#include "third_party/blink/public/common/permissions/permission_utils.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h"
#include "ui/gfx/geometry/size.h"
#include "url/origin.h"
namespace content {
namespace {
using testing::_;
const char kExampleUniqueId[] = "7e57ab1e-c0de-a150-ca75-1e75f005ba11";
const char kExampleDeveloperId[] = "my-background-fetch";
const char kAlternativeDeveloperId[] = "my-alternative-fetch";
blink::Manifest::ImageResource CreateIcon(const std::string& src,
std::vector<gfx::Size> sizes,
const std::string& type) {
blink::Manifest::ImageResource icon;
icon.src = GURL(src);
icon.sizes = std::move(sizes);
icon.type = base::ASCIIToUTF16(type);
return icon;
}
bool ContainsHeader(const base::flat_map<std::string, std::string>& headers,
const std::string& target) {
return base::ranges::any_of(headers, [target](const auto& pair) {
return base::EqualsCaseInsensitiveASCII(pair.first, target);
});
}
std::vector<blink::mojom::FetchAPIRequestPtr> CloneRequestVector(
const std::vector<blink::mojom::FetchAPIRequestPtr>& requests) {
std::vector<blink::mojom::FetchAPIRequestPtr> request_cp;
for (const auto& request : requests) {
request_cp.push_back(BackgroundFetchSettledFetch::CloneRequest(request));
}
return request_cp;
}
} // namespace
class BackgroundFetchServiceTest
: public BackgroundFetchTestBase,
public BackgroundFetchDataManagerObserver,
public ServiceWorkerContextCoreObserver,
public DevToolsBackgroundServicesContextImpl::EventObserver {
public:
BackgroundFetchServiceTest() = default;
BackgroundFetchServiceTest(const BackgroundFetchServiceTest&) = delete;
BackgroundFetchServiceTest& operator=(const BackgroundFetchServiceTest&) =
delete;
~BackgroundFetchServiceTest() override = default;
class ScopedCustomBackgroundFetchService {
public:
ScopedCustomBackgroundFetchService(BackgroundFetchServiceTest* test,
const blink::StorageKey& storage_key)
: scoped_service_(
&test->service_,
std::make_unique<BackgroundFetchServiceImpl>(
test->context_,
storage_key,
net::IsolationInfo(),
test->web_contents_->GetPrimaryMainFrame()->GetProcess(),
/*rfhi=*/nullptr)) {}
ScopedCustomBackgroundFetchService(
const ScopedCustomBackgroundFetchService&) = delete;
ScopedCustomBackgroundFetchService& operator=(
const ScopedCustomBackgroundFetchService&) = delete;
private:
base::AutoReset<std::unique_ptr<BackgroundFetchServiceImpl>>
scoped_service_;
};
// Synchronous wrapper for BackgroundFetchServiceImpl::Fetch().
mojo::Remote<blink::mojom::BackgroundFetchRegistrationService> Fetch(
int64_t service_worker_registration_id,
const std::string& developer_id,
std::vector<blink::mojom::FetchAPIRequestPtr> requests,
blink::mojom::BackgroundFetchOptionsPtr options,
const SkBitmap& icon,
blink::mojom::BackgroundFetchError* out_error,
blink::mojom::BackgroundFetchRegistrationPtr* out_registration) {
DCHECK(out_error);
DCHECK(out_registration);
base::RunLoop run_loop;
service_->Fetch(
service_worker_registration_id, developer_id, std::move(requests),
std::move(options), icon, blink::mojom::BackgroundFetchUkmData::New(),
base::BindOnce(&BackgroundFetchServiceTest::DidGetRegistration,
base::Unretained(this), run_loop.QuitClosure(),
out_error, out_registration));
run_loop.Run();
if (*out_error != blink::mojom::BackgroundFetchError::NONE) {
DCHECK(!(*out_registration)->registration_interface);
return mojo::Remote<blink::mojom::BackgroundFetchRegistrationService>();
}
DCHECK((*out_registration)->registration_interface);
return mojo::Remote<blink::mojom::BackgroundFetchRegistrationService>(
std::move((*out_registration)->registration_interface));
}
// Starts the Fetch without completing it. Only creates a registration.
void StartFetch(int64_t service_worker_registration_id,
const std::string& developer_id,
std::vector<blink::mojom::FetchAPIRequestPtr> requests,
blink::mojom::BackgroundFetchOptionsPtr options,
const SkBitmap& icon) {
BackgroundFetchRegistrationId registration_id(
service_worker_registration_id, storage_key(), developer_id,
kExampleUniqueId);
base::RunLoop run_loop;
context_->data_manager_->CreateRegistration(
registration_id, std::move(requests), std::move(options), icon,
/* start_paused= */ false, net::IsolationInfo(),
base::BindOnce(&BackgroundFetchServiceTest::DidStartFetch,
base::Unretained(this), run_loop.QuitClosure()));
run_loop.Run();
}
// Calls BackgroundFetchServiceImpl::Fetch() and unregisters the service
// worker before Fetch has completed but after the controller has been
// initialized.
void FetchAndUnregisterServiceWorker(
int64_t service_worker_registration_id,
const std::string& developer_id,
std::vector<blink::mojom::FetchAPIRequestPtr> requests,
blink::mojom::BackgroundFetchOptionsPtr options,
const SkBitmap& icon,
blink::mojom::BackgroundFetchError* out_error,
blink::mojom::BackgroundFetchRegistrationPtr* out_registration) {
DCHECK(out_error);
DCHECK(out_registration);
base::RunLoop run_loop;
service_->Fetch(
service_worker_registration_id, developer_id, std::move(requests),
std::move(options), icon, blink::mojom::BackgroundFetchUkmData::New(),
base::BindOnce(&BackgroundFetchServiceTest::DidGetRegistration,
base::Unretained(this), run_loop.QuitClosure(),
out_error, out_registration));
UnregisterServiceWorker(service_worker_registration_id);
run_loop.Run();
}
// Synchronous wrapper for BackgroundFetchServiceImpl::MatchRequests.
void MatchAllRequests(
const mojo::Remote<blink::mojom::BackgroundFetchRegistrationService>&
registration_service,
std::vector<blink::mojom::BackgroundFetchSettledFetchPtr>* out_fetches) {
DCHECK(registration_service);
DCHECK(out_fetches);
base::RunLoop run_loop;
registration_service->MatchRequests(
/* request_to_match= */ nullptr,
/* cache_query_options= */ nullptr, /* match_all= */ true,
base::BindOnce(&BackgroundFetchServiceTest::DidMatchAllRequests,
base::Unretained(this), run_loop.QuitClosure(),
out_fetches));
run_loop.Run();
}
// Synchronous wrapper for BackgroundFetchServiceImpl::UpdateUI().
void UpdateUI(
const mojo::Remote<blink::mojom::BackgroundFetchRegistrationService>&
registration_service,
const std::string& title,
blink::mojom::BackgroundFetchError* out_error) {
DCHECK(registration_service);
DCHECK(out_error);
base::RunLoop run_loop;
registration_service->UpdateUI(
title, SkBitmap(),
base::BindOnce(&BackgroundFetchServiceTest::DidGetError,
base::Unretained(this), run_loop.QuitClosure(),
out_error));
run_loop.Run();
}
// Synchronous wrapper for BackgroundFetchServiceImpl::Abort().
void Abort(
const mojo::Remote<blink::mojom::BackgroundFetchRegistrationService>&
registration_service,
blink::mojom::BackgroundFetchError* out_error) {
DCHECK(registration_service);
DCHECK(out_error);
base::RunLoop run_loop;
registration_service->Abort(base::BindOnce(
&BackgroundFetchServiceTest::DidGetError, base::Unretained(this),
run_loop.QuitClosure(), out_error));
run_loop.Run();
}
// Synchronous wrapper for BackgroundFetchServiceImpl::GetRegistration().
void GetRegistration(
int64_t service_worker_registration_id,
const std::string& developer_id,
blink::mojom::BackgroundFetchError* out_error,
blink::mojom::BackgroundFetchRegistrationPtr* out_registration) {
DCHECK(out_error);
DCHECK(out_registration);
base::RunLoop run_loop;
service_->GetRegistration(
service_worker_registration_id, developer_id,
base::BindOnce(&BackgroundFetchServiceTest::DidGetRegistration,
base::Unretained(this), run_loop.QuitClosure(),
out_error, out_registration));
run_loop.Run();
}
// Synchronous wrapper for BackgroundFetchServiceImpl::GetDeveloperIds().
void GetDeveloperIds(int64_t service_worker_registration_id,
blink::mojom::BackgroundFetchError* out_error,
std::vector<std::string>* out_developer_ids) {
DCHECK(out_error);
DCHECK(out_developer_ids);
base::RunLoop run_loop;
service_->GetDeveloperIds(
service_worker_registration_id,
base::BindOnce(&BackgroundFetchServiceTest::DidGetDeveloperIds,
base::Unretained(this), run_loop.QuitClosure(),
out_error, out_developer_ids));
run_loop.Run();
}
// BackgroundFetchTestBase overrides:
void SetUp() override {
BackgroundFetchTestBase::SetUp();
context_ = base::MakeRefCounted<BackgroundFetchContext>(
storage_partition(),
base::WrapRefCounted(embedded_worker_test_helper()->context_wrapper()),
/* quota_manager_proxy= */ nullptr, devtools_context());
context_->SetDataManagerForTesting(
std::make_unique<BackgroundFetchTestDataManager>(
browser_context(), storage_partition(),
embedded_worker_test_helper()->context_wrapper()));
context_->data_manager_->AddObserver(this);
embedded_worker_test_helper()->context_wrapper()->AddObserver(this);
devtools_context().AddObserver(this);
web_contents_ = base::WrapUnique(WebContentsTester::CreateTestWebContents(
WebContents::CreateParams(browser_context())));
std::unique_ptr<MockPermissionManager> mock_permission_manager(
new testing::NiceMock<MockPermissionManager>());
ON_CALL(*mock_permission_manager,
GetPermissionStatus(blink::PermissionType::BACKGROUND_FETCH, _, _))
.WillByDefault(
testing::Return(blink::mojom::PermissionStatus::GRANTED));
browser_context()->SetPermissionControllerDelegate(
std::move(mock_permission_manager));
context_->Initialize();
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(web_contents_->GetPrimaryMainFrame());
service_ = std::make_unique<BackgroundFetchServiceImpl>(
context_, storage_key(), net::IsolationInfo(),
web_contents_->GetPrimaryMainFrame()->GetProcess(), rfhi);
rfhi->SetLastCommittedOriginForTesting(storage_key().origin());
}
void TearDown() override {
BackgroundFetchTestBase::TearDown();
service_.reset();
devtools_context().RemoveObserver(this);
embedded_worker_test_helper()->context_wrapper()->RemoveObserver(this);
context_->data_manager_->RemoveObserver(this);
context_ = nullptr;
// Give pending shutdown operations a chance to finish.
base::RunLoop().RunUntilIdle();
}
// BackgroundFetchDataManagerObserver implementation & mocks:
MOCK_METHOD7(OnRegistrationCreated,
void(const BackgroundFetchRegistrationId& registration_id,
const blink::mojom::BackgroundFetchRegistrationData&
registration_data,
blink::mojom::BackgroundFetchOptionsPtr options,
const SkBitmap& icon,
int num_requests,
bool start_paused,
net::IsolationInfo isolation_info));
MOCK_METHOD8(OnRegistrationLoadedAtStartup,
void(const BackgroundFetchRegistrationId& registration_id,
const blink::mojom::BackgroundFetchRegistrationData&
registration_data,
blink::mojom::BackgroundFetchOptionsPtr options,
const SkBitmap& icon,
int num_completed_requests,
int num_requests,
std::vector<scoped_refptr<BackgroundFetchRequestInfo>>
active_fetch_requests,
std::optional<net::IsolationInfo> isolation_info));
MOCK_METHOD2(
OnRegistrationQueried,
void(const BackgroundFetchRegistrationId& registration_id,
blink::mojom::BackgroundFetchRegistrationData* registration_data));
MOCK_METHOD1(OnServiceWorkerDatabaseCorrupted,
void(int64_t service_worker_registration_id));
MOCK_METHOD3(OnRequestCompleted,
void(const std::string& unique_id,
blink::mojom::FetchAPIRequestPtr request,
blink::mojom::FetchAPIResponsePtr response));
// ServiceWorkerContextCoreObserver implementation.
MOCK_METHOD3(OnRegistrationDeleted,
void(int64_t registration_id,
const GURL& pattern,
const blink::StorageKey& key));
MOCK_METHOD0(OnStorageWiped, void());
// DevToolsBackgroundServicesContext::EventObserver implementation.
MOCK_METHOD1(OnEventReceived,
void(const devtools::proto::BackgroundServiceEvent&));
MOCK_METHOD2(OnRecordingStateChanged,
void(bool, devtools::proto::BackgroundService));
protected:
blink::mojom::FetchAPIRequestPtr CreateDefaultRequest() {
return CreateRequestWithProvidedResponse(
"GET", GURL("https://example.com/funny_cat.txt"),
TestResponseBuilder(200).MakeIndefinitelyPending().Build());
}
scoped_refptr<BackgroundFetchContext> context_;
private:
void DidGetRegistration(
base::OnceClosure quit_closure,
blink::mojom::BackgroundFetchError* out_error,
blink::mojom::BackgroundFetchRegistrationPtr* out_registration,
blink::mojom::BackgroundFetchError error,
blink::mojom::BackgroundFetchRegistrationPtr registration) {
*out_error = error;
*out_registration = registration
? std::move(registration)
: blink::mojom::BackgroundFetchRegistration::New();
std::move(quit_closure).Run();
}
void DidStartFetch(
base::OnceClosure quit_closure,
blink::mojom::BackgroundFetchError error,
blink::mojom::BackgroundFetchRegistrationDataPtr registration_data) {
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
std::move(quit_closure).Run();
}
void DidGetError(base::OnceClosure quit_closure,
blink::mojom::BackgroundFetchError* out_error,
blink::mojom::BackgroundFetchError error) {
*out_error = error;
std::move(quit_closure).Run();
}
void DidGetDeveloperIds(base::OnceClosure quit_closure,
blink::mojom::BackgroundFetchError* out_error,
std::vector<std::string>* out_developer_ids,
blink::mojom::BackgroundFetchError error,
const std::vector<std::string>& developer_ids) {
*out_error = error;
*out_developer_ids = developer_ids;
std::move(quit_closure).Run();
}
void DidMatchAllRequests(
base::OnceClosure quit_closure,
std::vector<blink::mojom::BackgroundFetchSettledFetchPtr>* out_fetches,
std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> fetches) {
for (const auto& in_fetch : fetches) {
auto out_fetch = blink::mojom::BackgroundFetchSettledFetch::New();
out_fetch->request =
BackgroundFetchSettledFetch::CloneRequest(in_fetch->request);
out_fetch->response =
BackgroundFetchSettledFetch::CloneResponse(in_fetch->response);
out_fetches->push_back(std::move(out_fetch));
}
std::move(quit_closure).Run();
}
RenderViewHostTestEnabler enabler_;
std::unique_ptr<content::WebContents> web_contents_;
std::unique_ptr<BackgroundFetchServiceImpl> service_;
};
TEST_F(BackgroundFetchServiceTest, FetchInvalidArguments) {
// This test verifies that the Fetch() function will kill the renderer and
// return INVALID_ARGUMENT when invalid data is send over the Mojo channel.
auto options = blink::mojom::BackgroundFetchOptions::New();
// The |developer_id| must be a non-empty string.
{
mojo::FakeMessageDispatchContext fake_dispatch_context;
mojo::test::BadMessageObserver bad_message_observer;
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateDefaultRequest());
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
Fetch(/* service_worker_registration_id= */ 42, /* developer_id= */ "",
std::move(requests), options.Clone(), SkBitmap(), &error,
®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::INVALID_ARGUMENT);
EXPECT_EQ("Invalid developer_id", bad_message_observer.WaitForBadMessage());
}
// At least a single blink::mojom::FetchAPIRequestPtr must be given.
{
mojo::FakeMessageDispatchContext fake_dispatch_context;
mojo::test::BadMessageObserver bad_message_observer;
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
// |requests| has deliberately been left empty.
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
Fetch(/* service_worker_registration_id= */ 42, kExampleDeveloperId,
std::move(requests), std::move(options), SkBitmap(), &error,
®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::INVALID_ARGUMENT);
EXPECT_EQ("Invalid requests", bad_message_observer.WaitForBadMessage());
}
}
TEST_F(BackgroundFetchServiceTest, FetchRegistrationProperties) {
// This test starts a new Background Fetch and verifies that the returned
// blink::mojom::BackgroundFetchRegistration object matches the given options.
// Then gets the active Background Fetch with the same |developer_id|, and
// verifies that.
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateDefaultRequest());
auto options = blink::mojom::BackgroundFetchOptions::New();
options->icons.push_back(
CreateIcon("funny_cat.png", {{256, 256}}, "image/png"));
options->icons.push_back(
CreateIcon("silly_cat.gif", {{512, 512}}, "image/gif"));
options->title = "My Background Fetch!";
options->download_total = 9001;
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
Fetch(service_worker_registration_id, kExampleDeveloperId,
std::move(requests), options.Clone(), SkBitmap(), &error,
®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
// The |registration| should reflect the options given in |options|.
EXPECT_EQ(registration->registration_data->developer_id, kExampleDeveloperId);
EXPECT_EQ(registration->registration_data->download_total,
options->download_total);
blink::mojom::BackgroundFetchError second_error;
blink::mojom::BackgroundFetchRegistrationPtr second_registration;
GetRegistration(service_worker_registration_id, kExampleDeveloperId,
&second_error, &second_registration);
ASSERT_EQ(second_error, blink::mojom::BackgroundFetchError::NONE);
// The |second_registration| should reflect the options given in |options|.
EXPECT_EQ(second_registration->registration_data->developer_id,
kExampleDeveloperId);
EXPECT_EQ(second_registration->registration_data->download_total,
options->download_total);
}
TEST_F(BackgroundFetchServiceTest, FetchDuplicatedRegistrationFailure) {
// This tests starts a new Background Fetch, verifies that a registration was
// successfully created, and then tries to start a second fetch for the same
// registration. This should fail with a DUPLICATED_DEVELOPER_ID error.
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateDefaultRequest());
auto options = blink::mojom::BackgroundFetchOptions::New();
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
// Create the first registration. This must succeed.
Fetch(service_worker_registration_id, kExampleDeveloperId,
CloneRequestVector(requests), options.Clone(), SkBitmap(), &error,
®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
blink::mojom::BackgroundFetchError second_error;
blink::mojom::BackgroundFetchRegistrationPtr second_registration;
// Create the second registration with the same data. This must fail.
Fetch(service_worker_registration_id, kExampleDeveloperId,
std::move(requests), std::move(options), SkBitmap(), &second_error,
&second_registration);
ASSERT_EQ(second_error,
blink::mojom::BackgroundFetchError::DUPLICATED_DEVELOPER_ID);
}
TEST_F(BackgroundFetchServiceTest, FetchSuccessEventDispatch) {
// This test starts a new Background Fetch, completes the registration, then
// fetches all files to complete the job, and then verifies that the
// `backgroundfetchsuccess` event will be dispatched with the expected
// contents.
auto* worker =
embedded_worker_test_helper()
->AddNewPendingServiceWorker<BackgroundFetchTestServiceWorker>(
embedded_worker_test_helper());
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
// base::RunLoop that we'll run until the event has been dispatched. If this
// test times out, it means that the event could not be dispatched.
base::RunLoop event_dispatched_loop;
worker->set_fetched_event_closure(event_dispatched_loop.QuitClosure());
// Don't dispatch the event so the background fetch's response cache is not
// deleted.
worker->delay_dispatch();
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
constexpr int kFirstResponseCode = 200;
constexpr int kSecondResponseCode = 201;
constexpr int kThirdResponseCode = 200;
requests.push_back(CreateRequestWithProvidedResponse(
"GET", GURL("https://example.com/funny_cat.txt"),
TestResponseBuilder(kFirstResponseCode)
.SetResponseData(
"This text describes a scenario involving a funny cat.")
.AddResponseHeader("Content-Type", "text/plain")
.AddResponseHeader("X-Cat", "yes")
.Build()));
requests.push_back(CreateRequestWithProvidedResponse(
"GET", GURL("https://example.com/crazy_cat.txt"),
TestResponseBuilder(kSecondResponseCode)
.SetResponseData(
"This text describes another scenario that involves a crazy cat.")
.AddResponseHeader("Content-Type", "text/plain")
.Build()));
requests.push_back(CreateRequestWithProvidedResponse(
"GET", GURL("https://chrome.com/accessible_cross_origin_cat.txt"),
TestResponseBuilder(kThirdResponseCode)
.SetResponseData("This cat originates from another origin.")
.AddResponseHeader("Access-Control-Allow-Origin", "*")
.AddResponseHeader("Content-Type", "text/plain")
.Build()));
// Create the registration with the given |requests|.
blink::mojom::BackgroundFetchRegistrationPtr registration;
mojo::Remote<blink::mojom::BackgroundFetchRegistrationService>
registration_service;
auto options = blink::mojom::BackgroundFetchOptions::New();
blink::mojom::BackgroundFetchError error;
// Create the first registration. This must succeed.
registration_service =
Fetch(service_worker_registration_id, kExampleDeveloperId,
CloneRequestVector(requests), std::move(options), SkBitmap(),
&error, ®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
// Spin the |event_dispatched_loop| to wait for the dispatched event.
event_dispatched_loop.Run();
ASSERT_TRUE(worker->last_registration());
EXPECT_EQ(kExampleDeveloperId, registration->registration_data->developer_id);
// Get all the settled fetches and test properties.
std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> fetches;
MatchAllRequests(registration_service, &fetches);
ASSERT_EQ(fetches.size(), requests.size());
for (size_t i = 0; i < fetches.size(); ++i) {
ASSERT_EQ(fetches[i]->request->url, requests[i]->url);
EXPECT_EQ(fetches[i]->request->method, requests[i]->method);
EXPECT_EQ(fetches[i]->response->url_list[0], fetches[i]->request->url);
EXPECT_EQ(fetches[i]->response->response_type,
network::mojom::FetchResponseType::kDefault);
switch (i) {
case 0:
EXPECT_EQ(fetches[i]->response->status_code, kFirstResponseCode);
EXPECT_TRUE(
ContainsHeader(fetches[i]->response->headers, "Content-Type"));
EXPECT_TRUE(ContainsHeader(fetches[i]->response->headers, "X-Cat"));
break;
case 1:
EXPECT_EQ(fetches[i]->response->status_code, kSecondResponseCode);
EXPECT_TRUE(
ContainsHeader(fetches[i]->response->headers, "Content-Type"));
EXPECT_FALSE(ContainsHeader(fetches[i]->response->headers, "X-Cat"));
break;
case 2:
EXPECT_EQ(fetches[i]->response->status_code, kThirdResponseCode);
EXPECT_TRUE(
ContainsHeader(fetches[i]->response->headers, "Content-Type"));
EXPECT_FALSE(ContainsHeader(fetches[i]->response->headers, "X-Cat"));
break;
default:
NOTREACHED_IN_MIGRATION();
}
// TODO(peter): change-detector tests for unsupported properties.
EXPECT_EQ(fetches[i]->response->error,
blink::mojom::ServiceWorkerResponseError::kUnknown);
// Verify that all properties have a sensible value.
EXPECT_FALSE(fetches[i]->response->response_time.is_null());
// Verify that the response blobs have been populated. We cannot consume
// their data here since the handles have already been released.
ASSERT_TRUE(fetches[i]->response->blob);
ASSERT_FALSE(fetches[i]->response->blob->uuid.empty());
ASSERT_GT(fetches[i]->response->blob->size, 0u);
}
}
TEST_F(BackgroundFetchServiceTest, FetchFailEventDispatch) {
// This test verifies that the fail event will be fired when a response either
// has a non-OK status code, or the response cannot be accessed due to CORS.
auto* worker =
embedded_worker_test_helper()
->AddNewPendingServiceWorker<BackgroundFetchTestServiceWorker>(
embedded_worker_test_helper());
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
// base::RunLoop that we'll run until the event has been dispatched. If this
// test times out, it means that the event could not be dispatched.
base::RunLoop event_dispatched_loop;
worker->set_fetch_fail_event_closure(event_dispatched_loop.QuitClosure());
// Don't dispatch the event so the background fetch's response cache is not
// deleted.
worker->delay_dispatch();
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
constexpr int kFirstResponseCode = 404;
constexpr int kSecondResponseCode = 200;
requests.push_back(CreateRequestWithProvidedResponse(
"GET", GURL("https://example.com/not_existing_cat.txt"),
TestResponseBuilder(kFirstResponseCode).Build()));
requests.push_back(CreateRequestWithProvidedResponse(
"GET", GURL("https://chrome.com/inaccessible_cross_origin_cat.txt"),
TestResponseBuilder(kSecondResponseCode)
.SetResponseData(
"This is a cross-origin response not accessible to the reader.")
.AddResponseHeader("Content-Type", "text/plain")
.Build()));
// Create the registration with the given |requests|.
blink::mojom::BackgroundFetchRegistrationPtr registration;
mojo::Remote<blink::mojom::BackgroundFetchRegistrationService>
registration_service;
{
auto options = blink::mojom::BackgroundFetchOptions::New();
blink::mojom::BackgroundFetchError error;
// Create the first registration. This must succeed.
registration_service =
Fetch(service_worker_registration_id, kExampleDeveloperId,
CloneRequestVector(requests), std::move(options), SkBitmap(),
&error, ®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
// Spin the |event_dispatched_loop| to wait for the dispatched event.
event_dispatched_loop.Run();
ASSERT_TRUE(worker->last_registration());
EXPECT_EQ(kExampleDeveloperId, registration->registration_data->developer_id);
// Get all the settled fetches and test properties.
std::vector<blink::mojom::BackgroundFetchSettledFetchPtr> fetches;
MatchAllRequests(registration_service, &fetches);
ASSERT_EQ(fetches.size(), 2u);
// Make sure the 404 request is first, which has a response.
if (!fetches[0]->response)
std::swap(fetches[0], fetches[1]);
for (size_t i = 0; i < fetches.size(); ++i) {
ASSERT_EQ(fetches[i]->request->url, requests[i]->url);
EXPECT_EQ(fetches[i]->request->method, requests[i]->method);
switch (i) {
case 0:
EXPECT_EQ(fetches[i]->response->status_code, 404);
EXPECT_EQ(fetches[i]->response->url_list[0], fetches[i]->request->url);
EXPECT_EQ(fetches[i]->response->response_type,
network::mojom::FetchResponseType::kDefault);
break;
case 1:
EXPECT_FALSE(fetches[i]->response);
continue;
default:
NOTREACHED_IN_MIGRATION();
}
EXPECT_TRUE(fetches[i]->response->headers.empty());
EXPECT_FALSE(fetches[i]->response->blob);
EXPECT_FALSE(fetches[i]->response->response_time.is_null());
// TODO(peter): change-detector tests for unsupported properties.
EXPECT_EQ(fetches[i]->response->error,
blink::mojom::ServiceWorkerResponseError::kUnknown);
EXPECT_TRUE(fetches[i]->response->cors_exposed_header_names.empty());
}
}
TEST_F(BackgroundFetchServiceTest, UpdateUI) {
// This test starts a new Background Fetch, completes the registration, and
// checks that updates to the title using UpdateUI are successfully reflected
// back when calling GetRegistration.
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateDefaultRequest());
auto options = blink::mojom::BackgroundFetchOptions::New();
options->title = "1st title";
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
// Create the registration.
auto registration_service = Fetch(
service_worker_registration_id, kExampleDeveloperId, std::move(requests),
std::move(options), SkBitmap(), &error, ®istration);
ASSERT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
std::string second_title = "2nd title";
// Immediately update the title. This should succeed.
UpdateUI(registration_service, second_title, &error);
EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
blink::mojom::BackgroundFetchRegistrationPtr second_registration;
// GetRegistration should now resolve with the updated title.
GetRegistration(service_worker_registration_id, kExampleDeveloperId, &error,
&second_registration);
ASSERT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
}
TEST_F(BackgroundFetchServiceTest, Abort) {
// This test starts a new Background Fetch, completes the registration, and
// then aborts the Background Fetch mid-process.
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateDefaultRequest());
auto options = blink::mojom::BackgroundFetchOptions::New();
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
// Create the registration. This must succeed.
auto registration_service = Fetch(
service_worker_registration_id, kExampleDeveloperId, std::move(requests),
std::move(options), SkBitmap(), &error, ®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
blink::mojom::BackgroundFetchError abort_error;
// Immediately abort the registration. This also is expected to succeed.
Abort(registration_service, &abort_error);
ASSERT_EQ(abort_error, blink::mojom::BackgroundFetchError::NONE);
// Wait for the response of the Mojo IPC to dispatch
// BackgroundFetchAbortEvent.
base::RunLoop().RunUntilIdle();
blink::mojom::BackgroundFetchError second_error;
blink::mojom::BackgroundFetchRegistrationPtr second_registration;
// Now try to get the created registration, which is expected to fail.
GetRegistration(service_worker_registration_id, kExampleDeveloperId,
&second_error, &second_registration);
ASSERT_EQ(second_error, blink::mojom::BackgroundFetchError::INVALID_ID);
auto* delegate = static_cast<MockBackgroundFetchDelegate*>(
browser_context()->GetBackgroundFetchDelegate());
EXPECT_FALSE(delegate->completed_jobs().empty());
}
TEST_F(BackgroundFetchServiceTest, AbortEventDispatch) {
// Tests that the `backgroundfetchabort` event will be fired when a Background
// Fetch registration has been aborted by either the user or developer.
auto* worker =
embedded_worker_test_helper()
->AddNewPendingServiceWorker<BackgroundFetchTestServiceWorker>(
embedded_worker_test_helper());
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
// base::RunLoop that we'll run until the event has been dispatched. If this
// test times out, it means that the event could not be dispatched.
base::RunLoop event_dispatched_loop;
worker->set_abort_event_closure(event_dispatched_loop.QuitClosure());
constexpr int kResponseCode = 200;
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateRequestWithProvidedResponse(
"GET", GURL("https://example.com/funny_cat.txt"),
TestResponseBuilder(kResponseCode)
.SetResponseData("Random data about a funny cat.")
.Build()));
// Create the registration with the given |requests|.
mojo::Remote<blink::mojom::BackgroundFetchRegistrationService>
registration_service;
{
auto options = blink::mojom::BackgroundFetchOptions::New();
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
// Create the registration. This must succeed.
registration_service =
Fetch(service_worker_registration_id, kExampleDeveloperId,
std::move(requests), std::move(options), SkBitmap(), &error,
®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
// Immediately abort the request created for the |registration_id|. Then wait
// for the `backgroundfetchabort` event to have been invoked.
{
blink::mojom::BackgroundFetchError error;
Abort(registration_service, &error);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
event_dispatched_loop.Run();
ASSERT_TRUE(worker->last_registration());
EXPECT_EQ(kExampleDeveloperId, worker->last_registration()->developer_id);
}
TEST_F(BackgroundFetchServiceTest, UniqueId) {
// Tests that Abort() and UpdateUI() update the correct Background Fetch
// registration, according to the registration's |unique_id|, rather than
// keying off the |developer_id| provided by JavaScript, since multiple
// registrations can share an |developer_id| if JavaScript holds a reference
// to a blink::mojom::BackgroundFetchRegistration object after that
// registration is completed/failed/aborted and then creates a new
// registration with the same |developer_id|.
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateDefaultRequest());
blink::mojom::BackgroundFetchError error;
// Create the first registration, that we will soon abort.
auto aborted_options = blink::mojom::BackgroundFetchOptions::New();
aborted_options->title = "Aborted";
blink::mojom::BackgroundFetchRegistrationPtr aborted_registration;
auto registration_service =
Fetch(service_worker_registration_id, kExampleDeveloperId,
CloneRequestVector(requests), std::move(aborted_options),
SkBitmap(), &error, &aborted_registration);
ASSERT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
// Immediately abort the registration so it is no longer active (everything
// that follows should behave the same if the registration had completed
// instead of being aborted).
Abort(registration_service, &error);
ASSERT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
// Wait for response of the Mojo IPC to dispatch BackgroundFetchAbortEvent.
base::RunLoop().RunUntilIdle();
// Create a second registration sharing the same |developer_id|. Should
// succeed.
auto second_options = blink::mojom::BackgroundFetchOptions::New();
second_options->title = "Second";
blink::mojom::BackgroundFetchRegistrationPtr second_registration;
auto second_registration_service = Fetch(
service_worker_registration_id, kExampleDeveloperId, std::move(requests),
std::move(second_options), SkBitmap(), &error, &second_registration);
EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
// Now try to get the registration using its |developer_id|. This should
// return the second registration since that is the active one.
blink::mojom::BackgroundFetchRegistrationPtr gotten_registration;
GetRegistration(service_worker_registration_id, kExampleDeveloperId, &error,
&gotten_registration);
EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
// Calling UpdateUI for the second registration should succeed, and update the
// title of the second registration only.
std::string updated_second_registration_title = "Foo";
UpdateUI(second_registration_service, updated_second_registration_title,
&error);
EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
// Verify that the second registration's title was indeed updated, and that it
// wasn't affected by the subsequent call to UpdateUI for the aborted
// registration, by getting the second registration again.
GetRegistration(service_worker_registration_id, kExampleDeveloperId, &error,
&gotten_registration);
EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
// Aborting the previously aborted registration should fail with INVALID_ID
// since it is no longer active.
Abort(registration_service, &error);
EXPECT_EQ(blink::mojom::BackgroundFetchError::INVALID_ID, error);
// Wait for response of the Mojo IPC to dispatch BackgroundFetchAbortEvent.
// (MockBackgroundFetchDelegate won't complete/fail second_registration in the
// meantime, since this test deliberately doesn't register a response).
base::RunLoop().RunUntilIdle();
// Getting the second registration should still succeed.
GetRegistration(service_worker_registration_id, kExampleDeveloperId, &error,
&gotten_registration);
EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
// Aborting the second registration should succeed.
Abort(second_registration_service, &error);
EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error);
// Wait for response of the Mojo IPC to dispatch BackgroundFetchAbortEvent.
// (MockBackgroundFetchDelegate won't complete/fail second_registration in the
// meantime, since this test deliberately doesn't register a response).
base::RunLoop().RunUntilIdle();
// Getting the second registration should now fail as it is no longer active.
GetRegistration(service_worker_registration_id, kExampleDeveloperId, &error,
&gotten_registration);
EXPECT_EQ(blink::mojom::BackgroundFetchError::INVALID_ID, error);
}
TEST_F(BackgroundFetchServiceTest, GetDeveloperIds) {
// This test verifies that the list of active |developer_id|s can be retrieved
// from the service for a given Service Worker, as extracted from a
// registration.
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateDefaultRequest());
auto options = blink::mojom::BackgroundFetchOptions::New();
// Verify that there are no active |developer_id|s yet.
{
blink::mojom::BackgroundFetchError error;
std::vector<std::string> developer_ids;
GetDeveloperIds(service_worker_registration_id, &error, &developer_ids);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
ASSERT_EQ(developer_ids.size(), 0u);
}
// Start the Background Fetch for the |registration_id|.
{
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
Fetch(service_worker_registration_id, kExampleDeveloperId,
CloneRequestVector(requests), options.Clone(), SkBitmap(), &error,
®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
// Verify that there is a single active fetch (the one we just started).
{
blink::mojom::BackgroundFetchError error;
std::vector<std::string> developer_ids;
GetDeveloperIds(service_worker_registration_id, &error, &developer_ids);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
ASSERT_EQ(developer_ids.size(), 1u);
EXPECT_EQ(developer_ids[0], kExampleDeveloperId);
}
// Start the Background Fetch for the |second_registration_id|.
{
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
Fetch(service_worker_registration_id, kAlternativeDeveloperId,
std::move(requests), std::move(options), SkBitmap(), &error,
®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
// Verify that there are two active fetches.
{
blink::mojom::BackgroundFetchError error;
std::vector<std::string> developer_ids;
GetDeveloperIds(service_worker_registration_id, &error, &developer_ids);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
ASSERT_EQ(developer_ids.size(), 2u);
// Both |developer_id|s should be present, in either order.
EXPECT_TRUE(developer_ids[0] == kExampleDeveloperId ||
developer_ids[1] == kExampleDeveloperId);
EXPECT_TRUE(developer_ids[0] == kAlternativeDeveloperId ||
developer_ids[1] == kAlternativeDeveloperId);
}
// Verify that using the wrong origin does not return developer ids even if
// the service worker registration is correct.
{
ScopedCustomBackgroundFetchService scoped_bogus_url_service(
this, blink::StorageKey::CreateFromStringForTesting(
"https://www.bogus-origin.com"));
blink::mojom::BackgroundFetchError error;
std::vector<std::string> developer_ids;
GetDeveloperIds(service_worker_registration_id, &error, &developer_ids);
EXPECT_EQ(error, blink::mojom::BackgroundFetchError::STORAGE_ERROR);
EXPECT_TRUE(developer_ids.empty());
}
// Verify that using the wrong service worker id does not return developer ids
// even if the origin is correct.
{
blink::mojom::BackgroundFetchError error;
std::vector<std::string> developer_ids;
int64_t bogus_service_worker_registration_id =
service_worker_registration_id + 1;
GetDeveloperIds(bogus_service_worker_registration_id, &error,
&developer_ids);
EXPECT_EQ(error, blink::mojom::BackgroundFetchError::STORAGE_ERROR);
EXPECT_TRUE(developer_ids.empty());
}
}
TEST_F(BackgroundFetchServiceTest, UnregisterServiceWorker) {
// This test registers a service worker, and calls fetch, but unregisters the
// service worker before fetch has finished. We then verify that the
// appropriate error is returned from Fetch().
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateDefaultRequest());
auto options = blink::mojom::BackgroundFetchOptions::New();
options->icons.push_back(
CreateIcon("funny_cat.png", {{256, 256}}, "image/png"));
options->icons.push_back(
CreateIcon("silly_cat.gif", {{512, 512}}, "image/gif"));
options->title = "My Background Fetch!";
options->download_total = 9001;
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
{
using blink::mojom::BackgroundFetchError;
EXPECT_CALL(*this,
OnRegistrationDeleted(service_worker_registration_id, _, _));
FetchAndUnregisterServiceWorker(service_worker_registration_id,
kExampleDeveloperId, std::move(requests),
std::move(options), SkBitmap(), &error,
®istration);
// There's a race condition between aborting due to unregistering the
// Service Worker, and a STORAGE_ERROR caused by the DatabaseTask as a
// result.
ASSERT_TRUE(error == BackgroundFetchError::STORAGE_ERROR ||
error == BackgroundFetchError::SERVICE_WORKER_UNAVAILABLE);
}
}
TEST_F(BackgroundFetchServiceTest, JobsInitializedOnBrowserRestart) {
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateDefaultRequest());
auto options = blink::mojom::BackgroundFetchOptions::New();
blink::mojom::BackgroundFetchError error;
blink::mojom::BackgroundFetchRegistrationPtr registration;
// Start the fetch. The request is indefinitley pending so this will never
// finish.
{
EXPECT_CALL(*this, OnRegistrationCreated(_, _, _, _, _, _, _));
Fetch(service_worker_registration_id, kExampleDeveloperId,
std::move(requests), std::move(options), SkBitmap(), &error,
®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
// Check that the registration is in the DB.
{
std::vector<std::string> developer_ids;
GetDeveloperIds(service_worker_registration_id, &error, &developer_ids);
EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
ASSERT_EQ(developer_ids.size(), 1u);
EXPECT_EQ(developer_ids[0], kExampleDeveloperId);
}
// Simulate browser restart by re-creating |context_| and |service_|.
context_->Shutdown();
task_environment_.RunUntilIdle();
TearDown();
SetUp();
// Overwrite pending request with a completable version.
CreateRequestWithProvidedResponse(
"GET", GURL("https://example.com/funny_cat.txt"),
TestResponseBuilder(200)
.SetResponseData("This request is no longer indefinitely pending.")
.Build());
{
EXPECT_CALL(*this, OnRegistrationLoadedAtStartup(_, _, _, _, _, _, _, _));
// Allow restart process to go through.
task_environment_.RunUntilIdle();
}
// Check that the registration is not in the DB, which means it completed.
{
std::vector<std::string> developer_ids;
GetDeveloperIds(service_worker_registration_id, &error, &developer_ids);
EXPECT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
ASSERT_EQ(developer_ids.size(), 0u);
}
}
TEST_F(BackgroundFetchServiceTest,
DevToolsContextReceivesBackgroundFetchEvents) {
// Allow the DevTools Context to log Background Fetch events.
devtools_context().StartRecording(devtools::proto::BACKGROUND_FETCH);
// Start a fetch and wait for it to complete.
auto* worker =
embedded_worker_test_helper()
->AddNewPendingServiceWorker<BackgroundFetchTestServiceWorker>(
embedded_worker_test_helper());
int64_t service_worker_registration_id = RegisterServiceWorker();
ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId,
service_worker_registration_id);
// base::RunLoop that we'll run until the event has been dispatched. If this
// test times out, it means that the event could not be dispatched.
base::RunLoop event_dispatched_loop;
worker->set_fetched_event_closure(event_dispatched_loop.QuitClosure());
std::vector<blink::mojom::FetchAPIRequestPtr> requests;
requests.push_back(CreateRequestWithProvidedResponse(
"GET", GURL("https://example.com/funny_cat.txt?id=1"),
TestResponseBuilder(200)
.SetResponseData("Cat 1")
.AddResponseHeader("Content-Type", "text/plain")
.AddResponseHeader("X-Cat", "yes")
.Build()));
requests.push_back(CreateRequestWithProvidedResponse(
"GET", GURL("https://example.com/funny_cat.txt?id=2"),
TestResponseBuilder(200)
.SetResponseData("Cat 2")
.AddResponseHeader("Content-Type", "text/plain")
.AddResponseHeader("X-Cat", "yes")
.Build()));
// We expect to receive the following events:
// 1 Registration + 1 Scheduling
// 1 Start + 1 Finish for each request.
// 1 Fetch completion (event dispatch).
EXPECT_CALL(*this, OnEventReceived(_)).Times(7);
// Create the registration with the given |requests|.
blink::mojom::BackgroundFetchRegistrationPtr registration;
{
auto options = blink::mojom::BackgroundFetchOptions::New();
blink::mojom::BackgroundFetchError error;
// Create the first registration. This must succeed.
Fetch(service_worker_registration_id, kExampleDeveloperId,
CloneRequestVector(requests), std::move(options), SkBitmap(), &error,
®istration);
ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE);
}
// Spin the |event_dispatched_loop| to wait for the dispatched event.
event_dispatched_loop.Run();
}
} // namespace content