diff --git a/src/commands/asset-registry/asset-registry.service.ts b/src/commands/asset-registry/asset-registry.service.ts index 70c93cf..965879a 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/variable.service.ts b/src/commands/configuration-management/variable.service.ts index 08945ab..462afcb 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 aed3267..3e1e637 100644 --- a/src/commands/t2tc/t2tc-package.service.ts +++ b/src/commands/t2tc/t2tc-package.service.ts @@ -142,7 +142,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); diff --git a/src/core/utils/file-service.ts b/src/core/utils/file-service.ts index cbf232b..1856feb 100644 --- a/src/core/utils/file-service.ts +++ b/src/core/utils/file-service.ts @@ -16,7 +16,7 @@ export class FileService { }); } - 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 bdd4bcf..4249470 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 09e9d9c..f5ec4fc 100644 --- a/tests/commands/action-flows/export-action-flows.spec.ts +++ b/tests/commands/action-flows/export-action-flows.spec.ts @@ -1,13 +1,12 @@ 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 { loggingTestTransport } from "../../jest.setup"; import { FileService } from "../../../src/core/utils/file-service"; -import { mockExistsSyncOnce, mockReadFileSync } from "../../utls/fs-mock-utils"; 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 +68,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 +77,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 +121,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 +129,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 6be51b7..7bd8935 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 } from "../../utls/fs-utils"; describe("Import action-flows", () => { @@ -28,7 +27,7 @@ describe("Import action-flows", () => { const resp = { data: mockImportResponse }; (mockedAxiosInstance.post as jest.Mock).mockResolvedValue(resp); const zip = new AdmZip(); - mockCreateReadStream(zip.toBuffer()); + zip.writeZip("tmp.zip"); await new ActionFlowCommandService(testContext).importActionFlows(packageId, "tmp", true, false); @@ -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()); + zip.writeZip("tmp.zip"); await new ActionFlowCommandService(testContext).importActionFlows(packageId, "tmp", 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 066d81b..c03e675 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 6d863d3..c727566 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 04619c8..5d5e28d 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 f85e4c3..6e65d80 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 4a63d99..8e0a40b 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 e756516..6805190 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 bc8e335..238029f 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 2b6e5f6..4e5939a 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 cafa8f7..bf07e3b 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 820fc62..e7b8e2f 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 6721e2f..4f06d82 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 6be73f8..2b4501e 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 6d89126..14d048c 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 39cd6df..430388f 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 0f35ea0..879943b 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 db0175c..40f37ba 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 d04bb36..c023d72 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 54bbaa1..26581da 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-import.spec.ts b/tests/commands/configuration-management/single-package-import.spec.ts index 5d74973..d569d29 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 } from "../../utls/fs-utils"; const IMPORT_URL = "https://myTeam.celonis.cloud/pacman/api/core/staging/packages/import-file"; @@ -66,18 +59,9 @@ 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()); + packageZip.writeZip("package.zip"); const importResponse = buildImportResponse(); mockAxiosPost(IMPORT_URL, importResponse); @@ -94,47 +78,35 @@ 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()); + packageZip.writeZip("package.zip"); const importResponse = buildImportResponse(); mockAxiosPost(IMPORT_URL, importResponse); await new SinglePackageImportService(testContext).importPackage("./package.zip", 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()); - + packageZip.writeZip("package.zip"); mockAxiosPost(IMPORT_URL, buildImportResponse()); await new SinglePackageImportService(testContext).importPackage("./package.zip", null, true, false); @@ -176,10 +148,6 @@ 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 FIVE_GB = 5 * 1024 * 1024 * 1024; (AdmZip as unknown as jest.Mock).mockImplementationOnce((...args: any[]) => { const instance = jest.requireActual("adm-zip")(...args); @@ -191,4 +159,5 @@ describe("Single package import", () => { 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.'); }); + }); diff --git a/tests/commands/deployment/deployment-create.spec.ts b/tests/commands/deployment/deployment-create.spec.ts index 28b26d1..d09ff30 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 08861f7..6efa58e 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 aff361b..1d08a30 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 31e86f0..ecb8946 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 fa672d6..688bfcd 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 f7d5a4e..04be7e8 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,9 +9,9 @@ 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 } from "../../utls/fs-utils"; function mockZipDiff(expectedUrl: string): PackageDiffTransport[] { const manifest: PackageManifestTransport[] = []; @@ -23,9 +21,7 @@ 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()); + exportedPackagesZip.writeZip("packages.zip"); const diffResponse: PackageDiffTransport[] = [{ packageKey: "package-key", @@ -58,10 +54,6 @@ 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")); @@ -70,9 +62,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()); + exportedPackagesZip.writeZip("packages.zip"); const diffResponse: PackageDiffMetadata[] = [{ packageKey: "package-key", @@ -116,10 +106,7 @@ describe("Config diff", () => { await new T2tcCommandService(testContext).diffPackages("./packages.zip", 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 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 +121,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()); + exportedPackagesZip.writeZip("packages.zip"); const diffResponse: PackageDiffMetadata[] = [{ packageKey: "package-key", @@ -147,10 +132,7 @@ describe("Config diff", () => { await new T2tcCommandService(testContext).diffPackages("./packages.zip", 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 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 1c58008..7cf81c0 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 f5430f6..6f7fe47 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 } 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, []); + exportedPackagesZip.writeZip("export_file.zip"); - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); const importResponse: PostPackageImportData[] = [{ @@ -65,7 +59,7 @@ describe("Config import", () => { await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", 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, []); + exportedPackagesZip.writeZip("export_temp.zip") 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("export_temp.zip"); + 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,13 @@ 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, []); + exportedPackagesZip.writeZip("export_file.zip") - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); - mockReadDirSync(["manifest.json", "variables.json"]); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); const importResponse: PostPackageImportData[] = [{ @@ -137,7 +132,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 +145,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]); + exportedPackagesZip.writeZip("export_file.zip"); const space: SpaceTransport = { id: "space-id", @@ -163,8 +159,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]); @@ -181,7 +175,7 @@ describe("Config import", () => { await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", 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 +188,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]); + exportedPackagesZip.writeZip("export_file.zip"); const space: SpaceTransport = { id: "space-id", @@ -201,8 +196,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]); @@ -221,7 +214,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]); - + exportedPackagesZip.writeZip("export_file.zip"); const existingNode: Partial = { id: "node-id", @@ -234,8 +227,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", {}); @@ -252,7 +243,7 @@ describe("Config import", () => { await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", 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 +257,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]); + exportedPackagesZip.writeZip("export_file.zip"); 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]); @@ -290,7 +280,7 @@ describe("Config import", () => { await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", 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 +294,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]); + exportedPackagesZip.writeZip("export_file.zip"); const space: SpaceTransport = { id: "space-id", @@ -317,8 +308,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]); @@ -337,7 +326,7 @@ describe("Config import", () => { await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", 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 +334,8 @@ describe("Config import", () => { const manifest: PackageManifestTransport[] = []; manifest.push(ConfigUtils.buildManifestForKeyAndFlavor("key-1", "TEST")); const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, []); + exportedPackagesZip.writeZip("export_file.zip"); - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); const FIVE_GB = 5 * 1024 * 1024 * 1024; @@ -381,9 +369,7 @@ describe("Config import", () => { runtimeVariableAssignments: [variableAssignment] }]; exportedPackagesZip.addFile(BatchExportImportConstants.STUDIO_FILE_NAME, Buffer.from(stringify(studioManifest))); - - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); + exportedPackagesZip.writeZip("export_file.zip"); const importResponse: PostPackageImportData[] = [{ packageKey: "key-1", @@ -416,7 +402,7 @@ describe("Config import", () => { await new T2tcCommandService(testContext).batchImportPackages("./export_file.zip", 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 +411,8 @@ describe("Config import", () => { const manifest: PackageManifestTransport[] = []; manifest.push(ConfigUtils.buildManifestForKeyAndFlavor("key-1", "TEST")); const exportedPackagesZip = ConfigUtils.buildBatchExportZip(manifest, []); + exportedPackagesZip.writeZip("export_file.zip"); - mockReadFileSync(exportedPackagesZip.toBuffer()); - mockCreateReadStream(exportedPackagesZip.toBuffer()); mockAxiosGet("https://myTeam.celonis.cloud/package-manager/api/packages", []); const importResponse: PostPackageImportData[] = [{ diff --git a/tests/commands/t2tc/t2tc-package-list.spec.ts b/tests/commands/t2tc/t2tc-package-list.spec.ts index 3af2ec6..fa8510a 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 1767e11..b23ad4a 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 217c8cc..07dc59b 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 ca11f68..e508477 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 54cc894..b4e404a 100644 --- a/tests/jest.setup.ts +++ b/tests/jest.setup.ts @@ -1,23 +1,40 @@ // 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"; -mockAxios(); -jest.mock("fs"); -jest.mock("node:fs", () => require("fs")); +import process = require("process"); -const mockWriteFileSync = jest.fn(); -(fs.writeFileSync as jest.Mock).mockImplementation(mockWriteFileSync); +mockAxios(); -const mockWriteSync = jest.fn(); -(fs.writeSync as jest.Mock).mockImplementation(mockWriteSync); +let tempDir = null; +beforeAll(done => { + fs.mkdtemp(join(tmpdir(), "jest"), (err, dir) => { + const spy = jest.spyOn(process, "cwd"); + spy.mockReturnValue(dir); + tempDir = dir; + done(); + }); +}); 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 +43,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 5dcb55f..254324d 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 0000000..80dc956 --- /dev/null +++ b/tests/utls/fs-utils.ts @@ -0,0 +1,37 @@ +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"; + +export function getDownloadedFileName(): string { + return loggingTestTransport.logMessages[0].message.split(FileService.fileDownloadedMessage)[1]; +} + +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; +} \ No newline at end of file