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

test(relayer): adds initial testing base #375

Merged
merged 5 commits into from
Dec 13, 2024

Conversation

fcanela
Copy link
Contributor

@fcanela fcanela commented Dec 6, 2024

This PR introduces a foundation consisting of basic setup and an initial test for relayer.

  • Adds Jest, with types and coverage output
  • Implements basic tests for ShutdownManager to validate the stack

PR-Codex overview

This PR introduces testing capabilities using jest, adds a new ShutdownManager class, and updates configuration files to support TypeScript and ESLint. It also enhances coverage reporting and updates various package dependencies.

Detailed summary

  • Added ShutdownManager class in shutdownManager.ts.
  • Implemented tests for ShutdownManager in shutdownManager.test.ts.
  • Updated .eslintrc.json to include jest and ts-jest.
  • Added jest and @types/jest to devDependencies.
  • Configured jest in jest.config.ts for TypeScript.
  • Modified package.json to include a test script for coverage.
  • Updated various dependencies in yarn.lock.

The following files were skipped due to too many changes: yarn.lock

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new ShutdownManager class to manage system shutdown states.
    • Added a Jest configuration file for improved testing capabilities, including coverage reporting.
    • New test script added to package.json for running tests with coverage.
    • Updated ESLint configuration to recognize Jest-specific globals.
  • Bug Fixes

    • Simplified shutdown management logic by externalizing it to the ShutdownManager class.
  • Tests

    • Added unit tests for the ShutdownManager class, covering instance creation and shutdown status retrieval.
    • Included tests for the getIsShuttingDown method and a placeholder for the triggerShutdown method.

@fcanela fcanela self-assigned this Dec 6, 2024
Copy link
Contributor

coderabbitai bot commented Dec 6, 2024

Walkthrough

The changes in this pull request introduce several updates to the relayer-cli project. A new configuration entry for code coverage is added to the .gitconfig file. A Jest configuration file is created to facilitate TypeScript testing with coverage reporting. The package.json is updated to include a new test script and several new development dependencies. The ShutdownManager class is introduced in a new file, and the previous implementation of shutdown management is refactored to utilize this new class. Additionally, unit tests for the ShutdownManager are added.

Changes

File Change Summary
relayer-cli/.gitconfig Added configuration entry for coverage.
relayer-cli/jest.config.ts Introduced Jest configuration for TypeScript testing with coverage.
relayer-cli/package.json Added "test": "jest --coverage" script and new devDependencies: @types/jest, jest, ts-jest.
relayer-cli/src/utils/relayerHelpers.ts Removed ShutdownManager class; imported from a separate module and updated setupExitHandlers function.
relayer-cli/src/utils/shutdownManager.test.ts Added unit tests for the ShutdownManager class, covering constructor and methods.
relayer-cli/src/utils/shutdownManager.ts Introduced ShutdownManager class with methods for managing shutdown state.
.eslintrc.json Updated to include Jest environment for linting.

Possibly related PRs

  • Resuscitated Arbitrum Sepolia to Sepolia devnet deployment #305: The changes in relayer-cli/package.json regarding the addition of a new script for testing with coverage reporting are directly related to the main PR's introduction of coverage settings in the .gitconfig file, indicating a focus on code coverage across the project.

Suggested labels

Type: Feature🗿, Type: Maintenance :construction:

Suggested reviewers

  • jaybuidl
  • alcercu

🐇 In the code, we now take a leap,
With coverage tools, our tests run deep.
A ShutdownManager, sleek and bright,
Handles exits, day or night.
With Jest in tow, we’ll test with glee,
Ensuring our code is bug-free! 🐇


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a9a3c00 and 2f4cdb7.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (1)
  • relayer-cli/package.json (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • relayer-cli/package.json

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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 or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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 Dec 6, 2024

Deploy Preview for veascan failed. Why did it fail? →

Name Link
🔨 Latest commit 2f4cdb7
🔍 Latest deploy log https://app.netlify.com/sites/veascan/deploys/675c000597140f0008af4ebc

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: 3

🧹 Outside diff range and nitpick comments (4)
relayer-cli/package.json (1)

13-13: Consider expanding test scripts for better developer experience.

While the basic test script with coverage is good, consider adding more specialized scripts:

 "scripts": {
   "test": "jest --coverage",
+  "test:watch": "jest --watch",
+  "test:ci": "jest --ci --coverage --coverageThreshold='{\"global\":{\"branches\":80,\"functions\":80,\"lines\":80,\"statements\":80}}'",
   "start-devnet-relayer": "npx ts-node ./src/devnetRelayExample.ts",
relayer-cli/src/utils/shutdownManager.ts (1)

1-15: LGTM with suggestions for enhanced functionality

The implementation follows good practices with proper encapsulation and immutable state management. Consider these enhancements:

  1. Add JSDoc documentation to describe the class purpose and methods
  2. Consider adding event emission on state change for better integration
  3. Consider adding a reset capability for testing scenarios

Example enhancement:

+import { EventEmitter } from 'events';
+
+/**
+ * Manages the shutdown state of the relayer
+ * @emits shutdown - Emitted when shutdown is triggered
+ */
-export default class ShutdownManager {
+export default class ShutdownManager extends EventEmitter {
   private isShuttingDown: boolean;

   constructor(initialState: boolean = false) {
+    super();
     this.isShuttingDown = initialState;
   }

+  /**
+   * Returns the current shutdown state
+   */
   public getIsShuttingDown(): boolean {
     return this.isShuttingDown;
   }

+  /**
+   * Triggers the shutdown process
+   * @emits shutdown
+   */
   public triggerShutdown() {
     this.isShuttingDown = true;
+    this.emit('shutdown');
   }

+  /**
+   * Resets the shutdown state (useful for testing)
+   */
+  public reset() {
+    this.isShuttingDown = false;
+  }
 }
relayer-cli/src/utils/relayerHelpers.ts (2)

Line range hint 47-76: Fix potential issues in exit handlers

There are several concerns in the exit handling logic:

  1. Async cleanup in 'exit' event won't work
  2. Duplicate process.exit calls
  3. Potential race condition in cleanup
  4. Inconsistent error handling

Suggested improvements:

 async function setupExitHandlers(chainId: number, shutdownManager: ShutdownManager, network: string) {
   const cleanup = async () => {
     console.log("exit");
     const lockFileName = "./state/" + network + "_" + chainId + ".pid";
     if (fs.existsSync(lockFileName)) {
-      await fs.promises.unlink(lockFileName);
+      try {
+        // Use sync version for cleanup to ensure completion
+        fs.unlinkSync(lockFileName);
+      } catch (error) {
+        console.error('Failed to cleanup:', error);
+      }
     }
   };

   const handleExit = async (exitCode: number = 0) => {
     shutdownManager.triggerShutdown();
-    await cleanup();
+    cleanup();
-    process.exit(0);
+    process.exit(exitCode);
   };

   ["SIGINT", "SIGTERM", "SIGQUIT"].forEach((signal) =>
     process.on(signal, async () => {
-      await handleExit(0);
-      process.exit(0);
+      await handleExit(0);
     })
   );

   // 'exit' event cannot handle async operations
   process.on("exit", () => {
-    await handleExit();
+    cleanup();
   });

   process.on("uncaughtException", async (err) => {
     console.error("Uncaught exception:", err);
     await handleExit(1);
   });

   process.on("unhandledRejection", async (reason, promise) => {
     console.error("Unhandled promise rejection:", reason, "at", promise);
     await handleExit(1);
   });
 }

2-2: Consider using more specific imports

Import only the required ShutdownManager type to improve bundle size.

-import ShutdownManager from "./shutdownManager";
+import type { ShutdownManager } from "./shutdownManager";
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3eebb3f and 1c1d352.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (6)
  • relayer-cli/.gitconfig (1 hunks)
  • relayer-cli/jest.config.ts (1 hunks)
  • relayer-cli/package.json (2 hunks)
  • relayer-cli/src/utils/relayerHelpers.ts (1 hunks)
  • relayer-cli/src/utils/shutdownManager.test.ts (1 hunks)
  • relayer-cli/src/utils/shutdownManager.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • relayer-cli/.gitconfig
  • relayer-cli/jest.config.ts
🧰 Additional context used
🪛 eslint
relayer-cli/src/utils/shutdownManager.test.ts

[error] 7-7: 'expect' is not defined.

(no-undef)


[error] 12-12: 'expect' is not defined.

(no-undef)


[error] 17-17: 'expect' is not defined.

(no-undef)


[error] 24-24: 'expect' is not defined.

(no-undef)


[error] 29-29: 'expect' is not defined.

(no-undef)

🔇 Additional comments (1)
relayer-cli/package.json (1)

27-31: 🛠️ Refactor suggestion

Review dependency management practices.

A few observations about the dependencies:

  1. The explicit yarn devDependency might be redundant since the package manager is already specified in packageManager field
  2. Using caret ranges (^) for all dependencies could lead to unexpected breaks. Consider using exact versions for test framework dependencies to ensure consistent behavior across environments.
 "devDependencies": {
-  "@types/jest": "^29.5.14",
-  "jest": "^29.7.0",
-  "ts-jest": "^29.2.5",
+  "@types/jest": "29.5.14",
+  "jest": "29.7.0",
+  "ts-jest": "29.2.5",
   "ts-node": "^10.9.2",
-  "yarn": "^1.22.22"
 }

Let's verify if yarn is used elsewhere in the project:

✅ Verification successful

Remove redundant yarn dependency and consider fixing version ranges

The verification shows that:

  1. Yarn is already specified as the package manager ([email protected]) in the packageManager field, making the explicit yarn dependency redundant
  2. Multiple yarn-specific scripts are used throughout the project, confirming yarn as the primary package manager
  3. The project heavily relies on yarn for its build, deployment, and development workflows

The original review suggestions are valid:

  • Remove the redundant yarn devDependency
  • Consider using exact versions for test framework dependencies to ensure consistent behavior
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if yarn is explicitly required in any source files
rg -l "require\(['\"]yarn['\"]|import.*from.*['\"]yarn['\"]"

Length of output: 70


Script:

#!/bin/bash
# Check for packageManager field in package.json files
fd package.json --exec jq -r '.packageManager // empty'

# Check for yarn-specific files and configs
fd -g 'yarn.lock|.yarnrc|.yarnrc.yml'

# Check for yarn-specific scripts in package.json
fd package.json --exec jq -r '.scripts | to_entries | .[] | select(.value | contains("yarn")) | .key + ": " + .value'

Length of output: 1653

relayer-cli/src/utils/shutdownManager.test.ts Show resolved Hide resolved
relayer-cli/src/utils/shutdownManager.test.ts Outdated Show resolved Hide resolved
relayer-cli/src/utils/shutdownManager.test.ts Show resolved Hide resolved
@fcanela fcanela mentioned this pull request Dec 6, 2024
relayer-cli/package.json Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (1)
.eslintrc.json (1)

Line range hint 6-11: Consider cleaning up environment configurations

There are a few potential inconsistencies in the environment setup:

  1. Both "es6" and "es2020" environments are enabled, which is redundant as "es2020" includes all "es6" features
  2. Both "mocha" and "jest" environments are enabled, but the PR indicates a transition to Jest for testing

Consider applying this cleanup:

  "env": {
    "browser": true,
-   "es6": true,
    "node": true,
-   "mocha": true,
    "es2020": true,
    "jest": true
  },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1c1d352 and da77614.

📒 Files selected for processing (1)
  • .eslintrc.json (1 hunks)
🔇 Additional comments (1)
.eslintrc.json (1)

11-11: LGTM: Jest environment enabled

The addition of the Jest environment is appropriate for the introduction of Jest-based testing infrastructure.

mani99brar
mani99brar previously approved these changes Dec 11, 2024
@mani99brar mani99brar merged commit cbfe0a3 into dev Dec 13, 2024
10 of 15 checks passed
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.

2 participants