Skip to content

Commit

Permalink
Refactor tests
Browse files Browse the repository at this point in the history
Signed-off-by: Patrik Stas <patrik.stas@absa.africa>
  • Loading branch information
Patrik-Stas committed Jul 19, 2022
1 parent 88bf722 commit ee24632
Show file tree
Hide file tree
Showing 15 changed files with 145 additions and 207 deletions.
1 change: 0 additions & 1 deletion agency_client/src/agency_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@ impl AgencyClient {
Ok(())
}

// TODO: This should be implemented in the module doing the tests
pub fn set_testing_defaults_agency(&mut self) {
trace!("set_testing_defaults_agency >>>");

Expand Down
6 changes: 3 additions & 3 deletions agency_client/src/testing/mocking.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::sync::Mutex;

use crate::error::AgencyClientResult;
use crate::testing::test_settings::{disable_agency_test_mode, enable_agency_test_mode, get_config_enable_test_mode};
use crate::testing::test_settings::{disable_agency_test_mode, enable_agency_test_mode, get_config_agency_test_mode};

lazy_static! {
static ref AGENCY_MOCK: Mutex<AgencyMock> = Mutex::new(AgencyMock::default());
Expand Down Expand Up @@ -102,14 +102,14 @@ impl AgencyMockDecrypted {
}

pub fn agency_mocks_enabled() -> bool {
match get_config_enable_test_mode().ok() {
match get_config_agency_test_mode().ok() {
None => false,
Some(value) => value == "true" || value == "agency"
}
}

pub fn agency_decrypted_mocks_enabled() -> bool {
match get_config_enable_test_mode().ok() {
match get_config_agency_test_mode().ok() {
None => false,
Some(value) => value == "true"
}
Expand Down
12 changes: 6 additions & 6 deletions agency_client/src/testing/test_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,26 @@ use url::Url;
use crate::error::{AgencyClientError, AgencyClientErrorKind, AgencyClientResult};
use crate::utils::{error_utils, validation};

const CONFIG_ENABLE_TEST_MODE: &str = "enable_test_mode";
const CONFIG_AGENCY_TEST_MODE: &str = "enable_test_mode";

static VALID_AGENCY_CONFIG_KEYS: &[&str] = &[
CONFIG_ENABLE_TEST_MODE,
CONFIG_AGENCY_TEST_MODE,
];

lazy_static! {
static ref AGENCY_SETTINGS: RwLock<HashMap<String, String>> = RwLock::new(HashMap::new());
}

pub fn get_config_enable_test_mode() -> AgencyClientResult<String> {
_get_config_value(CONFIG_ENABLE_TEST_MODE)
pub fn get_config_agency_test_mode() -> AgencyClientResult<String> {
_get_config_value(CONFIG_AGENCY_TEST_MODE)
}

pub fn enable_agency_test_mode() {
_set_test_config(CONFIG_ENABLE_TEST_MODE, "true");
_set_test_config(CONFIG_AGENCY_TEST_MODE, "true");
}

pub fn disable_agency_test_mode() {
_set_test_config(CONFIG_ENABLE_TEST_MODE, "false");
_set_test_config(CONFIG_AGENCY_TEST_MODE, "false");
}

fn _set_test_config(key: &str, value: &str) {
Expand Down
2 changes: 1 addition & 1 deletion aries_vcx/src/handlers/proof_presentation/prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ mod tests {
#[cfg(feature = "general_test")]
#[tokio::test]
async fn test_retrieve_credentials_fails_with_no_proof_req() {
let _setup = SetupLibraryWallet::init();
let _setup = SetupLibraryWallet::init().await;

let proof_req = PresentationRequest::create();
let proof = Prover::create_from_request("1", proof_req).unwrap();
Expand Down
9 changes: 2 additions & 7 deletions aries_vcx/src/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::libindy::utils::pool::{create_pool_ledger_config, open_pool_ledger, s
use crate::libindy::utils::wallet::{build_wallet_config, build_wallet_credentials, IssuerConfig, set_wallet_handle, WalletConfig};
use crate::settings;
use agency_client::configuration::AgencyClientConfig;
use crate::settings::enable_indy_mocks;

#[derive(Clone, Debug, Default, Builder, Serialize, Deserialize)]
#[builder(setter(into, strip_option), default)]
Expand All @@ -16,12 +17,6 @@ pub struct PoolConfig {
pub pool_config: Option<String>,
}

pub fn enable_vcx_mocks() -> VcxResult<()> {
info!("enable_vcx_mocks >>>");
settings::set_config_value(settings::CONFIG_ENABLE_TEST_MODE, "true");
Ok(())
}

pub fn enable_agency_mocks() -> VcxResult<()> {
info!("enable_agency_mocks >>>");
settings::get_agency_client_mut()?.enable_test_mode();
Expand All @@ -35,7 +30,7 @@ pub fn create_agency_client_for_main_wallet(config: &AgencyClientConfig) -> VcxR
}

pub fn init_issuer_config(config: &IssuerConfig) -> VcxResult<()> {
settings::set_config_value(settings::CONFIG_INSTITUTION_DID, &config.institution_did);
settings::set_config_value(settings::CONFIG_INSTITUTION_DID, &config.institution_did)?;
Ok(())
}

Expand Down
8 changes: 4 additions & 4 deletions aries_vcx/src/libindy/proofs/prover/prover_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,8 +270,7 @@ pub mod tests {
#[tokio::test]
#[cfg(feature = "general_test")]
async fn test_find_credential_def_fails() {
let _setup = SetupLibraryWallet::init();

let _setup = SetupLibraryWallet::init().await;
let credential_ids = vec![CredInfoProver {
requested_attr: "1".to_string(),
referent: "2".to_string(),
Expand All @@ -283,13 +282,14 @@ pub mod tests {
tails_file: None,
timestamp: None,
}];
assert_eq!(build_cred_defs_json_prover(&credential_ids).await.unwrap_err().kind(), VcxErrorKind::InvalidProofCredentialData);
let err_kind = build_cred_defs_json_prover(&credential_ids).await.unwrap_err().kind();
assert_eq!(err_kind, VcxErrorKind::InvalidProofCredentialData);
}

#[tokio::test]
#[cfg(feature = "general_test")]
async fn test_find_schemas_fails() {
let _setup = SetupLibraryWallet::init();
let _setup = SetupLibraryWallet::init().await;

let credential_ids = vec![CredInfoProver {
requested_attr: "1".to_string(),
Expand Down
31 changes: 25 additions & 6 deletions aries_vcx/src/libindy/utils/anoncreds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,7 @@ pub async fn build_cred_def_request(issuer_did: &str, cred_def_json: &str) -> Vc
pub async fn publish_cred_def(issuer_did: &str, cred_def_json: &str) -> VcxResult<()> {
trace!("publish_cred_def >>> issuer_did: {}, cred_def_json: {}", issuer_did, cred_def_json);
if settings::indy_mocks_enabled() {
warn!("publish_cred_def >>> mocked success");
return Ok(());
}
let cred_def_req = build_cred_def_request(issuer_did, &cred_def_json).await?;
Expand All @@ -496,7 +497,10 @@ pub async fn publish_cred_def(issuer_did: &str, cred_def_json: &str) -> VcxResul
}

pub async fn get_cred_def_json(cred_def_id: &str) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() { return Ok((CRED_DEF_ID.to_string(), CRED_DEF_JSON.to_string())); }
if settings::indy_mocks_enabled() {
warn!("get_cred_def_json >>> returning mocked value");
return Ok((CRED_DEF_ID.to_string(), CRED_DEF_JSON.to_string()));
}

let cred_def_json = libindy_get_cred_def(cred_def_id).await?;

Expand All @@ -506,7 +510,10 @@ pub async fn get_cred_def_json(cred_def_id: &str) -> VcxResult<(String, String)>
pub async fn generate_rev_reg(issuer_did: &str, cred_def_id: &str, tails_dir: &str, max_creds: u32, tag: &str)
-> VcxResult<(String, RevocationRegistryDefinition, String)> {
trace!("generate_rev_reg >>> issuer_did: {}, cred_def_id: {}, tails_file: {}, max_creds: {}, tag: {}", issuer_did, cred_def_id, tails_dir, max_creds, tag);
if settings::indy_mocks_enabled() { return Ok((REV_REG_ID.to_string(), RevocationRegistryDefinition::default(), "".to_string())); }
if settings::indy_mocks_enabled() {
warn!("generate_rev_reg >>> returning mocked value");
return Ok((REV_REG_ID.to_string(), RevocationRegistryDefinition::default(), "".to_string()));
}

let (rev_reg_id, rev_reg_def_json, rev_reg_entry_json) =
libindy_create_and_store_revoc_reg(issuer_did,
Expand All @@ -522,7 +529,10 @@ pub async fn generate_rev_reg(issuer_did: &str, cred_def_id: &str, tails_dir: &s
}

pub async fn build_rev_reg_request(issuer_did: &str, rev_reg_def_json: &str) -> VcxResult<String> {
if settings::indy_mocks_enabled() { return Ok("".to_string()); }
if settings::indy_mocks_enabled() {
warn!("build_rev_reg_request >>> returning mocked value");
return Ok("".to_string());
}

let rev_reg_def_req = libindy_build_revoc_reg_def_request(issuer_did, &rev_reg_def_json).await?;
let rev_reg_def_req = append_txn_author_agreement_to_request(&rev_reg_def_req).await?;
Expand All @@ -531,7 +541,10 @@ pub async fn build_rev_reg_request(issuer_did: &str, rev_reg_def_json: &str) ->

pub async fn publish_rev_reg_def(issuer_did: &str, rev_reg_def: &RevocationRegistryDefinition) -> VcxResult<()> {
trace!("publish_rev_reg_def >>> issuer_did: {}, rev_reg_def: ...", issuer_did);
if settings::indy_mocks_enabled() { return Ok(()); }
if settings::indy_mocks_enabled() {
warn!("publish_rev_reg_def >>> mocked success");
return Ok(());
}

let rev_reg_def_json = serde_json::to_string(&rev_reg_def)
.map_err(|err| VcxError::from_msg(VcxErrorKind::SerializationError, format!("Failed to serialize rev_reg_def: {:?}, error: {:?}", rev_reg_def, err)))?;
Expand All @@ -541,7 +554,10 @@ pub async fn publish_rev_reg_def(issuer_did: &str, rev_reg_def: &RevocationRegis
}

pub async fn get_rev_reg_def_json(rev_reg_id: &str) -> VcxResult<(String, String)> {
if settings::indy_mocks_enabled() { return Ok((REV_REG_ID.to_string(), rev_def_json())); }
if settings::indy_mocks_enabled() {
warn!("get_rev_reg_def_json >>> returning mocked value");
return Ok((REV_REG_ID.to_string(), rev_def_json()));
}

let submitter_did = crate::utils::random::generate_random_did();

Expand Down Expand Up @@ -569,7 +585,10 @@ pub async fn publish_rev_reg_delta(issuer_did: &str, rev_reg_id: &str, rev_reg_e
pub async fn get_rev_reg_delta_json(rev_reg_id: &str, from: Option<u64>, to: Option<u64>)
-> VcxResult<(String, String, u64)> {
trace!("get_rev_reg_delta_json >>> rev_reg_id: {}, from: {:?}, to: {:?}", rev_reg_id, from, to);
if settings::indy_mocks_enabled() { return Ok((REV_REG_ID.to_string(), REV_REG_DELTA_JSON.to_string(), 1)); }
if settings::indy_mocks_enabled() {
warn!("get_rev_reg_delta_json >>> returning mocked value");
return Ok((REV_REG_ID.to_string(), REV_REG_DELTA_JSON.to_string(), 1));
}

let submitter_did = crate::utils::random::generate_random_did();

Expand Down
21 changes: 0 additions & 21 deletions aries_vcx/src/libindy/utils/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,13 +495,6 @@ mod test {

use super::*;

pub async fn add_service_old(did: &str, service: &FullService) -> VcxResult<String> {
let ser_service = serde_json::to_string(service)
.map_err(|err| VcxError::from_msg(VcxErrorKind::SerializationError, format!("Failed to serialize service before writing to ledger: {:?}", err)))?;
let attrib_json = json!({ "service": ser_service }).to_string();
add_attr(did, &attrib_json).await
}

#[test]
#[cfg(feature = "general_test")]
fn test_verify_transaction_can_be_endorsed() {
Expand Down Expand Up @@ -550,20 +543,6 @@ mod test {

assert_eq!(expect_service, service)
}

#[cfg(feature = "pool_tests")]
#[tokio::test]
async fn test_add_get_service_old() {
let _setup = SetupWithWalletAndAgency::init().await;

let did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap();
let expect_service = FullService::default();
add_service_old(&did, &expect_service).await.unwrap();
thread::sleep(Duration::from_millis(50));
let service = get_service(&Did::new(&did).unwrap()).await.unwrap();

assert_eq!(expect_service, service)
}
}


Expand Down
1 change: 0 additions & 1 deletion aries_vcx/src/libindy/utils/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ pub fn get_main_wallet_handle() -> WalletHandle { unsafe { WALLET_HANDLE } }

pub fn reset_main_wallet_handle() -> VcxResult<()> {
set_wallet_handle(INVALID_WALLET_HANDLE);
settings::get_agency_client_mut()?.reset_wallet_handle();
Ok(())
}

Expand Down
32 changes: 25 additions & 7 deletions aries_vcx/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ pub fn get_agency_client() -> VcxResult<AgencyClient> {
pub fn set_testing_defaults() -> u32 {
trace!("set_testing_defaults >>>");

// if this fails the program should exit
let mut settings = SETTINGS.write().unwrap();

settings.insert(CONFIG_POOL_NAME.to_string(), DEFAULT_POOL_NAME.to_string());
Expand All @@ -95,12 +94,25 @@ pub fn set_testing_defaults() -> u32 {
error::SUCCESS.code_num
}

pub fn enable_indy_mocks() -> VcxResult<()> {
warn!("enable_indy_mocks >>>");
set_config_value(CONFIG_ENABLE_TEST_MODE, "true")
}

pub fn disable_indy_mocks() -> VcxResult<()> {
warn!("disable_indy_mocks >>>");
set_config_value(CONFIG_ENABLE_TEST_MODE, "false")
}

pub fn indy_mocks_enabled() -> bool {
let config = SETTINGS.read().unwrap();

match config.get(CONFIG_ENABLE_TEST_MODE) {
None => false,
Some(value) => value == "true" || value == "indy"
Some(value) => {
warn!("indy_mocks_enabled >>> {}", value);
value == "true" || value == "indy"
}
}
}

Expand All @@ -115,11 +127,13 @@ pub fn get_config_value(key: &str) -> VcxResult<String> {
.ok_or(VcxError::from_msg(VcxErrorKind::InvalidConfiguration, format!("Cannot read \"{}\" from settings", key)))
}

pub fn set_config_value(key: &str, value: &str) {
pub fn set_config_value(key: &str, value: &str) -> VcxResult<()> {
trace!("set_config_value >>> key: {}, value: {}", key, value);
SETTINGS
.write().unwrap()
.write()
.or(Err(VcxError::from_msg(VcxErrorKind::UnknownError, "Cannot write settings")))?
.insert(key.to_string(), value.to_string());
Ok(())
}

pub fn get_protocol_version() -> usize {
Expand Down Expand Up @@ -163,11 +177,15 @@ pub enum Actors {
Receiver,
}

pub fn clear_config() {
trace!("clear_config >>>");
pub fn reset_settings() {
trace!("reset_settings >>>");
let mut config = SETTINGS.write().unwrap();
let mut agency_client = AGENCY_CLIENT.write().unwrap();
config.clear();
}

pub fn reset_agency_client() {
trace!("reset_agency_client >>>");
let mut agency_client = AGENCY_CLIENT.write().unwrap();
*agency_client = AgencyClient::default();
}

Expand Down

0 comments on commit ee24632

Please sign in to comment.