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

feat: add app test #71

Merged
merged 6 commits into from
Jun 28, 2024
Merged

feat: add app test #71

merged 6 commits into from
Jun 28, 2024

Conversation

freak12techno
Copy link
Collaborator

@freak12techno freak12techno commented Jun 28, 2024

Summary by CodeRabbit

  • New Features

    • Added /metrics and /healthcheck routes for server monitoring and health check.
  • Bug Fixes

    • Improved error handling during application startup and shutdown.
  • Tests

    • Introduced new tests for loading, starting, and stopping the application.
    • Added configuration validation and startup tests.
  • Documentation

    • Added Codecov badge to README for better visibility of code coverage.
  • Configuration

    • Added new configuration files for various blockchain networks.
    • Updated .gitignore to include specific configuration files.
  • Refactor

    • Simplified error handling in tracer initialization and related tests.

Copy link
Contributor

coderabbitai bot commented Jun 28, 2024

Walkthrough

The recent updates introduce a new HTTP server along with /metrics and /healthcheck routes, enhance configuration handling with new assets and tests, and simplify tracer management by refining error handling. Additionally, logging severity is updated to Panic, and a Codecov badge is added to the README.md for improved documentation and coverage tracking.

Changes

File(s) Summary
pkg/app.go Added Server field to App struct, custom routes and Healthcheck method, and start/stop functionality for the server.
pkg/app_test.go Introduced tests for application configuration, start/stop, and HTTP mocking for API endpoints.
pkg/config/config_test.go Updated test configuration filename to config-valid.toml.
pkg/tracing/tracer.go, pkg/tracing/tracer_test.go Simplified error handling and adjusted return types in tracing functions.
.gitignore Added an exception to include files matching assets/config*.toml.
assets/config-invalid-listen-address.toml, assets/config-valid.toml, assets/config-with-warnings.toml, and assets/config-invalid.toml Introduced and updated configuration settings for various blockchain chains.
cmd/cosmos-validators-exporter.go Updated logging severity from Fatal to Panic for certain error conditions.
cmd/cosmos-validators-exporter_test.go Added tests for different configuration scenarios in the main() function.
README.md Added a Codecov badge.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant App
    participant HTTPServer

    Client->>App: Start()
    App->>HTTPServer: Initialize with /metrics and /healthcheck routes
    activate HTTPServer
    Note over HTTPServer: HTTP Server runs and listens for requests

    Client->>HTTPServer: /healthcheck
    HTTPServer->>App: Healthcheck()
    App-->>HTTPServer: HTTP 200 OK
    
    Client->>App: Stop()
    App->>HTTPServer: Graceful shutdown
    deactivate HTTPServer
    Note over App: Server stopped
Loading

Poem

In the land of code where circuits hum,
A server wakes, the network's drum,
Healthchecks hum and metrics sing,
Configs gathered, tests take wing.
Tracers dance in outputs clear,
Logging echoes far and near,
With Codecov badge, we cheer this feat,
Our software strong and sweet! 🌿🐇


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@freak12techno
Copy link
Collaborator Author

@coderabbitai I remember you had some learnings about pkg/app.go being untested, now it's not the case and it's not acceptable if it's not tested.

Copy link
Contributor

coderabbitai bot commented Jun 28, 2024

Tip

For best results, initiate chat on the files or code changes.

@freak12techno, thank you for updating the testing expectations for pkg/app.go. I will remove the outdated learnings that previously noted the acceptance of pkg/app.go being untested. Moving forward, I'll ensure to consider the necessity of having tests for this file in future reviews.


Learnings removed
User: freak12techno
PR: QuokkaStake/cosmos-validators-exporter#70
File: pkg/app.go:195-195
Timestamp: 2024-06-27T23:06:14.636Z
Learning: The `pkg/app.go` file isn't tested yet, and this has been acknowledged as acceptable for the current stage of development.

User: freak12techno
PR: QuokkaStake/cosmos-validators-exporter#64
File: pkg/app.go:105-112
Timestamp: 2024-06-25T19:32:53.262Z
Learning: User freak12techno has clarified that while specific tests for new generator functions in `app.go` exist, there is an overall lack of tests for `app.go` itself, which is currently expected and accepted.

Learnings used
User: freak12techno
PR: QuokkaStake/cosmos-validators-exporter#70
File: pkg/app.go:195-195
Timestamp: 2024-06-27T23:06:14.636Z
Learning: The `pkg/app.go` file isn't tested yet, and this has been acknowledged as acceptable for the current stage of development.

User: freak12techno
PR: QuokkaStake/cosmos-validators-exporter#64
File: pkg/app.go:105-112
Timestamp: 2024-06-25T19:32:53.262Z
Learning: User freak12techno has clarified that while specific tests for new generator functions in `app.go` exist, there is an overall lack of tests for `app.go` itself, which is currently expected and accepted.

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 (1)
pkg/app.go (1)

Line range hint 157-232: Comprehensive handling of metrics requests in Handler method.

The method effectively uses concurrency and detailed logging. Consider adding more detailed error handling and logging for fetch operations.

- data, fetcherQueryInfos := fetcher.Fetch(childQuerierCtx)
+ data, fetcherQueryInfos, err := fetcher.Fetch(childQuerierCtx)
+ if err != nil {
+    sublogger.Error().Err(err).Msg("Failed to fetch data with " + fetcher.Name())
+    return
+ }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 87241cf and f2804df.

Files selected for processing (5)
  • pkg/app.go (6 hunks)
  • pkg/app_test.go (1 hunks)
  • pkg/config/config_test.go (1 hunks)
  • pkg/tracing/tracer.go (3 hunks)
  • pkg/tracing/tracer_test.go (3 hunks)
Files skipped from review due to trivial changes (3)
  • pkg/config/config_test.go
  • pkg/tracing/tracer.go
  • pkg/tracing/tracer_test.go
Additional comments not posted (7)
pkg/app.go (3)

34-34: Addition of Server field to App struct approved.

This change aligns with the PR's goal to enhance server management capabilities.


223-225: Simple and effective implementation of the Healthcheck method.

The method correctly handles the health check route, ensuring basic operational validation.


140-149: Proper setup of HTTP handlers and server start in Start method.

The integration of OpenTelemetry and custom route handling enhances observability. Ensure the server responds as expected by conducting integration tests.

Verification successful

Proper setup of HTTP handlers and server start in Start method.

The integration of OpenTelemetry and custom route handling enhances observability. Ensure the server responds as expected by conducting integration tests.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify server response for `/metrics` and `/healthcheck`.

# Test: Send requests to the endpoints. Expect: Successful responses.
curl -s http://localhost:9560/metrics
curl -s http://localhost:9560/healthcheck

Length of output: 83



Script:

#!/bin/bash
# Check the implementation of the Start method in pkg/app.go
ast-grep --lang go --pattern $'func (a *App) Start() error {
  $$$
}' pkg/app.go

# Verify the server configuration settings in pkg/app.go
rg 'ListenAddress' pkg/app.go

Length of output: 334



Script:

#!/bin/bash
# Retrieve the full implementation of the Start method in pkg/app.go
ast-grep --lang go --pattern $'func (a *App) Start() error {
  $$$
}' pkg/app.go

Length of output: 81



Script:

#!/bin/bash
# Search for the Start method definition in pkg/app.go using ripgrep
rg 'func (a \*App\) Start\(\) error' pkg/app.go

Length of output: 137



Script:

#!/bin/bash
# Corrected regex pattern to search for the Start method definition in pkg/app.go using ripgrep
rg 'func \(a \*App\) Start\(\) error' pkg/app.go

Length of output: 50



Script:

#!/bin/bash
# List all method definitions in pkg/app.go using ripgrep
rg 'func \(' pkg/app.go

Length of output: 204



Script:

#!/bin/bash
# Retrieve the full implementation of the Start method in pkg/app.go with the correct signature
ast-grep --lang go --pattern $'func (a *App) Start() {
  $$$
}' pkg/app.go

Length of output: 730

pkg/app_test.go (4)

16-28: Proper testing of configuration loading failure in TestAppLoadConfigError.

The use of panic recovery to test the error handling of the NewApp function is appropriate. Ensure that similar tests are implemented for other critical failure points.


30-42: Testing of invalid configuration handling in TestAppLoadConfigInvalid.

This test ensures that the application correctly handles and reports invalid configurations. The approach is consistent with the previous test and effectively validates the robustness of the configuration loading.


44-56: Testing server start failure in TestAppFailToStart.

The test correctly anticipates a panic when the server fails to start, likely due to an invalid listen address. This is a critical test for ensuring the application handles startup errors gracefully.


67-232: Comprehensive testing of application start and HTTP mocking in TestAppLoadConfigOk.

This test effectively uses HTTP mocking to simulate external dependencies and checks the application's ability to handle external data. The extensive use of httpmock to simulate various endpoints is commendatory.

pkg/app.go Show resolved Hide resolved
pkg/app.go Outdated Show resolved Hide resolved
pkg/app_test.go Outdated Show resolved Hide resolved
Copy link

codecov bot commented Jun 28, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (87241cf) to head (e4f66b6).

Additional details and impacted files
@@             Coverage Diff             @@
##             main       #71      +/-   ##
===========================================
+ Coverage   93.51%   100.00%   +6.48%     
===========================================
  Files          63        63              
  Lines        2560      2567       +7     
===========================================
+ Hits         2394      2567     +173     
+ Misses        165         0     -165     
+ Partials        1         0       -1     

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

freak12techno and others added 3 commits June 28, 2024 16:41
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f2804df and 4b960fa.

Files selected for processing (9)
  • .gitignore (1 hunks)
  • assets/config-invalid-listen-address.toml (1 hunks)
  • assets/config-invalid.toml (1 hunks)
  • assets/config-valid.toml (1 hunks)
  • assets/config-with-warnings.toml (1 hunks)
  • cmd/cosmos-validators-exporter.go (2 hunks)
  • cmd/cosmos-validators-exporter_test.go (1 hunks)
  • pkg/app.go (6 hunks)
  • pkg/app_test.go (1 hunks)
Files not reviewed due to errors (3)
  • assets/config-invalid.toml (no review received)
  • assets/config-invalid-listen-address.toml (no review received)
  • assets/config-with-warnings.toml (no review received)
Files skipped from review due to trivial changes (1)
  • .gitignore
Files skipped from review as they are similar to previous changes (2)
  • pkg/app.go
  • pkg/app_test.go
Additional comments not posted (5)
cmd/cosmos-validators-exporter.go (1)

33-33: Updated error handling and configuration validation.

The changes to use logger.Panic() for critical errors and marking the config flag as required enhance the robustness of the application. Ensure that these changes are tested thoroughly.

Also applies to: 37-37, 76-76, 79-79, 84-84

Verification successful

Updated error handling and configuration validation verified.

The presence of specific test cases in cmd/cosmos-validators-exporter_test.go suggests that the error handling logic for various configuration scenarios is indeed being tested. This includes cases where the configuration is not provided, fails to load, or is invalid.

  • cmd/cosmos-validators-exporter_test.go
    • TestValidateConfigNoConfigProvided
    • TestValidateConfigFailedToLoad
    • TestValidateConfigInvalid
    • TestValidateConfigWithWarnings
    • TestValidateConfigValid
    • TestStartNoConfigProvided
    • TestStartConfigProvided
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the new error handling logic is triggered correctly.
# Test: Introduce errors in the config and check if the application logs them appropriately.

echo "Testing error handling..."
grep "Panic" cmd/cosmos-validators-exporter.go

Length of output: 333



Script:

#!/bin/bash
# Description: Search for test cases related to the error handling logic in the cmd directory.

# Find all test files in the cmd directory
fd --type f --extension go --glob '*_test.go' cmd/

# Search for test functions that might be testing the error handling logic
rg 'func Test' cmd/

Length of output: 730

cmd/cosmos-validators-exporter_test.go (1)

12-22: Comprehensive test coverage for configuration and startup.

The tests appear to cover various scenarios effectively. Ensure that these tests are executed as part of the continuous integration process to catch any issues early.

Also applies to: 25-35, 38-48, 51-55, 58-62, 65-75, 78-88

assets/config-valid.toml (3)

1-3: Logging level set correctly.

The logging level is appropriately set to "debug", which is useful for detailed output during development or troubleshooting.


29-39: Consumer chain configuration is well-defined.

The configuration for the "neutron" consumer chain is clearly defined with appropriate settings for endpoints, chain ID, and denominations.


4-27: Verify blockchain configuration settings.

Ensure that the endpoints, wallet prefixes, and other configuration settings are accurate according to the respective blockchain specifications.

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

Outside diff range and nitpick comments (4)
README.md (4)

Line range hint 32-32: Add blank lines around shell commands for clarity.

According to Markdownlint, fenced code blocks should be surrounded by blank lines to improve readability.

+ 

Line range hint 56-56: Specify language for code blocks.

For better syntax highlighting and readability, specify the language for fenced code blocks.

+ ```sh
56~ sudo systemctl daemon-reload # reflect the systemd file change
57~

Line range hint 107-107: Consider rephrasing for clarity and impact.

The phrase "quite big" is somewhat informal and vague. Specifying exact or recommended values can enhance clarity and professionalism.

107~
- *Important: consider setting quite big intervals/timeouts, both in app config and in Prometheus config.
+ *Important: consider setting substantial intervals/timeouts, such as 120s for both the app config and Prometheus config, to ensure reliability.

Line range hint 108-108: Add a comma for better readability.

Following the style guide, adding a comma after introductory phrases can improve the readability of the documentation.

108~
- This is due to some requests taking a lot of time, and with a shorter timeout there's a chance the whole scrape request will time out.
+ This is due to some requests taking a lot of time, and, with a shorter timeout, there's a chance the whole scrape request will time out.
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4b960fa and e4f66b6.

Files selected for processing (1)
  • README.md (1 hunks)
Additional context used
LanguageTool
README.md

[style] ~47-~47: You have already used this phrasing in nearby sentences. Consider replacing it to add variety to your writing.
Context: ...lidators-exporter /usr/bin ``` Then we need to create a systemd service for our app: ...

(REP_NEED_TO_VB)


[style] ~107-~107: As an alternative to the over-used intensifier ‘quite’, consider replacing this phrase.
Context: ...od to go! *Important: consider setting quite big intervals/timeouts, both in app config ...

(EN_WEAK_ADJECTIVE)


[typographical] ~108-~108: Consider adding a comma after this introductory phrase.
Context: ...aking a lot of time, and with a shorter timeout there's a chance the whole scrape reque...

(AS_A_NN_COMMA)

Markdownlint
README.md

32-32: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


56-56: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

README.md Show resolved Hide resolved
@freak12techno freak12techno merged commit ce2df06 into main Jun 28, 2024
8 checks passed
@freak12techno freak12techno deleted the add-app-test branch June 28, 2024 23:29
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.

1 participant