diff --git a/typescript/src/python.ts b/typescript/src/python.ts index 464cef8..f30ba28 100644 --- a/typescript/src/python.ts +++ b/typescript/src/python.ts @@ -66,8 +66,8 @@ export interface IPythonApi { * Subscribe to package changes detected by the environment's package * managers. * - * Only available from newer versions of - * `ms-python.python-environments`. + * Only available from newer versions of + * `ms-python.python-environments`. */ onDidChangePackages?(handler: () => void): Disposable; @@ -84,8 +84,26 @@ export interface IPythonApi { // API adapters // --------------------------------------------------------------------------- +type UsableEnvironmentsApi = Pick< + PythonEnvironmentApi, + 'getEnvironment' | 'resolveEnvironment' | 'onDidChangeEnvironment' +> & + Partial; + +function isUsableEnvironmentsApi(api: unknown): api is UsableEnvironmentsApi { + if (typeof api !== 'object' || api === null) { + return false; + } + const candidate = api as Partial; + return ( + typeof candidate.getEnvironment === 'function' && + typeof candidate.resolveEnvironment === 'function' && + typeof candidate.onDidChangeEnvironment === 'function' + ); +} + /** Wrap the newer `@vscode/python-environments` API. */ -function wrapEnvironmentsApi(api: PythonEnvironmentApi): IPythonApi { +function wrapEnvironmentsApi(api: UsableEnvironmentsApi): IPythonApi { return { extension: 'ms-python.python-environments', @@ -144,6 +162,9 @@ function wrapEnvironmentsApi(api: PythonEnvironmentApi): IPythonApi { }, onDidChangePackages(handler: () => void) { + if (typeof api.onDidChangePackages !== 'function') { + return { dispose: () => undefined }; + } return api.onDidChangePackages(handler); }, @@ -260,9 +281,12 @@ export class PythonEnvironmentsProvider { } try { const envsApi = await PythonEnvironments.api(); - this._api = wrapEnvironmentsApi(envsApi); - this._apiResolved = true; - return this._api; + if (isUsableEnvironmentsApi(envsApi)) { + this._api = wrapEnvironmentsApi(envsApi); + this._apiResolved = true; + return this._api; + } + traceLog('Python environments API is incomplete — trying legacy.'); } catch { traceLog('Python environments extension not available — trying legacy.'); } @@ -378,14 +402,14 @@ export class PythonEnvironmentsProvider { * wired regardless of how the interpreter was selected (resolved by the * Python extension *or* pinned via the `.interpreter` setting). * - * Subscription failures are non-fatal: if no API is available, the runtime - * does not expose `onDidChangePackages` (e.g. the legacy `ms-python.python` - * extension or a version-skewed runtime), or subscribing throws, this - * resolves to `undefined` and logs rather than propagating — a refresh - * feature must never block or break activation. + * Subscription failures are non-fatal: adapters without package events + * (e.g. the legacy `ms-python.python` extension or a version-skewed runtime) + * return a no-op disposable. If no API is available, or subscribing throws, + * this resolves to `undefined` rather than propagating — a refresh feature + * must never block or break activation. * - * @returns A {@link Disposable} for the subscription, or `undefined` when no - * package-change event is available. + * @returns A real or no-op {@link Disposable}, or `undefined` when no API is + * available or subscription fails. */ async subscribeToPackageChanges(handler: () => void): Promise { try { diff --git a/typescript/tests/python.test.ts b/typescript/tests/python.test.ts index 6de0eb4..611a7b5 100644 --- a/typescript/tests/python.test.ts +++ b/typescript/tests/python.test.ts @@ -3,6 +3,8 @@ import { assert } from 'chai'; import * as sinon from 'sinon'; +import { PythonEnvironments } from '@vscode/python-environments'; +import { PythonExtension } from '@vscode/python-extension'; import { EventEmitter, Uri } from 'vscode'; import { PythonEnvironmentsProvider, IInterpreterDetails } from '../src/python'; import { IResolvedPythonEnvironment, ToolConfig } from '../src/types'; @@ -139,6 +141,187 @@ suite('PythonEnvironmentsProvider', () => { assert.isArray(disposables); }); + for (const [description, incompleteApi] of [ + ['undefined', undefined], + ['null', null], + ['an empty object', {}], + [ + 'no getEnvironment', + { + resolveEnvironment: () => undefined, + onDidChangeEnvironment: () => undefined, + }, + ], + [ + 'no resolveEnvironment', + { + getEnvironment: () => undefined, + onDidChangeEnvironment: () => undefined, + }, + ], + [ + 'no onDidChangeEnvironment', + { + getEnvironment: () => undefined, + resolveEnvironment: () => undefined, + }, + ], + [ + 'a non-callable onDidChangeEnvironment', + { + getEnvironment: () => undefined, + resolveEnvironment: () => undefined, + onDidChangeEnvironment: {}, + }, + ], + ] as const) { + test(`falls back to the legacy API when the environments API returns ${description}`, async () => { + const environmentsApi = sinon.stub(PythonEnvironments, 'api').resolves(incompleteApi as never); + + const onDidChangeActiveEnvironmentPath = sinon.stub().returns({ dispose: sinon.stub() }); + const resolveEnvironment = sinon.stub().resolves({ + executable: { uri: { fsPath: '/usr/bin/python3' } }, + version: { major: 3, minor: 12, micro: 1 }, + }); + const legacyApi = sinon.stub(PythonExtension, 'api').resolves({ + environments: { + getActiveEnvironmentPath: sinon.stub().returns('/usr/bin/python3'), + onDidChangeActiveEnvironmentPath, + resolveEnvironment, + }, + debug: { + getDebuggerPackagePath: sinon.stub().resolves(undefined), + }, + } as never); + + const provider = new PythonEnvironmentsProvider(makeToolConfig()); + const disposables: { dispose: () => void }[] = []; + const resource = Uri.parse('file:///workspace'); + + await provider.initializePython(disposables, async () => [resource]); + + assert.isTrue(environmentsApi.calledOnce, 'should try the environments API first'); + assert.isTrue(legacyApi.calledOnce, 'should try the legacy API'); + sinon.assert.callOrder(environmentsApi, legacyApi); + assert.isTrue(onDidChangeActiveEnvironmentPath.calledOnce, 'should subscribe through the legacy API'); + assert.lengthOf(disposables, 2); + + const interpreter = await provider.getInterpreterDetails(resource); + assert.deepEqual(interpreter.path, ['/usr/bin/python3']); + assert.strictEqual(interpreter.resource, resource); + assert.isTrue(resolveEnvironment.calledTwice, 'should cache and reuse the legacy API'); + assert.isTrue(environmentsApi.calledOnce, 'should not retry the environments API'); + assert.isTrue(legacyApi.calledOnce, 'should reuse the cached legacy API'); + }); + } + + test('prefers and caches a healthy environments API', async () => { + const environment = { + version: '3.12.1', + execInfo: { + activatedRun: { executable: '/activated/python', args: ['-I'] }, + run: { executable: '/unactivated/python' }, + }, + }; + const getEnvironment = sinon.stub().resolves(environment); + const resolveEnvironment = sinon.stub().resolves(environment); + const packageChanges = new EventEmitter(); + const projects = [{ name: 'project', uri: Uri.parse('file:///workspace/project') }]; + const environmentsApi = sinon.stub(PythonEnvironments, 'api').resolves({ + getEnvironment, + resolveEnvironment, + onDidChangeEnvironment: sinon.stub().returns({ dispose: sinon.stub() }), + getPythonProjects: sinon.stub().returns(projects), + onDidChangePythonProjects: sinon.stub().returns({ dispose: sinon.stub() }), + onDidChangePackages: packageChanges.event, + } as never); + const legacyApi = sinon.stub(PythonExtension, 'api').rejects(new Error('must not use legacy')); + const provider = new PythonEnvironmentsProvider(makeToolConfig()); + const resource = Uri.parse('file:///workspace'); + + const interpreter = await provider.getInterpreterDetails(resource); + assert.deepEqual(interpreter, { + path: ['/activated/python', '-I'], + resource, + }); + sinon.assert.calledWithExactly(getEnvironment, resource); + + assert.deepEqual(await provider.resolveInterpreter(['/manual/python']), { + executablePath: '/activated/python', + args: ['-I'], + version: { major: 3, minor: 12, micro: 1 }, + }); + assert.strictEqual(resolveEnvironment.firstCall.args[0].fsPath, Uri.file('/manual/python').fsPath); + assert.deepEqual(await provider.getPythonProjects(), projects); + assert.isUndefined(await provider.getDebuggerPath()); + + const handler = sinon.stub(); + const disposable = await provider.subscribeToPackageChanges(handler); + packageChanges.fire(); + sinon.assert.calledOnce(handler); + disposable?.dispose(); + packageChanges.fire(); + sinon.assert.calledOnce(handler); + packageChanges.dispose(); + + sinon.assert.calledOnce(environmentsApi); + sinon.assert.notCalled(legacyApi); + }); + + test('uses the environments API without optional project or package capabilities', async () => { + const onDidChangeEnvironment = sinon.stub().returns({ dispose: sinon.stub() }); + const getEnvironment = sinon.stub().resolves({ + version: '3.12.1', + execInfo: { run: { executable: '/usr/bin/python3', args: ['-I'] } }, + }); + const environmentsApi = sinon.stub(PythonEnvironments, 'api').resolves({ + getEnvironment, + resolveEnvironment: sinon.stub().resolves(undefined), + onDidChangeEnvironment, + } as never); + const legacyApi = sinon.stub(PythonExtension, 'api'); + + const provider = new PythonEnvironmentsProvider(makeToolConfig()); + const disposables: { dispose: () => void }[] = []; + const resource = Uri.parse('file:///workspace'); + + await provider.initializePython(disposables, async () => [resource]); + + assert.isTrue(environmentsApi.calledOnce); + assert.isFalse(legacyApi.called); + assert.isTrue(onDidChangeEnvironment.calledOnce); + assert.lengthOf(disposables, 2); + assert.deepEqual((await provider.getInterpreterDetails(resource)).path, ['/usr/bin/python3', '-I']); + assert.deepEqual(await provider.getPythonProjects(), []); + + const packageDisposable = await provider.subscribeToPackageChanges(sinon.stub()); + assert.isDefined(packageDisposable); + assert.isTrue(environmentsApi.calledOnce, 'should reuse the cached environments API'); + packageDisposable?.dispose(); + }); + + test('handles incomplete preferred exports and an unavailable legacy API without caching a broken adapter', async () => { + const environmentsApi = sinon.stub(PythonEnvironments, 'api').resolves(undefined as never); + const legacyApi = sinon.stub(PythonExtension, 'api').rejects(new Error('legacy unavailable')); + const provider = new PythonEnvironmentsProvider(makeToolConfig()); + const disposables: { dispose: () => void }[] = []; + const resource = Uri.parse('file:///workspace'); + + await provider.initializePython(disposables, async () => [resource]); + + assert.isEmpty(disposables); + assert.deepEqual(await provider.getInterpreterDetails(resource), { + path: undefined, + resource, + }); + assert.isUndefined(await provider.resolveInterpreter(['/manual/python'])); + assert.isUndefined(await provider.getDebuggerPath()); + assert.isUndefined(await provider.subscribeToPackageChanges(sinon.stub())); + assert.deepEqual(await provider.getPythonProjects(), []); + sinon.assert.calledOnce(environmentsApi); + sinon.assert.calledOnce(legacyApi); + }); + test('supports an environments API without project events', async () => { const provider = new PythonEnvironmentsProvider(makeToolConfig()); const internal = provider as unknown as { _api: unknown; _apiResolved: boolean }; @@ -153,11 +336,7 @@ suite('PythonEnvironmentsProvider', () => { internal._apiResolved = true; const disposables: { dispose: () => void }[] = []; - await provider.initializePython( - disposables, - async () => [Uri.parse('file:///workspace')], - false, - ); + await provider.initializePython(disposables, async () => [Uri.parse('file:///workspace')], false); assert.lengthOf(disposables, 1); }); @@ -174,9 +353,7 @@ suite('PythonEnvironmentsProvider', () => { extension: 'ms-python.python-environments', getEnvironment: async (resource?: Uri) => { const executablePath = interpreters.get(resource?.toString() ?? ''); - return executablePath - ? { executablePath, version: { major: 3, minor: 10, micro: 0 } } - : undefined; + return executablePath ? { executablePath, version: { major: 3, minor: 10, micro: 0 } } : undefined; }, resolveEnvironment: sinon.stub(), onDidChangeEnvironment: environmentChanged.event, @@ -189,10 +366,7 @@ suite('PythonEnvironmentsProvider', () => { internal._api = api; internal._apiResolved = true; - const resources = async () => [ - Uri.parse('file:///workspace'), - Uri.parse('file:///workspace/project'), - ]; + const resources = async () => [Uri.parse('file:///workspace'), Uri.parse('file:///workspace/project')]; const changes = sinon.stub(); provider.onDidChangeInterpreter(changes); const disposables: { dispose: () => void }[] = []; @@ -247,6 +421,25 @@ suite('PythonEnvironmentsProvider', () => { internal._apiResolved = true; } + test('keeps a healthy preferred API when package subscriptions throw', async () => { + const environmentsApi = sinon.stub(PythonEnvironments, 'api').resolves({ + getEnvironment: sinon.stub().resolves({ + version: '3.12.1', + execInfo: { run: { executable: '/usr/bin/python3' } }, + }), + resolveEnvironment: sinon.stub().resolves(undefined), + onDidChangeEnvironment: sinon.stub().returns({ dispose: sinon.stub() }), + onDidChangePackages: sinon.stub().throws(new Error('package event unavailable')), + } as never); + const legacyApi = sinon.stub(PythonExtension, 'api'); + const provider = new PythonEnvironmentsProvider(makeToolConfig()); + + assert.isUndefined(await provider.subscribeToPackageChanges(sinon.stub())); + assert.deepEqual((await provider.getInterpreterDetails()).path, ['/usr/bin/python3']); + sinon.assert.calledOnce(environmentsApi); + sinon.assert.notCalled(legacyApi); + }); + test('subscribes to onDidChangePackages and forwards events to the handler', async () => { const provider = new PythonEnvironmentsProvider(makeToolConfig()); diff --git a/typescript/tests/toolExtension.test.ts b/typescript/tests/toolExtension.test.ts index 8694dac..6bf7910 100644 --- a/typescript/tests/toolExtension.test.ts +++ b/typescript/tests/toolExtension.test.ts @@ -47,6 +47,7 @@ suite('activateToolExtension', () => { let configuredInterpreter: string[] | undefined; let api: { getEnvironment: sinon.SinonStub; + resolveEnvironment: sinon.SinonStub; onDidChangeEnvironment: sinon.SinonStub; onDidChangePythonProjects: sinon.SinonStub; onDidChangePackages: sinon.SinonStub; @@ -147,6 +148,7 @@ suite('activateToolExtension', () => { run: { executable: path.join(process.cwd(), 'managed-python') }, }, }), + resolveEnvironment: sandbox.stub().resolves(undefined), onDidChangeEnvironment: sandbox.stub().callsFake(() => resource('python.environment')), onDidChangePythonProjects: sandbox.stub().callsFake(() => resource('python.projects')), onDidChangePackages: sandbox.stub().callsFake(() => resource('python.packages')),