deno.land / x / replicache@v10.0.0-beta.0 / test-util.ts

نووسراو ببینە
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
import {expect} from '@esm-bundle/chai';import {MutatorDefs, Replicache, BeginPullResult} from './replicache';import type { ReplicacheOptions, ReplicacheInternalOptions, ReplicacheInternalAPI,} from './replicache-options';import * as kv from './kv/mod';import * as persist from './persist/mod';import {SinonFakeTimers, useFakeTimers} from 'sinon';import * as sinon from 'sinon';import type {JSONValue, ReadonlyJSONValue} from './json';import {Hash, makeNewTempHashFunction} from './hash';
// 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-errorimport fetchMock from 'fetch-mock/esm/client';import {uuid} from './uuid';import type {WriteTransaction} from './transactions.js';import {TEST_LICENSE_KEY} from '@rocicorp/licensing/src/client';
export class ReplicacheTest< // eslint-disable-next-line @typescript-eslint/ban-types MD extends MutatorDefs = {},> extends Replicache<MD> { private _internalAPI!: ReplicacheInternalAPI;
constructor(options: ReplicacheOptions<MD>) { let internalAPI!: ReplicacheInternalAPI; super({ ...options, exposeInternalAPI: (api: ReplicacheInternalAPI) => { internalAPI = api; }, } as ReplicacheOptions<MD>); this._internalAPI = internalAPI; }
beginPull(): Promise<BeginPullResult> { return super._beginPull(); }
maybeEndPull(beginPullResult: BeginPullResult): Promise<void> { return super._maybeEndPull(beginPullResult); }
invokePush(): Promise<boolean> { return super._invokePush(); }
protected override _memdagHashFunction(): <V extends ReadonlyJSONValue>( data: V, ) => Hash { return makeNewTempHashFunction(); }
protected override _invokePush(): Promise<boolean> { // indirection to allow test to spy on it. return this.invokePush(); }
protected override _beginPull(): Promise<BeginPullResult> { return this.beginPull(); }
persist() { return this._internalAPI.persist(); // return this[persistSymbol](); }
recoverMutationsSpy = sinon.spy(this, 'recoverMutations');
recoverMutations(): Promise<boolean> { return super._recoverMutations(); }
protected override _recoverMutations(): Promise<boolean> { // indirection to allow test to spy on it. return this.recoverMutations(); }
licenseActive(): Promise<boolean> { return this._licenseActivePromise; }
licenseValid(): Promise<boolean> { return this._licenseCheckPromise; }
get perdag() { // @ts-expect-error Property '_perdag' is private return this._perdag; }}
export const reps: Set<ReplicacheTest> = new Set();
export async function closeAllReps(): Promise<void> { for (const rep of reps) { if (!rep.closed) { await rep.close(); } reps.delete(rep); }}
export const dbsToDrop: Set<string> = new Set();
export async function deleteAllDatabases(): Promise<void> { for (const name of dbsToDrop) { await kv.dropIDBStore(name); } dbsToDrop.clear();}
const partialNamesToReplicacheNames: Map<string, string> = new Map();/** Namespace replicache names to isolate tests' IndexedDB state. */export function createReplicacheNameForTest(partialName: string): string { let replicacheName = partialNamesToReplicacheNames.get(partialName); if (!replicacheName) { const namespaceForTest = uuid(); replicacheName = `${namespaceForTest}:${partialName}`; partialNamesToReplicacheNames.set(partialName, replicacheName); } return replicacheName;}
type ReplicacheTestOptions<MD extends MutatorDefs> = Omit< ReplicacheOptions<MD>, 'name' | 'licenseKey'> & { onClientStateNotFound?: (() => void) | null; licenseKey?: string;} & ReplicacheInternalOptions;
export async function replicacheForTesting< // eslint-disable-next-line @typescript-eslint/ban-types MD extends MutatorDefs = {},>( partialName: string, options: ReplicacheTestOptions<MD> = {},): Promise<ReplicacheTest<MD>> { const pullURL = 'https://pull.com/?name=' + partialName; const pushURL = 'https://push.com/?name=' + partialName; return replicacheForTestingNoDefaultURLs( createReplicacheNameForTest(partialName), { pullURL, pushURL, licenseKey: options.licenseKey ?? TEST_LICENSE_KEY, ...options, }, );}
export async function replicacheForTestingNoDefaultURLs< // eslint-disable-next-line @typescript-eslint/ban-types MD extends MutatorDefs = {},>( name: string, { pullURL, pushDelay = 60_000, // Large to prevent interfering pushURL, onClientStateNotFound = () => { throw new Error( 'Unexpected call to onClientStateNotFound. Did you forget to pass it as an option?', ); }, ...rest }: ReplicacheTestOptions<MD> = {},): Promise<ReplicacheTest<MD>> { const rep = new ReplicacheTest<MD>({ pullURL, pushDelay, pushURL, name, licenseKey: TEST_LICENSE_KEY, ...rest, }); dbsToDrop.add(rep.idbName); reps.add(rep);
rep.onClientStateNotFound = onClientStateNotFound;
// Wait for open to be done. await rep.clientID; fetchMock.post(pullURL, {lastMutationID: 0, patch: []}); fetchMock.post(pushURL, 'ok'); await tickAFewTimes(); return rep;}
export let clock: SinonFakeTimers;
export function initReplicacheTesting(): void { fetchMock.config.overwriteRoutes = true;
setup(() => { clock = useFakeTimers(0); persist.setupIDBDatabasesStoreForTest(); });
teardown(async () => { clock.restore(); fetchMock.restore(); sinon.restore(); partialNamesToReplicacheNames.clear(); await closeAllReps(); await deleteAllDatabases(); await persist.teardownIDBDatabasesStoreForTest(); });}
export async function tickAFewTimes(n = 10, time = 10) { for (let i = 0; i < n; i++) { await clock.tickAsync(time); }}
export async function tickUntil(f: () => boolean, msPerTest = 10) { while (!f()) { await clock.tickAsync(msPerTest); }}
export class MemStoreWithCounters implements kv.Store { readonly store = new kv.MemStore(); readCount = 0; writeCount = 0; closeCount = 0;
resetCounters() { this.readCount = 0; this.writeCount = 0; this.closeCount = 0; }
read() { this.readCount++; return this.store.read(); }
withRead<R>(fn: (read: kv.Read) => R | Promise<R>): Promise<R> { this.readCount++; return this.store.withRead(fn); }
write() { this.writeCount++; return this.store.write(); }
withWrite<R>(fn: (write: kv.Write) => R | Promise<R>): Promise<R> { this.writeCount++; return this.store.withWrite(fn); }
async close() { this.closeCount++; await this.store.close(); }
get closed(): boolean { return this.store.closed; }}
export async function addData( tx: WriteTransaction, data: {[key: string]: JSONValue},) { for (const [key, value] of Object.entries(data)) { await tx.put(key, value); }}
export function expectLogContext( consoleLogStub: sinon.SinonStub, index: number, rep: Replicache, expectedContext: string,) { expect(consoleLogStub.callCount).to.greaterThan(index); const {args} = consoleLogStub.getCall(index); expect(args).to.have.length(2); expect(args[0]).to.equal(`name=${rep.name}`); expect(args[1]).to.equal(expectedContext);}
replicache

Version Info

Tagged at
2 years ago