diff --git a/Cargo.toml b/Cargo.toml index 9f69902..f32ad44 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,3 +13,12 @@ license = "MIT" [badges] appveyor = { repository = "{{username}}/{{repository}}", branch = "main", service = "github" } + +[dependencies] +reqwest = "0.11" +serde = { version = "1", features = ["derive"] } + +[dev-dependencies] +reqwest = "0.11" +tokio = { version = "1", features = ["full"] } +wiremock = "0.5.19" diff --git a/src/api_client.rs b/src/api_client.rs new file mode 100644 index 0000000..eef2ba7 --- /dev/null +++ b/src/api_client.rs @@ -0,0 +1,31 @@ +use reqwest; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Serialize, Deserialize)] +struct Post { + userId: u32, + id: u32, + title: String, + body: String, +} + +pub struct ApiClient { + base_url: String, + client: reqwest::Client, +} + +impl ApiClient { + pub fn new(base_url: &str) -> Self { + let client = reqwest::Client::new(); + ApiClient { + base_url: base_url.to_string(), + client, + } + } + + pub async fn get_post(&self, post_id: u32) -> Result { + let url = format!("{}/posts/{}", self.base_url, post_id); + let response = self.client.get(&url).send().await?; + response.json().await + } +} diff --git a/src/bin/integration_tests.rs b/src/bin/integration_tests.rs new file mode 100644 index 0000000..a231a2a --- /dev/null +++ b/src/bin/integration_tests.rs @@ -0,0 +1,34 @@ +use reqwest; +use tokio::time::Duration; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +#[tokio::test] +async fn integration_test_api_client() { + let mock_server = MockServer::start().await; + let mock = Mock::given(wiremock::matchers::method("GET")) + .and(wiremock::matchers::path("/posts/1")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "userId": 1, + "id": 1, + "title": "Test Post", + "body": "This is a test post." + }))) + .expect(1) + .mount(&mock_server) + .await; + + let base_url = mock_server.uri(); + let api_client = your_module::ApiClient::new(&base_url); + + match api_client.get_post(1).await { + Ok(post) => { + assert_eq!(post.title, "Test Post"); + } + Err(err) => { + eprintln!("Error: {}", err); + panic!("Test failed"); + } + } + + mock.assert().await; +} diff --git a/src/bin/post.rs b/src/bin/post.rs new file mode 100644 index 0000000..e98368b --- /dev/null +++ b/src/bin/post.rs @@ -0,0 +1,19 @@ +mod api_client; + +#[tokio::main] +async fn main() -> Result<(), reqwest::Error> { + // Create an instance of the API client + let api_client = api_client::ApiClient::new("https://jsonplaceholder.typicode.com"); + + // Example: Get a post by ID + match api_client.get_post(1).await { + Ok(post) => { + println!("Post: {:?}", post); + } + Err(err) => { + eprintln!("Error: {}", err); + } + } + + Ok(()) +} diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index 847b314..0000000 --- a/src/lib.rs +++ /dev/null @@ -1 +0,0 @@ -//rust code here