diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/main.rs | 26 | ||||
| -rw-r--r-- | src/test.rs | 48 |
2 files changed, 74 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..428ebf9 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,26 @@ +use std::error::Error; +use std::net::IpAddr; +use std::str::FromStr; +use reqwest::Url; + +#[cfg(test)] +mod test; + +fn main() { + println!("Hello, world!"); +} + +pub struct IpService {} + +impl IpService { + + async fn resolve(config: &impl IpServiceConfiguration) -> Result<IpAddr, Box<dyn Error>> { + let response = reqwest::get(config.get_service_url()).await.unwrap(); + Ok(IpAddr::from_str(&response.text().await.unwrap())?) + } + +} + +pub trait IpServiceConfiguration { + fn get_service_url(&self) -> Url; +} diff --git a/src/test.rs b/src/test.rs new file mode 100644 index 0000000..f2c4219 --- /dev/null +++ b/src/test.rs @@ -0,0 +1,48 @@ +use std::net::{IpAddr, Ipv4Addr}; +use reqwest::Url; +use wiremock::{Mock, MockServer, ResponseTemplate}; +use wiremock::matchers::{method, path}; +use crate::{IpService, IpServiceConfiguration}; + +async fn setup_ipv4_service(service_path: &str, response: &str) -> MockServer { + let ip_service = MockServer::start().await; + + Mock::given(method("GET")) + .and(path(service_path)) + .respond_with(ResponseTemplate::new(200) + .insert_header("Content-Type", "text/plain; charset=utf-8") + .set_body_string(response)) + .mount(&ip_service) + .await; + + ip_service +} + +#[tokio::test] +async fn successful_ipv4_address_resolution() { + let service_path = "get-my-ip-address"; + let service_response = "17.5.7.8"; + + let ip_service = setup_ipv4_service(service_path, service_response).await; + let service_config = TestIpServiceConfiguration::new(&ip_service, service_path); + + let actual = IpService::resolve(&service_config).await.unwrap(); + assert_eq!(actual, IpAddr::V4(Ipv4Addr::new(17, 5, 7, 8))) +} + +struct TestIpServiceConfiguration { + service_url: Url, +} + +impl TestIpServiceConfiguration { + fn new(server: &MockServer, path: &str) -> Self { + Self { + service_url: Url::parse(format!("{}/{}", server.uri(), path).as_str()).unwrap() + } + } +} +impl IpServiceConfiguration for TestIpServiceConfiguration { + fn get_service_url(&self) -> Url { + self.service_url.clone() + } +} |
