Skip to content
Open
Show file tree
Hide file tree
Changes from 6 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
13 changes: 10 additions & 3 deletions src/extension/common/utils/localize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,17 @@ export namespace DebugConfigStrings {
label: l10n.t('FastAPI'),
description: l10n.t('Launch and debug a FastAPI web application'),
};
export const enterAppPathOrNamePath = {
export const snippetFile = {
name: l10n.t('Python Debugger: FastAPI File'),
};
export const selectConfigurationWithFile = {
label: l10n.t('FastAPI File'),
description: l10n.t('Launch and debug a FastAPI web application using the current file'),
};
export const enterAppPath = {
title: l10n.t('Debug FastAPI'),
prompt: l10n.t("Enter the path to the application, e.g. 'main.py' or 'main'"),
invalid: l10n.t('Enter a valid name'),
prompt: l10n.t('Enter the path to your FastAPI app (e.g. main.py or backend/app/main.py).'),
invalid: l10n.t('Enter a valid path'),
};
}
export namespace flask {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import { IMultiStepInputFactory, InputStep, IQuickPickParameters, MultiStepInput
import { AttachRequestArguments, DebugConfigurationArguments, LaunchRequestArguments } from '../../types';
import { DebugConfigurationState, DebugConfigurationType, IDebugConfigurationService } from '../types';
import { buildDjangoLaunchDebugConfiguration } from './providers/djangoLaunch';
import { buildFastAPILaunchDebugConfiguration } from './providers/fastapiLaunch';
import {
buildFastAPILaunchDebugConfiguration,
buildFastAPIWithFileLaunchDebugConfiguration,
} from './providers/fastapiLaunch';
import { buildFileLaunchDebugConfiguration } from './providers/fileLaunch';
import { buildFlaskLaunchDebugConfiguration } from './providers/flaskLaunch';
import { buildModuleLaunchConfiguration } from './providers/moduleLaunch';
Expand Down Expand Up @@ -158,6 +161,11 @@ export class PythonDebugConfigurationService implements IDebugConfigurationServi
type: DebugConfigurationType.launchFastAPI,
description: DebugConfigStrings.fastapi.selectConfiguration.description,
},
{
label: DebugConfigStrings.fastapi.selectConfigurationWithFile.label,
type: DebugConfigurationType.launchFastAPIWithFile,
description: DebugConfigStrings.fastapi.selectConfigurationWithFile.description,
},
{
label: DebugConfigStrings.flask.selectConfiguration.label,
type: DebugConfigurationType.launchFlask,
Expand All @@ -178,6 +186,10 @@ export class PythonDebugConfigurationService implements IDebugConfigurationServi
>();
debugConfigurations.set(DebugConfigurationType.launchDjango, buildDjangoLaunchDebugConfiguration);
debugConfigurations.set(DebugConfigurationType.launchFastAPI, buildFastAPILaunchDebugConfiguration);
debugConfigurations.set(
DebugConfigurationType.launchFastAPIWithFile,
buildFastAPIWithFileLaunchDebugConfiguration,
);
debugConfigurations.set(DebugConfigurationType.launchFile, buildFileLaunchDebugConfiguration);
debugConfigurations.set(DebugConfigurationType.launchFileWithArgs, buildFileWithArgsLaunchDebugConfiguration);
debugConfigurations.set(DebugConfigurationType.launchFlask, buildFlaskLaunchDebugConfiguration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import * as path from 'path';
import { CancellationToken, DebugConfiguration, WorkspaceFolder } from 'vscode';
import { IDynamicDebugConfigurationService } from '../types';
import { DebuggerTypeName } from '../../constants';
import { replaceAll } from '../../common/stringUtils';
import { getDjangoPaths, getFastApiPaths, getFlaskPaths } from './utils/configuration';
import { getDjangoPaths, getFastApiPaths, getFlaskPaths, tryResolveFastApiArgs } from './utils/configuration';
import { sendTelemetryEvent } from '../../telemetry';
import { EventName } from '../../telemetry/constants';

Expand Down Expand Up @@ -63,15 +62,22 @@ export class DynamicPythonDebugConfigurationService implements IDynamicDebugConf
}

const fastApiPaths = await getFastApiPaths(folder);
Comment thread
savannahostrowski marked this conversation as resolved.
let fastApiPath = fastApiPaths?.length ? fastApiPaths[0].fsPath : null;
if (fastApiPath) {
fastApiPath = replaceAll(path.relative(folder.uri.fsPath, fastApiPath), path.sep, '.').replace('.py', '');
if (fastApiPaths?.length) {
const fastApiArgs = tryResolveFastApiArgs(folder, fastApiPaths) ?? ['run'];
providers.push({
name: 'Python Debugger: FastAPI',
type: DebuggerTypeName,
request: 'launch',
module: 'uvicorn',
args: [`${fastApiPath}:app`, '--reload'],
module: 'fastapi',
args: fastApiArgs,
jinja: true,
});
providers.push({
name: 'Python Debugger: FastAPI File',
type: DebuggerTypeName,
request: 'launch',
module: 'fastapi',
args: ['run', '${file}'],
jinja: true,
});
}
Expand Down
89 changes: 51 additions & 38 deletions src/extension/debugger/configuration/providers/fastapiLaunch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,65 +4,78 @@
'use strict';

import * as path from 'path';
import * as fs from 'fs-extra';
import { WorkspaceFolder } from 'vscode';
import { MultiStepInput } from '../../../common/multiStepInput';
import { DebugConfigStrings } from '../../../common/utils/localize';
import { sendTelemetryEvent } from '../../../telemetry';
import { EventName } from '../../../telemetry/constants';
import { DebuggerTypeName } from '../../../constants';
import { LaunchRequestArguments } from '../../../types';
import { DebugConfigurationState, DebugConfigurationType } from '../../types';
import { getFastApiPaths, tryResolveFastApiArgs } from '../utils/configuration';

async function promptForAppPath(
input: MultiStepInput<DebugConfigurationState>,
value?: string,
): Promise<string | undefined> {
const entered = await input.showInputBox({
title: DebugConfigStrings.fastapi.enterAppPath.title,
prompt: DebugConfigStrings.fastapi.enterAppPath.prompt,
value: value ?? '',
validate: (v) =>
Promise.resolve(v && v.trim().length > 0 ? undefined : DebugConfigStrings.fastapi.enterAppPath.invalid),
});
return entered?.trim();
}

export async function buildFastAPILaunchDebugConfiguration(
input: MultiStepInput<DebugConfigurationState>,
state: DebugConfigurationState,
): Promise<void> {
const application = await getApplicationPath(state.folder);
let manuallyEnteredAValue: boolean | undefined;
const fastApiPaths = await getFastApiPaths(state.folder);
const autoArgs = state.folder ? tryResolveFastApiArgs(state.folder, fastApiPaths) : undefined;

let args: string[];
if (autoArgs) {
args = autoArgs;
} else {
const workspaceRoot = state.folder?.uri.fsPath;
const prefill =
workspaceRoot && fastApiPaths.length > 0 ? path.relative(workspaceRoot, fastApiPaths[0].fsPath) : undefined;
const entered = await promptForAppPath(input, prefill);
if (!entered) {
return;
}
args = ['run', entered];
}

const config: Partial<LaunchRequestArguments> = {
Comment thread
savannahostrowski marked this conversation as resolved.
name: DebugConfigStrings.fastapi.snippet.name,
type: DebuggerTypeName,
request: 'launch',
module: 'uvicorn',
args: ['main:app', '--reload'],
module: 'fastapi',
args,
jinja: true,
};

if (!application) {
Comment thread
savannahostrowski marked this conversation as resolved.
const selectedPath = await input.showInputBox({
title: DebugConfigStrings.fastapi.enterAppPathOrNamePath.title,
value: 'main.py',
prompt: DebugConfigStrings.fastapi.enterAppPathOrNamePath.prompt,
validate: (value) =>
Promise.resolve(
value && value.trim().length > 0
? undefined
: DebugConfigStrings.fastapi.enterAppPathOrNamePath.invalid,
),
});
if (selectedPath) {
manuallyEnteredAValue = true;
config.args = [`${path.basename(selectedPath, '.py').replace('/', '.')}:app`, '--reload'];
} else {
return;
}
}

sendTelemetryEvent(EventName.DEBUGGER_CONFIGURATION_PROMPTS, undefined, {
configurationType: DebugConfigurationType.launchFastAPI,
autoDetectedFastAPIMainPyPath: !!application,
manuallyEnteredAValue,
});
Object.assign(state.config, config);
}
export async function getApplicationPath(folder: WorkspaceFolder | undefined): Promise<string | undefined> {
if (!folder) {
return undefined;
}
const defaultLocationOfManagePy = path.join(folder.uri.fsPath, 'main.py');
if (await fs.pathExists(defaultLocationOfManagePy)) {
return 'main.py';
}
return undefined;

export async function buildFastAPIWithFileLaunchDebugConfiguration(
_input: MultiStepInput<DebugConfigurationState>,
state: DebugConfigurationState,
): Promise<void> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot generated:
The Architect notes the ['run', '${file}'] config literal now lives in two places (here and dynamicdebugConfigurationService.ts), and the ['run'] default is encoded both in tryResolveFastApiArgs and as ?? ['run'] in the dynamic caller. Hoist to a shared constant / small helper to prevent drift. Low priority.

[verified]

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried this but extracting ['run', '${file}'] into a readonly string[] constant required spreading at every call site ([...FASTAPI_RUN_FILE_ARGS]), which was longer than the inline literal.

const config: Partial<LaunchRequestArguments> = {
name: DebugConfigStrings.fastapi.snippetFile.name,
type: DebuggerTypeName,
request: 'launch',
module: 'fastapi',
args: ['run', '${file}'],
jinja: true,
};
sendTelemetryEvent(EventName.DEBUGGER_CONFIGURATION_PROMPTS, undefined, {
configurationType: DebugConfigurationType.launchFastAPIWithFile,
});
Object.assign(state.config, config);
}
9 changes: 9 additions & 0 deletions src/extension/debugger/configuration/utils/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
'use strict';

import * as fs from 'fs-extra';
import * as path from 'path';
import { MultiStepInput } from '../../../common/multiStepInput';
import { sendTelemetryEvent } from '../../../telemetry';
import { EventName } from '../../../telemetry/constants';
Expand Down Expand Up @@ -81,6 +82,14 @@ export async function getFastApiPaths(folder: WorkspaceFolder | undefined) {
return fastApiPaths;
}

export function tryResolveFastApiArgs(folder: WorkspaceFolder, paths: Uri[]): string[] | undefined {
Comment thread
savannahostrowski marked this conversation as resolved.
Outdated
Comment thread
savannahostrowski marked this conversation as resolved.
Outdated
Comment thread
savannahostrowski marked this conversation as resolved.
Outdated
if (paths.length !== 1) {
return undefined;
}
const relative = path.relative(folder.uri.fsPath, paths[0].fsPath);
return relative.includes(path.sep) ? ['run', relative] : ['run'];
}

export async function getFlaskPaths(folder: WorkspaceFolder | undefined) {
if (!folder) {
return [];
Expand Down
1 change: 1 addition & 0 deletions src/extension/debugger/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export enum DebugConfigurationType {
remoteAttach = 'remoteAttach',
launchDjango = 'launchDjango',
launchFastAPI = 'launchFastAPI',
launchFastAPIWithFile = 'launchFastAPIWithFile',
launchFlask = 'launchFlask',
launchModule = 'launchModule',
launchPyramid = 'launchPyramid',
Expand Down
110 changes: 93 additions & 17 deletions src/test/unittest/configuration/providers/fastapiLaunch.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,57 +5,133 @@

import { expect } from 'chai';
import * as path from 'path';
import * as fs from 'fs-extra';
import * as sinon from 'sinon';
import { anything, instance, mock, when } from 'ts-mockito';
import { Uri } from 'vscode';
import { DebugConfigStrings } from '../../../../extension/common/utils/localize';
import { DebuggerTypeName } from '../../../../extension/constants';
import * as fastApiLaunch from '../../../../extension/debugger/configuration/providers/fastapiLaunch';
import * as configurationUtils from '../../../../extension/debugger/configuration/utils/configuration';
import { DebugConfigurationState } from '../../../../extension/debugger/types';
import { MultiStepInput } from '../../../../extension/common/multiStepInput';

suite('Debugging - Configuration Provider FastAPI', () => {
let input: MultiStepInput<DebugConfigurationState>;
let pathExistsStub: sinon.SinonStub;
let getFastApiPathsStub: sinon.SinonStub;

setup(() => {
input = mock<MultiStepInput<DebugConfigurationState>>(MultiStepInput);
pathExistsStub = sinon.stub(fs, 'pathExists');
getFastApiPathsStub = sinon.stub(configurationUtils, 'getFastApiPaths');
});

teardown(() => {
sinon.restore();
});
test("getApplicationPath should return undefined if file doesn't exist", async () => {

test('Single match at workspace root → plain `fastapi run`', async () => {
const folder = { uri: Uri.parse(path.join('one', 'two')), name: '1', index: 0 };
const appPyPath = path.join(folder.uri.fsPath, 'main.py');
pathExistsStub.withArgs(appPyPath).resolves(false);
const file = await fastApiLaunch.getApplicationPath(folder);
const state = { config: {}, folder };
Comment thread
savannahostrowski marked this conversation as resolved.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot generated:
The Skeptic notes the nested-match expectations use path.join('backend','app','main.py'), which produces the resolver's own OS-specific output on every platform — the separator assertion is tautological and will never catch the portability bug above. Once the persisted arg is normalized to POSIX, assert the literal 'backend/app/main.py' instead.

[verified]

getFastApiPathsStub.resolves([Uri.parse(path.join('one', 'two', 'main.py'))]);

await fastApiLaunch.buildFastAPILaunchDebugConfiguration(instance(input), state);

expect(file).to.be.equal(undefined, 'Should return undefined');
const config = {
name: DebugConfigStrings.fastapi.snippet.name,
type: DebuggerTypeName,
request: 'launch',
module: 'fastapi',
args: ['run'],
jinja: true,
};

expect(state.config).to.be.deep.equal(config);
});
test('getApplicationPath should find path', async () => {

test('Single match in subdirectory → passes path explicitly', async () => {
const folder = { uri: Uri.parse(path.join('one', 'two')), name: '1', index: 0 };
const appPyPath = path.join(folder.uri.fsPath, 'main.py');
pathExistsStub.withArgs(appPyPath).resolves(true);
const file = await fastApiLaunch.getApplicationPath(folder);
const state = { config: {}, folder };
getFastApiPathsStub.resolves([Uri.parse(path.join('one', 'two', 'backend', 'app', 'main.py'))]);

expect(file).to.be.equal('main.py');
await fastApiLaunch.buildFastAPILaunchDebugConfiguration(instance(input), state);

const config = {
name: DebugConfigStrings.fastapi.snippet.name,
type: DebuggerTypeName,
request: 'launch',
module: 'fastapi',
args: ['run', path.join('backend', 'app', 'main.py')],
jinja: true,
};

expect(state.config).to.be.deep.equal(config);
});
test('Launch JSON with selected app path', async () => {

test('No matches → prompts the user and uses the entered path', async () => {
const folder = { uri: Uri.parse(path.join('one', 'two')), name: '1', index: 0 };
const state = { config: {}, folder };
getFastApiPathsStub.resolves([]);
when(input.showInputBox(anything())).thenResolve('custom/main.py');

await fastApiLaunch.buildFastAPILaunchDebugConfiguration(instance(input), state);

const config = {
name: DebugConfigStrings.fastapi.snippet.name,
type: DebuggerTypeName,
request: 'launch',
module: 'fastapi',
args: ['run', 'custom/main.py'],
jinja: true,
};

when(input.showInputBox(anything())).thenResolve('main');
expect(state.config).to.be.deep.equal(config);
});

test('Multiple matches → prompts the user and uses the entered path', async () => {
const folder = { uri: Uri.parse(path.join('one', 'two')), name: '1', index: 0 };
const state = { config: {}, folder };
getFastApiPathsStub.resolves([
Uri.parse(path.join('one', 'two', 'svc-a', 'main.py')),
Uri.parse(path.join('one', 'two', 'svc-b', 'main.py')),
]);
when(input.showInputBox(anything())).thenResolve(path.join('svc-a', 'main.py'));

await fastApiLaunch.buildFastAPILaunchDebugConfiguration(instance(input), state);

const config = {
name: DebugConfigStrings.fastapi.snippet.name,
type: DebuggerTypeName,
request: 'launch',
module: 'uvicorn',
args: ['main:app', '--reload'],
module: 'fastapi',
args: ['run', path.join('svc-a', 'main.py')],
jinja: true,
};

expect(state.config).to.be.deep.equal(config);
});

test('User cancels prompt → config is not populated', async () => {
const folder = { uri: Uri.parse(path.join('one', 'two')), name: '1', index: 0 };
const state = { config: {}, folder };
getFastApiPathsStub.resolves([]);
when(input.showInputBox(anything())).thenResolve(undefined);

await fastApiLaunch.buildFastAPILaunchDebugConfiguration(instance(input), state);

expect(state.config).to.be.deep.equal({});
});

test('Launch JSON with file configuration', async () => {
const folder = { uri: Uri.parse(path.join('one', 'two')), name: '1', index: 0 };
const state = { config: {}, folder };

await fastApiLaunch.buildFastAPIWithFileLaunchDebugConfiguration(instance(input), state);

const config = {
name: DebugConfigStrings.fastapi.snippetFile.name,
type: DebuggerTypeName,
request: 'launch',
module: 'fastapi',
args: ['run', '${file}'],
jinja: true,
};

Expand Down
Loading