From 3e7afe70ad13f4cdfacf5211e8d6c433f75f24b4 Mon Sep 17 00:00:00 2001 From: lmgyuan Date: Fri, 24 May 2024 17:14:57 -0400 Subject: [PATCH] fixed logging issue --- jest.config.js | 1 + lib/generator.js | 8 ++++---- lib/logMessages.js | 7 ++++++- lib/renderer/react.js | 15 ++++++--------- package.json | 4 ++-- test/integration.test.js | 19 +++++++------------ 6 files changed, 26 insertions(+), 28 deletions(-) diff --git a/jest.config.js b/jest.config.js index b3451c7c6..39544262b 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,5 +1,6 @@ module.exports = { clearMocks: true, + modulePathIgnorePatterns: ["./__mocks__(?!/loglevel.js)"], moduleNameMapper: { '^nimma/legacy$': '/node_modules/nimma/dist/legacy/cjs/index.js', '^nimma/(.*)': '/node_modules/nimma/dist/cjs/$1', diff --git a/lib/generator.js b/lib/generator.js index c55657b57..1d9941c62 100644 --- a/lib/generator.js +++ b/lib/generator.js @@ -145,8 +145,8 @@ class Generator { } }); }); - // PR 1162: set log level during construction to avoid asynchronous issues - this.setLogLevel(); + // // PR 1162: set log level during construction to avoid asynchronous issues + // this.setLogLevel(); } /** @@ -200,7 +200,7 @@ class Generator { this.validateAsyncAPIDocument(asyncapiDocument); await this.setupOutput(); // PR 1162: always set log level during construction to avoid asynchronous issues - // this.setLogLevel(); + this.setLogLevel(); await this.installAndSetupTemplate(); await this.configureTemplateWorkflow(parseOptions); @@ -856,7 +856,7 @@ class Generator { if (renderContent === undefined) { return; } else if (isReactTemplate(this.templateConfig)) { - await saveRenderedReactContent(renderContent, outputPath, this.noOverwriteGlobs); + await saveRenderedReactContent(renderContent, outputPath, this.noOverwriteGlobs, this); } else { await writeFile(outputPath, renderContent); } diff --git a/lib/logMessages.js b/lib/logMessages.js index 4bbcd82c1..d3be3f20b 100644 --- a/lib/logMessages.js +++ b/lib/logMessages.js @@ -46,6 +46,10 @@ function conditionalFilesMatched(relativeSourceFile) { return `${relativeSourceFile} was not generated because condition specified for this file in template configuration in conditionalFiles matched.`; } +function skipOverwriting(filePath) { + return `Skipping overwrite for: ${filePath}`; +} + module.exports = { TEMPLATE_INSTALL_FLAG_MSG, TEMPLATE_INSTALL_DISK_MSG, @@ -59,6 +63,7 @@ module.exports = { templateSuccessfullyInstalled, relativeSourceFileNotGenerated, conditionalFilesMatched, - fileNotOverwritten + fileNotOverwritten, + skipOverwriting }; \ No newline at end of file diff --git a/lib/renderer/react.js b/lib/renderer/react.js index 268fe2cfd..45213e544 100644 --- a/lib/renderer/react.js +++ b/lib/renderer/react.js @@ -2,6 +2,7 @@ const path = require('path'); const AsyncReactSDK = require('@asyncapi/generator-react-sdk'); const minimatch = require('minimatch'); const log = require('loglevel'); +const logMessages = require('../logMessages'); const { writeFile } = require('../utils'); @@ -61,7 +62,7 @@ reactExport.renderReact = async (asyncapiDocument, filePath, extraTemplateData, * @param {String} outputPath Path to the file being rendered. * @param {String[]} noOverwriteGlobs globs to check for files that should not be overwritten. */ -const saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = []) => { +const saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = [], generator) => { let filePath = outputPath; // Might be the same as in the `fs` package, but is an active choice for our default file permission for any rendered files. let permissions = 0o666; @@ -86,12 +87,8 @@ const saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = } } - // get the final file name of the file - const finalFileName = path.basename(filePath); - // check whether the filename should be ignored based on user's inputs - // const shouldOverwrite = !noOverwriteGlobs.some(globExp => minimatch(finalFileName, globExp)); // reuse methods from the generator.js to check if the file should be overwritten - const shouldOverwrite = await reactExport.shouldOverwriteFile(filePath, noOverwriteGlobs); + const shouldOverwrite = await generator.shouldOverwriteFile(filePath); // Write the file only if it should not be skipped if (shouldOverwrite) { @@ -100,7 +97,7 @@ const saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = }); } else { log.debug(`noOverwriteGlobs matched`); - log.debug(`Skipping overwrite for: ${filePath}`); + log.debug(logMessages.skipOverwriting(filePath)); } }; @@ -112,11 +109,11 @@ const saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = * @param {String} outputPath Path to the file being rendered. * @param {String[]} noOverwriteGlobs globs to check for files that should not be overwritten. */ -reactExport.saveRenderedReactContent = async (renderedContent, outputPath, noOverwriteGlobs = []) => { +reactExport.saveRenderedReactContent = async (renderedContent, outputPath, noOverwriteGlobs = [], generator) => { // If the rendered content is an array, we need to save each file individually if (Array.isArray(renderedContent)) { return Promise.all(renderedContent.map(content => saveContentToFile(content, outputPath, noOverwriteGlobs))); } // Otherwise, we can save the single file - return saveContentToFile(renderedContent, outputPath, noOverwriteGlobs); + return saveContentToFile(renderedContent, outputPath, noOverwriteGlobs, generator); }; diff --git a/package.json b/package.json index d00d0b012..567e9c6cf 100644 --- a/package.json +++ b/package.json @@ -15,8 +15,8 @@ "test": "npm run test:unit && npm run test:integration && npm run test:cli", "test:unit": "jest --coverage --testPathIgnorePatterns=integration --testPathIgnorePatterns=test-project", "test:dev": "npm run test:unit -- --watchAll", - "test:integration": "npm run test:cleanup && jest --testPathPattern=integration --modulePathIgnorePatterns='./__mocks__'", - "test:integration:update": "jest --updateSnapshot --testPathPattern=integration --modulePathIgnorePatterns='./__mocks__'", + "test:integration": "npm run test:cleanup && jest --testPathPattern=integration --modulePathIgnorePatterns='./__mocks__(?!\\/loglevel\\.js$)'", + "test:integration:update": "jest --updateSnapshot --testPathPattern=integration --modulePathIgnorePatterns='./__mocks__(?!\\/loglevel\\.js$)'", "test:cli": "node cli.js ./test/docs/dummy.yml ./test/test-templates/react-template -o test/output --force-write --debug && test -e test/output/test-file.md", "test:cleanup": "rimraf \"test/temp\"", "docs": "jsdoc2md --partial docs/jsdoc2md-handlebars/custom-sig-name.hbs docs/jsdoc2md-handlebars/main.hbs docs/jsdoc2md-handlebars/docs.hbs docs/jsdoc2md-handlebars/header.hbs docs/jsdoc2md-handlebars/defaultvalue.hbs docs/jsdoc2md-handlebars/link.hbs docs/jsdoc2md-handlebars/params-table.hbs --files lib/generator.js > docs/api.md", diff --git a/test/integration.test.js b/test/integration.test.js index 90f30de30..407ee33bd 100644 --- a/test/integration.test.js +++ b/test/integration.test.js @@ -15,6 +15,7 @@ const {exists, writeFile} = require('../lib/utils'); const mainTestResultPath = 'test/temp/integrationTestResult'; const reactTemplate = 'test/test-templates/react-template'; const nunjucksTemplate = 'test/test-templates/nunjucks-template'; +const logMessage = require('../lib/logMessages'); const log = require('loglevel'); describe('Integration testing generateFromFile() to make sure the result of the generation is not changend comparing to snapshot', () => { @@ -67,12 +68,12 @@ describe('Integration testing generateFromFile() to make sure the result of the }); it('should ignore specified files with noOverwriteGlobs', async () => { - // const logSpyDebug = jest.spyOn(log, 'debug').mockImplementation(() => {}); - log.debug = jest.fn(); + const logSpyDebug = jest.spyOn(log, 'debug').mockImplementation(() => {}); + // log.debug = jest.fn(); const outputDir = generateFolderName(); // Manually create a file to test if it's not overwritten - if (!await exists(outputDir)) { + if (!existsSync(outputDir)) { mkdirSync(outputDir, { recursive: true }); } // Create a variable to store the file content @@ -95,15 +96,9 @@ describe('Integration testing generateFromFile() to make sure the result of the // Check if the files have been overwritten await expect(fileContent).toBe(testContent); // Check if the log debug message was printed - await expect(log.debug).toHaveBeenCalledWith(`noOverwriteGlobs matched`); - await expect(log.debug).toHaveBeenCalledWith(`Skipping overwrite for: ${testFilePath}`); - // await console.log('All console.log calls:'); + // await expect(logSpyDebug).toHaveBeenCalledWith(`noOverwriteGlobs matched`); + await expect(logSpyDebug).toHaveBeenCalledWith(logMessage.skipOverwriting(testFilePath)); - // // Print all console.log calls - // await log.mock.calls.forEach((call, index) => { - // console.log(`${index + 1}:`, call); - // }); - - log.mockRestore(); + logSpyDebug.mockRestore(); }); });