├── src ├── lib.rs ├── error.rs ├── cookie.rs ├── client.rs └── response.rs ├── .gitignore ├── examples └── quick_dev.rs ├── LICENSE-MIT ├── Cargo.toml ├── tests └── test_base.rs ├── README.md └── LICENSE-APACHE /src/lib.rs: -------------------------------------------------------------------------------- 1 | mod client; 2 | mod cookie; 3 | mod error; 4 | mod response; 5 | 6 | // public re-exports 7 | pub type Result = std::result::Result; 8 | pub use crate::client::new_client; 9 | pub use crate::client::new_client_with_reqwest; 10 | pub use crate::client::Client; 11 | pub use crate::cookie::Cookie; 12 | pub use crate::error::Error; 13 | pub use crate::response::Response; 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # By Default, Ignore any .*, except .gitignore 2 | .* 3 | !.gitignore 4 | Cargo.lock 5 | 6 | # --- Rust 7 | target/ 8 | 9 | 10 | # --- Safety net 11 | dist/ 12 | out/ 13 | __pycache__/ 14 | node_modules/ 15 | npm-debug.log 16 | report.*.json 17 | 18 | *.parquet 19 | *.map 20 | *.zip 21 | *.gz 22 | *.tar 23 | *.tgz 24 | 25 | # videos 26 | *.mov 27 | *.mp4 28 | 29 | # images 30 | *.icns 31 | *.ico 32 | *.jpeg 33 | *.jpg 34 | *.png -------------------------------------------------------------------------------- /examples/quick_dev.rs: -------------------------------------------------------------------------------- 1 | //! Note: http rest endpoints: https://sqa.stackexchange.com/questions/47097/free-sites-for-testing-post-rest-api-calls 2 | //! Using: https://jsonplaceholder.typicode.com/ 3 | 4 | use anyhow::Result; 5 | 6 | const END_POINT: &str = "https://jsonplaceholder.typicode.com"; 7 | 8 | #[tokio::main] 9 | async fn main() -> Result<()> { 10 | let hc = httpc_test::new_client(END_POINT)?; 11 | 12 | let req = hc.do_get("/posts/1").await?; 13 | req.print().await?; 14 | 15 | let req = hc.do_get("/todos/1").await?; 16 | req.print().await?; 17 | 18 | Ok(()) 19 | } 20 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use reqwest::Method; 2 | 3 | #[derive(thiserror::Error, Debug)] 4 | pub enum Error { 5 | #[error("Generic error: {0}")] 6 | Generic(String), 7 | 8 | #[error("Static error: {0}")] 9 | Static(&'static str), 10 | 11 | #[error("Method not supported for client.do_push (only POST, PUSH, PATCH). Was: {given_method}")] 12 | NotSupportedMethodForPush { given_method: Method }, 13 | 14 | #[error("Not Json value at json pointer: {json_pointer}")] 15 | NoJsonValueFound { json_pointer: String }, 16 | 17 | #[error(transparent)] 18 | IO(#[from] std::io::Error), 19 | 20 | #[error(transparent)] 21 | Reqwest(#[from] reqwest::Error), 22 | 23 | #[error(transparent)] 24 | SerdeJson(#[from] serde_json::Error), 25 | } 26 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2023 Jeremy Chone 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "httpc-test" 3 | version = "0.1.10" 4 | edition = "2021" 5 | authors = ["Jeremy Chone "] 6 | license = "MIT OR Apache-2.0" 7 | description = "Minimalistic HTTP Client Test Utilities" 8 | categories = ["development-tools::testing", "network-programming", "web-programming::http-client" ] 9 | keywords = [ 10 | "test", 11 | "http-client" 12 | ] 13 | homepage = "https://github.com/jeremychone/rust-httpc-test" 14 | repository = "https://github.com/jeremychone/rust-httpc-test" 15 | 16 | [features] 17 | color-output = ["url", "colored_json", "colored"] 18 | 19 | [dependencies] 20 | tokio = { version = "1", features = ["full"] } 21 | thiserror = "1" 22 | reqwest = {version = "0.12", features = ["cookies", "json"]} 23 | reqwest_cookie_store = "0.8" 24 | cookie = "0.18" 25 | serde = { version = "1", features = ["derive"] } 26 | serde_json = "1" 27 | 28 | [dependencies.colored] 29 | version = "2.1.0" 30 | optional = true 31 | 32 | [dependencies.url] 33 | version = "2" 34 | optional = true 35 | 36 | [dependencies.colored_json] 37 | version = "5" 38 | optional = true 39 | 40 | [dev-dependencies] 41 | anyhow = "1" 42 | -------------------------------------------------------------------------------- /tests/test_base.rs: -------------------------------------------------------------------------------- 1 | //! Note: http rest endpoints: https://sqa.stackexchange.com/questions/47097/free-sites-for-testing-post-rest-api-calls 2 | //! Using: https://jsonplaceholder.typicode.com/ 3 | //! 4 | //! Some is better than none: At this point very basic tests. 5 | 6 | use anyhow::Result; 7 | use serde_json::json; 8 | 9 | const TYPICODE_END_POINT: &str = "https://jsonplaceholder.typicode.com"; 10 | 11 | #[tokio::test] 12 | async fn test_base_typicode_get() -> Result<()> { 13 | // -- Setup 14 | let hc = httpc_test::new_client(TYPICODE_END_POINT)?; 15 | 16 | // -- Exec 17 | let res = hc.do_get("/posts/1").await?; 18 | let status = res.status(); 19 | let res = res.json_body()?.to_string(); 20 | 21 | // -- Check 22 | assert_eq!(status, 200); 23 | assert!(res.contains(r#""body":"quia et suscipit\nsuscipit"#)); 24 | assert!(res.contains(r#""id":1"#)); 25 | assert!(res.contains(r#""userId":1"#)); 26 | 27 | Ok(()) 28 | } 29 | 30 | #[tokio::test] 31 | async fn test_base_typicode_post() -> Result<()> { 32 | // -- Setup 33 | let hc = httpc_test::new_client(TYPICODE_END_POINT)?; 34 | 35 | // -- Exec 36 | let res = hc 37 | .do_post( 38 | "/posts", 39 | json!( 40 | { 41 | "userId": 1, 42 | "title": "test_base_typicode_post - title-01", 43 | "body": "test_base_typicode_post - body-01" 44 | } 45 | ), 46 | ) 47 | .await?; 48 | let status = res.status(); 49 | let res = res.json_body()?; 50 | 51 | // -- Check 52 | assert_eq!(status, 201); // success, resource created. 53 | assert_eq!( 54 | res.to_string(), 55 | r#"{"body":"test_base_typicode_post - body-01","id":101,"title":"test_base_typicode_post - title-01","userId":1}"# 56 | ); 57 | 58 | Ok(()) 59 | } 60 | -------------------------------------------------------------------------------- /src/cookie.rs: -------------------------------------------------------------------------------- 1 | use std::time::{Duration, SystemTime}; 2 | 3 | #[derive(Debug)] 4 | pub struct Cookie { 5 | pub name: String, 6 | pub value: String, 7 | pub http_only: bool, 8 | pub secure: bool, 9 | pub same_site_lax: bool, 10 | pub same_site_strict: bool, 11 | pub path: Option, 12 | pub max_age: Option, 13 | pub expires: Option, 14 | } 15 | 16 | pub fn from_tower_cookie_deref(val: &cookie::Cookie) -> Cookie { 17 | let max_age: Option = val 18 | .max_age() 19 | .map(|d| d.try_into().expect("time::Duration into std::time::Duration")); 20 | let expires = match val.expires() { 21 | Some(cookie::Expiration::DateTime(offset)) => Some(SystemTime::from(offset)), 22 | None | Some(cookie::Expiration::Session) => None, 23 | }; 24 | 25 | Cookie { 26 | name: val.name().to_string(), 27 | value: val.value().to_string(), 28 | http_only: val.http_only().unwrap_or(false), 29 | secure: val.secure().unwrap_or(false), 30 | same_site_lax: matches!(val.same_site(), Some(cookie::SameSite::Lax)), 31 | same_site_strict: matches!(val.same_site(), Some(cookie::SameSite::Strict)), 32 | path: val.path().map(String::from), 33 | max_age, 34 | expires, 35 | } 36 | } 37 | 38 | impl From<&cookie::Cookie<'_>> for Cookie { 39 | fn from(val: &cookie::Cookie) -> Self { 40 | let max_age: Option = val 41 | .max_age() 42 | .map(|d| d.try_into().expect("time::Duration into std::time::Duration")); 43 | let expires = match val.expires() { 44 | Some(cookie::Expiration::DateTime(offset)) => Some(SystemTime::from(offset)), 45 | None | Some(cookie::Expiration::Session) => None, 46 | }; 47 | 48 | Cookie { 49 | name: val.name().to_string(), 50 | value: val.value().to_string(), 51 | http_only: val.http_only().unwrap_or(false), 52 | secure: val.secure().unwrap_or(false), 53 | same_site_lax: matches!(val.same_site(), Some(cookie::SameSite::Lax)), 54 | same_site_strict: matches!(val.same_site(), Some(cookie::SameSite::Strict)), 55 | path: val.path().map(String::from), 56 | max_age, 57 | expires, 58 | } 59 | } 60 | } 61 | 62 | impl From> for Cookie { 63 | fn from(val: reqwest::cookie::Cookie<'_>) -> Self { 64 | Cookie { 65 | name: val.name().to_string(), 66 | value: val.value().to_string(), 67 | http_only: val.http_only(), 68 | secure: val.secure(), 69 | same_site_lax: val.same_site_lax(), 70 | same_site_strict: val.same_site_strict(), 71 | path: val.path().map(String::from), 72 | max_age: val.max_age(), 73 | expires: val.expires(), 74 | } 75 | } 76 | } 77 | 78 | impl From<&reqwest::cookie::Cookie<'_>> for Cookie { 79 | fn from(val: &reqwest::cookie::Cookie) -> Self { 80 | Cookie { 81 | name: val.name().to_string(), 82 | value: val.value().to_string(), 83 | http_only: val.http_only(), 84 | secure: val.secure(), 85 | same_site_lax: val.same_site_lax(), 86 | same_site_strict: val.same_site_strict(), 87 | path: val.path().map(String::from), 88 | max_age: val.max_age(), 89 | expires: val.expires(), 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | Minimalistic HTTP Client Test Utilities. 3 | 4 | - Built on top of [reqwest](https://crates.io/crates/reqwest). 5 | - Optimized for testing convenience, not for performance. 6 | - Do not use for production/application code, just for testing. 7 | - For production code (apps, services, ...) use the underlying [reqwest](https://crates.io/crates/reqwest) library and its utilities. 8 | 9 | # Thanks 10 | 11 | - Thanks to [@joeftiger](https://github.com/joeftiger) for dependencies update (#23) 12 | - Thanks to [@Manubi](https://github.com/Manubi) for the `colored_json` update. 13 | - Thanks to [@JamesGuthrie](https://github.com/JamesGuthrie) for 14 | - [PR #17 + Allow building client with custom reqwest::ClientBuilder](https://github.com/jeremychone/rust-httpc-test/pull/17) 15 | - [PR #16 + Make rustc_http::Client public](https://github.com/jeremychone/rust-httpc-test/pull/16) 16 | - Thanks to [@cyril-marpaud](https://github.com/cyril-marpaud) for the [PR #9 - feat: provide Response's StatusCode](https://github.com/jeremychone/rust-httpc-test/pull/9). 17 | - Thanks to [@eboody](https://github.com/eboody) for the [PR #7 - Add colors to output](https://github.com/jeremychone/rust-httpc-test/pull/7) (enable with `features = ["color-output"]`) 18 | - Thanks to [@defic](https://github.com/defic) for the type client `get/post/put/patch/delete` and the response `body...` APIs. 19 | 20 | 21 | # Example 22 | 23 | ```rs 24 | use anyhow::Result; 25 | use serde_json::{json, Value}; 26 | 27 | #[tokio::test] 28 | async fn test_simple_base() -> httpc_test::Result<()> { 29 | // Create a new httpc test client with a base URL (will be prefixed for all calls) 30 | // The client will have a cookie_store. 31 | let hc = httpc_test::new_client("http://localhost:8080")?; 32 | 33 | 34 | //// do_get, do_post, do_put, do_patch, do_delete return a httpc_test::Response 35 | 36 | // Simple do_get 37 | let res = hc.do_get("/hello").await?; // httpc_test::Response 38 | let status = res.status(); 39 | // Pretty print the result (status, headers, response cookies, client cookies, body) 40 | res.print().await?; 41 | 42 | let auth_token = res.res_cookie_value("auth-token"); // Option 43 | let content_type = res.header("content_type"); // Option<&String> 44 | 45 | // Another do_get 46 | let res = hc.do_get("/context.rs").await?; 47 | // Pretty print but do not print the body 48 | res.print_no_body().await?; 49 | 50 | 51 | //// get, post, put, patch, delete return a DeserializeOwned 52 | 53 | // a get (return a Deserialized) 54 | let json_value = hc.get::("/api/tickets").await?; 55 | 56 | // Another post (with the cookie store updated from the login request above ) 57 | let res = hc 58 | .do_post( 59 | "/api/tickets", 60 | json!({ 61 | "subject": "ticket 01" 62 | }), 63 | ) 64 | .await?; 65 | res.print().await?; 66 | 67 | 68 | // Post with text content and specific content type 69 | let res = hc 70 | .do_post( 71 | "/api/tickets", 72 | (r#"{ 73 | "subject": "ticket bb" 74 | } 75 | "#, 76 | "application/json"), 77 | ) 78 | .await?; 79 | res.print().await?; 80 | 81 | // Same woth do_patch, do_put. 82 | 83 | 84 | Ok(()) 85 | } 86 | ``` 87 | 88 |

89 | [This GitHub repo](https://github.com/jeremychone/rust-httpc-test) -------------------------------------------------------------------------------- /src/client.rs: -------------------------------------------------------------------------------- 1 | use crate::cookie::{from_tower_cookie_deref, Cookie}; 2 | use crate::{Error, Response, Result}; 3 | use reqwest::Method; 4 | use reqwest_cookie_store::CookieStoreMutex; 5 | use serde::de::DeserializeOwned; 6 | use serde_json::Value; 7 | use std::sync::Arc; 8 | 9 | pub struct Client { 10 | base_url: Option, 11 | cookie_store: Arc, 12 | reqwest_client: reqwest::Client, 13 | } 14 | 15 | impl Client { 16 | pub fn cookie_store(&self) -> Arc { 17 | self.cookie_store.clone() 18 | } 19 | pub fn reqwest_client(&self) -> &reqwest::Client { 20 | &self.reqwest_client 21 | } 22 | } 23 | 24 | pub fn new_client(base_url: impl Into) -> Result { 25 | let reqwest_builder = reqwest::Client::builder(); 26 | 27 | new_client_with_reqwest(base_url, reqwest_builder) 28 | } 29 | 30 | pub fn new_client_with_reqwest( 31 | base_url: impl Into, 32 | reqwest_builder: reqwest::ClientBuilder, 33 | ) -> Result { 34 | let base_url = base_url.into().into(); 35 | let cookie_store = Arc::new(CookieStoreMutex::default()); 36 | let reqwest_client = reqwest_builder.cookie_provider(cookie_store.clone()).build()?; 37 | 38 | Ok(Client { 39 | base_url, 40 | cookie_store, 41 | reqwest_client, 42 | }) 43 | } 44 | 45 | impl Client { 46 | // region: --- http calls returning httpc-test Response 47 | pub async fn do_get(&self, url: &str) -> Result { 48 | let url = self.compose_url(url); 49 | let reqwest_res = self.reqwest_client.get(&url).send().await?; 50 | self.capture_response(Method::GET, url, reqwest_res).await 51 | } 52 | 53 | pub async fn do_delete(&self, url: &str) -> Result { 54 | let url = self.compose_url(url); 55 | let reqwest_res = self.reqwest_client.delete(&url).send().await?; 56 | self.capture_response(Method::DELETE, url, reqwest_res).await 57 | } 58 | 59 | pub async fn do_post(&self, url: &str, content: impl Into) -> Result { 60 | self.do_push(Method::POST, url, content.into()).await 61 | } 62 | 63 | pub async fn do_put(&self, url: &str, content: impl Into) -> Result { 64 | self.do_push(Method::PUT, url, content.into()).await 65 | } 66 | 67 | pub async fn do_patch(&self, url: &str, content: impl Into) -> Result { 68 | self.do_push(Method::PATCH, url, content.into()).await 69 | } 70 | // endregion: --- http calls returning httpc-test Response 71 | 72 | // region: --- http calls returning typed Deserialized body 73 | pub async fn get(&self, url: &str) -> Result 74 | where 75 | T: DeserializeOwned, 76 | { 77 | self.do_get(url).await.and_then(|res| res.json_body_as::()) 78 | } 79 | 80 | pub async fn delete(&self, url: &str) -> Result 81 | where 82 | T: DeserializeOwned, 83 | { 84 | self.do_delete(url).await.and_then(|res| res.json_body_as::()) 85 | } 86 | 87 | pub async fn post(&self, url: &str, content: impl Into) -> Result 88 | where 89 | T: DeserializeOwned, 90 | { 91 | self.do_post(url, content).await.and_then(|res| res.json_body_as::()) 92 | } 93 | 94 | pub async fn put(&self, url: &str, content: impl Into) -> Result 95 | where 96 | T: DeserializeOwned, 97 | { 98 | self.do_put(url, content).await.and_then(|res| res.json_body_as::()) 99 | } 100 | 101 | pub async fn patch(&self, url: &str, content: impl Into) -> Result 102 | where 103 | T: DeserializeOwned, 104 | { 105 | self.do_patch(url, content).await.and_then(|res| res.json_body_as::()) 106 | } 107 | // endregion: --- http calls returning typed Deserialized body 108 | 109 | // region: --- Cookie 110 | pub fn cookie(&self, name: &str) -> Option { 111 | let cookie_store = self.cookie_store.lock().unwrap(); 112 | let cookie = cookie_store 113 | .iter_any() 114 | .find(|c| c.name() == name) 115 | .map(|c| from_tower_cookie_deref(c)); 116 | 117 | cookie 118 | } 119 | 120 | pub fn cookie_value(&self, name: &str) -> Option { 121 | self.cookie(name).map(|c| c.value) 122 | } 123 | // endregion: --- Cookie 124 | 125 | // region: --- Client Privates 126 | 127 | /// Internal implementation for POST, PUT, PATCH 128 | async fn do_push(&self, method: Method, url: &str, content: PostContent) -> Result { 129 | let url = self.compose_url(url); 130 | if !matches!(method, Method::POST | Method::PUT | Method::PATCH) { 131 | return Err(Error::NotSupportedMethodForPush { given_method: method }); 132 | } 133 | let reqwest_res = match content { 134 | PostContent::Json(value) => self.reqwest_client.request(method.clone(), &url).json(&value).send().await?, 135 | PostContent::Text { content_type, body } => { 136 | self.reqwest_client 137 | .request(method.clone(), &url) 138 | .body(body) 139 | .header("content-type", content_type) 140 | .send() 141 | .await? 142 | } 143 | }; 144 | 145 | self.capture_response(method, url, reqwest_res).await 146 | } 147 | 148 | #[allow(clippy::await_holding_lock)] // ok for testing lib 149 | async fn capture_response( 150 | &self, 151 | request_method: Method, 152 | url: String, 153 | reqwest_res: reqwest::Response, 154 | ) -> Result { 155 | // Note: For now, we will unwrap/panic if fail. 156 | // Might handle this differently in the future. 157 | let cookie_store = self.cookie_store.lock().unwrap(); 158 | 159 | // Cookies from the client store 160 | let client_cookies: Vec = cookie_store.iter_any().map(|c| from_tower_cookie_deref(c)).collect(); 161 | 162 | Response::from_reqwest_response(request_method, url, client_cookies, reqwest_res).await 163 | } 164 | 165 | fn compose_url(&self, url: &str) -> String { 166 | match &self.base_url { 167 | Some(base_url) => format!("{base_url}{url}"), 168 | None => url.to_string(), 169 | } 170 | } 171 | // endregion: --- Client Privates 172 | } 173 | 174 | // region: --- Post Body 175 | pub enum PostContent { 176 | Json(Value), 177 | Text { body: String, content_type: &'static str }, 178 | } 179 | impl From for PostContent { 180 | fn from(val: Value) -> Self { 181 | PostContent::Json(val) 182 | } 183 | } 184 | impl From for PostContent { 185 | fn from(val: String) -> Self { 186 | PostContent::Text { 187 | content_type: "text/plain", 188 | body: val, 189 | } 190 | } 191 | } 192 | impl From<&String> for PostContent { 193 | fn from(val: &String) -> Self { 194 | PostContent::Text { 195 | content_type: "text/plain", 196 | body: val.to_string(), 197 | } 198 | } 199 | } 200 | 201 | impl From<&str> for PostContent { 202 | fn from(val: &str) -> Self { 203 | PostContent::Text { 204 | content_type: "text/plain", 205 | body: val.to_string(), 206 | } 207 | } 208 | } 209 | 210 | impl From<(String, &'static str)> for PostContent { 211 | fn from((body, content_type): (String, &'static str)) -> Self { 212 | PostContent::Text { body, content_type } 213 | } 214 | } 215 | 216 | impl From<(&str, &'static str)> for PostContent { 217 | fn from((body, content_type): (&str, &'static str)) -> Self { 218 | PostContent::Text { 219 | body: body.to_string(), 220 | content_type, 221 | } 222 | } 223 | } 224 | 225 | // endregion: --- Post Body 226 | 227 | // region: --- BaseUrl 228 | pub struct BaseUrl(Option); 229 | 230 | impl From<&str> for BaseUrl { 231 | fn from(val: &str) -> Self { 232 | BaseUrl(Some(val.to_string())) 233 | } 234 | } 235 | impl From for BaseUrl { 236 | fn from(val: String) -> Self { 237 | BaseUrl(Some(val)) 238 | } 239 | } 240 | impl From<&String> for BaseUrl { 241 | fn from(val: &String) -> Self { 242 | BaseUrl(Some(val.to_string())) 243 | } 244 | } 245 | impl From for Option { 246 | fn from(val: BaseUrl) -> Self { 247 | val.0 248 | } 249 | } 250 | impl From> for BaseUrl { 251 | fn from(val: Option) -> Self { 252 | BaseUrl(val) 253 | } 254 | } 255 | // endregion: --- BaseUrl 256 | -------------------------------------------------------------------------------- /src/response.rs: -------------------------------------------------------------------------------- 1 | use crate::cookie::Cookie; 2 | use crate::{Error, Result}; 3 | use reqwest::{Method, StatusCode}; 4 | use serde::de::DeserializeOwned; 5 | use serde_json::{to_string_pretty, Value}; 6 | 7 | #[allow(unused)] 8 | #[cfg(feature = "color-output")] 9 | use colored::*; 10 | #[allow(unused)] 11 | #[cfg(feature = "color-output")] 12 | use colored_json::prelude::*; 13 | use reqwest::header::HeaderMap; 14 | 15 | pub struct Response { 16 | request_method: Method, 17 | request_url: String, 18 | 19 | status: StatusCode, 20 | header_map: HeaderMap, 21 | 22 | client_cookies: Vec, 23 | 24 | /// Cookies from the response 25 | cookies: Vec, 26 | body: Body, 27 | } 28 | 29 | enum Body { 30 | Json(Value), 31 | Text(String), 32 | Other, 33 | } 34 | 35 | #[allow(unused)] 36 | #[cfg(feature = "color-output")] 37 | fn get_status_color(status: &StatusCode) -> Color { 38 | match status.as_u16() { 39 | 200..=299 => Color::Green, // 2xx status codes are successful so we color them green 40 | 300..=399 => Color::Blue, // 3xx status codes are for redirection so we color them blue 41 | 400..=499 => Color::Yellow, // 4xx status codes are client errors so we color them yellow 42 | 500..=599 => Color::Red, // 5xx status codes are server errors so we color them red 43 | _ => Color::White, // Anything else we just color white 44 | } 45 | } 46 | 47 | #[allow(unused)] 48 | #[cfg(feature = "color-output")] 49 | fn get_method_background(method: &Method) -> Color { 50 | match *method { 51 | Method::GET => Color::TrueColor { r: 223, g: 231, b: 238 }, 52 | Method::POST => Color::TrueColor { r: 220, g: 233, b: 228 }, 53 | Method::PUT => Color::TrueColor { r: 238, g: 229, b: 218 }, 54 | Method::DELETE => Color::TrueColor { r: 238, g: 219, b: 219 }, 55 | _ => Color::White, 56 | } 57 | } 58 | 59 | #[allow(unused)] 60 | #[cfg(feature = "color-output")] 61 | fn get_method_color(method: &Method) -> Color { 62 | match *method { 63 | Method::GET => Color::TrueColor { r: 92, g: 166, b: 241 }, 64 | Method::POST => Color::TrueColor { r: 59, g: 184, b: 127 }, 65 | Method::PUT => Color::TrueColor { r: 239, g: 153, b: 46 }, 66 | Method::DELETE => Color::TrueColor { r: 236, g: 59, b: 59 }, 67 | _ => Color::White, 68 | } 69 | } 70 | 71 | #[allow(unused)] 72 | #[cfg(feature = "color-output")] 73 | fn split_and_color_url(url: &str) -> String { 74 | let url_struct = url::Url::parse(url).unwrap(); 75 | let path = url_struct.path(); 76 | format!("{}", path.purple()) 77 | } 78 | 79 | #[allow(unused)] 80 | #[cfg(feature = "color-output")] 81 | fn format_method(method: &Method) -> String { 82 | format!(" {:<10}", method.to_string()) 83 | } 84 | 85 | #[allow(unused)] 86 | #[cfg(feature = "color-output")] 87 | const INDENTATION: u8 = 12; 88 | 89 | impl Response { 90 | pub(crate) async fn from_reqwest_response( 91 | request_method: Method, 92 | request_url: String, 93 | client_cookies: Vec, 94 | mut res: reqwest::Response, 95 | ) -> Result { 96 | let status = res.status(); 97 | 98 | // Cookies from response 99 | let cookies: Vec = res.cookies().map(Cookie::from).collect(); 100 | 101 | // Move the headers into a new HeaderMap 102 | let headers = res.headers_mut().drain().filter_map(|(n, v)| n.map(|n| (n, v))); 103 | let header_map = HeaderMap::from_iter(headers); 104 | 105 | // Capture the body 106 | let ct = header_map.get("content-type").and_then(|v| v.to_str().ok()); 107 | let body = if let Some(ct) = ct { 108 | if ct.starts_with("application/json") { 109 | Body::Json(res.json::().await?) 110 | } else if ct.starts_with("text/") { 111 | Body::Text(res.text().await?) 112 | } else { 113 | Body::Other 114 | } 115 | } else { 116 | Body::Other 117 | }; 118 | 119 | Ok(Response { 120 | client_cookies, 121 | request_method, 122 | request_url, 123 | status, 124 | header_map, 125 | cookies, 126 | body, 127 | }) 128 | } 129 | } 130 | 131 | impl Response { 132 | // region: --- Print Methods 133 | pub async fn print(&self) -> Result<()> { 134 | self.inner_print(true).await 135 | } 136 | 137 | pub async fn print_no_body(&self) -> Result<()> { 138 | self.inner_print(false).await 139 | } 140 | 141 | /// NOTE: For now, does not need to be async, but keeping the option of using async for later. 142 | #[allow(unused)] 143 | #[cfg(feature = "color-output")] 144 | async fn inner_print(&self, body: bool) -> Result<()> { 145 | let method_color = get_method_color(&self.request_method); 146 | let method_background = get_method_background(&self.request_method); 147 | let colored_url = split_and_color_url(&self.request_url); 148 | let status_color = get_status_color(&self.status); 149 | println!(); 150 | println!( 151 | "{}: {}", 152 | format_method(&self.request_method) 153 | .bold() 154 | .color(method_color) 155 | .on_truecolor(50, 50, 50), 156 | colored_url 157 | ); 158 | println!( 159 | " {:<9} : {} {}", 160 | "Status".blue(), 161 | self.status.as_str().bold().color(status_color).on_black(), 162 | self.status.canonical_reason().unwrap_or_default().color(status_color) 163 | ); 164 | 165 | // Print the response headers. 166 | println!(" {:<9} :", "Headers".blue()); 167 | 168 | for (n, v) in self.header_map.iter() { 169 | println!(" {}: {}", n.to_string().yellow(), v.to_str().unwrap_or_default()); 170 | } 171 | 172 | // Print the cookie_store 173 | if !self.cookies.is_empty() { 174 | println!(" {}:", "Response Cookies".blue()); 175 | for c in self.cookies.iter() { 176 | println!(" {}: {}", c.name.yellow(), c.value.bold()); 177 | } 178 | } 179 | 180 | // Print the cookie_store 181 | if !self.client_cookies.is_empty() { 182 | println!(" {}:", "Client Cookies".blue()); 183 | for c in self.client_cookies.iter() { 184 | println!(" {}: {}", c.name.yellow(), c.value.bold()); 185 | } 186 | } 187 | 188 | if body { 189 | // Print the body (json pretty print if json type) 190 | println!("{}:", "Response Body".blue()); 191 | match &self.body { 192 | Body::Json(val) => println!("{}", to_string_pretty(val)?.to_colored_json_auto()?), 193 | Body::Text(val) => println!(" {}", val.color(status_color)), 194 | _ => (), 195 | } 196 | } 197 | 198 | println!("\n"); 199 | Ok(()) 200 | } 201 | 202 | #[cfg(not(feature = "color-output"))] 203 | async fn inner_print(&self, body: bool) -> Result<()> { 204 | println!(); 205 | println!("=== Response for {} {}", self.request_method, &self.request_url); 206 | 207 | println!( 208 | "=> {:<15}: {} {}", 209 | "Status", 210 | self.status.as_str(), 211 | self.status.canonical_reason().unwrap_or_default() 212 | ); 213 | 214 | // Print the response headers. 215 | println!("=> {:<15}:", "Headers"); 216 | 217 | for (n, v) in self.header_map.iter() { 218 | println!(" {}: {}", n, v.to_str().unwrap_or_default()); 219 | } 220 | 221 | // Print the cookie_store 222 | if !self.cookies.is_empty() { 223 | println!("=> {:<15}:", "Response Cookies"); 224 | for c in self.cookies.iter() { 225 | println!(" {}: {}", c.name, c.value); 226 | } 227 | } 228 | 229 | // Print the cookie_store 230 | if !self.client_cookies.is_empty() { 231 | println!("=> {:<15}:", "Client Cookies"); 232 | for c in self.client_cookies.iter() { 233 | println!(" {}: {}", c.name, c.value); 234 | } 235 | } 236 | 237 | if body { 238 | // Print the body (json pretty print if json type) 239 | println!("=> {:<15}:", "Response Body"); 240 | match &self.body { 241 | Body::Json(val) => println!("{}", to_string_pretty(val)?), 242 | Body::Text(val) => println!("{}", val), 243 | _ => (), 244 | } 245 | } 246 | 247 | println!("===\n"); 248 | Ok(()) 249 | } 250 | 251 | // endregion: --- Print Methods 252 | 253 | // region: --- Headers 254 | pub fn header_all(&self, name: &str) -> Vec { 255 | self.header_map 256 | .get_all(name) 257 | .iter() 258 | .filter_map(|v| v.to_str().map(|v| v.to_string()).ok()) 259 | .collect() 260 | } 261 | 262 | pub fn header(&self, name: &str) -> Option { 263 | self.header_map.get(name).and_then(|v| v.to_str().map(|v| v.to_string()).ok()) 264 | } 265 | // endregion: --- Headers 266 | 267 | // region: --- Status Code 268 | /// Return the Response status code 269 | pub fn status(&self) -> StatusCode { 270 | self.status 271 | } 272 | // endregion: --- Status Code 273 | 274 | // region: --- Response Cookie 275 | /// Return the cookie that has been set for this http response. 276 | pub fn res_cookie(&self, name: &str) -> Option<&Cookie> { 277 | self.cookies.iter().find(|c| c.name == name) 278 | } 279 | 280 | /// Return the cookie value that has been set for this http response. 281 | pub fn res_cookie_value(&self, name: &str) -> Option { 282 | self.cookies.iter().find(|c| c.name == name).map(|c| c.value.clone()) 283 | } 284 | // endregion: --- Response Cookie 285 | 286 | // region: --- Client Cookies 287 | /// Return the client httpc-test Cookie for a given name. 288 | /// Note: The response.client_cookies are the captured client cookies 289 | /// at the time of the response. 290 | pub fn client_cookie(&self, name: &str) -> Option<&Cookie> { 291 | self.client_cookies.iter().find(|c| c.name == name) 292 | } 293 | 294 | /// Return the client cookie value as String for a given name. 295 | /// Note: The response.client_cookies are the captured client cookies 296 | /// at the time of the response. 297 | pub fn client_cookie_value(&self, name: &str) -> Option { 298 | self.client_cookies.iter().find(|c| c.name == name).map(|c| c.value.clone()) 299 | } 300 | // endregion: --- Client Cookies 301 | 302 | // region: --- Body 303 | pub fn json_body(&self) -> Result { 304 | match &self.body { 305 | Body::Json(val) => Ok(val.clone()), 306 | _ => Err(Error::Static("No json body")), 307 | } 308 | } 309 | 310 | pub fn text_body(&self) -> Result { 311 | match &self.body { 312 | Body::Text(val) => Ok(val.clone()), 313 | _ => Err(Error::Static("No text body")), 314 | } 315 | } 316 | 317 | pub fn json_value(&self, pointer: &str) -> Result 318 | where 319 | T: DeserializeOwned, 320 | { 321 | let Body::Json(body) = &self.body else { 322 | return Err(Error::Static("No json body")); 323 | }; 324 | 325 | let value = body.pointer(pointer).ok_or_else(|| Error::NoJsonValueFound { 326 | json_pointer: pointer.to_string(), 327 | })?; 328 | 329 | Ok(serde_json::from_value::(value.clone())?) 330 | } 331 | 332 | pub fn json_body_as(&self) -> Result 333 | where 334 | T: DeserializeOwned, 335 | { 336 | self.json_body() 337 | .and_then(|val| serde_json::from_value::(val).map_err(Error::SerdeJson)) 338 | } 339 | // endregion: --- Body 340 | } 341 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2023 Jeremy Chone 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. --------------------------------------------------------------------------------