diff --git a/.vscode/tasks.json b/.vscode/tasks.json index fe14014a..87453033 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -36,8 +36,8 @@ ], "background": { "activeOnStart": true, - "beginsPattern": "Compilation \\w+ starting…", - "endsPattern": "Compilation\\s+finished" + "beginsPattern": "assets by status", + "endsPattern": "compiled successfully in" } } } diff --git a/package-lock.json b/package-lock.json index 6348dc2d..929a8bf3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "dependencies": { "@fabric8-analytics/fabric8-analytics-lsp-server": "^0.9.4-ea.28", "@redhat-developer/vscode-redhat-telemetry": "^0.8.0", - "@trustification/exhort-javascript-api": "^0.1.1-ea.54", + "@trustification/exhort-javascript-api": "^0.1.1-ea.62", "fs": "^0.0.1-security", "path": "^0.12.7", "vscode-languageclient": "^8.1.0" @@ -910,9 +910,9 @@ "dev": true }, "node_modules/@trustification/exhort-javascript-api": { - "version": "0.1.1-ea.54", - "resolved": "https://npm.pkg.github.com/download/@trustification/exhort-javascript-api/0.1.1-ea.54/aae647f54b19514204c3dd98d554ae4513350d4e", - "integrity": "sha512-rep69WMzo7s8PUxuPCgnExe3cvBFxpGj1qMpBGzpUcbzBuLsDTr2YbbExpALzhtsnO05LfowInp1FERTEeX8nQ==", + "version": "0.1.1-ea.62", + "resolved": "https://npm.pkg.github.com/download/@trustification/exhort-javascript-api/0.1.1-ea.62/7fb821648ea3f6342c6137bd89ed9e94c550138f", + "integrity": "sha512-wvZWneHLkzYaf8BewySHmhBCmLz33nYX/Y1bXIoWXrHsZ4DwxhovJeWQXodJkx/KbwbGWYFS7OvQkEggP4+aug==", "license": "Apache-2.0", "dependencies": { "@babel/core": "^7.23.2", diff --git a/package.json b/package.json index 7713d1d7..9253f5af 100644 --- a/package.json +++ b/package.json @@ -385,7 +385,7 @@ "dependencies": { "@fabric8-analytics/fabric8-analytics-lsp-server": "^0.9.4-ea.28", "@redhat-developer/vscode-redhat-telemetry": "^0.8.0", - "@trustification/exhort-javascript-api": "^0.1.1-ea.54", + "@trustification/exhort-javascript-api": "^0.1.1-ea.62", "fs": "^0.0.1-security", "path": "^0.12.7", "vscode-languageclient": "^8.1.0" diff --git a/src/config.ts b/src/config.ts index 5cb4a9aa..267b1fe4 100644 --- a/src/config.ts +++ b/src/config.ts @@ -153,7 +153,7 @@ class Config { * Authorizes the RHDA (Red Hat Dependency Analytics) service. * @param context The extension context for authorization. */ - async authorizeRHDA(context): Promise { + async authorizeRHDA(context: vscode.ExtensionContext): Promise { this.telemetryId = await getTelemetryId(context); await this.setProcessEnv(); } @@ -214,7 +214,6 @@ class Config { } else { console.error(errorMsg); } - } } } diff --git a/src/exhortServices.ts b/src/exhortServices.ts index 4c32adc1..479f5065 100644 --- a/src/exhortServices.ts +++ b/src/exhortServices.ts @@ -12,36 +12,29 @@ import { IImageRef, IOptions } from './imageAnalysis'; * @param options - The options for running image analysis. * @returns A Promise resolving to the analysis response in HTML format. */ -function imageAnalysisService(images: IImageRef[], options: IOptions): Promise { - return new Promise(async (resolve, reject) => { - const jarPath = `${__dirname}/../javaApiAdapter/exhort-java-api-adapter-1.0-SNAPSHOT-jar-with-dependencies.jar`; - const reportType = 'html'; - let parameters = ''; - let properties = ''; +async function imageAnalysisService(images: IImageRef[], options: IOptions): Promise { + const jarPath = `${__dirname}/../javaApiAdapter/exhort-java-api-adapter-1.0-SNAPSHOT-jar-with-dependencies.jar`; + const reportType = 'html'; + let parameters = ''; + let properties = ''; - images.forEach(image => { - if (image.platform) { - parameters += ` ${image.image}^^${image.platform}`; - } else { - parameters += ` ${image.image}`; - } - }); - - for (const setting in options) { - if (options[setting]) { - properties += ` -D${setting}=${options[setting]}`; - } + images.forEach(image => { + if (image.platform) { + parameters += ` ${image.image}^^${image.platform}`; + } else { + parameters += ` ${image.image}`; } + }); - try { - const result = execSync(`java${properties} -jar ${jarPath} ${reportType}${parameters}`, { - maxBuffer: 1000 * 1000 * 10, // 10 MB - }); - resolve(result.toString()); - } catch (error) { - reject(error); + for (const setting in options) { + if (options[setting]) { + properties += ` -D${setting}=${options[setting]}`; } - }); + } + + return execSync(`java${properties} -jar ${jarPath} ${reportType}${parameters}`, { + maxBuffer: 1000 * 1000 * 10, // 10 MB + }).toString(); } /** @@ -50,16 +43,9 @@ function imageAnalysisService(images: IImageRef[], options: IOptions): Promise { - return new Promise(async (resolve, reject) => { - try { - // Get stack analysis in HTML format - const stackAnalysisReportHtml = await exhort.stackAnalysis(pathToManifest, true, options); - resolve(stackAnalysisReportHtml); - } catch (error) { - reject(error); - } - }); +async function stackAnalysisService(pathToManifest: string, options: object): Promise { + // Get stack analysis in HTML format + return await exhort.stackAnalysis(pathToManifest, true, options); } /** @@ -68,35 +54,25 @@ function stackAnalysisService(pathToManifest: string, options: object): Promise< * @param source The source for which the token is being validated. * @returns A promise resolving after validating the token. */ -async function tokenValidationService(options, source): Promise { +async function tokenValidationService(options: object, source: string): Promise { try { - // Get token validation status code const tokenValidationStatus = await exhort.validateToken(options); - if ( - tokenValidationStatus === 200 - ) { - vscode.window.showInformationMessage(`${source} token validated successfully`); - return; - } else if ( - tokenValidationStatus === 400 - ) { - return `Missing token. Please provide a valid ${source} Token in the extension workspace settings. Status: ${tokenValidationStatus}`; - } else if ( - tokenValidationStatus === 401 - ) { - return `Invalid token. Please provide a valid ${source} Token in the extension workspace settings. Status: ${tokenValidationStatus}`; - } else if ( - tokenValidationStatus === 403 - ) { - return `Forbidden. The token does not have permissions. Please provide a valid ${source} Token in the extension workspace settings. Status: ${tokenValidationStatus}`; - } else if ( - tokenValidationStatus === 429 - ) { - return `Too many requests. Rate limit exceeded. Please try again in a little while. Status: ${tokenValidationStatus}`; - } else { - return `Failed to validate token. Status: ${tokenValidationStatus}`; + switch (tokenValidationStatus) { + case 200: + vscode.window.showInformationMessage(`${source} token validated successfully`); + return; + case 400: + return `Missing token. Please provide a valid ${source} Token in the extension workspace settings. Status: ${tokenValidationStatus}`; + case 401: + return `Invalid token. Please provide a valid ${source} Token in the extension workspace settings. Status: ${tokenValidationStatus}`; + case 403: + return `Forbidden. The token does not have permissions. Please provide a valid ${source} Token in the extension workspace settings. Status: ${tokenValidationStatus}`; + case 429: + return `Too many requests. Rate limit exceeded. Please try again in a little while. Status: ${tokenValidationStatus}`; + default: + return `Failed to validate token. Status: ${tokenValidationStatus}`; } } catch (error) { return `Failed to validate token, Error: ${error.message}`; diff --git a/src/extension.ts b/src/extension.ts index f53f54f5..b8ddbd43 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -81,26 +81,6 @@ export function activate(context: vscode.ExtensionContext) { } ); - // const disposableSetSnykToken = vscode.commands.registerCommand( - // commands.SET_SNYK_TOKEN_COMMAND, - // async () => { - // const token = await vscode.window.showInputBox({ - // prompt: 'Please enter your Snyk Token:', - // placeHolder: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', - // password: true, - // validateInput: validateSnykToken - // }); - - // if (token === undefined) { - // return; - // } else if (token === '') { - // await globalConfig.clearSnykToken(true); - // } else { - // await globalConfig.setSnykToken(token); - // } - // } - // ); - registerStackAnalysisCommands(context); globalConfig.authorizeRHDA(context) @@ -157,8 +137,7 @@ export function activate(context: vscode.ExtensionContext) { if (selection === PromptText.FULL_STACK_PROMPT_TEXT) { record(context, TelemetryActions.vulnerabilityReportPopupOpened, { manifest: fileName, fileName: fileName }); vscode.commands.executeCommand(commands.STACK_ANALYSIS_COMMAND, filePath); - } - else { + } else { record(context, TelemetryActions.vulnerabilityReportPopupIgnored, { manifest: fileName, fileName: fileName }); } }; @@ -194,19 +173,12 @@ export function activate(context: vscode.ExtensionContext) { }) .catch(error => { vscode.window.showErrorMessage(`Failed to Authorize Red Hat Dependency Analytics extension: ${error.message}`); - throw (error); + throw error; }); vscode.workspace.onDidChangeConfiguration(() => { globalConfig.loadData(); }); - - // context.secrets.onDidChange(async (e) => { - // if (e.key === SNYK_TOKEN_KEY) { - // const token = await globalConfig.getSnykToken(); - // lspClient.sendNotification('snykTokenModified', token); - // } - // }); } /** @@ -214,10 +186,7 @@ export function activate(context: vscode.ExtensionContext) { * @returns A `Thenable` for void. */ export function deactivate(): Thenable { - if (!lspClient) { - return undefined; - } - return lspClient.stop(); + return lspClient?.stop(); } /** @@ -263,10 +232,10 @@ function redirectToRedHatCatalog() { * Shows a notification regarding Red Hat Dependency Analytics recommendations. */ function showRHRepositoryRecommendationNotification() { - const msg = `Important: If you apply Red Hat Dependency Analytics recommendations, - make sure the Red Hat GA Repository (${REDHAT_MAVEN_REPOSITORY}) has been added to your project configuration. - This ensures that the applied dependencies work correctly. - Learn how to add the repository: [Click here](${REDHAT_MAVEN_REPOSITORY_DOCUMENTATION_URL})`; + const msg = 'Important: If you apply Red Hat Dependency Analytics recommendations, ' + + `make sure the Red Hat GA Repository (${REDHAT_MAVEN_REPOSITORY}) has been added to your project configuration. ` + + 'This ensures that the applied dependencies work correctly. ' + + `Learn how to add the repository: [Click here](${REDHAT_MAVEN_REPOSITORY_DOCUMENTATION_URL})`; vscode.window.showWarningMessage(msg); } diff --git a/src/imageAnalysis.ts b/src/imageAnalysis.ts index 85d39925..6980c1a5 100644 --- a/src/imageAnalysis.ts +++ b/src/imageAnalysis.ts @@ -78,6 +78,7 @@ class DockerImageAnalysis implements IImageAnalysis { args: Map = new Map(); images: IImageRef[] = []; imageAnalysisReportHtml: string = ''; + filePath: string; /** * Regular expression for matching 'FROM' statements. @@ -101,20 +102,18 @@ class DockerImageAnalysis implements IImageAnalysis { constructor(filePath: string) { const lines = this.parseTxtDoc(filePath); - + this.filePath = filePath; this.images = this.collectImages(lines); } parseTxtDoc(filePath: string): string[] { try { const contentBuffer = fs.readFileSync(filePath); - const contentString = contentBuffer.toString('utf-8'); - return contentString.split('\n'); } catch (err) { updateCurrentWebviewPanel('error'); - throw (err); + throw err; } } @@ -179,43 +178,29 @@ class DockerImageAnalysis implements IImageAnalysis { } async runImageAnalysis() { - try { - return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: Titles.EXT_TITLE }, async p => { - return new Promise(async (resolve, reject) => { - p.report({ - message: StatusMessages.WIN_ANALYZING_DEPENDENCIES - }); - - // execute image analysis - await imageAnalysisService(this.images, this.options) - .then(async (resp) => { - p.report({ - message: StatusMessages.WIN_GENERATING_DEPENDENCIES - }); - - updateCurrentWebviewPanel(resp); - - p.report({ - message: StatusMessages.WIN_SUCCESS_DEPENDENCY_ANALYSIS - }); - - this.imageAnalysisReportHtml = resp; - - resolve(); - }) - .catch(err => { - p.report({ - message: StatusMessages.WIN_FAILURE_DEPENDENCY_ANALYSIS - }); - - reject(err); - }); - }); - }); - } catch (err) { - updateCurrentWebviewPanel('error'); - throw (err); - } + return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: Titles.EXT_TITLE }, async p => { + p.report({ message: StatusMessages.WIN_ANALYZING_DEPENDENCIES }); + + try { + + // execute image analysis + const promise = imageAnalysisService(this.images, this.options); + p.report({ message: StatusMessages.WIN_GENERATING_DEPENDENCIES }); + + const resp = await promise; + updateCurrentWebviewPanel(resp); + + p.report({ message: StatusMessages.WIN_SUCCESS_DEPENDENCY_ANALYSIS }); + + this.imageAnalysisReportHtml = resp; + } catch (error) { + p.report({ message: StatusMessages.WIN_FAILURE_DEPENDENCY_ANALYSIS }); + + updateCurrentWebviewPanel('error'); + + throw error; + } + }); } } @@ -225,13 +210,9 @@ class DockerImageAnalysis implements IImageAnalysis { * @returns A Promise resolving to an Analysis Report HTML. */ async function executeDockerImageAnalysis(filePath: string): Promise { - try { - const dockerImageAnalysis = new DockerImageAnalysis(filePath); - await dockerImageAnalysis.runImageAnalysis(); - return dockerImageAnalysis.imageAnalysisReportHtml; - } catch (error) { - throw (error); - } + const dockerImageAnalysis = new DockerImageAnalysis(filePath); + await dockerImageAnalysis.runImageAnalysis(); + return dockerImageAnalysis.imageAnalysisReportHtml; } export { executeDockerImageAnalysis, IImageRef, IOptions }; \ No newline at end of file diff --git a/src/redhatTelemetry.ts b/src/redhatTelemetry.ts index e43abadc..e6eca903 100644 --- a/src/redhatTelemetry.ts +++ b/src/redhatTelemetry.ts @@ -66,7 +66,7 @@ async function startUp(context: vscode.ExtensionContext) { * @param context The extension context. * @returns A promise resolving to the telemetry ID. */ -async function getTelemetryId(context) { +async function getTelemetryId(context: vscode.ExtensionContext) { const redhatService = await getRedHatService(context); const redhatIdProvider = await redhatService.getIdProvider(); const telemetryId = await redhatIdProvider.getRedHatUUID(); diff --git a/src/rhda.ts b/src/rhda.ts index a1e0bf39..b7c4880b 100644 --- a/src/rhda.ts +++ b/src/rhda.ts @@ -59,7 +59,7 @@ function getFileType(filePath: string): supportedFileTypes | undefined { * @param context The extension context. * @returns A Promise that resolves once the webview panel has been triggered. */ -async function triggerWebviewPanel(context) { +async function triggerWebviewPanel(context: vscode.ExtensionContext) { await globalConfig.authorizeRHDA(context); DependencyReportPanel.createOrShowWebviewPanel(); } @@ -78,25 +78,16 @@ function updateCurrentWebviewPanel(data) { /** * Writes the report data to a file. * @param data The data to write to the file. - * @returns A promise that resolves once the file is written. */ -function writeReportToFile(data) { - return new Promise((resolve, reject) => { - const reportFilePath = globalConfig.rhdaReportFilePath; - const reportDirectoryPath = path.dirname(reportFilePath); +async function writeReportToFile(data: string) { + const reportFilePath = globalConfig.rhdaReportFilePath; + const reportDirectoryPath = path.dirname(reportFilePath); - if (!fs.existsSync(reportDirectoryPath)) { - fs.mkdirSync(reportDirectoryPath, { recursive: true }); - } + if (!fs.existsSync(reportDirectoryPath)) { + fs.mkdirSync(reportDirectoryPath, { recursive: true }); + } - fs.writeFile(reportFilePath, data, (err) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); - }); + await fs.promises.writeFile(reportFilePath, data); } /** @@ -105,30 +96,22 @@ function writeReportToFile(data) { * @param filePath The path of the file for analysis. * @returns A promise that resolves once the report generation is complete. */ -async function generateRHDAReport(context, filePath) { +async function generateRHDAReport(context: vscode.ExtensionContext, filePath: string) { const fileType = getFileType(filePath); if (fileType) { - try { - - await triggerWebviewPanel(context); - let resp: string; - if (fileType === 'docker') { - resp = await executeDockerImageAnalysis(filePath); - } else { - resp = await executeStackAnalysis(filePath); - } - /* istanbul ignore else */ - if (DependencyReportPanel.currentPanel) { - await writeReportToFile(resp); - } - - } catch (error) { - throw (error); + await triggerWebviewPanel(context); + let resp: string; + if (fileType === 'docker') { + resp = await executeDockerImageAnalysis(filePath); + } else { + resp = await executeStackAnalysis(filePath); + } + /* istanbul ignore else */ + if (DependencyReportPanel.currentPanel) { + await writeReportToFile(resp); } } else { - vscode.window.showInformationMessage( - `File ${filePath} is not supported!!` - ); + vscode.window.showInformationMessage(`File ${filePath} is not supported.`); } } diff --git a/src/stackAnalysis.ts b/src/stackAnalysis.ts index 0a41f4a3..8aab69f7 100644 --- a/src/stackAnalysis.ts +++ b/src/stackAnalysis.ts @@ -14,65 +14,48 @@ import { updateCurrentWebviewPanel } from './rhda'; * @returns The stack analysis response string. */ export async function executeStackAnalysis(manifestFilePath: string): Promise { - try { - return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: Titles.EXT_TITLE }, async p => { - return new Promise(async (resolve, reject) => { - p.report({ - message: StatusMessages.WIN_ANALYZING_DEPENDENCIES - }); - - // set up configuration options for the stack analysis request - const options = { - 'RHDA_TOKEN': globalConfig.telemetryId, - 'RHDA_SOURCE': globalConfig.utmSource, - 'MATCH_MANIFEST_VERSIONS': globalConfig.matchManifestVersions, - 'EXHORT_PYTHON_VIRTUAL_ENV': globalConfig.usePythonVirtualEnvironment, - 'EXHORT_GO_MVS_LOGIC_ENABLED': globalConfig.useGoMVS, - 'EXHORT_PYTHON_INSTALL_BEST_EFFORTS': globalConfig.enablePythonBestEffortsInstallation, - 'EXHORT_PIP_USE_DEP_TREE': globalConfig.usePipDepTree, - 'EXHORT_MVN_PATH': globalConfig.exhortMvnPath, - 'EXHORT_PREFER_MVNW': globalConfig.exhortPreferMvnw, - 'EXHORT_GRADLE_PATH': globalConfig.exhortGradlePath, - 'EXHORT_NPM_PATH': globalConfig.exhortNpmPath, - 'EXHORT_GO_PATH': globalConfig.exhortGoPath, - 'EXHORT_PYTHON3_PATH': globalConfig.exhortPython3Path, - 'EXHORT_PIP3_PATH': globalConfig.exhortPip3Path, - 'EXHORT_PYTHON_PATH': globalConfig.exhortPythonPath, - 'EXHORT_PIP_PATH': globalConfig.exhortPipPath - }; - - // const snykToken = await globalConfig.getSnykToken(); - // /* istanbul ignore else */ - // if (snykToken !== '') { - // options['EXHORT_SNYK_TOKEN'] = snykToken; - // } - - // execute stack analysis - await stackAnalysisService(manifestFilePath, options) - .then(async (resp) => { - p.report({ - message: StatusMessages.WIN_GENERATING_DEPENDENCIES - }); - - updateCurrentWebviewPanel(resp); - - p.report({ - message: StatusMessages.WIN_SUCCESS_DEPENDENCY_ANALYSIS - }); - - resolve(resp); - }) - .catch(err => { - p.report({ - message: StatusMessages.WIN_FAILURE_DEPENDENCY_ANALYSIS - }); - - reject(err); - }); - }); - }); - } catch (err) { - updateCurrentWebviewPanel('error'); - throw (err); - } + return await vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: Titles.EXT_TITLE }, async p => { + p.report({ message: StatusMessages.WIN_ANALYZING_DEPENDENCIES }); + + // set up configuration options for the stack analysis request + const options = { + 'RHDA_TOKEN': globalConfig.telemetryId, + 'RHDA_SOURCE': globalConfig.utmSource, + 'MATCH_MANIFEST_VERSIONS': globalConfig.matchManifestVersions, + 'EXHORT_PYTHON_VIRTUAL_ENV': globalConfig.usePythonVirtualEnvironment, + 'EXHORT_GO_MVS_LOGIC_ENABLED': globalConfig.useGoMVS, + 'EXHORT_PYTHON_INSTALL_BEST_EFFORTS': globalConfig.enablePythonBestEffortsInstallation, + 'EXHORT_PIP_USE_DEP_TREE': globalConfig.usePipDepTree, + 'EXHORT_MVN_PATH': globalConfig.exhortMvnPath, + 'EXHORT_PREFER_MVNW': globalConfig.exhortPreferMvnw, + 'EXHORT_GRADLE_PATH': globalConfig.exhortGradlePath, + 'EXHORT_NPM_PATH': globalConfig.exhortNpmPath, + 'EXHORT_GO_PATH': globalConfig.exhortGoPath, + 'EXHORT_PYTHON3_PATH': globalConfig.exhortPython3Path, + 'EXHORT_PIP3_PATH': globalConfig.exhortPip3Path, + 'EXHORT_PYTHON_PATH': globalConfig.exhortPythonPath, + 'EXHORT_PIP_PATH': globalConfig.exhortPipPath + }; + + // execute stack analysis + try { + const promise = stackAnalysisService(manifestFilePath, options); + + p.report({ message: StatusMessages.WIN_GENERATING_DEPENDENCIES }); + + const resp = await promise; + + updateCurrentWebviewPanel(resp); + + p.report({ message: StatusMessages.WIN_SUCCESS_DEPENDENCY_ANALYSIS }); + + return resp; + } catch (err) { + p.report({ message: StatusMessages.WIN_FAILURE_DEPENDENCY_ANALYSIS }); + + updateCurrentWebviewPanel('error'); + + throw err; + } + }); } diff --git a/src/template.ts b/src/template.ts index 29e9d22f..99a78f29 100644 --- a/src/template.ts +++ b/src/template.ts @@ -265,23 +265,24 @@ export const LOADER_TEMPLATE = ` export const ERROR_TEMPLATE = ` - - - + -
-

Unable to analyze your stack.

-
- `; +
+

Unable to analyze your stack.

+
+ + `; diff --git a/test/rhda.test.ts b/test/rhda.test.ts index 1ec841d7..8ed41540 100644 --- a/test/rhda.test.ts +++ b/test/rhda.test.ts @@ -42,7 +42,7 @@ suite('RHDA module', () => { sandbox.restore(); }); - test('should ignore unsoported file', async () => { + test('should ignore unsupported file', async () => { const unsupportedFilePath = mockInvalidPath; const authorizeRHDAStub = sandbox.stub(globalConfig, 'authorizeRHDA').resolves(); const stackAnalysisServiceStub = sandbox.stub(stackAnalysis, 'executeStackAnalysis').resolves(mockReponse) @@ -54,15 +54,13 @@ suite('RHDA module', () => { expect(authorizeRHDAStub.calledOnce).to.be.false; expect(stackAnalysisServiceStub.calledOnce).to.be.false; expect(imageAnalysisServiceStub.calledOnce).to.be.false; - expect(showInformationMessageSpy.calledOnceWith(`File ${unsupportedFilePath} is not supported!!`)).to.be.true; + expect(showInformationMessageSpy.calledOnceWith(`File ${unsupportedFilePath} is not supported.`)).to.be.true; }); test('should receive RHDA report for supported dependency file and successfully save HTML data locally', async () => { const authorizeRHDAStub = sandbox.stub(globalConfig, 'authorizeRHDA').resolves(); const stackAnalysisServiceStub = sandbox.stub(stackAnalysis, 'executeStackAnalysis').resolves(mockReponse) - const writeFileStub = sandbox.stub(fs, 'writeFile').callsFake((path, data, callback) => { - callback(null); - }); + const writeFileStub = sandbox.stub(fs.promises, 'writeFile').resolves(null) await rhda.generateRHDAReport(context, mockGoPath); @@ -74,9 +72,7 @@ suite('RHDA module', () => { test('should receive RHDA report for supported image file and successfully save HTML data locally', async () => { const authorizeRHDAStub = sandbox.stub(globalConfig, 'authorizeRHDA').resolves(); const imageAnalysisServiceStub = sandbox.stub(imageAnalysis, 'executeDockerImageAnalysis').resolves(mockReponse) - const writeFileStub = sandbox.stub(fs, 'writeFile').callsFake((path, data, callback) => { - callback(null); - }); + const writeFileStub = sandbox.stub(fs.promises, 'writeFile').resolves(null) await rhda.generateRHDAReport(context, mockDockerfilePath); @@ -118,9 +114,7 @@ suite('RHDA module', () => { test('should generate RHDA report for supported file successfully but fail to save HTML locally', async () => { const authorizeRHDAStub = sandbox.stub(globalConfig, 'authorizeRHDA').resolves(); const stackAnalysisServiceStub = sandbox.stub(stackAnalysis, 'executeStackAnalysis').resolves(mockReponse) - const writeFileStub = sandbox.stub(fs, 'writeFile').callsFake((path, data, callback) => { - callback(new Error('Mock Error')); - }); + const writeFileStub = sandbox.stub(fs.promises, 'writeFile').throws(new Error('Mock Error')) await rhda.generateRHDAReport(context, mockNpmPath) .then(() => { @@ -156,9 +150,7 @@ suite('RHDA module', () => { test('should trigger and update webview panel', async () => { const authorizeRHDAStub = sandbox.stub(globalConfig, 'authorizeRHDA').resolves(); const stackAnalysisServiceStub = sandbox.stub(stackAnalysis, 'executeStackAnalysis').resolves(mockReponse) - const writeFileStub = sandbox.stub(fs, 'writeFile').callsFake((path, data, callback) => { - callback(null); - }); + const writeFileStub = sandbox.stub(fs.promises, 'writeFile').resolves(null) await rhda.generateRHDAReport(context, mockGradlePath);