From 0666306a8030a990e3ceb7f4a8f81f186a391f5d Mon Sep 17 00:00:00 2001 From: kianenigma Date: Mon, 16 Nov 2020 12:00:55 +0000 Subject: [PATCH 1/8] Thread-local parameter_types for testing. --- frame/balances/src/tests_composite.rs | 11 +--- frame/balances/src/tests_local.rs | 12 ++--- frame/contracts/src/tests.rs | 12 ++--- frame/democracy/src/tests.rs | 17 ++----- frame/elections-phragmen/src/lib.rs | 38 +++----------- frame/elections/src/mock.rs | 37 +++----------- frame/membership/src/lib.rs | 7 ++- frame/scored-pool/src/mock.rs | 5 +- frame/staking/src/mock.rs | 65 ++++-------------------- frame/support/src/lib.rs | 73 ++++++++++++++++++++++++++- frame/transaction-payment/src/lib.rs | 22 ++------ frame/vesting/src/lib.rs | 10 +--- 12 files changed, 122 insertions(+), 187 deletions(-) diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index 88b73b47273eb..af02106206edf 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -27,10 +27,8 @@ use sp_runtime::{ use sp_core::H256; use sp_io; use frame_support::{impl_outer_origin, impl_outer_event, parameter_types}; -use frame_support::traits::Get; use frame_support::weights::{Weight, DispatchInfo, IdentityFee}; use pallet_transaction_payment::CurrencyAdapter; -use std::cell::RefCell; use crate::{GenesisConfig, Module, Trait, decl_tests, tests::CallWithDispatchInfo}; use frame_system as system; @@ -49,13 +47,8 @@ impl_outer_event! { } } -thread_local! { - static EXISTENTIAL_DEPOSIT: RefCell = RefCell::new(0); -} - -pub struct ExistentialDeposit; -impl Get for ExistentialDeposit { - fn get() -> u64 { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow()) } +frame_support::parameter_types_thread_local! { + static ExistentialDeposit: u64 = 0; } // Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted. diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index 319fb3640b4c7..9ee6160f688f3 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -27,9 +27,8 @@ use sp_runtime::{ use sp_core::H256; use sp_io; use frame_support::{impl_outer_origin, impl_outer_event, parameter_types}; -use frame_support::traits::{Get, StorageMapShim}; +use frame_support::traits::StorageMapShim; use frame_support::weights::{Weight, DispatchInfo, IdentityFee}; -use std::cell::RefCell; use crate::{GenesisConfig, Module, Trait, decl_tests, tests::CallWithDispatchInfo}; use pallet_transaction_payment::CurrencyAdapter; @@ -49,13 +48,8 @@ impl_outer_event! { } } -thread_local! { - static EXISTENTIAL_DEPOSIT: RefCell = RefCell::new(0); -} - -pub struct ExistentialDeposit; -impl Get for ExistentialDeposit { - fn get() -> u64 { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow()) } +frame_support::parameter_types_thread_local! { + static ExistentialDeposit: u64 = 0; } // Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted. diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index c2d9ed6642559..9ce7b1183886a 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -30,11 +30,10 @@ use sp_runtime::{ use frame_support::{ assert_ok, assert_err_ignore_postinfo, impl_outer_dispatch, impl_outer_event, impl_outer_origin, parameter_types, StorageMap, StorageValue, - traits::{Currency, Get, ReservableCurrency}, + traits::{Currency, ReservableCurrency}, weights::{Weight, PostDispatchInfo}, dispatch::DispatchErrorWithPostInfo, }; -use std::cell::RefCell; use frame_system::{self as system, EventRecord, Phase}; mod contracts { @@ -99,13 +98,8 @@ pub mod test_utils { } } -thread_local! { - static EXISTENTIAL_DEPOSIT: RefCell = RefCell::new(0); -} - -pub struct ExistentialDeposit; -impl Get for ExistentialDeposit { - fn get() -> u64 { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow()) } +frame_support::parameter_types_thread_local! { + static ExistentialDeposit: u64 = 0; } #[derive(Clone, Eq, PartialEq, Debug)] diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index bcc7099bb34a4..09a6fef45b279 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -18,7 +18,6 @@ //! The crate's tests. use super::*; -use std::cell::RefCell; use codec::Encode; use frame_support::{ impl_outer_origin, impl_outer_dispatch, assert_noop, assert_ok, parameter_types, @@ -171,18 +170,12 @@ impl Contains for OneToFive { #[cfg(feature = "runtime-benchmarks")] fn add(_m: &u64) {} } -thread_local! { - static PREIMAGE_BYTE_DEPOSIT: RefCell = RefCell::new(0); - static INSTANT_ALLOWED: RefCell = RefCell::new(false); -} -pub struct PreimageByteDeposit; -impl Get for PreimageByteDeposit { - fn get() -> u64 { PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow()) } -} -pub struct InstantAllowed; -impl Get for InstantAllowed { - fn get() -> bool { INSTANT_ALLOWED.with(|v| *v.borrow()) } + +frame_support::parameter_types_thread_local! { + static PreimageByteDeposit: u64 = 0; + static InstantAllowed: bool = false; } + impl super::Trait for Test { type Proposal = Call; type Event = Event; diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index cf3864f2e3f92..06ab7dbb95511 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -1052,7 +1052,6 @@ impl ContainsLengthBound for Module { #[cfg(test)] mod tests { use super::*; - use std::cell::RefCell; use frame_support::{assert_ok, assert_noop, assert_err_with_weight, parameter_types, weights::Weight, }; @@ -1117,36 +1116,13 @@ mod tests { pub const CandidacyBond: u64 = 3; } - thread_local! { - static VOTING_BOND: RefCell = RefCell::new(2); - static DESIRED_MEMBERS: RefCell = RefCell::new(2); - static DESIRED_RUNNERS_UP: RefCell = RefCell::new(2); - static TERM_DURATION: RefCell = RefCell::new(5); - } - - pub struct VotingBond; - impl Get for VotingBond { - fn get() -> u64 { VOTING_BOND.with(|v| *v.borrow()) } - } - - pub struct DesiredMembers; - impl Get for DesiredMembers { - fn get() -> u32 { DESIRED_MEMBERS.with(|v| *v.borrow()) } - } - - pub struct DesiredRunnersUp; - impl Get for DesiredRunnersUp { - fn get() -> u32 { DESIRED_RUNNERS_UP.with(|v| *v.borrow()) } - } - - pub struct TermDuration; - impl Get for TermDuration { - fn get() -> u64 { TERM_DURATION.with(|v| *v.borrow()) } - } - - thread_local! { - pub static MEMBERS: RefCell> = RefCell::new(vec![]); - pub static PRIME: RefCell> = RefCell::new(None); + frame_support::parameter_types_thread_local! { + static VotingBond: u64 = 2; + static DesiredMembers: u32 = 2; + static DesiredRunnersUp: u32 = 2; + static TermDuration: u64 = 5; + static Members: Vec = vec![]; + static Prime: Option = None; } pub struct TestChangeMembers; diff --git a/frame/elections/src/mock.rs b/frame/elections/src/mock.rs index deec77da7b837..305f57b059b3e 100644 --- a/frame/elections/src/mock.rs +++ b/frame/elections/src/mock.rs @@ -19,10 +19,9 @@ #![cfg(test)] -use std::cell::RefCell; use frame_support::{ StorageValue, StorageMap, parameter_types, assert_ok, - traits::{Get, ChangeMembers, Currency, LockIdentifier}, + traits::{ChangeMembers, Currency, LockIdentifier}, weights::Weight, }; use sp_core::H256; @@ -87,32 +86,12 @@ parameter_types! { pub const MinimumVotingLock: u64 = 5; } -thread_local! { - static VOTER_BOND: RefCell = RefCell::new(0); - static VOTING_FEE: RefCell = RefCell::new(0); - static PRESENT_SLASH_PER_VOTER: RefCell = RefCell::new(0); - static DECAY_RATIO: RefCell = RefCell::new(0); - static MEMBERS: RefCell> = RefCell::new(vec![]); -} - -pub struct VotingBond; -impl Get for VotingBond { - fn get() -> u64 { VOTER_BOND.with(|v| *v.borrow()) } -} - -pub struct VotingFee; -impl Get for VotingFee { - fn get() -> u64 { VOTING_FEE.with(|v| *v.borrow()) } -} - -pub struct PresentSlashPerVoter; -impl Get for PresentSlashPerVoter { - fn get() -> u64 { PRESENT_SLASH_PER_VOTER.with(|v| *v.borrow()) } -} - -pub struct DecayRatio; -impl Get for DecayRatio { - fn get() -> u32 { DECAY_RATIO.with(|v| *v.borrow()) } +frame_support::parameter_types_thread_local! { + static VoterBond: u64 = 0; + static VotingFee: u64 = 0; + static PresentSlashPerVoter: u64 = 0; + static DecayRatio: u32 = 0; + static Members: Vec = vec![]; } pub struct TestChangeMembers; @@ -143,7 +122,7 @@ impl elections::Trait for Test { type LoserCandidate = (); type ChangeMembers = TestChangeMembers; type CandidacyBond = CandidacyBond; - type VotingBond = VotingBond; + type VotingBond = VoterBond; type VotingFee = VotingFee; type MinimumVotingLock = MinimumVotingLock; type PresentSlashPerVoter = PresentSlashPerVoter; diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 492fda88dd170..2e465b4f704dc 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -278,7 +278,6 @@ impl, I: Instance> Contains for Module { mod tests { use super::*; - use std::cell::RefCell; use frame_support::{ assert_ok, assert_noop, impl_outer_origin, parameter_types, weights::Weight, ord_parameter_types @@ -334,9 +333,9 @@ mod tests { pub const Five: u64 = 5; } - thread_local! { - static MEMBERS: RefCell> = RefCell::new(vec![]); - static PRIME: RefCell> = RefCell::new(None); + frame_support::parameter_types_thread_local! { + static Members: Vec = vec![]; + static Prime: Option = None; } pub struct TestChangeMembers; diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 59c0dc66cca60..5806f8a25245b 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -19,7 +19,6 @@ use super::*; -use std::cell::RefCell; use frame_support::{impl_outer_origin, parameter_types, weights::Weight, ord_parameter_types}; use sp_core::H256; use sp_runtime::{ @@ -87,8 +86,8 @@ impl pallet_balances::Trait for Test { type WeightInfo = (); } -thread_local! { - pub static MEMBERS: RefCell> = RefCell::new(vec![]); +frame_support::parameter_types_thread_local! { + static Members: Vec = vec![]; } pub struct TestChangeMembers; diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 055ebb9730805..ee3532b577a47 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -47,12 +47,6 @@ pub(crate) type Balance = u128; thread_local! { static SESSION: RefCell<(Vec, HashSet)> = RefCell::new(Default::default()); - static SESSION_PER_ERA: RefCell = RefCell::new(3); - static EXISTENTIAL_DEPOSIT: RefCell = RefCell::new(0); - static SLASH_DEFER_DURATION: RefCell = RefCell::new(0); - static ELECTION_LOOKAHEAD: RefCell = RefCell::new(0); - static PERIOD: RefCell = RefCell::new(1); - static MAX_ITERATIONS: RefCell = RefCell::new(0); } /// Another session handler struct to test on_disabled. @@ -92,53 +86,6 @@ pub fn is_disabled(controller: AccountId) -> bool { SESSION.with(|d| d.borrow().1.contains(&stash)) } -pub struct ExistentialDeposit; -impl Get for ExistentialDeposit { - fn get() -> Balance { - EXISTENTIAL_DEPOSIT.with(|v| *v.borrow()) - } -} - -pub struct SessionsPerEra; -impl Get for SessionsPerEra { - fn get() -> SessionIndex { - SESSION_PER_ERA.with(|v| *v.borrow()) - } -} -impl Get for SessionsPerEra { - fn get() -> BlockNumber { - SESSION_PER_ERA.with(|v| *v.borrow() as BlockNumber) - } -} - -pub struct ElectionLookahead; -impl Get for ElectionLookahead { - fn get() -> BlockNumber { - ELECTION_LOOKAHEAD.with(|v| *v.borrow()) - } -} - -pub struct Period; -impl Get for Period { - fn get() -> BlockNumber { - PERIOD.with(|v| *v.borrow()) - } -} - -pub struct SlashDeferDuration; -impl Get for SlashDeferDuration { - fn get() -> EraIndex { - SLASH_DEFER_DURATION.with(|v| *v.borrow()) - } -} - -pub struct MaxIterations; -impl Get for MaxIterations { - fn get() -> u32 { - MAX_ITERATIONS.with(|v| *v.borrow()) - } -} - impl_outer_origin! { pub enum Origin for Test where system = frame_system {} } @@ -187,6 +134,16 @@ parameter_types! { pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const MaxLocks: u32 = 1024; } + +frame_support::parameter_types_thread_local! { + static SessionsPerEra: SessionIndex = 3; + static ExistentialDeposit: Balance = 0; + static SlashDeferDuration: EraIndex = 0; + static ElectionLookahead: BlockNumber = 0; + static Period: BlockNumber = 1; + static MaxIterations: u32 = 0; +} + impl frame_system::Trait for Test { type BaseCallFilter = (); type Origin = Origin; @@ -437,7 +394,7 @@ impl ExtBuilder { pub fn set_associated_constants(&self) { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); SLASH_DEFER_DURATION.with(|v| *v.borrow_mut() = self.slash_defer_duration); - SESSION_PER_ERA.with(|v| *v.borrow_mut() = self.session_per_era); + SESSIONS_PER_ERA.with(|v| *v.borrow_mut() = self.session_per_era); ELECTION_LOOKAHEAD.with(|v| *v.borrow_mut() = self.election_lookahead); PERIOD.with(|v| *v.borrow_mut() = self.session_length); MAX_ITERATIONS.with(|v| *v.borrow_mut() = self.max_offchain_iterations); diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index a132b787fd9bf..3b4fffc1a52f1 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -142,7 +142,6 @@ pub enum Never {} /// pub const Argument: u64 = non_const_expression(); /// } /// ``` - #[macro_export] macro_rules! parameter_types { ( @@ -238,6 +237,78 @@ macro_rules! parameter_types { } } +/// An implementation of [`traits::Get`] with thread local variables. +/// +/// **Useful for testing only**. A mock externalities builder can change these value on the fly. +/// +/// Accepts a syntax similar to that of [`parameter_types`], and provides an additional `set` +/// function. +/// +/// ## Example +/// +/// ``` +/// # use frame_support::traits::Get; +/// # use frame_support::parameter_types_thread_local; +/// +/// parameter_types_thread_local! { +/// static MyConfig: u32 = 10; +/// static OtherConfig: u32 = 10; +/// } +/// +/// // Generates a static variable with name `MY_CONFIG` and `OTHER_CONFIG`. +/// // Manually altering them works: +/// MY_CONFIG.with(|v| *v.borrow_mut() = 1); +/// // Or use the setter function provided: +/// MyConfig::set(2); +/// ``` +#[macro_export] +#[cfg(feature = "std")] +macro_rules! parameter_types_thread_local { + ( + $( + static $name:ident : $type:ty = $default:expr; + )* + ) => { + $crate::parameter_types_thread_local! { + @THREAD_LOCAL($( + $name, $type, $default, + )*) + } + + $crate::parameter_types_thread_local! { + @GETTER_STRUCT($( + $name, $type, + )*) + } + }; + (@THREAD_LOCAL($($name:ident, $type:ty, $default:expr,)*)) => { + $crate::paste::item! { + std::thread_local! { + $( + pub static [<$name:snake:upper>]: std::cell::RefCell<$type> = std::cell::RefCell::new($default); + )* + } + } + }; + (@GETTER_STRUCT($($name:ident, $type:ty,)*)) => { + $crate::paste::item! { + $( + /// A struct that implements [`traits::Get`] via static variables. + pub struct $name; + impl $crate::traits::Get<$type> for $name { + fn get() -> $type { [<$name:snake:upper>].with(|v| v.borrow().clone() )} + } + impl $name { + /// Set the internal value. + pub fn set(t: $type) { + [<$name:snake:upper>].with(|v| *v.borrow_mut() = t); + } + } + )* + } + } +} + /// Macro for easily creating a new implementation of both the `Get` and `Contains` traits. Use /// exactly as with `parameter_types`, only the type must be `Ord`. #[macro_export] diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index dd310c2639842..9c4f904201d03 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -571,7 +571,6 @@ mod tests { traits::{BlakeTwo256, IdentityLookup}, Perbill, }; - use std::cell::RefCell; use smallvec::smallvec; const CALL: &::Call = @@ -599,13 +598,10 @@ mod tests { pub enum Origin for Runtime {} } - thread_local! { - static EXTRINSIC_BASE_WEIGHT: RefCell = RefCell::new(0); - } - - pub struct ExtrinsicBaseWeight; - impl Get for ExtrinsicBaseWeight { - fn get() -> u64 { EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow()) } + frame_support::parameter_types_thread_local! { + static ExtrinsicBaseWeight: u64 = 0; + static TransactionByteFee: u64 = 1; + static WeightToFee: u64 = 1; } parameter_types! { @@ -656,17 +652,7 @@ mod tests { type MaxLocks = (); type WeightInfo = (); } - thread_local! { - static TRANSACTION_BYTE_FEE: RefCell = RefCell::new(1); - static WEIGHT_TO_FEE: RefCell = RefCell::new(1); - } - - pub struct TransactionByteFee; - impl Get for TransactionByteFee { - fn get() -> u64 { TRANSACTION_BYTE_FEE.with(|v| *v.borrow()) } - } - pub struct WeightToFee; impl WeightToFeePolynomial for WeightToFee { type Balance = u64; diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 8b78eac4fedf8..d99265530fc59 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -390,10 +390,8 @@ impl VestingSchedule for Module where mod tests { use super::*; - use std::cell::RefCell; use frame_support::{ assert_ok, assert_noop, impl_outer_origin, parameter_types, weights::Weight, - traits::Get }; use sp_core::H256; use sp_runtime::{ @@ -468,12 +466,8 @@ mod tests { type Balances = pallet_balances::Module; type Vesting = Module; - thread_local! { - static EXISTENTIAL_DEPOSIT: RefCell = RefCell::new(0); - } - pub struct ExistentialDeposit; - impl Get for ExistentialDeposit { - fn get() -> u64 { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow()) } + frame_support::parameter_types_thread_local! { + static ExistentialDeposit: u64 = 0; } pub struct ExtBuilder { From 2fcf32e03c197425236b62d83d57173c4dca251b Mon Sep 17 00:00:00 2001 From: kianenigma Date: Mon, 16 Nov 2020 12:07:00 +0000 Subject: [PATCH 2/8] Better docs. --- frame/support/src/lib.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 3b4fffc1a52f1..863c884dca031 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -260,6 +260,16 @@ macro_rules! parameter_types { /// MY_CONFIG.with(|v| *v.borrow_mut() = 1); /// // Or use the setter function provided: /// MyConfig::set(2); +/// +/// // Can be passed as `Get<_>` as well. +/// trait Config { +/// type Parameter: Get; +/// } +/// +/// struct Runtime; +/// impl Config for Runtime { +/// type Parameter = MyConfig; +/// } /// ``` #[macro_export] #[cfg(feature = "std")] From 530268ec870fdb2c1c22eea1fb5f0279835df10f Mon Sep 17 00:00:00 2001 From: kianenigma Date: Mon, 16 Nov 2020 14:28:19 +0000 Subject: [PATCH 3/8] Some minors --- frame/elections/src/mock.rs | 14 +++++++------- frame/elections/src/tests.rs | 12 ++++++------ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/frame/elections/src/mock.rs b/frame/elections/src/mock.rs index 305f57b059b3e..539a311bc81f5 100644 --- a/frame/elections/src/mock.rs +++ b/frame/elections/src/mock.rs @@ -87,7 +87,7 @@ parameter_types! { } frame_support::parameter_types_thread_local! { - static VoterBond: u64 = 0; + static VotingBond: u64 = 0; static VotingFee: u64 = 0; static PresentSlashPerVoter: u64 = 0; static DecayRatio: u32 = 0; @@ -122,7 +122,7 @@ impl elections::Trait for Test { type LoserCandidate = (); type ChangeMembers = TestChangeMembers; type CandidacyBond = CandidacyBond; - type VotingBond = VoterBond; + type VotingBond = VotingBond; type VotingFee = VotingFee; type MinimumVotingLock = MinimumVotingLock; type PresentSlashPerVoter = PresentSlashPerVoter; @@ -154,7 +154,7 @@ pub struct ExtBuilder { decay_ratio: u32, desired_seats: u32, voting_fee: u64, - voter_bond: u64, + voting_bond: u64, bad_presentation_punishment: u64, } @@ -165,7 +165,7 @@ impl Default for ExtBuilder { decay_ratio: 24, desired_seats: 2, voting_fee: 0, - voter_bond: 0, + voting_bond: 0, bad_presentation_punishment: 1, } } @@ -188,8 +188,8 @@ impl ExtBuilder { self.bad_presentation_punishment = fee; self } - pub fn voter_bond(mut self, fee: u64) -> Self { - self.voter_bond = fee; + pub fn voting_bond(mut self, fee: u64) -> Self { + self.voting_bond = fee; self } pub fn desired_seats(mut self, seats: u32) -> Self { @@ -197,7 +197,7 @@ impl ExtBuilder { self } pub fn build(self) -> sp_io::TestExternalities { - VOTER_BOND.with(|v| *v.borrow_mut() = self.voter_bond); + VOTING_BOND.with(|v| *v.borrow_mut() = self.voting_bond); VOTING_FEE.with(|v| *v.borrow_mut() = self.voting_fee); PRESENT_SLASH_PER_VOTER.with(|v| *v.borrow_mut() = self.bad_presentation_punishment); DECAY_RATIO.with(|v| *v.borrow_mut() = self.decay_ratio); diff --git a/frame/elections/src/tests.rs b/frame/elections/src/tests.rs index 92f6e11252b05..d3579ca337436 100644 --- a/frame/elections/src/tests.rs +++ b/frame/elections/src/tests.rs @@ -298,7 +298,7 @@ fn voting_initial_set_approvals_ignores_voter_index() { } #[test] fn voting_bad_approval_index_slashes_voters_and_bond_reduces_stake() { - ExtBuilder::default().voting_fee(5).voter_bond(2).build().execute_with(|| { + ExtBuilder::default().voting_fee(5).voting_bond(2).build().execute_with(|| { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); (1..=63).for_each(|i| vote(i, 0)); @@ -365,7 +365,7 @@ fn voting_cannot_lock_less_than_limit() { #[test] fn voting_locking_more_than_total_balance_is_moot() { - ExtBuilder::default().voter_bond(2).build().execute_with(|| { + ExtBuilder::default().voting_bond(2).build().execute_with(|| { assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_eq!(balances(&3), (30, 0)); @@ -381,7 +381,7 @@ fn voting_locking_more_than_total_balance_is_moot() { #[test] fn voting_locking_stake_and_reserving_bond_works() { - ExtBuilder::default().voter_bond(2).build().execute_with(|| { + ExtBuilder::default().voting_bond(2).build().execute_with(|| { assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0)); assert_eq!(balances(&2), (20, 0)); @@ -558,7 +558,7 @@ fn retracting_inactive_voter_should_work() { #[test] fn retracting_inactive_voter_with_other_candidates_in_slots_should_work() { - ExtBuilder::default().voter_bond(2).build().execute_with(|| { + ExtBuilder::default().voting_bond(2).build().execute_with(|| { System::set_block_number(4); assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0)); assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20)); @@ -1107,7 +1107,7 @@ fn election_present_when_presenter_is_poor_should_not_work() { let test_present = |p| { ExtBuilder::default() .voting_fee(5) - .voter_bond(2) + .voting_bond(2) .bad_presentation_punishment(p) .build() .execute_with(|| { @@ -1507,7 +1507,7 @@ fn pot_winning_resets_accumulated_pot() { #[test] fn pot_resubmitting_approvals_stores_pot() { ExtBuilder::default() - .voter_bond(0) + .voting_bond(0) .voting_fee(0) .balance_factor(10) .build() From 2f51361cc1033292fea115fb20b5f2e9fe5754ea Mon Sep 17 00:00:00 2001 From: kianenigma Date: Mon, 16 Nov 2020 17:45:07 +0000 Subject: [PATCH 4/8] Merge'em --- frame/balances/src/tests_composite.rs | 5 +- frame/balances/src/tests_local.rs | 5 +- frame/contracts/src/tests.rs | 5 +- frame/democracy/src/tests.rs | 7 +- frame/elections-phragmen/src/lib.rs | 14 +-- frame/elections/src/mock.rs | 13 ++- frame/membership/src/lib.rs | 7 +- frame/scored-pool/src/mock.rs | 5 +- frame/staking/src/mock.rs | 15 ++-- frame/support/src/lib.rs | 118 +++++++++----------------- frame/transaction-payment/src/lib.rs | 9 +- frame/vesting/src/lib.rs | 4 +- 12 files changed, 74 insertions(+), 133 deletions(-) diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index af02106206edf..fd4ba1fd3c305 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -47,10 +47,6 @@ impl_outer_event! { } } -frame_support::parameter_types_thread_local! { - static ExistentialDeposit: u64 = 0; -} - // Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted. #[derive(Clone, PartialEq, Eq, Debug)] pub struct Test; @@ -59,6 +55,7 @@ parameter_types! { pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); + pub static ExistentialDeposit: u64 = 0; } impl frame_system::Trait for Test { type BaseCallFilter = (); diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index 9ee6160f688f3..c0a5d23ff1a41 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -48,10 +48,6 @@ impl_outer_event! { } } -frame_support::parameter_types_thread_local! { - static ExistentialDeposit: u64 = 0; -} - // Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted. #[derive(Clone, PartialEq, Eq, Debug)] pub struct Test; @@ -60,6 +56,7 @@ parameter_types! { pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); + pub static ExistentialDeposit: u64 = 0; } impl frame_system::Trait for Test { type BaseCallFilter = (); diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 9ce7b1183886a..05e46a3ab1585 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -98,10 +98,6 @@ pub mod test_utils { } } -frame_support::parameter_types_thread_local! { - static ExistentialDeposit: u64 = 0; -} - #[derive(Clone, Eq, PartialEq, Debug)] pub struct Test; parameter_types! { @@ -109,6 +105,7 @@ parameter_types! { pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); + pub static ExistentialDeposit: u64 = 0; } impl frame_system::Trait for Test { type BaseCallFilter = (); diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index 09a6fef45b279..25209901109fa 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -153,6 +153,8 @@ parameter_types! { pub const CooloffPeriod: u64 = 2; pub const MaxVotes: u32 = 100; pub const MaxProposals: u32 = MAX_PROPOSALS; + pub static PreimageByteDeposit: u64 = 0; + pub static InstantAllowed: bool = false; } ord_parameter_types! { pub const One: u64 = 1; @@ -171,11 +173,6 @@ impl Contains for OneToFive { fn add(_m: &u64) {} } -frame_support::parameter_types_thread_local! { - static PreimageByteDeposit: u64 = 0; - static InstantAllowed: bool = false; -} - impl super::Trait for Test { type Proposal = Call; type Event = Event; diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 06ab7dbb95511..1fa43d929b179 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -1116,13 +1116,13 @@ mod tests { pub const CandidacyBond: u64 = 3; } - frame_support::parameter_types_thread_local! { - static VotingBond: u64 = 2; - static DesiredMembers: u32 = 2; - static DesiredRunnersUp: u32 = 2; - static TermDuration: u64 = 5; - static Members: Vec = vec![]; - static Prime: Option = None; + frame_support::parameter_types! { + pub static VotingBond: u64 = 2; + pub static DesiredMembers: u32 = 2; + pub static DesiredRunnersUp: u32 = 2; + pub static TermDuration: u64 = 5; + pub static Members: Vec = vec![]; + pub static Prime: Option = None; } pub struct TestChangeMembers; diff --git a/frame/elections/src/mock.rs b/frame/elections/src/mock.rs index 539a311bc81f5..0d57089af5ef8 100644 --- a/frame/elections/src/mock.rs +++ b/frame/elections/src/mock.rs @@ -84,14 +84,11 @@ parameter_types! { pub const InactiveGracePeriod: u32 = 1; pub const VotingPeriod: u64 = 4; pub const MinimumVotingLock: u64 = 5; -} - -frame_support::parameter_types_thread_local! { - static VotingBond: u64 = 0; - static VotingFee: u64 = 0; - static PresentSlashPerVoter: u64 = 0; - static DecayRatio: u32 = 0; - static Members: Vec = vec![]; + pub static VotingBond: u64 = 0; + pub static VotingFee: u64 = 0; + pub static PresentSlashPerVoter: u64 = 0; + pub static DecayRatio: u32 = 0; + pub static Members: Vec = vec![]; } pub struct TestChangeMembers; diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 2e465b4f704dc..06188c42b21bd 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -297,6 +297,8 @@ mod tests { pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); + pub static Members: Vec = vec![]; + pub static Prime: Option = None; } impl frame_system::Trait for Test { type BaseCallFilter = (); @@ -333,11 +335,6 @@ mod tests { pub const Five: u64 = 5; } - frame_support::parameter_types_thread_local! { - static Members: Vec = vec![]; - static Prime: Option = None; - } - pub struct TestChangeMembers; impl ChangeMembers for TestChangeMembers { fn change_members_sorted(incoming: &[u64], outgoing: &[u64], new: &[u64]) { diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 5806f8a25245b..59c0dc66cca60 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -19,6 +19,7 @@ use super::*; +use std::cell::RefCell; use frame_support::{impl_outer_origin, parameter_types, weights::Weight, ord_parameter_types}; use sp_core::H256; use sp_runtime::{ @@ -86,8 +87,8 @@ impl pallet_balances::Trait for Test { type WeightInfo = (); } -frame_support::parameter_types_thread_local! { - static Members: Vec = vec![]; +thread_local! { + pub static MEMBERS: RefCell> = RefCell::new(vec![]); } pub struct TestChangeMembers; diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index ee3532b577a47..3aa3e9ae03d74 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -133,15 +133,12 @@ parameter_types! { pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const MaxLocks: u32 = 1024; -} - -frame_support::parameter_types_thread_local! { - static SessionsPerEra: SessionIndex = 3; - static ExistentialDeposit: Balance = 0; - static SlashDeferDuration: EraIndex = 0; - static ElectionLookahead: BlockNumber = 0; - static Period: BlockNumber = 1; - static MaxIterations: u32 = 0; + pub static SessionsPerEra: SessionIndex = 3; + pub static ExistentialDeposit: Balance = 0; + pub static SlashDeferDuration: EraIndex = 0; + pub static ElectionLookahead: BlockNumber = 0; + pub static Period: BlockNumber = 1; + pub static MaxIterations: u32 = 0; } impl frame_system::Trait for Test { diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 863c884dca031..898cfe0710e17 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -85,21 +85,26 @@ pub enum Never {} /// Create new implementations of the [`Get`](crate::traits::Get) trait. /// -/// The so-called parameter type can be created in three different ways: +/// The so-called parameter type can be created in four different ways: /// -/// - Using `const` to create a parameter type that provides a `const` getter. -/// It is required that the `value` is const. +/// - Using `const` to create a parameter type that provides a `const` getter. It is required that +/// the `value` is const. /// /// - Declare the parameter type without `const` to have more freedom when creating the value. /// -/// - Using `storage` to create a storage parameter type. This type is special as it tries to -/// load the value from the storage under a fixed key. If the value could not be found in the -/// storage, the given default value will be returned. It is required that the value implements -/// [`Encode`](codec::Encode) and [`Decode`](codec::Decode). The key for looking up the value -/// in the storage is built using the following formular: +/// - Using `storage` to create a storage parameter type. This type is special as it tries to load +/// the value from the storage under a fixed key. If the value could not be found in the storage, +/// the given default value will be returned. It is required that the value implements +/// [`Encode`](codec::Encode) and [`Decode`](codec::Decode). The key for looking up the value in +/// the storage is built using the following formula: /// /// `twox_128(":" ++ NAME ++ ":")` where `NAME` is the name that is passed as type name. /// +/// - Using `static` to create a struct that implements [`Get`](crate::traits::Get) and the value is +/// being provided by a static variable with the equivalent name in `UPPER_SNAKE_CASE`. An +/// additional `set` is provided in this case to alter the static variable. **This is intended for +/// testing ONLY**. +/// /// # Examples /// /// ``` @@ -114,12 +119,14 @@ pub enum Never {} /// /// Visibility of the type is optional /// OtherArgument: u64 = non_const_expression(); /// pub storage StorageArgument: u64 = 5; +/// pub static StaticArgument: u32 = 7; /// } /// /// trait Config { /// type Parameter: Get; /// type OtherParameter: Get; /// type StorageParameter: Get; +/// type StaticParameter: Get; /// } /// /// struct Runtime; @@ -127,7 +134,10 @@ pub enum Never {} /// type Parameter = Argument; /// type OtherParameter = OtherArgument; /// type StorageParameter = StorageArgument; +/// type StaticParameter = StaticArgument; /// } +/// +/// // In testing, `StaticArgument` can be altered later: `StaticArgument::set(8)`. /// ``` /// /// # Invalid example: @@ -234,80 +244,26 @@ macro_rules! parameter_types { I::from(Self::get()) } } - } -} - -/// An implementation of [`traits::Get`] with thread local variables. -/// -/// **Useful for testing only**. A mock externalities builder can change these value on the fly. -/// -/// Accepts a syntax similar to that of [`parameter_types`], and provides an additional `set` -/// function. -/// -/// ## Example -/// -/// ``` -/// # use frame_support::traits::Get; -/// # use frame_support::parameter_types_thread_local; -/// -/// parameter_types_thread_local! { -/// static MyConfig: u32 = 10; -/// static OtherConfig: u32 = 10; -/// } -/// -/// // Generates a static variable with name `MY_CONFIG` and `OTHER_CONFIG`. -/// // Manually altering them works: -/// MY_CONFIG.with(|v| *v.borrow_mut() = 1); -/// // Or use the setter function provided: -/// MyConfig::set(2); -/// -/// // Can be passed as `Get<_>` as well. -/// trait Config { -/// type Parameter: Get; -/// } -/// -/// struct Runtime; -/// impl Config for Runtime { -/// type Parameter = MyConfig; -/// } -/// ``` -#[macro_export] -#[cfg(feature = "std")] -macro_rules! parameter_types_thread_local { + }; ( $( - static $name:ident : $type:ty = $default:expr; + $( #[ $attr:meta ] )* + $vis:vis static $name:ident: $type:ty = $value:expr; )* - ) => { - $crate::parameter_types_thread_local! { - @THREAD_LOCAL($( - $name, $type, $default, - )*) - } - - $crate::parameter_types_thread_local! { - @GETTER_STRUCT($( - $name, $type, - )*) - } - }; - (@THREAD_LOCAL($($name:ident, $type:ty, $default:expr,)*)) => { + ) => ( + #[cfg(no_std)] + compile_error!("static parameter types is only available in std and for testing."); + $crate::parameter_types!( + IMPL_THREAD_LOCAL $( $vis, $name, $type, $value, )* + ); $crate::paste::item! { - std::thread_local! { + $crate::parameter_types!( $( - pub static [<$name:snake:upper>]: std::cell::RefCell<$type> = std::cell::RefCell::new($default); + $( #[ $attr ] )* + $vis $name: $type = [<$name:snake:upper>].with(|v| v.borrow().clone()); )* - } - } - }; - (@GETTER_STRUCT($($name:ident, $type:ty,)*)) => { - $crate::paste::item! { + ); $( - /// A struct that implements [`traits::Get`] via static variables. - pub struct $name; - impl $crate::traits::Get<$type> for $name { - fn get() -> $type { [<$name:snake:upper>].with(|v| v.borrow().clone() )} - } impl $name { /// Set the internal value. pub fn set(t: $type) { @@ -316,7 +272,17 @@ macro_rules! parameter_types_thread_local { } )* } - } + ); + (IMPL_THREAD_LOCAL $( $vis:vis, $name:ident, $type:ty, $value:expr, )* ) => { + $crate::paste::item! { + thread_local! { + $( + pub static [<$name:snake:upper>]: std::cell::RefCell<$type> = + std::cell::RefCell::new($value); + )* + } + } + }; } /// Macro for easily creating a new implementation of both the `Get` and `Contains` traits. Use diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 9c4f904201d03..751aa57da0f80 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -598,17 +598,14 @@ mod tests { pub enum Origin for Runtime {} } - frame_support::parameter_types_thread_local! { - static ExtrinsicBaseWeight: u64 = 0; - static TransactionByteFee: u64 = 1; - static WeightToFee: u64 = 1; - } - parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); + pub static ExtrinsicBaseWeight: u64 = 0; + pub static TransactionByteFee: u64 = 1; + pub static WeightToFee: u64 = 1; } impl frame_system::Trait for Runtime { diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index d99265530fc59..c09516c2cc27c 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -454,6 +454,7 @@ mod tests { } parameter_types! { pub const MinVestedTransfer: u64 = 256 * 2; + pub static ExistentialDeposit: u64 = 0; } impl Trait for Test { type Event = (); @@ -466,9 +467,6 @@ mod tests { type Balances = pallet_balances::Module; type Vesting = Module; - frame_support::parameter_types_thread_local! { - static ExistentialDeposit: u64 = 0; - } pub struct ExtBuilder { existential_deposit: u64, From bd4db310f0c2e5094da875c2d7603db4f45c1e96 Mon Sep 17 00:00:00 2001 From: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Date: Tue, 17 Nov 2020 15:17:30 +0100 Subject: [PATCH 5/8] Update frame/support/src/lib.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bastian Köcher --- frame/support/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 898cfe0710e17..b100fdd954f3b 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -102,7 +102,7 @@ pub enum Never {} /// /// - Using `static` to create a struct that implements [`Get`](crate::traits::Get) and the value is /// being provided by a static variable with the equivalent name in `UPPER_SNAKE_CASE`. An -/// additional `set` is provided in this case to alter the static variable. **This is intended for +/// additional `set` function is provided in this case to alter the static variable. **This is intended for /// testing ONLY**. /// /// # Examples From 830c3e21fcddedf7dce5dd6241a703729128143e Mon Sep 17 00:00:00 2001 From: kianenigma Date: Wed, 18 Nov 2020 20:13:19 +0000 Subject: [PATCH 6/8] Align more to basti's trick --- frame/support/src/lib.rs | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 898cfe0710e17..4319c82155e0f 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -251,9 +251,33 @@ macro_rules! parameter_types { $vis:vis static $name:ident: $type:ty = $value:expr; )* ) => ( - #[cfg(no_std)] + $crate::parameter_types_impl_thread_local!( + $( + $( #[ $attr ] )* + $vis static $name: $type = $value; + )* + ); + ); +} + +#[cfg(not(feature = "std"))] +#[macro_export] +macro_rules! parameter_types_impl_thread_local { + ( $( $any:tt )* ) => { compile_error!("static parameter types is only available in std and for testing."); - $crate::parameter_types!( + }; +} + +#[cfg(feature = "std")] +#[macro_export] +macro_rules! parameter_types_impl_thread_local { + ( + $( + $( #[ $attr:meta ] )* + $vis:vis static $name:ident: $type:ty = $value:expr; + )* + ) => { + $crate::parameter_types_impl_thread_local!( IMPL_THREAD_LOCAL $( $vis, $name, $type, $value, )* ); $crate::paste::item! { @@ -272,7 +296,7 @@ macro_rules! parameter_types { } )* } - ); + }; (IMPL_THREAD_LOCAL $( $vis:vis, $name:ident, $type:ty, $value:expr, )* ) => { $crate::paste::item! { thread_local! { From 169801249d1cc7e0e606edd6dcfdf6c7f6c47c0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Fri, 20 Nov 2020 18:20:54 +0100 Subject: [PATCH 7/8] Update frame/support/src/lib.rs --- frame/support/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index f681ca6ae5590..b4dfd15d1005e 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -100,7 +100,7 @@ pub enum Never {} /// /// `twox_128(":" ++ NAME ++ ":")` where `NAME` is the name that is passed as type name. /// -/// - Using `static` to create a struct that implements [`Get`](crate::traits::Get) and the value is +/// - Using `static` to create a static parameter type. Its value is /// being provided by a static variable with the equivalent name in `UPPER_SNAKE_CASE`. An /// additional `set` function is provided in this case to alter the static variable. **This is intended for /// testing ONLY**. From 2b364496a3a4eb8db4a3a349931a6de589da40a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Fri, 20 Nov 2020 18:22:48 +0100 Subject: [PATCH 8/8] Update frame/support/src/lib.rs --- frame/support/src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index b4dfd15d1005e..5dd452dbbe7b9 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -102,8 +102,9 @@ pub enum Never {} /// /// - Using `static` to create a static parameter type. Its value is /// being provided by a static variable with the equivalent name in `UPPER_SNAKE_CASE`. An -/// additional `set` function is provided in this case to alter the static variable. **This is intended for -/// testing ONLY**. +/// additional `set` function is provided in this case to alter the static variable. +/// +/// **This is intended for testing ONLY and is ONLY available when `std` is enabled** /// /// # Examples ///