Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/util/common/test/testUtils.ts
13401 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import { afterEach, beforeEach } from 'vitest';
7
import { DisposableStore, DisposableTracker, IDisposable, setDisposableTracker } from '../../vs/base/common/lifecycle';
8
9
/**
10
* Use this function to ensure that all disposables are cleaned up at the end of each test in the current suite.
11
*
12
* Use `markAsSingleton` if disposable singletons are created lazily that are allowed to outlive the test.
13
* Make sure that the singleton properly registers all child disposables so that they are excluded too.
14
*
15
* @returns A {@link DisposableStore} that can optionally be used to track disposables in the test.
16
* This will be automatically disposed on test teardown.
17
*/
18
export function ensureNoDisposablesAreLeakedInTestSuite(): Pick<DisposableStore, 'add'> {
19
let tracker: DisposableTracker | undefined;
20
let store: DisposableStore;
21
22
beforeEach(() => {
23
store = new DisposableStore();
24
tracker = new DisposableTracker();
25
setDisposableTracker(tracker);
26
});
27
28
afterEach(() => {
29
store.clear();
30
setDisposableTracker(null);
31
const result = tracker!.computeLeakingDisposables();
32
if (result) {
33
console.error(result.details);
34
throw new Error(`There are ${result.leaks.length} undisposed disposables!${result.details}`);
35
}
36
});
37
38
// Wrap store as the suite function is called before it's initialized
39
const testContext = {
40
add<T extends IDisposable>(o: T): T {
41
return store.add(o);
42
}
43
};
44
return testContext;
45
}
46
47
export function throwIfDisposablesAreLeaked(body: () => void, logToConsole = true): void {
48
const tracker = new DisposableTracker();
49
setDisposableTracker(tracker);
50
body();
51
setDisposableTracker(null);
52
computeLeakingDisposables(tracker, logToConsole);
53
}
54
55
export async function throwIfDisposablesAreLeakedAsync(body: () => Promise<void>): Promise<void> {
56
const tracker = new DisposableTracker();
57
setDisposableTracker(tracker);
58
await body();
59
setDisposableTracker(null);
60
computeLeakingDisposables(tracker);
61
}
62
63
function computeLeakingDisposables(tracker: DisposableTracker, logToConsole = true) {
64
const result = tracker.computeLeakingDisposables();
65
if (result) {
66
if (logToConsole) {
67
console.error(result.details);
68
}
69
throw new Error(`There are ${result.leaks.length} undisposed disposables!${result.details}`);
70
}
71
}
72
73