Skip to content
Closed
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
25 changes: 21 additions & 4 deletions .github/instructions/testing-workflow.instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,9 +235,25 @@ interface FunctionAnalysis {
import * as sinon from 'sinon';
import * as workspaceApis from '../../common/workspace.apis'; // Wrapper functions

// Stub wrapper functions, not VS Code APIs directly
// Always mock wrapper functions (e.g., workspaceApis.getConfiguration()) instead of
// VS Code APIs directly to avoid stubbing issues
// ❌ WRONG - stubbing raw VS Code modules causes errors
import { commands } from 'vscode';
const mockExecuteCommand = sinon.stub(commands, 'executeCommand').resolves();
// Error: TypeError: Cannot stub non-existent property executeCommand

// ✅ CORRECT - stub the wrapper function from common API layer
import * as commandApi from '../../common/command.api';
const mockExecuteCommand = sinon.stub(commandApi, 'executeCommand').resolves();

// CRITICAL: Always check the implementation's imports first
// If the code uses wrapper functions like these, stub the wrapper:
// - commandApi.executeCommand() → stub commandApi.executeCommand
// - workspaceApis.getConfiguration() → stub workspaceApis.getConfiguration
// - windowApis.showInformationMessage() → stub windowApis.showInformationMessage
// - workspaceApis.getWorkspaceFolder() → stub workspaceApis.getWorkspaceFolder
//
// Why? Raw VS Code modules aren't exported in the test environment, causing
// "Cannot stub non-existent property" errors when trying to stub them directly.

const mockGetConfiguration = sinon.stub(workspaceApis, 'getConfiguration');
```

Expand Down Expand Up @@ -574,6 +590,7 @@ envConfig.inspect
- Untestable Node.js APIs → Create proxy abstraction functions (use function overloads to preserve intelligent typing while making functions mockable)

## 🧠 Agent Learnings

- Avoid testing exact error messages or log output - assert only that errors are thrown or rejection occurs to prevent brittle tests (1)
- Create shared mock helpers (e.g., `createMockLogOutputChannel()`) instead of duplicating mock setup across multiple test files (1)

- When stubbing VS Code API functions in unit tests, always check the implementation imports first - if the code uses wrapper functions (like `commandApi.executeCommand()`, `workspaceApis.getConfiguration()`, `windowApis.showInformationMessage()`), stub the wrapper function instead of the raw VS Code module. Stubbing raw VS Code modules (e.g., `sinon.stub(commands, 'executeCommand')`) causes "Cannot stub non-existent property" errors because those modules aren't exported in the test environment (2)
2 changes: 2 additions & 0 deletions src/common/localize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ export namespace Common {
export const ok = l10n.t('Ok');
export const quickCreate = l10n.t('Quick Create');
export const installPython = l10n.t('Install Python');
export const dontShowAgain = l10n.t("Don't Show Again");
export const openSettings = l10n.t('Open Settings');
}

export namespace WorkbenchStrings {
Expand Down
42 changes: 38 additions & 4 deletions src/features/terminal/terminalEnvVarInjector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ import {
Disposable,
EnvironmentVariableScope,
GlobalEnvironmentVariableCollection,
window,
workspace,
WorkspaceFolder,
} from 'vscode';
import { executeCommand } from '../../common/command.api';
import { Common } from '../../common/localize';
import { traceError, traceVerbose } from '../../common/logging';
import { getGlobalPersistentState } from '../../common/persistentState';
import { resolveVariables } from '../../common/utils/internalVariables';
import * as windowApis from '../../common/window.apis';
import { getConfiguration, getWorkspaceFolder } from '../../common/workspace.apis';
import { EnvVarManager } from '../execution/envVariableManager';

Expand All @@ -22,6 +25,7 @@ import { EnvVarManager } from '../execution/envVariableManager';
*/
export class TerminalEnvVarInjector implements Disposable {
private disposables: Disposable[] = [];
private static readonly DONT_SHOW_ENV_FILE_NOTIFICATION_KEY = 'dontShowEnvFileNotification';

constructor(
private readonly envVarCollection: GlobalEnvironmentVariableCollection,
Expand Down Expand Up @@ -63,9 +67,9 @@ export class TerminalEnvVarInjector implements Disposable {

// Only show notification when env vars change and we have an env file but injection is disabled
if (!useEnvFile && envFilePath) {
window.showInformationMessage(
'An environment file is configured but terminal environment injection is disabled. Enable "python.terminal.useEnvFile" to use environment variables from .env files in terminals.',
);
this.showEnvFileNotification().catch((error) => {
traceError('Failed to show environment file notification:', error);
});
}

if (args.changeType === 2) {
Expand Down Expand Up @@ -184,6 +188,36 @@ export class TerminalEnvVarInjector implements Disposable {
}
}

/**
* Show notification about environment file configuration with "Don't Show Again" option.
*/
private async showEnvFileNotification(): Promise<void> {
const state = await getGlobalPersistentState();
const dontShowAgain = await state.get<boolean>(
TerminalEnvVarInjector.DONT_SHOW_ENV_FILE_NOTIFICATION_KEY,
false,
);

if (dontShowAgain) {
traceVerbose('TerminalEnvVarInjector: Env file notification suppressed by user preference');
return;
}

const result = await windowApis.showInformationMessage(
'An environment file is configured but terminal environment injection is disabled. Enable "python.terminal.useEnvFile" to use environment variables from .env files in terminals.',
Common.openSettings,
Common.dontShowAgain,
);

if (result === Common.openSettings) {
await executeCommand('workbench.action.openSettings', 'python.terminal.useEnvFile');
traceVerbose('TerminalEnvVarInjector: User opened settings for useEnvFile');
} else if (result === Common.dontShowAgain) {
await state.set(TerminalEnvVarInjector.DONT_SHOW_ENV_FILE_NOTIFICATION_KEY, true);
traceVerbose('TerminalEnvVarInjector: User chose to not show env file notification again');
}
}

/**
* Dispose of the injector and clean up resources.
*/
Expand Down
12 changes: 11 additions & 1 deletion src/managers/common/nativePythonFinder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,14 +162,24 @@ class NativePythonFinderImpl implements NativePythonFinder {
traceVerbose('Finder - from cache environments', key);
}
const result = await this.pool.addToQueue(options);
// Validate result from worker pool
if (!result || !Array.isArray(result)) {
this.outputChannel.warn(`[pet] Worker pool returned invalid result type: ${typeof result}`);
return [];
}
this.cache.set(key, result);
return result;
}

private async handleSoftRefresh(options?: NativePythonEnvironmentKind | Uri[]): Promise<NativeInfo[]> {
const key = this.getKey(options);
const cacheResult = this.cache.get(key);
if (!cacheResult) {
// Validate cache integrity - if cached value is not a valid array, do a hard refresh
if (!cacheResult || !Array.isArray(cacheResult)) {
if (cacheResult !== undefined) {
this.outputChannel.warn(`[pet] Cache contained invalid data type: ${typeof cacheResult}`);
this.cache.delete(key);
}
return this.handleHardRefresh(options);
}

Expand Down
98 changes: 83 additions & 15 deletions src/managers/conda/condaUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,10 +256,38 @@ export async function runCondaExecutable(
return await _runConda(conda, args, log, token);
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function getCondaInfo(): Promise<any> {
interface CondaInfo {
envs_dirs: string[];
}

/**
* Runs `conda info --envs --json` and parses the result.
* Validates the JSON response structure at the parsing boundary.
* @returns Validated CondaInfo object
* @throws Error if conda command fails or returns invalid JSON structure
*/
async function getCondaInfo(): Promise<CondaInfo> {
const raw = await runConda(['info', '--envs', '--json']);
return JSON.parse(raw);
const parsed = JSON.parse(raw);

// Validate at the JSON→TypeScript boundary
if (!parsed || typeof parsed !== 'object') {
traceWarn(`conda info returned invalid data: ${typeof parsed}`);
throw new Error(`conda info returned invalid data type: ${typeof parsed}`);
}

const envsDirs = parsed['envs_dirs'];
if (envsDirs === undefined || envsDirs === null) {
traceWarn('conda info envs_dirs is undefined/null');
return { envs_dirs: [] };
}
if (!Array.isArray(envsDirs)) {
traceWarn(`conda info envs_dirs is not an array (type: ${typeof envsDirs})`);
return { envs_dirs: [] };
}

traceVerbose(`conda info returned ${envsDirs.length} environment directories`);
return { envs_dirs: envsDirs };
}

let prefixes: string[] | undefined;
Expand All @@ -269,17 +297,15 @@ export async function getPrefixes(): Promise<string[]> {
}

const state = await getWorkspacePersistentState();
prefixes = await state.get<string[]>(CONDA_PREFIXES_KEY);
if (prefixes) {
const storedPrefixes = await state.get<string[]>(CONDA_PREFIXES_KEY);
if (storedPrefixes && Array.isArray(storedPrefixes)) {
prefixes = storedPrefixes;
return prefixes;
}

try {
const data = await getCondaInfo();
prefixes = Array.isArray(data['envs_dirs']) ? (data['envs_dirs'] as string[]) : [];
if (prefixes.length === 0) {
traceWarn('Conda info returned no environment directories (envs_dirs)');
}
prefixes = data.envs_dirs;
await state.set(CONDA_PREFIXES_KEY, prefixes);
} catch (error) {
traceError('Failed to get conda environment prefixes', error);
Expand Down Expand Up @@ -624,6 +650,11 @@ async function nativeToPythonEnv(
conda: string,
condaPrefixes: string[],
): Promise<PythonEnvironment | undefined> {
// Defensive check: Validate NativeEnvInfo object
if (!e) {
traceWarn('nativeToPythonEnv received null/undefined NativeEnvInfo');
return undefined;
}
if (!(e.prefix && e.executable && e.version)) {
let name = e.name;
const environment = api.createPythonEnvironmentItem(
Expand Down Expand Up @@ -687,20 +718,45 @@ export async function refreshCondaEnvs(
log: LogOutputChannel,
manager: EnvironmentManager,
): Promise<PythonEnvironment[]> {
log.info('Refreshing conda environments');
const data = await nativeFinder.refresh(hardRefresh);
log.info(`Refreshing conda environments (hardRefresh=${hardRefresh})`);

let data: (NativeEnvInfo | NativeEnvManagerInfo)[];
try {
data = await nativeFinder.refresh(hardRefresh);
} catch (error) {
traceError('Failed to refresh native finder for conda environments', error);
log.error(`Failed to refresh native finder: ${error instanceof Error ? error.message : String(error)}`);
return [];
}

// Ensure data is a valid array before proceeding
if (!data || !Array.isArray(data)) {
traceWarn(`Native finder returned invalid data: ${typeof data}, expected array`);
log.warn(`Native finder returned invalid data type: ${typeof data}`);
return [];
}

traceVerbose(`Native finder returned ${data.length} items for conda refresh`);

let conda: string | undefined = undefined;
try {
conda = await getConda();
} catch {
} catch (error) {
traceVerbose(`getConda() failed, will try to find conda from native data: ${error}`);
conda = undefined;
}
if (conda === undefined) {
const managers = data
.filter((e) => !isNativeEnvInfo(e))
.map((e) => e as NativeEnvManagerInfo)
.filter((e) => e.tool.toLowerCase() === 'conda');

if (managers.length === 0) {
traceWarn('No conda manager found in native finder data');
log.warn('No conda manager found in native finder data');
return [];
}

conda = managers[0].executable;
await setConda(conda);
}
Expand All @@ -717,9 +773,21 @@ export async function refreshCondaEnvs(

await Promise.all(
envs.map(async (e) => {
const environment = await nativeToPythonEnv(e, api, manager, log, condaPath, condaPrefixes);
if (environment) {
collection.push(environment);
try {
const environment = await nativeToPythonEnv(e, api, manager, log, condaPath, condaPrefixes);
if (environment) {
collection.push(environment);
}
} catch (error) {
traceError(
`Failed to convert native env to Python environment: ${e.prefix ?? e.executable}`,
error,
);
log.error(
`Failed to process conda environment ${e.prefix ?? e.executable}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}),
);
Expand Down
Loading
Loading