|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +use async_trait::async_trait; |
| 5 | +use azure_core::{HttpClient, Request, Response, Result}; |
| 6 | +use futures::{future::BoxFuture, lock::Mutex}; |
| 7 | +use std::fmt; |
| 8 | + |
| 9 | +/// An [`HttpClient`] from which you can assert [`Request`]s and return mock [`Response`]s. |
| 10 | +/// |
| 11 | +/// # Examples |
| 12 | +/// |
| 13 | +/// ``` |
| 14 | +/// use azure_core::{ |
| 15 | +/// Bytes, ClientOptions, |
| 16 | +/// headers::Headers, |
| 17 | +/// Response, StatusCode, TransportOptions, |
| 18 | +/// }; |
| 19 | +/// use azure_core_test::http::MockHttpClient; |
| 20 | +/// use azure_identity::DefaultAzureCredential; |
| 21 | +/// use azure_security_keyvault_secrets::{SecretClient, SecretClientOptions}; |
| 22 | +/// use futures::FutureExt as _; |
| 23 | +/// use std::sync::Arc; |
| 24 | +/// |
| 25 | +/// # #[tokio::main] |
| 26 | +/// # async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 27 | +/// let mock_client = Arc::new(MockHttpClient::new(|req| async { |
| 28 | +/// assert_eq!(req.url().host_str(), Some("my-vault.vault.azure.net")); |
| 29 | +/// Ok(Response::from_bytes( |
| 30 | +/// StatusCode::Ok, |
| 31 | +/// Headers::new(), |
| 32 | +/// Bytes::from_static(br#"{"value":"secret"}"#), |
| 33 | +/// )) |
| 34 | +/// }.boxed())); |
| 35 | +/// let credential = DefaultAzureCredential::new()?; |
| 36 | +/// let options = SecretClientOptions { |
| 37 | +/// client_options: ClientOptions { |
| 38 | +/// transport: Some(TransportOptions::new(mock_client.clone())), |
| 39 | +/// ..Default::default() |
| 40 | +/// }, |
| 41 | +/// ..Default::default() |
| 42 | +/// }; |
| 43 | +/// let client = SecretClient::new( |
| 44 | +/// "https://my-vault.vault.azure.net", |
| 45 | +/// credential.clone(), |
| 46 | +/// Some(options), |
| 47 | +/// ); |
| 48 | +/// # Ok(()) |
| 49 | +/// # } |
| 50 | +/// ``` |
| 51 | +pub struct MockHttpClient<C>(Mutex<C>); |
| 52 | + |
| 53 | +impl<C> MockHttpClient<C> |
| 54 | +where |
| 55 | + C: FnMut(&Request) -> BoxFuture<'_, Result<Response>> + Send + Sync, |
| 56 | +{ |
| 57 | + /// Creates a new `MockHttpClient` using a capture. |
| 58 | + /// |
| 59 | + /// The capture takes a `&Request` and returns a `BoxedFuture<Output = azure_core::Result<Response>>`. |
| 60 | + /// See the example on [`MockHttpClient`]. |
| 61 | + pub fn new(client: C) -> Self { |
| 62 | + Self(Mutex::new(client)) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +impl<C> fmt::Debug for MockHttpClient<C> { |
| 67 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 68 | + f.write_str(stringify!("MockHttpClient")) |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] |
| 73 | +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] |
| 74 | +impl<C> HttpClient for MockHttpClient<C> |
| 75 | +where |
| 76 | + C: FnMut(&Request) -> BoxFuture<'_, Result<Response>> + Send + Sync, |
| 77 | +{ |
| 78 | + async fn execute_request(&self, req: &Request) -> Result<Response> { |
| 79 | + let mut client = self.0.lock().await; |
| 80 | + (client)(req).await |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +#[cfg(test)] |
| 85 | +mod tests { |
| 86 | + use super::*; |
| 87 | + use futures::FutureExt as _; |
| 88 | + |
| 89 | + #[tokio::test] |
| 90 | + async fn mock_http_client() { |
| 91 | + use azure_core::{ |
| 92 | + headers::{HeaderName, Headers}, |
| 93 | + Method, StatusCode, |
| 94 | + }; |
| 95 | + use std::sync::{Arc, Mutex}; |
| 96 | + |
| 97 | + const COUNT_HEADER: HeaderName = HeaderName::from_static("x-count"); |
| 98 | + |
| 99 | + let count = Arc::new(Mutex::new(0)); |
| 100 | + let mock_client = Arc::new(MockHttpClient::new(|req| { |
| 101 | + let count = count.clone(); |
| 102 | + async move { |
| 103 | + assert_eq!(req.url().host_str(), Some("localhost")); |
| 104 | + |
| 105 | + if req.headers().get_optional_str(&COUNT_HEADER).is_some() { |
| 106 | + let mut count = count.lock().unwrap(); |
| 107 | + *count += 1; |
| 108 | + } |
| 109 | + |
| 110 | + Ok(Response::from_bytes(StatusCode::Ok, Headers::new(), vec![])) |
| 111 | + } |
| 112 | + .boxed() |
| 113 | + })) as Arc<dyn HttpClient>; |
| 114 | + |
| 115 | + let req = Request::new("https://localhost".parse().unwrap(), Method::Get); |
| 116 | + mock_client.execute_request(&req).await.unwrap(); |
| 117 | + |
| 118 | + let mut req = Request::new("https://localhost".parse().unwrap(), Method::Get); |
| 119 | + req.insert_header(COUNT_HEADER, "true"); |
| 120 | + mock_client.execute_request(&req).await.unwrap(); |
| 121 | + |
| 122 | + assert_eq!(*count.lock().unwrap(), 1); |
| 123 | + } |
| 124 | +} |
0 commit comments