forked from Azure/azure-sdk-for-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Resolves Azure#2030
- Loading branch information
Showing
20 changed files
with
630 additions
and
102 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
//! Credentials for live and recorded tests. | ||
use azure_core::{ | ||
credentials::{AccessToken, Secret, TokenCredential}, | ||
date::OffsetDateTime, | ||
error::ErrorKind, | ||
}; | ||
use azure_identity::{AzurePipelinesCredential, DefaultAzureCredential, TokenCredentialOptions}; | ||
use std::{env, sync::Arc, time::Duration}; | ||
|
||
/// A mock [`TokenCredential`] useful for testing. | ||
#[derive(Clone, Debug, Default)] | ||
pub struct MockCredential; | ||
|
||
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))] | ||
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)] | ||
impl TokenCredential for MockCredential { | ||
async fn get_token(&self, scopes: &[&str]) -> azure_core::Result<AccessToken> { | ||
let token: Secret = format!("TEST TOKEN {}", scopes.join(" ")).into(); | ||
let expires_on = OffsetDateTime::now_utc().saturating_add( | ||
Duration::from_secs(60 * 5).try_into().map_err(|err| { | ||
azure_core::Error::full(ErrorKind::Other, err, "failed to compute expiration") | ||
})?, | ||
); | ||
Ok(AccessToken { token, expires_on }) | ||
} | ||
|
||
async fn clear_cache(&self) -> azure_core::Result<()> { | ||
Ok(()) | ||
} | ||
} | ||
|
||
/// Gets a `TokenCredential` appropriate for the current environment. | ||
/// | ||
/// When running in Azure Pipelines, this will return an [`AzurePipelinesCredential`]; | ||
/// otherwise, it will return a [`DefaultAzureCredential`]. | ||
pub fn from_env( | ||
options: Option<TokenCredentialOptions>, | ||
) -> azure_core::Result<Arc<dyn TokenCredential>> { | ||
// cspell:ignore accesstoken azuresubscription | ||
let tenant_id = env::var("AZURESUBSCRIPTION_TENANT_ID").ok(); | ||
let client_id = env::var("AZURESUBSCRIPTION_CLIENT_ID").ok(); | ||
let connection_id = env::var("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID").ok(); | ||
let access_token = env::var("SYSTEM_ACCESSTOKEN").ok(); | ||
|
||
if let (Some(tenant_id), Some(client_id), Some(connection_id), Some(access_token)) = | ||
(tenant_id, client_id, connection_id, access_token) | ||
{ | ||
if !tenant_id.is_empty() | ||
&& !client_id.is_empty() | ||
&& !connection_id.is_empty() | ||
&& !access_token.is_empty() | ||
{ | ||
return Ok(AzurePipelinesCredential::new( | ||
tenant_id, | ||
client_id, | ||
&connection_id, | ||
access_token, | ||
options.map(Into::into), | ||
)? as Arc<dyn TokenCredential>); | ||
} | ||
} | ||
|
||
Ok( | ||
DefaultAzureCredential::with_options(options.unwrap_or_default())? | ||
as Arc<dyn TokenCredential>, | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
use async_trait::async_trait; | ||
use azure_core::{HttpClient, Request, Response, Result}; | ||
use futures::lock::Mutex; | ||
use std::{fmt, future::Future, pin::Pin}; | ||
|
||
pub struct MockHttpClient<C>(Mutex<C>); | ||
|
||
impl<C> MockHttpClient<C> | ||
where | ||
C: FnMut(&Request) -> Pin<Box<dyn Future<Output = Result<Response>> + Send + Sync + '_>> | ||
+ Send | ||
+ Sync, | ||
{ | ||
pub fn new(client: C) -> Self { | ||
Self(Mutex::new(client)) | ||
} | ||
} | ||
|
||
impl<C> fmt::Debug for MockHttpClient<C> { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
f.write_str(stringify!("MockHttpClient")) | ||
} | ||
} | ||
|
||
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] | ||
#[cfg_attr(not(target_arch = "wasm32"), async_trait)] | ||
impl<C> HttpClient for MockHttpClient<C> | ||
where | ||
C: FnMut(&Request) -> Pin<Box<dyn Future<Output = Result<Response>> + Send + Sync + '_>> | ||
+ Send | ||
+ Sync, | ||
{ | ||
async fn execute_request(&self, req: &Request) -> Result<Response> { | ||
let mut client = self.0.lock().await; | ||
(client)(req).await | ||
} | ||
} | ||
|
||
#[tokio::test] | ||
async fn test_mock_http_client() { | ||
use azure_core::{ | ||
headers::{HeaderName, Headers}, | ||
Method, StatusCode, | ||
}; | ||
use std::sync::{Arc, Mutex}; | ||
|
||
const COUNT_HEADER: HeaderName = HeaderName::from_static("x-count"); | ||
|
||
let count = Arc::new(Mutex::new(0)); | ||
let mock_client = Arc::new(MockHttpClient::new(|req| { | ||
let count = count.clone(); | ||
Box::pin(async move { | ||
assert_eq!(req.url().host_str(), Some("localhost")); | ||
|
||
if req.headers().get_optional_str(&COUNT_HEADER).is_some() { | ||
let mut count = count.lock().unwrap(); | ||
*count += 1; | ||
} | ||
|
||
Ok(Response::from_bytes(StatusCode::Ok, Headers::new(), vec![])) | ||
}) | ||
})) as Arc<dyn HttpClient>; | ||
|
||
let req = Request::new("https://localhost".parse().unwrap(), Method::Get); | ||
mock_client.execute_request(&req).await.unwrap(); | ||
|
||
let mut req = Request::new("https://localhost".parse().unwrap(), Method::Get); | ||
req.insert_header(COUNT_HEADER, "true"); | ||
mock_client.execute_request(&req).await.unwrap(); | ||
|
||
assert_eq!(*count.lock().unwrap(), 1); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
//! HTTP testing utilities. | ||
mod clients; | ||
|
||
pub use clients::*; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.