Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions .github/instructions/testing-workflow.instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,20 @@ This guide covers the full testing lifecycle:

These mistakes have occurred REPEATEDLY. Check this list BEFORE writing any test code:

| Mistake | Fix |
| ---------------------------------------------- | ------------------------------------------------------------------ |
| Hardcoded POSIX paths like `'/test/workspace'` | Use `'.'` for relative paths, `Uri.file(x).fsPath` for comparisons |
| Stubbing `workspace.getConfiguration` directly | Stub the wrapper `workspaceApis.getConfiguration` instead |
| Stubbing `workspace.workspaceFolders` property | Stub wrapper function `workspaceApis.getWorkspaceFolders()` |
| Comparing `fsPath` to raw string | Compare `fsPath` to `Uri.file(expected).fsPath` |
| Mistake | Fix |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------ |
| Hardcoded POSIX paths like `'/test/workspace'` | Use `'.'` for relative paths, `Uri.file(x).fsPath` for comparisons |
| Stubbing `workspace.getConfiguration` directly | Stub the wrapper `workspaceApis.getConfiguration` instead |
| Stubbing `workspace.workspaceFolders` property | Stub wrapper function `workspaceApis.getWorkspaceFolders()` |
| Comparing `fsPath` to raw string | Compare `fsPath` to `Uri.file(expected).fsPath` |
| Stubbing `commands.executeCommand` directly | First update production code to use `executeCommand` from `command.api.ts`, then stub that |
| Stubbing `window.createTreeView` directly | First update production code to use `createTreeView` from `window.apis.ts`, then stub that |

**Pre-flight checklist before completing test work:**

- [ ] All paths use `Uri.file().fsPath` (no hardcoded `/path/to/x`)
- [ ] All VS Code API stubs use wrapper modules, not `vscode.*` directly
- [ ] Production code uses wrappers for any VS Code API that tests need to stub (check `src/common/*.apis.ts`)
- [ ] Tests pass on both Windows and POSIX

## Test Types
Expand Down Expand Up @@ -597,4 +600,5 @@ envConfig.inspect
- Use `sinon.useFakeTimers()` with `clock.tickAsync()` instead of `await new Promise(resolve => setTimeout(resolve, ms))` for debounce/timeout handling - eliminates flakiness and speeds up tests significantly (1)
- Always compile tests (`npm run compile-tests`) before running them after adding new test cases - test counts will be wrong if running against stale compiled output (1)
- Never create "documentation tests" that just `assert.ok(true)` — if mocking limitations prevent testing, either test a different layer that IS mockable, or skip the test entirely with a clear explanation (1)
- When stubbing vscode APIs in tests via wrapper modules (e.g., `workspaceApis`), the production code must also use those wrappers — sinon cannot stub properties directly on the vscode namespace like `workspace.workspaceFolders`, so both production and test code must reference the same stubbable wrapper functions (3)
- When stubbing vscode APIs in tests via wrapper modules (e.g., `workspaceApis`), the production code must also use those wrappers — sinon cannot stub properties directly on the vscode namespace like `workspace.workspaceFolders`, so both production and test code must reference the same stubbable wrapper functions (4)
- **Before writing tests**, check if the function under test calls VS Code APIs directly (e.g., `commands.executeCommand`, `window.createTreeView`, `workspace.getConfiguration`). If so, FIRST update the production code to use wrapper functions from `src/common/*.apis.ts` (create the wrapper if it doesn't exist), THEN write tests that stub those wrappers. This prevents CI failures where sinon cannot stub the vscode namespace (4)
15 changes: 15 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,12 @@
"category": "Python Envs",
"icon": "$(folder-opened)"
},
{
"command": "python-envs.revealEnvInManagerView",
"title": "%python-envs.revealEnvInManagerView.title%",
"category": "Python Envs",
"icon": "$(eye)"
},
{
"command": "python-envs.runPetInTerminal",
"title": "%python-envs.runPetInTerminal.title%",
Expand Down Expand Up @@ -423,6 +429,10 @@
"command": "python-envs.revealProjectInExplorer",
"when": "false"
},
{
"command": "python-envs.revealEnvInManagerView",
"when": "false"
},
{
"command": "python-envs.createNewProjectFromTemplate",
"when": "config.python.useEnvironmentsExtension != false"
Expand Down Expand Up @@ -531,6 +541,11 @@
"command": "python-envs.uninstallPackage",
"group": "inline",
"when": "view == python-projects && viewItem == python-package"
},
{
"command": "python-envs.revealEnvInManagerView",
"group": "inline",
"when": "view == python-projects && viewItem == python-env"
}
],
"view/title": [
Expand Down
1 change: 1 addition & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"python-envs.terminal.deactivate.title": "Deactivate Environment in Current Terminal",
"python-envs.uninstallPackage.title": "Uninstall Package",
"python-envs.revealProjectInExplorer.title": "Reveal Project in Explorer",
"python-envs.revealEnvInManagerView.title": "Reveal in Environment Managers View",
"python-envs.runPetInTerminal.title": "Run Python Environment Tool (PET) in Terminal...",
"python-envs.alwaysUseUv.description": "When set to true, uv will be used to manage all virtual environments if available. When set to false, uv will only manage virtual environments explicitly created by uv."
}
6 changes: 6 additions & 0 deletions src/common/window.apis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import {
TerminalShellExecutionStartEvent,
TerminalShellIntegrationChangeEvent,
TextEditor,
TreeView,
TreeViewOptions,
Uri,
window,
WindowState,
Expand Down Expand Up @@ -377,3 +379,7 @@ export function onDidChangeWindowState(
): Disposable {
return window.onDidChangeWindowState(listener, thisArgs, disposables);
}

export function createTreeView<T>(viewId: string, options: TreeViewOptions<T>): TreeView<T> {
return window.createTreeView(viewId, options);
}
4 changes: 4 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
refreshPackagesCommand,
removeEnvironmentCommand,
removePythonProject,
revealEnvInManagerView,
revealProjectInExplorer,
runAsTaskCommand,
runInDedicatedTerminalCommand,
Expand Down Expand Up @@ -312,6 +313,9 @@ export async function activate(context: ExtensionContext): Promise<PythonEnviron
commands.registerCommand('python-envs.revealProjectInExplorer', async (item) => {
await revealProjectInExplorer(item);
}),
commands.registerCommand('python-envs.revealEnvInManagerView', async (item) => {
await revealEnvInManagerView(item, managerView);
}),
commands.registerCommand('python-envs.terminal.activate', async () => {
const terminal = activeTerminal();
if (terminal) {
Expand Down
30 changes: 18 additions & 12 deletions src/features/envCommands.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,6 @@
import * as fs from 'fs-extra';
import * as path from 'path';
import {
commands,
ProgressLocation,
QuickInputButtons,
TaskExecution,
TaskRevealKind,
Terminal,
Uri,
workspace,
} from 'vscode';
import { ProgressLocation, QuickInputButtons, TaskExecution, TaskRevealKind, Terminal, Uri, workspace } from 'vscode';
import {
CreateEnvironmentOptions,
PythonEnvironment,
Expand All @@ -28,6 +19,7 @@ import {
} from '../internal.api';
import { removePythonProjectSetting, setEnvironmentManager, setPackageManager } from './settings/settingHelpers';

import { executeCommand } from '../common/command.api';
import { clipboardWriteText } from '../common/env.apis';
import {} from '../common/errors/utils';
import { Pickers } from '../common/localize';
Expand All @@ -52,6 +44,7 @@ import {
import { runAsTask } from './execution/runAsTask';
import { runInTerminal } from './terminal/runInTerminal';
import { TerminalManager } from './terminal/terminalManager';
import { EnvManagerView } from './views/envManagersView';
import {
EnvManagerTreeItem,
EnvTreeItemKind,
Expand Down Expand Up @@ -469,7 +462,7 @@ export async function addPythonProjectCommand(
'Open Folder',
);
if (r === 'Open Folder') {
await commands.executeCommand('vscode.openFolder');
await executeCommand('vscode.openFolder');
return;
}
}
Expand Down Expand Up @@ -746,8 +739,21 @@ export async function copyPathToClipboard(item: unknown): Promise<void> {
export async function revealProjectInExplorer(item: unknown): Promise<void> {
if (item instanceof ProjectItem) {
const projectUri = item.project.uri;
await commands.executeCommand('revealInExplorer', projectUri);
await executeCommand('revealInExplorer', projectUri);
} else {
traceVerbose(`Invalid context for reveal project in explorer: ${item}`);
}
}

/**
* Focuses the Environment Managers view and reveals the given project environment.
*/
export async function revealEnvInManagerView(item: unknown, managerView: EnvManagerView): Promise<void> {
if (item instanceof ProjectEnvironment) {
await executeCommand('env-managers.focus');
await managerView.reveal(item.environment);
return;
}

traceVerbose(`Invalid context for reveal environment in manager view: ${item}`);
}
63 changes: 54 additions & 9 deletions src/features/views/envManagersView.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Disposable, Event, EventEmitter, ProviderResult, TreeDataProvider, TreeItem, TreeView, window } from 'vscode';
import { Disposable, Event, EventEmitter, ProviderResult, TreeDataProvider, TreeItem, TreeView } from 'vscode';
import { DidChangeEnvironmentEventArgs, EnvironmentGroupInfo, PythonEnvironment } from '../../api';
import { ProjectViews } from '../../common/localize';
import { createSimpleDebounce } from '../../common/utils/debounce';
import { createTreeView } from '../../common/window.apis';
import {
DidChangeEnvironmentManagerEventArgs,
DidChangePackageManagerEventArgs,
Expand Down Expand Up @@ -34,18 +35,23 @@ export class EnvManagerView implements TreeDataProvider<EnvTreeItem>, Disposable
>();
private revealMap = new Map<string, PythonEnvTreeItem>();
private managerViews = new Map<string, EnvManagerTreeItem>();
private groupViews = new Map<string, PythonGroupEnvTreeItem>();
private selected: Map<string, string> = new Map();
private disposables: Disposable[] = [];

public constructor(public providers: EnvironmentManagers, private stateManager: ITemporaryStateManager) {
this.treeView = window.createTreeView<EnvTreeItem>('env-managers', {
public constructor(
public providers: EnvironmentManagers,
private stateManager: ITemporaryStateManager,
) {
this.treeView = createTreeView<EnvTreeItem>('env-managers', {
treeDataProvider: this,
});

this.disposables.push(
new Disposable(() => {
this.revealMap.clear();
this.managerViews.clear();
this.groupViews.clear();
this.selected.clear();
}),
this.treeView,
Expand Down Expand Up @@ -107,6 +113,7 @@ export class EnvManagerView implements TreeDataProvider<EnvTreeItem>, Disposable
if (!element) {
const views: EnvTreeItem[] = [];
this.managerViews.clear();
this.groupViews.clear();
this.providers.managers.forEach((m) => {
const view = new EnvManagerTreeItem(m);
views.push(view);
Expand Down Expand Up @@ -137,7 +144,10 @@ export class EnvManagerView implements TreeDataProvider<EnvTreeItem>, Disposable
});

groupObjects.forEach((group) => {
views.push(new PythonGroupEnvTreeItem(element as EnvManagerTreeItem, group));
const groupView = new PythonGroupEnvTreeItem(element as EnvManagerTreeItem, group);
const groupName = typeof group === 'string' ? group : group.name;
this.groupViews.set(`${manager.id}:${groupName}`, groupView);
views.push(groupView);
});

if (views.length === 0) {
Expand Down Expand Up @@ -202,12 +212,47 @@ export class EnvManagerView implements TreeDataProvider<EnvTreeItem>, Disposable
return element.parent;
}

reveal(environment?: PythonEnvironment) {
const view = environment ? this.revealMap.get(environment.envId.id) : undefined;
/**
* Reveals and focuses on the given environment in the Environment Managers view.
*
* @param environment - The Python environment to reveal
*/
async reveal(environment?: PythonEnvironment): Promise<void> {
if (!environment) {
return;
}

const manager = this.providers.getEnvironmentManager(environment);
if (!manager) {
return;
}

if (!this.managerViews.has(manager.id)) {
await this.getChildren(undefined);
}

const managerView = this.managerViews.get(manager.id);
if (!managerView) {
return;
}

const groupName = typeof environment.group === 'string' ? environment.group : environment.group?.name;
if (groupName) {
if (!this.groupViews.has(`${manager.id}:${groupName}`)) {
await this.getChildren(managerView);
}

const groupView = this.groupViews.get(`${manager.id}:${groupName}`);
if (groupView) {
await this.getChildren(groupView);
}
} else {
await this.getChildren(managerView);
}

const view = this.revealMap.get(environment.envId.id);
if (view && this.treeView.visible) {
setImmediate(async () => {
await this.treeView.reveal(view);
});
await this.treeView.reveal(view, { expand: false, focus: true, select: true });
}
}

Expand Down
51 changes: 50 additions & 1 deletion src/test/features/envCommands.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ import * as sinon from 'sinon';
import * as typeMoq from 'typemoq';
import { Uri } from 'vscode';
import { PythonEnvironment, PythonProject } from '../../api';
import * as commandApi from '../../common/command.api';
import * as managerApi from '../../common/pickers/managers';
import * as projectApi from '../../common/pickers/projects';
import { createAnyEnvironmentCommand } from '../../features/envCommands';
import { createAnyEnvironmentCommand, revealEnvInManagerView } from '../../features/envCommands';
import { EnvManagerView } from '../../features/views/envManagersView';
import { ProjectEnvironment, ProjectItem } from '../../features/views/treeViewItems';
import { EnvironmentManagers, InternalEnvironmentManager, PythonProjectManager } from '../../internal.api';
import { setupNonThenable } from '../mocks/helper';

Expand Down Expand Up @@ -175,3 +178,49 @@ suite('Create Any Environment Command Tests', () => {
em.verifyAll();
});
});

suite('Reveal Env In Manager View Command Tests', () => {
let managerView: typeMoq.IMock<EnvManagerView>;
let executeCommandStub: sinon.SinonStub;

setup(() => {
managerView = typeMoq.Mock.ofType<EnvManagerView>();
setupNonThenable(managerView);
executeCommandStub = sinon.stub(commandApi, 'executeCommand');
});

teardown(() => {
sinon.restore();
});

test('Focuses env-managers view and reveals environment when given a ProjectEnvironment', async () => {
// Mock
const project: PythonProject = {
uri: Uri.file('/test/project'),
name: 'test-project',
};
const projectItem = new ProjectItem(project);

const environment: PythonEnvironment = {
envId: { id: 'test-env-id', managerId: 'test-manager' },
name: 'test-env',
displayName: 'Test Environment',
displayPath: '/path/to/env',
version: '3.10.0',
environmentPath: Uri.file('/path/to/env'),
execInfo: { run: { executable: '/path/to/python' }, activatedRun: { executable: '/path/to/python' } },
sysPrefix: '/path/to/env',
};
const projectEnv = new ProjectEnvironment(projectItem, environment);

executeCommandStub.resolves();
managerView.setup((m) => m.reveal(environment)).returns(() => Promise.resolve());

// Run
await revealEnvInManagerView(projectEnv, managerView.object);

// Assert
assert.ok(executeCommandStub.calledOnceWith('env-managers.focus'), 'Should focus the env-managers view');
managerView.verify((m) => m.reveal(environment), typeMoq.Times.once());
});
});
Loading