Skip to content

feat(chproxy): add unit tests for config.go#2975

Merged
chronark merged 1 commit intomainfrom
chproxy-add-config-tests
Mar 17, 2025
Merged

feat(chproxy): add unit tests for config.go#2975
chronark merged 1 commit intomainfrom
chproxy-add-config-tests

Conversation

@imeyer
Copy link
Contributor

@imeyer imeyer commented Mar 16, 2025

  • Add comprehensive test coverage for LoadConfig()
  • Update service version from 1.3.0 to 1.3.1
  • Add config.Logger initialization in LoadConfig
  • Use structured logging with slog instead of log.Fatalf
  • Add .gitignore for chproxy binary and coverage files

What does this PR do?

Includes tests because I messed up and introduced a nil pointer deref in f3dfdb3 ☹️

Summary by CodeRabbit

  • Chores
    • Refined repository setup by excluding non-essential files and directories from version control.
  • New Features
    • Updated the service version to 1.3.1 and enhanced error reporting with a more structured logging approach for clearer telemetry insights.
  • Tests
    • Added comprehensive tests to validate configuration loading and error handling, ensuring a more stable application experience.

- Add comprehensive test coverage for LoadConfig()
- Update service version from 1.3.0 to 1.3.1
- Add config.Logger initialization in LoadConfig
- Use structured logging with slog instead of log.Fatalf
- Add .gitignore for chproxy binary and coverage files

Signed-off-by: Ian Meyer (imeyer) <k@imeyer.io>
@changeset-bot
Copy link

changeset-bot bot commented Mar 16, 2025

⚠️ No Changeset found

Latest commit: a4d7407

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel
Copy link

vercel bot commented Mar 16, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 16, 2025 11:40pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 16, 2025 11:40pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 16, 2025 11:40pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 16, 2025 11:40pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 16, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a new .gitignore file in the apps/chproxy directory, updates configuration management by changing the service version from "1.3.0" to "1.3.1" and instantiating a structured logger, and refines error handling in the main application. A new test file has been added to ensure that configuration loading works as expected, and telemetry logging has been updated to use a structured logging method.

Changes

Files Summary
apps/chproxy/.gitignore New file added to ignore the chproxy directory and coverage.out file.
apps/chproxy/config.go, apps/chproxy/main.go, apps/chproxy/otel.go Updated structured logging: in config.go, updated ServiceVersion to "1.3.1" and added a new Logger field; in main.go, replaced log.Fatalf with config.Logger.Error and an explicit os.Exit(1); in otel.go, refined logging to use slog.Float64.
apps/chproxy/config_test.go New unit tests added for the LoadConfig function, covering valid configurations, error cases, and custom settings with proper environment variable management.

Sequence Diagram(s)

sequenceDiagram
    participant Main
    participant ConfigLoader as LoadConfig
    participant Logger
    participant Telemetry as SetupTelemetry

    Main->>ConfigLoader: Load configuration
    ConfigLoader-->>Main: Returns config (includes ServiceVersion and Logger)
    Main->>Main: Validate configuration result
    alt Error Occurs
        Main->>Logger: Log error with structured logging
        Main-->>Main: Invoke os.Exit(1)
    else Successful Load
        Main->>Telemetry: Call setupTelemetry(config)
        Telemetry-->>Main: Log trace sample rate (using slog.Float64)
        Main->>Main: Continue with application initialization
    end
Loading

Possibly related PRs

Suggested reviewers

  • mcstepp
  • perkinsjr
  • MichaelUnkey
  • chronark
  • ogzhanolguncu

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

Error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24.0)
Failed executing command with error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24.0)

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @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.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 16, 2025

Thank you for following the naming conventions for pull request titles! 🙏

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

🧹 Nitpick comments (1)
apps/chproxy/config_test.go (1)

77-79: Consider extending logger verification

While checking that the logger is non-nil is a good start, consider extending the test to verify specific logger properties (output destination, log level, etc.) to ensure it's configured correctly.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f3dfdb3 and a4d7407.

📒 Files selected for processing (5)
  • apps/chproxy/.gitignore (1 hunks)
  • apps/chproxy/config.go (1 hunks)
  • apps/chproxy/config_test.go (1 hunks)
  • apps/chproxy/main.go (2 hunks)
  • apps/chproxy/otel.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (15)
  • GitHub Check: Test Packages / Test ./packages/rbac
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/hash
  • GitHub Check: Test Packages / Test ./internal/billing
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test Go API Local / Test
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Build / Build
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (10)
apps/chproxy/.gitignore (1)

1-2: Good practice for ignoring binary and coverage files.

Excluding the chproxy binary and coverage.out file from version control is good practice. This prevents binary artifacts and test results from cluttering the repository.

apps/chproxy/main.go (2)

36-37: Improved error handling with structured logging.

The switch from log.Fatalf to structured logging with config.Logger.Error followed by explicit os.Exit(1) is a good improvement. This provides better error details in a structured format that's easier to parse in logging systems.


55-56: Consistent structured error logging for telemetry failures.

Good application of the same structured logging pattern for telemetry setup errors, maintaining consistency throughout the codebase.

apps/chproxy/otel.go (1)

144-144: Enhanced type information in structured logging.

Using slog.Float64 instead of a simple key-value pair adds explicit type information that improves log parsing and consistency.

apps/chproxy/config.go (2)

32-32: Version bump from 1.3.0 to 1.3.1.

Appropriate version increment that aligns with the PR objectives.


37-39: Good initialization of structured logger.

The initialization of the logger in the Config struct provides a foundation for the structured logging improvements seen throughout the codebase. Using a text handler with stdout is a sensible default configuration.

apps/chproxy/config_test.go (4)

1-37: Well-structured test setup and teardown

The helper functions for environment manipulation are well-designed with proper use of t.Helper() and comprehensive cleanup through t.Cleanup(). This ensures tests remain isolated and don't interfere with each other, which is essential for reliable testing.


39-80: Good use of table-driven tests for configuration verification

The table-driven approach makes the tests maintainable and easy to extend when new configuration parameters are added. The verification of default values ensures that any future changes to defaults are explicitly recognized in the tests.


152-244: Comprehensive edge case testing

The test cases thoroughly validate boundary conditions for configuration parameters, including extreme values (0.0 and 1.0) for sample rate and custom settings for all configurable parameters. This comprehensive approach ensures the configuration behaves correctly across its entire range of valid inputs.


1-244: Excellent test coverage addressing the PR objectives

The test file provides comprehensive coverage for the LoadConfig() function, which directly addresses the PR objective of enhancing test coverage. The tests verify the updated service version (1.3.1), proper initialization of the logger, and correct handling of environment variables, all of which align with the PR goals.

Comment on lines +145 to +146
if got := err.Error(); got != tc.wantErr && got[:len(tc.wantErr)] != tc.wantErr {
t.Errorf("LoadConfig() error = %v, want to contain %v", got, tc.wantErr)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential index out of range error in error comparison

The current error check could panic if the actual error message is shorter than the expected error message.

Replace with a safer approach using strings.Contains:

- if got := err.Error(); got != tc.wantErr && got[:len(tc.wantErr)] != tc.wantErr {
-   t.Errorf("LoadConfig() error = %v, want to contain %v", got, tc.wantErr)
- }
+ import "strings" // Add this to imports
+ if got := err.Error(); got != tc.wantErr && !strings.Contains(got, tc.wantErr) {
+   t.Errorf("LoadConfig() error = %v, want to contain %v", got, tc.wantErr)
+ }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if got := err.Error(); got != tc.wantErr && got[:len(tc.wantErr)] != tc.wantErr {
t.Errorf("LoadConfig() error = %v, want to contain %v", got, tc.wantErr)
// Add the following to your imports section if it's not already present:
import "strings"
// ... (other code)
if got := err.Error(); got != tc.wantErr && !strings.Contains(got, tc.wantErr) {
t.Errorf("LoadConfig() error = %v, want to contain %v", got, tc.wantErr)
}

@chronark chronark merged commit 3b2929b into main Mar 17, 2025
29 of 31 checks passed
@chronark chronark deleted the chproxy-add-config-tests branch March 17, 2025 06:21
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