forked from rocicorp/replicache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplicache.test.ts
More file actions
1985 lines (1677 loc) · 47.4 KB
/
Copy pathreplicache.test.ts
File metadata and controls
1985 lines (1677 loc) · 47.4 KB
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
import {
ReplicacheTest,
httpStatusUnauthorized,
MutatorDefs,
} from './replicache.js';
import type {ReplicacheOptions} from './replicache.js';
import {Replicache, TransactionClosedError} from './mod.js';
import type {ReadTransaction, WriteTransaction} from './mod.js';
import {deepEqual, JSONValue} from './json.js';
import {assert, expect} from '@esm-bundle/chai';
import * as sinon from 'sinon';
import type {SinonSpy} from 'sinon';
// fetch-mock has invalid d.ts file so we removed that on npm install.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
import fetchMock from 'fetch-mock/esm/client.js';
import {Invoke, RPC} from './repm-invoker.js';
import type {ScanOptions} from './scan-options.js';
import {SinonFakeTimers, useFakeTimers} from 'sinon';
import {asyncIterableToArray} from './async-iterable-to-array.js';
let clock: SinonFakeTimers;
setup(function () {
clock = useFakeTimers(0);
});
teardown(function () {
clock.restore();
});
async function tickAFewTimes(n = 10, time = 10) {
for (let i = 0; i < n; i++) {
await clock.tickAsync(time);
}
}
fetchMock.config.overwriteRoutes = true;
const {fail} = assert;
const reps: Set<ReplicacheTest> = new Set();
let overrideUseMemstore = false;
// eslint-disable-next-line @typescript-eslint/ban-types
async function replicacheForTesting<MD extends MutatorDefs = {}>(
name: string,
{
pullURL = 'https://pull.com/?name=' + name,
pushDelay = 60_000, // Large to prevent interfering
pushURL = 'https://push.com/?name=' + name,
useMemstore = overrideUseMemstore,
...rest
}: ReplicacheOptions<MD> = {},
): Promise<ReplicacheTest<MD>> {
dbsToDrop.add(name);
const rep = new ReplicacheTest<MD>({
pullURL,
pushDelay,
pushURL,
name,
useMemstore,
...rest,
});
reps.add(rep);
fetchMock.post(pullURL, {lastMutationID: 0, patch: []});
fetchMock.post(pushURL, {});
await tickAFewTimes();
return rep;
}
const dbsToDrop = new Set<string>();
async function addData(tx: WriteTransaction, data: {[key: string]: JSONValue}) {
for (const [key, value] of Object.entries(data)) {
await tx.put(key, value);
}
}
const emptyHash = '';
function spyInvoke(
rep: Replicache,
): SinonSpy<Parameters<Invoke>, ReturnType<Invoke>> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return sinon.spy(rep, '_invoke');
}
teardown(async () => {
fetchMock.restore();
sinon.restore();
for (const rep of reps) {
if (!rep.closed) {
await rep.close();
}
reps.delete(rep);
}
for (const name of dbsToDrop) {
indexedDB.deleteDatabase(name);
}
dbsToDrop.clear();
});
async function expectPromiseToReject(p: unknown): Promise<Chai.Assertion> {
let e;
try {
await p;
} catch (ex) {
e = ex;
}
return expect(e);
}
async function expectAsyncFuncToThrow(f: () => unknown, c: unknown) {
(await expectPromiseToReject(f())).to.be.instanceof(c);
}
function testWithBothStores(name: string, func: () => Promise<void>) {
for (const useMemstore of [false, true]) {
test(`${name} {useMemstore: ${useMemstore}}`, async () => {
try {
overrideUseMemstore = useMemstore;
await func();
} finally {
overrideUseMemstore = false;
}
});
}
}
testWithBothStores('get, has, scan on empty db', async () => {
const rep = await replicacheForTesting('test2');
async function t(tx: ReadTransaction) {
expect(await tx.get('key')).to.equal(undefined);
expect(await tx.has('key')).to.be.false;
const scanItems = await asyncIterableToArray(tx.scan());
expect(scanItems).to.have.length(0);
}
await t(rep);
});
testWithBothStores('put, get, has, del inside tx', async () => {
const rep = await replicacheForTesting('test3', {
mutators: {
testMut: async (
tx: WriteTransaction,
args: {key: string; value: JSONValue},
) => {
const key = args['key'];
const value = args['value'];
await tx.put(key, value);
expect(await tx.has(key)).to.equal(true);
const v = await tx.get(key);
expect(v).to.deep.equal(value);
expect(await tx.del(key)).to.equal(true);
expect(await tx.has(key)).to.be.false;
},
},
});
const {testMut} = rep.mutate;
for (const [key, value] of Object.entries({
a: true,
b: false,
c: null,
d: 'string',
e: 12,
f: {},
g: [],
h: {h1: true},
i: [0, 1],
})) {
await testMut({key, value: value as JSONValue});
}
});
async function testScanResult<K, V>(
rep: Replicache,
options: ScanOptions | undefined,
entries: [K, V][],
) {
await rep.query(async tx => {
expect(
await asyncIterableToArray(tx.scan(options).entries()),
).to.deep.equal(entries);
});
await rep.query(async tx => {
expect(await asyncIterableToArray(tx.scan(options))).to.deep.equal(
entries.map(([, v]) => v),
);
});
await rep.query(async tx => {
expect(await asyncIterableToArray(tx.scan(options).values())).to.deep.equal(
entries.map(([, v]) => v),
);
});
await rep.query(async tx => {
expect(await asyncIterableToArray(tx.scan(options).keys())).to.deep.equal(
entries.map(([k]) => k),
);
});
await rep.query(async tx => {
expect(await tx.scanAll(options)).to.deep.equal(entries);
});
await rep.query(async tx => {
expect(await tx.scan(options).toArray()).to.deep.equal(
entries.map(([, v]) => v),
);
});
// scan().xxx().toArray()
await rep.query(async tx => {
expect(await tx.scan(options).entries().toArray()).to.deep.equal(entries);
});
await rep.query(async tx => {
expect(await tx.scan(options).values().toArray()).to.deep.equal(
entries.map(([, v]) => v),
);
});
await rep.query(async tx => {
expect(await tx.scan(options).keys().toArray()).to.deep.equal(
entries.map(([k]) => k),
);
});
}
testWithBothStores('scan', async () => {
const rep = await replicacheForTesting('test4', {
mutators: {
addData,
},
});
const add = rep.mutate.addData;
await add({
'a/0': 0,
'a/1': 1,
'a/2': 2,
'a/3': 3,
'a/4': 4,
'b/0': 5,
'b/1': 6,
'b/2': 7,
'c/0': 8,
});
await testScanResult(rep, undefined, [
['a/0', 0],
['a/1', 1],
['a/2', 2],
['a/3', 3],
['a/4', 4],
['b/0', 5],
['b/1', 6],
['b/2', 7],
['c/0', 8],
]);
await testScanResult(rep, {prefix: 'a'}, [
['a/0', 0],
['a/1', 1],
['a/2', 2],
['a/3', 3],
['a/4', 4],
]);
await testScanResult(rep, {prefix: 'b'}, [
['b/0', 5],
['b/1', 6],
['b/2', 7],
]);
await testScanResult(rep, {prefix: 'c/'}, [['c/0', 8]]);
await testScanResult(
rep,
{
start: {key: 'b/1', exclusive: false},
},
[
['b/1', 6],
['b/2', 7],
['c/0', 8],
],
);
await testScanResult(
rep,
{
start: {key: 'b/1'},
},
[
['b/1', 6],
['b/2', 7],
['c/0', 8],
],
);
await testScanResult(
rep,
{
start: {key: 'b/1', exclusive: true},
},
[
['b/2', 7],
['c/0', 8],
],
);
await testScanResult(
rep,
{
limit: 3,
},
[
['a/0', 0],
['a/1', 1],
['a/2', 2],
],
);
await testScanResult(
rep,
{
limit: 10,
prefix: 'a/',
},
[
['a/0', 0],
['a/1', 1],
['a/2', 2],
['a/3', 3],
['a/4', 4],
],
);
await testScanResult(
rep,
{
limit: 1,
prefix: 'b/',
},
[['b/0', 5]],
);
});
testWithBothStores('subscribe', async () => {
const log: [string, JSONValue][] = [];
const rep = await replicacheForTesting('subscribe', {
mutators: {
addData,
},
});
let queryCallCount = 0;
const cancel = rep.subscribe(
async (tx: ReadTransaction) => {
queryCallCount++;
const rv = [];
for await (const entry of tx.scan({prefix: 'a/'}).entries()) {
rv.push(entry);
}
return rv;
},
{
onData: (values: Iterable<[string, JSONValue]>) => {
for (const entry of values) {
log.push(entry);
}
},
},
);
expect(log).to.have.length(0);
expect(queryCallCount).to.equal(0);
const add = rep.mutate.addData;
await add({'a/0': 0});
expect(log).to.deep.equal([['a/0', 0]]);
expect(queryCallCount).to.equal(2); // One for initial subscribe and one for the add.
// The body returns the same JSON value in the following case.
log.length = 0;
await add({'a/0': 0});
expect(log).to.deep.equal([]);
expect(queryCallCount).to.equal(3);
log.length = 0;
await add({'a/1': 1});
expect(log).to.deep.equal([
['a/0', 0],
['a/1', 1],
]);
expect(queryCallCount).to.equal(4);
log.length = 0;
log.length = 0;
await add({'a/1': 11});
expect(log).to.deep.equal([
['a/0', 0],
['a/1', 11],
]);
expect(queryCallCount).to.equal(5);
log.length = 0;
cancel();
await add({'a/1': 11});
await Promise.resolve();
expect(log).to.have.length(0);
expect(queryCallCount).to.equal(5);
});
testWithBothStores('subscribe close', async () => {
const rep = await replicacheForTesting('subscribe-close', {
mutators: {addData},
});
const log: (JSONValue | undefined)[] = [];
const cancel = rep.subscribe((tx: ReadTransaction) => tx.get('k'), {
onData: value => log.push(value),
onDone: () => (done = true),
});
expect(log).to.have.length(0);
const add = rep.mutate.addData;
await add({k: 0});
await Promise.resolve();
expect(log).to.deep.equal([undefined, 0]);
let done = false;
await rep.close();
expect(done).to.equal(true);
cancel();
});
testWithBothStores('name', async () => {
const repA = await replicacheForTesting('a', {mutators: {addData}});
const repB = await replicacheForTesting('b', {mutators: {addData}});
const addA = repA.mutate.addData;
const addB = repB.mutate.addData;
await addA({key: 'A'});
await addB({key: 'B'});
expect(await repA.get('key')).to.equal('A');
expect(await repB.get('key')).to.equal('B');
await repA.close();
await repB.close();
indexedDB.deleteDatabase('a');
indexedDB.deleteDatabase('b');
});
testWithBothStores('register with error', async () => {
const rep = await replicacheForTesting('regerr', {
mutators: {
err: async (_: WriteTransaction, args: number) => {
throw args;
},
},
});
const doErr = rep.mutate.err;
try {
await doErr(42);
fail('Should have thrown');
} catch (ex) {
expect(ex).to.equal(42);
}
});
testWithBothStores('subscribe with error', async () => {
const rep = await replicacheForTesting('suberr', {mutators: {addData}});
const add = rep.mutate.addData;
let gottenValue = 0;
let error;
const cancel = rep.subscribe(
async tx => {
const v = await tx.get('k');
if (v !== undefined && v !== null) {
throw v;
}
return null;
},
{
onData: () => {
gottenValue++;
},
onError: e => {
error = e;
},
},
);
await Promise.resolve();
expect(error).to.equal(undefined);
expect(gottenValue).to.equal(0);
await add({k: 'throw'});
expect(gottenValue).to.equal(1);
await Promise.resolve();
expect(error).to.equal('throw');
cancel();
});
testWithBothStores('overlapping writes', async () => {
async function dbWait(tx: ReadTransaction, dur: number) {
// Try to take setTimeout away from me???
const t0 = Date.now();
while (Date.now() - t0 > dur) {
await tx.get('foo');
}
}
const pushURL = 'https://push.com';
// writes wait on writes
const rep = await replicacheForTesting('conflict', {
pushURL,
mutators: {
'wait-then-return': async <T extends JSONValue>(
tx: ReadTransaction,
{duration, ret}: {duration: number; ret: T},
) => {
await dbWait(tx, duration);
return ret;
},
},
});
fetchMock.post(pushURL, {});
const mut = rep.mutate['wait-then-return'];
let resA = mut({duration: 250, ret: 'a'});
// create a gap to make sure resA starts first (our rwlock isn't fair).
await clock.tickAsync(100);
let resB = mut({duration: 0, ret: 'b'});
// race them, a should complete first, indicating that b waited
expect(await Promise.race([resA, resB])).to.equal('a');
// wait for the other to finish so that we're starting from null state for next one.
await Promise.all([resA, resB]);
// reads wait on writes
resA = mut({duration: 250, ret: 'a'});
await clock.tickAsync(100);
resB = rep.query(() => 'b');
await tickAFewTimes();
expect(await Promise.race([resA, resB])).to.equal('a');
await tickAFewTimes();
await resA;
await tickAFewTimes();
await resB;
});
testWithBothStores('push', async () => {
const pushURL = 'https://push.com';
const rep = await replicacheForTesting('push', {
pushAuth: '1',
pushURL,
pushDelay: 10,
mutators: {
createTodo: async <A extends {id: number}>(
tx: WriteTransaction,
args: A,
) => {
createCount++;
await tx.put(`/todo/${args.id}`, args);
},
deleteTodo: async <A extends {id: number}>(
tx: WriteTransaction,
args: A,
) => {
deleteCount++;
await tx.del(`/todo/${args.id}`);
},
},
});
let createCount = 0;
let deleteCount = 0;
const {createTodo, deleteTodo} = rep.mutate;
const id1 = 14323534;
const id2 = 22354345;
await deleteTodo({id: id1});
await deleteTodo({id: id2});
expect(deleteCount).to.equal(2);
fetchMock.postOnce(pushURL, {
mutationInfos: [
{id: 1, error: 'deleteTodo: todo not found'},
{id: 2, error: 'deleteTodo: todo not found'},
],
});
await tickAFewTimes();
expect(deleteCount).to.equal(2);
const {mutations} = await fetchMock.lastCall().request.json();
expect(mutations).to.deep.equal([
{id: 1, name: 'deleteTodo', args: {id: id1}},
{id: 2, name: 'deleteTodo', args: {id: id2}},
]);
await createTodo({
id: id1,
text: 'Test',
});
expect(createCount).to.equal(1);
expect(((await rep?.get(`/todo/${id1}`)) as {text: string}).text).to.equal(
'Test',
);
fetchMock.postOnce(pushURL, {
mutationInfos: [{id: 3, error: 'mutation has already been processed'}],
});
await tickAFewTimes();
{
const {mutations} = await fetchMock.lastCall().request.json();
expect(mutations).to.deep.equal([
{id: 1, name: 'deleteTodo', args: {id: id1}},
{id: 2, name: 'deleteTodo', args: {id: id2}},
{id: 3, name: 'createTodo', args: {id: id1, text: 'Test'}},
]);
}
await createTodo({
id: id2,
text: 'Test 2',
});
expect(createCount).to.equal(2);
expect(((await rep?.get(`/todo/${id2}`)) as {text: string}).text).to.equal(
'Test 2',
);
// Clean up
await deleteTodo({id: id1});
await deleteTodo({id: id2});
expect(deleteCount).to.equal(4);
expect(createCount).to.equal(2);
fetchMock.postOnce(pushURL, {
mutationInfos: [],
});
await tickAFewTimes();
{
const {mutations} = await fetchMock.lastCall().request.json();
expect(mutations).to.deep.equal([
{id: 1, name: 'deleteTodo', args: {id: id1}},
{id: 2, name: 'deleteTodo', args: {id: id2}},
{id: 3, name: 'createTodo', args: {id: id1, text: 'Test'}},
{id: 4, name: 'createTodo', args: {id: id2, text: 'Test 2'}},
{id: 5, name: 'deleteTodo', args: {id: id1}},
{id: 6, name: 'deleteTodo', args: {id: id2}},
]);
}
expect(deleteCount).to.equal(4);
expect(createCount).to.equal(2);
});
testWithBothStores('push delay', async () => {
const pushURL = 'https://push.com';
const rep = await replicacheForTesting('push', {
pushAuth: '1',
pushURL,
pushDelay: 1,
mutators: {
createTodo: async <A extends {id: number}>(
tx: WriteTransaction,
args: A,
) => {
await tx.put(`/todo/${args.id}`, args);
},
},
});
const {createTodo} = rep.mutate;
const id1 = 14323534;
await tickAFewTimes();
fetchMock.reset();
fetchMock.postOnce(pushURL, {
mutationInfos: [],
});
expect(fetchMock.calls()).to.have.length(0);
await createTodo({id: id1});
expect(fetchMock.calls()).to.have.length(0);
await tickAFewTimes();
expect(fetchMock.calls()).to.have.length(1);
});
testWithBothStores('pull', async () => {
const pullURL = 'https://diff.com/pull';
const rep = await replicacheForTesting('pull', {
pullAuth: '1',
pullURL,
mutators: {
createTodo: async <A extends {id: number}>(
tx: WriteTransaction,
args: A,
) => {
createCount++;
await tx.put(`/todo/${args.id}`, args);
},
deleteTodo: async <A extends {id: number}>(
tx: WriteTransaction,
args: A,
) => {
deleteCount++;
await tx.del(`/todo/${args.id}`);
},
},
});
let createCount = 0;
let deleteCount = 0;
let syncHead: string;
let beginPullResult: {
requestID: string;
syncHead: string;
ok: boolean;
};
const {createTodo, deleteTodo} = rep.mutate;
const id1 = 14323534;
const id2 = 22354345;
await deleteTodo({id: id1});
await deleteTodo({id: id2});
expect(deleteCount).to.equal(2);
fetchMock.postOnce(pullURL, {
cookie: '',
lastMutationID: 2,
patch: [
{op: 'del', key: ''},
{
op: 'put',
key: '/list/1',
value: {id: 1, ownerUserID: 1},
},
],
});
rep.pull();
await tickAFewTimes();
expect(deleteCount).to.equal(2);
fetchMock.postOnce(pullURL, {
cookie: '',
lastMutationID: 2,
patch: [],
});
beginPullResult = await rep.beginPull();
({syncHead} = beginPullResult);
expect(syncHead).to.equal(emptyHash);
expect(deleteCount).to.equal(2);
await createTodo({
id: id1,
text: 'Test',
});
expect(createCount).to.equal(1);
expect(((await rep?.get(`/todo/${id1}`)) as {text: string}).text).to.equal(
'Test',
);
fetchMock.postOnce(pullURL, {
cookie: '',
lastMutationID: 3,
patch: [
{
op: 'put',
key: '/todo/14323534',
value: {id: 14323534, text: 'Test'},
},
],
});
beginPullResult = await rep.beginPull();
({syncHead} = beginPullResult);
expect(syncHead).equal('vadlsm00t0h5n05204h6srdjama32lft');
await createTodo({
id: id2,
text: 'Test 2',
});
expect(createCount).to.equal(2);
expect(((await rep?.get(`/todo/${id2}`)) as {text: string}).text).to.equal(
'Test 2',
);
fetchMock.postOnce(pullURL, {
cookie: '',
lastMutationID: 3,
patch: [],
});
await rep.maybeEndPull(beginPullResult);
expect(createCount).to.equal(3);
// Clean up
await deleteTodo({id: id1});
await deleteTodo({id: id2});
expect(deleteCount).to.equal(4);
expect(createCount).to.equal(3);
fetchMock.postOnce(pullURL, {
cookie: '',
lastMutationID: 6,
patch: [{op: 'del', key: '/todo/14323534'}],
});
rep.pull();
await tickAFewTimes();
expect(deleteCount).to.equal(4);
expect(createCount).to.equal(3);
});
testWithBothStores('reauth', async () => {
const pullURL = 'https://diff.com/pull';
const rep = await replicacheForTesting('reauth', {
pullURL,
pullAuth: 'wrong',
});
fetchMock.post(pullURL, {body: 'xxx', status: httpStatusUnauthorized});
const consoleErrorStub = sinon.stub(console, 'error');
const getPullAuthFake = sinon.fake.returns(null);
rep.getPullAuth = getPullAuthFake;
await rep.beginPull();
expect(getPullAuthFake.callCount).to.equal(1);
expect(consoleErrorStub.firstCall.args[0]).to.equal(
'Got error response from server (https://diff.com/pull) doing pull: 401: xxx',
);
{
const consoleInfoStub = sinon.stub(console, 'log');
const getPullAuthFake = sinon.fake(() => 'boo');
rep.getPullAuth = getPullAuthFake;
expect((await rep.beginPull()).syncHead).to.equal('');
expect(getPullAuthFake.callCount).to.equal(8);
expect(consoleInfoStub.firstCall.args[0]).to.equal(
'Tried to reauthenticate too many times',
);
}
});
testWithBothStores('HTTP status pull', async () => {
const pullURL = 'https://diff.com/pull';
const rep = await replicacheForTesting('http-status-pull', {
pullURL,
});
let okCalled = false;
let i = 0;
fetchMock.post(pullURL, () => {
switch (i++) {
case 0:
return {body: 'internal error', status: 500};
case 1:
return {body: 'not found', status: 404};
default:
okCalled = true;
return {body: {lastMutationID: 0, patch: []}, status: 200};
}
});
const consoleErrorStub = sinon.stub(console, 'error');
rep.pull();
await tickAFewTimes(20, 10);
expect(consoleErrorStub.getCalls().map(o => o.args[0])).to.deep.equal([
'Got error response from server (https://diff.com/pull) doing pull: 500: internal error',
'Got error response from server (https://diff.com/pull) doing pull: 404: not found',
]);
expect(okCalled).to.equal(true);
});
testWithBothStores('HTTP status push', async () => {
const pushURL = 'https://diff.com/push';
const rep = await replicacheForTesting('http-status-push', {
pushURL,
pushDelay: 1,
mutators: {addData},
});
const add = rep.mutate.addData;
let okCalled = false;
let i = 0;
fetchMock.post(pushURL, () => {
switch (i++) {
case 0:
return {body: 'internal error', status: 500};
case 1:
return {body: 'not found', status: 404};
default:
okCalled = true;
return {body: {}, status: 200};
}
});
const consoleErrorStub = sinon.stub(console, 'error');
await add({
a: 0,
});
await tickAFewTimes(20, 10);
expect(consoleErrorStub.getCalls().map(o => o.args[0])).to.deep.equal([
'Got error response from server (https://diff.com/push) doing push: 500: internal error',
'Got error response from server (https://diff.com/push) doing push: 404: not found',
]);
expect(okCalled).to.equal(true);
});
testWithBothStores('closed tx', async () => {
const rep = await replicacheForTesting('reauth', {
mutators: {
mut: async tx => {
wtx = tx;
},
},
});
let rtx: ReadTransaction;
await rep.query(tx => (rtx = tx));
await expectAsyncFuncToThrow(() => rtx.get('x'), TransactionClosedError);
await expectAsyncFuncToThrow(() => rtx.has('y'), TransactionClosedError);
await expectAsyncFuncToThrow(
() => rtx.scan().values().next(),
TransactionClosedError,
);
let wtx: WriteTransaction | undefined;
await rep.mutate.mut();
expect(wtx).to.not.be.undefined;
await expectAsyncFuncToThrow(() => wtx?.put('z', 1), TransactionClosedError);
await expectAsyncFuncToThrow(() => wtx?.del('w'), TransactionClosedError);
});
testWithBothStores('pullInterval in constructor', async () => {
const rep = await replicacheForTesting('pullInterval', {
pullInterval: 12.34,
});
expect(rep.pullInterval).to.equal(12.34);
await rep.close();
});