Skip to content

Test try from remote network config source #1713

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

0xgleb
Copy link
Collaborator

@0xgleb 0xgleb commented Apr 29, 2025

Motivation

  • HTTP request and parsing logic are not tested

Solution

  • Add unit tests

Checks

By submitting this for review, I'm confirming I've done the following:

  • made this PR as small as possible
  • unit-tested any new functionality
  • linked any relevant issues or PRs
  • included screenshots (if this involves a front-end change)

Summary by CodeRabbit

  • Tests
    • Added asynchronous tests to verify correct handling of various remote network configuration scenarios, including successful parsing, decode errors, connection errors, and unsupported formats.

Copy link
Contributor

coderabbitai bot commented Apr 29, 2025

Walkthrough

A new test module has been added to the codebase, specifically targeting the asynchronous behavior of the RemoteNetworks::try_from_remote_network_config_source method. The tests are written using Tokio and cover multiple scenarios, including successful parsing of a remote network configuration, handling of HTTP decoding errors, connection errors due to invalid URLs, and error cases for unsupported or empty format strings. The tests assert the expected outcomes for each scenario and ensure that errors are correctly wrapped and reported.

Changes

File(s) Change Summary
crates/settings/src/remote/chains/mod.rs Added a private asynchronous test module for RemoteNetworks::try_from_remote_network_config_source, covering success and multiple error scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Function
    participant RemoteNetworks as RemoteNetworks::try_from_remote_network_config_source
    participant HTTP as HTTP Endpoint
    participant Error as Error Handling

    Test->>RemoteNetworks: Call with config source and format
    alt Successful "chainid" fetch
        RemoteNetworks->>HTTP: Fetch config source
        HTTP-->>RemoteNetworks: Return valid response
        RemoteNetworks-->>Test: Return parsed RemoteNetworks
    else HTTP decode error
        RemoteNetworks->>HTTP: Fetch config source
        HTTP-->>RemoteNetworks: Return undecodable response
        RemoteNetworks->>Error: Wrap as ReqwestError
        RemoteNetworks-->>Test: Return error
    else Connection error
        RemoteNetworks->>HTTP: Fetch config source (invalid URL)
        HTTP-->>RemoteNetworks: Connection error
        RemoteNetworks->>Error: Wrap as ReqwestError
        RemoteNetworks-->>Test: Return error
    else Unsupported/empty format
        RemoteNetworks->>Error: UnknownFormat error
        RemoteNetworks-->>Test: Return error
    end
Loading
✨ 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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@0xgleb 0xgleb force-pushed the test-try-from-remote-network-config-source branch from b049b99 to 47f9809 Compare April 29, 2025 17:49
@0xgleb 0xgleb marked this pull request as ready for review April 29, 2025 17:51
@0xgleb 0xgleb linked an issue Apr 29, 2025 that may be closed by this pull request
1 task
@0xgleb 0xgleb added this to the Test coverage, tech debt milestone Apr 29, 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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9c4c519 and 47f9809.

📒 Files selected for processing (1)
  • crates/settings/src/remote/chains/mod.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-artifacts)
  • GitHub Check: standard-tests (ubuntu-latest, test-js-bindings)
  • GitHub Check: Deploy-Preview
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-static)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-artifacts, true)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-artifacts)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-legal)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-static)
  • GitHub Check: standard-tests (ubuntu-latest, ob-rs-test, true)
  • GitHub Check: test
  • GitHub Check: build-tauri (ubuntu-22.04, true)
  • GitHub Check: test
  • GitHub Check: git-clean
  • GitHub Check: test
🔇 Additional comments (1)
crates/settings/src/remote/chains/mod.rs (1)

97-124: Good test structure for multiple cases.

This test effectively covers multiple format string cases without making network calls, making it fast and reliable. The use of a vector to test multiple cases is a good pattern for similar test scenarios.

Comment on lines +40 to +55
#[tokio::test]
async fn test_try_from_remote_network_config_source_ok_case() {
let remote_networks_config_source = RemoteNetworksConfigSource {
format: "chainid".to_string(),
url: "https://chainid.network/chains.json".to_string(),
};

let result =
RemoteNetworks::try_from_remote_network_config_source(remote_networks_config_source)
.await
.unwrap();

let RemoteNetworks::ChainId(chain_ids) = result;

assert_ne!(chain_ids.len(), 0);
}
Copy link
Contributor

@coderabbitai coderabbitai bot Apr 29, 2025

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider using mocks for external API calls in tests.

This test makes a real network call to an external API, which is good for end-to-end testing but can make tests brittle and slow. Consider using a mock server like mockito or wiremock to simulate the API response, making the test more reliable and faster.

// Example with mockito:
let mock_server = mockito::server_url();
let _m = mockito::mock("GET", "/chains.json")
    .with_status(200)
    .with_header("content-type", "application/json")
    .with_body(r#"[{"name":"Ethereum Mainnet","chain":"ETH","icon":"ethereum","rpc":["https://eth.llamarpc.com"]}]"#)
    .create();

let remote_networks_config_source = RemoteNetworksConfigSource {
    format: "chainid".to_string(),
    url: format!("{}/chains.json", mock_server),
};

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yeah, I was thinking about this. Should I make all requests mocked? @hardyjosh @findolor

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment on lines +36 to +125
#[cfg(test)]
mod tests {
use super::*;

#[tokio::test]
async fn test_try_from_remote_network_config_source_ok_case() {
let remote_networks_config_source = RemoteNetworksConfigSource {
format: "chainid".to_string(),
url: "https://chainid.network/chains.json".to_string(),
};

let result =
RemoteNetworks::try_from_remote_network_config_source(remote_networks_config_source)
.await
.unwrap();

let RemoteNetworks::ChainId(chain_ids) = result;

assert_ne!(chain_ids.len(), 0);
}

#[tokio::test]
async fn test_try_from_remote_network_config_source_invalid_response_err_case() {
let remote_networks_config_source = RemoteNetworksConfigSource {
format: "chainid".to_string(),
url: "https://example.com/".to_string(),
};

let result =
RemoteNetworks::try_from_remote_network_config_source(remote_networks_config_source)
.await;

if let Err(RemoteNetworkError::ReqwestError(err)) = &result {
if err.is_decode() {
return;
}
}

panic!("Expected RemoteNetworkError::ReqwestError decoding error");
}

#[tokio::test]
async fn test_try_from_remote_network_config_source_invalid_url_err_case() {
let remote_networks_config_source = RemoteNetworksConfigSource {
format: "chainid".to_string(),
url: "https://invalid.url/unreal".to_string(),
};

let result =
RemoteNetworks::try_from_remote_network_config_source(remote_networks_config_source)
.await;

if let Err(RemoteNetworkError::ReqwestError(err)) = &result {
if err.is_connect() {
return;
}
}

panic!("Expected RemoteNetworkError::ReqwestError connection error");
}

#[tokio::test]
async fn test_try_from_remote_network_config_source_format_parsing_err_case() {
let remote_networks_config_sources = vec![
RemoteNetworksConfigSource {
format: "".to_string(),
url: "https://example.com".to_string(),
},
RemoteNetworksConfigSource {
format: "unknown".to_string(),
url: "https://polygon-rpc.com/".to_string(),
},
];

for remote_networks_config_source in remote_networks_config_sources {
let unexpected_format = remote_networks_config_source.format.clone();

let result = RemoteNetworks::try_from_remote_network_config_source(
remote_networks_config_source,
)
.await;

if let Err(RemoteNetworkError::UnknownFormat(format)) = result {
assert_eq!(format, unexpected_format);
} else {
panic!("Expected RemoteNetworkError::UnknownFormat error");
}
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add tests for potential timeouts and slow responses.

The current tests cover success, decoding errors, connection errors, and format errors, but don't test timeout scenarios. Consider adding tests that verify how the system handles slow responses or timeouts, which are common in network interactions.

#[tokio::test]
async fn test_try_from_remote_network_config_source_timeout() {
    // This requires a mock server that can be configured to delay responses
    // or a real endpoint that's known to be slow/timeout
    let remote_networks_config_source = RemoteNetworksConfigSource {
        format: "chainid".to_string(),
        url: "https://blackhole.webpagetest.org/".to_string(), // Known to time out
    };

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_millis(100))
        .build()
        .unwrap();
    
    // This would require modifying the original function to accept a custom client
    let result = RemoteNetworks::try_from_remote_network_config_source_with_client(
        remote_networks_config_source,
        client,
    ).await;

    assert!(matches!(
        result,
        Err(RemoteNetworkError::ReqwestError(err)) if err.is_timeout()
    ));
}

Comment on lines +77 to +95
#[tokio::test]
async fn test_try_from_remote_network_config_source_invalid_url_err_case() {
let remote_networks_config_source = RemoteNetworksConfigSource {
format: "chainid".to_string(),
url: "https://invalid.url/unreal".to_string(),
};

let result =
RemoteNetworks::try_from_remote_network_config_source(remote_networks_config_source)
.await;

if let Err(RemoteNetworkError::ReqwestError(err)) = &result {
if err.is_connect() {
return;
}
}

panic!("Expected RemoteNetworkError::ReqwestError connection error");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Test might be flaky due to network changes.

This test relies on a non-existent domain name which could potentially be registered in the future, causing the test to fail. Consider using a more controlled approach like a mock server or a well-known local address that will reliably fail (like localhost with an unused port).

- url: "https://invalid.url/unreal".to_string(),
+ url: "http://localhost:1".to_string(), // Guaranteed to fail with connection refused
📝 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
#[tokio::test]
async fn test_try_from_remote_network_config_source_invalid_url_err_case() {
let remote_networks_config_source = RemoteNetworksConfigSource {
format: "chainid".to_string(),
url: "https://invalid.url/unreal".to_string(),
};
let result =
RemoteNetworks::try_from_remote_network_config_source(remote_networks_config_source)
.await;
if let Err(RemoteNetworkError::ReqwestError(err)) = &result {
if err.is_connect() {
return;
}
}
panic!("Expected RemoteNetworkError::ReqwestError connection error");
}
#[tokio::test]
async fn test_try_from_remote_network_config_source_invalid_url_err_case() {
let remote_networks_config_source = RemoteNetworksConfigSource {
format: "chainid".to_string(),
url: "http://localhost:1".to_string(), // Guaranteed to fail with connection refused
};
let result =
RemoteNetworks::try_from_remote_network_config_source(remote_networks_config_source)
.await;
if let Err(RemoteNetworkError::ReqwestError(err)) = &result {
if err.is_connect() {
return;
}
}
panic!("Expected RemoteNetworkError::ReqwestError connection error");
}

Comment on lines +57 to +75
#[tokio::test]
async fn test_try_from_remote_network_config_source_invalid_response_err_case() {
let remote_networks_config_source = RemoteNetworksConfigSource {
format: "chainid".to_string(),
url: "https://example.com/".to_string(),
};

let result =
RemoteNetworks::try_from_remote_network_config_source(remote_networks_config_source)
.await;

if let Err(RemoteNetworkError::ReqwestError(err)) = &result {
if err.is_decode() {
return;
}
}

panic!("Expected RemoteNetworkError::ReqwestError decoding error");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Improve test assertions with more explicit error checks.

The current pattern of using if let ... return followed by a panic works but makes the test's intent less clear. Consider using a more explicit assertion pattern and testing specific error details.

- if let Err(RemoteNetworkError::ReqwestError(err)) = &result {
-     if err.is_decode() {
-         return;
-     }
- }
- 
- panic!("Expected RemoteNetworkError::ReqwestError decoding error");
+ assert!(matches!(
+     result,
+     Err(RemoteNetworkError::ReqwestError(err)) if err.is_decode()
+ ), "Expected a decoding error, got {:?}", result);
📝 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
#[tokio::test]
async fn test_try_from_remote_network_config_source_invalid_response_err_case() {
let remote_networks_config_source = RemoteNetworksConfigSource {
format: "chainid".to_string(),
url: "https://example.com/".to_string(),
};
let result =
RemoteNetworks::try_from_remote_network_config_source(remote_networks_config_source)
.await;
if let Err(RemoteNetworkError::ReqwestError(err)) = &result {
if err.is_decode() {
return;
}
}
panic!("Expected RemoteNetworkError::ReqwestError decoding error");
}
#[tokio::test]
async fn test_try_from_remote_network_config_source_invalid_response_err_case() {
let remote_networks_config_source = RemoteNetworksConfigSource {
format: "chainid".to_string(),
url: "https://example.com/".to_string(),
};
let result =
RemoteNetworks::try_from_remote_network_config_source(remote_networks_config_source)
.await;
assert!(matches!(
result,
Err(RemoteNetworkError::ReqwestError(err)) if err.is_decode()
), "Expected a decoding error, got {:?}", result);
}

@hardyjosh hardyjosh self-requested a review May 1, 2025 11:39
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.

Missing test - Settings crate - remote/chains/mod.rs
1 participant