Skip to content

Commit d1b1d7f

Browse files
authored
Use MockCredential for recorded test playback (Azure#2079)
Fixes Azure#2063
1 parent 00d0106 commit d1b1d7f

File tree

3 files changed

+40
-4
lines changed

3 files changed

+40
-4
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
use azure_core::{
5+
credentials::{AccessToken, Secret, TokenCredential},
6+
date::OffsetDateTime,
7+
error::ErrorKind,
8+
};
9+
use std::time::Duration;
10+
11+
/// A mock [`TokenCredential`] useful for testing.
12+
#[derive(Clone, Debug, Default)]
13+
pub struct MockCredential;
14+
15+
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
16+
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
17+
impl TokenCredential for MockCredential {
18+
async fn get_token(&self, scopes: &[&str]) -> azure_core::Result<AccessToken> {
19+
let token: Secret = format!("TEST TOKEN {}", scopes.join(" ")).into();
20+
let expires_on = OffsetDateTime::now_utc().saturating_add(
21+
Duration::from_secs(60 * 5).try_into().map_err(|err| {
22+
azure_core::Error::full(ErrorKind::Other, err, "failed to compute expiration")
23+
})?,
24+
);
25+
Ok(AccessToken { token, expires_on })
26+
}
27+
28+
async fn clear_cache(&self) -> azure_core::Result<()> {
29+
Ok(())
30+
}
31+
}

sdk/core/azure_core_test/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@
33

44
#![doc = include_str!("../README.md")]
55

6+
mod credential;
67
pub mod proxy;
78
pub mod recorded;
89
mod recording;
910

1011
use azure_core::Error;
1112
pub use azure_core::{error::ErrorKind, test::TestMode};
13+
pub use credential::*;
1214
pub use proxy::{matchers::*, sanitizers::*};
1315
pub use recording::*;
1416
use std::path::{Path, PathBuf};

sdk/core/azure_core_test/src/recording.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use crate::{
1313
policy::RecordingPolicy,
1414
Proxy, RecordingId,
1515
},
16-
Matcher, Sanitizer,
16+
Matcher, MockCredential, Sanitizer,
1717
};
1818
use azure_core::{
1919
credentials::TokenCredential,
@@ -73,9 +73,12 @@ impl Recording {
7373
///
7474
/// Panics if the [`TokenCredential`] could not be created.
7575
pub fn credential(&self) -> Arc<dyn TokenCredential> {
76-
match DefaultAzureCredential::new() {
77-
Ok(credential) => credential as Arc<dyn TokenCredential>,
78-
Err(err) => panic!("{err}"),
76+
match self.test_mode {
77+
TestMode::Playback => Arc::new(MockCredential) as Arc<dyn TokenCredential>,
78+
_ => DefaultAzureCredential::new().map_or_else(
79+
|err| panic!("failed to create DefaultAzureCredential: {err}"),
80+
|cred| cred as Arc<dyn TokenCredential>,
81+
),
7982
}
8083
}
8184

0 commit comments

Comments
 (0)