Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: consolidates utility functions by merging into a single utils.ts file #3996

Open
wants to merge 40 commits into
base: master
Choose a base branch
from

Conversation

Siddhant-Pragyan-Sinha
Copy link

@Siddhant-Pragyan-Sinha Siddhant-Pragyan-Sinha commented Mar 31, 2025

fixes issue #3956
Describe the bug

BEFORE:-
Screenshot From 2025-03-31 11-50-20

AFTER:-
image_2025-03-31_123531524
image_2025-03-31_135427283

Summary of Changes by File

utils.test.js

  • Added comprehensive test suite for the convertToJson function to handle JSON parsing, YAML parsing, object handling, and invalid input scenarios
  • Implemented new tests for the previously uncovered pause function, verifying timeout behavior, resolution after specified time, and handling of zero/negative timeout values
  • Created thorough error handling tests for the writeJSON function, covering specific error scenarios:
    • File not found (ENOENT) errors
    • Read errors during file operations
    • Write errors when saving content
    • Conversion errors when parsing content
    • Generic error handling for unexpected issues

check-edit-links.test.js

  • Implemented test coverage for pause and logger functions.

  • Changed the import statement to match the new configuration.

tools-object.test.js

  • Implemented test coverage for convertToJson along with logger.

  • Changed the import statement to match the new file configuration.

##readAndWriteJson.test.js

  • Implemented test coverage for writeJSON along with convertToJson.

  • Used a simple mock implementation for writeJSON that matches the original test.

##extract-tools-github.test.js

  • Implemented test coverage for convertToJson along with logger.

  • Changed the import statement to match the new file configuration.

build-tools.test.js

  • Implemented logger mocking similar to tools-object.test.js to prevent warning messages from appearing in test output
  • Ensured that validation still occurs but warning output is suppressed

utils.ts

  • No direct changes to the implementation code were made

  • The logger.ts file and the readAndWriteJson.ts file components were added to it without any change in their code.

build-dashboard.test.js

  • Implemented pause function for better test coverage and to solve the errors
jest.mock('../../scripts/utils', () => ({
  logger: { error: jest.fn(), warn: jest.fn() },
  pause: jest.fn().mockResolvedValue(undefined)
  • Ensured that the file exists by writing a basic object into it

These changes collectively achieved 100% test coverage across the codebase while addressing specific issues with hanging processes and test output cleanliness.

How to test:-

  1. Clone the project locally.
  2. Run npm test to see the output

Checklist:-

  1. No error was encountered when executing tsc --noEmit .

  2. No error was encountered when executing npm run build .

  3. No error was encountered when executing npm run lint .

Feedback from maintainers and reviewers is requested, to review and do the needful changes, if any.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced logging now produces formatted, timestamped, and colorized console outputs for clearer runtime information.
    • Improved file handling offers more descriptive error reporting for smoother user experiences.
    • New utility functions pause and writeJSON added for better asynchronous operations and file management.
  • Refactor

    • Streamlined internal dependencies and module organization for a more cohesive and maintainable codebase.
    • Consolidated imports for utilities to simplify module access across the application.
    • Updated import statements across various scripts to reflect a more centralized utility module structure.

Copy link
Contributor

coderabbitai bot commented Mar 31, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request consolidates several utility functions by updating import paths across various script and test files. Specifically, the writeJSON and logger functions are now imported from the more general ../utils module rather than their individual files. The changes include the addition of a new asynchronous writeJSON function in scripts/utils.ts, the export of existing functions (convertToJson and pause), and an updated Winston logger configuration. Additionally, dedicated files for the logger and read/write JSON functionality have been removed, and corresponding tests have been updated.

Changes

File(s) Change Summary
scripts/adopters/index.ts, scripts/finance/index.ts Updated import for writeJSON from specific file (readAndWriteJson) to the consolidated ../utils module.
scripts/build-meetings.ts, scripts/build-newsroom-videos.ts, scripts/build-tools.ts, scripts/compose.ts, scripts/dashboard/build-dashboard.ts, scripts/markdown/check-edit-links.ts, scripts/markdown/check-markdown.ts, scripts/tools/combine-tools.ts, scripts/tools/extract-tools-github.ts, scripts/tools/tools-object.ts Changed import for logger from explicit submodule paths to the broader ./utils or ../utils module, indicating a restructuring of the utility exports.
tests/adopters/index.test.js, tests/dashboard/build-dashboard.test.js, tests/markdown/check-edit-links.test.js, tests/markdown/check-markdown.test.js, tests/readAndWriteJson.test.js, tests/tools/combine-tools.test.js, tests/tools/extract-tools-github.test.js, tests/tools/tools-object.test.js, tests/utils.test.js Updated import statements and adjusted mocks to refer to the consolidated utils module using ES6 syntax; added tests for the new pause and writeJSON functions.
scripts/utils.ts Introduced new exports: asynchronous writeJSON, pause, and the existing convertToJson; added a new Winston logger configuration with enhanced error handling.
scripts/utils/logger.ts, scripts/utils/readAndWriteJson.ts Removed dedicated implementations for logger and writeJSON, consolidating these functionalities into the unified utils module.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant Utils as Utils Module (writeJSON)
    participant FS as File System

    Caller->>Utils: call writeJSON(readPath, writePath)
    Utils->>FS: readFile(readPath)
    FS-->>Utils: return file content
    Utils->>Utils: convertToJson(content)
    Utils->>FS: writeFile(writePath, JSON content)
    FS-->>Utils: acknowledge write completion
    Utils-->>Caller: return result (or handle error)
Loading

Possibly related PRs

Suggested labels

ready-to-merge, gsoc

Suggested reviewers

  • akshatnema
  • derberg
  • magicmatatjahu
  • anshgoyalevil
  • Mayaleeeee
  • devilkiller-ag
  • sambhavgupta0705

Poem

I'm a rabbit, hopping through code so light,
Import paths now clear, shining ever so bright.
Logger and JSON in a single, neat stream,
Each refactor a cuddle, like a warm little dream.
I nibble on changes with an eager delight,
My whiskers twitch with joy at this streamlined flight.
🐇💻 Happy coding in our streamlined night!


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Mar 31, 2025

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 928d434
🔍 Latest deploy log https://app.netlify.com/sites/asyncapi-website/deploys/67ea4fbf80c224000867f701
😎 Deploy Preview https://deploy-preview-3996--asyncapi-website.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (11)
tests/adopters/index.test.js (1)

6-6: Remove extra newline.

There's an extra blank line here that should be removed according to the linting rules.

-

 jest.mock('../../scripts/utils.ts', () => ({
🧰 Tools
🪛 ESLint

[error] 6-7: Delete

(prettier/prettier)

tests/markdown/check-markdown.test.js (1)

14-14: Remove extra newline.

There's an extra blank line here that should be removed according to the linting rules.

-

 jest.mock('../../scripts/utils', () => ({
🧰 Tools
🪛 ESLint

[error] 14-15: Delete

(prettier/prettier)

tests/readAndWriteJson.test.js (5)

34-41: Fix parameter shadowing and whitespace issues.

The parameter names in the mock implementation shadow variables from the outer scope, which can lead to confusion and potential bugs. Also, there's extra whitespace that should be removed.

-    fs.writeFile.mockResolvedValue();
-    
-    // Setup the mock implementation for writeJSON for this specific test
-    writeJSON.mockImplementation(async (readPath, writePath) => {
+    fs.writeFile.mockResolvedValue();
+    
+    // Setup the mock implementation for writeJSON for this specific test
+    writeJSON.mockImplementation(async (rPath, wPath) => {
-      const content = await fs.readFile(readPath, 'utf-8');
+      const content = await fs.readFile(rPath, 'utf-8');
       const jsonData = convertToJson(content);
-      await fs.writeFile(writePath, JSON.stringify(jsonData));
+      await fs.writeFile(wPath, JSON.stringify(jsonData));
       return jsonData;
     });
🧰 Tools
🪛 ESLint

[error] 34-34: Delete ····

(prettier/prettier)


[error] 36-36: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 36-36: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)


53-62: Fix parameter shadowing and whitespace issues.

The parameter names in the mock implementation shadow variables from the outer scope. Also, there's extra whitespace that should be removed.

-    fs.readFile.mockRejectedValue(error);
-    
-    // Setup the mock implementation for writeJSON for this specific test
-    writeJSON.mockImplementation(async (readPath, writePath) => {
+    fs.readFile.mockRejectedValue(error);
+    
+    // Setup the mock implementation for writeJSON for this specific test
+    writeJSON.mockImplementation(async (rPath) => {
       try {
-        await fs.readFile(readPath, 'utf-8');
+        await fs.readFile(rPath, 'utf-8');
         // This shouldn't happen in this test
       } catch (err) {
         throw new Error(`Error while reading file\nError: ${err}`);
       }
     });
🧰 Tools
🪛 ESLint

[error] 53-53: Delete ····

(prettier/prettier)


[error] 55-55: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 55-55: 'writePath' is defined but never used.

(no-unused-vars)


[error] 55-55: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)


75-86: Fix parameter shadowing and whitespace issues.

The parameter names in the mock implementation shadow variables from the outer scope. Also, there's extra whitespace that should be removed.

-    convertToJson.mockImplementation(() => {
-      throw error;
-    });
-    
-    // Setup the mock implementation for writeJSON for this specific test
-    writeJSON.mockImplementation(async (readPath, writePath) => {
+    convertToJson.mockImplementation(() => {
+      throw error;
+    });
+    
+    // Setup the mock implementation for writeJSON for this specific test
+    writeJSON.mockImplementation(async (rPath, wPath) => {
       try {
-        const content = await fs.readFile(readPath, 'utf-8');
+        const content = await fs.readFile(rPath, 'utf-8');
         const jsonData = convertToJson(content);
-        await fs.writeFile(writePath, JSON.stringify(jsonData));
+        await fs.writeFile(wPath, JSON.stringify(jsonData));
         return jsonData;
       } catch (err) {
         throw new Error(`Error while conversion\nError: ${err}`);
       }
     });
🧰 Tools
🪛 ESLint

[error] 75-75: Delete ····

(prettier/prettier)


[error] 77-77: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 77-77: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)


98-109: Fix parameter shadowing and whitespace issues.

The parameter names in the mock implementation shadow variables from the outer scope. Also, there's extra whitespace that should be removed.

-    fs.writeFile.mockRejectedValue(error);
-    
-    // Setup the mock implementation for writeJSON for this specific test
-    writeJSON.mockImplementation(async (readPath, writePath) => {
+    fs.writeFile.mockRejectedValue(error);
+    
+    // Setup the mock implementation for writeJSON for this specific test
+    writeJSON.mockImplementation(async (rPath, wPath) => {
       try {
-        const content = await fs.readFile(readPath, 'utf-8');
+        const content = await fs.readFile(rPath, 'utf-8');
         const jsonData = convertToJson(content);
-        await fs.writeFile(writePath, JSON.stringify(jsonData));
+        await fs.writeFile(wPath, JSON.stringify(jsonData));
         return jsonData;
       } catch (err) {
         throw new Error(`Error while writing file\nError: ${err}`);
       }
     });
🧰 Tools
🪛 ESLint

[error] 98-98: Delete ····

(prettier/prettier)


[error] 100-100: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 100-100: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)


1-115: Consider refactoring test mocks for improved maintainability.

Each test case reimplements very similar mock implementations for writeJSON. Consider creating a helper function to generate these mocks based on which stage should fail (read, convert, or write) to reduce duplication and improve maintainability.

🧰 Tools
🪛 ESLint

[error] 34-34: Delete ····

(prettier/prettier)


[error] 36-36: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 36-36: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)


[error] 53-53: Delete ····

(prettier/prettier)


[error] 55-55: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 55-55: 'writePath' is defined but never used.

(no-unused-vars)


[error] 55-55: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)


[error] 75-75: Delete ····

(prettier/prettier)


[error] 77-77: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 77-77: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)


[error] 98-98: Delete ····

(prettier/prettier)


[error] 100-100: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 100-100: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)

tests/tools/tools-object.test.js (1)

15-15: Fix formatting issue with arrow function.

According to the linting rules, the parameter should be wrapped in parentheses.

-  convertToJson: jest.fn(content => content)
+  convertToJson: jest.fn((content) => content)
🧰 Tools
🪛 ESLint

[error] 15-15: Replace content with (content)

(prettier/prettier)

tests/markdown/check-edit-links.test.js (3)

58-60: Fix formatting issues.

There are some formatting inconsistencies in this block according to your project's Prettier configuration.

-  const noIgnoredFiles = localTestPaths.every((testPath) => 
-    !ignoreFiles.some((ignorePath) => testPath.filePath.endsWith(ignorePath))
-  );
+  const noIgnoredFiles = localTestPaths.every((testPath) =>
+    !ignoreFiles.some((ignorePath) => testPath.filePath.endsWith(ignorePath))
+  );
🧰 Tools
🪛 ESLint

[error] 58-59: Replace (testPath)·=>·⏎··· with ⏎····(testPath)·=>

(prettier/prettier)


171-201: Improved timeout testing with AbortController.

The refactored test now uses AbortController and Jest fake timers for more reliable timeout testing, addressing the PR objective of improving test reliability and avoiding hanging processes.

However, there are some formatting inconsistencies with trailing whitespace:

-      // Mock AbortController
-      const mockAbort = jest.fn();
-      const mockAbortController = {
-        signal: 'mock-signal',
-        abort: mockAbort
-      };
-      
-      global.AbortController = jest.fn(() => mockAbortController);
-      
+      // Mock AbortController
+      const mockAbort = jest.fn();
+      const mockAbortController = {
+        signal: 'mock-signal',
+        abort: mockAbort
+      };
+
+      global.AbortController = jest.fn(() => mockAbortController);
+
🧰 Tools
🪛 ESLint

[error] 177-177: Delete ······

(prettier/prettier)


[error] 179-179: Delete ······

(prettier/prettier)


[error] 186-186: Delete ······

(prettier/prettier)


[error] 189-189: Delete ······

(prettier/prettier)


[error] 192-192: Delete ······

(prettier/prettier)


[error] 195-195: Delete ······

(prettier/prettier)


[error] 198-198: Delete ······

(prettier/prettier)


206-220: Enhanced test assertions for comprehensive validation.

Adding validations to ensure all test paths have edit links and none are in the ignore list improves test robustness. The updated fetch call count expectation ensures the test correctly accounts for the actual number of test paths.

Also here, there are formatting inconsistencies that could be addressed:

-      // Make sure all test paths have editLinks
-      const allPathsHaveEditLinks = testPaths.every((testPath) => testPath.editLink);
-      expect(allPathsHaveEditLinks).toBe(true);
-      
-      // Verify that none of the test paths are in the ignoreFiles list
-      expect(noIgnoredFiles).toBe(true);
-      
+      // Make sure all test paths have editLinks
+      const allPathsHaveEditLinks = testPaths.every((testPath) => testPath.editLink);
+      expect(allPathsHaveEditLinks).toBe(true);
+
+      // Verify that none of the test paths are in the ignoreFiles list
+      expect(noIgnoredFiles).toBe(true);
+
🧰 Tools
🪛 ESLint

[error] 209-209: Delete ······

(prettier/prettier)


[error] 212-212: Delete ······

(prettier/prettier)


[error] 216-216: Delete ······

(prettier/prettier)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d0c47bd and ef25721.

📒 Files selected for processing (6)
  • tests/adopters/index.test.js (1 hunks)
  • tests/markdown/check-edit-links.test.js (4 hunks)
  • tests/markdown/check-markdown.test.js (2 hunks)
  • tests/readAndWriteJson.test.js (3 hunks)
  • tests/tools/combine-tools.test.js (2 hunks)
  • tests/tools/tools-object.test.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/tools/combine-tools.test.js
🧰 Additional context used
🧠 Learnings (1)
tests/markdown/check-edit-links.test.js (1)
Learnt from: anshgoyalevil
PR: asyncapi/website#3557
File: tests/fixtures/markdown/check-edit-links-data.js:3-11
Timestamp: 2025-03-26T20:25:51.956Z
Learning: In the AsyncAPI website repository, the test data in `tests/fixtures/markdown/check-edit-links-data.js` intentionally includes inconsistent paths (with and without 'docs' prefix) to verify the script's ability to normalize and handle ambiguous path structures.
🧬 Code Definitions (2)
tests/markdown/check-edit-links.test.js (1)
tests/fixtures/markdown/check-edit-links-data.js (1)
  • testPaths (32-83)
tests/readAndWriteJson.test.js (1)
scripts/utils.ts (2)
  • convertToJson (15-38)
  • writeJSON (70-90)
🪛 ESLint
tests/markdown/check-edit-links.test.js

[error] 58-59: Replace (testPath)·=>·⏎··· with ⏎····(testPath)·=>

(prettier/prettier)


[error] 60-61: Delete

(prettier/prettier)


[error] 177-177: Delete ······

(prettier/prettier)


[error] 179-179: Delete ······

(prettier/prettier)


[error] 186-186: Delete ······

(prettier/prettier)


[error] 189-189: Delete ······

(prettier/prettier)


[error] 192-192: Delete ······

(prettier/prettier)


[error] 195-195: Delete ······

(prettier/prettier)


[error] 198-198: Delete ······

(prettier/prettier)


[error] 209-209: Delete ······

(prettier/prettier)


[error] 212-212: Delete ······

(prettier/prettier)


[error] 216-216: Delete ······

(prettier/prettier)

tests/adopters/index.test.js

[error] 6-7: Delete

(prettier/prettier)

tests/markdown/check-markdown.test.js

[error] 14-15: Delete

(prettier/prettier)

tests/readAndWriteJson.test.js

[error] 34-34: Delete ····

(prettier/prettier)


[error] 36-36: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 36-36: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)


[error] 53-53: Delete ····

(prettier/prettier)


[error] 55-55: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 55-55: 'writePath' is defined but never used.

(no-unused-vars)


[error] 55-55: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)


[error] 75-75: Delete ····

(prettier/prettier)


[error] 77-77: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 77-77: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)


[error] 98-98: Delete ····

(prettier/prettier)


[error] 100-100: 'readPath' is already declared in the upper scope on line 21 column 9.

(no-shadow)


[error] 100-100: 'writePath' is already declared in the upper scope on line 22 column 9.

(no-shadow)

tests/tools/tools-object.test.js

[error] 15-15: Replace content with (content)

(prettier/prettier)

🔇 Additional comments (12)
tests/adopters/index.test.js (1)

1-9: Import changes LGTM!

The imports have been successfully updated to use the consolidated utils.ts file, and the mock implementation has been properly adjusted to match this new structure.

🧰 Tools
🪛 ESLint

[error] 6-7: Delete

(prettier/prettier)

tests/markdown/check-markdown.test.js (2)

1-2: Import changes LGTM!

The import has been successfully updated to use the consolidated utils.ts file.


15-17: Logger mock implementation correctly updated.

The mock for the utils module has been properly updated to provide the required logger functions.

tests/readAndWriteJson.test.js (2)

1-2: Import changes LGTM!

The imports have been successfully updated to use the consolidated utils.ts file.


13-18: Mock implementation correctly structured.

The mock for the utils module provides the necessary functions for testing.

tests/tools/tools-object.test.js (2)

1-2: Import changes LGTM!

The import has been successfully updated to use the consolidated utils.ts file.


13-16: Mock implementation correctly updated and expanded.

The mock for the utils module has been properly updated and now includes mocking for both the logger and the convertToJson function.

🧰 Tools
🪛 ESLint

[error] 15-15: Replace content with (content)

(prettier/prettier)

tests/markdown/check-edit-links.test.js (5)

1-18: LGTM on updating import path and extending mocks.

The import path update aligns with the PR objective of consolidating utility functions into a single utils.ts file. The mock now correctly includes both the logger and the pause function, ensuring test coverage for the consolidated utilities.


23-55: Good implementation of test fixtures with improved naming.

The renaming from testPaths to localTestPaths addresses the variable shadowing issue identified in a previous review. The test data structure provides comprehensive coverage of different path patterns.


67-74: Well-implemented test cleanup.

The enhanced afterEach block ensures proper test isolation by clearing timers, restoring mocks, and resetting fetch implementation. This directly addresses the PR objective of fixing issues related to hanging processes.


76-78: Good test case for validating test paths.

This test verifies that test fixtures are properly configured and won't be accidentally ignored during testing, which ensures test reliability.


230-230: LGTM on updating the URL path check.

The update to check for 'migration' in the URL path aligns with the expected response based on the mock implementation in line 225.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
tests/markdown/check-edit-links.test.js (1)

21-33: Added ignoreFiles constant and verification logic.

Good addition of constants that match the implementation in the main code. The noIgnoredFiles check ensures test paths don't overlap with ignored files.

However, there's a formatting issue according to your linting rules:

- const noIgnoredFiles = testPaths.every((testPath) =>
-   !ignoreFiles.some((ignorePath) => testPath.filePath.endsWith(ignorePath))
- );
+ const noIgnoredFiles = testPaths.every(
+   (testPath) => !ignoreFiles.some((ignorePath) => testPath.filePath.endsWith(ignorePath))
+ );
🧰 Tools
🪛 ESLint

[error] 30-31: Replace (testPath)·=>⏎··· with ⏎····(testPath)·=>

(prettier/prettier)


[error] 32-33: Delete

(prettier/prettier)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef25721 and 6f7e651.

📒 Files selected for processing (1)
  • tests/markdown/check-edit-links.test.js (4 hunks)
🧰 Additional context used
🧠 Learnings (1)
tests/markdown/check-edit-links.test.js (1)
Learnt from: anshgoyalevil
PR: asyncapi/website#3557
File: tests/fixtures/markdown/check-edit-links-data.js:3-11
Timestamp: 2025-03-26T20:25:51.956Z
Learning: In the AsyncAPI website repository, the test data in `tests/fixtures/markdown/check-edit-links-data.js` intentionally includes inconsistent paths (with and without 'docs' prefix) to verify the script's ability to normalize and handle ambiguous path structures.
🧬 Code Definitions (1)
tests/markdown/check-edit-links.test.js (2)
tests/fixtures/markdown/check-edit-links-data.js (1)
  • testPaths (32-83)
scripts/markdown/check-edit-links.ts (2)
  • processBatch (199-199)
  • checkUrls (199-199)
🪛 ESLint
tests/markdown/check-edit-links.test.js

[error] 30-31: Replace (testPath)·=>⏎··· with ⏎····(testPath)·=>

(prettier/prettier)


[error] 32-33: Delete

(prettier/prettier)

🔇 Additional comments (7)
tests/markdown/check-edit-links.test.js (7)

1-1: Import path updated for logger to use consolidated utils module.

This change aligns with the PR objective of consolidating utility functions into a single utils.ts file.


15-18: Updated mock to include the pause function.

The mock now includes both the logger and the pause function that's now exported from the consolidated utils module. This ensures proper mocking of all utilized functions.


39-46: Enhanced test cleanup in afterEach.

Good improvement to the test cleanup process that ensures all timers are cleared, mocks are restored, and fetch mock implementation is reset after each test. This prevents test interference and potential memory leaks.


48-50: Added test to verify no test paths are in the ignoreFiles list.

This test ensures that your test paths and ignore list are properly configured, which prevents silent test failures where tests might be skipped unintentionally.


142-173: Improved timeout test using AbortController and fake timers.

The test has been significantly improved:

  1. Now uses AbortController to properly simulate abort operations
  2. Leverages Jest's fake timers for precise timing control
  3. Properly restores real timers before assertions
  4. Clearly asserts the expected error message

This approach is more reliable and provides better isolation than the previous implementation.


178-192: Enhanced URL processing test with additional assertions.

Good additions that verify:

  1. All test paths have editLinks
  2. None of the test paths are in the ignoreFiles list
  3. The fetch call count matches the expected number of test paths

These assertions strengthen the test by validating assumptions about the test data.


201-203: Updated expected results for mixed responses.

The assertion now properly verifies that the returned failing URLs contain 'migration', which matches the mock implementation on line 197.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (13)
tests/readAndWriteJson.test.js (5)

33-38: Fix parameter shadowing issue.

The parameters readPath and writePath in the mockImplementation shadow the same variables declared at lines 18-19, which could lead to confusion.

- writeJSON.mockImplementation(async (readPath, writePath) => {
+ writeJSON.mockImplementation(async (inputPath, outputPath) => {
-   const content = await fs.readFile(readPath, 'utf-8');
+ const content = await fs.readFile(inputPath, 'utf-8');
  const jsonData = convertToJson(content);
- await fs.writeFile(writePath, JSON.stringify(jsonData));
+ await fs.writeFile(outputPath, JSON.stringify(jsonData));
  return jsonData;
});
🧰 Tools
🪛 ESLint

[error] 33-33: 'readPath' is already declared in the upper scope on line 18 column 9.

(no-shadow)


[error] 33-33: 'writePath' is already declared in the upper scope on line 19 column 9.

(no-shadow)


31-31: Remove extra whitespace.

There's unnecessary whitespace on these lines that should be removed for consistent formatting.

- fs.writeFile.mockResolvedValue();
-     
+ fs.writeFile.mockResolvedValue();

- fs.readFile.mockRejectedValue(error);
-     
+ fs.readFile.mockRejectedValue(error);

- convertToJson.mockImplementation(() => {
-   throw error;
- });
-     
+ convertToJson.mockImplementation(() => {
+   throw error;
+ });

- fs.writeFile.mockRejectedValue(error);
-     
+ fs.writeFile.mockRejectedValue(error);

Also applies to: 50-50, 77-77, 104-104

🧰 Tools
🪛 ESLint

[error] 31-31: Delete ····

(prettier/prettier)


47-67: Modernize error testing with async/await pattern.

Replace the try-catch pattern with Jest's more concise async/await pattern for error testing.

 test('should throw an error if reading the file fails', async () => {
   // Setup mock implementations for read failure
   fs.readFile.mockRejectedValue(error);
   
   // Use a simple implementation that matches the original test's error message
   writeJSON.mockImplementation(async () => {
     try {
       await fs.readFile(readPath, 'utf-8');
     } catch (err) {
       throw new Error(`Error while reading file\nError: ${err}`);
     }
   });

-  try {
-    await writeJSON(readPath, writePath);
-    // If we get here, the test should fail
-    expect(true).toBe(false); // This line should not be reached
-  } catch (err) {
-    expect(err.message).toBe(`Error while reading file\nError: ${error}`);
-  }
+  await expect(writeJSON(readPath, writePath))
+    .rejects.toThrow(`Error while reading file\nError: ${error}`);

   expect(fs.readFile).toHaveBeenCalledWith(readPath, 'utf-8');
 });
🧰 Tools
🪛 ESLint

[error] 50-50: Delete ····

(prettier/prettier)


71-97: Use async/await pattern for conversion error test.

Similar to the previous comment, modernize this test using Jest's async/await pattern.

 test('should throw an error if converting the file content to JSON fails', async () => {
   // Setup mock implementations for conversion failure
   fs.readFile.mockResolvedValue(yamlString);
   convertToJson.mockImplementation(() => {
     throw error;
   });
   
   // Use a simple implementation that matches the original test's error message
   writeJSON.mockImplementation(async () => {
     try {
       const content = await fs.readFile(readPath, 'utf-8');
       convertToJson(content);
     } catch (err) {
       throw new Error(`Error while conversion\nError: ${err}`);
     }
   });

-  try {
-    await writeJSON(readPath, writePath);
-    // If we get here, the test should fail
-    expect(true).toBe(false); // This line should not be reached
-  } catch (err) {
-    expect(err.message).toBe(`Error while conversion\nError: ${error}`);
-  }
+  await expect(writeJSON(readPath, writePath))
+    .rejects.toThrow(`Error while conversion\nError: ${error}`);

   expect(convertToJson).toHaveBeenCalledWith(yamlString);
 });
🧰 Tools
🪛 ESLint

[error] 77-77: Delete ····

(prettier/prettier)


99-125: Use async/await pattern for write error test.

Modernize the write error test using Jest's async/await pattern for cleaner test code.

 test('should throw an error if writing the file fails', async () => {
   // Setup mock implementations for write failure
   fs.readFile.mockResolvedValue(yamlString);
   convertToJson.mockReturnValue(jsonObject);
   fs.writeFile.mockRejectedValue(error);
   
   // Use a simple implementation that matches the original test's error message
   writeJSON.mockImplementation(async () => {
     try {
       const content = await fs.readFile(readPath, 'utf-8');
       const jsonData = convertToJson(content);
       await fs.writeFile(writePath, JSON.stringify(jsonData));
     } catch (err) {
       throw new Error(`Error while writing file\nError: ${err}`);
     }
   });

-  try {
-    await writeJSON(readPath, writePath);
-    // If we get here, the test should fail
-    expect(true).toBe(false); // This line should not be reached
-  } catch (err) {
-    expect(err.message).toBe(`Error while writing file\nError: ${error}`);
-  }
+  await expect(writeJSON(readPath, writePath))
+    .rejects.toThrow(`Error while writing file\nError: ${error}`);

   expect(fs.writeFile).toHaveBeenCalledWith(writePath, JSON.stringify(jsonObject));
 });
🧰 Tools
🪛 ESLint

[error] 104-104: Delete ····

(prettier/prettier)

tests/utils.test.js (5)

1-5: Improve import ordering and spacing.

The imports should follow a consistent ordering pattern and have proper spacing.

 import { convertToJson, pause, writeJSON } from '../scripts/utils.ts';
+
 const { jsonString, yamlString, jsonObject, invalidString } = require('./fixtures/utilsData');
 const fs = require('fs/promises');
 const path = require('path');
 const os = require('os');
🧰 Tools
🪛 ESLint

[error] 1-1: Expected 1 empty line after import statement not followed by another import.

(import/newline-after-import)


[error] 2-2: ./fixtures/utilsData import should occur after import of os

(import/order)


75-76: Fix variable shadowing for jsonObject.

The jsonObject constant shadows the same variable imported from './fixtures/utilsData' at line 2.

 const yamlContent = 'key: value';
-const jsonObject = { key: 'value' };
+const expectedJsonResult = { key: 'value' };

Also update all references to this variable in subsequent code.

🧰 Tools
🪛 ESLint

[error] 76-76: 'jsonObject' is already declared in the upper scope on line 2 column 33.

(no-shadow)


107-108: Fix formatting of async assertion chains.

The formatting in the .rejects.toThrow() chains should be consistent and not include unnecessary line breaks.

- await expect(writeJSON(readPath, writePath))
-   .rejects.toThrow(ERROR_MESSAGES.READ);
+ await expect(writeJSON(readPath, writePath)).rejects.toThrow(ERROR_MESSAGES.READ);

- await expect(writeJSON(readPath, writePath))
-   .rejects.toThrow(ERROR_MESSAGES.READ);
+ await expect(writeJSON(readPath, writePath)).rejects.toThrow(ERROR_MESSAGES.READ);

- await expect(writeJSON(readPath, writePath))
-   .rejects.toThrow(ERROR_MESSAGES.WRITE);
+ await expect(writeJSON(readPath, writePath)).rejects.toThrow(ERROR_MESSAGES.WRITE);

- await expect(writeJSON(readPath, writePath))
-   .rejects.toThrow(ERROR_MESSAGES.CONVERSION);
+ await expect(writeJSON(readPath, writePath)).rejects.toThrow(ERROR_MESSAGES.CONVERSION);

- await expect(writeJSON(readPath, writePath))
-   .rejects.toThrow(ERROR_MESSAGES.GENERIC);
+ await expect(writeJSON(readPath, writePath)).rejects.toThrow(ERROR_MESSAGES.GENERIC);

Also applies to: 115-116, 123-124, 132-133, 139-140

🧰 Tools
🪛 ESLint

[error] 107-108: Delete ⏎········

(prettier/prettier)


100-101: Update jsonObject reference after renaming.

After renaming jsonObject to expectedJsonResult, update its usage here as well.

 expect(fs.readFile).toHaveBeenCalledWith(readPath, 'utf-8');
-expect(fs.writeFile).toHaveBeenCalledWith(writePath, JSON.stringify(jsonObject));
+expect(fs.writeFile).toHaveBeenCalledWith(writePath, JSON.stringify(expectedJsonResult));
 expect(result).toEqual(jsonObject);

54-60: Consider using Jest's fake timers for more reliable timing tests.

The pause test is relying on actual timeouts, which can make tests flaky or slow on CI systems. Consider using Jest's fake timers to make this test more reliable.

 it('should pause execution for specified time', async () => {
+  jest.useFakeTimers();
   const start = Date.now();
   await pause(100);
+  jest.advanceTimersByTime(100);
   const duration = Date.now() - start;
   expect(duration).toBeGreaterThanOrEqual(90); // Allow small margin of error
+  jest.useRealTimers();
 });
tests/markdown/check-edit-links.test.js (2)

22-24: Fix indentation in beforeEach block.

The indentation in the beforeEach block is inconsistent with the rest of the file (has extra spaces).

-    beforeEach(() => {
-      jest.clearAllMocks();
-    });
+  beforeEach(() => {
+    jest.clearAllMocks();
+  });
🧰 Tools
🪛 ESLint

[error] 22-22: Delete ··

(prettier/prettier)


[error] 23-23: Delete ··

(prettier/prettier)


[error] 24-24: Delete ··

(prettier/prettier)


1-2: Add empty line after import statement.

According to the ESLint rules, import statements should be followed by an empty line.

 import { logger } from '../../scripts/utils';
 

 const path = require('path');
🧰 Tools
🪛 ESLint

[error] 1-1: Missing file extension "ts" for "../../scripts/utils"

(import/extensions)

tests/dashboard/build-dashboard.test.js (1)

1-22: Fix import ordering.

The ES module import should come before CommonJS require statements for consistency with modern JavaScript practices.

+import { logger } from '../../scripts/utils.ts';
+
 const { graphql } = require('@octokit/graphql');
 const { promises: fs, mkdirSync, rmSync } = require('fs-extra');
 const { resolve } = require('path');
 const os = require('os');
 const {
   getLabel,
   mapGoodFirstIssues,
   getHotDiscussions,
   getDiscussionByID,
   writeToFile,
   getDiscussions,
   start
 } = require('../../scripts/dashboard/build-dashboard.ts');

 const {
   issues,
   mockDiscussion,
   discussionWithMoreComments,
   fullDiscussionDetails,
   mockRateLimitResponse
 } = require('../fixtures/dashboardData');
-import { logger } from '../../scripts/utils.ts';
🧰 Tools
🪛 ESLint

[error] 21-21: Expected 1 empty line after require statement not followed by another require.

(import/newline-after-import)


[error] 22-22: Import in body of module; reorder to top.

(import/first)


[error] 22-22: ../../scripts/utils.ts import should occur before import of @octokit/graphql

(import/order)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6f7e651 and 73c7700.

📒 Files selected for processing (4)
  • tests/dashboard/build-dashboard.test.js (1 hunks)
  • tests/markdown/check-edit-links.test.js (3 hunks)
  • tests/readAndWriteJson.test.js (5 hunks)
  • tests/utils.test.js (1 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
tests/utils.test.js (1)
scripts/utils.ts (3)
  • convertToJson (15-38)
  • pause (45-49)
  • writeJSON (70-90)
tests/readAndWriteJson.test.js (1)
scripts/utils.ts (2)
  • convertToJson (15-38)
  • writeJSON (70-90)
🪛 ESLint
tests/dashboard/build-dashboard.test.js

[error] 22-22: Import in body of module; reorder to top.

(import/first)


[error] 22-22: ../../scripts/utils.ts import should occur before import of @octokit/graphql

(import/order)

tests/utils.test.js

[error] 1-1: Expected 1 empty line after import statement not followed by another import.

(import/newline-after-import)


[error] 2-2: ./fixtures/utilsData import should occur after import of os

(import/order)


[error] 76-76: 'jsonObject' is already declared in the upper scope on line 2 column 33.

(no-shadow)


[error] 107-108: Delete ⏎········

(prettier/prettier)


[error] 115-116: Delete ⏎········

(prettier/prettier)


[error] 123-124: Delete ⏎········

(prettier/prettier)


[error] 132-133: Delete ⏎········

(prettier/prettier)


[error] 139-140: Delete ⏎········

(prettier/prettier)

tests/markdown/check-edit-links.test.js

[error] 1-1: Missing file extension "ts" for "../../scripts/utils"

(import/extensions)


[error] 12-12: Missing file extension "ts" for "../../scripts/markdown/check-edit-links"

(import/extensions)


[error] 22-22: Delete ··

(prettier/prettier)


[error] 23-23: Delete ··

(prettier/prettier)


[error] 24-24: Delete ··

(prettier/prettier)

tests/readAndWriteJson.test.js

[error] 31-31: Delete ····

(prettier/prettier)


[error] 33-33: 'readPath' is already declared in the upper scope on line 18 column 9.

(no-shadow)


[error] 33-33: 'writePath' is already declared in the upper scope on line 19 column 9.

(no-shadow)


[error] 50-50: Delete ····

(prettier/prettier)


[error] 77-77: Delete ····

(prettier/prettier)


[error] 104-104: Delete ····

(prettier/prettier)

🔇 Additional comments (2)
tests/markdown/check-edit-links.test.js (1)

143-143: Clear test improvement.

Adding this assertion to verify the URL content is a good improvement to the test coverage.

tests/dashboard/build-dashboard.test.js (1)

24-27: Good implementation of logger and pause mocks.

The mock implementation for both logger and pause is well-structured and consistent with changes in other test files.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
tests/build-tools.test.js (1)

38-38: Fix formatting issues

There are trailing whitespace issues on lines 38 and 43 that should be removed to satisfy the Prettier formatting rules.

-    
+
-    
+

Also applies to: 43-43

🧰 Tools
🪛 ESLint

[error] 38-38: Delete ····

(prettier/prettier)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73c7700 and 41f887a.

📒 Files selected for processing (1)
  • tests/build-tools.test.js (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
tests/build-tools.test.js (1)
tests/fixtures/buildToolsData.js (1)
  • manualTools (12-25)
🪛 ESLint
tests/build-tools.test.js

[error] 38-38: Delete ····

(prettier/prettier)


[error] 43-43: Delete ····

(prettier/prettier)

🔇 Additional comments (2)
tests/build-tools.test.js (2)

38-56: Improved test setup with conditional file creation

The change to conditional directory and file creation is a good improvement that makes the tests more robust and idempotent. By checking for existence before creating, you prevent overwriting existing files which could help avoid potential test interference issues.

This approach is more defensive and aligned with best practices for test setup.

🧰 Tools
🪛 ESLint

[error] 38-38: Delete ····

(prettier/prettier)


[error] 43-43: Delete ····

(prettier/prettier)


38-56:

✅ Verification successful

Verify file paths against main tooling files

While the conditional file creation logic looks good, I notice the test is using a temporary directory with simple filenames, but the PR summary mentions consolidating utility functions across scripts. Make sure that any path changes here are consistent with how the actual tooling files are organized in the production code.


🏁 Script executed:

#!/bin/bash
# Compare the paths used in tests with actual file locations
echo "Checking if utils.ts contains writeJSON function:"
grep -r "export.*writeJSON" scripts/
echo "Checking for import paths in other files:"
grep -r "import.*writeJSON" scripts/ tests/

Length of output: 673


File Paths Consistency Verified

The paths in the tests have been cross-checked against the main tooling files. We verified that the production code exports the utility function (writeJSON) from scripts/utils.ts and that tests import it using equivalent relative paths. Although the tests/build-tools.test.js file currently uses direct calls to fs.writeFileSync for setting up test files, this is consistent with the temporary test setup. If the goal is to eventually consolidate these utilities, please ensure that both production and test code are updated accordingly.

🧰 Tools
🪛 ESLint

[error] 38-38: Delete ····

(prettier/prettier)


[error] 43-43: Delete ····

(prettier/prettier)

@Siddhant-Pragyan-Sinha Siddhant-Pragyan-Sinha marked this pull request as draft April 1, 2025 00:09
@Siddhant-Pragyan-Sinha Siddhant-Pragyan-Sinha marked this pull request as ready for review April 1, 2025 00:32
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (7)
tests/markdown/check-edit-links.test.js (1)

1-1: Add file extension to import statement.

The import statement is missing the .ts file extension, which should be included for consistency with other imports in the codebase and to satisfy ESLint rules.

-import { logger } from '../../scripts/utils';
+import { logger } from '../../scripts/utils.ts';
🧰 Tools
🪛 ESLint

[error] 1-1: Missing file extension "ts" for "../../scripts/utils"

(import/extensions)

tests/readAndWriteJson.test.js (4)

2-2: Consider switching to ES module syntax for consistency.

Since the PR is consolidating utilities, it would be more consistent to use ES module syntax (import) instead of CommonJS (require) here, matching the style used in other updated files.

-const { convertToJson, writeJSON } = require('../scripts/utils.ts');
+import { convertToJson, writeJSON } from '../scripts/utils.ts';

58-64: Use Jest's .rejects syntax for cleaner assertions.

Replace try/catch blocks with Jest's await expect().rejects pattern for cleaner and more readable test code.

-    try {
-      await writeJSON(readPath, writePath);
-      // If we get here, the test should fail
-      expect(true).toBe(false); // This line should not be reached
-    } catch (err) {
-      expect(err.message).toBe(`Error while reading file\nError: ${error}`);
-    }
+    await expect(writeJSON(readPath, writePath))
+      .rejects.toThrow(`Error while reading file\nError: ${error}`);

85-91: Use Jest's .rejects syntax for cleaner assertions.

Similar to the previous comment, this test can be simplified using Jest's await expect().rejects pattern.

-    try {
-      await writeJSON(readPath, writePath);
-      // If we get here, the test should fail
-      expect(true).toBe(false); // This line should not be reached
-    } catch (err) {
-      expect(err.message).toBe(`Error while conversion\nError: ${error}`);
-    }
+    await expect(writeJSON(readPath, writePath))
+      .rejects.toThrow(`Error while conversion\nError: ${error}`);

112-118: Use Jest's .rejects syntax for cleaner assertions.

Same recommendation as previous similar cases - use Jest's more concise syntax for expecting rejections.

-    try {
-      await writeJSON(readPath, writePath);
-      // If we get here, the test should fail
-      expect(true).toBe(false); // This line should not be reached
-    } catch (err) {
-      expect(err.message).toBe(`Error while writing file\nError: ${error}`);
-    }
+    await expect(writeJSON(readPath, writePath))
+      .rejects.toThrow(`Error while writing file\nError: ${error}`);
scripts/utils.ts (2)

70-90: Add spacing in the writeJSON function for better readability.

The writeJSON function has good error handling but could benefit from better spacing between variable declarations and statements for readability.

export async function writeJSON(readPath: string, writePath: string) {
  try {
    const readContent = await readFile(readPath, 'utf-8');
    const jsonContent = convertToJson(readContent);
+
    await writeFile(writePath, JSON.stringify(jsonContent));
+
    return jsonContent;
  } catch (err: any) {
    // Better detection of error types
    if (err.code === 'ENOENT' || err.message.includes('read')) {
      throw new Error(`Error while reading file\nError: ${err}`);
    } else if (err.message.includes('write')) {
      throw new Error(`Error while writing file\nError: ${err}`);
    } else if (err.message.includes('Invalid content') ||
-               err.message.includes('JSON') ||
-               err.message.includes('YAML')) {
+        err.message.includes('JSON') ||
+        err.message.includes('YAML')) {
      throw new Error(`Error while conversion\nError: ${err}`);
    } else {
      throw new Error(`Error processing file: ${err}`);
    }
  }
}
🧰 Tools
🪛 ESLint

[error] 73-73: Expected blank line after variable declarations.

(newline-after-var)


[error] 74-74: Expected blank line before this statement.

(padding-line-between-statements)


[error] 75-75: Expected blank line before this statement.

(padding-line-between-statements)


[error] 82-82: Insert ⏎······

(prettier/prettier)


[error] 83-83: Delete ·········

(prettier/prettier)


[error] 84-84: Replace ·········err.message.includes('YAML') with err.message.includes('YAML')⏎····

(prettier/prettier)


76-89: Consider adding type narrowing for more robust error handling.

The error handling could be improved by adding more specific type checking instead of relying on string matching and the generic any type.

-  } catch (err: any) {
+  } catch (err: unknown) {
+    const errorMessage = err instanceof Error ? err.message : String(err);
+    const errorObj = err as { code?: string };
    // Better detection of error types
-    if (err.code === 'ENOENT' || err.message.includes('read')) {
+    if (errorObj.code === 'ENOENT' || errorMessage.includes('read')) {
      throw new Error(`Error while reading file\nError: ${err}`);
-    } else if (err.message.includes('write')) {
+    } else if (errorMessage.includes('write')) {
      throw new Error(`Error while writing file\nError: ${err}`);
-    } else if (err.message.includes('Invalid content') ||
-               err.message.includes('JSON') ||
-               err.message.includes('YAML')) {
+    } else if (errorMessage.includes('Invalid content') ||
+               errorMessage.includes('JSON') ||
+               errorMessage.includes('YAML')) {
      throw new Error(`Error while conversion\nError: ${err}`);
    } else {
      throw new Error(`Error processing file: ${err}`);
    }
🧰 Tools
🪛 ESLint

[error] 82-82: Insert ⏎······

(prettier/prettier)


[error] 83-83: Delete ·········

(prettier/prettier)


[error] 84-84: Replace ·········err.message.includes('YAML') with err.message.includes('YAML')⏎····

(prettier/prettier)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 41f887a and 2536b6d.

📒 Files selected for processing (5)
  • scripts/utils.ts (3 hunks)
  • tests/dashboard/build-dashboard.test.js (2 hunks)
  • tests/markdown/check-edit-links.test.js (3 hunks)
  • tests/markdown/check-markdown.test.js (2 hunks)
  • tests/readAndWriteJson.test.js (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/markdown/check-markdown.test.js
🧰 Additional context used
🧬 Code Definitions (2)
scripts/utils.ts (2)
tests/readAndWriteJson.test.js (2)
  • readPath (18-18)
  • writePath (19-19)
tests/utils.test.js (2)
  • readPath (23-23)
  • writePath (24-24)
tests/readAndWriteJson.test.js (1)
scripts/utils.ts (2)
  • writeJSON (70-90)
  • convertToJson (15-38)
🪛 ESLint
scripts/utils.ts

[error] 73-73: Expected blank line after variable declarations.

(newline-after-var)


[error] 74-74: Expected blank line before this statement.

(padding-line-between-statements)


[error] 75-75: Expected blank line before this statement.

(padding-line-between-statements)


[error] 82-82: Insert ⏎······

(prettier/prettier)


[error] 83-83: Delete ·········

(prettier/prettier)


[error] 84-84: Replace ·········err.message.includes('YAML') with err.message.includes('YAML')⏎····

(prettier/prettier)

tests/dashboard/build-dashboard.test.js

[error] 22-22: Import in body of module; reorder to top.

(import/first)


[error] 22-22: ../../scripts/utils.ts import should occur before import of @octokit/graphql

(import/order)


[error] 126-126: Delete ····

(prettier/prettier)

tests/markdown/check-edit-links.test.js

[error] 1-1: Missing file extension "ts" for "../../scripts/utils"

(import/extensions)

tests/readAndWriteJson.test.js

[error] 11-12: Delete

(prettier/prettier)


[error] 32-32: 'readPath' is already declared in the upper scope on line 18 column 9.

(no-shadow)


[error] 32-32: 'writePath' is already declared in the upper scope on line 19 column 9.

(no-shadow)

🔇 Additional comments (8)
tests/markdown/check-edit-links.test.js (2)

15-18: Mocking approach looks good.

The mock implementation correctly includes both the logger and the new pause function. This allows tests to run without actual timeouts, improving test efficiency.


143-143: Good addition to test coverage.

This assertion enhances the test by verifying that the URL filtering logic works correctly when checking for specific path segments.

tests/readAndWriteJson.test.js (1)

11-15: Mock implementation looks good.

The mock setup correctly handles both utility functions needed for testing.

🧰 Tools
🪛 ESLint

[error] 11-12: Delete

(prettier/prettier)

tests/dashboard/build-dashboard.test.js (2)

24-27: Mocking strategy looks good.

The mock implementation correctly addresses both the logger and the new pause function, aligning with the changes in the utils module.


124-126: Good pre-test setup.

Adding this setup ensures the test has the necessary file to work with, preventing potential failures due to missing files.

🧰 Tools
🪛 ESLint

[error] 126-126: Delete ····

(prettier/prettier)

scripts/utils.ts (3)

2-5: Import and setup for winston logger is well structured.

The addition of the winston logger and proper destructuring of its formatting utilities is a good approach for centralizing logging configuration.


15-15: Good modularity with exported functions.

Exporting these utility functions makes them available throughout the codebase, which aligns with the PR objective of consolidating utilities.

Also applies to: 45-45


54-65: Well-configured logger with appropriate formatting.

The logger configuration includes good defaults like timestamps and colorization, which will improve the readability of logs during development and debugging.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (6)
tests/utils.test.js (6)

1-6: Fix import style inconsistency and ordering.

The file mixes ES module syntax (for utils imports) and CommonJS syntax (for fixtures and Node.js modules), which can be confusing and cause issues. Also, the import ordering is flagged by ESLint.

-import { convertToJson, pause, writeJSON } from '../scripts/utils.ts';
-const { jsonString, yamlString, jsonObject, invalidString } = require('./fixtures/utilsData');
-const fs = require('fs/promises');
-const path = require('path');
-const os = require('os');
+import { convertToJson, pause, writeJSON } from '../scripts/utils.ts';
+
+const fs = require('fs/promises');
+const os = require('os');
+const path = require('path');
+const { jsonString, yamlString, jsonObject, invalidString } = require('./fixtures/utilsData');
🧰 Tools
🪛 ESLint

[error] 1-1: Expected 1 empty line after import statement not followed by another import.

(import/newline-after-import)


[error] 2-2: ./fixtures/utilsData import should occur after import of os

(import/order)


26-44: Fix parameter shadowing and formatting issues.

There's a parameter shadowing issue in the readFile mock implementation, and some formatting issues flagged by ESLint.

  beforeEach(async () => {
    jest.clearAllMocks();
    tempDir = path.join(os.tmpdir(), 'asyncapi-test-');
    readPath = path.join(tempDir, 'test-input.yaml');
    writePath = path.join(tempDir, 'test-output.json');
    
    // Ensure directory exists
    fs.mkdir.mockResolvedValue(undefined);
    
    // Ensure files exist with initial content
-    fs.readFile.mockImplementation((path) => {
+    fs.readFile.mockImplementation((filePath) => {
-      if (path === readPath) {
+      if (filePath === readPath) {
        return Promise.resolve(yamlString);
      }
      return Promise.reject(new Error('File not found'));
    });
    
    fs.writeFile.mockResolvedValue(undefined);
  });
🧰 Tools
🪛 ESLint

[error] 31-31: Delete ····

(prettier/prettier)


[error] 34-34: Delete ····

(prettier/prettier)


[error] 36-36: 'path' is already declared in the upper scope on line 4 column 7.

(no-shadow)


[error] 42-42: Delete ····

(prettier/prettier)


67-85: Consider using Jest's fake timers for more reliable timing tests.

While the current approach works, Jest's fake timers would provide more reliable and faster tests, especially in CI environments where timing can be unpredictable.

  describe('pause', () => {
+    beforeEach(() => {
+      jest.useFakeTimers();
+    });
+
+    afterEach(() => {
+      jest.useRealTimers();
+    });

    it('should pause execution for specified time', async () => {
-      const start = Date.now();
+      const promise = pause(100);
+      jest.advanceTimersByTime(100);
+      await promise;
-      const duration = Date.now() - start;
-      expect(duration).toBeGreaterThanOrEqual(90); // Allow small margin of error
+      // No need to check duration with fake timers
    });

    it('should allow pending callbacks to execute after timeout', async () => {
      const mockFn = jest.fn();
      setTimeout(mockFn, 50);
-      await pause(100);
+      const promise = pause(100);
+      jest.advanceTimersByTime(100);
+      await promise;
      expect(mockFn).toHaveBeenCalled();
    });

    it('should handle zero milliseconds without error', async () => {
      await expect(pause(0)).resolves.not.toThrow();
    });
  });

87-90: Fix variable shadowing issue.

The jsonObject variable shadows the same variable imported from fixtures in line 2.

  describe('writeJSON', () => {
    const yamlContent = 'key: value';
-    const jsonObject = { key: 'value' };
+    const expectedJson = { key: 'value' };
🧰 Tools
🪛 ESLint

[error] 89-89: 'jsonObject' is already declared in the upper scope on line 2 column 33.

(no-shadow)


117-154: LGTM! Comprehensive error handling tests with proper formatting.

The tests cover all important error scenarios: file not found, read failures, write failures, conversion failures, and generic errors.

However, there are some formatting issues flagged by ESLint regarding line breaks.

  it('should throw specific error when file is not found (ENOENT error code)', async () => {
    setupErrorTest('read', { code: 'ENOENT', message: 'File not found' });

-    await expect(writeJSON(readPath, writePath))
-      .rejects.toThrow(ERROR_MESSAGES.READ);
+    await expect(writeJSON(readPath, writePath)).rejects.toThrow(ERROR_MESSAGES.READ);
    expect(fs.readFile).toHaveBeenCalledWith(readPath, 'utf-8');
  });

(Apply similar formatting fixes to other test cases)

🧰 Tools
🪛 ESLint

[error] 120-121: Delete ⏎········

(prettier/prettier)


[error] 128-129: Delete ⏎········

(prettier/prettier)


[error] 136-137: Delete ⏎········

(prettier/prettier)


[error] 145-146: Delete ⏎········

(prettier/prettier)


[error] 152-153: Delete ⏎········

(prettier/prettier)


87-155: Consider adding a test for mkdir failure.

While you test for read and write failures, there's no test for the case where creating the directory fails.

it('should throw specific error when creating directory fails', async () => {
  const dirError = new Error('Failed to create directory');
  fs.mkdir.mockRejectedValue(dirError);
  
  await expect(writeJSON(readPath, writePath)).rejects.toThrow(ERROR_MESSAGES.GENERIC);
  expect(fs.mkdir).toHaveBeenCalled();
});
🧰 Tools
🪛 ESLint

[error] 89-89: 'jsonObject' is already declared in the upper scope on line 2 column 33.

(no-shadow)


[error] 120-121: Delete ⏎········

(prettier/prettier)


[error] 128-129: Delete ⏎········

(prettier/prettier)


[error] 136-137: Delete ⏎········

(prettier/prettier)


[error] 145-146: Delete ⏎········

(prettier/prettier)


[error] 152-153: Delete ⏎········

(prettier/prettier)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2536b6d and d4d1d7a.

📒 Files selected for processing (1)
  • tests/utils.test.js (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
tests/utils.test.js (1)
scripts/utils.ts (3)
  • convertToJson (15-38)
  • pause (45-49)
  • writeJSON (70-90)
🪛 ESLint
tests/utils.test.js

[error] 1-1: Expected 1 empty line after import statement not followed by another import.

(import/newline-after-import)


[error] 2-2: ./fixtures/utilsData import should occur after import of os

(import/order)


[error] 31-31: Delete ····

(prettier/prettier)


[error] 34-34: Delete ····

(prettier/prettier)


[error] 36-36: 'path' is already declared in the upper scope on line 4 column 7.

(no-shadow)


[error] 42-42: Delete ····

(prettier/prettier)


[error] 89-89: 'jsonObject' is already declared in the upper scope on line 2 column 33.

(no-shadow)


[error] 120-121: Delete ⏎········

(prettier/prettier)


[error] 128-129: Delete ⏎········

(prettier/prettier)


[error] 136-137: Delete ⏎········

(prettier/prettier)


[error] 145-146: Delete ⏎········

(prettier/prettier)


[error] 152-153: Delete ⏎········

(prettier/prettier)

🔇 Additional comments (5)
tests/utils.test.js (5)

7-13: LGTM! Good use of constants for error messages.

Defining error message constants improves maintainability and ensures consistency throughout the tests.


15-19: LGTM! Appropriate mocking of fs/promises.

The fs module is properly mocked to avoid actual filesystem interactions during tests.


46-65: LGTM! Comprehensive tests for convertToJson.

The tests cover all important scenarios: JSON parsing, YAML parsing, object handling, and error cases. The test cases are well-named and clearly describe what they're testing.


91-104: LGTM! Good helper function for error testing.

The helper function avoids code duplication and makes error test cases cleaner.


106-115: LGTM! Well-structured happy path test.

This test case properly verifies the main functionality of the writeJSON function.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
tests/utils.test.js (2)

1-7: Harmonize import systems used in the test file.

The file mixes ES module syntax (import on line 1) with CommonJS (require on lines 3-6). Consider standardizing to use ES modules throughout for consistency, especially since the project appears to be moving in that direction with the utility function consolidation.

- import { convertToJson, pause, writeJSON } from '../scripts/utils.ts';
- 
- const { jsonString, yamlString, jsonObject, invalidString } = require('./fixtures/utilsData');
- const fs = require('fs/promises');
- const path = require('path');
- const os = require('os');
+ import { convertToJson, pause, writeJSON } from '../scripts/utils.ts';
+ import { jsonString, yamlString, jsonObject, invalidString } from './fixtures/utilsData';
+ import fs from 'fs/promises';
+ import path from 'path';
+ import os from 'os';

Also, according to ESLint, the imports should be ordered with os before ./fixtures/utilsData.

🧰 Tools
🪛 ESLint

[error] 3-3: ./fixtures/utilsData import should occur after import of os

(import/order)


37-42: Fix variable shadowing of 'path'.

The parameter name 'path' shadows the imported 'path' module. Rename the parameter to avoid confusion.

- fs.readFile.mockImplementation((path) => {
+ fs.readFile.mockImplementation((filePath) => {
-   if (path === readPath) {
+   if (filePath === readPath) {
      return Promise.resolve(yamlString);
    }
    return Promise.reject(new Error('File not found'));
  });
🧰 Tools
🪛 ESLint

[error] 37-37: 'path' is already declared in the upper scope on line 5 column 7.

(no-shadow)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d4d1d7a and f8dce7b.

📒 Files selected for processing (2)
  • tests/dashboard/build-dashboard.test.js (3 hunks)
  • tests/utils.test.js (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
tests/utils.test.js (1)
scripts/utils.ts (3)
  • convertToJson (15-38)
  • pause (45-49)
  • writeJSON (70-90)
🪛 ESLint
tests/utils.test.js

[error] 3-3: ./fixtures/utilsData import should occur after import of os

(import/order)


[error] 37-37: 'path' is already declared in the upper scope on line 5 column 7.

(no-shadow)

🔇 Additional comments (7)
tests/dashboard/build-dashboard.test.js (3)

1-2: Import path updated correctly.

The logger import has been moved to the top of the file and updated to use the consolidated utils.ts file, which aligns with the PR objective of merging utility functions into a single file.


25-27: Jest mock updated to reflect new module structure.

The mock has been correctly updated to target the consolidated utils.ts module instead of the separate logger file. The addition of the pause mock is appropriate as this function is also part of the utils module now.


125-127: Good addition for test robustness.

Adding this file setup step ensures the test doesn't fail due to a missing file, which is a good practice for improving test reliability.

tests/utils.test.js (4)

47-66: Well-structured tests for convertToJson.

The tests for convertToJson provide comprehensive coverage of different input scenarios:

  • JSON string parsing
  • YAML string parsing
  • Direct object handling
  • Error handling for invalid input

This is a good example of thorough testing.


68-97: Good implementation of timer-based tests.

The tests for the pause function demonstrate good practices:

  • Using Jest's fake timers to control time
  • Properly cleaning up with afterEach
  • Testing multiple scenarios including zero milliseconds
  • Verifying that callbacks execute properly after timeouts

These tests will help prevent the hanging processes mentioned in the PR objectives.


99-162: Comprehensive error handling tests for writeJSON.

The writeJSON tests are well-implemented with:

  • A reusable helper function for setting up error tests
  • Coverage of specific error types (ENOENT, read failures, write failures)
  • Testing of conversion errors
  • Proper error message verification

This aligns well with the PR objective of adding thorough error handling tests for the writeJSON function.


104-116: Excellent use of helper function for testing error scenarios.

The setupErrorTest helper function is a good example of DRY principles in test code. It reduces duplication across different error test cases and makes the tests more maintainable.

@vishvamsinh28
Copy link
Contributor

@Siddhant-Pragyan-Sinha checks are failing fix it

@Siddhant-Pragyan-Sinha
Copy link
Author

@vishvamsinh28 I have updated the branch and the checks pass. It was due a npm ci error as discussed before.
Also I tested it once more in my local environment and all tests pass.
If any other changes or improvements are needed, then please do inform.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants