| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use self::url::ParseError; |
| 6 |
use super::*; |
| 7 |
use std::error::Error; |
| 8 |
use std::net::{AddrParseError, Ipv4Addr, Ipv6Addr}; |
| 9 |
|
| 10 |
#[derive(Debug)] |
| 11 |
enum ParseTestError { |
| 12 |
Host(ParseError), |
| 13 |
Ip(AddrParseError), |
| 14 |
} |
| 15 |
impl fmt::Display for ParseTestError { |
| 16 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 17 |
match self { |
| 18 |
ParseTestError::Host(inner) => inner.fmt(f), |
| 19 |
ParseTestError::Ip(inner) => inner.fmt(f), |
| 20 |
} |
| 21 |
} |
| 22 |
} |
| 23 |
impl From<ParseError> for ParseTestError { |
| 24 |
fn from(err: ParseError) -> Self { |
| 25 |
ParseTestError::Host(err) |
| 26 |
} |
| 27 |
} |
| 28 |
impl From<AddrParseError> for ParseTestError { |
| 29 |
fn from(err: AddrParseError) -> Self { |
| 30 |
ParseTestError::Ip(err) |
| 31 |
} |
| 32 |
} |
| 33 |
impl Error for ParseTestError { |
| 34 |
fn source(&self) -> Option<&(dyn Error + 'static)> { |
| 35 |
// Generic error, underlying cause isn't tracked. |
| 36 |
match self { |
| 37 |
ParseTestError::Host(a) => Some(a), |
| 38 |
ParseTestError::Ip(a) => Some(a), |
| 39 |
} |
| 40 |
} |
| 41 |
} |
| 42 |
#[test] |
| 43 |
fn test_domain_name_parsing() -> Result<(), ParseTestError> { |
| 44 |
let address = Host::parse("this.is.a.fqdn")?; |
| 45 |
if let Host::Domain(domain) = address { |
| 46 |
assert_eq!(domain, "this.is.a.fqdn"); |
| 47 |
} else { |
| 48 |
panic!(); |
| 49 |
} |
| 50 |
Ok(()) |
| 51 |
} |
| 52 |
|
| 53 |
#[test] |
| 54 |
fn test_ipv4_address_parsing() -> Result<(), ParseTestError> { |
| 55 |
let address = Host::parse("1.0.0.1")?; |
| 56 |
if let Host::Ipv4(ip) = address { |
| 57 |
assert_eq!(ip, "1.0.0.1".parse::<Ipv4Addr>()?); |
| 58 |
} else { |
| 59 |
panic!(); |
| 60 |
} |
| 61 |
Ok(()) |
| 62 |
} |
| 63 |
|
| 64 |
#[test] |
| 65 |
fn test_ipv6_address_parsing() -> Result<(), ParseTestError> { |
| 66 |
let address = Host::parse("[::1]")?; |
| 67 |
if let Host::Ipv6(ip) = address { |
| 68 |
assert_eq!(ip, "::1".parse::<Ipv6Addr>()?); |
| 69 |
} else { |
| 70 |
panic!(); |
| 71 |
} |
| 72 |
Ok(()) |
| 73 |
} |