Changed test for IpAddr::from_str() to test more points of failure

This commit is contained in:
Luke Else 2023-02-11 16:49:23 +00:00
parent d5ec71a000
commit 43cd0f5bc5

View File

@ -1,5 +1,8 @@
use std::str::FromStr; use std::str::FromStr;
#[derive(Debug, PartialEq, Eq)]
pub struct InvalidIPErr;
/// Ip address enum that includes associated type /// Ip address enum that includes associated type
/// ///
/// # Example /// # Example
@ -15,9 +18,6 @@ pub enum IpAddr {
V6(String) V6(String)
} }
#[derive(Debug)]
pub struct InvalidIPErr;
impl ToString for IpAddr { impl ToString for IpAddr {
/// Function that returns an IP address in string form /// Function that returns an IP address in string form
fn to_string(&self) -> String { fn to_string(&self) -> String {
@ -51,6 +51,10 @@ impl FromStr for IpAddr {
let mut ip: [u8; 4] = Default::default(); let mut ip: [u8; 4] = Default::default();
//Go through each octet and ensure it can be parsed; //Go through each octet and ensure it can be parsed;
for (i, oct) in split_ip.into_iter().enumerate() { for (i, oct) in split_ip.into_iter().enumerate() {
if i > ip.len() {
//Ip string is out of the range of the 4 octets in an IPv4 Address
return Err(InvalidIPErr)
}
match oct.parse::<u8>() { match oct.parse::<u8>() {
Ok(parsed_oct) => ip[i] = parsed_oct, Ok(parsed_oct) => ip[i] = parsed_oct,
Err(_) => return Err(InvalidIPErr) Err(_) => return Err(InvalidIPErr)
@ -100,7 +104,8 @@ mod tests {
/// converting from a string to an IpAddr /// converting from a string to an IpAddr
fn invalid_string_to_ip() { fn invalid_string_to_ip() {
use super::*; use super::*;
let ip = "Hello, world"; let ip = "127.0.0.0.1";
IpAddr::from_str(ip).unwrap(); IpAddr::from_str(ip).unwrap();
assert_eq!(IpAddr::from_str(ip), Err(InvalidIPErr))
} }
} }