diff --git a/.github/assign-reviewers/dev-requirements.txt b/.github/assign-reviewers/dev-requirements.txt index 32236b7dcaee..ffda51f2e406 100644 --- a/.github/assign-reviewers/dev-requirements.txt +++ b/.github/assign-reviewers/dev-requirements.txt @@ -21,7 +21,7 @@ certifi==2020.11.8 # via # -r requirements.txt # httpx -cffi==1.14.4 +cffi==1.15.0 # via # -r requirements.txt # cryptography diff --git a/.github/assign-reviewers/requirements.txt b/.github/assign-reviewers/requirements.txt index 89778f0dcdea..d3f5653a2bff 100644 --- a/.github/assign-reviewers/requirements.txt +++ b/.github/assign-reviewers/requirements.txt @@ -18,7 +18,7 @@ certifi==2020.11.8 \ --hash=sha256:1f422849db327d534e3d0c5f02a263458c3955ec0aae4ff09b95f195c59f4edd \ --hash=sha256:f05def092c44fbf25834a51509ef6e631dc19765ab8a57b4e7ab85531f0a9cf4 # via httpx -cffi==1.14.4 \ +cffi==1.15.0 \ --hash=sha256:00a1ba5e2e95684448de9b89888ccd02c98d512064b4cb987d48f4b40aa0421e \ --hash=sha256:00e28066507bfc3fe865a31f325c8391a1ac2916219340f87dfad602c3e48e5d \ --hash=sha256:045d792900a75e8b1e1b0ab6787dd733a8190ffcf80e8c8ceb2fb10a29ff238a \ diff --git a/.github/workflows/pr-file-check.yml b/.github/workflows/pr-file-check.yml deleted file mode 100644 index fe538bb683a0..000000000000 --- a/.github/workflows/pr-file-check.yml +++ /dev/null @@ -1,50 +0,0 @@ -name: PR files -on: - pull_request: - types: - # On by default if you specify no types. - - 'opened' - - 'reopened' - - 'synchronize' - # For `skip-label` only. - - 'labeled' - - 'unlabeled' - -jobs: - changed-files-in-pr: - name: 'Check for changed files' - runs-on: ubuntu-latest - steps: - - name: 'News entry' - uses: brettcannon/check-for-changed-files@v1.1.0 - with: - file-pattern: 'news/*/*.md' - skip-label: 'skip news' - failure-message: 'News entry file missing; see news/README.md for instructions (the ${skip-label} label can be used to pass this check)' - - - name: 'package-lock.json matches package.json' - uses: brettcannon/check-for-changed-files@v1.1.0 - with: - prereq-pattern: 'package.json' - file-pattern: 'package-lock.json' - skip-label: 'skip package*.json' - failure-message: '${prereq-pattern} was edited but ${file-pattern} was not (the ${skip-label} label can be used to pass this check)' - - - name: 'package.json matches package-lock.json' - uses: brettcannon/check-for-changed-files@v1.1.0 - with: - prereq-pattern: 'package-lock.json' - file-pattern: 'package.json' - skip-label: 'skip package*.json' - failure-message: '${prereq-pattern} was edited but ${file-pattern} was not (the ${skip-label} label can be used to pass this check)' - - - name: 'Tests' - uses: brettcannon/check-for-changed-files@v1.1.0 - with: - prereq-pattern: src/**/*.ts - file-pattern: | - src/**/*.test.ts - src/**/*.testvirtualenvs.ts - .github/test_plan.md - skip-label: 'skip tests' - failure-message: 'TypeScript code was edited without also editing a ${file-pattern} file; see the Testing page in our wiki on testing guidelines (the ${skip-label} label can be used to pass this check)' diff --git a/.gitignore b/.gitignore index eb8b02d00b17..3d7af4082c84 100644 --- a/.gitignore +++ b/.gitignore @@ -22,7 +22,9 @@ cucumber-report.json **/.venv*/ port.txt precommit.hook -pythonFiles/lib/** +pythonFiles/lib/python/bin +pythonFiles/lib/python/isort +pythonFiles/lib/python/isort-5.10.0.dist-info debug_coverage*/** languageServer/** languageServer.*/** diff --git a/news/2 Fixes/18372.md b/news/2 Fixes/18372.md new file mode 100644 index 000000000000..cae18e9b1ffb --- /dev/null +++ b/news/2 Fixes/18372.md @@ -0,0 +1 @@ +Created requirements.txt to stop Python github Action Errors (Thanks [Harry-Hopkinson](https://github.com/Harry-Hopkinson)) diff --git a/news/3 Code Health/18345.md b/news/3 Code Health/18345.md new file mode 100644 index 000000000000..cd6622f77ff4 --- /dev/null +++ b/news/3 Code Health/18345.md @@ -0,0 +1 @@ +Fixed typescript and namespace errors. (Thanks [Harry-Hopkinson](https://github.com/Harry-Hopkinson)) diff --git a/package-lock.json b/package-lock.json index 0fd7473ef5db..213794718491 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,6 +24,7 @@ "minimatch": "^3.0.4", "named-js-regexp": "^1.3.3", "node-stream-zip": "^1.6.0", + "react": "^17.0.2", "reflect-metadata": "^0.1.12", "request": "^2.87.0", "request-progress": "^3.0.0", @@ -9412,8 +9413,7 @@ "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "node_modules/js-yaml": { "version": "3.13.1", @@ -9932,7 +9932,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", - "dev": true, "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, @@ -11478,7 +11477,6 @@ "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -12763,6 +12761,18 @@ "node": ">=0.10.0" } }, + "node_modules/react": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react/-/react-17.0.2.tgz", + "integrity": "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA==", + "dependencies": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/react-is": { "version": "16.13.1", "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", @@ -24547,8 +24557,7 @@ "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "js-yaml": { "version": "3.13.1", @@ -24980,7 +24989,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", - "dev": true, "requires": { "js-tokens": "^3.0.0 || ^4.0.0" } @@ -26216,8 +26224,7 @@ "object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", - "dev": true + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" }, "object-copy": { "version": "0.1.0", @@ -27221,6 +27228,15 @@ } } }, + "react": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react/-/react-17.0.2.tgz", + "integrity": "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA==", + "requires": { + "loose-envify": "^1.1.0", + "object-assign": "^4.1.1" + } + }, "react-is": { "version": "16.13.1", "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", diff --git a/package.json b/package.json index 781a4e6ff514..ab94aa72354a 100644 --- a/package.json +++ b/package.json @@ -1957,6 +1957,7 @@ "minimatch": "^3.0.4", "named-js-regexp": "^1.3.3", "node-stream-zip": "^1.6.0", + "react": "^17.0.2", "reflect-metadata": "^0.1.12", "request": "^2.87.0", "request-progress": "^3.0.0", diff --git a/pythonFiles/lib/python/requirements.txt b/pythonFiles/lib/python/requirements.txt new file mode 100644 index 000000000000..678af042c08e --- /dev/null +++ b/pythonFiles/lib/python/requirements.txt @@ -0,0 +1,10 @@ +# +# This file is autogenerated by pip-compile with python 3.7 +# To update, run: +# +# pip-compile --generate-hashes requirements.in +# +isort==5.10.0 \ + --hash=sha256:1a18ccace2ed8910bd9458b74a3ecbafd7b2f581301b0ab65cfdd4338272d76f \ + --hash=sha256:e52ff6d38012b131628cf0f26c51e7bd3a7c81592eefe3ac71411e692f1b9345 + # via -r requirements.in diff --git a/src/client/activation/activationService.ts b/src/client/activation/activationService.ts index 02ed57689cde..e29a3537571b 100644 --- a/src/client/activation/activationService.ts +++ b/src/client/activation/activationService.ts @@ -60,7 +60,8 @@ function logStartup(serverType: LanguageServerType): void { @injectable() export class LanguageServerExtensionActivationService - implements IExtensionActivationService, ILanguageServerCache, Disposable { + implements IExtensionActivationService, ILanguageServerCache, Disposable +{ private cache = new Map>(); private activatedServer?: IActivatedServer; diff --git a/src/client/activation/jedi/languageClientFactory.ts b/src/client/activation/jedi/languageClientFactory.ts index 82616ca36f15..857859948ae4 100644 --- a/src/client/activation/jedi/languageClientFactory.ts +++ b/src/client/activation/jedi/languageClientFactory.ts @@ -31,7 +31,9 @@ export class JediLanguageClientFactory implements ILanguageClientFactory { }; // eslint-disable-next-line global-require - const vscodeLanguageClient = require('vscode-languageclient/node') as typeof import('vscode-languageclient/node'); // NOSONAR + const vscodeLanguageClient = + // eslint-disable-next-line global-require + require('vscode-languageclient/node') as typeof import('vscode-languageclient/node'); // NOSONAR return new vscodeLanguageClient.LanguageClient( PYTHON_LANGUAGE, languageClientName, diff --git a/src/client/activation/node/languageClientFactory.ts b/src/client/activation/node/languageClientFactory.ts index 0c1534dd5619..d29cab46b3d2 100644 --- a/src/client/activation/node/languageClientFactory.ts +++ b/src/client/activation/node/languageClientFactory.ts @@ -28,8 +28,9 @@ export class NodeLanguageClientFactory implements ILanguageClientFactory { clientOptions: LanguageClientOptions, ): Promise { // this must exist for node language client - const commandArgs = (clientOptions.connectionOptions - ?.cancellationStrategy as FileBasedCancellationStrategy).getCommandLineArguments(); + const commandArgs = ( + clientOptions.connectionOptions?.cancellationStrategy as FileBasedCancellationStrategy + ).getCommandLineArguments(); const folderName = await this.languageServerFolderService.getLanguageServerFolderName(resource); const languageServerFolder = path.isAbsolute(folderName) diff --git a/src/client/apiTypes.ts b/src/client/apiTypes.ts index e01e70243998..da33c43b2a16 100644 --- a/src/client/apiTypes.ts +++ b/src/client/apiTypes.ts @@ -55,9 +55,7 @@ export interface IExtensionApi { * * If no folder is present, it returns the global setting. * @returns {({ execCommand: string[] | undefined })} */ - getExecutionDetails( - resource?: Resource, - ): { + getExecutionDetails(resource?: Resource): { /** * E.g of execution commands returned could be, * * `['']` diff --git a/src/client/application/diagnostics/checks/invalidPythonPathInDebugger.ts b/src/client/application/diagnostics/checks/invalidPythonPathInDebugger.ts index 61460f9db701..a0ac193ecd57 100644 --- a/src/client/application/diagnostics/checks/invalidPythonPathInDebugger.ts +++ b/src/client/application/diagnostics/checks/invalidPythonPathInDebugger.ts @@ -45,8 +45,10 @@ class InvalidPythonPathInDebuggerDiagnostic extends BaseDiagnostic { export const InvalidPythonPathInDebuggerServiceId = 'InvalidPythonPathInDebuggerServiceId'; @injectable() -export class InvalidPythonPathInDebuggerService extends BaseDiagnosticsService - implements IInvalidPythonPathInDebuggerService { +export class InvalidPythonPathInDebuggerService + extends BaseDiagnosticsService + implements IInvalidPythonPathInDebuggerService +{ constructor( @inject(IServiceContainer) serviceContainer: IServiceContainer, @inject(IWorkspaceService) private readonly workspace: IWorkspaceService, diff --git a/src/client/browser/extension.ts b/src/client/browser/extension.ts index 88891aebd4a6..0f0a11d8f641 100644 --- a/src/client/browser/extension.ts +++ b/src/client/browser/extension.ts @@ -83,7 +83,7 @@ async function runPylance( const languageClient = new LanguageClient('python', 'Python Language Server', clientOptions, worker); - languageClient.onDidChangeState((e) => { + languageClient.onDidChangeState((e): void => { // The client's on* methods must be called after the client has started, but if called too // late the server may have already sent a message (which leads to failures). Register // these on the state change to running to ensure they are ready soon enough. @@ -97,20 +97,27 @@ async function runPylance( ), ); - languageClient.onTelemetry((telemetryEvent) => { - const eventName = telemetryEvent.EventName || EventName.LANGUAGE_SERVER_TELEMETRY; - const formattedProperties = { - ...telemetryEvent.Properties, - // Replace all slashes in the method name so it doesn't get scrubbed by vscode-extension-telemetry. - method: telemetryEvent.Properties.method?.replace(/\//g, '.'), - }; - sendTelemetryEventBrowser( - eventName, - telemetryEvent.Measurements, - formattedProperties, - telemetryEvent.Exception, - ); - }); + languageClient.onTelemetry( + (telemetryEvent: { + EventName: EventName; + Properties: { method: string }; + Measurements: number | Record | undefined; + Exception: Error | undefined; + }) => { + const eventName = telemetryEvent.EventName || EventName.LANGUAGE_SERVER_TELEMETRY; + const formattedProperties = { + ...telemetryEvent.Properties, + // Replace all slashes in the method name so it doesn't get scrubbed by vscode-extension-telemetry. + method: telemetryEvent.Properties.method?.replace(/\//g, '.'), + }; + sendTelemetryEventBrowser( + eventName, + telemetryEvent.Measurements, + formattedProperties, + telemetryEvent.Exception, + ); + }, + ); }); const disposable = languageClient.start(); diff --git a/src/client/browser/intellisenseStatus.ts b/src/client/browser/intellisenseStatus.ts index 8e199aea49ca..89258dedac9b 100644 --- a/src/client/browser/intellisenseStatus.ts +++ b/src/client/browser/intellisenseStatus.ts @@ -22,5 +22,5 @@ export function createStatusItem(): vscode.Disposable { return statusItem; } // eslint-disable-next-line @typescript-eslint/no-empty-function - return { dispose: () => {} }; + return { dispose: () => undefined }; } diff --git a/src/client/common/application/commandManager.ts b/src/client/common/application/commandManager.ts index 9e1f34a5885b..9e377dc0629c 100644 --- a/src/client/common/application/commandManager.ts +++ b/src/client/common/application/commandManager.ts @@ -23,7 +23,7 @@ export class CommandManager implements ICommandManager { // eslint-disable-next-line class-methods-use-this public registerCommand< E extends keyof ICommandNameArgumentTypeMapping, - U extends ICommandNameArgumentTypeMapping[E] + U extends ICommandNameArgumentTypeMapping[E], // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any >(command: E, callback: (...args: U) => any, thisArg?: any): Disposable { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -73,7 +73,7 @@ export class CommandManager implements ICommandManager { public executeCommand< T, E extends keyof ICommandNameArgumentTypeMapping, - U extends ICommandNameArgumentTypeMapping[E] + U extends ICommandNameArgumentTypeMapping[E], >(command: E, ...rest: U): Thenable { return commands.executeCommand(command, ...rest); } diff --git a/src/client/common/application/commands/reportIssueCommand.ts b/src/client/common/application/commands/reportIssueCommand.ts index 18c95f669d78..5cca6f505e60 100644 --- a/src/client/common/application/commands/reportIssueCommand.ts +++ b/src/client/common/application/commands/reportIssueCommand.ts @@ -49,7 +49,7 @@ export class ReportIssueCommandHandler implements IExtensionSingleActivationServ if (argSetting) { if (typeof argSetting === 'object') { userSettings = userSettings.concat(os.EOL, property, os.EOL); - const argSettingsDict = (settings[property] as unknown) as Record; + const argSettingsDict = settings[property] as unknown as Record; if (typeof argSettingsDict === 'object') { Object.keys(argSetting).forEach((item) => { const prop = argSetting[item]; diff --git a/src/client/common/net/httpClient.ts b/src/client/common/net/httpClient.ts index 8aac63d17142..57620a93863f 100644 --- a/src/client/common/net/httpClient.ts +++ b/src/client/common/net/httpClient.ts @@ -20,7 +20,7 @@ export class HttpClient implements IHttpClient { } public async downloadFile(uri: string): Promise { - const request = ((await import('request')) as any) as typeof requestTypes; + const request = (await import('request')) as any as typeof requestTypes; return request(uri, this.requestOptions); } diff --git a/src/client/common/process/currentProcess.ts b/src/client/common/process/currentProcess.ts index b80c32e97b7c..4d549630279f 100644 --- a/src/client/common/process/currentProcess.ts +++ b/src/client/common/process/currentProcess.ts @@ -13,7 +13,7 @@ export class CurrentProcess implements ICurrentProcess { return process as any; }; public get env(): EnvironmentVariables { - return (process.env as any) as EnvironmentVariables; + return process.env as any as EnvironmentVariables; } public get argv(): string[] { return process.argv; diff --git a/src/client/common/terminal/environmentActivationProviders/baseActivationProvider.ts b/src/client/common/terminal/environmentActivationProviders/baseActivationProvider.ts index b764819d9de8..9b4dd0a07f2f 100644 --- a/src/client/common/terminal/environmentActivationProviders/baseActivationProvider.ts +++ b/src/client/common/terminal/environmentActivationProviders/baseActivationProvider.ts @@ -52,8 +52,9 @@ abstract class BaseActivationCommandProvider implements ITerminalActivationComma resource: Uri | undefined, targetShell: TerminalShellType, ): Promise { - const pythonPath = this.serviceContainer.get(IConfigurationService).getSettings(resource) - .pythonPath; + const pythonPath = this.serviceContainer + .get(IConfigurationService) + .getSettings(resource).pythonPath; return this.getActivationCommandsForInterpreter(pythonPath, targetShell); } public abstract getActivationCommandsForInterpreter( diff --git a/src/client/common/terminal/environmentActivationProviders/bash.ts b/src/client/common/terminal/environmentActivationProviders/bash.ts index 83a4c9bc353c..075329575dda 100644 --- a/src/client/common/terminal/environmentActivationProviders/bash.ts +++ b/src/client/common/terminal/environmentActivationProviders/bash.ts @@ -7,7 +7,7 @@ import { TerminalShellType } from '../types'; import { ActivationScripts, VenvBaseActivationCommandProvider } from './baseActivationProvider'; // For a given shell the scripts are in order of precedence. -const SCRIPTS: ActivationScripts = ({ +const SCRIPTS: ActivationScripts = { // Group 1 [TerminalShellType.wsl]: ['activate.sh', 'activate'], [TerminalShellType.ksh]: ['activate.sh', 'activate'], @@ -19,7 +19,7 @@ const SCRIPTS: ActivationScripts = ({ [TerminalShellType.cshell]: ['activate.csh'], // Group 3 [TerminalShellType.fish]: ['activate.fish'], -} as unknown) as ActivationScripts; +} as unknown as ActivationScripts; export function getAllScripts(): string[] { const scripts: string[] = []; diff --git a/src/client/common/terminal/environmentActivationProviders/commandPrompt.ts b/src/client/common/terminal/environmentActivationProviders/commandPrompt.ts index b5695524a5ae..66defb3b1515 100644 --- a/src/client/common/terminal/environmentActivationProviders/commandPrompt.ts +++ b/src/client/common/terminal/environmentActivationProviders/commandPrompt.ts @@ -9,13 +9,13 @@ import { TerminalShellType } from '../types'; import { ActivationScripts, VenvBaseActivationCommandProvider } from './baseActivationProvider'; // For a given shell the scripts are in order of precedence. -const SCRIPTS: ActivationScripts = ({ +const SCRIPTS: ActivationScripts = { // Group 1 [TerminalShellType.commandPrompt]: ['activate.bat', 'Activate.ps1'], // Group 2 [TerminalShellType.powershell]: ['Activate.ps1', 'activate.bat'], [TerminalShellType.powershellCore]: ['Activate.ps1', 'activate.bat'], -} as unknown) as ActivationScripts; +} as unknown as ActivationScripts; export function getAllScripts(pathJoin: (...p: string[]) => string): string[] { const scripts: string[] = []; @@ -40,7 +40,7 @@ export class CommandPromptAndPowerShell extends VenvBaseActivationCommandProvide protected readonly scripts: ActivationScripts; constructor(@inject(IServiceContainer) serviceContainer: IServiceContainer) { super(serviceContainer); - this.scripts = ({} as unknown) as ActivationScripts; + this.scripts = {} as unknown as ActivationScripts; for (const key of Object.keys(SCRIPTS)) { const shell = key as TerminalShellType; const scripts: string[] = []; diff --git a/src/client/common/utils/async.ts b/src/client/common/utils/async.ts index 76f15ec511c4..dcd8fb439424 100644 --- a/src/client/common/utils/async.ts +++ b/src/client/common/utils/async.ts @@ -107,9 +107,9 @@ export interface IAsyncIterableIterator extends IAsyncIterator, AsyncItera * An iterator that yields nothing. */ export function iterEmpty(): IAsyncIterableIterator { - return ((async function* () { + return (async function* () { /** No body. */ - })() as unknown) as IAsyncIterableIterator; + })() as unknown as IAsyncIterableIterator; } type NextResult = { index: number } & ( diff --git a/src/client/common/utils/enum.ts b/src/client/common/utils/enum.ts index 78104b48846f..1717ea51f5ba 100644 --- a/src/client/common/utils/enum.ts +++ b/src/client/common/utils/enum.ts @@ -12,7 +12,7 @@ function getNames(e: any) { } export function getValues(e: any) { - return (getObjValues(e).filter((v) => typeof v === 'number') as any) as T[]; + return getObjValues(e).filter((v) => typeof v === 'number') as any as T[]; } function getObjValues(e: any): (number | string)[] { diff --git a/src/client/common/utils/platform.ts b/src/client/common/utils/platform.ts index cf3b28e5cc35..67a5cbbe899a 100644 --- a/src/client/common/utils/platform.ts +++ b/src/client/common/utils/platform.ts @@ -53,7 +53,7 @@ export function getArchitecture(): Architecture { * Look up the requested env var value (or undefined` if not set). */ export function getEnvironmentVariable(key: string): string | undefined { - return ((process.env as any) as EnvironmentVariables)[key]; + return (process.env as any as EnvironmentVariables)[key]; } /** diff --git a/src/client/common/utils/version.ts b/src/client/common/utils/version.ts index 4ef9c3b3d92c..c6a569637de7 100644 --- a/src/client/common/utils/version.ts +++ b/src/client/common/utils/version.ts @@ -85,7 +85,7 @@ function copyStrict(info: T): RawBasicVersionInfo { micro: info.micro, }; - const { unnormalized } = (info as unknown) as RawBasicVersionInfo; + const { unnormalized } = info as unknown as RawBasicVersionInfo; if (unnormalized !== undefined) { copied.unnormalized = { major: unnormalized.major, @@ -139,7 +139,7 @@ function validateVersionPart(prop: string, part: number, unnormalized?: ErrorMsg * is responsible for any other properties beyond that. */ function validateBasicVersionInfo(info: T): void { - const raw = (info as unknown) as RawBasicVersionInfo; + const raw = info as unknown as RawBasicVersionInfo; validateVersionPart('major', info.major, raw.unnormalized?.major); validateVersionPart('minor', info.minor, raw.unnormalized?.minor); validateVersionPart('micro', info.micro, raw.unnormalized?.micro); @@ -229,7 +229,7 @@ export function parseBasicVersionInfo(verStr: string const micro = microStr ? parseInt(microStr, 10) : -1; return { // This is effectively normalized. - version: ({ major, minor, micro } as unknown) as T, + version: { major, minor, micro } as unknown as T, before: before || '', after: after || '', }; @@ -393,10 +393,10 @@ export function areSimilarVersions { - ((this as any) as Record)[`env:${key}`] = ((this as any) as Record< - string, - string | undefined - >)[`env.${key}`] = process.env[key]; + (this as any as Record)[`env:${key}`] = ( + this as any as Record + )[`env.${key}`] = process.env[key]; }); } diff --git a/src/client/debugger/extension/configuration/resolvers/base.ts b/src/client/debugger/extension/configuration/resolvers/base.ts index e64ee25c3eee..571e860d64b7 100644 --- a/src/client/debugger/extension/configuration/resolvers/base.ts +++ b/src/client/debugger/extension/configuration/resolvers/base.ts @@ -20,7 +20,8 @@ import { IDebugConfigurationResolver } from '../types'; @injectable() export abstract class BaseConfigurationResolver - implements IDebugConfigurationResolver { + implements IDebugConfigurationResolver +{ protected pythonPathSource: PythonPathSource = PythonPathSource.launchJson; constructor( diff --git a/src/client/extension.ts b/src/client/extension.ts index d5bc7374b8a0..5abdcb29d5bc 100644 --- a/src/client/extension.ts +++ b/src/client/extension.ts @@ -29,7 +29,6 @@ initializeFileLogging(logDispose); // loading starts here import { ProgressLocation, ProgressOptions, window } from 'vscode'; - import { buildApi } from './api'; import { IApplicationShell, IWorkspaceService } from './common/application/types'; import { IAsyncDisposableRegistry, IDisposableRegistry, IExperimentService, IExtensionContext } from './common/types'; @@ -187,12 +186,12 @@ interface IAppShell { function notifyUser(msg: string) { try { - let appShell: IAppShell = (window as any) as IAppShell; + let appShell: IAppShell = window as any as IAppShell; if (activatedServiceContainer) { - appShell = (activatedServiceContainer.get(IApplicationShell) as any) as IAppShell; + appShell = activatedServiceContainer.get(IApplicationShell) as any as IAppShell; } appShell.showErrorMessage(msg).ignoreErrors(); } catch (ex) { - traceError('failed to notify user', ex); + traceError('Failed to Notify User', ex); } } diff --git a/src/client/formatters/baseFormatter.ts b/src/client/formatters/baseFormatter.ts index b91a6ac85def..5e0a478ca506 100644 --- a/src/client/formatters/baseFormatter.ts +++ b/src/client/formatters/baseFormatter.ts @@ -67,9 +67,8 @@ export abstract class BaseFormatter { const executionInfo = this.helper.getExecutionInfo(this.product, args, document.uri); executionInfo.args.push(tempFile); - const pythonToolsExecutionService = this.serviceContainer.get( - IPythonToolExecutionService, - ); + const pythonToolsExecutionService = + this.serviceContainer.get(IPythonToolExecutionService); const promise = pythonToolsExecutionService .exec(executionInfo, { cwd, throwOnStdErr: false, token }, document.uri) .then((output) => output.stdout) diff --git a/src/client/interpreter/autoSelection/index.ts b/src/client/interpreter/autoSelection/index.ts index 3117ad1826fb..f0f54badc1f7 100644 --- a/src/client/interpreter/autoSelection/index.ts +++ b/src/client/interpreter/autoSelection/index.ts @@ -29,12 +29,11 @@ export class InterpreterAutoSelectionService implements IInterpreterAutoSelectio private readonly autoSelectedInterpreterByWorkspace = new Map(); - private globallyPreferredInterpreter: IPersistentState< - PythonEnvironment | undefined - > = this.stateFactory.createGlobalPersistentState( - preferredGlobalInterpreter, - undefined, - ); + private globallyPreferredInterpreter: IPersistentState = + this.stateFactory.createGlobalPersistentState( + preferredGlobalInterpreter, + undefined, + ); constructor( @inject(IWorkspaceService) private readonly workspaceService: IWorkspaceService, diff --git a/src/client/interpreter/configuration/interpreterSelector/commands/base.ts b/src/client/interpreter/configuration/interpreterSelector/commands/base.ts index e549745ff58f..3351268a8ef5 100644 --- a/src/client/interpreter/configuration/interpreterSelector/commands/base.ts +++ b/src/client/interpreter/configuration/interpreterSelector/commands/base.ts @@ -35,9 +35,7 @@ export abstract class BaseInterpreterSelectorCommand implements IExtensionSingle public abstract activate(): Promise; - protected async getConfigTargets(options?: { - resetTarget?: boolean; - }): Promise< + protected async getConfigTargets(options?: { resetTarget?: boolean }): Promise< | { folderUri: Resource; configTarget: ConfigurationTarget; diff --git a/src/client/interpreter/display/shebangCodeLensProvider.ts b/src/client/interpreter/display/shebangCodeLensProvider.ts index a426a80a1a41..6b9a97616bd7 100644 --- a/src/client/interpreter/display/shebangCodeLensProvider.ts +++ b/src/client/interpreter/display/shebangCodeLensProvider.ts @@ -16,7 +16,7 @@ export class ShebangCodeLensProvider implements IShebangCodeLensProvider { @inject(IPlatformService) private readonly platformService: IPlatformService, @inject(IWorkspaceService) workspaceService: IWorkspaceService, ) { - this.onDidChangeCodeLenses = (workspaceService.onDidChangeConfiguration as any) as Event; + this.onDidChangeCodeLenses = workspaceService.onDidChangeConfiguration as any as Event; } public async detectShebang( document: TextDocument, diff --git a/src/client/interpreter/helpers.ts b/src/client/interpreter/helpers.ts index e54ae902dea7..b1705de103ab 100644 --- a/src/client/interpreter/helpers.ts +++ b/src/client/interpreter/helpers.ts @@ -4,6 +4,7 @@ import { IDocumentManager, IWorkspaceService } from '../common/application/types import { FileSystemPaths } from '../common/platform/fs-paths'; import { Resource } from '../common/types'; import { IServiceContainer } from '../ioc/types'; +import { PythonEnvSource } from '../pythonEnvironments/base/info'; import { compareSemVerLikeVersions } from '../pythonEnvironments/base/info/pythonVersion'; import { EnvironmentType, getEnvironmentTypeName, PythonEnvironment } from '../pythonEnvironments/info'; import { IComponentAdapter, IInterpreterHelper, WorkspacePythonPath } from './contracts'; @@ -66,6 +67,22 @@ export class InterpreterHelper implements IInterpreterHelper { return this.pyenvs.getInterpreterInformation(pythonPath); } + public async getInterpreters({ resource, source }: { resource?: Uri; source?: PythonEnvSource[] } = {}): Promise< + PythonEnvironment[] + > { + const interpreters = await this.pyenvs.getInterpreters(resource, source); + return sortInterpreters(interpreters); + } + + public async getInterpreterPath(pythonPath: string): Promise { + const interpreterInfo: any = await this.getInterpreterInformation(pythonPath); + if (interpreterInfo) { + return interpreterInfo.path; + } else { + return pythonPath; + } + } + public async isMacDefaultPythonPath(pythonPath: string): Promise { return this.pyenvs.isMacDefaultPythonPath(pythonPath); } diff --git a/src/client/interpreter/interpreterService.ts b/src/client/interpreter/interpreterService.ts index 46d542929012..f157bb10f35a 100644 --- a/src/client/interpreter/interpreterService.ts +++ b/src/client/interpreter/interpreterService.ts @@ -107,7 +107,7 @@ export class InterpreterService implements Disposable, IInterpreterService { interpreterDisplay.registerVisibilityFilter(filter); } disposables.push( - this.onDidChangeInterpreters((e) => { + this.onDidChangeInterpreters((e): void => { const interpreter = e.old ?? e.new; if (interpreter) { this.didChangeInterpreterInformation.fire(interpreter); @@ -119,7 +119,7 @@ export class InterpreterService implements Disposable, IInterpreterService { // To handle scenario when language mode is set to "python" filter.interpreterVisibilityEmitter.fire(); }), - documentManager.onDidChangeActiveTextEditor((e) => { + documentManager.onDidChangeActiveTextEditor((e): void => { filter.interpreterVisibilityEmitter.fire(); if (e && e.document) { this.refresh(e.document.uri); @@ -129,7 +129,7 @@ export class InterpreterService implements Disposable, IInterpreterService { const pySettings = this.configService.getSettings(); this._pythonPathSetting = pySettings.pythonPath; disposables.push( - this.interpreterPathService.onDidChange((i) => { + this.interpreterPathService.onDidChange((i): void => { this._onConfigChanged(i.uri); }), ); diff --git a/src/client/linters/baseLinter.ts b/src/client/linters/baseLinter.ts index d8147089392d..39d034ac6053 100644 --- a/src/client/linters/baseLinter.ts +++ b/src/client/linters/baseLinter.ts @@ -142,7 +142,7 @@ export abstract class BaseLinter implements ILinter { return LintMessageSeverity.Warning; default: { if (LintMessageSeverity[severityName]) { - return (LintMessageSeverity[severityName] as unknown) as LintMessageSeverity; + return LintMessageSeverity[severityName] as unknown as LintMessageSeverity; } } } @@ -161,9 +161,8 @@ export abstract class BaseLinter implements ILinter { } const executionInfo = this.info.getExecutionInfo(args, document.uri); const cwd = this.getWorkingDirectoryPath(document); - const pythonToolsExecutionService = this.serviceContainer.get( - IPythonToolExecutionService, - ); + const pythonToolsExecutionService = + this.serviceContainer.get(IPythonToolExecutionService); try { const result = await pythonToolsExecutionService.exec( executionInfo, diff --git a/src/client/logging/index.ts b/src/client/logging/index.ts index b28cadc74682..c39e4a5affd9 100644 --- a/src/client/logging/index.ts +++ b/src/client/logging/index.ts @@ -149,7 +149,7 @@ function tracing(log: (t: TraceInfo) => void, run: () => T): T { // If method being wrapped returns a promise then wait for it. if (isPromise(result)) { - ((result as unknown) as Promise) + (result as unknown as Promise) .then((data) => { log({ elapsed: timer.elapsedTime, returnValue: data }); return data; @@ -214,7 +214,7 @@ function logResult(logInfo: LogInfo, traced: TraceInfo, call?: CallInfo) { } } else { logTo(LogLevel.Error, [formatted, traced.err]); - sendTelemetryEvent(('ERROR' as unknown) as EventName, undefined, undefined, traced.err); + sendTelemetryEvent('ERROR' as unknown as EventName, undefined, undefined, traced.err); } } diff --git a/src/client/providers/formatProvider.ts b/src/client/providers/formatProvider.ts index 1ea239c03bec..3ef79f51e6c8 100644 --- a/src/client/providers/formatProvider.ts +++ b/src/client/providers/formatProvider.ts @@ -14,7 +14,8 @@ import { DummyFormatter } from '../formatters/dummyFormatter'; import { YapfFormatter } from '../formatters/yapfFormatter'; export class PythonFormattingEditProvider - implements vscode.DocumentFormattingEditProvider, vscode.DocumentRangeFormattingEditProvider, vscode.Disposable { + implements vscode.DocumentFormattingEditProvider, vscode.DocumentRangeFormattingEditProvider, vscode.Disposable +{ private readonly config: IConfigurationService; private readonly workspace: IWorkspaceService; diff --git a/src/client/pythonEnvironments/base/info/pythonVersion.ts b/src/client/pythonEnvironments/base/info/pythonVersion.ts index 589bf4c7b7af..8fca961862bf 100644 --- a/src/client/pythonEnvironments/base/info/pythonVersion.ts +++ b/src/client/pythonEnvironments/base/info/pythonVersion.ts @@ -235,9 +235,7 @@ function compareVersionRelease(left: PythonVersion, right: PythonVersion): [numb * Remarks: primarily used to convert to old type of environment info. * @deprecated */ -export function toSemverLikeVersion( - version: PythonVersion, -): { +export function toSemverLikeVersion(version: PythonVersion): { raw: string; major: number; minor: number; diff --git a/src/client/pythonEnvironments/base/locator.ts b/src/client/pythonEnvironments/base/locator.ts index a2f635925e4e..c71e7e5d555e 100644 --- a/src/client/pythonEnvironments/base/locator.ts +++ b/src/client/pythonEnvironments/base/locator.ts @@ -211,7 +211,8 @@ interface IEmitter { * `BasicPythonEnvsChangedEvent`. */ abstract class LocatorBase - implements ILocator { + implements ILocator +{ public readonly onChanged: Event; protected readonly emitter: IEmitter; diff --git a/src/client/pythonEnvironments/base/locators/composite/envsCollectionCache.ts b/src/client/pythonEnvironments/base/locators/composite/envsCollectionCache.ts index ae107b76d375..05e35daab694 100644 --- a/src/client/pythonEnvironments/base/locators/composite/envsCollectionCache.ts +++ b/src/client/pythonEnvironments/base/locators/composite/envsCollectionCache.ts @@ -68,8 +68,10 @@ interface IPersistentStorage { /** * Environment info cache using persistent storage to save and retrieve pre-cached env info. */ -export class PythonEnvInfoCache extends PythonEnvsWatcher - implements IEnvsCollectionCache { +export class PythonEnvInfoCache + extends PythonEnvsWatcher + implements IEnvsCollectionCache +{ private envs: PythonEnvCompleteInfo[] = []; constructor(private readonly persistentStorage: IPersistentStorage) { diff --git a/src/client/telemetry/importTracker.ts b/src/client/telemetry/importTracker.ts index 39f278bef9bb..61c59d6455a8 100644 --- a/src/client/telemetry/importTracker.ts +++ b/src/client/telemetry/importTracker.ts @@ -38,7 +38,8 @@ Things we are ignoring the following for simplicity/performance: - Non-standard whitespace separators within the import statement (i.e. more than a single space, tabs) */ -const ImportRegEx = /^\s*(from (?\w+)(?:\.\w+)* import \w+(?:, \w+)*(?: as \w+)?|import (?\w+(?:, \w+)*)(?: as \w+)?)$/; +const ImportRegEx = + /^\s*(from (?\w+)(?:\.\w+)* import \w+(?:, \w+)*(?: as \w+)?|import (?\w+(?:, \w+)*)(?: as \w+)?)$/; const MAX_DOCUMENT_LINES = 1000; // Capture isTestExecution on module load so that a test can turn it off and still diff --git a/src/client/tensorBoard/helpers.ts b/src/client/tensorBoard/helpers.ts index 3efb6aca04f9..de13ef910f1b 100644 --- a/src/client/tensorBoard/helpers.ts +++ b/src/client/tensorBoard/helpers.ts @@ -10,9 +10,11 @@ import { noop } from '../common/utils/misc'; // matches the 'main' module. // RegEx to match `import torch.profiler` or `from torch import profiler` -export const TorchProfilerImportRegEx = /^\s*(?:import (?:(\w+, )*torch\.profiler(, \w+)*))|(?:from torch import (?:(\w+, )*profiler(, \w+)*))/; +export const TorchProfilerImportRegEx = + /^\s*(?:import (?:(\w+, )*torch\.profiler(, \w+)*))|(?:from torch import (?:(\w+, )*profiler(, \w+)*))/; // RegEx to match `from torch.utils import tensorboard`, `import torch.utils.tensorboard`, `import tensorboardX`, `import tensorboard` -const TensorBoardImportRegEx = /^\s*(?:from torch\.utils\.tensorboard import \w+)|(?:from torch\.utils import (?:(\w+, )*tensorboard(, \w+)*))|(?:from tensorboardX import \w+)|(?:import (\w+, )*((torch\.utils\.tensorboard)|(tensorboardX)|(tensorboard))(, \w+)*)/; +const TensorBoardImportRegEx = + /^\s*(?:from torch\.utils\.tensorboard import \w+)|(?:from torch\.utils import (?:(\w+, )*tensorboard(, \w+)*))|(?:from tensorboardX import \w+)|(?:import (\w+, )*((torch\.utils\.tensorboard)|(tensorboardX)|(tensorboard))(, \w+)*)/; export function containsTensorBoardImport(lines: (string | undefined)[]): boolean { try { diff --git a/src/client/testing/common/runner.ts b/src/client/testing/common/runner.ts index abf4d0c40344..bc1acfe29fc8 100644 --- a/src/client/testing/common/runner.ts +++ b/src/client/testing/common/runner.ts @@ -58,9 +58,8 @@ async function run(serviceContainer: IServiceContainer, testProvider: TestProvid executionService.execModuleObservable(executionInfo.moduleName!, executionInfo.args, options), ); } else { - const pythonToolsExecutionService = serviceContainer.get( - IPythonToolExecutionService, - ); + const pythonToolsExecutionService = + serviceContainer.get(IPythonToolExecutionService); promise = pythonToolsExecutionService.execObservable(executionInfo, spawnOptions, options.workspaceFolder); } diff --git a/src/test/activation/activationManager.unit.test.ts b/src/test/activation/activationManager.unit.test.ts index 9188cb74ac15..638e3367500f 100644 --- a/src/test/activation/activationManager.unit.test.ts +++ b/src/test/activation/activationManager.unit.test.ts @@ -198,8 +198,8 @@ suite('Activation Manager', () => { const disposable2 = typemoq.Mock.ofType(); when(workspaceService.onDidChangeWorkspaceFolders).thenReturn(() => disposable.object); when(workspaceService.workspaceFolders).thenReturn([ - (1 as unknown) as WorkspaceFolder, - (2 as unknown) as WorkspaceFolder, + 1 as unknown as WorkspaceFolder, + 2 as unknown as WorkspaceFolder, ]); when(workspaceService.hasWorkspaceFolders).thenReturn(true); const eventDef = () => disposable2.object; @@ -229,8 +229,8 @@ suite('Activation Manager', () => { const disposable2 = typemoq.Mock.ofType(); when(workspaceService.onDidChangeWorkspaceFolders).thenReturn(() => disposable.object); when(workspaceService.workspaceFolders).thenReturn([ - (1 as unknown) as WorkspaceFolder, - (2 as unknown) as WorkspaceFolder, + 1 as unknown as WorkspaceFolder, + 2 as unknown as WorkspaceFolder, ]); when(workspaceService.hasWorkspaceFolders).thenReturn(true); const eventDef = () => disposable2.object; @@ -356,7 +356,7 @@ suite('Activation Manager', () => { languageId: 'NOT PYTHON', }; - managerTest.onDocOpened((doc as unknown) as TextDocument); + managerTest.onDocOpened(doc as unknown as TextDocument); verify(workspaceService.getWorkspaceFolderIdentifier(doc.uri, anything())).never(); }); @@ -368,7 +368,7 @@ suite('Activation Manager', () => { when(workspaceService.getWorkspaceFolderIdentifier(doc.uri, anything())).thenReturn(''); when(workspaceService.hasWorkspaceFolders).thenReturn(true); - managerTest.onDocOpened((doc as unknown) as TextDocument); + managerTest.onDocOpened(doc as unknown as TextDocument); verify(workspaceService.getWorkspaceFolderIdentifier(doc.uri, anything())).once(); verify(workspaceService.getWorkspaceFolder(doc.uri)).never(); @@ -382,7 +382,7 @@ suite('Activation Manager', () => { when(workspaceService.getWorkspaceFolderIdentifier(doc.uri, anything())).thenReturn('key'); managerTest.activatedWorkspaces.add('key'); - managerTest.onDocOpened((doc as unknown) as TextDocument); + managerTest.onDocOpened(doc as unknown as TextDocument); verify(workspaceService.getWorkspaceFolderIdentifier(doc.uri, anything())).once(); verify(workspaceService.getWorkspaceFolder(doc.uri)).never(); diff --git a/src/test/activation/partialModeStatus.unit.test.ts b/src/test/activation/partialModeStatus.unit.test.ts index 28f134379c87..6dff7305c3f3 100644 --- a/src/test/activation/partialModeStatus.unit.test.ts +++ b/src/test/activation/partialModeStatus.unit.test.ts @@ -20,15 +20,15 @@ suite('Partial Mode Status', async () => { let vscodeMock: typeof vscodeTypes; setup(() => { workspaceService = typemoq.Mock.ofType(); - languageItem = ({ + languageItem = { name: '', severity: 2, text: '', detail: undefined, command: undefined, - } as unknown) as LanguageStatusItem; + } as unknown as LanguageStatusItem; actualSelector = undefined; - vscodeMock = ({ + vscodeMock = { languages: { createLanguageStatusItem: (_: string, selector: DocumentSelector) => { actualSelector = selector; @@ -43,7 +43,7 @@ suite('Partial Mode Status', async () => { Uri: { parse: (s: string) => s, }, - } as unknown) as typeof vscodeTypes; + } as unknown as typeof vscodeTypes; rewiremock.enable(); rewiremock('vscode').with(vscodeMock); }); @@ -78,7 +78,7 @@ suite('Partial Mode Status', async () => { assert.deepEqual(actualSelector!, { language: 'python', }); - assert.deepEqual(languageItem, ({ + assert.deepEqual(languageItem, { name: LanguageService.statusItem.name(), severity: vscodeMock.LanguageStatusSeverity.Warning, text: LanguageService.statusItem.text(), @@ -88,7 +88,7 @@ suite('Partial Mode Status', async () => { command: 'vscode.open', arguments: ['https://aka.ms/AAdzyh4'], }, - } as unknown) as LanguageStatusItem); + } as unknown as LanguageStatusItem); }); test('Expected status item is created if workspace is virtual', async () => { @@ -104,7 +104,7 @@ suite('Partial Mode Status', async () => { assert.deepEqual(actualSelector!, { language: 'python', }); - assert.deepEqual(languageItem, ({ + assert.deepEqual(languageItem, { name: LanguageService.statusItem.name(), severity: vscodeMock.LanguageStatusSeverity.Warning, text: LanguageService.statusItem.text(), @@ -114,7 +114,7 @@ suite('Partial Mode Status', async () => { command: 'vscode.open', arguments: ['https://aka.ms/AAdzyh4'], }, - } as unknown) as LanguageStatusItem); + } as unknown as LanguageStatusItem); }); test('Expected status item is created if workspace is both virtual and untrusted', async () => { @@ -130,7 +130,7 @@ suite('Partial Mode Status', async () => { assert.deepEqual(actualSelector!, { language: 'python', }); - assert.deepEqual(languageItem, ({ + assert.deepEqual(languageItem, { name: LanguageService.statusItem.name(), severity: vscodeMock.LanguageStatusSeverity.Warning, text: LanguageService.statusItem.text(), @@ -140,6 +140,6 @@ suite('Partial Mode Status', async () => { command: 'vscode.open', arguments: ['https://aka.ms/AAdzyh4'], }, - } as unknown) as LanguageStatusItem); + } as unknown as LanguageStatusItem); }); }); diff --git a/src/test/application/diagnostics/checks/jediPython27NotSupported.unit.test.ts b/src/test/application/diagnostics/checks/jediPython27NotSupported.unit.test.ts index 21c60d7860fe..d8fd24173452 100644 --- a/src/test/application/diagnostics/checks/jediPython27NotSupported.unit.test.ts +++ b/src/test/application/diagnostics/checks/jediPython27NotSupported.unit.test.ts @@ -34,21 +34,22 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { suite('Diagnostics', () => { const resource = Uri.file('test.py'); - function createConfigurationAndWorkspaceServices( - languageServer: LanguageServerType, - ): { configurationService: IConfigurationService; workspaceService: IWorkspaceService } { - const configurationService = ({ + function createConfigurationAndWorkspaceServices(languageServer: LanguageServerType): { + configurationService: IConfigurationService; + workspaceService: IWorkspaceService; + } { + const configurationService = { getSettings: () => ({ languageServer }), updateSetting: () => Promise.resolve(), - } as unknown) as IConfigurationService; + } as unknown as IConfigurationService; - const workspaceService = ({ + const workspaceService = { getConfiguration: () => ({ inspect: () => ({ workspaceValue: languageServer, }), }), - } as unknown) as IWorkspaceService; + } as unknown as IWorkspaceService; return { configurationService, workspaceService }; } @@ -70,9 +71,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { ); const service = new JediPython27NotSupportedDiagnosticService( - ({ + { get: () => ({}), - } as unknown) as IServiceContainer, + } as unknown as IServiceContainer, interpreterService, workspaceService, configurationService, @@ -95,9 +96,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { ); const service = new JediPython27NotSupportedDiagnosticService( - ({ + { get: () => ({}), - } as unknown) as IServiceContainer, + } as unknown as IServiceContainer, interpreterService, workspaceService, configurationService, @@ -127,9 +128,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { ); const service = new JediPython27NotSupportedDiagnosticService( - ({ + { get: () => ({}), - } as unknown) as IServiceContainer, + } as unknown as IServiceContainer, interpreterService, workspaceService, configurationService, @@ -161,9 +162,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { ); const service = new JediPython27NotSupportedDiagnosticService( - ({ + { get: () => ({}), - } as unknown) as IServiceContainer, + } as unknown as IServiceContainer, interpreterService, workspaceService, configurationService, @@ -195,9 +196,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { ); const service = new JediPython27NotSupportedDiagnosticService( - ({ + { get: () => ({}), - } as unknown) as IServiceContainer, + } as unknown as IServiceContainer, interpreterService, workspaceService, configurationService, @@ -227,9 +228,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { ); const service = new JediPython27NotSupportedDiagnosticService( - ({ + { get: () => ({}), - } as unknown) as IServiceContainer, + } as unknown as IServiceContainer, interpreterService, workspaceService, configurationService, @@ -265,10 +266,10 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { } as IInterpreterService; setup(() => { - serviceContainer = ({ + serviceContainer = { get: (serviceIdentifier: symbol) => services[serviceIdentifier.toString()] as IWorkspaceService, tryGet: () => ({}), - } as unknown) as IServiceContainer; + } as unknown as IServiceContainer; workspaceService = new WorkspaceService(); services = { @@ -279,9 +280,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { updateSettingStub = sinon.stub(ConfigurationService.prototype, 'updateSetting'); const getSettingsStub = sinon.stub(ConfigurationService.prototype, 'getSettings'); - getSettingsStub.returns(({ + getSettingsStub.returns({ getSettings: () => ({ languageServer: LanguageServerType.Jedi }), - } as unknown) as IPythonSettings); + } as unknown as IPythonSettings); }); teardown(() => { @@ -297,9 +298,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { const configurationService = new ConfigurationService(serviceContainer); const service = new JediPython27NotSupportedDiagnosticService( - ({ + { get: () => ({}), - } as unknown) as IServiceContainer, + } as unknown as IServiceContainer, interpreterService, workspaceService, configurationService, @@ -328,9 +329,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { const configurationService = new ConfigurationService(serviceContainer); const service = new JediPython27NotSupportedDiagnosticService( - ({ + { get: () => ({}), - } as unknown) as IServiceContainer, + } as unknown as IServiceContainer, interpreterService, workspaceService, configurationService, @@ -359,9 +360,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { const configurationService = new ConfigurationService(serviceContainer); const service = new JediPython27NotSupportedDiagnosticService( - ({ + { get: () => ({}), - } as unknown) as IServiceContainer, + } as unknown as IServiceContainer, interpreterService, workspaceService, configurationService, @@ -384,9 +385,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { const configurationService = new ConfigurationService(serviceContainer); const service = new JediPython27NotSupportedDiagnosticService( - ({ + { get: () => ({}), - } as unknown) as IServiceContainer, + } as unknown as IServiceContainer, interpreterService, workspaceService, configurationService, @@ -465,9 +466,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { test('Handling a diagnostic that should be ignored does not display a prompt', async () => { const diagnosticHandlerService = new DiagnosticCommandPromptHandlerService(serviceContainer); - services['Symbol(IDiagnosticFilterService)'] = ({ + services['Symbol(IDiagnosticFilterService)'] = { shouldIgnoreDiagnostic: async () => Promise.resolve(true), - } as unknown) as IDiagnosticFilterService; + } as unknown as IDiagnosticFilterService; const service = new TestJediPython27NotSupportedDiagnosticService( serviceContainer, @@ -487,9 +488,9 @@ suite('Application Diagnostics - Jedi with Python 2.7 deprecated', () => { const diagnosticHandlerService = new DiagnosticCommandPromptHandlerService(serviceContainer); const configurationService = new ConfigurationService(serviceContainer); - services['Symbol(IDiagnosticFilterService)'] = ({ + services['Symbol(IDiagnosticFilterService)'] = { shouldIgnoreDiagnostic: () => Promise.resolve(false), - } as unknown) as IDiagnosticFilterService; + } as unknown as IDiagnosticFilterService; const service = new TestJediPython27NotSupportedDiagnosticService( serviceContainer, diff --git a/src/test/application/diagnostics/checks/macPythonInterpreter.unit.test.ts b/src/test/application/diagnostics/checks/macPythonInterpreter.unit.test.ts index 5421cbcf99ee..4dd774ca6592 100644 --- a/src/test/application/diagnostics/checks/macPythonInterpreter.unit.test.ts +++ b/src/test/application/diagnostics/checks/macPythonInterpreter.unit.test.ts @@ -317,8 +317,8 @@ suite('Application Diagnostics - Checks Mac Python Interpreter', () => { DiagnosticCodes.MacInterpreterSelectedAndHaveOtherInterpretersDiagnostic, undefined, ); - const cmd = ({} as any) as IDiagnosticCommand; - const cmdIgnore = ({} as any) as IDiagnosticCommand; + const cmd = {} as any as IDiagnosticCommand; + const cmdIgnore = {} as any as IDiagnosticCommand; let messagePrompt: MessageCommandPrompt | undefined; messageHandler .setup((i) => i.handle(typemoq.It.isValue(diagnostic), typemoq.It.isAny())) @@ -364,9 +364,9 @@ suite('Application Diagnostics - Checks Mac Python Interpreter', () => { DiagnosticCodes.MacInterpreterSelectedAndNoOtherInterpretersDiagnostic, undefined, ); - const cmdDownload = ({} as any) as IDiagnosticCommand; - const cmdLearn = ({} as any) as IDiagnosticCommand; - const cmdIgnore = ({} as any) as IDiagnosticCommand; + const cmdDownload = {} as any as IDiagnosticCommand; + const cmdLearn = {} as any as IDiagnosticCommand; + const cmdIgnore = {} as any as IDiagnosticCommand; let messagePrompt: MessageCommandPrompt | undefined; messageHandler .setup((i) => i.handle(typemoq.It.isValue(diagnostic), typemoq.It.isAny())) diff --git a/src/test/application/diagnostics/checks/pythonInterpreter.unit.test.ts b/src/test/application/diagnostics/checks/pythonInterpreter.unit.test.ts index 1cf9e8a96670..b2c3f47283eb 100644 --- a/src/test/application/diagnostics/checks/pythonInterpreter.unit.test.ts +++ b/src/test/application/diagnostics/checks/pythonInterpreter.unit.test.ts @@ -203,7 +203,7 @@ suite('Application Diagnostics - Checks Python Interpreter', () => { DiagnosticCodes.NoPythonInterpretersDiagnostic, undefined, ); - const cmd = ({} as any) as IDiagnosticCommand; + const cmd = {} as any as IDiagnosticCommand; let messagePrompt: MessageCommandPrompt | undefined; messageHandler .setup((i) => i.handle(typemoq.It.isValue(diagnostic), typemoq.It.isAny())) @@ -233,7 +233,7 @@ suite('Application Diagnostics - Checks Python Interpreter', () => { DiagnosticCodes.NoCurrentlySelectedPythonInterpreterDiagnostic, undefined, ); - const cmd = ({} as any) as IDiagnosticCommand; + const cmd = {} as any as IDiagnosticCommand; let messagePrompt: MessageCommandPrompt | undefined; messageHandler .setup((i) => i.handle(typemoq.It.isValue(diagnostic), typemoq.It.isAny())) @@ -267,7 +267,7 @@ suite('Application Diagnostics - Checks Python Interpreter', () => { DiagnosticCodes.NoCurrentlySelectedPythonInterpreterDiagnostic, undefined, ); - const cmd = ({} as any) as IDiagnosticCommand; + const cmd = {} as any as IDiagnosticCommand; let messagePrompt: MessageCommandPrompt | undefined; messageHandler .setup((i) => i.handle(typemoq.It.isValue(diagnostic), typemoq.It.isAny())) @@ -298,7 +298,7 @@ suite('Application Diagnostics - Checks Python Interpreter', () => { }); test('Handling an empty diagnostic should not show a message nor return a command', async () => { const diagnostics: IDiagnostic[] = []; - const cmd = ({} as any) as IDiagnosticCommand; + const cmd = {} as any as IDiagnosticCommand; messageHandler .setup((i) => i.handle(typemoq.It.isAny(), typemoq.It.isAny())) @@ -327,10 +327,10 @@ suite('Application Diagnostics - Checks Python Interpreter', () => { DiagnosticCodes.NoCurrentlySelectedPythonInterpreterDiagnostic, undefined, ); - const cmd = ({} as any) as IDiagnosticCommand; - const diagnosticServiceMock = (typemoq.Mock.ofInstance(diagnosticService) as any) as typemoq.IMock< - InvalidPythonInterpreterService - >; + const cmd = {} as any as IDiagnosticCommand; + const diagnosticServiceMock = typemoq.Mock.ofInstance( + diagnosticService, + ) as any as typemoq.IMock; diagnosticServiceMock.setup((f) => f.canHandle(typemoq.It.isAny())).returns(() => Promise.resolve(false)); messageHandler @@ -357,7 +357,7 @@ suite('Application Diagnostics - Checks Python Interpreter', () => { }); test('Getting command prompts for an unsupported diagnostic code should throw an error', async () => { const diagnostic = new InvalidLaunchJsonDebuggerDiagnostic(DiagnosticCodes.JustMyCodeDiagnostic, undefined); - const cmd = ({} as any) as IDiagnosticCommand; + const cmd = {} as any as IDiagnosticCommand; messageHandler .setup((i) => i.handle(typemoq.It.isAny(), typemoq.It.isAny())) diff --git a/src/test/application/diagnostics/checks/pythonPathDeprecated.unit.test.ts b/src/test/application/diagnostics/checks/pythonPathDeprecated.unit.test.ts index 82495623af3b..4147cc297821 100644 --- a/src/test/application/diagnostics/checks/pythonPathDeprecated.unit.test.ts +++ b/src/test/application/diagnostics/checks/pythonPathDeprecated.unit.test.ts @@ -140,11 +140,11 @@ suite('Application Diagnostics - Python Path Deprecated', () => { test('Python Path Deprecated Diagnostic is handled as expected', async () => { let invoked = false; const diagnostic = new PythonPathDeprecatedDiagnostic('message', resource); - const ignoreCmd = ({ + const ignoreCmd = { invoke: () => { invoked = true; }, - } as any) as IDiagnosticCommand; + } as any as IDiagnosticCommand; filterService .setup((f) => f.shouldIgnoreDiagnostic(typemoq.It.isValue(DiagnosticCodes.PythonPathDeprecatedDiagnostic)), diff --git a/src/test/application/diagnostics/checks/upgradeCodeRunner.unit.test.ts b/src/test/application/diagnostics/checks/upgradeCodeRunner.unit.test.ts index 86b32668d276..16c8ed19f61d 100644 --- a/src/test/application/diagnostics/checks/upgradeCodeRunner.unit.test.ts +++ b/src/test/application/diagnostics/checks/upgradeCodeRunner.unit.test.ts @@ -138,7 +138,7 @@ suite('Application Diagnostics - Upgrade Code Runner', () => { test('UpgradeCodeRunnerDiagnostic is handled as expected', async () => { const diagnostic = new UpgradeCodeRunnerDiagnostic('message', resource); - const ignoreCmd = ({ cmd: 'ignoreCmd' } as any) as IDiagnosticCommand; + const ignoreCmd = { cmd: 'ignoreCmd' } as any as IDiagnosticCommand; filterService .setup((f) => f.shouldIgnoreDiagnostic(typemoq.It.isValue(DiagnosticCodes.UpgradeCodeRunnerDiagnostic))) .returns(() => Promise.resolve(false)); diff --git a/src/test/common.ts b/src/test/common.ts index 17dcc5cd1935..9c444f8d7958 100644 --- a/src/test/common.ts +++ b/src/test/common.ts @@ -120,13 +120,13 @@ export const resetGlobalInterpreterPathSetting = async () => retryAsync(restoreG async function restoreGlobalInterpreterPathSetting(): Promise { const vscode = require('vscode') as typeof import('vscode'); - const pythonConfig = vscode.workspace.getConfiguration('python', (null as any) as Uri); + const pythonConfig = vscode.workspace.getConfiguration('python', null as any as Uri); await pythonConfig.update('defaultInterpreterPath', undefined, true); await disposePythonSettings(); } async function setGlobalPathToInterpreter(pythonPath?: string): Promise { const vscode = require('vscode') as typeof import('vscode'); - const pythonConfig = vscode.workspace.getConfiguration('python', (null as any) as Uri); + const pythonConfig = vscode.workspace.getConfiguration('python', null as any as Uri); await pythonConfig.update('defaultInterpreterPath', pythonPath, true); await disposePythonSettings(); } @@ -211,7 +211,7 @@ async function setPythonPathInWorkspace( } async function restoreGlobalPythonPathSetting(): Promise { const vscode = require('vscode') as typeof import('vscode'); - const pythonConfig = vscode.workspace.getConfiguration('python', (null as any) as Uri); + const pythonConfig = vscode.workspace.getConfiguration('python', null as any as Uri); await Promise.all([ pythonConfig.update('defaultInterpreterPath', undefined, true), pythonConfig.update('defaultInterpreterPath', undefined, true), diff --git a/src/test/common/application/commands/reportIssueCommand.unit.test.ts b/src/test/common/application/commands/reportIssueCommand.unit.test.ts index 323240fb7d3b..003e6b670618 100644 --- a/src/test/common/application/commands/reportIssueCommand.unit.test.ts +++ b/src/test/common/application/commands/reportIssueCommand.unit.test.ts @@ -44,10 +44,10 @@ suite('Report Issue Command', () => { languageServer: LanguageServerType.Node, }), ); - const interpreter = ({ + const interpreter = { envType: EnvironmentType.Venv, version: { raw: '3.9.0' }, - } as unknown) as PythonEnvironment; + } as unknown as PythonEnvironment; when(interpreterService.getActiveInterpreter()).thenResolve(interpreter); when(configurationService.getSettings()).thenReturn({ experiments: { diff --git a/src/test/common/configSettings.test.ts b/src/test/common/configSettings.test.ts index 75c20f512bbe..eb7a5f26403b 100644 --- a/src/test/common/configSettings.test.ts +++ b/src/test/common/configSettings.test.ts @@ -15,7 +15,7 @@ suite('Configuration Settings', () => { test('Check Values', (done) => { const systemVariables: SystemVariables = new SystemVariables(undefined, workspaceRoot); - const pythonConfig = vscode.workspace.getConfiguration('python', (null as any) as vscode.Uri); + const pythonConfig = vscode.workspace.getConfiguration('python', null as any as vscode.Uri); const pythonSettings = getExtensionSettings(vscode.Uri.file(workspaceRoot)); Object.keys(pythonSettings).forEach((key) => { let settingValue = pythonConfig.get(key, 'Not a config'); diff --git a/src/test/common/experiments/service.unit.test.ts b/src/test/common/experiments/service.unit.test.ts index cbbd53d78151..651a1c51d43c 100644 --- a/src/test/common/experiments/service.unit.test.ts +++ b/src/test/common/experiments/service.unit.test.ts @@ -169,9 +169,9 @@ suite('Experimentation service', () => { }); getTreatmentVariable = sinon.stub().returns(Promise.resolve(true)); - sinon.stub(tasClient, 'getExperimentationService').returns(({ + sinon.stub(tasClient, 'getExperimentationService').returns({ getTreatmentVariable, - } as unknown) as tasClient.IExperimentationService); + } as unknown as tasClient.IExperimentationService); configureApplicationEnvironment('stable', extensionVersion); }); @@ -322,9 +322,9 @@ suite('Experimentation service', () => { setup(() => { getTreatmentVariableStub = sinon.stub().returns(Promise.resolve('value')); - sinon.stub(tasClient, 'getExperimentationService').returns(({ + sinon.stub(tasClient, 'getExperimentationService').returns({ getTreatmentVariable: getTreatmentVariableStub, - } as unknown) as tasClient.IExperimentationService); + } as unknown as tasClient.IExperimentationService); configureApplicationEnvironment('stable', extensionVersion); }); diff --git a/src/test/common/installer/installer.unit.test.ts b/src/test/common/installer/installer.unit.test.ts index 3e6ba0e3118d..d327d58740f2 100644 --- a/src/test/common/installer/installer.unit.test.ts +++ b/src/test/common/installer/installer.unit.test.ts @@ -693,7 +693,7 @@ suite('Module Installer only', () => { 'Use black', 'Use yapf', ), - ).thenReturn((undefined as unknown) as Thenable); + ).thenReturn(undefined as unknown as Thenable); const response = await installer.promptToInstallImplementation(product, resource); @@ -720,7 +720,7 @@ suite('Module Installer only', () => { 'Use black', 'Use yapf', ), - ).thenReturn(('Yes' as unknown) as Thenable); + ).thenReturn('Yes' as unknown as Thenable); const response = await installer.promptToInstallImplementation(product, resource); verify( @@ -747,7 +747,7 @@ suite('Module Installer only', () => { 'Use black', 'Use yapf', ), - ).thenReturn(('Use black' as unknown) as Thenable); + ).thenReturn('Use black' as unknown as Thenable); when(configService.updateSetting('formatting.provider', 'black', resource)).thenResolve(); const response = await installer.promptToInstallImplementation(product, resource); @@ -777,7 +777,7 @@ suite('Module Installer only', () => { 'Use black', 'Use yapf', ), - ).thenReturn(('Use yapf' as unknown) as Thenable); + ).thenReturn('Use yapf' as unknown as Thenable); when(configService.updateSetting('formatting.provider', 'yapf', resource)).thenResolve(); const response = await installer.promptToInstallImplementation(product, resource); @@ -879,7 +879,7 @@ suite('Module Installer only', () => { const productName = ProductNames.get(product)!; when( appShell.showErrorMessage(`Linter ${productName} is not installed.`, 'Install', options[0], options[1]), - ).thenResolve(('Select Linter' as unknown) as void); + ).thenResolve('Select Linter' as unknown as void); when(cmdManager.executeCommand(Commands.Set_Linter)).thenResolve(undefined); const response = await installer.promptToInstallImplementation(product, resource); @@ -896,7 +896,7 @@ suite('Module Installer only', () => { const productName = ProductNames.get(product)!; when( appShell.showErrorMessage(`Linter ${productName} is not installed.`, 'Install', options[0], options[1]), - ).thenResolve(('Install' as unknown) as void); + ).thenResolve('Install' as unknown as void); when(cmdManager.executeCommand(Commands.Set_Linter)).thenResolve(undefined); const install = sinon.stub(LinterInstaller.prototype, 'install'); install.resolves(InstallerResponse.Installed); diff --git a/src/test/common/net/httpClient.unit.test.ts b/src/test/common/net/httpClient.unit.test.ts index 0a4bf5f5da7a..ca43f30af5cb 100644 --- a/src/test/common/net/httpClient.unit.test.ts +++ b/src/test/common/net/httpClient.unit.test.ts @@ -88,8 +88,7 @@ suite('Http Client', () => { [ { - name: - "If strict is set to false, and jsonc parsing returns error codes, then log errors and don't throw, return json", + name: "If strict is set to false, and jsonc parsing returns error codes, then log errors and don't throw, return json", returnedArgs: [undefined, { statusCode: 200 }, '[{ "strictJSON" : false,, }]'], strict: false, expectedJSON: [{ strictJSON: false }], diff --git a/src/test/common/platform/filesystem.unit.test.ts b/src/test/common/platform/filesystem.unit.test.ts index 8c54b0c08ab7..24b8594c9ec5 100644 --- a/src/test/common/platform/filesystem.unit.test.ts +++ b/src/test/common/platform/filesystem.unit.test.ts @@ -238,7 +238,7 @@ suite('Raw FileSystem', () => { raw.setup((r) => r.dirname(tgt)) // Provide the target's parent. .returns(() => 'x/y'); raw.setup((r) => r.stat(Uri('x/y'))) // The parent dir exists. - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); raw.setup((r) => r.rename(Uri(src), Uri(tgt), { overwrite: false })) // expect the specific filename .returns(() => Promise.resolve()); @@ -253,12 +253,12 @@ suite('Raw FileSystem', () => { raw.setup((r) => r.dirname(tgt)) // Provide the target's parent. .returns(() => 'x/y'); raw.setup((r) => r.stat(Uri('x/y'))) // The parent dir exists. - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); const err = vscode.FileSystemError.FileExists('...'); raw.setup((r) => r.rename(Uri(src), Uri(tgt), { overwrite: false })) // expect the specific filename .returns(() => Promise.reject(err)); raw.setup((r) => r.stat(Uri(tgt))) // It's a file. - .returns(() => Promise.resolve(({ type: FileType.File } as unknown) as FileStat)); + .returns(() => Promise.resolve({ type: FileType.File } as unknown as FileStat)); raw.setup((r) => r.rename(Uri(src), Uri(tgt), { overwrite: true })) // expect the specific filename .returns(() => Promise.resolve()); @@ -273,7 +273,7 @@ suite('Raw FileSystem', () => { raw.setup((r) => r.dirname(tgt)) // Provide the target's parent. .returns(() => 'x/y'); raw.setup((r) => r.stat(Uri('x/y'))) // The parent dir exists. - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); raw.setup((r) => r.rename(Uri(src), Uri(tgt), { overwrite: false })) // expect the specific filename .returns(() => Promise.resolve()); @@ -288,12 +288,12 @@ suite('Raw FileSystem', () => { raw.setup((r) => r.dirname(tgt)) // Provide the target's parent. .returns(() => 'x/y'); raw.setup((r) => r.stat(Uri('x/y'))) // The parent dir exists. - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); const err = vscode.FileSystemError.FileExists('...'); raw.setup((r) => r.rename(Uri(src), Uri(tgt), { overwrite: false })) // expect the specific filename .returns(() => Promise.reject(err)); raw.setup((r) => r.stat(Uri(tgt))) // It's a directory. - .returns(() => Promise.resolve(({ type: FileType.Directory } as unknown) as FileStat)); + .returns(() => Promise.resolve({ type: FileType.Directory } as unknown as FileStat)); const promise = filesystem.move(src, tgt); @@ -307,13 +307,13 @@ suite('Raw FileSystem', () => { raw.setup((r) => r.dirname(tgt)) // Provide the target's parent. .returns(() => 'x/y'); raw.setup((r) => r.stat(Uri('x/y'))) // The parent dir exists. - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); const err = vscode.FileSystemError.FileExists('...'); raw.setup((r) => r.rename(Uri(src), Uri(tgt), { overwrite: false })) // expect the specific filename .returns(() => Promise.reject(err)); raw.setup((r) => r.stat(Uri(tgt))) // It's a symlink. .returns(() => - Promise.resolve(({ type: FileType.SymbolicLink | FileType.Directory } as unknown) as FileStat), + Promise.resolve({ type: FileType.SymbolicLink | FileType.Directory } as unknown as FileStat), ); raw.setup((r) => r.rename(Uri(src), Uri(tgt), { overwrite: true })) // expect the specific filename .returns(() => Promise.resolve()); @@ -340,7 +340,7 @@ suite('Raw FileSystem', () => { raw.setup((r) => r.dirname(TypeMoq.It.isAny())) // Provide the target's parent. .returns(() => ''); raw.setup((r) => r.stat(TypeMoq.It.isAny())) // The parent dir exists. - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); const err = new Error('oops!'); raw.setup((r) => r.rename(TypeMoq.It.isAny(), TypeMoq.It.isAny(), { overwrite: false })) // We don't care about the filename. .throws(err); @@ -455,7 +455,7 @@ suite('Raw FileSystem', () => { raw.setup((r) => r.dirname(tgt)) // Provide the target's parent. .returns(() => 'x/y/z'); raw.setup((r) => r.stat(Uri('x/y/z'))) // The parent dir exists. - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); raw.setup((r) => r.copy(Uri(src), Uri(tgt), { overwrite: true })) // Expect the specific args. .returns(() => Promise.resolve()); @@ -481,7 +481,7 @@ suite('Raw FileSystem', () => { raw.setup((r) => r.dirname(TypeMoq.It.isAny())) // Provide the target's parent. .returns(() => ''); raw.setup((r) => r.stat(TypeMoq.It.isAny())) // The parent dir exists. - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); raw.setup((r) => r.copy(TypeMoq.It.isAny(), TypeMoq.It.isAny(), { overwrite: true })) // We don't care about the filename. .throws(new Error('file not found')); @@ -607,7 +607,7 @@ suite('Raw FileSystem', () => { test('wraps the low-level function', async () => { const dirname = 'x/y/z/spam'; raw.setup((r) => r.stat(Uri(dirname))) // The dir exists. - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); raw.setup((r) => r.delete(Uri(dirname), opts)) // Expect the specific dirname. .returns(() => Promise.resolve()); @@ -618,7 +618,7 @@ suite('Raw FileSystem', () => { test('fails if the low-level call fails', async () => { raw.setup((r) => r.stat(TypeMoq.It.isAny())) // The "file" exists. - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); raw.setup((r) => r.delete(TypeMoq.It.isAny(), opts)) // We don't care about the filename. .throws(new Error('file not found')); @@ -1300,7 +1300,7 @@ suite('FileSystemUtils', () => { const dirname = 'x/y/z/spam'; const filename = `${dirname}/___vscpTest___`; deps.setup((d) => d.stat(dirname)) // Success! - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); deps.setup((d) => d.writeText(filename, '')) // Success! .returns(() => Promise.resolve()); deps.setup((d) => d.rmfile(filename)) // Success! @@ -1319,7 +1319,7 @@ suite('FileSystemUtils', () => { (err as any).code = 'EACCES'; // errno deps.setup((d) => d.stat(dirname)) // Success! - .returns(() => Promise.resolve((undefined as unknown) as FileStat)); + .returns(() => Promise.resolve(undefined as unknown as FileStat)); deps.setup((d) => d.writeText(filename, '')) // not permitted .returns(() => Promise.reject(err)); @@ -1430,7 +1430,7 @@ suite('FileSystemUtils', () => { test('no matches (undefined)', async () => { const pattern = `x/y/z/spam.*`; deps.setup((d) => d.globFile(pattern, undefined)) // found none - .returns(() => Promise.resolve((undefined as unknown) as string[])); + .returns(() => Promise.resolve(undefined as unknown as string[])); const files = await utils.search(pattern); @@ -1443,7 +1443,7 @@ suite('FileSystemUtils', () => { test('file exists', async () => { const filename = 'x/y/z/spam.py'; deps.setup((d) => d.statSync(filename)) // The file exists. - .returns(() => (undefined as unknown) as FileStat); + .returns(() => undefined as unknown as FileStat); const exists = utils.fileExistsSync(filename); diff --git a/src/test/common/process/logger.unit.test.ts b/src/test/common/process/logger.unit.test.ts index 48d8bca82220..6eb720fc8984 100644 --- a/src/test/common/process/logger.unit.test.ts +++ b/src/test/common/process/logger.unit.test.ts @@ -24,7 +24,7 @@ suite('ProcessLogger suite', () => { workspaceService = TypeMoq.Mock.ofType(); workspaceService .setup((w) => w.workspaceFolders) - .returns(() => [({ uri: { fsPath: path.join('path', 'to', 'workspace') } } as unknown) as WorkspaceFolder]); + .returns(() => [{ uri: { fsPath: path.join('path', 'to', 'workspace') } } as unknown as WorkspaceFolder]); logger = new ProcessLogger(workspaceService.object); }); diff --git a/src/test/common/process/pythonExecutionFactory.unit.test.ts b/src/test/common/process/pythonExecutionFactory.unit.test.ts index 6b5e9d4a25db..4221b8160484 100644 --- a/src/test/common/process/pythonExecutionFactory.unit.test.ts +++ b/src/test/common/process/pythonExecutionFactory.unit.test.ts @@ -205,7 +205,7 @@ suite('Process - PythonExecutionFactory', () => { factory.create = async () => { createInvoked = true; // eslint-disable-next-line @typescript-eslint/no-explicit-any - return Promise.resolve((mockExecService as any) as IPythonExecutionService); + return Promise.resolve(mockExecService as any as IPythonExecutionService); }; const service = await verifyCreateActivated(factory, activationHelper, resource, interpreter); @@ -225,7 +225,7 @@ suite('Process - PythonExecutionFactory', () => { factory.create = async () => { createInvoked = true; // eslint-disable-next-line @typescript-eslint/no-explicit-any - return Promise.resolve((mockExecService as any) as IPythonExecutionService); + return Promise.resolve(mockExecService as any as IPythonExecutionService); }; const service = await verifyCreateActivated(factory, activationHelper, resource, interpreter); @@ -238,7 +238,7 @@ suite('Process - PythonExecutionFactory', () => { factory.create = async () => { createInvoked = true; // eslint-disable-next-line @typescript-eslint/no-explicit-any - return Promise.resolve((mockExecService as any) as IPythonExecutionService); + return Promise.resolve(mockExecService as any as IPythonExecutionService); }; const pythonSettings = mock(PythonSettings); @@ -337,7 +337,7 @@ suite('Process - PythonExecutionFactory', () => { factory.create = async () => { createInvoked = true; // eslint-disable-next-line @typescript-eslint/no-explicit-any - return Promise.resolve((mockExecService as any) as IPythonExecutionService); + return Promise.resolve(mockExecService as any as IPythonExecutionService); }; const pythonSettings = mock(PythonSettings); diff --git a/src/test/common/socketStream.test.ts b/src/test/common/socketStream.test.ts index 35420e4a614c..19298b132bf1 100644 --- a/src/test/common/socketStream.test.ts +++ b/src/test/common/socketStream.test.ts @@ -42,7 +42,7 @@ suite('SocketStream', () => { const byteValue = buffer[0]; const socket = new MockSocket(); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); assert.strictEqual(stream.ReadByte(), byteValue); done(); @@ -52,7 +52,7 @@ suite('SocketStream', () => { const socket = new MockSocket(); const buffer = uint64be.encode(num); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); assert.strictEqual(stream.ReadInt32(), num); done(); @@ -62,7 +62,7 @@ suite('SocketStream', () => { const socket = new MockSocket(); const buffer = uint64be.encode(num); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); assert.strictEqual(stream.ReadInt64(), num); done(); @@ -72,7 +72,7 @@ suite('SocketStream', () => { const socket = new MockSocket(); const buffer = Buffer.concat([Buffer.from('A'), uint64be.encode(message.length), Buffer.from(message)]); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); assert.strictEqual(stream.ReadString(), message); done(); @@ -86,7 +86,7 @@ suite('SocketStream', () => { stringBuffer, ]); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); assert.strictEqual(stream.ReadString(), message); done(); @@ -100,7 +100,7 @@ suite('SocketStream', () => { const partOfSecondMessage = Buffer.concat([Buffer.from('A'), uint64be.encode(message.length)]); buffer = Buffer.concat([buffer, partOfSecondMessage]); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); stream.BeginTransaction(); assert.strictEqual(stream.ReadString(), message, 'First message not read properly'); @@ -123,7 +123,7 @@ suite('SocketStream', () => { const partOfSecondMessage = Buffer.concat([Buffer.from('A'), uint64be.encode(message.length)]); buffer = Buffer.concat([buffer, partOfSecondMessage]); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); stream.BeginTransaction(); assert.strictEqual(stream.ReadString(), message, 'First message not read properly'); @@ -139,7 +139,7 @@ suite('SocketStream', () => { const buffer = Buffer.from(''); const socket = new MockSocket(); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); stream.Write(Buffer.from(message)); assert.strictEqual(socket.dataWritten, message); @@ -150,7 +150,7 @@ suite('SocketStream', () => { const buffer = Buffer.from(''); const socket = new MockSocket(); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); stream.WriteInt32(num); assert.strictEqual(uint64be.decode(socket.rawDataWritten), num); @@ -161,7 +161,7 @@ suite('SocketStream', () => { const buffer = Buffer.from(''); const socket = new MockSocket(); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); stream.WriteInt64(num); assert.strictEqual(uint64be.decode(socket.rawDataWritten), num); @@ -172,7 +172,7 @@ suite('SocketStream', () => { const buffer = Buffer.from(''); const socket = new MockSocket(); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); stream.WriteString(message); assert.strictEqual(socket.dataWritten, message); @@ -183,7 +183,7 @@ suite('SocketStream', () => { const buffer = Buffer.from(''); const socket = new MockSocket(); - const stream = new SocketStream((socket as any) as net.Socket, buffer); + const stream = new SocketStream(socket as any as net.Socket, buffer); stream.WriteString(message); assert.strictEqual(socket.dataWritten, message); diff --git a/src/test/common/terminals/activation.unit.test.ts b/src/test/common/terminals/activation.unit.test.ts index 49ada1c06b11..65e6dd67b475 100644 --- a/src/test/common/terminals/activation.unit.test.ts +++ b/src/test/common/terminals/activation.unit.test.ts @@ -25,7 +25,7 @@ suite('Terminal Auto Activation', () => { let terminal: Terminal; setup(() => { - terminal = ({ + terminal = { dispose: noop, hide: noop, name: 'Python', @@ -34,7 +34,7 @@ suite('Terminal Auto Activation', () => { sendText: noop, show: noop, exitStatus: { code: 0 }, - } as unknown) as Terminal; + } as unknown as Terminal; terminalManager = mock(TerminalManager); activator = mock(TerminalActivator); activeResourceService = mock(ActiveResourceService); @@ -68,7 +68,7 @@ suite('Terminal Auto Activation', () => { verify(activator.activateEnvironmentInTerminal(terminal, anything())).once(); }); test('New Terminals should not be activated if hidden from user', async () => { - terminal = ({ + terminal = { dispose: noop, hide: noop, name: 'Python', @@ -77,7 +77,7 @@ suite('Terminal Auto Activation', () => { sendText: noop, show: noop, exitStatus: { code: 0 }, - } as unknown) as Terminal; + } as unknown as Terminal; type EventHandler = (e: Terminal) => void; let handler: undefined | EventHandler; const handlerDisposable = TypeMoq.Mock.ofType(); @@ -98,7 +98,7 @@ suite('Terminal Auto Activation', () => { verify(activator.activateEnvironmentInTerminal(terminal, anything())).never(); }); test('New Terminals should not be activated if auto activation is to be disabled', async () => { - terminal = ({ + terminal = { dispose: noop, hide: noop, name: 'Python', @@ -107,7 +107,7 @@ suite('Terminal Auto Activation', () => { sendText: noop, show: noop, exitStatus: { code: 0 }, - } as unknown) as Terminal; + } as unknown as Terminal; type EventHandler = (e: Terminal) => void; let handler: undefined | EventHandler; const handlerDisposable = TypeMoq.Mock.ofType(); diff --git a/src/test/common/terminals/activator/base.unit.test.ts b/src/test/common/terminals/activator/base.unit.test.ts index fdfe9dcee579..4acb7d6ad420 100644 --- a/src/test/common/terminals/activator/base.unit.test.ts +++ b/src/test/common/terminals/activator/base.unit.test.ts @@ -16,12 +16,12 @@ suite('Terminal Base Activator', () => { setup(() => { helper = TypeMoq.Mock.ofType(); - activator = (new (class extends BaseTerminalActivator { + activator = new (class extends BaseTerminalActivator { public waitForCommandToProcess() { noop(); return Promise.resolve(); } - })(helper.object) as any) as ITerminalActivator; + })(helper.object) as any as ITerminalActivator; }); [ { commandCount: 1, preserveFocus: false }, diff --git a/src/test/common/terminals/activator/index.unit.test.ts b/src/test/common/terminals/activator/index.unit.test.ts index 9dff5a800cad..32155e0b581d 100644 --- a/src/test/common/terminals/activator/index.unit.test.ts +++ b/src/test/common/terminals/activator/index.unit.test.ts @@ -29,9 +29,9 @@ suite('Terminal Activator', () => { configService .setup((c) => c.getSettings(TypeMoq.It.isAny())) .returns(() => { - return ({ + return { terminal: terminalSettings.object, - } as unknown) as IPythonSettings; + } as unknown as IPythonSettings; }); activator = new (class extends TerminalActivator { protected initialize() { diff --git a/src/test/common/terminals/helper.unit.test.ts b/src/test/common/terminals/helper.unit.test.ts index ef688ac2257d..7d4ec94fafac 100644 --- a/src/test/common/terminals/helper.unit.test.ts +++ b/src/test/common/terminals/helper.unit.test.ts @@ -217,7 +217,7 @@ suite('Terminal Service helpers', () => { when(pipenvActivationProvider.isShellSupported(anything())).thenReturn(false); const cmd = await helper.getEnvironmentActivationCommands( - ('someShell' as any) as TerminalShellType, + 'someShell' as any as TerminalShellType, resource, ); diff --git a/src/test/common/terminals/shellDetectors/shellDetectors.unit.test.ts b/src/test/common/terminals/shellDetectors/shellDetectors.unit.test.ts index 07befdda9291..f694c81e017d 100644 --- a/src/test/common/terminals/shellDetectors/shellDetectors.unit.test.ts +++ b/src/test/common/terminals/shellDetectors/shellDetectors.unit.test.ts @@ -102,9 +102,9 @@ suite('Shell Detectors', () => { shellPathsAndIdentification.forEach((shellType, shellPath) => { when(appEnv.shell).thenReturn('defaultshellPath'); expect( - shellDetector.identify(telemetryProperties, ({ + shellDetector.identify(telemetryProperties, { creationOptions: { shellPath }, - } as unknown) as Terminal), + } as unknown as Terminal), ).to.equal(shellType, `Incorrect Shell Type from identifyShellByTerminalName, for path '${shellPath}'`); }); }); diff --git a/src/test/common/utils/version.unit.test.ts b/src/test/common/utils/version.unit.test.ts index 3541b9b82926..30cd8b57d9f2 100644 --- a/src/test/common/utils/version.unit.test.ts +++ b/src/test/common/utils/version.unit.test.ts @@ -35,13 +35,13 @@ function ver( micro = -1; } const info = { - major: (major as unknown) as number, - minor: (minor as unknown) as number, - micro: (micro as unknown) as number, + major: major as unknown as number, + minor: minor as unknown as number, + micro: micro as unknown as number, raw: undefined, }; if (unnormalized !== undefined) { - ((info as unknown) as any).unnormalized = unnormalized; + (info as unknown as any).unnormalized = unnormalized; } return info; } @@ -143,7 +143,7 @@ suite('common utils - normalizeVersionInfo', () => { const info = ver(1, 2, 3); info.raw = '1.2.3'; - ((info as unknown) as any).unnormalized = unnorm('', '', ''); + (info as unknown as any).unnormalized = unnorm('', '', ''); const expected = info; const normalized = normalizeVersionInfo(info); @@ -188,7 +188,7 @@ suite('common utils - normalizeVersionInfo', () => { ].forEach((data) => { const [info, expected] = data; - ((expected as unknown) as any).unnormalized = unnorm('', '', ''); + (expected as unknown as any).unnormalized = unnorm('', '', ''); expected.raw = ''; test(`[${info.major}, ${info.minor}, ${info.micro}]`, () => { const normalized = normalizeVersionInfo(info); @@ -199,16 +199,18 @@ suite('common utils - normalizeVersionInfo', () => { }); suite('partially "invalid"', () => { - ([ - [ver(undefined, 4, 5), unnorm('missing', '', '')], - [ver(3, null, 5), unnorm('', 'missing', '')], - [ver(3, 4, NaN), unnorm('', '', 'missing')], - [ver(3, 4, ''), unnorm('', '', 'string not numeric')], - [ver(3, 4, ' '), unnorm('', '', 'string not numeric')], - [ver(3, 4, 'foo'), unnorm('', '', 'string not numeric')], - [ver(3, 4, {}), unnorm('', '', 'unsupported type')], - [ver(3, 4, []), unnorm('', '', 'unsupported type')], - ] as [VersionInfo, Unnormalized][]).forEach((data) => { + ( + [ + [ver(undefined, 4, 5), unnorm('missing', '', '')], + [ver(3, null, 5), unnorm('', 'missing', '')], + [ver(3, 4, NaN), unnorm('', '', 'missing')], + [ver(3, 4, ''), unnorm('', '', 'string not numeric')], + [ver(3, 4, ' '), unnorm('', '', 'string not numeric')], + [ver(3, 4, 'foo'), unnorm('', '', 'string not numeric')], + [ver(3, 4, {}), unnorm('', '', 'unsupported type')], + [ver(3, 4, []), unnorm('', '', 'unsupported type')], + ] as [VersionInfo, Unnormalized][] + ).forEach((data) => { const [info, unnormalized] = data; const expected = { ...info }; if (info.major !== 3) { @@ -219,7 +221,7 @@ suite('common utils - normalizeVersionInfo', () => { expected.micro = -1; } - ((expected as unknown) as any).unnormalized = unnormalized; + (expected as unknown as any).unnormalized = unnormalized; expected.raw = ''; test(`[${info.major}, ${info.minor}, ${info.micro}]`, () => { const normalized = normalizeVersionInfo(info); @@ -310,28 +312,30 @@ suite('common utils - parseVersionInfo', () => { }); suite('valid versions', () => { - ([ - // plain - ...VERSIONS.map(([v, s]) => [s, { version: v, before: '', after: '' }]), - ['02.7', res(2, 7, -1, '', '')], - ['2.07', res(2, 7, -1, '', '')], - ['2.7.01', res(2, 7, 1, '', '')], - // with before/after - [' 2.7.9 ', res(2, 7, 9, ' ', ' ')], - ['2.7.9-3.2.7', res(2, 7, 9, '', '-3.2.7')], - ['python2.7.exe', res(2, 7, -1, 'python', '.exe')], - ['1.2.3.4.5-x2.2', res(1, 2, 3, '', '.4.5-x2.2')], - ['3.8.1a2', res(3, 8, 1, '', 'a2')], - ['3.8.1-alpha2', res(3, 8, 1, '', '-alpha2')], + ( [ - '3.7.5 (default, Nov 7 2019, 10:50:52) \\n[GCC 8.3.0]', - res(3, 7, 5, '', ' (default, Nov 7 2019, 10:50:52) \\n[GCC 8.3.0]'), - ], - ['python2', res(2, -1, -1, 'python', '')], - // without the "before" the following won't match. - ['python2.a', res(2, -1, -1, 'python', '.a')], - ['python2.b7', res(2, -1, -1, 'python', '.b7')], - ] as [string, ParseResult][]).forEach((data) => { + // plain + ...VERSIONS.map(([v, s]) => [s, { version: v, before: '', after: '' }]), + ['02.7', res(2, 7, -1, '', '')], + ['2.07', res(2, 7, -1, '', '')], + ['2.7.01', res(2, 7, 1, '', '')], + // with before/after + [' 2.7.9 ', res(2, 7, 9, ' ', ' ')], + ['2.7.9-3.2.7', res(2, 7, 9, '', '-3.2.7')], + ['python2.7.exe', res(2, 7, -1, 'python', '.exe')], + ['1.2.3.4.5-x2.2', res(1, 2, 3, '', '.4.5-x2.2')], + ['3.8.1a2', res(3, 8, 1, '', 'a2')], + ['3.8.1-alpha2', res(3, 8, 1, '', '-alpha2')], + [ + '3.7.5 (default, Nov 7 2019, 10:50:52) \\n[GCC 8.3.0]', + res(3, 7, 5, '', ' (default, Nov 7 2019, 10:50:52) \\n[GCC 8.3.0]'), + ], + ['python2', res(2, -1, -1, 'python', '')], + // without the "before" the following won't match. + ['python2.a', res(2, -1, -1, 'python', '.a')], + ['python2.b7', res(2, -1, -1, 'python', '.b7')], + ] as [string, ParseResult][] + ).forEach((data) => { const [verStr, result] = data; if (verStr === '') { return; diff --git a/src/test/configuration/environmentTypeComparer.unit.test.ts b/src/test/configuration/environmentTypeComparer.unit.test.ts index e3b909378b63..896b2487af7b 100644 --- a/src/test/configuration/environmentTypeComparer.unit.test.ts +++ b/src/test/configuration/environmentTypeComparer.unit.test.ts @@ -22,10 +22,10 @@ suite('Environment sorting', () => { getActiveWorkspaceUriStub = sinon.stub().returns({ folderUri: { fsPath: workspacePath } }); getInterpreterTypeDisplayNameStub = sinon.stub(); - interpreterHelper = ({ + interpreterHelper = { getActiveWorkspaceUri: getActiveWorkspaceUriStub, getInterpreterTypeDisplayName: getInterpreterTypeDisplayNameStub, - } as unknown) as IInterpreterHelper; + } as unknown as IInterpreterHelper; }); teardown(() => { @@ -189,8 +189,7 @@ suite('Environment sorting', () => { expected: 1, }, { - title: - "If 2 global environments have the same Python version and there's a Conda one, the Conda env should not come first", + title: "If 2 global environments have the same Python version and there's a Conda one, the Conda env should not come first", envA: { envType: EnvironmentType.Conda, envName: 'conda-env', @@ -204,8 +203,7 @@ suite('Environment sorting', () => { expected: 1, }, { - title: - 'If 2 global environments are of the same type and have the same Python version, they should be sorted by name', + title: 'If 2 global environments are of the same type and have the same Python version, they should be sorted by name', envA: { envType: EnvironmentType.Conda, envName: 'conda-foo', diff --git a/src/test/configuration/interpreterSelector/commands/setInterpreter.unit.test.ts b/src/test/configuration/interpreterSelector/commands/setInterpreter.unit.test.ts index 0b91a5f9445e..8fb0027af490 100644 --- a/src/test/configuration/interpreterSelector/commands/setInterpreter.unit.test.ts +++ b/src/test/configuration/interpreterSelector/commands/setInterpreter.unit.test.ts @@ -172,7 +172,7 @@ suite('Set Interpreter Command', () => { workspace .setup((w) => w.getWorkspaceFolder(TypeMoq.It.isAny())) - .returns(() => (({ uri: { fsPath: workspacePath } } as unknown) as WorkspaceFolder)); + .returns(() => ({ uri: { fsPath: workspacePath } } as unknown as WorkspaceFolder)); setInterpreterCommand = new SetInterpreterCommand( appShell.object, @@ -233,7 +233,7 @@ suite('Set Interpreter Command', () => { .callback((options) => { actualParameters = options; }) - .returns(() => Promise.resolve((undefined as unknown) as QuickPickItem)); + .returns(() => Promise.resolve(undefined as unknown as QuickPickItem)); await setInterpreterCommand._pickInterpreter(multiStepInput.object, state); @@ -337,7 +337,7 @@ suite('Set Interpreter Command', () => { .callback((options) => { actualParameters = options; }) - .returns(() => Promise.resolve((undefined as unknown) as QuickPickItem)); + .returns(() => Promise.resolve(undefined as unknown as QuickPickItem)); await setInterpreterCommand._pickInterpreter(multiStepInput.object, state); @@ -420,7 +420,7 @@ suite('Set Interpreter Command', () => { .callback((options) => { actualParameters = options; }) - .returns(() => Promise.resolve((undefined as unknown) as QuickPickItem)); + .returns(() => Promise.resolve(undefined as unknown as QuickPickItem)); await setInterpreterCommand._pickInterpreter(multiStepInput.object, state); @@ -443,7 +443,7 @@ suite('Set Interpreter Command', () => { .callback((options) => { actualParameters = options; }) - .returns(() => Promise.resolve((undefined as unknown) as QuickPickItem)); + .returns(() => Promise.resolve(undefined as unknown as QuickPickItem)); await setInterpreterCommand._pickInterpreter(multiStepInput.object, state); @@ -465,7 +465,7 @@ suite('Set Interpreter Command', () => { .callback((options) => { actualParameters = options; }) - .returns(() => Promise.resolve((undefined as unknown) as QuickPickItem)); + .returns(() => Promise.resolve(undefined as unknown as QuickPickItem)); const refreshPromiseDeferred = createDeferred(); // Assume a refresh is currently going on... when(interpreterService.refreshPromise).thenReturn(refreshPromiseDeferred.promise); @@ -491,7 +491,7 @@ suite('Set Interpreter Command', () => { old: item.interpreter, new: refreshedItem.interpreter, }; - await onChangedCallback!(changeEvent, (quickPick as unknown) as QuickPick); // Invoke callback, meaning that the items are supposed to change. + await onChangedCallback!(changeEvent, quickPick as unknown as QuickPick); // Invoke callback, meaning that the items are supposed to change. assert.deepStrictEqual( quickPick, @@ -575,7 +575,7 @@ suite('Set Interpreter Command', () => { interpreterSelector .setup((i) => i.suggestionToQuickPickItem(TypeMoq.It.isValue(newItem.interpreter), undefined, false)) .returns(() => newItem); - await onChangedCallback!(changeEvent2, (quickPick as unknown) as QuickPick); // Invoke callback, meaning that the items are supposed to change. + await onChangedCallback!(changeEvent2, quickPick as unknown as QuickPick); // Invoke callback, meaning that the items are supposed to change. assert.deepStrictEqual( quickPick, @@ -669,7 +669,7 @@ suite('Set Interpreter Command', () => { const multiStepInput = TypeMoq.Mock.ofType>(); multiStepInput .setup((i) => i.showQuickPick(expectedParameters)) - .returns(() => Promise.resolve((undefined as unknown) as QuickPickItem)) + .returns(() => Promise.resolve(undefined as unknown as QuickPickItem)) .verifiable(TypeMoq.Times.once()); await setInterpreterCommand._enterOrBrowseInterpreterPath(multiStepInput.object, state, []); diff --git a/src/test/configuration/interpreterSelector/interpreterSelector.unit.test.ts b/src/test/configuration/interpreterSelector/interpreterSelector.unit.test.ts index 851d38492cb0..db77d5aedebd 100644 --- a/src/test/configuration/interpreterSelector/interpreterSelector.unit.test.ts +++ b/src/test/configuration/interpreterSelector/interpreterSelector.unit.test.ts @@ -38,7 +38,7 @@ class InterpreterQuickPickItem implements IInterpreterQuickPickItem { public detail?: string; - public interpreter = ({} as unknown) as PythonEnvironment; + public interpreter = {} as unknown as PythonEnvironment; constructor(l: string, p: string) { this.path = p; diff --git a/src/test/debugger/envVars.test.ts b/src/test/debugger/envVars.test.ts index e7b251b08a5f..0c2ee25a0e23 100644 --- a/src/test/debugger/envVars.test.ts +++ b/src/test/debugger/envVars.test.ts @@ -55,13 +55,13 @@ suite('Resolving Environment Variables when Debugging', () => { } async function testBasicProperties(console: ConsoleType, expectedNumberOfVariables: number) { - const args = ({ + const args = { program: '', pythonPath: '', args: [], envFile: '', console, - } as any) as LaunchRequestArguments; + } as any as LaunchRequestArguments; const envVars = await debugEnvParser.getEnvironmentVariables(args); expect(envVars).not.be.undefined; @@ -96,14 +96,14 @@ suite('Resolving Environment Variables when Debugging', () => { env[prop2] = prop2; mockProcess.env[prop3] = prop3; - const args = ({ + const args = { program: '', pythonPath: '', args: [], envFile: '', console, env, - } as any) as LaunchRequestArguments; + } as any as LaunchRequestArguments; const envVars = await debugEnvParser.getEnvironmentVariables(args); @@ -161,14 +161,14 @@ suite('Resolving Environment Variables when Debugging', () => { env[prop2] = prop2; mockProcess.env[prop3] = prop3; - const args = ({ + const args = { program: '', pythonPath: '', args: [], envFile: '', console, env, - } as any) as LaunchRequestArguments; + } as any as LaunchRequestArguments; const envVars = await debugEnvParser.getEnvironmentVariables(args); expect(envVars).not.be.undefined; diff --git a/src/test/debugger/extension/adapter/activator.unit.test.ts b/src/test/debugger/extension/adapter/activator.unit.test.ts index 529a76a69940..6e8be22d65c6 100644 --- a/src/test/debugger/extension/adapter/activator.unit.test.ts +++ b/src/test/debugger/extension/adapter/activator.unit.test.ts @@ -36,9 +36,9 @@ suite('Debugging - Adapter Factory and logger Registration', () => { setup(() => { const configurationService = mock(ConfigurationService); - when(configurationService.getSettings(undefined)).thenReturn(({ + when(configurationService.getSettings(undefined)).thenReturn({ experiments: { enabled: true }, - } as any) as IPythonSettings); + } as any as IPythonSettings); attachFactory = mock(AttachProcessProviderFactory); debugService = mock(DebugService); diff --git a/src/test/debugger/extension/adapter/factory.unit.test.ts b/src/test/debugger/extension/adapter/factory.unit.test.ts index b775c4241a0f..f38f779814af 100644 --- a/src/test/debugger/extension/adapter/factory.unit.test.ts +++ b/src/test/debugger/extension/adapter/factory.unit.test.ts @@ -65,9 +65,9 @@ suite('Debugging - Adapter Factory', () => { rewiremock('vscode-extension-telemetry').with({ default: Reporter }); const configurationService = mock(ConfigurationService); - when(configurationService.getSettings(undefined)).thenReturn(({ + when(configurationService.getSettings(undefined)).thenReturn({ experiments: { enabled: true }, - } as any) as IPythonSettings); + } as any as IPythonSettings); interpreterService = mock(InterpreterService); appShell = mock(ApplicationShell); diff --git a/src/test/debugger/extension/adapter/outdatedDebuggerPrompt.unit.test.ts b/src/test/debugger/extension/adapter/outdatedDebuggerPrompt.unit.test.ts index 42f37b5ad5c9..1976f0bd47a1 100644 --- a/src/test/debugger/extension/adapter/outdatedDebuggerPrompt.unit.test.ts +++ b/src/test/debugger/extension/adapter/outdatedDebuggerPrompt.unit.test.ts @@ -38,9 +38,9 @@ suite('Debugging - Outdated Debugger Prompt tests.', () => { setup(() => { const configurationService = mock(ConfigurationService); - when(configurationService.getSettings(undefined)).thenReturn(({ + when(configurationService.getSettings(undefined)).thenReturn({ experiments: { enabled: true }, - } as any) as IPythonSettings); + } as any as IPythonSettings); appShell = mock(ApplicationShell); browserService = mock(BrowserService); diff --git a/src/test/debugger/extension/attachQuickPick/provider.unit.test.ts b/src/test/debugger/extension/attachQuickPick/provider.unit.test.ts index 64d9103f3c5d..fdeda6af60f1 100644 --- a/src/test/debugger/extension/attachQuickPick/provider.unit.test.ts +++ b/src/test/debugger/extension/attachQuickPick/provider.unit.test.ts @@ -397,8 +397,7 @@ ProcessId=8026\r { label: 'python.exe', description: '8026', - detail: - 'C:\\Users\\Contoso\\AppData\\Local\\Programs\\Python\\Python37\\python.exe c:/Users/Contoso/Documents/foo_bar.py', + detail: 'C:\\Users\\Contoso\\AppData\\Local\\Programs\\Python\\Python37\\python.exe c:/Users/Contoso/Documents/foo_bar.py', id: '8026', processName: 'python.exe', commandLine: @@ -407,8 +406,7 @@ ProcessId=8026\r { label: 'python.exe', description: '6028', - detail: - 'C:\\Users\\Contoso\\AppData\\Local\\Programs\\Python\\Python37\\python.exe c:/Users/Contoso/Documents/hello_world.py', + detail: 'C:\\Users\\Contoso\\AppData\\Local\\Programs\\Python\\Python37\\python.exe c:/Users/Contoso/Documents/hello_world.py', id: '6028', processName: 'python.exe', commandLine: diff --git a/src/test/debugger/extension/attachQuickPick/wmicProcessParser.unit.test.ts b/src/test/debugger/extension/attachQuickPick/wmicProcessParser.unit.test.ts index e29490c47926..ba36cfdf61ec 100644 --- a/src/test/debugger/extension/attachQuickPick/wmicProcessParser.unit.test.ts +++ b/src/test/debugger/extension/attachQuickPick/wmicProcessParser.unit.test.ts @@ -70,8 +70,7 @@ ProcessId=6028\r\n\ { label: 'python.exe', description: '6028', - detail: - 'C:\\Users\\Contoso\\AppData\\Local\\Programs\\Python\\Python37\\python.exe c:/Users/Contoso/Documents/hello_world.py', + detail: 'C:\\Users\\Contoso\\AppData\\Local\\Programs\\Python\\Python37\\python.exe c:/Users/Contoso/Documents/hello_world.py', id: '6028', processName: 'python.exe', commandLine: @@ -148,8 +147,7 @@ ProcessId=6028\r\n\ { label: 'python.exe', description: '6028', - detail: - 'C:\\Users\\Contoso\\AppData\\Local\\Programs\\Python\\Python37\\python.exe c:/Users/Contoso/Documents/hello_world.py', + detail: 'C:\\Users\\Contoso\\AppData\\Local\\Programs\\Python\\Python37\\python.exe c:/Users/Contoso/Documents/hello_world.py', id: '6028', processName: 'python.exe', commandLine: @@ -199,8 +197,7 @@ ProcessId=6028\r\n\ { label: 'python.exe', description: '6028', - detail: - 'C:\\Users\\Contoso\\AppData\\Local\\Programs\\Python\\Python37\\python.exe c:/Users/Contoso/Documents/hello_world.py', + detail: 'C:\\Users\\Contoso\\AppData\\Local\\Programs\\Python\\Python37\\python.exe c:/Users/Contoso/Documents/hello_world.py', id: '6028', processName: 'python.exe', commandLine: diff --git a/src/test/debugger/extension/configuration/debugConfigurationService.unit.test.ts b/src/test/debugger/extension/configuration/debugConfigurationService.unit.test.ts index 8495d4820c0a..2c043ce40304 100644 --- a/src/test/debugger/extension/configuration/debugConfigurationService.unit.test.ts +++ b/src/test/debugger/extension/configuration/debugConfigurationService.unit.test.ts @@ -43,9 +43,9 @@ suite('Debugging - Configuration Service', () => { ); }); test('Should use attach resolver when passing attach config', async () => { - const config = ({ + const config = { request: 'attach', - } as any) as AttachRequestArguments; + } as any as AttachRequestArguments; const folder = { name: '1', index: 0, uri: Uri.parse('1234') }; const expectedConfig = { yay: 1 }; @@ -74,7 +74,7 @@ suite('Debugging - Configuration Service', () => { .setup((a) => a.resolveDebugConfiguration( typemoq.It.isValue(folder), - typemoq.It.isValue((config as any) as LaunchRequestArguments), + typemoq.It.isValue(config as any as LaunchRequestArguments), typemoq.It.isAny(), ), ) @@ -92,7 +92,7 @@ suite('Debugging - Configuration Service', () => { }); }); test('Picker should be displayed', async () => { - const state = ({ configs: [], folder: {}, token: undefined } as any) as DebugConfigurationState; + const state = { configs: [], folder: {}, token: undefined } as any as DebugConfigurationState; const multiStepInput = typemoq.Mock.ofType>(); multiStepInput .setup((i) => i.showQuickPick(typemoq.It.isAny())) @@ -104,7 +104,7 @@ suite('Debugging - Configuration Service', () => { multiStepInput.verifyAll(); }); test('Existing Configuration items must be removed before displaying picker', async () => { - const state = ({ configs: [1, 2, 3], folder: {}, token: undefined } as any) as DebugConfigurationState; + const state = { configs: [1, 2, 3], folder: {}, token: undefined } as any as DebugConfigurationState; const multiStepInput = typemoq.Mock.ofType>(); multiStepInput .setup((i) => i.showQuickPick(typemoq.It.isAny())) diff --git a/src/test/debugger/extension/configuration/providers/providerFactory.unit.test.ts b/src/test/debugger/extension/configuration/providers/providerFactory.unit.test.ts index a786347ed8d1..ec8962ee8f21 100644 --- a/src/test/debugger/extension/configuration/providers/providerFactory.unit.test.ts +++ b/src/test/debugger/extension/configuration/providers/providerFactory.unit.test.ts @@ -15,7 +15,7 @@ suite('Debugging - Configuration Provider Factory', () => { setup(() => { mappedProviders = new Map(); getNamesAndValues(DebugConfigurationType).forEach((item) => { - mappedProviders.set(item.value, (item.value as any) as IDebugConfigurationProvider); + mappedProviders.set(item.value, item.value as any as IDebugConfigurationProvider); }); factory = new DebugConfigurationProviderFactory( mappedProviders.get(DebugConfigurationType.launchFastAPI)!, diff --git a/src/test/debugger/extension/configuration/resolvers/launch.unit.test.ts b/src/test/debugger/extension/configuration/resolvers/launch.unit.test.ts index 93789c832526..86a174560a77 100644 --- a/src/test/debugger/extension/configuration/resolvers/launch.unit.test.ts +++ b/src/test/debugger/extension/configuration/resolvers/launch.unit.test.ts @@ -122,8 +122,9 @@ getInfoPerOS().forEach(([osName, osType, path]) => { return config; } - const interpreterPath = configService.object.getSettings(workspaceFolder ? workspaceFolder.uri : undefined) - .pythonPath; + const interpreterPath = configService.object.getSettings( + workspaceFolder ? workspaceFolder.uri : undefined, + ).pythonPath; for (const key of Object.keys(config)) { const value = config[key]; if (typeof value === 'string') { diff --git a/src/test/debugger/utils.ts b/src/test/debugger/utils.ts index 4a41489940b8..0f3cbbc84d5b 100644 --- a/src/test/debugger/utils.ts +++ b/src/test/debugger/utils.ts @@ -80,9 +80,9 @@ class DebugAdapterTracker { this.tracked.dapHandler(src, msg); } if (msg.type === 'event') { - const event = ((msg as unknown) as DebugProtocol.Event).event; + const event = (msg as unknown as DebugProtocol.Event).event; if (event === 'output') { - this.onOutputEvent((msg as unknown) as DebugProtocol.OutputEvent); + this.onOutputEvent(msg as unknown as DebugProtocol.OutputEvent); } } } @@ -233,12 +233,12 @@ class DebuggerSession { public handleDAPMessage(_src: DAPSource, baseMsg: DebugProtocol.ProtocolMessage) { if (baseMsg.type === 'event') { - const event = ((baseMsg as unknown) as DebugProtocol.Event).event; + const event = (baseMsg as unknown as DebugProtocol.Event).event; if (event === 'stopped') { - const msg = (baseMsg as unknown) as DebugProtocol.StoppedEvent; + const msg = baseMsg as unknown as DebugProtocol.StoppedEvent; this.stopped = { breakpoint: msg.body.reason === 'breakpoint', - threadId: (msg.body.threadId as unknown) as number, + threadId: msg.body.threadId as unknown as number, }; } else { // For now there aren't any other events we care about. diff --git a/src/test/extensionSettings.ts b/src/test/extensionSettings.ts index d3e96c030a49..f5e2f5d862af 100644 --- a/src/test/extensionSettings.ts +++ b/src/test/extensionSettings.ts @@ -35,7 +35,8 @@ export function getExtensionSettings(resource: Uri | undefined): IPythonSettings return undefined; } } - const pythonSettings = require('../client/common/configSettings') as typeof import('../client/common/configSettings'); + const pythonSettings = + require('../client/common/configSettings') as typeof import('../client/common/configSettings'); const workspaceService = new WorkspaceService(); const workspaceMemento = new MockMemento(); const globalMemento = new MockMemento(); diff --git a/src/test/initialize.ts b/src/test/initialize.ts index 1fce36607df5..bc479356073b 100644 --- a/src/test/initialize.ts +++ b/src/test/initialize.ts @@ -39,7 +39,7 @@ export async function initialize(): Promise { configSettings.PythonSettings.dispose(); } - return (api as any) as IExtensionTestApi; + return api as any as IExtensionTestApi; } export async function activateExtension() { const extension = vscode.extensions.getExtension(PVSC_EXTENSION_ID_FOR_TESTS)!; diff --git a/src/test/install/channelManager.channels.test.ts b/src/test/install/channelManager.channels.test.ts index 5e102a0a5182..b9f4947c4a9b 100644 --- a/src/test/install/channelManager.channels.test.ts +++ b/src/test/install/channelManager.channels.test.ts @@ -81,9 +81,7 @@ suite('Installation - installation channels', () => { .callback((i: string[]) => { items = i; }) - .returns( - () => new Promise((resolve, _reject) => resolve(undefined)), - ); + .returns(() => new Promise((resolve, _reject) => resolve(undefined))); installer1.setup((x) => x.displayName).returns(() => 'Name 1'); installer2.setup((x) => x.displayName).returns(() => 'Name 2'); @@ -101,9 +99,7 @@ suite('Installation - installation channels', () => { const installer = TypeMoq.Mock.ofType(); installer .setup((x) => x.isSupported(TypeMoq.It.isAny())) - .returns( - () => new Promise((resolve) => resolve(supported)), - ); + .returns(() => new Promise((resolve) => resolve(supported))); installer.setup((x) => x.priority).returns(() => priority || 0); serviceManager.addSingletonInstance(IModuleInstaller, installer.object, name); return installer; diff --git a/src/test/install/channelManager.messages.test.ts b/src/test/install/channelManager.messages.test.ts index c21612e8f56c..2eada46b85c4 100644 --- a/src/test/install/channelManager.messages.test.ts +++ b/src/test/install/channelManager.messages.test.ts @@ -160,9 +160,7 @@ suite('Installation - channel messages', () => { }; interpreters .setup((x) => x.getActiveInterpreter(TypeMoq.It.isAny())) - .returns( - () => new Promise((resolve, _reject) => resolve(activeInterpreter)), - ); + .returns(() => new Promise((resolve, _reject) => resolve(activeInterpreter))); const channels = new InstallationChannelManager(serviceContainer); let url = ''; @@ -174,9 +172,7 @@ suite('Installation - channel messages', () => { message = m; search = s; }) - .returns( - () => new Promise((resolve, _reject) => resolve(search)), - ); + .returns(() => new Promise((resolve, _reject) => resolve(search))); appShell .setup((x) => x.openUrl(TypeMoq.It.isAnyString())) .callback((s: string) => { diff --git a/src/test/interpreters/display.unit.test.ts b/src/test/interpreters/display.unit.test.ts index 9561aad47836..632098047d62 100644 --- a/src/test/interpreters/display.unit.test.ts +++ b/src/test/interpreters/display.unit.test.ts @@ -236,10 +236,10 @@ suite('Interpreters Display', () => { const expectedDisplayName = inExperiment ? '3.10.1' : 'Python 3.10.1'; setupWorkspaceFolder(resource, workspaceFolder); - const pythonInterpreter: PythonEnvironment = ({ + const pythonInterpreter: PythonEnvironment = { detailedDisplayName: displayName, path: pythonPath, - } as any) as PythonEnvironment; + } as any as PythonEnvironment; interpreterService .setup((i) => i.getActiveInterpreter(TypeMoq.It.isValue(workspaceFolder))) .returns(() => Promise.resolve(pythonInterpreter)); diff --git a/src/test/linters/lint.unit.test.ts b/src/test/linters/lint.unit.test.ts index b5468b9a8b27..a2f3e1b038a3 100644 --- a/src/test/linters/lint.unit.test.ts +++ b/src/test/linters/lint.unit.test.ts @@ -806,7 +806,7 @@ suite('Linting Products', () => { .map((key) => Product[Number(key)]); products.forEach((p) => { - const product = (p as unknown) as Product; + const product = p as unknown as Product; if (prodService.getProductType(product) === ProductType.Linter) { const found = LINTERID_BY_PRODUCT.get(product); assert.notStrictEqual(found, undefined, `did find linter ${Product[product]}`); diff --git a/src/test/linters/linterCommands.unit.test.ts b/src/test/linters/linterCommands.unit.test.ts index f73b0dea13ec..490f2826a72d 100644 --- a/src/test/linters/linterCommands.unit.test.ts +++ b/src/test/linters/linterCommands.unit.test.ts @@ -47,7 +47,7 @@ suite('Linting - Linter Commands', () => { }); test('Run Linting method will lint all open files', async () => { - when(lintingEngine.lintOpenPythonFiles()).thenResolve(('Hello' as unknown) as DiagnosticCollection); + when(lintingEngine.lintOpenPythonFiles()).thenResolve('Hello' as unknown as DiagnosticCollection); const result = await linterCommands.runLinting(); @@ -119,7 +119,7 @@ suite('Linting - Linter Commands', () => { test('Set Linter should display a quickpick and currently active linter when only one is enabled', async () => { const linterId = 'Hello World'; - const activeLinters: ILinterInfo[] = [({ id: linterId } as unknown) as ILinterInfo]; + const activeLinters: ILinterInfo[] = [{ id: linterId } as unknown as ILinterInfo]; when(manager.getAllLinterInfos()).thenReturn([]); when(manager.getActiveLinters(anything())).thenResolve(activeLinters); when(shell.showQuickPick(anything(), anything())).thenResolve(); @@ -137,7 +137,7 @@ suite('Linting - Linter Commands', () => { }); test('Set Linter should display a quickpick and with message about multiple linters being enabled', async () => { - const activeLinters: ILinterInfo[] = ([{ id: 'linterId' }, { id: 'linterId2' }] as unknown) as ILinterInfo[]; + const activeLinters: ILinterInfo[] = [{ id: 'linterId' }, { id: 'linterId2' }] as unknown as ILinterInfo[]; when(manager.getAllLinterInfos()).thenReturn([]); when(manager.getActiveLinters(anything())).thenResolve(activeLinters); when(shell.showQuickPick(anything(), anything())).thenResolve(); @@ -155,12 +155,12 @@ suite('Linting - Linter Commands', () => { }); test('Selecting a linter should display warning message about multiple linters', async () => { - const linters: ILinterInfo[] = ([ + const linters: ILinterInfo[] = [ { id: '1' }, { id: '2' }, { id: '3', product: 'Three' }, - ] as unknown) as ILinterInfo[]; - const activeLinters: ILinterInfo[] = ([{ id: '1' }, { id: '3' }] as unknown) as ILinterInfo[]; + ] as unknown as ILinterInfo[]; + const activeLinters: ILinterInfo[] = [{ id: '1' }, { id: '3' }] as unknown as ILinterInfo[]; when(manager.getAllLinterInfos()).thenReturn(linters); when(manager.getActiveLinters(anything())).thenResolve(activeLinters); when(shell.showQuickPick(anything(), anything())).thenReturn(Promise.resolve('3')); @@ -177,6 +177,6 @@ suite('Linting - Linter Commands', () => { verify(shell.showWarningMessage(anything(), 'Yes', 'No')).once(); const quickPickOptions = capture(shell.showQuickPick).last()[1]; expect(quickPickOptions).to.deep.equal(expectedQuickPickOptions); - verify(manager.setActiveLintersAsync(deepEqual([('Three' as unknown) as Product]), anything())).once(); + verify(manager.setActiveLintersAsync(deepEqual(['Three' as unknown as Product]), anything())).once(); }); }); diff --git a/src/test/linters/pylint.unit.test.ts b/src/test/linters/pylint.unit.test.ts index 2648dacd9ab5..cc27155555f5 100644 --- a/src/test/linters/pylint.unit.test.ts +++ b/src/test/linters/pylint.unit.test.ts @@ -40,7 +40,7 @@ suite('Pylint - Function runLinter()', () => { // eslint-disable-next-line class-methods-use-this public parseMessagesSeverity(_error: string, _categorySeverity: unknown): LintMessageSeverity { - return ('Severity' as unknown) as LintMessageSeverity; + return 'Severity' as unknown as LintMessageSeverity; } // eslint-disable-next-line class-methods-use-this @@ -91,7 +91,7 @@ suite('Pylint - Function runLinter()', () => { fileSystem .setup((x) => x.arePathsSame(TypeMoq.It.isAnyString(), TypeMoq.It.isAnyString())) .returns((a, b) => a === b); - manager.setup((m) => m.getLinterInfo(TypeMoq.It.isAny())).returns(() => (undefined as unknown) as ILinterInfo); + manager.setup((m) => m.getLinterInfo(TypeMoq.It.isAny())).returns(() => undefined as unknown as ILinterInfo); _info.setup((x) => x.id).returns(() => LinterId.PyLint); }); @@ -143,7 +143,7 @@ suite('Pylint - Function runLinter()', () => { parseMessagesSeverity.callsFake(() => 'LintMessageSeverity'); const pylint = new PylintTest(serviceContainer.object); const result = await pylint.runLinter(doc as vscode.TextDocument, mock(vscode.CancellationTokenSource).token); - assert.deepEqual(result, (expectedResult as unknown) as ILintMessage[]); + assert.deepEqual(result, expectedResult as unknown as ILintMessage[]); assert.ok(parseMessagesSeverity.calledOnce); assert.ok(run.calledOnce); }); diff --git a/src/test/mocks/autoSelector.ts b/src/test/mocks/autoSelector.ts index cc4ab4ddb8e5..efc25b227a12 100644 --- a/src/test/mocks/autoSelector.ts +++ b/src/test/mocks/autoSelector.ts @@ -14,7 +14,8 @@ import { PythonEnvironment } from '../../client/pythonEnvironments/info'; @injectable() export class MockAutoSelectionService - implements IInterpreterAutoSelectionService, IInterpreterAutoSelectionProxyService { + implements IInterpreterAutoSelectionService, IInterpreterAutoSelectionProxyService +{ // eslint-disable-next-line class-methods-use-this public async setWorkspaceInterpreter(_resource: Resource, _interpreter: PythonEnvironment): Promise { return Promise.resolve(); diff --git a/src/test/mocks/vsc/arrays.ts b/src/test/mocks/vsc/arrays.ts index c06cefa7c27f..2944d872021f 100644 --- a/src/test/mocks/vsc/arrays.ts +++ b/src/test/mocks/vsc/arrays.ts @@ -367,7 +367,7 @@ export function index(array: T[], indexer: (t: T) => string, merger?: (t: export function index( array: T[], indexer: (t: T) => string, - merger: (t: T, r: R) => R = (t) => (t as unknown) as R, + merger: (t: T, r: R) => R = (t) => t as unknown as R, ): Record { return array.reduce((r, t) => { const key = indexer(t); diff --git a/src/test/mocks/vsc/extHostedTypes.ts b/src/test/mocks/vsc/extHostedTypes.ts index fb25662ee3b5..a970185bb876 100644 --- a/src/test/mocks/vsc/extHostedTypes.ts +++ b/src/test/mocks/vsc/extHostedTypes.ts @@ -448,12 +448,12 @@ export class Selection extends Range { } toJSON(): [Position, Position] { - return ({ + return { start: this.start, end: this.end, active: this.active, anchor: this.anchor, - } as unknown) as [Position, Position]; + } as unknown as [Position, Position]; } } @@ -665,7 +665,7 @@ export class WorkspaceEdit implements vscode.WorkspaceEdit { set(uri: vscUri.URI, edits: TextEdit[]): void { let data = this._textEdits.get(uri.toString()); if (!data) { - data = { seq: this._seqPool += 1, uri, edits: [] }; + data = { seq: (this._seqPool += 1), uri, edits: [] }; this._textEdits.set(uri.toString(), data); } if (!edits) { @@ -901,7 +901,7 @@ export class Diagnostic { toJSON(): { severity: DiagnosticSeverity; message: string; range: Range; source: string; code: string | number } { return { - severity: (DiagnosticSeverity[this.severity] as unknown) as DiagnosticSeverity, + severity: DiagnosticSeverity[this.severity] as unknown as DiagnosticSeverity, message: this.message, range: this.range, source: this.source, @@ -953,7 +953,7 @@ export class DocumentHighlight { toJSON(): { range: Range; kind: DocumentHighlightKind } { return { range: this.range, - kind: (DocumentHighlightKind[this.kind] as unknown) as DocumentHighlightKind, + kind: DocumentHighlightKind[this.kind] as unknown as DocumentHighlightKind, }; } } @@ -1028,7 +1028,7 @@ export class SymbolInformation { toJSON(): { name: string; kind: SymbolKind; location: Location; containerName: string } { return { name: this.name, - kind: (SymbolKind[this.kind] as unknown) as SymbolKind, + kind: SymbolKind[this.kind] as unknown as SymbolKind, location: this.location, containerName: this.containerName, }; @@ -1289,7 +1289,7 @@ export class CompletionItem { return { label: this.label, label2: this.label2, - kind: this.kind && ((CompletionItemKind[this.kind] as unknown) as CompletionItemKind), + kind: this.kind && (CompletionItemKind[this.kind] as unknown as CompletionItemKind), detail: this.detail, documentation: this.documentation, sortText: this.sortText, diff --git a/src/test/mocks/vsc/index.ts b/src/test/mocks/vsc/index.ts index fcef8af923d1..b92fbcf576ee 100644 --- a/src/test/mocks/vsc/index.ts +++ b/src/test/mocks/vsc/index.ts @@ -56,7 +56,7 @@ export class EventEmitter implements vscode.EventEmitter { public emitter: NodeEventEmitter; constructor() { - this.event = (this.add.bind(this) as unknown) as vscode.Event; + this.event = this.add.bind(this) as unknown as vscode.Event; this.emitter = new NodeEventEmitter(); } diff --git a/src/test/proc.ts b/src/test/proc.ts index a25ae1aebfc0..6e3488a34748 100644 --- a/src/test/proc.ts +++ b/src/test/proc.ts @@ -51,7 +51,7 @@ export class Proc { private readonly output: ProcOutput; private result: ProcResult | undefined; constructor(raw: cp.ChildProcess, output: ProcOutput) { - this.raw = (raw as unknown) as IRawProc; + this.raw = raw as unknown as IRawProc; this.output = output; } public get pid(): number { diff --git a/src/test/proposedApi.unit.test.ts b/src/test/proposedApi.unit.test.ts index a85b04e23b70..fd50de949f64 100644 --- a/src/test/proposedApi.unit.test.ts +++ b/src/test/proposedApi.unit.test.ts @@ -41,7 +41,7 @@ suite('Proposed Extension API', () => { const pythonPath = 'this/is/a/test/path'; configService .setup((c) => c.getSettings(undefined)) - .returns(() => (({ pythonPath } as unknown) as IPythonSettings)); + .returns(() => ({ pythonPath } as unknown as IPythonSettings)); const actual = await proposed.environment.getActiveInterpreterPath(); expect(actual).to.be.equals(pythonPath); }); @@ -50,7 +50,7 @@ suite('Proposed Extension API', () => { const pythonPath = 'this/is/a/test/path'; configService .setup((c) => c.getSettings(resource)) - .returns(() => (({ pythonPath } as unknown) as IPythonSettings)); + .returns(() => ({ pythonPath } as unknown as IPythonSettings)); const actual = await proposed.environment.getActiveInterpreterPath(resource); expect(actual).to.be.equals(pythonPath); }); diff --git a/src/test/providers/codeActionProvider/main.unit.test.ts b/src/test/providers/codeActionProvider/main.unit.test.ts index 55644d80ae54..227c162f2ae4 100644 --- a/src/test/providers/codeActionProvider/main.unit.test.ts +++ b/src/test/providers/codeActionProvider/main.unit.test.ts @@ -48,7 +48,7 @@ suite('Code Action Provider service', async () => { pattern: '**/launch.json', }); assert.deepEqual(metadata!, { - providedCodeActionKinds: [('CodeAction' as unknown) as CodeActionKind], + providedCodeActionKinds: ['CodeAction' as unknown as CodeActionKind], }); expect(provider!).instanceOf(LaunchJsonCodeActionProvider); }); diff --git a/src/test/pythonEnvironments/base/info/environmentInfoService.functional.test.ts b/src/test/pythonEnvironments/base/info/environmentInfoService.functional.test.ts index 6485208904a8..7695f41b71a7 100644 --- a/src/test/pythonEnvironments/base/info/environmentInfoService.functional.test.ts +++ b/src/test/pythonEnvironments/base/info/environmentInfoService.functional.test.ts @@ -47,8 +47,7 @@ suite('Environment Info Service', () => { 'shellExecute', new Promise>((resolve) => { resolve({ - stdout: - '{"versionInfo": [3, 8, 3, "final", 0], "sysPrefix": "path", "sysVersion": "3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]", "is64Bit": true}', + stdout: '{"versionInfo": [3, 8, 3, "final", 0], "sysPrefix": "path", "sysVersion": "3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]", "is64Bit": true}', stderr: 'Some std error', // This should be ignored. }); }), diff --git a/src/test/pythonEnvironments/base/locatorUtils.unit.test.ts b/src/test/pythonEnvironments/base/locatorUtils.unit.test.ts index c9527f4a52ee..0b99b7f1e7c9 100644 --- a/src/test/pythonEnvironments/base/locatorUtils.unit.test.ts +++ b/src/test/pythonEnvironments/base/locatorUtils.unit.test.ts @@ -85,14 +85,16 @@ suite('Python envs locator utils - getQueryFilter', () => { assert.deepEqual(filtered, []); }); - ([ - [PythonEnvKind.Unknown, [env3]], - [PythonEnvKind.System, [env1, env5]], - [PythonEnvKind.WindowsStore, []], - [PythonEnvKind.Pyenv, [env2, env4]], - [PythonEnvKind.Venv, [envL1, envSL1, envSL5]], - [PythonEnvKind.Conda, [env6, envL2, envSL3]], - ] as [PythonEnvKind, PythonEnvInfo[]][]).forEach(([kind, expected]) => { + ( + [ + [PythonEnvKind.Unknown, [env3]], + [PythonEnvKind.System, [env1, env5]], + [PythonEnvKind.WindowsStore, []], + [PythonEnvKind.Pyenv, [env2, env4]], + [PythonEnvKind.Venv, [envL1, envSL1, envSL5]], + [PythonEnvKind.Conda, [env6, envL2, envSL3]], + ] as [PythonEnvKind, PythonEnvInfo[]][] + ).forEach(([kind, expected]) => { test(`match some (one kind: ${kind})`, () => { const query: PythonLocatorQuery = { kinds: [kind] }; diff --git a/src/test/pythonEnvironments/base/locators/composite/envsResolver.unit.test.ts b/src/test/pythonEnvironments/base/locators/composite/envsResolver.unit.test.ts index 3d6dcd528912..f460e017ccdc 100644 --- a/src/test/pythonEnvironments/base/locators/composite/envsResolver.unit.test.ts +++ b/src/test/pythonEnvironments/base/locators/composite/envsResolver.unit.test.ts @@ -97,8 +97,7 @@ suite('Python envs locator - Environments Resolver', () => { 'shellExecute', new Promise>((resolve) => { resolve({ - stdout: - '{"versionInfo": [3, 8, 3, "final", 0], "sysPrefix": "path", "sysVersion": "3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]", "is64Bit": true}', + stdout: '{"versionInfo": [3, 8, 3, "final", 0], "sysPrefix": "path", "sysVersion": "3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]", "is64Bit": true}', }); }), ); @@ -248,8 +247,7 @@ suite('Python envs locator - Environments Resolver', () => { 'shellExecute', new Promise>((resolve) => { resolve({ - stdout: - '{"versionInfo": [3, 8, 3, "final", 0], "sysPrefix": "path", "sysVersion": "3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]", "is64Bit": true}', + stdout: '{"versionInfo": [3, 8, 3, "final", 0], "sysPrefix": "path", "sysVersion": "3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]", "is64Bit": true}', }); }), ); diff --git a/src/test/pythonEnvironments/common/environmentManagers/conda.unit.test.ts b/src/test/pythonEnvironments/common/environmentManagers/conda.unit.test.ts index cdfd3284891d..e2e1f192a568 100644 --- a/src/test/pythonEnvironments/common/environmentManagers/conda.unit.test.ts +++ b/src/test/pythonEnvironments/common/environmentManagers/conda.unit.test.ts @@ -139,21 +139,19 @@ suite('Conda and its environments are located correctly', () => { return names; } - return names.map( - (name): fs.Dirent => { - const isFile = typeof dir[name] === 'string'; - return { - name, - isFile: () => isFile, - isDirectory: () => !isFile, - isBlockDevice: () => false, - isCharacterDevice: () => false, - isSymbolicLink: () => false, - isFIFO: () => false, - isSocket: () => false, - }; - }, - ); + return names.map((name): fs.Dirent => { + const isFile = typeof dir[name] === 'string'; + return { + name, + isFile: () => isFile, + isDirectory: () => !isFile, + isBlockDevice: () => false, + isCharacterDevice: () => false, + isSymbolicLink: () => false, + isFIFO: () => false, + isSocket: () => false, + }; + }); }); sinon diff --git a/src/test/tensorBoard/tensorBoardSession.test.ts b/src/test/tensorBoard/tensorBoardSession.test.ts index 447cf8d470e3..96218c919ebf 100644 --- a/src/test/tensorBoard/tensorBoardSession.test.ts +++ b/src/test/tensorBoard/tensorBoardSession.test.ts @@ -495,7 +495,7 @@ suite('TensorBoard session creation', async () => { return [showQuickPickStub, createInputStub, filePickerStub]; } test('Resolves filepaths without displaying prompt', async () => { - const session = ((await createSession()) as unknown) as ITensorBoardSessionTestAPI; + const session = (await createSession()) as unknown as ITensorBoardSessionTestAPI; const stubs = setupStubsForMultiStepInput(); await session.jumpToSource(fsPath, 0); assert.ok(window.activeTextEditor !== undefined, 'Source file not resolved'); @@ -506,7 +506,7 @@ suite('TensorBoard session creation', async () => { ); }); test('Display quickpick to user if filepath is not on disk', async () => { - const session = ((await createSession()) as unknown) as ITensorBoardSessionTestAPI; + const session = (await createSession()) as unknown as ITensorBoardSessionTestAPI; const stubs = setupStubsForMultiStepInput(); await session.jumpToSource('/nonexistent/file/path.py', 0); assert.ok(window.activeTextEditor !== undefined, 'Source file not resolved'); diff --git a/src/test/terminals/activation.unit.test.ts b/src/test/terminals/activation.unit.test.ts index dea0c891229d..97898e7da6ba 100644 --- a/src/test/terminals/activation.unit.test.ts +++ b/src/test/terminals/activation.unit.test.ts @@ -37,7 +37,7 @@ suite('Terminal', () => { instance(resourceService), ); - terminal = ({ + terminal = { dispose: noop, hide: noop, name: 'Some Name', @@ -46,8 +46,8 @@ suite('Terminal', () => { sendText: noop, show: noop, exitStatus: { code: 0 }, - } as unknown) as Terminal; - nonActivatedTerminal = ({ + } as unknown as Terminal; + nonActivatedTerminal = { dispose: noop, hide: noop, creationOptions: { hideFromUser: true }, @@ -56,7 +56,7 @@ suite('Terminal', () => { sendText: noop, show: noop, exitStatus: { code: 0 }, - } as unknown) as Terminal; + } as unknown as Terminal; autoActivation.register(); }); // teardown(() => fakeTimer.uninstall()); @@ -64,7 +64,7 @@ suite('Terminal', () => { test('Should activate terminal', async () => { // Trigger opening a terminal. - await ((onDidOpenTerminalEventEmitter.fire(terminal) as unknown) as Promise); + await (onDidOpenTerminalEventEmitter.fire(terminal) as unknown as Promise); // The terminal should get activated. verify(activator.activateEnvironmentInTerminal(terminal, anything())).once(); @@ -72,7 +72,7 @@ suite('Terminal', () => { test('Should not activate terminal if name starts with specific prefix', async () => { // Trigger opening a terminal. - await ((onDidOpenTerminalEventEmitter.fire(nonActivatedTerminal) as unknown) as Promise); + await (onDidOpenTerminalEventEmitter.fire(nonActivatedTerminal) as unknown as Promise); // The terminal should get activated. verify(activator.activateEnvironmentInTerminal(anything(), anything())).never(); diff --git a/src/test/terminals/codeExecution/helper.test.ts b/src/test/terminals/codeExecution/helper.test.ts index 9771a0b8713f..a291440dfc5f 100644 --- a/src/test/terminals/codeExecution/helper.test.ts +++ b/src/test/terminals/codeExecution/helper.test.ts @@ -97,7 +97,7 @@ suite('Terminal - Code Execution Helper', () => { .setup((p) => p.execObservable(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny())) .returns((_, args: string[]) => { execArgs = args.join(' '); - return ({} as unknown) as ObservableExecutionResult; + return {} as unknown as ObservableExecutionResult; }); await helper.normalizeLines('print("hello")'); diff --git a/src/test/terminals/codeExecution/terminalCodeExec.unit.test.ts b/src/test/terminals/codeExecution/terminalCodeExec.unit.test.ts index 8fcc308d99e8..c1bcdb702298 100644 --- a/src/test/terminals/codeExecution/terminalCodeExec.unit.test.ts +++ b/src/test/terminals/codeExecution/terminalCodeExec.unit.test.ts @@ -514,7 +514,7 @@ suite('Terminal - Code Execution', () => { await executor.execute(''); await executor.execute(' '); - await executor.execute((undefined as any) as string); + await executor.execute(undefined as any as string); terminalService.verify( async (t) => t.sendCommand(TypeMoq.It.isAny(), TypeMoq.It.isAny()), diff --git a/src/test/terminals/serviceRegistry.unit.test.ts b/src/test/terminals/serviceRegistry.unit.test.ts index 38a9a9744e91..3f4561c03612 100644 --- a/src/test/terminals/serviceRegistry.unit.test.ts +++ b/src/test/terminals/serviceRegistry.unit.test.ts @@ -44,7 +44,7 @@ suite('Terminal - Service Registry', () => { typemoq.It.is((v) => args[0] === v), typemoq.It.is((value) => args[1] === value), - typemoq.It.isValue((args[2] as unknown) as string), + typemoq.It.isValue(args[2] as unknown as string), ), ) .verifiable(typemoq.Times.once()); diff --git a/src/test/testBootstrap.ts b/src/test/testBootstrap.ts index 03f24a680d0d..2e5ba8d0712e 100644 --- a/src/test/testBootstrap.ts +++ b/src/test/testBootstrap.ts @@ -88,16 +88,13 @@ async function startSocketServer() { }); }); - server.listen( - { host: '127.0.0.1', port: 0 }, - async (): Promise => { - const port = (server!.address() as AddressInfo).port; - console.log(`Test server listening on port ${port}`); - await deletePortFile(); - await fs.writeFile(portFile, port.toString()); - resolve(); - }, - ); + server.listen({ host: '127.0.0.1', port: 0 }, async (): Promise => { + const port = (server!.address() as AddressInfo).port; + console.log(`Test server listening on port ${port}`); + await deletePortFile(); + await fs.writeFile(portFile, port.toString()); + resolve(); + }); server.on('error', (ex) => { // Just log it, no need to do anything else. console.error(ex); diff --git a/typings/index.d.ts b/typings/index.d.ts index eed574565d66..7003ea5043b7 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -1,8 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. - // Added to allow compilation of backbone types pulled in from ipywidgets (@jupyterlab/widgets). -declare module JQuery { - type TriggeredEvent = any; +declare namespace JQuery { + type TriggeredEvent = unknown; }