diff --git a/src/commands/action-flows/action-flow/action-flow.service.ts b/src/commands/action-flows/action-flow/action-flow.service.ts index b6583edb..e450734f 100644 --- a/src/commands/action-flows/action-flow/action-flow.service.ts +++ b/src/commands/action-flows/action-flow/action-flow.service.ts @@ -7,6 +7,7 @@ import { ActionFlowApi } from "./action-flow-api"; import { fileService, FileService } from "../../../core/utils/file-service"; import { logger } from "../../../core/utils/logger"; import { FileConstants } from "../../../core/utils/file.constants"; +import { resolve } from "node:path"; export class ActionFlowService { public static readonly METADATA_FILE_NAME = "metadata.json"; @@ -31,7 +32,8 @@ export class ActionFlowService { } const fileName = "action-flows_export_" + uuidv4() + ".zip"; - zip.writeZip(fileName, () => fs.chmodSync(fileName, FileConstants.DEFAULT_FILE_PERMISSIONS)); + const fullFilePath = resolve(process.cwd(), fileName); + zip.writeZip(fullFilePath, () => fs.chmodSync(fullFilePath, FileConstants.DEFAULT_FILE_PERMISSIONS)); logger.info(FileService.fileDownloadedMessage + fileName); } diff --git a/src/commands/asset-registry/asset-registry.service.ts b/src/commands/asset-registry/asset-registry.service.ts index 70c93cf2..965879a1 100644 --- a/src/commands/asset-registry/asset-registry.service.ts +++ b/src/commands/asset-registry/asset-registry.service.ts @@ -4,7 +4,6 @@ import { Context } from "../../core/command/cli-context"; import { fileService, FileService } from "../../core/utils/file-service"; import { FatalError, logger } from "../../core/utils/logger"; import { v4 as uuidv4 } from "uuid"; -import * as fs from "fs"; export class AssetRegistryService { private api: AssetRegistryApi; @@ -92,7 +91,8 @@ export class AssetRegistryService { } if (hasFile) { - return this.parseJson(fs.readFileSync(opts.file!, "utf-8"), `-f ${opts.file}`); + + return this.parseJson(fileService.readFile(opts.file), `-f ${opts.file}`); } if (hasNodeKey && hasConfig) { diff --git a/src/commands/configuration-management/single-package-export.service.ts b/src/commands/configuration-management/single-package-export.service.ts index 81e07b0c..7e000000 100644 --- a/src/commands/configuration-management/single-package-export.service.ts +++ b/src/commands/configuration-management/single-package-export.service.ts @@ -2,6 +2,7 @@ import { Context } from "../../core/command/cli-context"; import { fileService, FileService } from "../../core/utils/file-service"; import { logger } from "../../core/utils/logger"; import { SinglePackageExportApi } from "./api/single-package-export-api"; +import { resolve } from "node:path"; export class SinglePackageExportService { @@ -16,7 +17,7 @@ export class SinglePackageExportService { if (zip) { const fileName = `${packageKey}.zip`; - fileService.writeBufferToFileWithGivenName(packageData, fileName); + fileService.writeBufferToFileWithGivenName(packageData, resolve(process.cwd(), fileName)); logger.info(FileService.fileDownloadedMessage + fileName); return; } diff --git a/src/commands/configuration-management/variable.service.ts b/src/commands/configuration-management/variable.service.ts index 08945abd..462afcb8 100644 --- a/src/commands/configuration-management/variable.service.ts +++ b/src/commands/configuration-management/variable.service.ts @@ -70,19 +70,19 @@ export class VariableService { } private async getVersionedVariablesByKeyVersionPairs(keysByVersion: string[], keysByVersionFile: string): Promise { - const variablesExportRequest: PackageKeyAndVersionPair[] = await this.buildKeyVersionPairs(keysByVersion, keysByVersionFile); + const variablesExportRequest: PackageKeyAndVersionPair[] = this.buildKeyVersionPairs(keysByVersion, keysByVersionFile); const variableManifests = await this.variableApi.findVariablesWithValuesByPackageKeysAndVersion(variablesExportRequest); return fixConnectionVariables(variableManifests); } - private async buildKeyVersionPairs(keysByVersion: string[], keysByVersionFile: string): Promise { + private buildKeyVersionPairs(keysByVersion: string[], keysByVersionFile: string): PackageKeyAndVersionPair[] { let variablesExportRequest: PackageKeyAndVersionPair[] = []; if (keysByVersion.length !== 0) { variablesExportRequest = this.buildKeyAndVersionPairsFromArrayInput(keysByVersion); } else if (keysByVersion.length === 0 && keysByVersionFile !== "") { - variablesExportRequest = await fileService.readFileToJson(keysByVersionFile); + variablesExportRequest = fileService.readFileToJson(keysByVersionFile); } else { throw new FatalError("Please provide keysByVersion mappings or file path!"); } diff --git a/src/commands/t2tc/t2tc-package.service.ts b/src/commands/t2tc/t2tc-package.service.ts index aed32676..9b7d41ef 100644 --- a/src/commands/t2tc/t2tc-package.service.ts +++ b/src/commands/t2tc/t2tc-package.service.ts @@ -20,6 +20,7 @@ import { StudioService } from "./studio.service"; import { GitService } from "../../core/git-profile/git/git.service"; import * as fs from "fs"; import { FileConstants } from "../../core/utils/file.constants"; +import { resolve } from "node:path"; export class T2tcPackageService { @@ -142,7 +143,7 @@ export class T2tcPackageService { await this.studioService.processImportedPackages(configs, existingStudioPackages, studioManifests); if (gitBranch) { - fs.rmSync(temporaryGitFolder, { recursive: true }); + fs.rmSync(temporaryGitFolder, { recursive: true, force: true }); } fs.rmSync(sourceToBeImported); @@ -248,7 +249,8 @@ export class T2tcPackageService { } else { const fileDownloadedMessage = "File downloaded successfully. New filename: "; const filename = `export_${uuidv4()}.zip`; - exportedZip.writeZip(filename, () => fs.chmodSync(filename, FileConstants.DEFAULT_FILE_PERMISSIONS)); + const fullFilePath = resolve(process.cwd(), filename); + exportedZip.writeZip(fullFilePath, () => fs.chmodSync(fullFilePath, FileConstants.DEFAULT_FILE_PERMISSIONS)); logger.info(fileDownloadedMessage + filename); } } diff --git a/src/core/utils/file-service.ts b/src/core/utils/file-service.ts index 5769572b..5794fc14 100644 --- a/src/core/utils/file-service.ts +++ b/src/core/utils/file-service.ts @@ -29,7 +29,7 @@ export class FileService { this.restrictFilePermissions(targetPath); } - public async readFileToJson(fileName: string): Promise { + public readFileToJson(fileName: string): any { const fileContent = this.readFile(fileName); return JSON.parse(fileContent); diff --git a/tests/commands/action-flows/analyze-action-flows.spec.ts b/tests/commands/action-flows/analyze-action-flows.spec.ts index bdd4bcf7..42494709 100644 --- a/tests/commands/action-flows/analyze-action-flows.spec.ts +++ b/tests/commands/action-flows/analyze-action-flows.spec.ts @@ -1,9 +1,10 @@ import * as path from "path"; import { mockedAxiosInstance } from "../../utls/http-requests-mock"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { FileService } from "../../../src/core/utils/file-service"; import { ActionFlowCommandService } from "../../../src/commands/action-flows/action-flow/action-flow-command.service"; import { testContext } from "../../utls/test-context"; +import { getJsonFromDownloadedFile, getJsonFromFile } from "../../utls/fs-utils"; describe("Analyze action-flows", () => { @@ -62,9 +63,8 @@ describe("Analyze action-flows", () => { expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain(FileService.fileDownloadedMessage); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(mockAnalyzeResponse, null, 4), { encoding: "utf-8", mode: 0o600 }); + expect(getJsonFromDownloadedFile()).toEqual(mockAnalyzeResponse); expect(mockedAxiosInstance.get).toHaveBeenCalledWith(`https://myTeam.celonis.cloud/ems-automation/api/root/${packageId}/export/assets/analyze`, expect.anything()); }); }); \ No newline at end of file diff --git a/tests/commands/action-flows/export-action-flows.spec.ts b/tests/commands/action-flows/export-action-flows.spec.ts index 09e9d9cb..82524e06 100644 --- a/tests/commands/action-flows/export-action-flows.spec.ts +++ b/tests/commands/action-flows/export-action-flows.spec.ts @@ -1,13 +1,11 @@ import * as AdmZip from "adm-zip"; -import * as fs from "fs"; import { parse, stringify } from "yaml"; import { mockAxiosGet } from "../../utls/http-requests-mock"; import { ActionFlowCommandService } from "../../../src/commands/action-flows/action-flow/action-flow-command.service"; -import { loggingTestTransport, mockWriteSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import { mockExistsSyncOnce, mockReadFileSync } from "../../utls/fs-mock-utils"; +import { loggingTestTransport } from "../../jest.setup"; import { ActionFlowService } from "../../../src/commands/action-flows/action-flow/action-flow.service"; import { testContext } from "../../utls/test-context"; +import { getDownloadedFileName, writeJsonTempFile } from "../../utls/fs-utils"; describe("Export action-flows", () => { @@ -69,10 +67,6 @@ describe("Export action-flows", () => { }, }; - beforeEach(() => { - (fs.openSync as jest.Mock).mockReturnValue(100); - }); - it("Should call export API and return the zip response", async () => { const zipExport = new AdmZip(); zipExport.addFile(actionFlowFileName, Buffer.from(stringify(actionFlowConfig))); @@ -82,12 +76,7 @@ describe("Export action-flows", () => { await new ActionFlowCommandService(testContext).exportActionFlows(packageId, null); expect(loggingTestTransport.logMessages.length).toBe(1); - const expectedZipFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedZipFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const receivedZip = new AdmZip(fileBuffer); + const receivedZip = new AdmZip(getDownloadedFileName()); expect(receivedZip.getEntries().length).toBe(1); const receivedZipEntry = receivedZip.getEntries()[0]; @@ -131,8 +120,7 @@ describe("Export action-flows", () => { "actionFlowsTeamId": "555", }; - mockExistsSyncOnce(); - mockReadFileSync(stringify(metadata)); + writeJsonTempFile("metadata.json", metadata); const zipExport = new AdmZip(); zipExport.addFile(actionFlowFileName, Buffer.from(stringify(actionFlowConfig))); @@ -140,12 +128,7 @@ describe("Export action-flows", () => { await new ActionFlowCommandService(testContext).exportActionFlows(packageId, ActionFlowService.METADATA_FILE_NAME); expect(loggingTestTransport.logMessages.length).toBe(1); - const expectedZipFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedZipFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const receivedZip = new AdmZip(fileBuffer); + const receivedZip = new AdmZip(getDownloadedFileName()); expect(receivedZip.getEntries().length).toBe(2); expect(receivedZip.getEntries().filter(entry => entry.name === ActionFlowService.METADATA_FILE_NAME).length).toBe(1); diff --git a/tests/commands/action-flows/import-action-flows.spec.ts b/tests/commands/action-flows/import-action-flows.spec.ts index 6be51b71..442e5d94 100644 --- a/tests/commands/action-flows/import-action-flows.spec.ts +++ b/tests/commands/action-flows/import-action-flows.spec.ts @@ -1,11 +1,10 @@ -import * as path from "path"; import * as AdmZip from "adm-zip"; import { mockedAxiosInstance } from "../../utls/http-requests-mock"; -import { mockCreateReadStream } from "../../utls/fs-mock-utils"; import { ActionFlowCommandService } from "../../../src/commands/action-flows/action-flow/action-flow-command.service"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { FileService } from "../../../src/core/utils/file-service"; import { testContext } from "../../utls/test-context"; +import { getJsonFromDownloadedFile, zipToTempFolder } from "../../utls/fs-utils"; describe("Import action-flows", () => { @@ -28,9 +27,9 @@ describe("Import action-flows", () => { const resp = { data: mockImportResponse }; (mockedAxiosInstance.post as jest.Mock).mockResolvedValue(resp); const zip = new AdmZip(); - mockCreateReadStream(zip.toBuffer()); + const zipPath = zipToTempFolder(zip); - await new ActionFlowCommandService(testContext).importActionFlows(packageId, "tmp", true, false); + await new ActionFlowCommandService(testContext).importActionFlows(packageId, zipPath, true, false); expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain(JSON.stringify(mockImportResponse, null, 4)); @@ -42,15 +41,14 @@ describe("Import action-flows", () => { const resp = { data: mockImportResponse }; (mockedAxiosInstance.post as jest.Mock).mockResolvedValue(resp); const zip = new AdmZip(); - mockCreateReadStream(zip.toBuffer()); + const zipPath = zipToTempFolder(zip); - await new ActionFlowCommandService(testContext).importActionFlows(packageId, "tmp", true, true); + await new ActionFlowCommandService(testContext).importActionFlows(packageId, zipPath, true, true); expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain(FileService.fileDownloadedMessage); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(mockImportResponse, null, 4), { encoding: "utf-8", mode: 0o600 }); + expect(getJsonFromDownloadedFile()).toEqual(mockImportResponse); expect(mockedAxiosInstance.post).toHaveBeenCalledWith(`https://myTeam.celonis.cloud/ems-automation/api/root/${packageId}/import/assets`, expect.anything(), expect.anything()); }); }); \ No newline at end of file diff --git a/tests/commands/asset-registry/asset-registry-examples.spec.ts b/tests/commands/asset-registry/asset-registry-examples.spec.ts index 066d81b1..c03e6754 100644 --- a/tests/commands/asset-registry/asset-registry-examples.spec.ts +++ b/tests/commands/asset-registry/asset-registry-examples.spec.ts @@ -1,9 +1,8 @@ import { mockAxiosGet } from "../../utls/http-requests-mock"; import { AssetRegistryService } from "../../../src/commands/asset-registry/asset-registry.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Asset registry examples", () => { const examplesResponse = [ @@ -27,14 +26,7 @@ describe("Asset registry examples", () => { await new AssetRegistryService(testContext).getExamples("BOARD_V2", true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const written = JSON.parse(mockWriteFileSync.mock.calls[0][1]); + const written = getJsonFromDownloadedFile(); expect(written.length).toBe(2); expect(written[0].name).toBe("Simple View"); }); diff --git a/tests/commands/asset-registry/asset-registry-get.spec.ts b/tests/commands/asset-registry/asset-registry-get.spec.ts index 6d863d32..c7275661 100644 --- a/tests/commands/asset-registry/asset-registry-get.spec.ts +++ b/tests/commands/asset-registry/asset-registry-get.spec.ts @@ -2,9 +2,8 @@ import { AssetRegistryDescriptor } from "../../../src/commands/asset-registry/as import { mockAxiosGet } from "../../utls/http-requests-mock"; import { AssetRegistryService } from "../../../src/commands/asset-registry/asset-registry.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Asset registry get", () => { const boardDescriptor: AssetRegistryDescriptor = { @@ -46,14 +45,7 @@ describe("Asset registry get", () => { await new AssetRegistryService(testContext).getType("BOARD_V2", true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const written = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as AssetRegistryDescriptor; + const written = getJsonFromDownloadedFile() as AssetRegistryDescriptor; expect(written.assetType).toBe("BOARD_V2"); expect(written.displayName).toBe("View"); expect(written.service.basePath).toBe("/blueprint/api"); diff --git a/tests/commands/asset-registry/asset-registry-list.spec.ts b/tests/commands/asset-registry/asset-registry-list.spec.ts index 04619c8a..5d5e28dd 100644 --- a/tests/commands/asset-registry/asset-registry-list.spec.ts +++ b/tests/commands/asset-registry/asset-registry-list.spec.ts @@ -2,9 +2,8 @@ import { AssetRegistryMetadata } from "../../../src/commands/asset-registry/asse import { mockAxiosGet } from "../../utls/http-requests-mock"; import { AssetRegistryService } from "../../../src/commands/asset-registry/asset-registry.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Asset registry list", () => { const metadata: AssetRegistryMetadata = { @@ -85,14 +84,7 @@ describe("Asset registry list", () => { await new AssetRegistryService(testContext).listTypes(true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const written = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as AssetRegistryMetadata; + const written = getJsonFromDownloadedFile() as AssetRegistryMetadata; expect(Object.keys(written.types).length).toBe(2); expect(written.types["BOARD_V2"].assetType).toBe("BOARD_V2"); expect(written.types["SEMANTIC_MODEL"].assetType).toBe("SEMANTIC_MODEL"); diff --git a/tests/commands/asset-registry/asset-registry-schema.spec.ts b/tests/commands/asset-registry/asset-registry-schema.spec.ts index f85e4c37..6e65d80d 100644 --- a/tests/commands/asset-registry/asset-registry-schema.spec.ts +++ b/tests/commands/asset-registry/asset-registry-schema.spec.ts @@ -1,9 +1,8 @@ import { mockAxiosGet } from "../../utls/http-requests-mock"; import { AssetRegistryService } from "../../../src/commands/asset-registry/asset-registry.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Asset registry schema", () => { const schemaResponse = { @@ -33,14 +32,7 @@ describe("Asset registry schema", () => { await new AssetRegistryService(testContext).getSchema("BOARD_V2", true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const written = JSON.parse(mockWriteFileSync.mock.calls[0][1]); + const written = getJsonFromDownloadedFile(); expect(written.$schema).toBe("http://json-schema.org/draft-07/schema#"); expect(written.title).toBe("Board"); }); diff --git a/tests/commands/asset-registry/asset-registry-skills-list.spec.ts b/tests/commands/asset-registry/asset-registry-skills-list.spec.ts index 4a63d993..8e0a40be 100644 --- a/tests/commands/asset-registry/asset-registry-skills-list.spec.ts +++ b/tests/commands/asset-registry/asset-registry-skills-list.spec.ts @@ -2,9 +2,8 @@ import { AgentSkillsResponse } from "../../../src/commands/asset-registry/asset- import { mockAxiosGet } from "../../utls/http-requests-mock"; import { AssetRegistryService } from "../../../src/commands/asset-registry/asset-registry.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Asset registry skills list", () => { const skillsResponse: AgentSkillsResponse = { @@ -46,14 +45,7 @@ describe("Asset registry skills list", () => { await new AssetRegistryService(testContext).listSkills(true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const written = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as AgentSkillsResponse; + const written = getJsonFromDownloadedFile() as AgentSkillsResponse; expect(written.skills.length).toBe(2); expect(written.skills[0].name).toBe("skill-one"); expect(written.skills[1].path).toBe("asset/BOARD_V2/board-authoring"); diff --git a/tests/commands/asset-registry/asset-registry-validate.spec.ts b/tests/commands/asset-registry/asset-registry-validate.spec.ts index e756516f..6805190f 100644 --- a/tests/commands/asset-registry/asset-registry-validate.spec.ts +++ b/tests/commands/asset-registry/asset-registry-validate.spec.ts @@ -1,15 +1,8 @@ import { mockAxiosPost, mockedPostRequestBodyByUrl } from "../../utls/http-requests-mock"; import { AssetRegistryService } from "../../../src/commands/asset-registry/asset-registry.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; -import * as fs from "fs"; - -jest.mock("fs", () => ({ - ...jest.requireActual("fs"), - readFileSync: jest.fn(), -})); +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile, writeJsonTempFile, writeTempFile } from "../../utls/fs-utils"; describe("Asset registry validate", () => { const validateResponse = { @@ -53,14 +46,7 @@ describe("Asset registry validate", () => { json: true, }); - const msg = loggingTestTransport.logMessages[0].message; - const expectedFileName = msg.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - expect.objectContaining({ encoding: "utf-8" }) - ); - const written = JSON.parse(mockWriteFileSync.mock.calls[0][1]); + const written = getJsonFromDownloadedFile(); expect(written.valid).toBe(false); }); @@ -144,7 +130,7 @@ describe("Asset registry validate", () => { }; it("Should validate with -f file and print result", async () => { - (fs.readFileSync as jest.Mock).mockReturnValue(JSON.stringify(fullRequest)); + writeJsonTempFile("request.json", fullRequest); mockAxiosPost(mockUrl, validateResponse); await new AssetRegistryService(testContext).validate({ @@ -153,12 +139,11 @@ describe("Asset registry validate", () => { json: false, }); - expect(fs.readFileSync).toHaveBeenCalledWith("request.json", "utf-8"); expect(loggingTestTransport.logMessages[0].message).toContain("INVALID_ENUM_VALUE"); }); it("Should send the file body as-is (no envelope wrapping)", async () => { - (fs.readFileSync as jest.Mock).mockReturnValue(JSON.stringify(fullRequest)); + writeJsonTempFile("request.json", fullRequest); mockAxiosPost(mockUrl, validateResponse); await new AssetRegistryService(testContext).validate({ @@ -173,7 +158,7 @@ describe("Asset registry validate", () => { }); it("Should throw when -f file contains invalid JSON", async () => { - (fs.readFileSync as jest.Mock).mockReturnValue("not-json{"); + writeTempFile("bad.json", "not-json{"); await expect( new AssetRegistryService(testContext).validate({ diff --git a/tests/commands/configuration-management/config-list-variables.spec.ts b/tests/commands/configuration-management/config-list-variables.spec.ts index bc8e3355..238029f4 100644 --- a/tests/commands/configuration-management/config-list-variables.spec.ts +++ b/tests/commands/configuration-management/config-list-variables.spec.ts @@ -1,5 +1,3 @@ -import * as path from "path"; -import * as fs from "fs"; import { parse } from "../../../src/core/utils/json"; import { PackageKeyAndVersionPair, @@ -11,8 +9,9 @@ import { PackageManagerVariableType } from "../../../src/commands/studio/interfa import { mockAxiosPost, mockedPostRequestBodyByUrl } from "../../utls/http-requests-mock"; import { ConfigCommandService } from "../../../src/commands/configuration-management/config-command.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { FileService } from "../../../src/core/utils/file-service"; +import { getJsonFromDownloadedFile, writeJsonTempFile } from "../../utls/fs-utils"; describe("Config listVariables", () => { @@ -131,16 +130,11 @@ describe("Config listVariables", () => { expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain(FileService.fileDownloadedMessage); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(fixedVariableManifests), {encoding: "utf-8", mode: 0o600}); - - const variableExportRequest = parse(mockedPostRequestBodyByUrl.get("https://myTeam.celonis.cloud/package-manager/api/core/packages/export/batch/variables-with-assignments")); - expect(variableExportRequest).toEqual(packageKeyAndVersionPairs); + expect(getJsonFromDownloadedFile()).toEqual(fixedVariableManifests); }) it("Should list fixed variables for non-json response and keysByVersion file mapping", async () => { - (fs.existsSync as jest.Mock).mockReturnValue(true); - (fs.readFileSync as jest.Mock).mockReturnValue(JSON.stringify(packageKeyAndVersionPairs)); + writeJsonTempFile("key_version_mapping.json", packageKeyAndVersionPairs); await new ConfigCommandService(testContext).listVariables(false, [], "key_version_mapping.json", []); @@ -154,19 +148,14 @@ describe("Config listVariables", () => { }) it("Should export fixed variables for json response and keysByVersion file mapping", async () => { - (fs.existsSync as jest.Mock).mockReturnValue(true); - (fs.readFileSync as jest.Mock).mockReturnValue(JSON.stringify(packageKeyAndVersionPairs)); + writeJsonTempFile("key_version_mapping.json", packageKeyAndVersionPairs); await new ConfigCommandService(testContext).listVariables(true, [], "key_version_mapping.json", []); expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain(FileService.fileDownloadedMessage); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(fixedVariableManifests), {encoding: "utf-8", mode: 0o600}); - - const variableExportRequest = parse(mockedPostRequestBodyByUrl.get("https://myTeam.celonis.cloud/package-manager/api/core/packages/export/batch/variables-with-assignments")); - expect(variableExportRequest).toEqual(packageKeyAndVersionPairs); + expect(getJsonFromDownloadedFile()).toEqual(fixedVariableManifests); }) it("Should throw error if no mapping and no file path is provided", async () => { @@ -222,15 +211,7 @@ describe("Config listVariables", () => { expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain(FileService.fileDownloadedMessage); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - JSON.stringify(pkgAOnlyResponse), - {encoding: "utf-8", mode: 0o600} - ); - - const postBody = parse(mockedPostRequestBodyByUrl.get(url)); - expect(postBody).toEqual(["pkg-a"]); + expect(getJsonFromDownloadedFile()).toEqual(pkgAOnlyResponse); }); }); }); diff --git a/tests/commands/configuration-management/config-metadata-export.spec.ts b/tests/commands/configuration-management/config-metadata-export.spec.ts index 2b6e5f6f..4e5939aa 100644 --- a/tests/commands/configuration-management/config-metadata-export.spec.ts +++ b/tests/commands/configuration-management/config-metadata-export.spec.ts @@ -1,20 +1,13 @@ -import { mockExistsSync } from "../../utls/fs-mock-utils"; import { mockAxiosGet } from "../../utls/http-requests-mock"; import { PackageMetadataExportTransport } from "../../../src/commands/configuration-management/interfaces/package-export.interfaces"; import { MetadataService } from "../../../src/commands/configuration-management/metadata.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Config metadata export", () => { - - beforeEach(() => { - mockExistsSync(); - }); - it("Should show on terminal if packages have unpublished changes", async () => { const packageKeys: string[] = ["package-key-1", "package-key-2"]; @@ -51,10 +44,7 @@ describe("Config metadata export", () => { await new MetadataService(testContext).exportPackagesMetadata(packageKeys, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - const exportedPackagesMetadataTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageMetadataExportTransport[]; + const exportedPackagesMetadataTransports = getJsonFromDownloadedFile() as PackageMetadataExportTransport[]; expect(exportedPackagesMetadataTransports.length).toBe(2); expect(exportedPackagesMetadataTransports).toEqual(response); diff --git a/tests/commands/configuration-management/config-node-create.spec.ts b/tests/commands/configuration-management/config-node-create.spec.ts index cafa8f7c..bf07e3b6 100644 --- a/tests/commands/configuration-management/config-node-create.spec.ts +++ b/tests/commands/configuration-management/config-node-create.spec.ts @@ -2,9 +2,8 @@ import { NodeTransport, SaveNodeTransport } from "../../../src/commands/configur import { mockAxiosPost, mockedPostRequestBodyByUrl } from "../../utls/http-requests-mock"; import { NodeService } from "../../../src/commands/configuration-management/node.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Node create", () => { const packageKey = "package-key"; @@ -52,13 +51,7 @@ describe("Node create", () => { await new NodeService(testContext).createNode(packageKey, JSON.stringify(saveTransport), undefined, false, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const savedTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeTransport; - - expect(savedTransport).toEqual(createdNode); + expect(getJsonFromDownloadedFile()).toEqual(createdNode); }); it("Should send correct request body", async () => { @@ -78,7 +71,6 @@ describe("Node create", () => { await new NodeService(testContext).createNode(packageKey, JSON.stringify(saveTransport), undefined, true, false); - expect(mockWriteFileSync).not.toHaveBeenCalled(); expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain( `Validation successful for node ${saveTransport.key} in package ${packageKey}.` diff --git a/tests/commands/configuration-management/config-node-dependency.spec.ts b/tests/commands/configuration-management/config-node-dependency.spec.ts index 820fc628..e7b8e2fe 100644 --- a/tests/commands/configuration-management/config-node-dependency.spec.ts +++ b/tests/commands/configuration-management/config-node-dependency.spec.ts @@ -2,9 +2,8 @@ import { NodeDependencyTransport } from "../../../src/commands/configuration-man import { mockAxiosGet } from "../../utls/http-requests-mock"; import { NodeDependencyService } from "../../../src/commands/configuration-management/node-dependency.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Node Dependencies", () => { const packageKey = "test-package-key"; @@ -52,17 +51,7 @@ describe("Node Dependencies", () => { await new NodeDependencyService(testContext).listNodeDependencies(packageKey, nodeKey, version, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const dependenciesTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeDependencyTransport[]; - - expect(dependenciesTransport).toEqual(dependencies); + expect(getJsonFromDownloadedFile()).toEqual(dependencies); }); it("Should handle empty dependencies list in console output", async () => { @@ -89,17 +78,7 @@ describe("Node Dependencies", () => { await new NodeDependencyService(testContext).listNodeDependencies(packageKey, nodeKey, version, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const dependenciesTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeDependencyTransport[]; - - expect(dependenciesTransport).toEqual([]); + expect(getJsonFromDownloadedFile()).toEqual([]); }); it("Should list single node dependency", async () => { @@ -147,17 +126,7 @@ describe("Node Dependencies", () => { await new NodeDependencyService(testContext).listNodeDependencies(packageKey, nodeKey, null, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const dependenciesTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeDependencyTransport[]; - - expect(dependenciesTransport).toEqual(dependencies); + expect(getJsonFromDownloadedFile()).toEqual(dependencies); }); it("Should handle empty staging dependencies list in console output", async () => { @@ -184,17 +153,7 @@ describe("Node Dependencies", () => { await new NodeDependencyService(testContext).listNodeDependencies(packageKey, nodeKey, null, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const dependenciesTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeDependencyTransport[]; - - expect(dependenciesTransport).toEqual([]); + expect(getJsonFromDownloadedFile()).toEqual([]); }); it("Should list single staging node dependency", async () => { diff --git a/tests/commands/configuration-management/config-node-diff.spec.ts b/tests/commands/configuration-management/config-node-diff.spec.ts index 6721e2f9..4f06d820 100644 --- a/tests/commands/configuration-management/config-node-diff.spec.ts +++ b/tests/commands/configuration-management/config-node-diff.spec.ts @@ -8,11 +8,9 @@ import { } from "../../utls/http-requests-mock"; import { NodeDiffService } from "../../../src/commands/configuration-management/node-diff.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import { mockCreateReadStream } from "../../utls/fs-mock-utils"; +import { loggingTestTransport } from "../../jest.setup"; import * as FormData from "form-data"; -import * as path from "path"; +import { getJsonFromDownloadedFile, writeJsonTempFile } from "../../utls/fs-utils"; describe("Node diff", () => { const packageKey = "test-package-key"; @@ -78,17 +76,7 @@ describe("Node diff", () => { await new NodeDiffService(testContext).diff(packageKey, nodeKey, baseVersion, compareVersion, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split( - FileService.fileDownloadedMessage - )[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const savedDiff = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeConfigurationDiffTransport; + const savedDiff = getJsonFromDownloadedFile() as NodeConfigurationDiffTransport; // Dates are serialized as strings in JSON expect(savedDiff.packageKey).toEqual(nodeDiff.packageKey); @@ -223,17 +211,7 @@ describe("Node diff", () => { await new NodeDiffService(testContext).diff(packageKey, nodeKey, baseVersion, compareVersion, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split( - FileService.fileDownloadedMessage - )[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const savedDiff = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeConfigurationDiffTransport; + const savedDiff = getJsonFromDownloadedFile() as NodeConfigurationDiffTransport; expect(savedDiff.changeType).toBe(NodeConfigurationChangeType.UNCHANGED); expect(savedDiff.changes).toEqual(emptyChangesNodeDiff.changes); @@ -304,8 +282,6 @@ describe("Node diff", () => { await expect( new NodeDiffService(testContext).diff(packageKey, nodeKey, baseVersion, compareVersion, false) ).rejects.toThrow(/Problem getting the node diff/); - - expect(mockWriteFileSync).not.toHaveBeenCalled(); }); it("Should request the diff with both baseVersion and compareVersion query parameters", async () => { @@ -321,10 +297,9 @@ describe("Node diff", () => { describe("With file", () => { const file = "./node.json"; - const nodeJsonContent = Buffer.from(JSON.stringify({ key: nodeKey, configuration: { foo: "bar" } })); beforeEach(() => { - mockCreateReadStream(nodeJsonContent); + writeJsonTempFile(file, { key: nodeKey, configuration: { foo: "bar" } }); }); it("Should diff a node file against STAGING and log all fields", async () => { @@ -361,17 +336,7 @@ describe("Node diff", () => { await new NodeDiffService(testContext).diffWithFile(packageKey, nodeKey, "STAGING", file, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split( - FileService.fileDownloadedMessage - )[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - expect.any(String), - { encoding: "utf-8", mode: 0o600 } - ); - - const savedDiff = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeConfigurationDiffTransport; + const savedDiff = getJsonFromDownloadedFile() as NodeConfigurationDiffTransport; expect(savedDiff.packageKey).toEqual(nodeDiff.packageKey); expect(savedDiff.nodeKey).toEqual(nodeDiff.nodeKey); @@ -419,8 +384,6 @@ describe("Node diff", () => { await expect( new NodeDiffService(testContext).diffWithFile(packageKey, nodeKey, "STAGING", file, false) ).rejects.toThrow(/Problem getting the node diff/); - - expect(mockWriteFileSync).not.toHaveBeenCalled(); }); }); }); diff --git a/tests/commands/configuration-management/config-node-list.spec.ts b/tests/commands/configuration-management/config-node-list.spec.ts index 6be73f87..2b4501ef 100644 --- a/tests/commands/configuration-management/config-node-list.spec.ts +++ b/tests/commands/configuration-management/config-node-list.spec.ts @@ -2,9 +2,8 @@ import { NodeTransport } from "../../../src/commands/configuration-management/in import { mockAxiosGet } from "../../utls/http-requests-mock"; import { NodeService } from "../../../src/commands/configuration-management/node.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Node list", () => { const createNode = (id: string, key: string, name: string, parentNodeKey?: string): NodeTransport => ({ @@ -143,11 +142,7 @@ describe("Node list", () => { await new NodeService(testContext).listNodes(packageKey, packageVersion, limit, offset, false, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const nodes = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeTransport[]; + const nodes = getJsonFromDownloadedFile() as NodeTransport[]; expect(nodes).toEqual([node1, node2]); expect(nodes.length).toBe(2); @@ -185,11 +180,7 @@ describe("Node list", () => { await new NodeService(testContext).listNodes(packageKey, packageVersion, limit, offset, true, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const nodes = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeTransport[]; + const nodes = getJsonFromDownloadedFile() as NodeTransport[]; expect(nodes).toEqual([node1, node2]); expect(nodes[0].configuration).toEqual(node1.configuration); @@ -246,11 +237,7 @@ describe("Node list", () => { await new NodeService(testContext).listNodes(packageKey, packageVersion, limit, offset, false, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const nodes = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeTransport[]; + const nodes = getJsonFromDownloadedFile() as NodeTransport[]; expect(nodes).toEqual([node1, node2]); expect(nodes[0].invalidConfiguration).toEqual(invalidConfigMessage); diff --git a/tests/commands/configuration-management/config-node-update.spec.ts b/tests/commands/configuration-management/config-node-update.spec.ts index 6d89126b..14d048c1 100644 --- a/tests/commands/configuration-management/config-node-update.spec.ts +++ b/tests/commands/configuration-management/config-node-update.spec.ts @@ -2,9 +2,8 @@ import { NodeTransport, UpdateNodeTransport } from "../../../src/commands/config import { mockAxiosPut, mockedPostRequestBodyByUrl } from "../../utls/http-requests-mock"; import { NodeService } from "../../../src/commands/configuration-management/node.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Node update", () => { const packageKey = "package-key"; @@ -51,13 +50,7 @@ describe("Node update", () => { await new NodeService(testContext).updateNode(packageKey, nodeKey, JSON.stringify(updateTransport), undefined, false, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const savedTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeTransport; - - expect(savedTransport).toEqual(updatedNode); + expect(getJsonFromDownloadedFile()).toEqual(updatedNode); }); it("Should send correct request body", async () => { @@ -76,7 +69,6 @@ describe("Node update", () => { await new NodeService(testContext).updateNode(packageKey, nodeKey, JSON.stringify(updateTransport), undefined, true, false); - expect(mockWriteFileSync).not.toHaveBeenCalled(); expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain( `Validation successful for node ${nodeKey} in package ${packageKey}.` diff --git a/tests/commands/configuration-management/config-node.spec.ts b/tests/commands/configuration-management/config-node.spec.ts index 39cd6df0..430388f6 100644 --- a/tests/commands/configuration-management/config-node.spec.ts +++ b/tests/commands/configuration-management/config-node.spec.ts @@ -2,9 +2,8 @@ import { NodeTransport } from "../../../src/commands/configuration-management/in import { mockAxiosGet } from "../../utls/http-requests-mock"; import { NodeService } from "../../../src/commands/configuration-management/node.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Node find", () => { const node: NodeTransport = { @@ -103,13 +102,7 @@ describe("Node find", () => { await new NodeService(testContext).findNode(packageKey, nodeKey, false, null, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const nodeTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeTransport; - - expect(nodeTransport).toEqual(node); + expect(getJsonFromDownloadedFile()).toEqual(node); }); it("Should find node with configuration and return as JSON", async () => { @@ -129,11 +122,7 @@ describe("Node find", () => { await new NodeService(testContext).findNode(packageKey, nodeKey, true, null, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const nodeTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeTransport; + const nodeTransport = getJsonFromDownloadedFile() as NodeTransport; expect(nodeTransport).toEqual(nodeWithConfig); expect(nodeTransport.configuration).toEqual(nodeWithConfig.configuration); @@ -173,11 +162,7 @@ describe("Node find", () => { await new NodeService(testContext).findNode(packageKey, nodeKey, false, null, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const nodeTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as NodeTransport; + const nodeTransport = getJsonFromDownloadedFile() as NodeTransport; expect(nodeTransport).toEqual(nodeWithInvalidConfig); expect(nodeTransport.invalidConfiguration).toEqual(invalidConfigMessage); diff --git a/tests/commands/configuration-management/config-validate.spec.ts b/tests/commands/configuration-management/config-validate.spec.ts index 0f35ea04..879943b7 100644 --- a/tests/commands/configuration-management/config-validate.spec.ts +++ b/tests/commands/configuration-management/config-validate.spec.ts @@ -4,8 +4,9 @@ import { } from "../../utls/http-requests-mock"; import { PackageValidationService } from "../../../src/commands/configuration-management/package-validation.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { SchemaValidationResponse } from "../../../src/commands/configuration-management/interfaces/package-validation.interfaces"; +import { getJsonFromFile } from "../../utls/fs-utils"; describe("Config validate", () => { @@ -81,11 +82,8 @@ describe("Config validate", () => { await new PackageValidationService(testContext).validatePackage("my-package", ["SCHEMA"], null, true); - expect(mockWriteFileSync).toHaveBeenCalledWith( - expect.stringMatching(/config_validate_report_.+\.json$/), - JSON.stringify(response), - { encoding: "utf-8", mode: 0o600 } - ); + const expectedFileName = loggingTestTransport.logMessages[0].message.split("Validation report file: ")[1]; + expect(getJsonFromFile(expectedFileName)).toEqual(response); }) it("Should log VALID when package has no errors", async () => { diff --git a/tests/commands/configuration-management/config-version-create.spec.ts b/tests/commands/configuration-management/config-version-create.spec.ts index db0175cf..40f37bad 100644 --- a/tests/commands/configuration-management/config-version-create.spec.ts +++ b/tests/commands/configuration-management/config-version-create.spec.ts @@ -8,9 +8,8 @@ import { PackageVersionCommandService, } from "../../../src/commands/configuration-management/package-version-command.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Package Version create", () => { const packageKey = "test-package-key"; @@ -47,13 +46,7 @@ describe("Package Version create", () => { packageKey, "1.2.0", "NONE", "Added new analysis views", undefined, true, ); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const savedTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageVersionCreatedTransport; - - expect(savedTransport).toEqual(createdVersion); + expect(getJsonFromDownloadedFile()).toEqual(createdVersion); }); it("Should create package version with PATCH version bump option", async () => { diff --git a/tests/commands/configuration-management/config-version.spec.ts b/tests/commands/configuration-management/config-version.spec.ts index d04bb361..c023d72c 100644 --- a/tests/commands/configuration-management/config-version.spec.ts +++ b/tests/commands/configuration-management/config-version.spec.ts @@ -2,12 +2,11 @@ import { PackageVersionTransport } from "../../../src/commands/configuration-man import { mockAxiosGet } from "../../utls/http-requests-mock"; import { PackageVersionService } from "../../../src/commands/configuration-management/package-version.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; import { PackageVersionCommandService } from "../../../src/commands/configuration-management/package-version-command.service"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Package Version get", () => { const packageVersion: PackageVersionTransport = { @@ -46,13 +45,7 @@ describe("Package Version get", () => { await new PackageVersionService(testContext).findPackageVersion(packageKey, version, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const packageVersionTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageVersionTransport; - - expect(packageVersionTransport).toEqual(packageVersion); + expect(getJsonFromDownloadedFile()).toEqual(packageVersion); }); it("Should handle package version with empty publish message", async () => { diff --git a/tests/commands/configuration-management/list-assignments.spec.ts b/tests/commands/configuration-management/list-assignments.spec.ts index 54bbaa1b..26581dae 100644 --- a/tests/commands/configuration-management/list-assignments.spec.ts +++ b/tests/commands/configuration-management/list-assignments.spec.ts @@ -1,9 +1,9 @@ -import * as path from "path"; import { mockedAxiosInstance } from "../../utls/http-requests-mock"; import { VariableCommandService } from "../../../src/commands/configuration-management/variable-command.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { FileService } from "../../../src/core/utils/file-service"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("List assignments", () => { @@ -37,9 +37,7 @@ describe("List assignments", () => { expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain(FileService.fileDownloadedMessage); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(mockAssignmentValues), {encoding: "utf-8", mode: 0o600}); + expect(getJsonFromDownloadedFile()).toEqual(mockAssignmentValues); }) it("Should contain url params in the url", async () => { diff --git a/tests/commands/configuration-management/single-package-export.spec.ts b/tests/commands/configuration-management/single-package-export.spec.ts index 304c0394..89fcda67 100644 --- a/tests/commands/configuration-management/single-package-export.spec.ts +++ b/tests/commands/configuration-management/single-package-export.spec.ts @@ -3,8 +3,9 @@ import AdmZip = require("adm-zip"); import { mockAxiosGet, mockAxiosGetError, mockedAxiosInstance } from "../../utls/http-requests-mock"; import { SinglePackageExportService } from "../../../src/commands/configuration-management/single-package-export.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { FileService } from "../../../src/core/utils/file-service"; +import { accessSync, readFileSync } from "node:fs"; const PACKAGE_KEY = "pkg-1"; const EXPORT_URL = `https://myTeam.celonis.cloud/pacman/api/core/staging/packages/${PACKAGE_KEY}/export-file`; @@ -44,7 +45,6 @@ describe("Single package export", () => { const [extractedData, extractedDir] = extractSpy.mock.calls[0]; expect((extractedData as Buffer).equals(packageData)).toBe(true); expect(extractedDir).toEqual(PACKAGE_KEY); - expect(mockWriteFileSync).not.toHaveBeenCalled(); expect(loggingTestTransport.logMessages[0].message).toContain(`Successful export. Exported directory: ${PACKAGE_KEY}`); }); @@ -56,10 +56,10 @@ describe("Single package export", () => { expect(mockedAxiosInstance.get).toHaveBeenCalledWith(EXPORT_URL, expect.anything()); - const [writtenPath, writtenData, writtenOptions] = mockWriteFileSync.mock.calls[0]; - expect(writtenPath).toEqual(path.resolve(process.cwd(), `${PACKAGE_KEY}.zip`)); - expect((writtenData as Buffer).equals(packageData)).toBe(true); - expect(writtenOptions).toEqual({ mode: 0o600 }); + console.log(`CWD is ${process.cwd()}`); + const expectedFile = path.resolve(process.cwd(), `${PACKAGE_KEY}.zip`); + expect(() => accessSync(expectedFile)).not.toThrow(); + expect(readFileSync(expectedFile)).toEqual(packageData); expect(loggingTestTransport.logMessages[0].message).toContain(`${FileService.fileDownloadedMessage}${PACKAGE_KEY}.zip`); }); @@ -69,7 +69,5 @@ describe("Single package export", () => { await expect( new SinglePackageExportService(testContext).exportPackage(PACKAGE_KEY, false) ).rejects.toThrow(`Problem exporting package ${PACKAGE_KEY}`); - - expect(mockWriteFileSync).not.toHaveBeenCalled(); }); }); diff --git a/tests/commands/configuration-management/single-package-import.spec.ts b/tests/commands/configuration-management/single-package-import.spec.ts index 5d749730..87d6b982 100644 --- a/tests/commands/configuration-management/single-package-import.spec.ts +++ b/tests/commands/configuration-management/single-package-import.spec.ts @@ -1,24 +1,17 @@ -import * as path from "path"; -import * as fs from "node:fs"; import AdmZip = require("adm-zip"); -import { mockCreateReadStream, mockExistsSync, mockReadFileSync } from "../../utls/fs-mock-utils"; - -// The service imports `node:fs`; the global jest.mock("fs") in jest.setup only -// covers the bare "fs" specifier, so mock the prefixed module explicitly to -// intercept the temp-file cleanup (fs.rmSync). -jest.mock("node:fs"); jest.mock("adm-zip", () => { const realAdmZip = jest.requireActual("adm-zip"); return jest.fn((...args: any[]) => realAdmZip(...args)); }); - +import fs = require("node:fs"); import { mockAxiosPost, mockedAxiosInstance, mockedPostRequestBodyByUrl } from "../../utls/http-requests-mock"; import { SinglePackageImportService } from "../../../src/commands/configuration-management/single-package-import.service"; import { SinglePackageImportResult } from "../../../src/commands/configuration-management/interfaces/single-package-import.interfaces"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { FileService } from "../../../src/core/utils/file-service"; +import { getJsonFromDownloadedFile, makeTempDir, zipToTempFolder } from "../../utls/fs-utils"; const IMPORT_URL = "https://myTeam.celonis.cloud/pacman/api/core/staging/packages/import-file"; @@ -66,23 +59,14 @@ function buildImportResponse(): SinglePackageImportResult { describe("Single package import", () => { - beforeEach(() => { - mockExistsSync(); - }); - - afterEach(() => { - jest.restoreAllMocks(); - }); - it.each([true, false])("Should import a single package from a zip file with overwrite %p", async (overwrite: boolean) => { const packageZip = buildSinglePackageZip(); - mockReadFileSync(packageZip.toBuffer()); - mockCreateReadStream(packageZip.toBuffer()); + const zipPath = zipToTempFolder(packageZip); const importResponse = buildImportResponse(); mockAxiosPost(IMPORT_URL, importResponse); - await new SinglePackageImportService(testContext).importPackage("./package.zip", null, overwrite, false); + await new SinglePackageImportService(testContext).importPackage(zipPath, null, overwrite, false); expect(mockedAxiosInstance.post).toHaveBeenCalledWith( IMPORT_URL, @@ -94,50 +78,38 @@ describe("Single package import", () => { }); it("Should import a single package from a directory by zipping it first", async () => { - const packageZip = buildSinglePackageZip(); - const temporaryZipPath = "/tmp/content-cli-imports/single_package_test.zip"; - - jest.spyOn(FileService.prototype, "isDirectory").mockReturnValue(true); - const zipDirectorySpy = jest.spyOn(FileService.prototype, "zipDirectoryAsSinglePackage").mockReturnValue(temporaryZipPath); - mockReadFileSync(packageZip.toBuffer()); - mockCreateReadStream(packageZip.toBuffer()); + const packageFolder = makeTempDir(); + const zipDirectorySpy = jest.spyOn(FileService.prototype, "zipDirectoryAsSinglePackage"); + const rmSyncSpy = jest.spyOn(fs, "rmSync"); const importResponse = buildImportResponse(); mockAxiosPost(IMPORT_URL, importResponse); - await new SinglePackageImportService(testContext).importPackage(null, "./package-dir", true, false); + await new SinglePackageImportService(testContext).importPackage(null, packageFolder, true, false); - expect(zipDirectorySpy).toHaveBeenCalledWith("./package-dir"); + expect(zipDirectorySpy).toHaveBeenCalledWith(packageFolder); expect(mockedAxiosInstance.post).toHaveBeenCalledWith(IMPORT_URL, expect.anything(), expect.anything()); - expect(fs.rmSync).toHaveBeenCalledWith(temporaryZipPath); + expect(rmSyncSpy).toHaveBeenCalledWith(zipDirectorySpy.mock.results[0].value); }); it("Should write the import result to a json file when jsonResponse is true", async () => { const packageZip = buildSinglePackageZip(); - mockReadFileSync(packageZip.toBuffer()); - mockCreateReadStream(packageZip.toBuffer()); + const zipPath = zipToTempFolder(packageZip); const importResponse = buildImportResponse(); mockAxiosPost(IMPORT_URL, importResponse); - await new SinglePackageImportService(testContext).importPackage("./package.zip", null, false, true); + await new SinglePackageImportService(testContext).importPackage(zipPath, null, false, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), expectedFileName), - JSON.stringify(importResponse, null, 2), - { encoding: "utf-8", mode: 0o600 } - ); + expect(getJsonFromDownloadedFile()).toEqual(importResponse); }); it("Should pass the overwrite flag to the API", async () => { const packageZip = buildSinglePackageZip(); - mockReadFileSync(packageZip.toBuffer()); - mockCreateReadStream(packageZip.toBuffer()); - + const zipPath = zipToTempFolder(packageZip); mockAxiosPost(IMPORT_URL, buildImportResponse()); - await new SinglePackageImportService(testContext).importPackage("./package.zip", null, true, false); + await new SinglePackageImportService(testContext).importPackage(zipPath, null, true, false); expect(mockedPostRequestBodyByUrl.has(IMPORT_URL)).toBe(true); expect(mockedAxiosInstance.post).toHaveBeenCalledWith( @@ -177,9 +149,7 @@ describe("Single package import", () => { it("Should throw when the uncompressed zip size exceeds the 4 GB limit", async () => { const packageZip = buildSinglePackageZip(); - mockReadFileSync(packageZip.toBuffer()); - mockCreateReadStream(packageZip.toBuffer()); - + const zipPath = zipToTempFolder(packageZip); const FIVE_GB = 5 * 1024 * 1024 * 1024; (AdmZip as unknown as jest.Mock).mockImplementationOnce((...args: any[]) => { const instance = jest.requireActual("adm-zip")(...args); @@ -188,7 +158,8 @@ describe("Single package import", () => { }); await expect( - new SinglePackageImportService(testContext).importPackage("./package.zip", null, false, false) - ).rejects.toThrow('Failed to handle zip file "./package.zip": uncompressed size 5.00 GB exceeds the 4 GB limit.'); + new SinglePackageImportService(testContext).importPackage(zipPath, null, false, false) + ).rejects.toThrow(/Failed to handle zip file ".+": uncompressed size 5.00 GB exceeds the 4 GB limit./); }); + }); diff --git a/tests/commands/deployment/deployment-create.spec.ts b/tests/commands/deployment/deployment-create.spec.ts index 28b26d18..d09ff30e 100644 --- a/tests/commands/deployment/deployment-create.spec.ts +++ b/tests/commands/deployment/deployment-create.spec.ts @@ -2,9 +2,8 @@ import { DeploymentStatus, DeploymentTransport } from "../../../src/commands/dep import { mockAxiosPost } from "../../utls/http-requests-mock"; import { DeploymentService } from "../../../src/commands/deployment/deployment.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Deployment create", () => { const deployment: DeploymentTransport = { @@ -37,12 +36,6 @@ describe("Deployment create", () => { await new DeploymentService(testContext).createDeployment(deployment.packageKey, deployment.packageVersion, deployment.deployableType, deployment.target.id, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const deploymentTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as DeploymentTransport; - - expect(deploymentTransport).toEqual(deployment); + expect(getJsonFromDownloadedFile()).toEqual(deployment); }); }) \ No newline at end of file diff --git a/tests/commands/deployment/deployment-list-active.spec.ts b/tests/commands/deployment/deployment-list-active.spec.ts index 08861f75..6efa58e8 100644 --- a/tests/commands/deployment/deployment-list-active.spec.ts +++ b/tests/commands/deployment/deployment-list-active.spec.ts @@ -2,9 +2,9 @@ import { DeploymentStatus, DeploymentTransport} from "../../../src/commands/depl import { mockAxiosGet } from "../../utls/http-requests-mock"; import { DeploymentService } from "../../../src/commands/deployment/deployment.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { getJsonFromFile } from "../../utls/fs-utils"; describe("Deployment list active", () => { const deployment: DeploymentTransport = { @@ -42,10 +42,7 @@ describe("Deployment list active", () => { const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const deploymentTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as DeploymentTransport; - + const deploymentTransport = getJsonFromFile(expectedFileName) as DeploymentTransport; expect(deploymentTransport).toEqual(deployment); }); @@ -90,11 +87,8 @@ describe("Deployment list active", () => { const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const deploymentTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as DeploymentTransport[]; + const deploymentTransports = getJsonFromFile(expectedFileName) as DeploymentTransport[]; expect(deploymentTransports.length).toBe(1); - expect(deploymentTransports[0]).toEqual(deployment); }); }); \ No newline at end of file diff --git a/tests/commands/deployment/deployment-list-deployables.spec.ts b/tests/commands/deployment/deployment-list-deployables.spec.ts index aff361bf..1d08a308 100644 --- a/tests/commands/deployment/deployment-list-deployables.spec.ts +++ b/tests/commands/deployment/deployment-list-deployables.spec.ts @@ -2,9 +2,8 @@ import { DeployableTransport } from "../../../src/commands/deployment/deployment import { mockAxiosGet } from "../../utls/http-requests-mock"; import { DeploymentService } from "../../../src/commands/deployment/deployment.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Deployment list deployables", () => { const appPackage: DeployableTransport = { @@ -45,11 +44,7 @@ describe("Deployment list deployables", () => { await new DeploymentService(testContext).getDeployables(true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const deployableTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as DeployableTransport[]; + const deployableTransports = getJsonFromDownloadedFile() as DeployableTransport[]; expect(deployableTransports.length).toBe(2); const appPackageTransport = deployableTransports.filter(transport => transport.name === appPackage.name)[0]; diff --git a/tests/commands/deployment/deployment-list-history.spec.ts b/tests/commands/deployment/deployment-list-history.spec.ts index 31e86f0d..ecb89468 100644 --- a/tests/commands/deployment/deployment-list-history.spec.ts +++ b/tests/commands/deployment/deployment-list-history.spec.ts @@ -5,9 +5,8 @@ import { import { mockAxiosGet } from "../../utls/http-requests-mock"; import { DeploymentService } from "../../../src/commands/deployment/deployment.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { loggingTestTransport } from "../../jest.setup"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Deployments list history", () => { const deploymentTransport: DeploymentTransport = { @@ -58,11 +57,7 @@ describe("Deployments list history", () => { await new DeploymentService(testContext).getDeployments(true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const deploymentTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as DeploymentTransport[]; + const deploymentTransports = getJsonFromDownloadedFile() as DeploymentTransport[]; expect(deploymentTransports.length).toBe(1); expect(deploymentTransports[0]).toEqual(deploymentTransport); diff --git a/tests/commands/deployment/deployment-list-targets.spec.ts b/tests/commands/deployment/deployment-list-targets.spec.ts index fa672d6a..688bfcd0 100644 --- a/tests/commands/deployment/deployment-list-targets.spec.ts +++ b/tests/commands/deployment/deployment-list-targets.spec.ts @@ -2,9 +2,9 @@ import { DeployableTransport, TargetTransport } from "../../../src/commands/depl import { mockAxiosGet } from "../../utls/http-requests-mock"; import { DeploymentService } from "../../../src/commands/deployment/deployment.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { FileService } from "../../../src/core/utils/file-service"; -import * as path from "path"; +import { getJsonFromFile } from "../../utls/fs-utils"; describe("Deployment list targets", () => { const firstTarget: TargetTransport = { @@ -34,9 +34,7 @@ describe("Deployment list targets", () => { const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const targetTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as DeployableTransport[]; + const targetTransports = getJsonFromFile(expectedFileName) as DeployableTransport[]; expect(targetTransports.length).toBe(2); const firstTargetTransport = targetTransports.filter(transport => transport.name === firstTarget.name)[0]; diff --git a/tests/commands/t2tc/t2tc-package-diff.spec.ts b/tests/commands/t2tc/t2tc-package-diff.spec.ts index f7d5a4ef..157d50f5 100644 --- a/tests/commands/t2tc/t2tc-package-diff.spec.ts +++ b/tests/commands/t2tc/t2tc-package-diff.spec.ts @@ -1,5 +1,3 @@ -import * as path from "path"; -import { mockCreateReadStream, mockExistsSync, mockReadFileSync } from "../../utls/fs-mock-utils"; import { PackageManifestTransport } from "../../../src/commands/configuration-management/interfaces/package-export.interfaces"; @@ -11,21 +9,19 @@ import { import { mockAxiosPost } from "../../utls/http-requests-mock"; import { T2tcCommandService } from "../../../src/commands/t2tc/t2tc-command.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; +import { loggingTestTransport } from "../../jest.setup"; import { ConfigUtils } from "../../utls/config-utils"; +import { getJsonFromDownloadedFile, zipToTempFolder } from "../../utls/fs-utils"; -function mockZipDiff(expectedUrl: string): PackageDiffTransport[] { +function createZip(): string { const manifest: PackageManifestTransport[] = []; manifest.push(ConfigUtils.buildManifestForKeyAndFlavor("package-key", "STUDIO")); + const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, []); + return zipToTempFolder(exportedPackagesZip); +} - const firstPackageNode = ConfigUtils.buildPackageNode("package-key", {metadata: {description: "test"}, variables: [], dependencies: []}); +function mockZipDiff(expectedUrl: string): PackageDiffTransport[] { const firstChildNode = ConfigUtils.buildChildNode("key-1", "package-key", "TEST"); - const firstPackageZip = ConfigUtils.buildExportPackageZip(firstPackageNode, [firstChildNode], "1.0.0"); - const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, [firstPackageZip]); - - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); const diffResponse: PackageDiffTransport[] = [{ packageKey: "package-key", @@ -58,22 +54,7 @@ function mockZipDiff(expectedUrl: string): PackageDiffTransport[] { describe("Config diff", () => { - beforeEach(() => { - mockExistsSync(); - }); - it("Should show on terminal if packages have changes with hasChanges set to true and jsonResponse false", async () => { - const manifest: PackageManifestTransport[] = []; - manifest.push(ConfigUtils.buildManifestForKeyAndFlavor("package-key", "STUDIO")); - - const firstPackageNode = ConfigUtils.buildPackageNode("package-key", {metadata: {description: "test"}, variables: [], dependencies: []}); - const firstChildNode = ConfigUtils.buildChildNode("key-1", "package-key", "TEST"); - const firstPackageZip = ConfigUtils.buildExportPackageZip(firstPackageNode, [firstChildNode], "1.0.0"); - const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, [firstPackageZip]); - - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); - const diffResponse: PackageDiffMetadata[] = [{ packageKey: "package-key", hasChanges: true @@ -81,7 +62,7 @@ describe("Config diff", () => { mockAxiosPost("https://myTeam.celonis.cloud/package-manager/api/core/packages/diff/configuration/has-changes", diffResponse); - await new T2tcCommandService(testContext).diffPackages("./packages.zip", true, null, false); + await new T2tcCommandService(testContext).diffPackages(createZip(), true, null, false); expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain( @@ -92,7 +73,7 @@ describe("Config diff", () => { it("Should show diff on terminal with hasChanges set to false and jsonResponse false", async () => { const diffResponse = mockZipDiff("https://myTeam.celonis.cloud/package-manager/api/core/packages/diff/configuration"); - await new T2tcCommandService(testContext).diffPackages("./packages.zip", false, null, false); + await new T2tcCommandService(testContext).diffPackages(createZip(), false, null, false); expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain( @@ -103,7 +84,7 @@ describe("Config diff", () => { it("Should compare with specified version", async () => { const diffResponse = mockZipDiff("https://myTeam.celonis.cloud/package-manager/api/core/packages/diff/configuration?baseVersion=1.0.0"); - await new T2tcCommandService(testContext).diffPackages("./packages.zip", false, "1.0.0", false); + await new T2tcCommandService(testContext).diffPackages(createZip(), false, "1.0.0", false); expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain( @@ -114,12 +95,9 @@ describe("Config diff", () => { it("Should generate a json file with diff info when hasChanges is set to false and jsonResponse is set to true", async () => { const diffResponse = mockZipDiff("https://myTeam.celonis.cloud/package-manager/api/core/packages/diff/configuration"); - await new T2tcCommandService(testContext).diffPackages("./packages.zip", false, null, true); - - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; + await new T2tcCommandService(testContext).diffPackages(createZip(), false, null, true); - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - const exportedPackageDiffTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageDiffTransport[]; + const exportedPackageDiffTransport = getJsonFromDownloadedFile() as PackageDiffTransport[]; expect(exportedPackageDiffTransport.length).toBe(1); const exportedFirstPackageDiffTransport = exportedPackageDiffTransport.filter(diffTransport => diffTransport.packageKey === "package-key"); @@ -134,9 +112,7 @@ describe("Config diff", () => { const firstChildNode = ConfigUtils.buildChildNode("key-1", "package-key", "TEST"); const firstPackageZip = ConfigUtils.buildExportPackageZip(firstPackageNode, [firstChildNode], "1.0.0"); const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, [firstPackageZip]); - - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); + const zipPath = zipToTempFolder(exportedPackagesZip); const diffResponse: PackageDiffMetadata[] = [{ packageKey: "package-key", @@ -145,12 +121,9 @@ describe("Config diff", () => { mockAxiosPost("https://myTeam.celonis.cloud/package-manager/api/core/packages/diff/configuration/has-changes", diffResponse); - await new T2tcCommandService(testContext).diffPackages("./packages.zip", true, null, true); - - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; + await new T2tcCommandService(testContext).diffPackages(zipPath, true, null, true); - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - const exportedPackageDiffTransport = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageDiffTransport[]; + const exportedPackageDiffTransport = getJsonFromDownloadedFile() as PackageDiffTransport[]; expect(exportedPackageDiffTransport.length).toBe(1); const exportedFirstPackageDiffTransport = exportedPackageDiffTransport.filter(diffTransport => diffTransport.packageKey === firstPackageNode.key); diff --git a/tests/commands/t2tc/t2tc-package-export.spec.ts b/tests/commands/t2tc/t2tc-package-export.spec.ts index 1c58008c..7cf81c0d 100644 --- a/tests/commands/t2tc/t2tc-package-export.spec.ts +++ b/tests/commands/t2tc/t2tc-package-export.spec.ts @@ -12,8 +12,7 @@ import { PackageManagerVariableType, VariableDefinition, VariablesAssignments, } from "../../../src/commands/studio/interfaces/package-manager.interfaces"; -import { loggingTestTransport, mockWriteSync } from "../../jest.setup"; -import { FileService } from "../../../src/core/utils/file-service"; +import { loggingTestTransport } from "../../jest.setup"; import { parse, stringify } from "../../../src/core/utils/json"; import { T2tcCommandService } from "../../../src/commands/t2tc/t2tc-command.service"; import { testContext } from "../../utls/test-context"; @@ -21,6 +20,7 @@ import { ConfigUtils } from "../../utls/config-utils"; import { PacmanApiUtils } from "../../utls/pacman-api.utils"; import { mockReadDirSync } from "../../utls/fs-mock-utils"; import { GitService } from "../../../src/core/git-profile/git/git.service"; +import { getDownloadedFileName } from "../../utls/fs-utils"; describe("Config export", () => { @@ -30,7 +30,6 @@ describe("Config export", () => { let mockGitServicePushToBranch: jest.SpyInstance; beforeEach(() => { - (fs.openSync as jest.Mock).mockReturnValue(100); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/spaces/space-1", {...firstSpace}); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/spaces/space-2", {...secondSpace}); @@ -62,12 +61,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(["key-1", "key-2", "key-3"], undefined, true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const studioManifest: StudioPackageManifest[] = parse(actualZip.getEntry(BatchExportImportConstants.STUDIO_FILE_NAME).getData().toString()); expect(studioManifest).toHaveLength(2); @@ -107,12 +101,8 @@ describe("Config export", () => { mockReadDirSync(["manifest.json", "studio.json", "variables.json"]); - (fs.mkdirSync as jest.Mock).mockImplementation(() => { - // Mock implementation for mkdirSync - }); - (fs.rmSync as jest.Mock).mockImplementation(() => { - // Mock implementation for rmSync - }); + jest.spyOn(fs, "rmSync").mockImplementation(() => {}); + jest.spyOn(fs, "chmodSync").mockImplementation(() => {}); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/core/packages/export/batch?packageKeys=key-1&packageKeys=key-2&packageKeys=key-3&withDependencies=true", exportedPackagesZip.toBuffer()); mockAxiosPost("https://myTeam.celonis.cloud/package-manager/api/core/packages/export/batch/variables-with-assignments", []); @@ -162,12 +152,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(undefined, ["key-1.1.0.1", "key-2.1.0.4", "key-3.1.2.0"], true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const studioManifest: StudioPackageManifest[] = parse(actualZip.getEntry(BatchExportImportConstants.STUDIO_FILE_NAME).getData().toString()); expect(studioManifest).toHaveLength(2); @@ -288,12 +273,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(["key-1", "key-2"], undefined, true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const exportedVariablesFileContent: VariableManifestTransport[] = parse(actualZip.getEntry(BatchExportImportConstants.VARIABLES_FILE_NAME).getData().toString()); expect(exportedVariablesFileContent).toHaveLength(2); @@ -452,12 +432,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(["key-1", "key-2"], undefined, true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const exportedVariablesFileContent: VariableManifestTransport[] = parse(actualZip.getEntry(BatchExportImportConstants.VARIABLES_FILE_NAME).getData().toString()); expect(exportedVariablesFileContent).toHaveLength(2); @@ -613,12 +588,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(undefined, ["key-1.1.0.2", "key-2.1.0.3"], true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const exportedVariablesFileContent: VariableManifestTransport[] = parse(actualZip.getEntry(BatchExportImportConstants.VARIABLES_FILE_NAME).getData().toString()); expect(exportedVariablesFileContent).toHaveLength(2); @@ -705,12 +675,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(["key-1", "key-2"], undefined, true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const firstPackageExportedZip = new AdmZip(actualZip.getEntry("key-1_1.0.0.zip").getData()); expect(firstPackageExportedZip.getEntry("nodes/child-1-scenario.json")).toBeNull(); @@ -747,12 +712,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(undefined, ["key-1.1.0.2", "key-2.1.0.3"], true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const firstPackageExportedZip = new AdmZip(actualZip.getEntry("key-1_1.0.2.zip").getData()); expect(firstPackageExportedZip.getEntry("nodes/child-1-scenario.json")).toBeNull(); @@ -863,12 +823,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(["key-1", "key-2"], undefined, true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const firstPackageExportedZip = new AdmZip(actualZip.getEntry("key-1_1.0.0.zip").getData()); const firstPackageExportedNode: NodeExportTransport = parse(firstPackageExportedZip.getEntry("package.json").getData().toString()); @@ -1004,12 +959,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(undefined, ["key-1.1.0.4", "key-2.1.0.5"], true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const firstPackageExportedZip = new AdmZip(actualZip.getEntry("key-1_1.0.4.zip").getData()); const firstPackageExportedNode: NodeExportTransport = parse(firstPackageExportedZip.getEntry("package.json").getData().toString()); @@ -1112,12 +1062,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(["key_with_underscores_1"], undefined, true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const firstPackageExportedZip = new AdmZip(actualZip.getEntry("key_with_underscores_1_1.0.0.zip").getData()); const firstPackageExportedNode: NodeExportTransport = parse(firstPackageExportedZip.getEntry("package.json").getData().toString()); @@ -1211,12 +1156,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(undefined, ["key_with_underscores_1.1.0.6"], true, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); - - const fileBuffer = mockWriteSync.mock.calls[0][1]; - const actualZip = new AdmZip(fileBuffer); + const actualZip = new AdmZip(getDownloadedFileName()); const firstPackageExportedZip = new AdmZip(actualZip.getEntry("key_with_underscores_1_1.0.6.zip").getData()); const firstPackageExportedNode: NodeExportTransport = parse(firstPackageExportedZip.getEntry("package.json").getData().toString()); @@ -1254,9 +1194,7 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(["key-1", "key-2", "key-3"], undefined, false, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); + expect(getDownloadedFileName()).not.toBeNull(); }) it("Should export by packageKeys without dependencies when packages are sent with keys and versions", async () => { @@ -1270,8 +1208,6 @@ describe("Config export", () => { await new T2tcCommandService(testContext).batchExportPackages(undefined, ["key-1.1.0.3", "key-2.1.0.4", "key-3.1.0.5"], false, null, null); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - expect(fs.openSync).toHaveBeenCalledWith(expectedFileName, expect.anything(), expect.anything()); - expect(mockWriteSync).toHaveBeenCalled(); + expect(getDownloadedFileName()).not.toBeNull(); }) }) \ No newline at end of file diff --git a/tests/commands/t2tc/t2tc-package-import.spec.ts b/tests/commands/t2tc/t2tc-package-import.spec.ts index f5430f63..16b15124 100644 --- a/tests/commands/t2tc/t2tc-package-import.spec.ts +++ b/tests/commands/t2tc/t2tc-package-import.spec.ts @@ -1,6 +1,4 @@ -import * as path from "path"; import AdmZip = require("adm-zip"); -import { mockCreateReadStream, mockExistsSync, mockReadDirSync, mockReadFileSync } from "../../utls/fs-mock-utils"; jest.mock("adm-zip", () => { const realAdmZip = jest.requireActual("adm-zip"); @@ -18,7 +16,7 @@ import { } from "../../utls/http-requests-mock"; import { T2tcCommandService } from "../../../src/commands/t2tc/t2tc-command.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { SpaceTransport } from "../../../src/commands/studio/interfaces/space.interface"; import { ContentNodeTransport, @@ -31,15 +29,12 @@ import { ConfigUtils } from "../../utls/config-utils"; import { stringify } from "../../../src/core/utils/json"; import { GitService } from "../../../src/core/git-profile/git/git.service"; import { FileService } from "../../../src/core/utils/file-service"; +import { getJsonFromFile, zipToTempFolder } from "../../utls/fs-utils"; describe("Config import", () => { const LOG_MESSAGE: string = "Config import report file: "; - beforeEach(() => { - mockExistsSync(); - }) - it.each([ true, false @@ -47,9 +42,8 @@ describe("Config import", () => { const manifest: PackageManifestTransport[] = []; manifest.push(ConfigUtils.buildManifestForKeyAndFlavor("key-1", "TEST")); const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, []); + const zipPath = zipToTempFolder(exportedPackagesZip); - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); const importResponse: PostPackageImportData[] = [{ @@ -62,10 +56,10 @@ describe("Config import", () => { mockAxiosPost("https://myTeam.celonis.cloud/package-manager/api/core/packages/import/batch", importResponse); - await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", null, overwrite, null); + await new T2tcCommandService(testContext).batchImportPackages(zipPath, null, overwrite, null); const expectedFileName = loggingTestTransport.logMessages[0].message.split(LOG_MESSAGE)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(importResponse), {encoding: "utf-8", mode: 0o600}); + expect(getJsonFromFile(expectedFileName)).toEqual(importResponse); }) it.each([ @@ -78,11 +72,13 @@ describe("Config import", () => { const manifest: PackageManifestTransport[] = []; manifest.push(ConfigUtils.buildManifestForKeyAndFlavor("key-1", "TEST")); const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, []); + const zipPath = zipToTempFolder(exportedPackagesZip); jest.spyOn(GitService.prototype, "pullFromBranch") .mockResolvedValue("mocked-pulled-git-path"); - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); + jest.spyOn(FileService.prototype, "isDirectory").mockReturnValueOnce(true); + jest.spyOn(FileService.prototype, "zipDirectoryInBatchExportFormat").mockReturnValue(zipPath); + mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); const importResponse: PostPackageImportData[] = [{ @@ -98,7 +94,7 @@ describe("Config import", () => { await new T2tcCommandService(testContext).batchImportPackages(null, null, overwrite, branchName); const expectedFileName = loggingTestTransport.logMessages[0].message.split(LOG_MESSAGE)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(importResponse), {encoding: "utf-8", mode: 0o600}); + expect(getJsonFromFile(expectedFileName)).toEqual(importResponse); }) it.each([ @@ -114,14 +110,12 @@ describe("Config import", () => { const returnedGitPath = "mocked-pulled-git-path"; jest.spyOn(GitService.prototype, "pullFromBranch") .mockResolvedValue(returnedGitPath); + jest.spyOn(FileService.prototype, "isDirectory").mockReturnValueOnce(true); - jest.spyOn(FileService.prototype, "zipDirectoryInBatchExportFormat") - .mockReturnValue("export_file.zip"); const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, []); - - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); - mockReadDirSync(["manifest.json", "variables.json"]); + const zipPath = zipToTempFolder(exportedPackagesZip); + jest.spyOn(FileService.prototype, "zipDirectoryInBatchExportFormat") + .mockReturnValue(zipPath); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); const importResponse: PostPackageImportData[] = [{ @@ -137,7 +131,7 @@ describe("Config import", () => { await new T2tcCommandService(testContext).batchImportPackages(null, null, overwrite, branchName); const expectedFileName = loggingTestTransport.logMessages[0].message.split(LOG_MESSAGE)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(importResponse), {encoding: "utf-8", mode: 0o600}); + expect(getJsonFromFile(expectedFileName)).toEqual(importResponse); }) it("Should batch import configs & map space ID as specified in manifest file for Studio Packages", async () => { @@ -150,6 +144,7 @@ describe("Config import", () => { const firstPackageNode = ConfigUtils.buildPackageNode("key-2", {variables: []}); const firstPackageZip = ConfigUtils.buildExportPackageZip(firstPackageNode, [], "1.0.0"); const exportedPackagesZip = ConfigUtils.buildBatchExportZipWithStudioManifest(manifest, studioManifest,[firstPackageZip]); + const zipPath = zipToTempFolder(exportedPackagesZip); const space: SpaceTransport = { id: "space-id", @@ -163,8 +158,6 @@ describe("Config import", () => { iconReference: "earth" }; - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/spaces", [space, otherSpace]); @@ -178,10 +171,10 @@ describe("Config import", () => { mockAxiosPost("https://myTeam.celonis.cloud/package-manager/api/core/packages/import/batch", importResponse); - await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", null, true, null); + await new T2tcCommandService(testContext).batchImportPackages(zipPath, null, true, null); const expectedFileName = loggingTestTransport.logMessages[0].message.split(LOG_MESSAGE)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(importResponse), {encoding: "utf-8", mode: 0o600}); + expect(getJsonFromFile(expectedFileName)).toEqual(importResponse); }) it("Should fail to map space ID as the space id specified in manifest file cannot be found", async () => { @@ -194,6 +187,7 @@ describe("Config import", () => { const firstPackageNode = ConfigUtils.buildPackageNode("key-2", {variables: []}); const firstPackageZip = ConfigUtils.buildExportPackageZip(firstPackageNode, [], "1.0.0"); const exportedPackagesZip = ConfigUtils.buildBatchExportZipWithStudioManifest(manifest, studioManifest,[firstPackageZip]); + const zipPath = zipToTempFolder(exportedPackagesZip); const space: SpaceTransport = { id: "space-id", @@ -201,13 +195,11 @@ describe("Config import", () => { iconReference: "earth" }; - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/spaces", [space]); await expect( - new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", null, true, null) + new T2tcCommandService(testContext).batchImportPackages(zipPath, null, true, null) ).rejects.toThrow("Provided space ID does not exist."); }) @@ -221,7 +213,7 @@ describe("Config import", () => { const firstPackageNode = ConfigUtils.buildPackageNode("key-2", {variables: []}); const firstPackageZip = ConfigUtils.buildExportPackageZip(firstPackageNode, [], "1.0.0"); const exportedPackagesZip = ConfigUtils.buildBatchExportZipWithStudioManifest(manifest, studioManifest,[firstPackageZip]); - + const zipPath = zipToTempFolder(exportedPackagesZip); const existingNode: Partial = { id: "node-id", @@ -234,8 +226,6 @@ describe("Config import", () => { iconReference: "earth" }; - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", [existingNode]); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/spaces", [space]); mockAxiosPut("https://myTeam.celonis.cloud/package-manager/api/packages/node-id/move/spaceId", {}); @@ -250,9 +240,9 @@ describe("Config import", () => { mockAxiosPost("https://myTeam.celonis.cloud/package-manager/api/core/packages/import/batch", importResponse); - await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", null, true, null); + await new T2tcCommandService(testContext).batchImportPackages(zipPath, null, true, null); const expectedFileName = loggingTestTransport.logMessages[0].message.split(LOG_MESSAGE)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(importResponse), {encoding: "utf-8", mode: 0o600}); + expect(getJsonFromFile(expectedFileName)).toEqual(importResponse); expect(mockedAxiosInstance.put).toHaveBeenCalledWith("https://myTeam.celonis.cloud/package-manager/api/packages/node-id/move/spaceId", expect.anything(), expect.anything()); }) @@ -266,14 +256,13 @@ describe("Config import", () => { const firstPackageNode = ConfigUtils.buildPackageNode("key-2", {variables: []}); const firstPackageZip = ConfigUtils.buildExportPackageZip(firstPackageNode, [], "1.0.0"); const exportedPackagesZip = ConfigUtils.buildBatchExportZipWithStudioManifest(manifest, studioManifest,[firstPackageZip]); + const zipPath = zipToTempFolder(exportedPackagesZip); const space: SpaceTransport = { id: "spaceId", name: "spaceName", iconReference: "earth" }; - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/spaces", [space]); @@ -287,10 +276,10 @@ describe("Config import", () => { mockAxiosPost("https://myTeam.celonis.cloud/package-manager/api/core/packages/import/batch", importResponse); - await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", null, true, null); + await new T2tcCommandService(testContext).batchImportPackages(zipPath, null, true, null); const expectedFileName = loggingTestTransport.logMessages[0].message.split(LOG_MESSAGE)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(importResponse), {encoding: "utf-8", mode: 0o600}); + expect(getJsonFromFile(expectedFileName)).toEqual(importResponse); expect(mockedAxiosInstance.put).not.toHaveBeenCalledWith("https://myTeam.celonis.cloud/package-manager/api/spaces", expect.anything(), expect.anything()); }) @@ -304,6 +293,7 @@ describe("Config import", () => { const firstPackageNode = ConfigUtils.buildPackageNode("key-2", {variables: []}); const firstPackageZip = ConfigUtils.buildExportPackageZip(firstPackageNode, [], "1.0.0"); const exportedPackagesZip = ConfigUtils.buildBatchExportZipWithStudioManifest(manifest, studioManifest,[firstPackageZip]); + const zipPath = zipToTempFolder(exportedPackagesZip); const space: SpaceTransport = { id: "space-id", @@ -317,8 +307,6 @@ describe("Config import", () => { iconReference: "earth" }; - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/spaces", [space]); mockAxiosPost("https://myTeam.celonis.cloud/package-manager/api/spaces", [newSpace]); @@ -334,10 +322,10 @@ describe("Config import", () => { mockAxiosPost("https://myTeam.celonis.cloud/package-manager/api/core/packages/import/batch", importResponse); - await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", null, true, null); + await new T2tcCommandService(testContext).batchImportPackages(zipPath, null, true, null); const expectedFileName = loggingTestTransport.logMessages[0].message.split(LOG_MESSAGE)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(importResponse), {encoding: "utf-8", mode: 0o600}); + expect(getJsonFromFile(expectedFileName)).toEqual(importResponse); expect(mockedAxiosInstance.put).not.toHaveBeenCalledWith("https://myTeam.celonis.cloud/package-manager/api/spaces", expect.anything(), expect.anything()); }) @@ -345,9 +333,8 @@ describe("Config import", () => { const manifest: PackageManifestTransport[] = []; manifest.push(ConfigUtils.buildManifestForKeyAndFlavor("key-1", "TEST")); const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, []); + const zipPath = zipToTempFolder(exportedPackagesZip); - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); const FIVE_GB = 5 * 1024 * 1024 * 1024; @@ -358,8 +345,8 @@ describe("Config import", () => { }); await expect( - new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", null, false, null) - ).rejects.toThrow('Failed to handle zip file "./export_file.zip": uncompressed size 5.00 GB exceeds the 4 GB limit.'); + new T2tcCommandService(testContext).batchImportPackages(zipPath, null, false, null) + ).rejects.toThrow(/Failed to handle zip file ".+": uncompressed size 5.00 GB exceeds the 4 GB limit./); }) it("Should assign studio runtime variable values after import", async () => { @@ -381,9 +368,7 @@ describe("Config import", () => { runtimeVariableAssignments: [variableAssignment] }]; exportedPackagesZip.addFile(BatchExportImportConstants.STUDIO_FILE_NAME, Buffer.from(stringify(studioManifest))); - - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); + const zipPath = zipToTempFolder(exportedPackagesZip); const importResponse: PostPackageImportData[] = [{ packageKey: "key-1", @@ -413,10 +398,10 @@ describe("Config import", () => { mockAxiosPost(assignVariablesUrl, {}); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", [node]); - await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", null, true, null); + await new T2tcCommandService(testContext).batchImportPackages(zipPath, null, true, null); const expectedFileName = loggingTestTransport.logMessages[0].message.split(LOG_MESSAGE)[1]; - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), JSON.stringify(importResponse), {encoding: "utf-8", mode: 0o600}); + expect(getJsonFromFile(expectedFileName)).toEqual(importResponse); expect(mockedPostRequestBodyByUrl.get(assignVariablesUrl)).toEqual(JSON.stringify([variableAssignment])); }) @@ -425,9 +410,8 @@ describe("Config import", () => { const manifest: PackageManifestTransport[] = []; manifest.push(ConfigUtils.buildManifestForKeyAndFlavor("key-1", "TEST")); const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, []); + const zipPath = zipToTempFolder(exportedPackagesZip); - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); const importResponse: PostPackageImportData[] = [{ @@ -440,7 +424,7 @@ describe("Config import", () => { mockAxiosPost("https://myTeam.celonis.cloud/package-manager/api/core/packages/import/batch", importResponse); - await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", null, false, null, true); + await new T2tcCommandService(testContext).batchImportPackages(zipPath, null, false, null, true); expect(mockedAxiosInstance.post).toHaveBeenCalledWith( expect.stringContaining("/package-manager/api/core/packages/import/batch"), diff --git a/tests/commands/t2tc/t2tc-package-list.spec.ts b/tests/commands/t2tc/t2tc-package-list.spec.ts index 3af2ec6c..fa8510a3 100644 --- a/tests/commands/t2tc/t2tc-package-list.spec.ts +++ b/tests/commands/t2tc/t2tc-package-list.spec.ts @@ -1,17 +1,16 @@ -import * as path from "path"; import { PacmanApiUtils } from "../../utls/pacman-api.utils"; import { mockAxiosGet } from "../../utls/http-requests-mock"; import { T2tcCommandService } from "../../../src/commands/t2tc/t2tc-command.service"; import { testContext } from "../../utls/test-context"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { ContentNodeTransport, PackageWithVariableAssignments, StudioComputeNodeDescriptor, } from "../../../src/commands/studio/interfaces/package-manager.interfaces"; -import { FileService } from "../../../src/core/utils/file-service"; import { PackageExportTransport } from "../../../src/commands/configuration-management/interfaces/package-export.interfaces"; +import { getJsonFromDownloadedFile } from "../../utls/fs-utils"; describe("Config list", () => { @@ -52,11 +51,7 @@ describe("Config list", () => { await new T2tcCommandService(testContext).listPackages(true, [], false, [], undefined, null, null, false, false); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const exportedTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageExportTransport[]; + const exportedTransports = getJsonFromDownloadedFile() as PackageExportTransport[]; expect(exportedTransports.length).toBe(2); const exportedFirstPackage = exportedTransports.filter(transport => transport.key === firstPackage.key)[0]; @@ -98,11 +93,7 @@ describe("Config list", () => { await new T2tcCommandService(testContext).listPackages(true, [], true, [], undefined, null, null, false, false); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const exportedTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageExportTransport[]; + const exportedTransports = getJsonFromDownloadedFile() as PackageExportTransport[]; expect(exportedTransports.length).toBe(2); const exportedFirstPackage = exportedTransports.filter(transport => transport.key === firstPackage.key)[0]; @@ -123,11 +114,7 @@ describe("Config list", () => { await new T2tcCommandService(testContext).listPackages(true, [], false, [firstPackage.key, secondPackage.key], undefined, null, null, false, false); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const exportedTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageExportTransport[]; + const exportedTransports = getJsonFromDownloadedFile() as PackageExportTransport[]; expect(exportedTransports.length).toBe(2); const exportedFirstPackage = exportedTransports.filter(transport => transport.key === firstPackage.key)[0]; @@ -169,11 +156,7 @@ describe("Config list", () => { await new T2tcCommandService(testContext).listPackages(true, [], true, [firstPackage.key, secondPackage.key], undefined, null, null, false, false); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const exportedTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageExportTransport[]; + const exportedTransports = getJsonFromDownloadedFile() as PackageExportTransport[]; expect(exportedTransports.length).toBe(2); const exportedFirstPackage = exportedTransports.filter(transport => transport.key === firstPackage.key)[0]; @@ -207,11 +190,7 @@ describe("Config list", () => { await new T2tcCommandService(testContext).listPackages(true, [], false, [], undefined, "1", null, false, false); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const exportedTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageExportTransport[]; + const exportedTransports = getJsonFromDownloadedFile() as PackageExportTransport[]; expect(exportedTransports.length).toBe(2); }) @@ -262,11 +241,7 @@ describe("Config list", () => { await new T2tcCommandService(testContext).listPackages(true, [], false, [], keysByVersion, null, null, false, false); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const exportedTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageExportTransport[]; + const exportedTransports = getJsonFromDownloadedFile() as PackageExportTransport[]; expect(exportedTransports.length).toBe(2); const exportedFirstPackage = exportedTransports.filter(transport => transport.key === firstPackage.key)[0]; @@ -321,11 +296,7 @@ describe("Config list", () => { await new T2tcCommandService(testContext).listPackages(true, ["STUDIO"], false, [], undefined, null, null, false, true); - const expectedFileName = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; - - expect(mockWriteFileSync).toHaveBeenCalledWith(path.resolve(process.cwd(), expectedFileName), expect.any(String), {encoding: "utf-8", mode: 0o600}); - - const exportedTransports = JSON.parse(mockWriteFileSync.mock.calls[0][1]) as PackageExportTransport[]; + const exportedTransports = getJsonFromDownloadedFile() as PackageExportTransport[]; expect(exportedTransports.length).toBe(2); const exportedFirstPackage = exportedTransports.find(transport => transport.key === firstPackage.key); diff --git a/tests/commands/view/view-bookmarks.spec.ts b/tests/commands/view/view-bookmarks.spec.ts index 1767e11a..b23ad4a0 100644 --- a/tests/commands/view/view-bookmarks.spec.ts +++ b/tests/commands/view/view-bookmarks.spec.ts @@ -1,11 +1,11 @@ import * as fs from "node:fs"; import * as path from "node:path"; import { mockAxiosGet, mockAxiosPost, mockedAxiosInstance } from "../../utls/http-requests-mock"; -import { mockCreateReadStream, mockExistsSync } from "../../utls/fs-mock-utils"; import { ViewBookmarksCommandService } from "../../../src/commands/view/view-bookmarks-command.service"; import { ViewBookmarksManagerFactory } from "../../../src/commands/view/view-bookmarks.manager-factory"; -import { loggingTestTransport, mockWriteFileSync } from "../../jest.setup"; +import { loggingTestTransport } from "../../jest.setup"; import { testContext } from "../../utls/test-context"; +import { getJsonFromDownloadedFile, writeJsonTempFile } from "../../utls/fs-utils"; describe("View bookmarks", () => { @@ -26,11 +26,7 @@ describe("View bookmarks", () => { await new ViewBookmarksCommandService(testContext).pullViewBookmarks(boardId, undefined); expect(mockedAxiosInstance.get).toHaveBeenCalledWith(`${exportBaseUrl}&type=USER`, expect.anything()); - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), `studio_view_bookmarks_${boardId}.json`), - JSON.stringify(bookmarksResponse), - { encoding: "utf-8", mode: 0o600 } - ); + expect(getJsonFromDownloadedFile()).toEqual(bookmarksResponse); expect(loggingTestTransport.logMessages.length).toBe(1); expect(loggingTestTransport.logMessages[0].message).toContain("File downloaded successfully. New filename: "); }); @@ -41,19 +37,14 @@ describe("View bookmarks", () => { await new ViewBookmarksCommandService(testContext).pullViewBookmarks(boardId, "SHARED"); expect(mockedAxiosInstance.get).toHaveBeenCalledWith(`${exportBaseUrl}&type=SHARED`, expect.anything()); - expect(mockWriteFileSync).toHaveBeenCalledWith( - path.resolve(process.cwd(), `studio_view_bookmarks_${boardId}.json`), - JSON.stringify(bookmarksResponse), - { encoding: "utf-8", mode: 0o600 } - ); + expect(getJsonFromDownloadedFile()).toEqual(bookmarksResponse); }); }); describe("push", () => { it("Should call import API with the file as multipart body", async () => { mockAxiosPost(importUrl, {}); - mockExistsSync(); - mockCreateReadStream(Buffer.from(JSON.stringify(bookmarksResponse))); + writeJsonTempFile("bookmarks.json", bookmarksResponse); await new ViewBookmarksCommandService(testContext).pushViewBookmarks(boardId, "bookmarks.json"); @@ -65,7 +56,6 @@ describe("View bookmarks", () => { describe("manager factory", () => { it("Should report a fatal error when the push file does not exist", () => { - (fs.existsSync as jest.Mock).mockReturnValue(false); const exitSpy = jest.spyOn(process, "exit").mockImplementation((() => undefined) as never); new ViewBookmarksManagerFactory(testContext).createViewBookmarksManager("missing.json", boardId); diff --git a/tests/core/profile/profile.service.spec.ts b/tests/core/profile/profile.service.spec.ts index 217c8ccf..07dc59bc 100644 --- a/tests/core/profile/profile.service.spec.ts +++ b/tests/core/profile/profile.service.spec.ts @@ -38,6 +38,7 @@ jest.mock("../../../src/core/utils/logger", () => ({ })); import { ProfileService } from "../../../src/core/profile/profile.service"; +import { Dirent } from "node:fs"; describe("ProfileService - mapCelonisEnvProfile", () => { let profileService: ProfileService; @@ -302,7 +303,7 @@ describe("ProfileService - findProfile", () => { }; const profileFilePath = path.resolve(mockProfilePath, `${profileName}.json`); - (fs.readFileSync as jest.Mock).mockReturnValue(JSON.stringify(mockProfile)); + jest.spyOn(fs, "readFileSync").mockReturnValue(JSON.stringify(mockProfile)); process.env.TEAM_URL = "https://env.celonis.cloud"; process.env.API_TOKEN = "env-token"; @@ -326,8 +327,7 @@ describe("ProfileService - findProfile", () => { type: ProfileType.KEY }; - const profileFilePath = path.resolve(mockProfilePath, `${profileName}.json`); - (fs.readFileSync as jest.Mock).mockReturnValue(JSON.stringify(mockProfile)); + jest.spyOn(fs, "readFileSync").mockReturnValue(JSON.stringify(mockProfile)); const refreshProfileSpy = jest.spyOn(profileService, "refreshProfile").mockResolvedValue(undefined); @@ -868,8 +868,8 @@ describe("ProfileService - makeDefaultProfile", () => { }); it("should call findProfile and store default profile name in config", async () => { - (fs.existsSync as jest.Mock).mockReturnValue(true); - (fs.writeFileSync as jest.Mock).mockImplementation(() => {}); + jest.spyOn(fs, "existsSync").mockReturnValue(true); + jest.spyOn(fs, "writeFileSync").mockImplementation(() => {}); await profileService.makeDefaultProfile("my-profile"); @@ -896,8 +896,8 @@ describe("ProfileService - getDefaultProfile", () => { }); it("should return default profile name when config exists", () => { - (fs.existsSync as jest.Mock).mockReturnValue(true); - (fs.readFileSync as jest.Mock).mockReturnValue(JSON.stringify({ defaultProfile: "my-default" })); + jest.spyOn(fs, "existsSync").mockReturnValue(true); + jest.spyOn(fs, "readFileSync").mockReturnValue(JSON.stringify({ defaultProfile: "my-default" })); const result = profileService.getDefaultProfile(); @@ -906,12 +906,11 @@ describe("ProfileService - getDefaultProfile", () => { }); it("should return null when config file does not exist", () => { - (fs.existsSync as jest.Mock).mockReturnValue(false); + jest.spyOn(fs, "existsSync").mockReturnValue(false); const result = profileService.getDefaultProfile(); expect(result).toBeNull(); - expect(fs.readFileSync).not.toHaveBeenCalled(); }); }); @@ -923,12 +922,13 @@ describe("ProfileService - storeProfile", () => { beforeEach(() => { (os.homedir as jest.Mock).mockReturnValue(mockHomedir); profileService = new ProfileService(); - (fs.existsSync as jest.Mock).mockReturnValue(true); - (fs.writeFileSync as jest.Mock).mockImplementation(() => {}); + jest.spyOn(fs, "existsSync").mockReturnValue(true); + jest.spyOn(fs, "writeFileSync").mockImplementation(() => {}); + jest.spyOn(fs, "mkdirSync").mockReturnValue(mockProfilePath); }); it("should create profile container if not exists and write profile with normalized team URL", async () => { - (fs.existsSync as jest.Mock).mockReturnValue(false); + jest.spyOn(fs, "existsSync").mockReturnValue(false); const profile: Profile = { name: "test-profile", @@ -997,13 +997,13 @@ describe("ProfileService - getAllFilesInDirectory", () => { }); it("should return profile names (without .json) when directory exists", () => { - (fs.existsSync as jest.Mock).mockReturnValue(true); - (fs.readdirSync as jest.Mock).mockReturnValue([ + jest.spyOn(fs, "existsSync").mockReturnValue(true); + jest.spyOn(fs, "readdirSync").mockReturnValue([ { name: "profile1.json", isDirectory: () => false }, { name: "profile2.json", isDirectory: () => false }, { name: "config.json", isDirectory: () => false }, { name: "subdir", isDirectory: () => true }, - ]); + ] as Dirent[]); const result = profileService.getAllFilesInDirectory(); @@ -1012,12 +1012,11 @@ describe("ProfileService - getAllFilesInDirectory", () => { }); it("should return empty array when directory does not exist", () => { - (fs.existsSync as jest.Mock).mockReturnValue(false); + jest.spyOn(fs, "existsSync").mockReturnValue(false); const result = profileService.getAllFilesInDirectory(); expect(result).toEqual([]); - expect(fs.readdirSync).not.toHaveBeenCalled(); }); }); diff --git a/tests/core/utils/file.service.spec.ts b/tests/core/utils/file.service.spec.ts index 11c6ffe8..a166b2ba 100644 --- a/tests/core/utils/file.service.spec.ts +++ b/tests/core/utils/file.service.spec.ts @@ -1,18 +1,16 @@ -jest.unmock("fs"); - -import * as fs from "fs"; +import * as fs from "node:fs"; import * as path from "path"; import * as os from "os"; import * as AdmZip from "adm-zip"; import { FileService } from "../../../src/core/utils/file-service"; -import { FatalError } from "../../../src/core/utils/logger"; +import { FatalError, logger } from "../../../src/core/utils/logger"; describe("FileService", () => { let fileService: FileService; const tempDir = path.join(os.tmpdir(), "file-service-test"); const symLinkSourceTempDir = path.join(os.tmpdir(), "file-service-symlink-source"); - beforeEach(() => { + beforeAll(() => { fileService = new FileService(); if (!fs.existsSync(tempDir)) { @@ -26,13 +24,21 @@ describe("FileService", () => { fileService = new FileService(); }); - afterEach(() => { + afterAll(() => { if (fs.existsSync(tempDir)) { - fs.rmSync(tempDir, { recursive: true, force: true }); + try { + fs.rmSync(tempDir, { recursive: true, force: true }); + } catch (e) { + logger.warn(`Could not delete: ${tempDir}`); + } } if (fs.existsSync(symLinkSourceTempDir)) { - fs.rmSync(symLinkSourceTempDir, { recursive: true, force: true }); + try { + fs.rmSync(symLinkSourceTempDir, { recursive: true, force: true }); + } catch (e) { + logger.warn(`Could not delete: ${tempDir}`); + } } }); diff --git a/tests/jest.setup.ts b/tests/jest.setup.ts index 54cc8944..bd916be5 100644 --- a/tests/jest.setup.ts +++ b/tests/jest.setup.ts @@ -1,23 +1,43 @@ // Mock the modules using Jest -import * as fs from "fs"; +import * as fs from "node:fs"; import { mockAxios } from "./utls/http-requests-mock"; import { LoggingTestTransport } from "./utls/logging-test-transport"; import { logger } from "../src/core/utils/logger"; +import { tmpdir } from "os" +import { join } from "path"; + +import process = require("process"); mockAxios(); -jest.mock("fs"); -jest.mock("node:fs", () => require("fs")); -const mockWriteFileSync = jest.fn(); -(fs.writeFileSync as jest.Mock).mockImplementation(mockWriteFileSync); +let tempDir = null; +beforeAll(done => { + fs.mkdtemp(join(tmpdir(), "jest"), (err, dir) => { + tempDir = dir; + done(); + }); +}); -const mockWriteSync = jest.fn(); -(fs.writeSync as jest.Mock).mockImplementation(mockWriteSync); +beforeEach(() => { + const spy = jest.spyOn(process, "cwd"); + spy.mockReturnValue(tempDir); +}); afterEach(() => { jest.clearAllMocks(); }); +afterAll(() => { + if (tempDir !== null) { + logger.info(`Removing tempdir: ${tempDir}`); + try { + fs.rmSync(tempDir, { recursive: true, force: true }); + } catch (e) { + logger.warn(`Could not delete tempdir: ${tempDir}`, e); + } + } +}); + let loggingTestTransport: LoggingTestTransport; beforeEach(() => { @@ -26,4 +46,4 @@ beforeEach(() => { logger.add(loggingTestTransport); }); -export {loggingTestTransport, mockWriteFileSync, mockWriteSync}; \ No newline at end of file +export {loggingTestTransport}; \ No newline at end of file diff --git a/tests/utls/fs-mock-utils.ts b/tests/utls/fs-mock-utils.ts index 5dcb55f8..254324dc 100644 --- a/tests/utls/fs-mock-utils.ts +++ b/tests/utls/fs-mock-utils.ts @@ -1,25 +1,5 @@ -import * as fs from "fs"; -import {Readable} from "stream"; - -export function mockReadFileSync(data: any): void { - (fs.readFileSync as jest.Mock).mockReturnValue(data); -} +import fs = require("node:fs"); export function mockReadDirSync(data: any): void { - (fs.readdirSync as jest.Mock).mockReturnValue(data); -} - -export function mockCreateReadStream(data: any): void { - const stream = new Readable(); - stream.push(data); - stream.push(null); - (fs.createReadStream as jest.Mock).mockReturnValue(stream); + jest.spyOn(fs, "readdirSync").mockReturnValue(data); } - -export function mockExistsSync(): void { - (fs.existsSync as jest.Mock).mockReturnValue(true); -} - -export function mockExistsSyncOnce(): void { - (fs.existsSync as jest.Mock).mockReturnValueOnce(true); -} \ No newline at end of file diff --git a/tests/utls/fs-utils.ts b/tests/utls/fs-utils.ts new file mode 100644 index 00000000..b026934f --- /dev/null +++ b/tests/utls/fs-utils.ts @@ -0,0 +1,45 @@ +import { readFileSync, mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { loggingTestTransport } from "../jest.setup"; +import { FileService } from "../../src/core/utils/file-service"; +import { v4 as uuid } from "uuid"; +import AdmZip = require("adm-zip"); + +export function getDownloadedFileName(): string { + const filename = loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; + return resolve(process.cwd(), filename); +} + +export function getJsonFromDownloadedFile(): any { + return getJsonFromFile(getDownloadedFileName()); +} + +export function getJsonFromFile(filename: string): any { + const fullPath = resolve(process.cwd(), filename); + const fileContents = readFileSync(fullPath, "utf8"); + return JSON.parse(fileContents); +} + +export function writeJsonTempFile(filename: string, contents: any): void { + writeTempFile(filename, JSON.stringify(contents)); +} + +export function writeTempFile(filename: string, contents: any): void { + const fullPath = resolve(process.cwd(), filename); + writeFileSync(fullPath, contents); +} +export function makeTempDir(): string { + const folder = uuid(); + return makeTempDirWithName(folder); +} +export function makeTempDirWithName(folder: string): string { + const fullPath = resolve(process.cwd(), folder); + mkdirSync(fullPath); + return fullPath; +} + +export function zipToTempFolder(zip: AdmZip): string { + const fullPath = resolve(process.cwd(), `${uuid()}.zip`); + zip.writeZip(fullPath); + return fullPath; +} \ No newline at end of file