summaryrefslogtreecommitdiffstats
path: root/services/sync/tests/unit/test_syncscheduler.js
blob: 98b7937da37a2189cdbf7f8543fe685453b51093 (plain)
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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

const { FxAccounts } = ChromeUtils.importESModule(
  "resource://gre/modules/FxAccounts.sys.mjs"
);
const { SyncAuthManager } = ChromeUtils.importESModule(
  "resource://services-sync/sync_auth.sys.mjs"
);
const { SyncScheduler } = ChromeUtils.importESModule(
  "resource://services-sync/policies.sys.mjs"
);
const { Service } = ChromeUtils.importESModule(
  "resource://services-sync/service.sys.mjs"
);
const { Status } = ChromeUtils.importESModule(
  "resource://services-sync/status.sys.mjs"
);

function CatapultEngine() {
  SyncEngine.call(this, "Catapult", Service);
}
CatapultEngine.prototype = {
  exception: null, // tests fill this in
  async _sync() {
    throw this.exception;
  },
};
Object.setPrototypeOf(CatapultEngine.prototype, SyncEngine.prototype);

var scheduler = new SyncScheduler(Service);
let clientsEngine;

async function sync_httpd_setup() {
  let clientsSyncID = await clientsEngine.resetLocalSyncID();
  let global = new ServerWBO("global", {
    syncID: Service.syncID,
    storageVersion: STORAGE_VERSION,
    engines: {
      clients: { version: clientsEngine.version, syncID: clientsSyncID },
    },
  });
  let clientsColl = new ServerCollection({}, true);

  // Tracking info/collections.
  let collectionsHelper = track_collections_helper();
  let upd = collectionsHelper.with_updated_collection;

  return httpd_setup({
    "/1.1/johndoe@mozilla.com/storage/meta/global": upd(
      "meta",
      global.handler()
    ),
    "/1.1/johndoe@mozilla.com/info/collections": collectionsHelper.handler,
    "/1.1/johndoe@mozilla.com/storage/crypto/keys": upd(
      "crypto",
      new ServerWBO("keys").handler()
    ),
    "/1.1/johndoe@mozilla.com/storage/clients": upd(
      "clients",
      clientsColl.handler()
    ),
  });
}

async function setUp(server) {
  await configureIdentity({ username: "johndoe@mozilla.com" }, server);

  await generateNewKeys(Service.collectionKeys);
  let serverKeys = Service.collectionKeys.asWBO("crypto", "keys");
  await serverKeys.encrypt(Service.identity.syncKeyBundle);
  let result = (
    await serverKeys.upload(Service.resource(Service.cryptoKeysURL))
  ).success;
  return result;
}

async function cleanUpAndGo(server) {
  await Async.promiseYield();
  await clientsEngine._store.wipe();
  await Service.startOver();
  // Re-enable logging, which we just disabled.
  syncTestLogging();
  if (server) {
    await promiseStopServer(server);
  }
}

add_task(async function setup() {
  await Service.promiseInitialized;
  clientsEngine = Service.clientsEngine;
  // Don't remove stale clients when syncing. This is a test-only workaround
  // that lets us add clients directly to the store, without losing them on
  // the next sync.
  clientsEngine._removeRemoteClient = async id => {};
  await Service.engineManager.clear();

  validate_all_future_pings();

  scheduler.setDefaults();

  await Service.engineManager.register(CatapultEngine);
});

add_test(function test_prefAttributes() {
  _("Test various attributes corresponding to preferences.");

  const INTERVAL = 42 * 60 * 1000; // 42 minutes
  const THRESHOLD = 3142;
  const SCORE = 2718;
  const TIMESTAMP1 = 1275493471649;

  _(
    "The 'nextSync' attribute stores a millisecond timestamp rounded down to the nearest second."
  );
  Assert.equal(scheduler.nextSync, 0);
  scheduler.nextSync = TIMESTAMP1;
  Assert.equal(scheduler.nextSync, Math.floor(TIMESTAMP1 / 1000) * 1000);

  _("'syncInterval' defaults to singleDeviceInterval.");
  Assert.equal(
    Svc.PrefBranch.getPrefType("syncInterval"),
    Ci.nsIPrefBranch.PREF_INVALID
  );
  Assert.equal(scheduler.syncInterval, scheduler.singleDeviceInterval);

  _("'syncInterval' corresponds to a preference setting.");
  scheduler.syncInterval = INTERVAL;
  Assert.equal(scheduler.syncInterval, INTERVAL);
  Assert.equal(Svc.PrefBranch.getIntPref("syncInterval"), INTERVAL);

  _(
    "'syncThreshold' corresponds to preference, defaults to SINGLE_USER_THRESHOLD"
  );
  Assert.equal(
    Svc.PrefBranch.getPrefType("syncThreshold"),
    Ci.nsIPrefBranch.PREF_INVALID
  );
  Assert.equal(scheduler.syncThreshold, SINGLE_USER_THRESHOLD);
  scheduler.syncThreshold = THRESHOLD;
  Assert.equal(scheduler.syncThreshold, THRESHOLD);

  _("'globalScore' corresponds to preference, defaults to zero.");
  Assert.equal(Svc.PrefBranch.getIntPref("globalScore"), 0);
  Assert.equal(scheduler.globalScore, 0);
  scheduler.globalScore = SCORE;
  Assert.equal(scheduler.globalScore, SCORE);
  Assert.equal(Svc.PrefBranch.getIntPref("globalScore"), SCORE);

  _("Intervals correspond to default preferences.");
  Assert.equal(
    scheduler.singleDeviceInterval,
    Svc.PrefBranch.getIntPref("scheduler.fxa.singleDeviceInterval") * 1000
  );
  Assert.equal(
    scheduler.idleInterval,
    Svc.PrefBranch.getIntPref("scheduler.idleInterval") * 1000
  );
  Assert.equal(
    scheduler.activeInterval,
    Svc.PrefBranch.getIntPref("scheduler.activeInterval") * 1000
  );
  Assert.equal(
    scheduler.immediateInterval,
    Svc.PrefBranch.getIntPref("scheduler.immediateInterval") * 1000
  );

  _("Custom values for prefs will take effect after a restart.");
  Svc.PrefBranch.setIntPref("scheduler.fxa.singleDeviceInterval", 420);
  Svc.PrefBranch.setIntPref("scheduler.idleInterval", 230);
  Svc.PrefBranch.setIntPref("scheduler.activeInterval", 180);
  Svc.PrefBranch.setIntPref("scheduler.immediateInterval", 31415);
  scheduler.setDefaults();
  Assert.equal(scheduler.idleInterval, 230000);
  Assert.equal(scheduler.singleDeviceInterval, 420000);
  Assert.equal(scheduler.activeInterval, 180000);
  Assert.equal(scheduler.immediateInterval, 31415000);

  _("Custom values for interval prefs can't be less than 60 seconds.");
  Svc.PrefBranch.setIntPref("scheduler.fxa.singleDeviceInterval", 42);
  Svc.PrefBranch.setIntPref("scheduler.idleInterval", 50);
  Svc.PrefBranch.setIntPref("scheduler.activeInterval", 50);
  Svc.PrefBranch.setIntPref("scheduler.immediateInterval", 10);
  scheduler.setDefaults();
  Assert.equal(scheduler.idleInterval, 60000);
  Assert.equal(scheduler.singleDeviceInterval, 60000);
  Assert.equal(scheduler.activeInterval, 60000);
  Assert.equal(scheduler.immediateInterval, 60000);

  for (const pref of Svc.PrefBranch.getChildList("")) {
    Svc.PrefBranch.clearUserPref(pref);
  }
  scheduler.setDefaults();
  run_next_test();
});

add_task(async function test_sync_skipped_low_score_no_resync() {
  enableValidationPrefs();
  let server = await sync_httpd_setup();

  function SkipEngine() {
    SyncEngine.call(this, "Skip", Service);
    this.syncs = 0;
  }

  SkipEngine.prototype = {
    _sync() {
      do_throw("Should have been skipped");
    },
    shouldSkipSync() {
      return true;
    },
  };
  Object.setPrototypeOf(SkipEngine.prototype, SyncEngine.prototype);
  await Service.engineManager.register(SkipEngine);

  let engine = Service.engineManager.get("skip");
  engine.enabled = true;
  engine._tracker._score = 30;

  Assert.equal(Status.sync, SYNC_SUCCEEDED);

  Assert.ok(await setUp(server));

  let resyncDoneObserver = promiseOneObserver("weave:service:resyncs-finished");

  let synced = false;
  function onSyncStarted() {
    Assert.ok(!synced, "Only should sync once");
    synced = true;
  }

  await Service.sync();

  Assert.equal(Status.sync, SYNC_SUCCEEDED);

  Svc.Obs.add("weave:service:sync:start", onSyncStarted);
  await resyncDoneObserver;

  Svc.Obs.remove("weave:service:sync:start", onSyncStarted);
  engine._tracker._store = 0;
  await cleanUpAndGo(server);
});

add_task(async function test_updateClientMode() {
  _(
    "Test updateClientMode adjusts scheduling attributes based on # of clients appropriately"
  );
  Assert.equal(scheduler.syncThreshold, SINGLE_USER_THRESHOLD);
  Assert.equal(scheduler.syncInterval, scheduler.singleDeviceInterval);
  Assert.equal(false, scheduler.numClients > 1);
  Assert.ok(!scheduler.idle);

  // Trigger a change in interval & threshold by noting there are multiple clients.
  Svc.PrefBranch.setIntPref("clients.devices.desktop", 1);
  Svc.PrefBranch.setIntPref("clients.devices.mobile", 1);
  scheduler.updateClientMode();

  Assert.equal(scheduler.syncThreshold, MULTI_DEVICE_THRESHOLD);
  Assert.equal(scheduler.syncInterval, scheduler.activeInterval);
  Assert.ok(scheduler.numClients > 1);
  Assert.ok(!scheduler.idle);

  // Resets the number of clients to 0.
  await clientsEngine.resetClient();
  Svc.PrefBranch.clearUserPref("clients.devices.mobile");
  scheduler.updateClientMode();

  // Goes back to single user if # clients is 1.
  Assert.equal(scheduler.numClients, 1);
  Assert.equal(scheduler.syncThreshold, SINGLE_USER_THRESHOLD);
  Assert.equal(scheduler.syncInterval, scheduler.singleDeviceInterval);
  Assert.equal(false, scheduler.numClients > 1);
  Assert.ok(!scheduler.idle);

  await cleanUpAndGo();
});

add_task(async function test_masterpassword_locked_retry_interval() {
  enableValidationPrefs();

  _(
    "Test Status.login = MASTER_PASSWORD_LOCKED results in reschedule at MASTER_PASSWORD interval"
  );
  let loginFailed = false;
  Svc.Obs.add("weave:service:login:error", function onLoginError() {
    Svc.Obs.remove("weave:service:login:error", onLoginError);
    loginFailed = true;
  });

  let rescheduleInterval = false;

  let oldScheduleAtInterval = SyncScheduler.prototype.scheduleAtInterval;
  SyncScheduler.prototype.scheduleAtInterval = function (interval) {
    rescheduleInterval = true;
    Assert.equal(interval, MASTER_PASSWORD_LOCKED_RETRY_INTERVAL);
  };

  let oldVerifyLogin = Service.verifyLogin;
  Service.verifyLogin = async function () {
    Status.login = MASTER_PASSWORD_LOCKED;
    return false;
  };

  let server = await sync_httpd_setup();
  await setUp(server);

  await Service.sync();

  Assert.ok(loginFailed);
  Assert.equal(Status.login, MASTER_PASSWORD_LOCKED);
  Assert.ok(rescheduleInterval);

  Service.verifyLogin = oldVerifyLogin;
  SyncScheduler.prototype.scheduleAtInterval = oldScheduleAtInterval;

  await cleanUpAndGo(server);
});

add_task(async function test_calculateBackoff() {
  Assert.equal(Status.backoffInterval, 0);

  // Test no interval larger than the maximum backoff is used if
  // Status.backoffInterval is smaller.
  Status.backoffInterval = 5;
  let backoffInterval = Utils.calculateBackoff(
    50,
    MAXIMUM_BACKOFF_INTERVAL,
    Status.backoffInterval
  );

  Assert.equal(backoffInterval, MAXIMUM_BACKOFF_INTERVAL);

  // Test Status.backoffInterval is used if it is
  // larger than MAXIMUM_BACKOFF_INTERVAL.
  Status.backoffInterval = MAXIMUM_BACKOFF_INTERVAL + 10;
  backoffInterval = Utils.calculateBackoff(
    50,
    MAXIMUM_BACKOFF_INTERVAL,
    Status.backoffInterval
  );

  Assert.equal(backoffInterval, MAXIMUM_BACKOFF_INTERVAL + 10);

  await cleanUpAndGo();
});

add_task(async function test_scheduleNextSync_nowOrPast() {
  enableValidationPrefs();

  let promiseObserved = promiseOneObserver("weave:service:sync:finish");

  let server = await sync_httpd_setup();
  await setUp(server);

  // We're late for a sync...
  scheduler.scheduleNextSync(-1);
  await promiseObserved;
  await cleanUpAndGo(server);
});

add_task(async function test_scheduleNextSync_future_noBackoff() {
  enableValidationPrefs();

  _(
    "scheduleNextSync() uses the current syncInterval if no interval is provided."
  );
  // Test backoffInterval is 0 as expected.
  Assert.equal(Status.backoffInterval, 0);

  _("Test setting sync interval when nextSync == 0");
  scheduler.nextSync = 0;
  scheduler.scheduleNextSync();

  // nextSync - Date.now() might be smaller than expectedInterval
  // since some time has passed since we called scheduleNextSync().
  Assert.ok(scheduler.nextSync - Date.now() <= scheduler.syncInterval);
  Assert.equal(scheduler.syncTimer.delay, scheduler.syncInterval);

  _("Test setting sync interval when nextSync != 0");
  scheduler.nextSync = Date.now() + scheduler.singleDeviceInterval;
  scheduler.scheduleNextSync();

  // nextSync - Date.now() might be smaller than expectedInterval
  // since some time has passed since we called scheduleNextSync().
  Assert.ok(scheduler.nextSync - Date.now() <= scheduler.syncInterval);
  Assert.ok(scheduler.syncTimer.delay <= scheduler.syncInterval);

  _(
    "Scheduling requests for intervals larger than the current one will be ignored."
  );
  // Request a sync at a longer interval. The sync that's already scheduled
  // for sooner takes precedence.
  let nextSync = scheduler.nextSync;
  let timerDelay = scheduler.syncTimer.delay;
  let requestedInterval = scheduler.syncInterval * 10;
  scheduler.scheduleNextSync(requestedInterval);
  Assert.equal(scheduler.nextSync, nextSync);
  Assert.equal(scheduler.syncTimer.delay, timerDelay);

  // We can schedule anything we want if there isn't a sync scheduled.
  scheduler.nextSync = 0;
  scheduler.scheduleNextSync(requestedInterval);
  Assert.ok(scheduler.nextSync <= Date.now() + requestedInterval);
  Assert.equal(scheduler.syncTimer.delay, requestedInterval);

  // Request a sync at the smallest possible interval (0 triggers now).
  scheduler.scheduleNextSync(1);
  Assert.ok(scheduler.nextSync <= Date.now() + 1);
  Assert.equal(scheduler.syncTimer.delay, 1);

  await cleanUpAndGo();
});

add_task(async function test_scheduleNextSync_future_backoff() {
  enableValidationPrefs();

  _("scheduleNextSync() will honour backoff in all scheduling requests.");
  // Let's take a backoff interval that's bigger than the default sync interval.
  const BACKOFF = 7337;
  Status.backoffInterval = scheduler.syncInterval + BACKOFF;

  _("Test setting sync interval when nextSync == 0");
  scheduler.nextSync = 0;
  scheduler.scheduleNextSync();

  // nextSync - Date.now() might be smaller than expectedInterval
  // since some time has passed since we called scheduleNextSync().
  Assert.ok(scheduler.nextSync - Date.now() <= Status.backoffInterval);
  Assert.equal(scheduler.syncTimer.delay, Status.backoffInterval);

  _("Test setting sync interval when nextSync != 0");
  scheduler.nextSync = Date.now() + scheduler.singleDeviceInterval;
  scheduler.scheduleNextSync();

  // nextSync - Date.now() might be smaller than expectedInterval
  // since some time has passed since we called scheduleNextSync().
  Assert.ok(scheduler.nextSync - Date.now() <= Status.backoffInterval);
  Assert.ok(scheduler.syncTimer.delay <= Status.backoffInterval);

  // Request a sync at a longer interval. The sync that's already scheduled
  // for sooner takes precedence.
  let nextSync = scheduler.nextSync;
  let timerDelay = scheduler.syncTimer.delay;
  let requestedInterval = scheduler.syncInterval * 10;
  Assert.ok(requestedInterval > Status.backoffInterval);
  scheduler.scheduleNextSync(requestedInterval);
  Assert.equal(scheduler.nextSync, nextSync);
  Assert.equal(scheduler.syncTimer.delay, timerDelay);

  // We can schedule anything we want if there isn't a sync scheduled.
  scheduler.nextSync = 0;
  scheduler.scheduleNextSync(requestedInterval);
  Assert.ok(scheduler.nextSync <= Date.now() + requestedInterval);
  Assert.equal(scheduler.syncTimer.delay, requestedInterval);

  // Request a sync at the smallest possible interval (0 triggers now).
  scheduler.scheduleNextSync(1);
  Assert.ok(scheduler.nextSync <= Date.now() + Status.backoffInterval);
  Assert.equal(scheduler.syncTimer.delay, Status.backoffInterval);

  await cleanUpAndGo();
});

add_task(async function test_handleSyncError() {
  enableValidationPrefs();

  let server = await sync_httpd_setup();
  await setUp(server);

  // Force sync to fail.
  Svc.PrefBranch.setStringPref("firstSync", "notReady");

  _("Ensure expected initial environment.");
  Assert.equal(scheduler._syncErrors, 0);
  Assert.ok(!Status.enforceBackoff);
  Assert.equal(scheduler.syncInterval, scheduler.singleDeviceInterval);
  Assert.equal(Status.backoffInterval, 0);

  // Trigger sync with an error several times & observe
  // functionality of handleSyncError()
  _("Test first error calls scheduleNextSync on default interval");
  await Service.sync();
  Assert.ok(scheduler.nextSync <= Date.now() + scheduler.singleDeviceInterval);
  Assert.equal(scheduler.syncTimer.delay, scheduler.singleDeviceInterval);
  Assert.equal(scheduler._syncErrors, 1);
  Assert.ok(!Status.enforceBackoff);
  scheduler.syncTimer.clear();

  _("Test second error still calls scheduleNextSync on default interval");
  await Service.sync();
  Assert.ok(scheduler.nextSync <= Date.now() + scheduler.singleDeviceInterval);
  Assert.equal(scheduler.syncTimer.delay, scheduler.singleDeviceInterval);
  Assert.equal(scheduler._syncErrors, 2);
  Assert.ok(!Status.enforceBackoff);
  scheduler.syncTimer.clear();

  _("Test third error sets Status.enforceBackoff and calls scheduleAtInterval");
  await Service.sync();
  let maxInterval = scheduler._syncErrors * (2 * MINIMUM_BACKOFF_INTERVAL);
  Assert.equal(Status.backoffInterval, 0);
  Assert.ok(scheduler.nextSync <= Date.now() + maxInterval);
  Assert.ok(scheduler.syncTimer.delay <= maxInterval);
  Assert.equal(scheduler._syncErrors, 3);
  Assert.ok(Status.enforceBackoff);

  // Status.enforceBackoff is false but there are still errors.
  Status.resetBackoff();
  Assert.ok(!Status.enforceBackoff);
  Assert.equal(scheduler._syncErrors, 3);
  scheduler.syncTimer.clear();

  _(
    "Test fourth error still calls scheduleAtInterval even if enforceBackoff was reset"
  );
  await Service.sync();
  maxInterval = scheduler._syncErrors * (2 * MINIMUM_BACKOFF_INTERVAL);
  Assert.ok(scheduler.nextSync <= Date.now() + maxInterval);
  Assert.ok(scheduler.syncTimer.delay <= maxInterval);
  Assert.equal(scheduler._syncErrors, 4);
  Assert.ok(Status.enforceBackoff);
  scheduler.syncTimer.clear();

  _("Arrange for a successful sync to reset the scheduler error count");
  let promiseObserved = promiseOneObserver("weave:service:sync:finish");
  Svc.PrefBranch.setStringPref("firstSync", "wipeRemote");
  scheduler.scheduleNextSync(-1);
  await promiseObserved;
  await cleanUpAndGo(server);
});

add_task(async function test_client_sync_finish_updateClientMode() {
  enableValidationPrefs();

  let server = await sync_httpd_setup();
  await setUp(server);

  // Confirm defaults.
  Assert.equal(scheduler.syncThreshold, SINGLE_USER_THRESHOLD);
  Assert.equal(scheduler.syncInterval, scheduler.singleDeviceInterval);
  Assert.ok(!scheduler.idle);

  // Trigger a change in interval & threshold by adding a client.
  await clientsEngine._store.create({
    id: "foo",
    cleartext: { os: "mobile", version: "0.01", type: "desktop" },
  });
  Assert.equal(false, scheduler.numClients > 1);
  scheduler.updateClientMode();
  await Service.sync();

  Assert.equal(scheduler.syncThreshold, MULTI_DEVICE_THRESHOLD);
  Assert.equal(scheduler.syncInterval, scheduler.activeInterval);
  Assert.ok(scheduler.numClients > 1);
  Assert.ok(!scheduler.idle);

  // Resets the number of clients to 0.
  await clientsEngine.resetClient();
  // Also re-init the server, or we suck our "foo" client back down.
  await setUp(server);

  await Service.sync();

  // Goes back to single user if # clients is 1.
  Assert.equal(scheduler.numClients, 1);
  Assert.equal(scheduler.syncThreshold, SINGLE_USER_THRESHOLD);
  Assert.equal(scheduler.syncInterval, scheduler.singleDeviceInterval);
  Assert.equal(false, scheduler.numClients > 1);
  Assert.ok(!scheduler.idle);

  await cleanUpAndGo(server);
});

add_task(async function test_autoconnect_nextSync_past() {
  enableValidationPrefs();

  let promiseObserved = promiseOneObserver("weave:service:sync:finish");
  // nextSync will be 0 by default, so it's way in the past.

  let server = await sync_httpd_setup();
  await setUp(server);

  scheduler.autoConnect();
  await promiseObserved;
  await cleanUpAndGo(server);
});

add_task(async function test_autoconnect_nextSync_future() {
  enableValidationPrefs();

  let previousSync = Date.now() + scheduler.syncInterval / 2;
  scheduler.nextSync = previousSync;
  // nextSync rounds to the nearest second.
  let expectedSync = scheduler.nextSync;
  let expectedInterval = expectedSync - Date.now() - 1000;

  // Ensure we don't actually try to sync (or log in for that matter).
  function onLoginStart() {
    do_throw("Should not get here!");
  }
  Svc.Obs.add("weave:service:login:start", onLoginStart);

  await configureIdentity({ username: "johndoe@mozilla.com" });
  scheduler.autoConnect();
  await promiseZeroTimer();

  Assert.equal(scheduler.nextSync, expectedSync);
  Assert.ok(scheduler.syncTimer.delay >= expectedInterval);

  Svc.Obs.remove("weave:service:login:start", onLoginStart);
  await cleanUpAndGo();
});

add_task(async function test_autoconnect_mp_locked() {
  let server = await sync_httpd_setup();
  await setUp(server);

  // Pretend user did not unlock master password.
  let origLocked = Utils.mpLocked;
  Utils.mpLocked = () => true;

  let origEnsureMPUnlocked = Utils.ensureMPUnlocked;
  Utils.ensureMPUnlocked = () => {
    _("Faking Master Password entry cancelation.");
    return false;
  };
  let origFxA = Service.identity._fxaService;
  Service.identity._fxaService = new FxAccounts({
    currentAccountState: {
      getUserAccountData(...args) {
        return origFxA._internal.currentAccountState.getUserAccountData(
          ...args
        );
      },
    },
    keys: {
      canGetKeyForScope() {
        return false;
      },
    },
  });
  // A locked master password will still trigger a sync, but then we'll hit
  // MASTER_PASSWORD_LOCKED and hence MASTER_PASSWORD_LOCKED_RETRY_INTERVAL.
  let promiseObserved = promiseOneObserver("weave:service:login:error");

  scheduler.autoConnect();
  await promiseObserved;

  await Async.promiseYield();

  Assert.equal(Status.login, MASTER_PASSWORD_LOCKED);

  Utils.mpLocked = origLocked;
  Utils.ensureMPUnlocked = origEnsureMPUnlocked;
  Service.identity._fxaService = origFxA;

  await cleanUpAndGo(server);
});

add_task(async function test_no_autoconnect_during_wizard() {
  let server = await sync_httpd_setup();
  await setUp(server);

  // Simulate the Sync setup wizard.
  Svc.PrefBranch.setStringPref("firstSync", "notReady");

  // Ensure we don't actually try to sync (or log in for that matter).
  function onLoginStart() {
    do_throw("Should not get here!");
  }
  Svc.Obs.add("weave:service:login:start", onLoginStart);

  scheduler.autoConnect(0);
  await promiseZeroTimer();
  Svc.Obs.remove("weave:service:login:start", onLoginStart);
  await cleanUpAndGo(server);
});

add_task(async function test_no_autoconnect_status_not_ok() {
  let server = await sync_httpd_setup();
  Status.__authManager = Service.identity = new SyncAuthManager();

  // Ensure we don't actually try to sync (or log in for that matter).
  function onLoginStart() {
    do_throw("Should not get here!");
  }
  Svc.Obs.add("weave:service:login:start", onLoginStart);

  scheduler.autoConnect();
  await promiseZeroTimer();
  Svc.Obs.remove("weave:service:login:start", onLoginStart);

  Assert.equal(Status.service, CLIENT_NOT_CONFIGURED);
  Assert.equal(Status.login, LOGIN_FAILED_NO_USERNAME);

  await cleanUpAndGo(server);
});

add_task(async function test_idle_adjustSyncInterval() {
  // Confirm defaults.
  Assert.equal(scheduler.idle, false);

  // Single device: nothing changes.
  scheduler.observe(
    null,
    "idle",
    Svc.PrefBranch.getIntPref("scheduler.idleTime")
  );
  Assert.equal(scheduler.idle, true);
  Assert.equal(scheduler.syncInterval, scheduler.singleDeviceInterval);

  // Multiple devices: switch to idle interval.
  scheduler.idle = false;
  Svc.PrefBranch.setIntPref("clients.devices.desktop", 1);
  Svc.PrefBranch.setIntPref("clients.devices.mobile", 1);
  scheduler.updateClientMode();
  scheduler.observe(
    null,
    "idle",
    Svc.PrefBranch.getIntPref("scheduler.idleTime")
  );
  Assert.equal(scheduler.idle, true);
  Assert.equal(scheduler.syncInterval, scheduler.idleInterval);

  await cleanUpAndGo();
});

add_task(async function test_back_triggersSync() {
  // Confirm defaults.
  Assert.ok(!scheduler.idle);
  Assert.equal(Status.backoffInterval, 0);

  // Set up: Define 2 clients and put the system in idle.
  Svc.PrefBranch.setIntPref("clients.devices.desktop", 1);
  Svc.PrefBranch.setIntPref("clients.devices.mobile", 1);
  scheduler.observe(
    null,
    "idle",
    Svc.PrefBranch.getIntPref("scheduler.idleTime")
  );
  Assert.ok(scheduler.idle);

  // We don't actually expect the sync (or the login, for that matter) to
  // succeed. We just want to ensure that it was attempted.
  let promiseObserved = promiseOneObserver("weave:service:login:error");

  // Send an 'active' event to trigger sync soonish.
  scheduler.observe(
    null,
    "active",
    Svc.PrefBranch.getIntPref("scheduler.idleTime")
  );
  await promiseObserved;
  await cleanUpAndGo();
});

add_task(async function test_active_triggersSync_observesBackoff() {
  // Confirm defaults.
  Assert.ok(!scheduler.idle);

  // Set up: Set backoff, define 2 clients and put the system in idle.
  const BACKOFF = 7337;
  Status.backoffInterval = scheduler.idleInterval + BACKOFF;
  Svc.PrefBranch.setIntPref("clients.devices.desktop", 1);
  Svc.PrefBranch.setIntPref("clients.devices.mobile", 1);
  scheduler.observe(
    null,
    "idle",
    Svc.PrefBranch.getIntPref("scheduler.idleTime")
  );
  Assert.equal(scheduler.idle, true);

  function onLoginStart() {
    do_throw("Shouldn't have kicked off a sync!");
  }
  Svc.Obs.add("weave:service:login:start", onLoginStart);

  let promiseTimer = promiseNamedTimer(
    IDLE_OBSERVER_BACK_DELAY * 1.5,
    {},
    "timer"
  );

  // Send an 'active' event to try to trigger sync soonish.
  scheduler.observe(
    null,
    "active",
    Svc.PrefBranch.getIntPref("scheduler.idleTime")
  );
  await promiseTimer;
  Svc.Obs.remove("weave:service:login:start", onLoginStart);

  Assert.ok(scheduler.nextSync <= Date.now() + Status.backoffInterval);
  Assert.equal(scheduler.syncTimer.delay, Status.backoffInterval);

  await cleanUpAndGo();
});

add_task(async function test_back_debouncing() {
  _(
    "Ensure spurious back-then-idle events, as observed on OS X, don't trigger a sync."
  );

  // Confirm defaults.
  Assert.equal(scheduler.idle, false);

  // Set up: Define 2 clients and put the system in idle.
  Svc.PrefBranch.setIntPref("clients.devices.desktop", 1);
  Svc.PrefBranch.setIntPref("clients.devices.mobile", 1);
  scheduler.observe(
    null,
    "idle",
    Svc.PrefBranch.getIntPref("scheduler.idleTime")
  );
  Assert.equal(scheduler.idle, true);

  function onLoginStart() {
    do_throw("Shouldn't have kicked off a sync!");
  }
  Svc.Obs.add("weave:service:login:start", onLoginStart);

  // Create spurious back-then-idle events as observed on OS X:
  scheduler.observe(
    null,
    "active",
    Svc.PrefBranch.getIntPref("scheduler.idleTime")
  );
  scheduler.observe(
    null,
    "idle",
    Svc.PrefBranch.getIntPref("scheduler.idleTime")
  );

  await promiseNamedTimer(IDLE_OBSERVER_BACK_DELAY * 1.5, {}, "timer");
  Svc.Obs.remove("weave:service:login:start", onLoginStart);
  await cleanUpAndGo();
});

add_task(async function test_no_sync_node() {
  enableValidationPrefs();

  // Test when Status.sync == NO_SYNC_NODE_FOUND
  // it is not overwritten on sync:finish
  let server = await sync_httpd_setup();
  await setUp(server);

  let oldfc = Service.identity._findCluster;
  Service.identity._findCluster = () => null;
  Service.clusterURL = "";
  try {
    await Service.sync();
    Assert.equal(Status.sync, NO_SYNC_NODE_FOUND);
    Assert.equal(scheduler.syncTimer.delay, NO_SYNC_NODE_INTERVAL);

    await cleanUpAndGo(server);
  } finally {
    Service.identity._findCluster = oldfc;
  }
});

add_task(async function test_sync_failed_partial_500s() {
  enableValidationPrefs();

  _("Test a 5xx status calls handleSyncError.");
  scheduler._syncErrors = MAX_ERROR_COUNT_BEFORE_BACKOFF;
  let server = await sync_httpd_setup();

  let engine = Service.engineManager.get("catapult");
  engine.enabled = true;
  engine.exception = { status: 500 };

  Assert.equal(Status.sync, SYNC_SUCCEEDED);

  Assert.ok(await setUp(server));

  await Service.sync();

  Assert.equal(Status.service, SYNC_FAILED_PARTIAL);

  let maxInterval = scheduler._syncErrors * (2 * MINIMUM_BACKOFF_INTERVAL);
  Assert.equal(Status.backoffInterval, 0);
  Assert.ok(Status.enforceBackoff);
  Assert.equal(scheduler._syncErrors, 4);
  Assert.ok(scheduler.nextSync <= Date.now() + maxInterval);
  Assert.ok(scheduler.syncTimer.delay <= maxInterval);

  await cleanUpAndGo(server);
});

add_task(async function test_sync_failed_partial_noresync() {
  enableValidationPrefs();
  let server = await sync_httpd_setup();

  let engine = Service.engineManager.get("catapult");
  engine.enabled = true;
  engine.exception = "Bad news";
  engine._tracker._score = MULTI_DEVICE_THRESHOLD + 1;

  Assert.equal(Status.sync, SYNC_SUCCEEDED);

  Assert.ok(await setUp(server));

  let resyncDoneObserver = promiseOneObserver("weave:service:resyncs-finished");

  await Service.sync();

  Assert.equal(Status.service, SYNC_FAILED_PARTIAL);

  function onSyncStarted() {
    do_throw("Should not start resync when previous sync failed");
  }

  Svc.Obs.add("weave:service:sync:start", onSyncStarted);
  await resyncDoneObserver;

  Svc.Obs.remove("weave:service:sync:start", onSyncStarted);
  engine._tracker._store = 0;
  await cleanUpAndGo(server);
});

add_task(async function test_sync_failed_partial_400s() {
  enableValidationPrefs();

  _("Test a non-5xx status doesn't call handleSyncError.");
  scheduler._syncErrors = MAX_ERROR_COUNT_BEFORE_BACKOFF;
  let server = await sync_httpd_setup();

  let engine = Service.engineManager.get("catapult");
  engine.enabled = true;
  engine.exception = { status: 400 };

  // Have multiple devices for an active interval.
  await clientsEngine._store.create({
    id: "foo",
    cleartext: { os: "mobile", version: "0.01", type: "desktop" },
  });

  Assert.equal(Status.sync, SYNC_SUCCEEDED);

  Assert.ok(await setUp(server));

  await Service.sync();

  Assert.equal(Status.service, SYNC_FAILED_PARTIAL);
  Assert.equal(scheduler.syncInterval, scheduler.activeInterval);

  Assert.equal(Status.backoffInterval, 0);
  Assert.ok(!Status.enforceBackoff);
  Assert.equal(scheduler._syncErrors, 0);
  Assert.ok(scheduler.nextSync <= Date.now() + scheduler.activeInterval);
  Assert.ok(scheduler.syncTimer.delay <= scheduler.activeInterval);

  await cleanUpAndGo(server);
});

add_task(async function test_sync_X_Weave_Backoff() {
  enableValidationPrefs();

  let server = await sync_httpd_setup();
  await setUp(server);

  // Use an odd value on purpose so that it doesn't happen to coincide with one
  // of the sync intervals.
  const BACKOFF = 7337;

  // Extend info/collections so that we can put it into server maintenance mode.
  const INFO_COLLECTIONS = "/1.1/johndoe@mozilla.com/info/collections";
  let infoColl = server._handler._overridePaths[INFO_COLLECTIONS];
  let serverBackoff = false;
  function infoCollWithBackoff(request, response) {
    if (serverBackoff) {
      response.setHeader("X-Weave-Backoff", "" + BACKOFF);
    }
    infoColl(request, response);
  }
  server.registerPathHandler(INFO_COLLECTIONS, infoCollWithBackoff);

  // Pretend we have two clients so that the regular sync interval is
  // sufficiently low.
  await clientsEngine._store.create({
    id: "foo",
    cleartext: { os: "mobile", version: "0.01", type: "desktop" },
  });
  let rec = await clientsEngine._store.createRecord("foo", "clients");
  await rec.encrypt(Service.collectionKeys.keyForCollection("clients"));
  await rec.upload(Service.resource(clientsEngine.engineURL + rec.id));

  // Sync once to log in and get everything set up. Let's verify our initial
  // values.
  await Service.sync();
  Assert.equal(Status.backoffInterval, 0);
  Assert.equal(Status.minimumNextSync, 0);
  Assert.equal(scheduler.syncInterval, scheduler.activeInterval);
  Assert.ok(scheduler.nextSync <= Date.now() + scheduler.syncInterval);
  // Sanity check that we picked the right value for BACKOFF:
  Assert.ok(scheduler.syncInterval < BACKOFF * 1000);

  // Turn on server maintenance and sync again.
  serverBackoff = true;
  await Service.sync();

  Assert.ok(Status.backoffInterval >= BACKOFF * 1000);
  // Allowing 20 seconds worth of of leeway between when Status.minimumNextSync
  // was set and when this line gets executed.
  let minimumExpectedDelay = (BACKOFF - 20) * 1000;
  Assert.ok(Status.minimumNextSync >= Date.now() + minimumExpectedDelay);

  // Verify that the next sync is actually going to wait that long.
  Assert.ok(scheduler.nextSync >= Date.now() + minimumExpectedDelay);
  Assert.ok(scheduler.syncTimer.delay >= minimumExpectedDelay);

  await cleanUpAndGo(server);
});

add_task(async function test_sync_503_Retry_After() {
  enableValidationPrefs();

  let server = await sync_httpd_setup();
  await setUp(server);

  // Use an odd value on purpose so that it doesn't happen to coincide with one
  // of the sync intervals.
  const BACKOFF = 7337;

  // Extend info/collections so that we can put it into server maintenance mode.
  const INFO_COLLECTIONS = "/1.1/johndoe@mozilla.com/info/collections";
  let infoColl = server._handler._overridePaths[INFO_COLLECTIONS];
  let serverMaintenance = false;
  function infoCollWithMaintenance(request, response) {
    if (!serverMaintenance) {
      infoColl(request, response);
      return;
    }
    response.setHeader("Retry-After", "" + BACKOFF);
    response.setStatusLine(request.httpVersion, 503, "Service Unavailable");
  }
  server.registerPathHandler(INFO_COLLECTIONS, infoCollWithMaintenance);

  // Pretend we have two clients so that the regular sync interval is
  // sufficiently low.
  await clientsEngine._store.create({
    id: "foo",
    cleartext: { os: "mobile", version: "0.01", type: "desktop" },
  });
  let rec = await clientsEngine._store.createRecord("foo", "clients");
  await rec.encrypt(Service.collectionKeys.keyForCollection("clients"));
  await rec.upload(Service.resource(clientsEngine.engineURL + rec.id));

  // Sync once to log in and get everything set up. Let's verify our initial
  // values.
  await Service.sync();
  Assert.ok(!Status.enforceBackoff);
  Assert.equal(Status.backoffInterval, 0);
  Assert.equal(Status.minimumNextSync, 0);
  Assert.equal(scheduler.syncInterval, scheduler.activeInterval);
  Assert.ok(scheduler.nextSync <= Date.now() + scheduler.syncInterval);
  // Sanity check that we picked the right value for BACKOFF:
  Assert.ok(scheduler.syncInterval < BACKOFF * 1000);

  // Turn on server maintenance and sync again.
  serverMaintenance = true;
  await Service.sync();

  Assert.ok(Status.enforceBackoff);
  Assert.ok(Status.backoffInterval >= BACKOFF * 1000);
  // Allowing 3 seconds worth of of leeway between when Status.minimumNextSync
  // was set and when this line gets executed.
  let minimumExpectedDelay = (BACKOFF - 3) * 1000;
  Assert.ok(Status.minimumNextSync >= Date.now() + minimumExpectedDelay);

  // Verify that the next sync is actually going to wait that long.
  Assert.ok(scheduler.nextSync >= Date.now() + minimumExpectedDelay);
  Assert.ok(scheduler.syncTimer.delay >= minimumExpectedDelay);

  await cleanUpAndGo(server);
});

add_task(async function test_loginError_recoverable_reschedules() {
  _("Verify that a recoverable login error schedules a new sync.");
  await configureIdentity({ username: "johndoe@mozilla.com" });
  Service.clusterURL = "http://localhost:1234/";
  Status.resetSync(); // reset Status.login

  let promiseObserved = promiseOneObserver("weave:service:login:error");

  // Let's set it up so that a sync is overdue, both in terms of previously
  // scheduled syncs and the global score. We still do not expect an immediate
  // sync because we just tried (duh).
  scheduler.nextSync = Date.now() - 100000;
  scheduler.globalScore = SINGLE_USER_THRESHOLD + 1;
  function onSyncStart() {
    do_throw("Shouldn't have started a sync!");
  }
  Svc.Obs.add("weave:service:sync:start", onSyncStart);

  // Sanity check.
  Assert.equal(scheduler.syncTimer, null);
  Assert.equal(Status.checkSetup(), STATUS_OK);
  Assert.equal(Status.login, LOGIN_SUCCEEDED);

  scheduler.scheduleNextSync(0);
  await promiseObserved;
  await Async.promiseYield();

  Assert.equal(Status.login, LOGIN_FAILED_NETWORK_ERROR);

  let expectedNextSync = Date.now() + scheduler.syncInterval;
  Assert.ok(scheduler.nextSync > Date.now());
  Assert.ok(scheduler.nextSync <= expectedNextSync);
  Assert.ok(scheduler.syncTimer.delay > 0);
  Assert.ok(scheduler.syncTimer.delay <= scheduler.syncInterval);

  Svc.Obs.remove("weave:service:sync:start", onSyncStart);
  await cleanUpAndGo();
});

add_task(async function test_loginError_fatal_clearsTriggers() {
  _("Verify that a fatal login error clears sync triggers.");
  await configureIdentity({ username: "johndoe@mozilla.com" });

  let server = httpd_setup({
    "/1.1/johndoe@mozilla.com/info/collections": httpd_handler(
      401,
      "Unauthorized"
    ),
  });

  Service.clusterURL = server.baseURI + "/";
  Status.resetSync(); // reset Status.login

  let promiseObserved = promiseOneObserver("weave:service:login:error");

  // Sanity check.
  Assert.equal(scheduler.nextSync, 0);
  Assert.equal(scheduler.syncTimer, null);
  Assert.equal(Status.checkSetup(), STATUS_OK);
  Assert.equal(Status.login, LOGIN_SUCCEEDED);

  scheduler.scheduleNextSync(0);
  await promiseObserved;
  await Async.promiseYield();

  // For the FxA identity, a 401 on info/collections means a transient
  // error, probably due to an inability to fetch a token.
  Assert.equal(Status.login, LOGIN_FAILED_NETWORK_ERROR);
  // syncs should still be scheduled.
  Assert.ok(scheduler.nextSync > Date.now());
  Assert.ok(scheduler.syncTimer.delay > 0);

  await cleanUpAndGo(server);
});

add_task(async function test_proper_interval_on_only_failing() {
  _("Ensure proper behavior when only failed records are applied.");

  // If an engine reports that no records succeeded, we shouldn't decrease the
  // sync interval.
  Assert.ok(!scheduler.hasIncomingItems);
  const INTERVAL = 10000000;
  scheduler.syncInterval = INTERVAL;

  Svc.Obs.notify("weave:service:sync:applied", {
    applied: 2,
    succeeded: 0,
    failed: 2,
    newFailed: 2,
    reconciled: 0,
  });

  await Async.promiseYield();
  scheduler.adjustSyncInterval();
  Assert.ok(!scheduler.hasIncomingItems);
  Assert.equal(scheduler.syncInterval, scheduler.singleDeviceInterval);
});

add_task(async function test_link_status_change() {
  _("Check that we only attempt to sync when link status is up");
  try {
    sinon.spy(scheduler, "scheduleNextSync");

    Svc.Obs.notify("network:link-status-changed", null, "down");
    equal(scheduler.scheduleNextSync.callCount, 0);

    Svc.Obs.notify("network:link-status-changed", null, "change");
    equal(scheduler.scheduleNextSync.callCount, 0);

    Svc.Obs.notify("network:link-status-changed", null, "up");
    equal(scheduler.scheduleNextSync.callCount, 1);

    Svc.Obs.notify("network:link-status-changed", null, "change");
    equal(scheduler.scheduleNextSync.callCount, 1);
  } finally {
    scheduler.scheduleNextSync.restore();
  }
});