Skip to content

Commit

Permalink
fix: from string
Browse files Browse the repository at this point in the history
  • Loading branch information
renancloudwalk committed Jun 6, 2024
1 parent 7c36ad0 commit 0dec2d5
Showing 1 changed file with 50 additions and 4 deletions.
54 changes: 50 additions & 4 deletions src/eth/consensus/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,22 @@ impl PeerAddress {
}

fn from_string(s: String) -> Result<Self, anyhow::Error> {
let parts: Vec<&str> = s.split(':').collect();
let (scheme, address_part) = if s.starts_with("http://") {
("http://", &s[7..])
} else if s.starts_with("https://") {
("https://", &s[8..])
} else {
return Err(anyhow::anyhow!("invalid scheme"));
};

let parts: Vec<&str> = address_part.split(':').collect();
if parts.len() != 2 {
return Err(anyhow::anyhow!("Invalid format"));
return Err(anyhow::anyhow!("invalid format"));
}
let address = parts[0].to_string();
let address = format!("{}{}", scheme, parts[0]);
let ports: Vec<&str> = parts[1].split(';').collect();
if ports.len() != 2 {
return Err(anyhow::anyhow!("Invalid format"));
return Err(anyhow::anyhow!("invalid format for jsonrpc and grpc ports"));
}
let jsonrpc_port = ports[0].parse::<u16>()?;
let grpc_port = ports[1].parse::<u16>()?;
Expand Down Expand Up @@ -750,3 +758,41 @@ impl AppendEntryService for AppendEntryServiceImpl {
}))
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_peer_address_from_string_valid() {
let input = "http://127.0.0.1:3000;3777".to_string();
let result = PeerAddress::from_string(input);

assert!(result.is_ok());
let peer_address = result.unwrap();
assert_eq!(peer_address.address, "http://127.0.0.1");
assert_eq!(peer_address.jsonrpc_port, 3000);
assert_eq!(peer_address.grpc_port, 3777);
}

#[test]
fn test_another_peer_address_from_string_valid() {
let input = "https://127.0.0.1:3000;3777".to_string();
let result = PeerAddress::from_string(input);

assert!(result.is_ok());
let peer_address = result.unwrap();
assert_eq!(peer_address.address, "https://127.0.0.1");
assert_eq!(peer_address.jsonrpc_port, 3000);
assert_eq!(peer_address.grpc_port, 3777);
}

#[test]
fn test_peer_address_from_string_invalid_format() {
let input = "http://127.0.0.1-3000;3777".to_string();
let result = PeerAddress::from_string(input);

assert!(result.is_err());
assert_eq!(result.err().unwrap().to_string(), "invalid format");
}
}

0 comments on commit 0dec2d5

Please sign in to comment.