Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Commit

Permalink
Tests for pallet-tx-pause (#12259)
Browse files Browse the repository at this point in the history
* mock added
* tests added
* dummy benchmarks started
  • Loading branch information
nuke-web3 authored Sep 21, 2022
1 parent 379b82f commit 7f8688e
Show file tree
Hide file tree
Showing 10 changed files with 483 additions and 9 deletions.
5 changes: 5 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions bin/node/cli/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,8 @@ pub fn testnet_genesis(
min_join_bond: 1 * DOLLARS,
..Default::default()
},
safe_mode: Default::default(),
tx_pause: Default::default(),
}
}

Expand Down
9 changes: 9 additions & 0 deletions bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,14 @@ impl pallet_tx_pause::Config for Runtime {
type UnpauseOrigin = EnsureRoot<AccountId>;
type MaxNameLen = ConstU32<256>;
type PauseTooLongNames = ConstBool<true>;
type WeightInfo = pallet_tx_pause::weights::SubstrateWeight<Runtime>;
}

parameter_types! {
// signed config
pub const EnableStakeAmount: Balance = 1 * DOLLARS; //TODO This needs to be something sensible for the implications of enablement!
pub const ExtendStakeAmount: Balance = 1 * DOLLARS; //TODO This needs to be something sensible for the implications of enablement!
pub BlockHeight: BlockNumber = System::block_number(); // TODO ensure this plus config below is correct
}

parameter_types! {
Expand Down Expand Up @@ -1807,6 +1815,7 @@ mod benches {
[pallet_utility, Utility]
[pallet_vesting, Vesting]
[pallet_whitelist, Whitelist]
[pallet_tx_pause, TxPause]
[pallet_safe_mode, SafeMode]
);
}
Expand Down
2 changes: 2 additions & 0 deletions bin/node/testing/src/genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,5 +95,7 @@ pub fn config_endowed(code: Option<&[u8]>, extra_endowed: Vec<AccountId>) -> Gen
alliance: Default::default(),
alliance_motion: Default::default(),
nomination_pools: Default::default(),
safe_mode: Default::default(),
tx_pause: Default::default(),
}
}
13 changes: 12 additions & 1 deletion frame/tx-pause/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,34 @@ targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
frame-benchmarking = { version = "4.0.0-dev", default-features = false, optional = true, path = "../benchmarking" }
frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" }
frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" }
scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
sp-runtime = { version = "6.0.0", default-features = false, path = "../../primitives/runtime" }
sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" }


[dev-dependencies]
sp-core = { version = "6.0.0", path = "../../primitives/core" }
sp-std = { version = "4.0.0", path = "../../primitives/std" }
sp-io = { version = "6.0.0", path = "../../primitives/io" }
pallet-balances = { version = "4.0.0-dev", path = "../balances" }


[features]
default = ["std"]
std = [
"codec/std",
"scale-info/std",
"frame-benchmarking/std",
"frame-support/std",
"frame-system/std",
"sp-runtime/std",
"sp-std/std",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
]
Expand Down
40 changes: 40 additions & 0 deletions frame/tx-pause/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,43 @@
// limitations under the License.

#![cfg(feature = "runtime-benchmarks")]

use super::{Pallet as TxPause, *};

use frame_benchmarking::benchmarks;
use frame_support::traits::UnfilteredDispatchable;

benchmarks! {
pause_call {
let pallet: PalletNameOf<T> = b"SomePalletName".to_vec().try_into().unwrap();
let function: FunctionNameOf<T> = b"some_fn_name".to_vec().try_into().unwrap();
let origin = T::PauseOrigin::successful_origin();
let call = Call::<T>::pause_call { pallet: pallet.clone(), function: function.clone() };

}: { call.dispatch_bypass_filter(origin)?}
verify {
assert![TxPause::<T>::paused_calls((pallet.clone(),function.clone())).is_some()]
}

unpause_call {
let pallet: PalletNameOf<T> = b"SomePalletName".to_vec().try_into().unwrap();
let function: FunctionNameOf<T> = b"some_fn_name".to_vec().try_into().unwrap();
let pause_origin = T::PauseOrigin::successful_origin();

// Set
TxPause::<T>::pause_call(
pause_origin,
pallet.clone(),
function.clone(),
)?;

let unpause_origin = T::UnpauseOrigin::successful_origin();
let call = Call::<T>::unpause_call { pallet: pallet.clone(), function: function.clone() };

}: { call.dispatch_bypass_filter(unpause_origin)?}
verify {
assert![TxPause::<T>::paused_calls((pallet.clone(),function.clone())).is_none()]
}

impl_benchmark_test_suite!(TxPause, crate::mock::new_test_ext(), crate::mock::Test);
}
20 changes: 13 additions & 7 deletions frame/tx-pause/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,23 @@

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
#[cfg(test)]
pub mod mock;
#[cfg(test)]
mod tests;
pub mod weights;

use frame_support::{
pallet_prelude::*,
traits::{CallMetadata, Contains, GetCallMetadata},
};
use frame_system::pallet_prelude::*;
use sp_std::{convert::TryInto, prelude::*};

mod benchmarking;
mod mock;
mod tests;

pub use pallet::*;
pub use weights::*;

pub type PalletNameOf<T> = BoundedVec<u8, <T as Config>::MaxNameLen>;
pub type CallNameOf<T> = BoundedVec<u8, <T as Config>::MaxNameLen>;
Expand Down Expand Up @@ -74,7 +79,7 @@ pub mod pallet {
type PauseTooLongNames: Get<bool>;

// Weight information for extrinsics in this pallet.
//type WeightInfo: WeightInfo;
type WeightInfo: WeightInfo;
}

#[pallet::error]
Expand All @@ -100,6 +105,7 @@ pub mod pallet {

/// The set of calls that are explicitly paused.
#[pallet::storage]
#[pallet::getter(fn paused_calls)]
pub type PausedCalls<T: Config> =
StorageMap<_, Blake2_128Concat, (PalletNameOf<T>, CallNameOf<T>), (), OptionQuery>;

Expand Down Expand Up @@ -135,7 +141,7 @@ pub mod pallet {
///
/// Can only be called by [`Config::PauseOrigin`].
/// Emits an [`Event::CallPaused`] event on success.
#[pallet::weight(0)]
#[pallet::weight(T::WeightInfo::pause_call())]
pub fn pause_call(
origin: OriginFor<T>,
pallet: PalletNameOf<T>,
Expand All @@ -154,7 +160,7 @@ pub mod pallet {
///
/// Can only be called by [`Config::UnpauseOrigin`].
/// Emits an [`Event::CallUnpaused`] event on success.
#[pallet::weight(0)]
#[pallet::weight(T::WeightInfo::unpause_call())]
pub fn unpause_call(
origin: OriginFor<T>,
pallet: PalletNameOf<T>,
Expand Down
159 changes: 158 additions & 1 deletion frame/tx-pause/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,161 @@
// See the License for the specific language governing permissions and
// limitations under the License.

#![cfg(any(test, feature = "runtime-benchmarks"))]
//! Test utilities for transaction pause (tx pause) pallet.
use super::*;
use crate as pallet_tx_pause;

use frame_support::{
parameter_types,
traits::{Everything, InsideBoth, SortedMembers},
};
use frame_system::EnsureSignedBy;
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
};

parameter_types! {
pub const BlockHashCount: u64 = 250;
}
impl frame_system::Config for Test {
type BaseCallFilter = InsideBoth<Everything, TxPause>;
type BlockWeights = ();
type BlockLength = ();
type Origin = Origin;
type Call = Call;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = BlockHashCount;
type DbWeight = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
}

parameter_types! {
pub const ExistentialDeposit: u64 = 1;
pub const MaxLocks: u32 = 10;
}
impl pallet_balances::Config for Test {
type Balance = u64;
type DustRemoval = ();
type Event = Event;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type WeightInfo = ();
type MaxLocks = MaxLocks;
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
}

parameter_types! {
pub const PauseOrigin: u64 = 1;
pub const UnpauseOrigin: u64 = 2;
pub const MaxNameLen: u32 = 50;
pub const PauseTooLongNames: bool = false;
}

pub struct MockUnpausablePallets;

impl Contains<PalletNameOf<Test>> for MockUnpausablePallets {
fn contains(pallet: &PalletNameOf<Test>) -> bool {
let unpausables: Vec<PalletNameOf<Test>> =
vec![b"UnpausablePallet".to_vec().try_into().unwrap()];

unpausables.iter().any(|i| i == pallet)
}
}
// Required impl to use some <Configured Origin>::get() in tests
impl SortedMembers<u64> for PauseOrigin {
fn sorted_members() -> Vec<u64> {
vec![Self::get()]
}
#[cfg(feature = "runtime-benchmarks")]
fn add(_m: &u64) {}
}
impl SortedMembers<u64> for UnpauseOrigin {
fn sorted_members() -> Vec<u64> {
vec![Self::get()]
}
#[cfg(feature = "runtime-benchmarks")]
fn add(_m: &u64) {}
}

impl Config for Test {
type Event = Event;
type PauseOrigin = EnsureSignedBy<PauseOrigin, Self::AccountId>;
type UnpauseOrigin = EnsureSignedBy<UnpauseOrigin, Self::AccountId>;
type UnpausablePallets = MockUnpausablePallets;
type MaxNameLen = MaxNameLen;
type PauseTooLongNames = PauseTooLongNames;
type WeightInfo = ();
}

type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;

frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system,
Balances: pallet_balances,
TxPause: pallet_tx_pause,
}
);

pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();

pallet_balances::GenesisConfig::<Test> {
// The 0 account is NOT a special origin. The rest may be:
balances: vec![(0, 1234), (1, 5678), (2, 5678), (3, 5678), (4, 5678)],
}
.assimilate_storage(&mut t)
.unwrap();

GenesisBuild::<Test>::assimilate_storage(
&pallet_tx_pause::GenesisConfig { paused: vec![], _phantom: Default::default() },
&mut t,
)
.unwrap();

let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| {
System::set_block_number(1);
});
ext
}

pub fn next_block() {
TxPause::on_finalize(System::block_number());
Balances::on_finalize(System::block_number());
System::on_finalize(System::block_number());
System::set_block_number(System::block_number() + 1);
System::on_initialize(System::block_number());
Balances::on_initialize(System::block_number());
TxPause::on_initialize(System::block_number());
}

pub fn run_to(n: u64) {
while System::block_number() < n {
next_block();
}
}
Loading

0 comments on commit 7f8688e

Please sign in to comment.