From af69d5e9267164d6382244c6ebff4707c90a49b6 Mon Sep 17 00:00:00 2001 From: imstar15 Date: Thu, 27 Jul 2023 16:14:29 +0800 Subject: [PATCH] Fix tests --- pallets/automation-time/Cargo.toml | 1 + pallets/automation-time/src/lib.rs | 43 +----- pallets/automation-time/src/mock.rs | 8 +- pallets/automation-time/src/tests.rs | 222 +++++++++++---------------- 4 files changed, 99 insertions(+), 175 deletions(-) diff --git a/pallets/automation-time/Cargo.toml b/pallets/automation-time/Cargo.toml index 6de63848..f2a3ab09 100644 --- a/pallets/automation-time/Cargo.toml +++ b/pallets/automation-time/Cargo.toml @@ -63,6 +63,7 @@ pallet-xcmp-handler = { path = "../xcmp-handler", default-features = false } primitives = { path = "../../primitives", default-features = false } [dev-dependencies] +env_logger = "0.9" rand = { version = "0.7.3" } serde = { version = "1.0.144" } sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.38" } diff --git a/pallets/automation-time/src/lib.rs b/pallets/automation-time/src/lib.rs index cc25251c..aa1598b0 100644 --- a/pallets/automation-time/src/lib.rs +++ b/pallets/automation-time/src/lib.rs @@ -82,14 +82,6 @@ use sp_std::{boxed::Box, collections::btree_map::BTreeMap, vec, vec::Vec}; pub use weights::WeightInfo; use xcm::{latest::prelude::*, VersionedMultiLocation}; -#[macro_export] -macro_rules! ERROR_MESSAGE_DELEGATION_FORMAT { - () => { - "delegator: {:?}, collator: {:?}" - }; -} -pub const ERROR_MESSAGE_BALANCE_LOW: &str = "Balance less than minimum"; - #[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo)] pub struct DispatchErrorDataMap(BTreeMap); impl sp_runtime::traits::Printable for DispatchErrorDataMap { @@ -101,7 +93,7 @@ impl sp_runtime::traits::Printable for DispatchErrorDataMap { } pub type DispatchErrorWithDataMap = DispatchErrorWithData; -const AUTO_COMPOUND_DELEGATION_CANCEL_UPON_ERRORS: [&str; 1] = ["DelegationDNE"]; +const AUTO_COMPOUND_DELEGATION_CANCEL_UPON_ERRORS: [&str; 2] = ["DelegatorDNE", "DelegationDNE"]; #[frame_support::pallet] pub mod pallet { @@ -1520,39 +1512,6 @@ pub mod pallet { }; }, } - - // if let Some(err) = dispatch_error if task.cancel_upon_errors.contains(&err.as_str()) { - // Self::deposit_event(Event::::TaskNotRescheduled { - // who: task.owner_id.clone(), - // task_id, - // error: err, - // }); - // AccountTasks::::remove(task.owner_id.clone(), task_id); - // } else { - // let owner_id = task.owner_id.clone(); - // let action = task.action.clone(); - // match Self::reschedule_existing_task(task_id, &mut task) { - // Ok(_) => { - // let schedule_as = match action { - // Action::XCMP { schedule_as, .. } => schedule_as, - // _ => None, - // }; - // Self::deposit_event(Event::::TaskRescheduled { - // who: owner_id, - // task_id, - // schedule_as, - // }); - // }, - // Err(err) => { - // Self::deposit_event(Event::::TaskFailedToReschedule { - // who: task.owner_id.clone(), - // task_id, - // error: err, - // }); - // AccountTasks::::remove(task.owner_id.clone(), task_id); - // }, - // }; - // } } fn reschedule_existing_task(task_id: TaskId, task: &mut TaskOf) -> DispatchResult { diff --git a/pallets/automation-time/src/mock.rs b/pallets/automation-time/src/mock.rs index 686de279..190e35ec 100644 --- a/pallets/automation-time/src/mock.rs +++ b/pallets/automation-time/src/mock.rs @@ -264,12 +264,14 @@ impl< candidate: &T::AccountId, account_minimum: BalanceOf, ) -> Result, DispatchErrorWithPostInfo> { - log::error!("delegator_bond_till_minimum AAAAAAA"); + if *delegator != T::AccountId::decode(&mut DELEGATOR_ACCOUNT.as_ref()).unwrap() { + return Err(DispatchErrorWithPostInfo::from(>::DelegatorDNE)); + } if *candidate != T::AccountId::decode(&mut COLLATOR_ACCOUNT.as_ref()).unwrap() { - log::error!("delegator_bond_till_minimum BBBB"); return Err(DispatchErrorWithPostInfo::from(>::DelegationDNE)); } - log::error!("delegator_bond_till_minimum CCCCCC"); + log::error!("delegator_bond_till_minimum CCCCCC, C::free_balance(&delegator): {:?}", C::free_balance(&delegator)); + log::error!("delegator_bond_till_minimum CCCCCC, account_minimum: {:?}", account_minimum); let delegation = C::free_balance(&delegator) .checked_sub(&account_minimum) diff --git a/pallets/automation-time/src/tests.rs b/pallets/automation-time/src/tests.rs index 5c0797c1..c9a988a7 100644 --- a/pallets/automation-time/src/tests.rs +++ b/pallets/automation-time/src/tests.rs @@ -18,7 +18,7 @@ use crate::{ mock::*, AccountTasks, Action, ActionOf, AssetPayment, Config, Error, InstructionSequence, LastTimeSlot, MissedTaskV2Of, ScheduleParam, ScheduledTasksOf, TaskHashInput, TaskOf, - TaskQueueV2, WeightInfo, ERROR_MESSAGE_BALANCE_LOW, ERROR_MESSAGE_DELEGATION_FORMAT, + TaskQueueV2, WeightInfo, DispatchErrorWithDataMap, }; use codec::Encode; use frame_support::{ @@ -28,7 +28,6 @@ use frame_support::{ weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}, }; use frame_system::{self, RawOrigin}; -use hex; use rand::Rng; use sp_core::Get; use sp_runtime::{ @@ -36,8 +35,8 @@ use sp_runtime::{ AccountId32, }; use xcm::latest::{prelude::*, Junction::Parachain, MultiLocation}; -use sp_runtime::DispatchError::Module; -use sp_runtime::ModuleError; +// use sp_runtime::DispatchError::Module; +// use sp_runtime::ModuleError; use frame_support::pallet_prelude::DispatchError; use sp_std::collections::btree_map::BTreeMap; @@ -378,8 +377,6 @@ fn will_emit_task_completed_event_when_task_completed() { new_test_ext(START_BLOCK_TIME).execute_with(|| { let frequency = 3_600; let account_id = AccountId32::new(ALICE); - let provided_id = vec![1, 2]; - let task_id = AutomationTime::generate_task_id(account_id.clone(), provided_id.clone()); fund_account(&account_id, 900_000_000, 2, Some(0)); @@ -487,11 +484,9 @@ fn will_emit_task_completed_event_when_task_failed() { new_test_ext(START_BLOCK_TIME).execute_with(|| { let frequency = 3_600; let account_id = AccountId32::new(ALICE); - let provided_id = vec![1, 2]; - let task_id = AutomationTime::generate_task_id(account_id.clone(), provided_id.clone()); fund_account(&account_id, 900_000_000, 2, Some(0)); - let current_funds = Balances::free_balance(AccountId32::new(ALICE)); + let current_funds = Balances::free_balance(account_id.clone()); // Because the execution of the transfer task twice requires a total amount is larger than current balance, the second task will fail. let call: ::RuntimeCall = pallet_balances::Call::transfer { @@ -531,14 +526,8 @@ fn will_emit_task_completed_event_when_task_failed() { AutomationTime::trigger_tasks(Weight::from_ref_time(900_000_000)); let my_events = events(); - // The DynamicDispatchResult event with error should be emitted when task failed. - // let event = my_events.clone().into_iter().find(|e| { - // matches!(e, RuntimeEvent::AutomationTime(crate::Event::DynamicDispatchResult { result, .. }) if result.is_err()) - // }) - // .expect("The DynamicDispatchResult event with error should be emitted when task failed"); - // When a task fails, the TaskCompleted event will still be emitted. - let event = my_events + my_events .into_iter() .find(|e| matches!(e, RuntimeEvent::AutomationTime(crate::Event::TaskCompleted { .. }))) .expect("When a task fails, the TaskCompleted event will still be emitted"); @@ -1626,7 +1615,6 @@ mod extrinsics { mod run_dynamic_dispatch_action { use super::*; - use sp_runtime::DispatchError; #[test] fn cannot_decode() { @@ -2423,17 +2411,18 @@ fn trigger_tasks_completes_some_xcmp_tasks() { #[test] fn trigger_tasks_completes_auto_compound_delegated_stake_task() { new_test_ext(START_BLOCK_TIME).execute_with(|| { - get_funds(AccountId32::new(ALICE)); - let before_balance = Balances::free_balance(AccountId32::new(ALICE)); + let delegator = AccountId32::new(DELEGATOR_ACCOUNT); + get_funds(delegator.clone()); + let before_balance = Balances::free_balance(delegator.clone()); let account_minimum = before_balance / 2; - let task_id = add_recurring_task_to_task_queue( - ALICE, + add_recurring_task_to_task_queue( + DELEGATOR_ACCOUNT, vec![1], SCHEDULED_TIME, 3600, Action::AutoCompoundDelegatedStake { - delegator: AccountId32::new(ALICE), + delegator: delegator.clone(), collator: AccountId32::new(COLLATOR_ACCOUNT), account_minimum, }, @@ -2444,29 +2433,9 @@ fn trigger_tasks_completes_auto_compound_delegated_stake_task() { AutomationTime::trigger_tasks(Weight::from_ref_time(120_000)); - let new_balance = Balances::free_balance(AccountId32::new(ALICE)); + let new_balance = Balances::free_balance(delegator.clone()); assert!(new_balance < before_balance); assert_eq!(new_balance, account_minimum); - // let delegation_event = events() - // .into_iter() - // .find(|e| match e { - // RuntimeEvent::AutomationTime( - // crate::Event::AutoCompoundDelegatorStakeSucceeded { .. }, - // ) => true, - // _ => false, - // }) - // .expect("AutoCompound success event should have been emitted"); - let execution_weight = MockWeight::::run_auto_compound_delegated_stake_task(); - let fee = ExecutionWeightFee::get().saturating_mul(execution_weight.ref_time().into()); - // assert_eq!( - // delegation_event, - // RuntimeEvent::AutomationTime(crate::Event::AutoCompoundDelegatorStakeSucceeded { - // task_id, - // amount: before_balance - // .checked_sub(account_minimum.saturating_add(fee)) - // .expect("Event should not exist if value is neg"), - // }) - // ); }) } @@ -2475,25 +2444,26 @@ fn trigger_tasks_completes_auto_compound_delegated_stake_task() { // 1. User's wallet balance >= minimum balance + execution fee // 2. User has a delegation with the specificed collator // Expected result: -// 1. Current execution will run and emit AutoCompoundDelegatorStakeSucceeded event +// 1. Current execution will run // 2. Next execution will be scheduled -// 3. The task will re-run in the next execution time and emit AutoCompoundDelegatorStakeSucceeded event again +// 3. The task will re-run in the next execution time #[test] fn auto_compound_delegated_stake_enough_balance_has_delegation() { new_test_ext(START_BLOCK_TIME).execute_with(|| { - get_funds(AccountId32::new(ALICE)); - let before_balance = Balances::free_balance(AccountId32::new(ALICE)); + let delegator = AccountId32::new(DELEGATOR_ACCOUNT); + get_funds(delegator.clone()); + let before_balance = Balances::free_balance(delegator.clone()); // Minimum balance is half of the user's wallet balance let account_minimum = before_balance / 2; let frequency = 3_600; let task_id = add_recurring_task_to_task_queue( - ALICE, + DELEGATOR_ACCOUNT, vec![1], SCHEDULED_TIME, frequency, Action::AutoCompoundDelegatedStake { - delegator: AccountId32::new(ALICE), + delegator: delegator.clone(), collator: AccountId32::new(COLLATOR_ACCOUNT), account_minimum, }, @@ -2506,56 +2476,44 @@ fn auto_compound_delegated_stake_enough_balance_has_delegation() { let emitted_events = events(); // // Expected result: - // // 1. Current execution will run and emit AutoCompoundDelegatorStakeSucceeded event - // emitted_events - // .clone() - // .into_iter() - // .find(|e| { - // matches!( - // e, - // RuntimeEvent::AutomationTime( - // crate::Event::AutoCompoundDelegatorStakeSucceeded { .. } - // ) - // ) - // }) - // .expect("AutoCompoundDelegatorStakeSucceeded event should have been emitted"); - - // // 2. Next execution will be scheduled - // emitted_events - // .clone() - // .into_iter() - // .find(|e| matches!(e, RuntimeEvent::AutomationTime(crate::Event::TaskScheduled { .. }))) - // .expect("TaskScheduled event should have been emitted"); + // // 1. Current execution will run + + // 2. Next execution will be scheduled + emitted_events + .clone() + .into_iter() + .find(|e| matches!(e, RuntimeEvent::AutomationTime(crate::Event::TaskRescheduled { .. }))) + .expect("TaskRescheduled event should have been emitted"); let next_scheduled_time = SCHEDULED_TIME + frequency; AutomationTime::get_scheduled_tasks(next_scheduled_time) .expect("Task should have been rescheduled") .tasks .into_iter() - .find(|t| *t == (AccountId32::new(ALICE), task_id)) + .find(|t| *t == (delegator.clone(), task_id)) .expect("Task should have been rescheduled"); - let task = AutomationTime::get_account_task(AccountId32::new(ALICE), task_id) + let task = AutomationTime::get_account_task(delegator.clone(), task_id) .expect("Task should not have been removed from task map"); assert_eq!(task.schedule.known_executions_left(), 1); assert_eq!(task.execution_times(), vec![next_scheduled_time]); // 3. The task will re-run in the next execution time Timestamp::set_timestamp(next_scheduled_time * 1_000); - get_funds(AccountId32::new(ALICE)); + get_funds(delegator.clone()); System::reset_events(); AutomationTime::trigger_tasks(Weight::from_ref_time(100_000_000_000)); - // events() - // .into_iter() - // .find(|e| { - // matches!( - // e, - // RuntimeEvent::AutomationTime( - // crate::Event::AutoCompoundDelegatorStakeSucceeded { .. } - // ) - // ) - // }) - // .expect("AutoCompoundDelegatorStakeSucceeded event should have been emitted again!"); + events() + .into_iter() + .find(|e| { + matches!( + e, + RuntimeEvent::AutomationTime( + crate::Event::TaskTriggered { .. } + ) + ) + }) + .expect("AutoCompoundDelegatorStakeSucceeded event should have been emitted again!"); }) } @@ -2568,20 +2526,22 @@ fn auto_compound_delegated_stake_enough_balance_has_delegation() { // 2. Next execution will be scheduled #[test] fn auto_compound_delegated_stake_not_enough_balance_has_delegation() { + let _ = env_logger::try_init(); new_test_ext(START_BLOCK_TIME).execute_with(|| { - get_funds(AccountId32::new(ALICE)); - let before_balance = Balances::free_balance(AccountId32::new(ALICE)); + let delegator = AccountId32::new(DELEGATOR_ACCOUNT); + get_funds(delegator.clone()); + let before_balance = Balances::free_balance(delegator.clone()); // Minimum balance is twice of the user's wallet balance let account_minimum = before_balance * 2; let frequency = 3_600; let task_id = add_recurring_task_to_task_queue( - ALICE, + DELEGATOR_ACCOUNT, vec![1], SCHEDULED_TIME, frequency, Action::AutoCompoundDelegatedStake { - delegator: AccountId32::new(ALICE), + delegator: delegator.clone(), collator: AccountId32::new(COLLATOR_ACCOUNT), account_minimum, }, @@ -2596,7 +2556,7 @@ fn auto_compound_delegated_stake_not_enough_balance_has_delegation() { // Expected result: // 1. Emit TaskExecutionFailed event with error: InsufficientBalance let insufficient_balance_error: DispatchError = >::InsufficientBalance.into(); - let event = emitted_events.clone().into_iter() + emitted_events.clone().into_iter() .find(|e| matches!(e, RuntimeEvent::AutomationTime(crate::Event::TaskExecutionFailed { error, .. }) if *error == insufficient_balance_error )).expect("TaskExecutionFailed event should have been emitted"); // 2. Next execution will be scheduled @@ -2610,9 +2570,9 @@ fn auto_compound_delegated_stake_not_enough_balance_has_delegation() { .expect("Task should have been rescheduled") .tasks .into_iter() - .find(|t| *t == (AccountId32::new(ALICE), task_id)) + .find(|t| *t == (delegator.clone(), task_id)) .expect("Task should have been rescheduled"); - let task = AutomationTime::get_account_task(AccountId32::new(ALICE), task_id) + let task = AutomationTime::get_account_task(delegator.clone(), task_id) .expect("Task should not have been removed from task map"); assert_eq!(task.schedule.known_executions_left(), 1); assert_eq!(task.execution_times(), vec![next_scheduled_time]); @@ -2628,9 +2588,11 @@ fn auto_compound_delegated_stake_not_enough_balance_has_delegation() { // 2. Next execution will not be scheduled #[test] fn auto_compound_delegated_stake_enough_balance_no_delegation() { + let _ = env_logger::try_init(); new_test_ext(START_BLOCK_TIME).execute_with(|| { - get_funds(AccountId32::new(ALICE)); - let before_balance = Balances::free_balance(AccountId32::new(ALICE)); + let delegator = AccountId32::new(DELEGATOR_ACCOUNT); + get_funds(delegator.clone()); + let before_balance = Balances::free_balance(delegator.clone()); // Minimum balance is half of the user's wallet balance let account_minimum = before_balance / 2; let frequency = 3_600; @@ -2641,7 +2603,7 @@ fn auto_compound_delegated_stake_enough_balance_no_delegation() { SCHEDULED_TIME, frequency, Action::AutoCompoundDelegatedStake { - delegator: AccountId32::new(ALICE), + delegator: delegator.clone(), collator: AccountId32::new(BOB), account_minimum, }, @@ -2651,20 +2613,21 @@ fn auto_compound_delegated_stake_enough_balance_no_delegation() { AutomationTime::trigger_tasks(Weight::from_ref_time(120_000)); - // // Expected result: - // // 1. The current execution will result in failure, triggering the emission of an AutoCompoundDelegatorStakeFailed event, error: DelegationNotFound - // events() - // .into_iter() - // .find(|e| matches!(e, RuntimeEvent::AutomationTime(crate::Event::AutoCompoundDelegatorStakeFailed { error, .. }) if *error == sp_runtime::DispatchErrorWithPostInfo::from(Error::::DelegationNotFound))) - // .expect("AutoCompound failure event should have been emitted"); + // Expected result: + // 1. The current execution will result in failure, triggering the emission of an AutoCompoundDelegatorStakeFailed event, error: DelegationDNE + let delegation_dne_error: DispatchError = >::DelegationDNE.into(); + events() + .into_iter() + .find(|e| matches!(e, RuntimeEvent::AutomationTime(crate::Event::AutoCompoundDelegatorStakeFailed { error, .. }) if error.error == delegation_dne_error)) + .expect("AutoCompoundDelegatorStakeFailed event should have been emitted"); - // // 2. Next execution will not be scheduled - // assert!(AutomationTime::get_scheduled_tasks(SCHEDULED_TIME + frequency) - // .filter(|scheduled| { - // scheduled.tasks.iter().any(|t| *t == (AccountId32::new(ALICE), task_id)) - // }) - // .is_none()); - // assert!(AutomationTime::get_account_task(AccountId32::new(ALICE), task_id).is_none()); + // 2. Next execution will not be scheduled + assert!(AutomationTime::get_scheduled_tasks(SCHEDULED_TIME + frequency) + .filter(|scheduled| { + scheduled.tasks.iter().any(|t| *t == (AccountId32::new(ALICE), task_id)) + }) + .is_none()); + assert!(AutomationTime::get_account_task(AccountId32::new(ALICE), task_id).is_none()); }) } @@ -2677,8 +2640,9 @@ fn auto_compound_delegated_stake_enough_balance_no_delegation() { // 2. Next execution will not be scheduled #[test] fn auto_compound_delegated_stake_not_enough_balance_no_delegation() { + let _ = env_logger::try_init(); new_test_ext(START_BLOCK_TIME).execute_with(|| { - let delegator = AccountId32::new(ALICE); + let delegator = AccountId32::new(DELEGATOR_ACCOUNT); let collator = AccountId32::new(BOB); get_funds(delegator.clone()); let before_balance = Balances::free_balance(AccountId32::new(ALICE)); @@ -2701,36 +2665,34 @@ fn auto_compound_delegated_stake_not_enough_balance_no_delegation() { System::reset_events(); AutomationTime::trigger_tasks(Weight::from_ref_time(120_000)); + let emit_events = events(); - // Expected result: - // 1. The current execution will result in failure, triggering the emission of an AutoCompoundDelegatorStakeFailed event, error: DelegationNotFound - // let failed_error_message = format!(ERROR_MESSAGE_DELEGATION_FORMAT!(), hex::encode(&delegator), hex::encode(&collator)); - // events() - // .into_iter() - // .find(|e| { - // matches!(e, - // RuntimeEvent::AutomationTime(crate::Event::AutoCompoundDelegatorStakeFailed { - // error_message, - // error, - // .. - // }) if *error == sp_runtime::DispatchErrorWithPostInfo::from(Error::::DelegationNotFound) && *error_message == failed_error_message.as_bytes().to_vec()) - // }) - // .expect("AutoCompound failure event should have been emitted"); + log::error!("emit_events: {:?}", emit_events); + // Expected result: + // 1. The current execution will result in failure, triggering the emission of an AutoCompoundDelegatorStakeFailed event, error: DelegationDNE let delegation_dne_error: DispatchError = >::DelegationDNE.into(); - - let emit_events = events(); + emit_events.clone() + .into_iter() + .find(|e| { + matches!(e, + RuntimeEvent::AutomationTime(crate::Event::AutoCompoundDelegatorStakeFailed { + error: DispatchErrorWithDataMap { error, .. }, + .. + }) if *error == delegation_dne_error.clone()) + }) + .expect("AutoCompoundDelegatorStakeFailed event should have been emitted"); - let event = emit_events.into_iter() + emit_events.into_iter() .find(|e| matches!(e, RuntimeEvent::AutomationTime(crate::Event::TaskExecutionFailed { error, .. }) if *error == delegation_dne_error )).expect("TaskExecutionFailed event should have been emitted"); // 2. Next execution will not be scheduled - // assert!(AutomationTime::get_scheduled_tasks(SCHEDULED_TIME + frequency) - // .filter(|scheduled| { - // scheduled.tasks.iter().any(|t| *t == (delegator.clone(), task_id)) - // }) - // .is_none()); - // assert!(AutomationTime::get_account_task(delegator.clone(), task_id).is_none()); + assert!(AutomationTime::get_scheduled_tasks(SCHEDULED_TIME + frequency) + .filter(|scheduled| { + scheduled.tasks.iter().any(|t| *t == (delegator.clone(), task_id)) + }) + .is_none()); + assert!(AutomationTime::get_account_task(delegator.clone(), task_id).is_none()); }) }