forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorators.unit.test.ts
More file actions
335 lines (295 loc) · 12.8 KB
/
decorators.unit.test.ts
File metadata and controls
335 lines (295 loc) · 12.8 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { expect, use } from 'chai';
import * as chaiPromise from 'chai-as-promised';
import { clearCache } from '../../../client/common/utils/cacheUtils';
import { cache, makeDebounceAsyncDecorator, makeDebounceDecorator } from '../../../client/common/utils/decorators';
import { sleep } from '../../core';
use(chaiPromise);
suite('Common Utils - Decorators', function () {
// For some reason, sometimes we have timeouts on CI.
// Note: setTimeout and similar functions are not guaranteed to execute
// at the precise time prescribed.
this.retries(3);
suite('Cache Decorator', () => {
const oldValueOfVSC_PYTHON_UNIT_TEST = process.env.VSC_PYTHON_UNIT_TEST;
const oldValueOfVSC_PYTHON_CI_TEST = process.env.VSC_PYTHON_CI_TEST;
setup(() => {
process.env.VSC_PYTHON_UNIT_TEST = undefined;
process.env.VSC_PYTHON_CI_TEST = undefined;
});
teardown(() => {
process.env.VSC_PYTHON_UNIT_TEST = oldValueOfVSC_PYTHON_UNIT_TEST;
process.env.VSC_PYTHON_CI_TEST = oldValueOfVSC_PYTHON_CI_TEST;
clearCache();
});
class TestClass {
public invoked = false;
@cache(1000)
public async doSomething(a: number, b: number): Promise<number> {
this.invoked = true;
return a + b;
}
}
test('Result should be cached for 1s', async () => {
const cls = new TestClass();
expect(cls.invoked).to.equal(false, 'Wrong initialization value');
await expect(cls.doSomething(1, 2)).to.eventually.equal(3);
expect(cls.invoked).to.equal(true, 'Should have been invoked');
// Reset and ensure it is not updated.
cls.invoked = false;
await expect(cls.doSomething(1, 2)).to.eventually.equal(3);
expect(cls.invoked).to.equal(false, 'Should not have been invoked');
await expect(cls.doSomething(1, 2)).to.eventually.equal(3);
expect(cls.invoked).to.equal(false, 'Should not have been invoked');
// Cache should expire.
await sleep(2000);
await expect(cls.doSomething(1, 2)).to.eventually.equal(3);
expect(cls.invoked).to.equal(true, 'Should have been invoked');
// Reset and ensure it is not updated.
cls.invoked = false;
await expect(cls.doSomething(1, 2)).to.eventually.equal(3);
expect(cls.invoked).to.equal(false, 'Should not have been invoked');
}).timeout(3000);
});
suite('Debounce', () => {
/*
* Time in milliseconds (from some arbitrary point in time for current process).
* Don't use new Date().getTime() to calculate differences in times.
* Similarly setTimeout doesn't always trigger at prescribed time (accuracy isn't guaranteed).
* This has an accuracy of around 2-20ms.
* However we're dealing with tests that need accuracy of 1ms.
* Use API that'll give us better accuracy when dealing with elapsed times.
*
* @returns {number}
*/
function getHighPrecisionTime(): number {
const currentTime = process.hrtime();
// Convert seconds to ms and nanoseconds to ms.
return currentTime[0] * 1000 + currentTime[1] / 1000_000;
}
/**
* setTimeout doesn't always trigger at prescribed time (accuracy isn't guaranteed).
* Allow a discrepancy of +-5%.
* Here's a simple test to prove this (this has been reported by others too):
* ```js
* // Execute the following around 100 times, you'll see at least one where elapsed time is < 100.
* const startTime = ....
* await new Promise(resolve = setTimeout(resolve, 100))
* console.log(currentTime - startTijme)
* ```
*
* @param {number} actualDelay
* @param {number} expectedDelay
*/
function assertElapsedTimeWithinRange(actualDelay: number, expectedDelay: number) {
const difference = actualDelay - expectedDelay;
if (difference >= 0) {
return;
}
expect(Math.abs(difference)).to.be.lessThan(
expectedDelay * 0.05,
`Actual delay ${actualDelay}, expected delay ${expectedDelay}, not within 5% of accuracy`,
);
}
class Base {
public created: number;
public calls: string[];
public timestamps: number[];
constructor() {
this.created = getHighPrecisionTime();
this.calls = [];
this.timestamps = [];
}
protected _addCall(funcname: string, timestamp?: number): void {
if (!timestamp) {
timestamp = getHighPrecisionTime();
}
this.calls.push(funcname);
this.timestamps.push(timestamp);
}
}
async function waitForCalls(timestamps: number[], count: number, delay = 10, timeout = 1000) {
const steps = timeout / delay;
for (let i = 0; i < steps; i += 1) {
if (timestamps.length >= count) {
return;
}
await sleep(delay);
}
if (timestamps.length < count) {
throw Error(`timed out after ${timeout}ms`);
}
}
test('Debounce: one sync call', async () => {
const wait = 100;
class One extends Base {
@makeDebounceDecorator(wait)
public run(): void {
this._addCall('run');
}
}
const one = new One();
const start = getHighPrecisionTime();
one.run();
await waitForCalls(one.timestamps, 1);
const delay = one.timestamps[0] - start;
assertElapsedTimeWithinRange(delay, wait);
expect(one.calls).to.deep.equal(['run']);
expect(one.timestamps).to.have.lengthOf(one.calls.length);
});
test('Debounce: one async call & no wait', async () => {
const wait = 100;
class One extends Base {
@makeDebounceAsyncDecorator(wait)
public async run(): Promise<void> {
this._addCall('run');
}
}
const one = new One();
const start = getHighPrecisionTime();
let errored = false;
one.run().catch(() => (errored = true));
await waitForCalls(one.timestamps, 1);
const delay = one.timestamps[0] - start;
assertElapsedTimeWithinRange(delay, wait);
expect(one.calls).to.deep.equal(['run']);
expect(one.timestamps).to.have.lengthOf(one.calls.length);
expect(errored).to.be.equal(false, "Exception raised when there shouldn't have been any");
});
test('Debounce: one async call', async () => {
const wait = 100;
class One extends Base {
@makeDebounceAsyncDecorator(wait)
public async run(): Promise<void> {
this._addCall('run');
}
}
const one = new One();
const start = getHighPrecisionTime();
await one.run();
await waitForCalls(one.timestamps, 1);
const delay = one.timestamps[0] - start;
assertElapsedTimeWithinRange(delay, wait);
expect(one.calls).to.deep.equal(['run']);
expect(one.timestamps).to.have.lengthOf(one.calls.length);
});
test('Debounce: one async call and ensure exceptions are re-thrown', async () => {
const wait = 100;
class One extends Base {
@makeDebounceAsyncDecorator(wait)
public async run(): Promise<void> {
this._addCall('run');
throw new Error('Kaboom');
}
}
const one = new One();
const start = getHighPrecisionTime();
let capturedEx: Error | undefined;
await one.run().catch((ex) => (capturedEx = ex));
await waitForCalls(one.timestamps, 1);
const delay = one.timestamps[0] - start;
assertElapsedTimeWithinRange(delay, wait);
expect(one.calls).to.deep.equal(['run']);
expect(one.timestamps).to.have.lengthOf(one.calls.length);
expect(capturedEx).to.not.be.equal(undefined, 'Exception not re-thrown');
});
test('Debounce: multiple async calls', async () => {
const wait = 100;
class One extends Base {
@makeDebounceAsyncDecorator(wait)
public async run(): Promise<void> {
this._addCall('run');
}
}
const one = new One();
const start = getHighPrecisionTime();
let errored = false;
one.run().catch(() => (errored = true));
one.run().catch(() => (errored = true));
one.run().catch(() => (errored = true));
one.run().catch(() => (errored = true));
await waitForCalls(one.timestamps, 1);
const delay = one.timestamps[0] - start;
assertElapsedTimeWithinRange(delay, wait);
expect(one.calls).to.deep.equal(['run']);
expect(one.timestamps).to.have.lengthOf(one.calls.length);
expect(errored).to.be.equal(false, "Exception raised when there shouldn't have been any");
});
test('Debounce: multiple async calls when awaiting on all', async function () {
const wait = 100;
class One extends Base {
@makeDebounceAsyncDecorator(wait)
public async run(): Promise<void> {
this._addCall('run');
}
}
const one = new One();
const start = getHighPrecisionTime();
await Promise.all([one.run(), one.run(), one.run(), one.run()]);
await waitForCalls(one.timestamps, 1);
const delay = one.timestamps[0] - start;
assertElapsedTimeWithinRange(delay, wait);
expect(one.calls).to.deep.equal(['run']);
expect(one.timestamps).to.have.lengthOf(one.calls.length);
});
test('Debounce: multiple async calls & wait on some', async () => {
const wait = 100;
class One extends Base {
@makeDebounceAsyncDecorator(wait)
public async run(): Promise<void> {
this._addCall('run');
}
}
const one = new One();
const start = getHighPrecisionTime();
let errored = false;
one.run().catch(() => (errored = true));
await one.run();
one.run().catch(() => (errored = true));
one.run().catch(() => (errored = true));
await waitForCalls(one.timestamps, 2);
const delay = one.timestamps[1] - start;
assertElapsedTimeWithinRange(delay, wait);
expect(one.calls).to.deep.equal(['run', 'run']);
expect(one.timestamps).to.have.lengthOf(one.calls.length);
expect(errored).to.be.equal(false, "Exception raised when there shouldn't have been any");
});
test('Debounce: multiple calls grouped', async () => {
const wait = 100;
class One extends Base {
@makeDebounceDecorator(wait)
public run(): void {
this._addCall('run');
}
}
const one = new One();
const start = getHighPrecisionTime();
one.run();
one.run();
one.run();
await waitForCalls(one.timestamps, 1);
const delay = one.timestamps[0] - start;
assertElapsedTimeWithinRange(delay, wait);
expect(one.calls).to.deep.equal(['run']);
expect(one.timestamps).to.have.lengthOf(one.calls.length);
});
test('Debounce: multiple calls spread', async () => {
const wait = 100;
class One extends Base {
@makeDebounceDecorator(wait)
public run(): void {
this._addCall('run');
}
}
const one = new One();
one.run();
await sleep(wait);
one.run();
await waitForCalls(one.timestamps, 2);
expect(one.calls).to.deep.equal(['run', 'run']);
expect(one.timestamps).to.have.lengthOf(one.calls.length);
});
});
});