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