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: should return default value when env is empty string #758

Merged
merged 1 commit into from
Feb 10, 2025
Merged

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Feb 10, 2025

Summary by CodeRabbit

  • Refactor

    • Enhanced environment variable handling to trim extra whitespace and improve default value checks for more robust configuration processing.
  • Tests

    • Expanded test coverage to validate default behavior, type conversions, and error handling for various environment variable scenarios.

Copy link
Contributor

coderabbitai bot commented Feb 10, 2025

Walkthrough

This update refines the processing of environment variables in the env() function. The function now trims whitespace from string values and applies a falsy check rather than only checking for undefined. The error handling for boolean and number types remains intact. In addition, a comprehensive test suite has been introduced using Mocha and egg-mock to validate behavior under various conditions including default value returns, whitespace handling, type conversions, and error cases.

Changes

File(s) Change Summary
app/common/EnvUtil.ts Modified env() to trim string values and use a falsy check for returning default values, while maintaining existing error handling for booleans and numbers.
test/common/EnvUtil.test.ts Added a comprehensive Mocha test suite to verify env() function behavior across default values, whitespace handling, type validations, and error scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant EnvUtil as env()
    participant Env as process.env

    Caller ->> EnvUtil: call env(key, type, default)
    EnvUtil ->> Env: Retrieve process.env[key]
    EnvUtil -->> EnvUtil: Check if value is a string
    EnvUtil ->> EnvUtil: Trim whitespace if applicable
    EnvUtil ->> EnvUtil: Evaluate if value is falsy
    alt Value is falsy
        EnvUtil -->> Caller: Return defaultValue
    else Valid value
        EnvUtil ->> EnvUtil: Convert to required type
        EnvUtil -->> Caller: Return converted value
    end
Loading

Poem

I'm a happy rabbit, code in tow,
Trimming strings and letting whitespace go,
Falsy checks guide my hops so light,
With tests that ensure my code is right,
Carrot-fueled bytes and bugs out of sight!
Hooray for changes that brighten the night!
🥕🐇 Happy coding, day or night!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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. (Beta)
  • @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 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.

@fengmk2
Copy link
Member Author

fengmk2 commented Feb 10, 2025

不写单测不行。。。

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)
test/common/EnvUtil.test.ts (1)

56-62: Consider adding test for trimmed value.

While the test suite is comprehensive, consider adding a test case to verify that leading/trailing whitespace is properly trimmed from non-empty values:

 it('should work with string value', () => {
   mock(process.env, 'TEST_ENV_STRING', 'http://localhost:3000');
   assert.equal(env('TEST_ENV_STRING', 'string', 'default'), 'http://localhost:3000');

+  mock(process.env, 'TEST_ENV_STRING', '  value with spaces  ');
+  assert.equal(env('TEST_ENV_STRING', 'string', 'default'), 'value with spaces');
+
   mock(process.env, 'TEST_ENV_STRING', '      ');
   assert.equal(env('TEST_ENV_STRING', 'string', 'default'), 'default');
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3869742 and 1d6c223.

📒 Files selected for processing (2)
  • app/common/EnvUtil.ts (1 hunks)
  • test/common/EnvUtil.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: test-mysql57-fs-nfs (22, ubuntu-latest)
  • GitHub Check: test-mysql57-fs-nfs (20, ubuntu-latest)
  • GitHub Check: test-mysql57-fs-nfs (18, ubuntu-latest)
  • GitHub Check: test-mysql57-fs-nfs (18.20.0, ubuntu-latest)
  • GitHub Check: test-postgresql-fs-nfs (22, ubuntu-latest)
  • GitHub Check: test-postgresql-fs-nfs (20, ubuntu-latest)
  • GitHub Check: Analyze (typescript)
  • GitHub Check: test-postgresql-fs-nfs (18, ubuntu-latest)
  • GitHub Check: test-postgresql-fs-nfs (18.20.0, ubuntu-latest)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
app/common/EnvUtil.ts (1)

7-12: LGTM! Improved handling of empty and whitespace-only environment variables.

The changes correctly handle empty strings and whitespace by:

  1. Trimming whitespace from string values
  2. Using falsy check to handle empty strings, null, and undefined consistently

This aligns with the PR objective to fix behavior when env is empty string.

test/common/EnvUtil.test.ts (1)

5-91: LGTM! Comprehensive test coverage.

The test suite thoroughly covers:

  • Default value handling
  • Empty string and whitespace handling
  • Error conditions
  • All supported value types

Copy link

codecov bot commented Feb 10, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 96.43%. Comparing base (9f4f1f1) to head (1d6c223).
Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #758      +/-   ##
==========================================
+ Coverage   96.35%   96.43%   +0.07%     
==========================================
  Files         192      192              
  Lines       19274    19277       +3     
  Branches     2513     2520       +7     
==========================================
+ Hits        18572    18589      +17     
+ Misses        702      688      -14     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@fengmk2 fengmk2 merged commit e72e396 into master Feb 10, 2025
19 checks passed
@fengmk2 fengmk2 deleted the fix-env branch February 10, 2025 01:26
fengmk2 pushed a commit that referenced this pull request Feb 10, 2025
[skip ci]

## [3.74.1](v3.74.0...v3.74.1) (2025-02-10)

### Bug Fixes

* should return default value when env is empty string ([#758](#758)) ([e72e396](e72e396))
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