From aed1d68b2e5e523d52c3c4acfc8a00f40052c395 Mon Sep 17 00:00:00 2001 From: Tife Date: Mon, 15 Aug 2022 11:40:38 +0100 Subject: [PATCH 01/29] Edit to Assets. parameter_types --- frame/assets/src/mock.rs | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 67690e2b28ec1..aa6253f9e537d 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -20,10 +20,7 @@ use super::*; use crate as pallet_assets; -use frame_support::{ - construct_runtime, - traits::{ConstU32, ConstU64, GenesisBuild}, -}; +use frame_support::{construct_runtime, parameter_types, traits::{ConstU32, ConstU64, GenesisBuild}}; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -101,44 +98,44 @@ impl Config for Test { type Extra = (); } -use std::{cell::RefCell, collections::HashMap}; +use std::{collections::HashMap}; #[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub(crate) enum Hook { +pub enum Hook { Died(u32, u64), } -thread_local! { - static FROZEN: RefCell> = RefCell::new(Default::default()); - static HOOKS: RefCell> = RefCell::new(Default::default()); +parameter_types! { + pub static FROZEN: HashMap<(u32, u64), u64> = Default::default(); + pub static HOOKS: Vec = Default::default(); } pub struct TestFreezer; impl FrozenBalance for TestFreezer { fn frozen_balance(asset: u32, who: &u64) -> Option { - FROZEN.with(|f| f.borrow().get(&(asset, who.clone())).cloned()) + FROZEN::get().get(&(asset, who.clone())).cloned() } fn died(asset: u32, who: &u64) { - HOOKS.with(|h| h.borrow_mut().push(Hook::Died(asset, who.clone()))); + HOOKS::get().push(Hook::Died(asset, who.clone())); // Sanity check: dead accounts have no balance. assert!(Assets::balance(asset, *who).is_zero()); } } pub(crate) fn set_frozen_balance(asset: u32, who: u64, amount: u64) { - FROZEN.with(|f| f.borrow_mut().insert((asset, who), amount)); + FROZEN::get().insert((asset, who), amount); } pub(crate) fn clear_frozen_balance(asset: u32, who: u64) { - FROZEN.with(|f| f.borrow_mut().remove(&(asset, who))); + FROZEN::get().remove(&(asset, who)); } pub(crate) fn hooks() -> Vec { - HOOKS.with(|h| h.borrow().clone()) + HOOKS::get().clone() } pub(crate) fn take_hooks() -> Vec { - HOOKS.with(|h| h.take()) + HOOKS::get() } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { From 04ce047be405b628faa41092027c562199e3d6de Mon Sep 17 00:00:00 2001 From: Tife Date: Mon, 15 Aug 2022 22:33:52 +0100 Subject: [PATCH 02/29] fixes --- frame/assets/src/mock.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index aa6253f9e537d..9e850eb854752 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -116,18 +116,24 @@ impl FrozenBalance for TestFreezer { } fn died(asset: u32, who: &u64) { - HOOKS::get().push(Hook::Died(asset, who.clone())); + let mut temp = HOOKS::get(); + temp.push(Hook::Died(asset, who.clone())); + HOOKS::set(temp); // Sanity check: dead accounts have no balance. assert!(Assets::balance(asset, *who).is_zero()); } } pub(crate) fn set_frozen_balance(asset: u32, who: u64, amount: u64) { - FROZEN::get().insert((asset, who), amount); + let mut temp = FROZEN::get(); + temp.insert((asset, who), amount); + FROZEN::set(temp) } pub(crate) fn clear_frozen_balance(asset: u32, who: u64) { - FROZEN::get().remove(&(asset, who)); + let mut temp = FROZEN::get(); + temp.remove(&(asset, who)); + FROZEN::set(temp); } pub(crate) fn hooks() -> Vec { From 10626863a6d0aec5f20be8a4b4900e803e87401b Mon Sep 17 00:00:00 2001 From: Tife Date: Mon, 15 Aug 2022 23:17:53 +0100 Subject: [PATCH 03/29] Test Fixes. WIP --- frame/assets/src/mock.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 9e850eb854752..c11606304bb72 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -141,7 +141,9 @@ pub(crate) fn hooks() -> Vec { } pub(crate) fn take_hooks() -> Vec { - HOOKS::get() + let result = HOOKS::get(); + HOOKS::set(Default::default()); + result } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { From 42bbc2653b542d4a0d9a9c96fc1b6151e825ee0b Mon Sep 17 00:00:00 2001 From: Tife Date: Mon, 15 Aug 2022 23:57:25 +0100 Subject: [PATCH 04/29] Edits to pallet-aura --- frame/assets/src/mock.rs | 11 +++++++---- frame/aura/src/mock.rs | 18 ++++++++---------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index c11606304bb72..8a12a9b3a9a69 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -20,7 +20,10 @@ use super::*; use crate as pallet_assets; -use frame_support::{construct_runtime, parameter_types, traits::{ConstU32, ConstU64, GenesisBuild}}; +use frame_support::{ + construct_runtime, parameter_types, + traits::{ConstU32, ConstU64, GenesisBuild}, +}; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -98,15 +101,15 @@ impl Config for Test { type Extra = (); } -use std::{collections::HashMap}; +use std::collections::HashMap; #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum Hook { Died(u32, u64), } parameter_types! { - pub static FROZEN: HashMap<(u32, u64), u64> = Default::default(); - pub static HOOKS: Vec = Default::default(); + static FROZEN: HashMap<(u32, u64), u64> = Default::default(); + static HOOKS: Vec = Default::default(); } pub struct TestFreezer; diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 636a28692ba28..692819bb54cd9 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -30,7 +30,6 @@ use sp_runtime::{ testing::{Header, UintAuthorityId}, traits::IdentityLookup, }; -use sp_std::cell::RefCell; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -86,26 +85,25 @@ impl pallet_timestamp::Config for Test { type WeightInfo = (); } -thread_local! { - static DISABLED_VALIDATORS: RefCell> = RefCell::new(Default::default()); +parameter_types! { + static DISABLED_VALIDATORS: Vec = Default::default(); } pub struct MockDisabledValidators; impl MockDisabledValidators { pub fn disable_validator(index: AuthorityIndex) { - DISABLED_VALIDATORS.with(|v| { - let mut disabled = v.borrow_mut(); - if let Err(i) = disabled.binary_search(&index) { - disabled.insert(i, index); - } - }) + let mut disabled = DISABLED_VALIDATORS::get(); + if let Err(i) = disabled.binary_search(&index) { + disabled.insert(i, index); + } + DISABLED_VALIDATORS::set(disabled) } } impl DisabledValidators for MockDisabledValidators { fn is_disabled(index: AuthorityIndex) -> bool { - DISABLED_VALIDATORS.with(|v| v.borrow().binary_search(&index).is_ok()) + DISABLED_VALIDATORS::get().binary_search(&index).is_ok() } } From 1694082ff352aa9235d209c7eeec02d5dd50072a Mon Sep 17 00:00:00 2001 From: Boluwatife Bakre Date: Tue, 16 Aug 2022 09:50:30 +0100 Subject: [PATCH 05/29] Camel Case Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- frame/assets/src/mock.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 0b7cefc81f846..a9defb17b1950 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -108,8 +108,8 @@ pub enum Hook { Died(u32, u64), } parameter_types! { - static FROZEN: HashMap<(u32, u64), u64> = Default::default(); - static HOOKS: Vec = Default::default(); + static Frozen: HashMap<(u32, u64), u64> = Default::default(); + static Hooks: Vec = Default::default(); } pub struct TestFreezer; From d6ff5dbe6bcfedf90231ea4f4218d56d94c0b77e Mon Sep 17 00:00:00 2001 From: Tife Date: Tue, 16 Aug 2022 10:13:12 +0100 Subject: [PATCH 06/29] Implementation of mutate fn --- frame/assets/src/mock.rs | 16 +++++++--------- frame/support/src/lib.rs | 7 +++++++ 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 0b7cefc81f846..397f4a206322d 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -119,9 +119,7 @@ impl FrozenBalance for TestFreezer { } fn died(asset: u32, who: &u64) { - let mut temp = HOOKS::get(); - temp.push(Hook::Died(asset, *who)); - HOOKS::set(temp); + HOOKS::mutate(|v| v.push(Hook::Died(asset, *who))); // Sanity check: dead accounts have no balance. assert!(Assets::balance(asset, *who).is_zero()); @@ -129,15 +127,15 @@ impl FrozenBalance for TestFreezer { } pub(crate) fn set_frozen_balance(asset: u32, who: u64, amount: u64) { - let mut temp = FROZEN::get(); - temp.insert((asset, who), amount); - FROZEN::set(temp) + FROZEN::mutate(|v| { + v.insert((asset, who), amount); + }); } pub(crate) fn clear_frozen_balance(asset: u32, who: u64) { - let mut temp = FROZEN::get(); - temp.remove(&(asset, who)); - FROZEN::set(temp); + FROZEN::mutate(|v| { + v.remove(&(asset, who)); + }); } pub(crate) fn hooks() -> Vec { diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 7e4c944330fe3..5e3bd890d0d4f 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -438,6 +438,13 @@ macro_rules! parameter_types_impl_thread_local { pub fn set(t: $type) { [<$name:snake:upper>].with(|v| *v.borrow_mut() = t); } + + /// Mutate the internal value in place. + pub fn mutate ()>(mutate: F) { + let mut current = Self::get(); + mutate(&mut current); + Self::set(current); + } } )* } From 83b63045bd3590ed80b7275303009ec0dc06ebda Mon Sep 17 00:00:00 2001 From: Tife Date: Tue, 16 Aug 2022 10:22:15 +0100 Subject: [PATCH 07/29] update to pallet-aura --- frame/aura/src/mock.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 692819bb54cd9..3dedbef42cd10 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -93,11 +93,11 @@ pub struct MockDisabledValidators; impl MockDisabledValidators { pub fn disable_validator(index: AuthorityIndex) { - let mut disabled = DISABLED_VALIDATORS::get(); - if let Err(i) = disabled.binary_search(&index) { - disabled.insert(i, index); - } - DISABLED_VALIDATORS::set(disabled) + DISABLED_VALIDATORS::mutate(|v| { + if let Err(i) = v.binary_search(&index) { + v.insert(i, index); + } + }) } } @@ -118,7 +118,7 @@ pub fn new_test_ext(authorities: Vec) -> sp_io::TestExternalities { pallet_aura::GenesisConfig:: { authorities: authorities.into_iter().map(|a| UintAuthorityId(a).to_public_key()).collect(), } - .assimilate_storage(&mut t) - .unwrap(); + .assimilate_storage(&mut t) + .unwrap(); t.into() } From 2e3ff7cc0db4be960d4cbf85be67d936852c18f2 Mon Sep 17 00:00:00 2001 From: Tife Date: Tue, 16 Aug 2022 17:00:08 +0100 Subject: [PATCH 08/29] Update to frame-system. Fixes --- frame/assets/src/mock.rs | 4 ++-- frame/system/src/mock.rs | 7 +++---- frame/system/src/tests.rs | 4 ++-- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 54abb351d50ef..397f4a206322d 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -108,8 +108,8 @@ pub enum Hook { Died(u32, u64), } parameter_types! { - static Frozen: HashMap<(u32, u64), u64> = Default::default(); - static Hooks: Vec = Default::default(); + static FROZEN: HashMap<(u32, u64), u64> = Default::default(); + static HOOKS: Vec = Default::default(); } pub struct TestFreezer; diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index f3f542aa83a9a..84ae6b8bc743f 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -26,7 +26,6 @@ use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -use sp_std::cell::RefCell; type UncheckedExtrinsic = mocking::MockUncheckedExtrinsic; type Block = mocking::MockBlock; @@ -79,14 +78,14 @@ parameter_types! { limits::BlockLength::max_with_normal_ratio(1024, NORMAL_DISPATCH_RATIO); } -thread_local! { - pub static KILLED: RefCell> = RefCell::new(vec![]); +parameter_types! { + pub static KILLED: Vec = vec![]; } pub struct RecordKilled; impl OnKilledAccount for RecordKilled { fn on_killed_account(who: &u64) { - KILLED.with(|r| r.borrow_mut().push(*who)) + KILLED::mutate(|r| r.push(*who)) } } diff --git a/frame/system/src/tests.rs b/frame/system/src/tests.rs index 417dca12045ee..1ac80059671b4 100644 --- a/frame/system/src/tests.rs +++ b/frame/system/src/tests.rs @@ -55,9 +55,9 @@ fn stored_map_works() { System::dec_consumers(&0); assert!(!System::is_provider_required(&0)); - assert!(KILLED.with(|r| r.borrow().is_empty())); + assert!(KILLED::get().is_empty()); assert_ok!(System::remove(&0)); - assert_eq!(KILLED.with(|r| r.borrow().clone()), vec![0u64]); + assert_eq!(KILLED::get(), vec![0u64]); }); } From fa0adc60b208f8986726527368a450e2493553e8 Mon Sep 17 00:00:00 2001 From: Tife Date: Tue, 16 Aug 2022 18:40:11 +0100 Subject: [PATCH 09/29] Update to frame-support-test. CamelCases --- frame/assets/src/mock.rs | 18 +++++++++--------- frame/support/test/tests/construct_runtime.rs | 12 ++++++------ frame/system/src/mock.rs | 4 ++-- frame/system/src/tests.rs | 4 ++-- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 397f4a206322d..10d56dc2275f0 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -108,18 +108,18 @@ pub enum Hook { Died(u32, u64), } parameter_types! { - static FROZEN: HashMap<(u32, u64), u64> = Default::default(); - static HOOKS: Vec = Default::default(); + static Frozen: HashMap<(u32, u64), u64> = Default::default(); + static Hooks: Vec = Default::default(); } pub struct TestFreezer; impl FrozenBalance for TestFreezer { fn frozen_balance(asset: u32, who: &u64) -> Option { - FROZEN::get().get(&(asset, *who)).cloned() + Frozen::get().get(&(asset, *who)).cloned() } fn died(asset: u32, who: &u64) { - HOOKS::mutate(|v| v.push(Hook::Died(asset, *who))); + Hooks::mutate(|v| v.push(Hook::Died(asset, *who))); // Sanity check: dead accounts have no balance. assert!(Assets::balance(asset, *who).is_zero()); @@ -127,24 +127,24 @@ impl FrozenBalance for TestFreezer { } pub(crate) fn set_frozen_balance(asset: u32, who: u64, amount: u64) { - FROZEN::mutate(|v| { + Frozen::mutate(|v| { v.insert((asset, who), amount); }); } pub(crate) fn clear_frozen_balance(asset: u32, who: u64) { - FROZEN::mutate(|v| { + Frozen::mutate(|v| { v.remove(&(asset, who)); }); } pub(crate) fn hooks() -> Vec { - HOOKS::get().clone() + Hooks::get().clone() } pub(crate) fn take_hooks() -> Vec { - let result = HOOKS::get(); - HOOKS::set(Default::default()); + let result = Hooks::get(); + Hooks::set(Default::default()); result } diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index d388127f29abd..145609d8d7491 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -24,20 +24,20 @@ use codec::MaxEncodedLen; use frame_support::traits::{CrateVersion, PalletInfo as _}; use scale_info::TypeInfo; +use frame_support::parameter_types; use sp_core::{sr25519, H256}; use sp_runtime::{ generic, traits::{BlakeTwo256, Verify}, DispatchError, ModuleError, }; -use sp_std::cell::RefCell; mod system; pub trait Currency {} -thread_local! { - pub static INTEGRITY_TEST_EXEC: RefCell = RefCell::new(0); +parameter_types! { + pub static IntegrityTestExec: u32 = 0; } mod module1 { @@ -95,7 +95,7 @@ mod module2 { } fn integrity_test() { - INTEGRITY_TEST_EXEC.with(|i| *i.borrow_mut() += 1); + IntegrityTestExec::mutate(|i| *i += 1); } } } @@ -140,7 +140,7 @@ mod nested { } fn integrity_test() { - INTEGRITY_TEST_EXEC.with(|i| *i.borrow_mut() += 1); + IntegrityTestExec::mutate(|i| *i += 1); } } } @@ -377,7 +377,7 @@ fn check_modules_error_type() { #[test] fn integrity_test_works() { __construct_runtime_integrity_test::runtime_integrity_tests(); - assert_eq!(INTEGRITY_TEST_EXEC.with(|i| *i.borrow()), 2); + assert_eq!(IntegrityTestExec::get(), 2); } #[test] diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index 84ae6b8bc743f..23656252e145d 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -79,13 +79,13 @@ parameter_types! { } parameter_types! { - pub static KILLED: Vec = vec![]; + pub static Killed: Vec = vec![]; } pub struct RecordKilled; impl OnKilledAccount for RecordKilled { fn on_killed_account(who: &u64) { - KILLED::mutate(|r| r.push(*who)) + Killed::mutate(|r| r.push(*who)) } } diff --git a/frame/system/src/tests.rs b/frame/system/src/tests.rs index 1ac80059671b4..f871d7b300a4d 100644 --- a/frame/system/src/tests.rs +++ b/frame/system/src/tests.rs @@ -55,9 +55,9 @@ fn stored_map_works() { System::dec_consumers(&0); assert!(!System::is_provider_required(&0)); - assert!(KILLED::get().is_empty()); + assert!(Killed::get().is_empty()); assert_ok!(System::remove(&0)); - assert_eq!(KILLED::get(), vec![0u64]); + assert_eq!(Killed::get(), vec![0u64]); }); } From f175b7ff2df14794ebd703ce4612404e6d906308 Mon Sep 17 00:00:00 2001 From: Tife Date: Wed, 17 Aug 2022 22:58:18 +0100 Subject: [PATCH 10/29] Updates to frame- contracts, offences, staking, bounties, child bounties --- frame/bounties/src/tests.rs | 5 ++--- frame/child-bounties/src/tests.rs | 5 ++--- frame/contracts/src/exec.rs | 10 +++++----- frame/offences/src/mock.rs | 19 ++++++++++--------- frame/staking/src/mock.rs | 9 ++++----- frame/staking/src/tests.rs | 4 ++-- 6 files changed, 25 insertions(+), 27 deletions(-) diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index b4ce039b35fbc..5a66310c9ad28 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -21,7 +21,6 @@ use super::*; use crate as pallet_bounties; -use std::cell::RefCell; use frame_support::{ assert_noop, assert_ok, @@ -102,8 +101,8 @@ impl pallet_balances::Config for Test { type AccountStore = System; type WeightInfo = (); } -thread_local! { - static TEN_TO_FOURTEEN: RefCell> = RefCell::new(vec![10,11,12,13,14]); +parameter_types! { + static TentoFourteen: Vec = vec![10,11,12,13,14]; } parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); diff --git a/frame/child-bounties/src/tests.rs b/frame/child-bounties/src/tests.rs index 2584445071471..fbcd7c0d96fed 100644 --- a/frame/child-bounties/src/tests.rs +++ b/frame/child-bounties/src/tests.rs @@ -21,7 +21,6 @@ use super::*; use crate as pallet_child_bounties; -use std::cell::RefCell; use frame_support::{ assert_noop, assert_ok, @@ -105,8 +104,8 @@ impl pallet_balances::Config for Test { type AccountStore = System; type WeightInfo = (); } -thread_local! { - static TEN_TO_FOURTEEN: RefCell> = RefCell::new(vec![10,11,12,13,14]); +parameter_types! { + static TenToFourteen: Vec = vec![10,11,12,13,14]; } parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index 3b186236dd0fa..8760db6167378 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -1354,7 +1354,7 @@ mod tests { }; use assert_matches::assert_matches; use codec::{Decode, Encode}; - use frame_support::{assert_err, assert_ok}; + use frame_support::{assert_err, assert_ok, parameter_types}; use frame_system::{EventRecord, Phase}; use hex_literal::hex; use pallet_contracts_primitives::ReturnFlags; @@ -1509,14 +1509,14 @@ mod tests { #[test] fn it_works() { - thread_local! { - static TEST_DATA: RefCell> = RefCell::new(vec![0]); + parameter_types! { + static TestData: Vec = vec![0]; } let value = Default::default(); let mut gas_meter = GasMeter::::new(GAS_LIMIT); let exec_ch = MockLoader::insert(Call, |_ctx, _executable| { - TEST_DATA.with(|data| data.borrow_mut().push(1)); + TestData::mutate(|data| data.push(1)); exec_success() }); @@ -1540,7 +1540,7 @@ mod tests { ); }); - TEST_DATA.with(|data| assert_eq!(*data.borrow(), vec![0, 1])); + assert_eq!(TestData::get(), vec![0, 1]); } #[test] diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index d9ecf44ad8734..f45ea3d4bc55b 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -44,13 +44,13 @@ use std::cell::RefCell; pub struct OnOffenceHandler; -thread_local! { - pub static ON_OFFENCE_PERBILL: RefCell> = RefCell::new(Default::default()); - pub static OFFENCE_WEIGHT: RefCell = RefCell::new(Default::default()); +parameter_types! { + pub static OnOffencePerBill: Vec = Default::default(); + pub static OffenceWeight: Weight = Default::default(); } impl offence::OnOffenceHandler - for OnOffenceHandler +for OnOffenceHandler { fn on_offence( _offenders: &[OffenceDetails], @@ -58,16 +58,17 @@ impl offence::OnOffenceHandler _offence_session: SessionIndex, _disable_strategy: DisableStrategy, ) -> Weight { - ON_OFFENCE_PERBILL.with(|f| { - *f.borrow_mut() = slash_fraction.to_vec(); + OnOffencePerBill::mutate(|f| { + *f = slash_fraction.to_vec(); }); - OFFENCE_WEIGHT.with(|w| *w.borrow()) + OffenceWeight::get() } } -pub fn with_on_offence_fractions) -> R>(f: F) -> R { - ON_OFFENCE_PERBILL.with(|fractions| f(&mut fractions.borrow_mut())) +pub fn with_on_offence_fractions) -> R>(f: F) -> Vec { + OnOffencePerBill::mutate(|fractions| { f(fractions);}); + OnOffencePerBill::get() } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 7911428b3337c..cdad11589f743 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -37,7 +37,6 @@ use sp_runtime::{ traits::{IdentityLookup, Zero}, }; use sp_staking::offence::{DisableStrategy, OffenceDetails, OnOffenceHandler}; -use std::cell::RefCell; pub const INIT_TIMESTAMP: u64 = 30_000; pub const BLOCK_TIME: u64 = 1000; @@ -216,16 +215,16 @@ parameter_types! { pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(75); } -thread_local! { - pub static REWARD_REMAINDER_UNBALANCED: RefCell = RefCell::new(0); +parameter_types! { + pub static RewardRemainderUnbalanced: u128 = 0; } pub struct RewardRemainderMock; impl OnUnbalanced> for RewardRemainderMock { fn on_nonzero_unbalanced(amount: NegativeImbalanceOf) { - REWARD_REMAINDER_UNBALANCED.with(|v| { - *v.borrow_mut() += amount.peek(); + RewardRemainderUnbalanced::mutate(|v| { + *v += amount.peek(); }); drop(amount); } diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 485a9dc3ae66a..274ead2fd993b 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -302,7 +302,7 @@ fn rewards_should_work() { assert_eq!(active_era(), 1); assert_eq!( - mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()), + mock::RewardRemainderUnbalanced::get(), maximum_payout - total_payout_0, ); assert_eq!( @@ -340,7 +340,7 @@ fn rewards_should_work() { mock::start_active_era(2); assert_eq!( - mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()), + mock::RewardRemainderUnbalanced::get(), maximum_payout * 2 - total_payout_0 - total_payout_1, ); assert_eq!( From 46f12c3dd794f505239227381dbdb683307869bc Mon Sep 17 00:00:00 2001 From: Tife Date: Thu, 18 Aug 2022 17:30:04 +0100 Subject: [PATCH 11/29] Edit to mutate fn. Changes to frame-contracts. CamelCase pallet-aura --- frame/aura/src/mock.rs | 6 +++--- frame/contracts/src/exec.rs | 20 ++++++++------------ frame/offences/src/mock.rs | 6 +++--- frame/support/src/lib.rs | 5 +++-- 4 files changed, 17 insertions(+), 20 deletions(-) diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 3dedbef42cd10..e172e8500450f 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -86,14 +86,14 @@ impl pallet_timestamp::Config for Test { } parameter_types! { - static DISABLED_VALIDATORS: Vec = Default::default(); + static DisabledValidatorTestValue: Vec = Default::default(); } pub struct MockDisabledValidators; impl MockDisabledValidators { pub fn disable_validator(index: AuthorityIndex) { - DISABLED_VALIDATORS::mutate(|v| { + DisabledValidatorTestValue::mutate(|v| { if let Err(i) = v.binary_search(&index) { v.insert(i, index); } @@ -103,7 +103,7 @@ impl MockDisabledValidators { impl DisabledValidators for MockDisabledValidators { fn is_disabled(index: AuthorityIndex) -> bool { - DISABLED_VALIDATORS::get().binary_search(&index).is_ok() + DisabledValidatorTestValue::get().binary_search(&index).is_ok() } } diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index 8760db6167378..d60577dddfe3a 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -1371,8 +1371,8 @@ mod tests { type MockStack<'a> = Stack<'a, Test, MockExecutable>; - thread_local! { - static LOADER: RefCell = RefCell::new(MockLoader::default()); + parameter_types! { + static Loader: MockLoader = MockLoader::default(); } fn events() -> Vec> { @@ -1398,8 +1398,8 @@ mod tests { refcount: u64, } - #[derive(Default)] - struct MockLoader { + #[derive(Default, Clone)] + pub struct MockLoader { map: HashMap, MockExecutable>, counter: u64, } @@ -1409,8 +1409,7 @@ mod tests { func_type: ExportedFunction, f: impl Fn(MockCtx, &MockExecutable) -> ExecResult + 'static, ) -> CodeHash { - LOADER.with(|loader| { - let mut loader = loader.borrow_mut(); + Loader::mutate(|loader| { // Generate code hashes as monotonically increasing values. let hash = ::Hash::from_low_u64_be(loader.counter); loader.counter += 1; @@ -1423,8 +1422,7 @@ mod tests { } fn increment_refcount(code_hash: CodeHash) -> Result<(), DispatchError> { - LOADER.with(|loader| { - let mut loader = loader.borrow_mut(); + Loader::mutate(|loader| { match loader.map.entry(code_hash) { Entry::Vacant(_) => Err(>::CodeNotFound)?, Entry::Occupied(mut entry) => entry.get_mut().refcount += 1, @@ -1435,8 +1433,7 @@ mod tests { fn decrement_refcount(code_hash: CodeHash) { use std::collections::hash_map::Entry::Occupied; - LOADER.with(|loader| { - let mut loader = loader.borrow_mut(); + Loader::mutate(|loader| { let mut entry = match loader.map.entry(code_hash) { Occupied(e) => e, _ => panic!("code_hash does not exist"), @@ -1456,9 +1453,8 @@ mod tests { _schedule: &Schedule, _gas_meter: &mut GasMeter, ) -> Result { - LOADER.with(|loader| { + Loader::mutate(|loader| { loader - .borrow_mut() .map .get(&code_hash) .cloned() diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index f45ea3d4bc55b..399edb3926d82 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -66,9 +66,9 @@ for OnOffenceHandler } } -pub fn with_on_offence_fractions) -> R>(f: F) -> Vec { - OnOffencePerBill::mutate(|fractions| { f(fractions);}); - OnOffencePerBill::get() +pub fn with_on_offence_fractions) -> R>(f: F) -> R { + OnOffencePerBill::mutate(|fractions| f(fractions)) + //OnOffencePerBill::get() } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 5e3bd890d0d4f..12e7ce2dc5d70 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -440,10 +440,11 @@ macro_rules! parameter_types_impl_thread_local { } /// Mutate the internal value in place. - pub fn mutate ()>(mutate: F) { + pub fn mutate R>(mutate: F) -> R{ let mut current = Self::get(); - mutate(&mut current); + let result = mutate(&mut current); Self::set(current); + result } } )* From b8587c2320ef5b8e80efa14b37f6c03e4f208dde Mon Sep 17 00:00:00 2001 From: Tife Date: Fri, 19 Aug 2022 00:28:47 +0100 Subject: [PATCH 12/29] Edits to frame-contracts & executive --- frame/contracts/src/exec.rs | 25 +++++++-------- frame/contracts/src/storage/meter.rs | 48 ++++++++++++---------------- frame/contracts/src/tests.rs | 31 +++++++++--------- frame/executive/src/lib.rs | 44 ++++++++++++------------- frame/offences/src/mock.rs | 1 - 5 files changed, 71 insertions(+), 78 deletions(-) diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index d60577dddfe3a..95822982ce21b 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -1815,16 +1815,15 @@ mod tests { fn max_depth() { // This test verifies that when we reach the maximal depth creation of an // yet another context fails. - thread_local! { - static REACHED_BOTTOM: RefCell = RefCell::new(false); + parameter_types! { + static ReachedBottom: bool = false; } let value = Default::default(); let recurse_ch = MockLoader::insert(Call, |ctx, _| { // Try to call into yourself. let r = ctx.ext.call(0, BOB, 0, vec![], true); - REACHED_BOTTOM.with(|reached_bottom| { - let mut reached_bottom = reached_bottom.borrow_mut(); + ReachedBottom::mutate(|reached_bottom| { if !*reached_bottom { // We are first time here, it means we just reached bottom. // Verify that we've got proper error and set `reached_bottom`. @@ -1865,15 +1864,15 @@ mod tests { let origin = ALICE; let dest = BOB; - thread_local! { - static WITNESSED_CALLER_BOB: RefCell>> = RefCell::new(None); - static WITNESSED_CALLER_CHARLIE: RefCell>> = RefCell::new(None); + parameter_types! { + static WitnessedCallerBob: Option> = None; + static WitnessedCallerCharlie: Option> = None; } let bob_ch = MockLoader::insert(Call, |ctx, _| { // Record the caller for bob. - WITNESSED_CALLER_BOB - .with(|caller| *caller.borrow_mut() = Some(ctx.ext.caller().clone())); + WitnessedCallerBob + ::mutate(|caller| *caller = Some(ctx.ext.caller().clone())); // Call into CHARLIE contract. assert_matches!(ctx.ext.call(0, CHARLIE, 0, vec![], true), Ok(_)); @@ -1881,8 +1880,8 @@ mod tests { }); let charlie_ch = MockLoader::insert(Call, |ctx, _| { // Record the caller for charlie. - WITNESSED_CALLER_CHARLIE - .with(|caller| *caller.borrow_mut() = Some(ctx.ext.caller().clone())); + WitnessedCallerCharlie + ::mutate(|caller| *caller = Some(ctx.ext.caller().clone())); exec_success() }); @@ -1906,8 +1905,8 @@ mod tests { assert_matches!(result, Ok(_)); }); - WITNESSED_CALLER_BOB.with(|caller| assert_eq!(*caller.borrow(), Some(origin))); - WITNESSED_CALLER_CHARLIE.with(|caller| assert_eq!(*caller.borrow(), Some(dest))); + assert_eq!(WitnessedCallerBob::get(), Some(origin)); + assert_eq!(WitnessedCallerCharlie::get(), Some(dest)); } #[test] diff --git a/frame/contracts/src/storage/meter.rs b/frame/contracts/src/storage/meter.rs index b06f7ea4aedb5..e8d12c3d502a6 100644 --- a/frame/contracts/src/storage/meter.rs +++ b/frame/contracts/src/storage/meter.rs @@ -442,22 +442,22 @@ mod tests { tests::{Test, ALICE, BOB, CHARLIE}, }; use pretty_assertions::assert_eq; - use std::cell::RefCell; + use frame_support::parameter_types; type TestMeter = RawMeter; - thread_local! { - static TEST_EXT: RefCell = RefCell::new(Default::default()); + parameter_types! { + static TestExtTestValue: TestExt = Default::default(); } - #[derive(Debug, PartialEq, Eq)] + #[derive(Debug, PartialEq, Eq, Clone)] struct LimitCheck { origin: AccountIdOf, limit: BalanceOf, min_leftover: BalanceOf, } - #[derive(Debug, PartialEq, Eq)] + #[derive(Debug, PartialEq, Eq, Clone)] struct Charge { origin: AccountIdOf, contract: AccountIdOf, @@ -465,8 +465,8 @@ mod tests { terminated: bool, } - #[derive(Default, Debug, PartialEq, Eq)] - struct TestExt { + #[derive(Default, Debug, PartialEq, Eq, Clone)] + pub struct TestExt { limit_checks: Vec, charges: Vec, } @@ -485,8 +485,8 @@ mod tests { min_leftover: BalanceOf, ) -> Result, DispatchError> { let limit = limit.unwrap_or(42); - TEST_EXT.with(|ext| { - ext.borrow_mut().limit_checks.push(LimitCheck { + TestExtTestValue::mutate(|ext| { + ext.limit_checks.push(LimitCheck { origin: origin.clone(), limit, min_leftover, @@ -501,8 +501,8 @@ mod tests { amount: &DepositOf, terminated: bool, ) { - TEST_EXT.with(|ext| { - ext.borrow_mut().charges.push(Charge { + TestExtTestValue::mutate(|ext| { + ext.charges.push(Charge { origin: origin.clone(), contract: contract.clone(), amount: amount.clone(), @@ -513,7 +513,7 @@ mod tests { } fn clear_ext() { - TEST_EXT.with(|ext| ext.borrow_mut().clear()) + TestExtTestValue::mutate(|ext| ext.clear()) } fn new_info(deposit: BalanceOf) -> ContractInfo { @@ -533,15 +533,15 @@ mod tests { TestMeter::new(&ALICE, Some(1_000), 0).unwrap(); - TEST_EXT.with(|ext| { + assert_eq!( - *ext.borrow(), + TestExtTestValue::get(), TestExt { limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], ..Default::default() } ) - }); + } #[test] @@ -556,15 +556,14 @@ mod tests { nested0.charge(&Default::default()).unwrap(); meter.absorb(nested0, &ALICE, &BOB, None); - TEST_EXT.with(|ext| { assert_eq!( - *ext.borrow(), + TestExtTestValue::get(), TestExt { limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], ..Default::default() } ) - }); + } #[test] @@ -582,9 +581,8 @@ mod tests { .unwrap(); meter.absorb(nested0, &ALICE, &BOB, None); - TEST_EXT.with(|ext| { assert_eq!( - *ext.borrow(), + TestExtTestValue::get(), TestExt { limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], charges: vec![Charge { @@ -595,7 +593,7 @@ mod tests { }] } ) - }); + } #[test] @@ -638,9 +636,8 @@ mod tests { assert_eq!(nested1_info.storage_deposit, 40); assert_eq!(nested2_info.storage_deposit, min_balance); - TEST_EXT.with(|ext| { assert_eq!( - *ext.borrow(), + TestExtTestValue::get(), TestExt { limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], charges: vec![ @@ -665,7 +662,6 @@ mod tests { ] } ) - }); } #[test] @@ -697,9 +693,8 @@ mod tests { meter.absorb(nested0, &ALICE, &BOB, None); drop(meter); - TEST_EXT.with(|ext| { assert_eq!( - *ext.borrow(), + TestExtTestValue::get(), TestExt { limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], charges: vec![ @@ -718,6 +713,5 @@ mod tests { ] } ) - }); } } diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 204908cc4a989..f9864a29516c5 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -108,10 +108,11 @@ pub mod test_utils { } } -thread_local! { - static TEST_EXTENSION: RefCell = Default::default(); +parameter_types! { + static TestExtensionsTestValue: TestExtension = Default::default(); } +#[derive(Clone)] pub struct TestExtension { enabled: bool, last_seen_buffer: Vec, @@ -131,15 +132,15 @@ pub struct TempStorageExtension { impl TestExtension { fn disable() { - TEST_EXTENSION.with(|e| e.borrow_mut().enabled = false) + TestExtensionsTestValue::mutate(|e| e.enabled = false) } fn last_seen_buffer() -> Vec { - TEST_EXTENSION.with(|e| e.borrow().last_seen_buffer.clone()) + TestExtensionsTestValue::get().last_seen_buffer.clone() } fn last_seen_inputs() -> (u32, u32, u32, u32) { - TEST_EXTENSION.with(|e| e.borrow().last_seen_inputs) + TestExtensionsTestValue::get().last_seen_inputs } } @@ -162,13 +163,13 @@ impl ChainExtension for TestExtension { let mut env = env.buf_in_buf_out(); let input = env.read(8)?; env.write(&input, false, None)?; - TEST_EXTENSION.with(|e| e.borrow_mut().last_seen_buffer = input); + TestExtensionsTestValue::mutate(|e| e.last_seen_buffer = input); Ok(RetVal::Converging(id)) }, 0x8001 => { let env = env.only_in(); - TEST_EXTENSION.with(|e| { - e.borrow_mut().last_seen_inputs = + TestExtensionsTestValue::mutate(|e| { + e.last_seen_inputs = (env.val0(), env.val1(), env.val2(), env.val3()) }); Ok(RetVal::Converging(id)) @@ -187,7 +188,7 @@ impl ChainExtension for TestExtension { } fn enabled() -> bool { - TEST_EXTENSION.with(|e| e.borrow().enabled) + TestExtensionsTestValue::get().enabled } } @@ -205,7 +206,7 @@ impl ChainExtension for RevertingExtension { } fn enabled() -> bool { - TEST_EXTENSION.with(|e| e.borrow().enabled) + TestExtensionsTestValue::get().enabled } } @@ -254,7 +255,7 @@ impl ChainExtension for TempStorageExtension { } fn enabled() -> bool { - TEST_EXTENSION.with(|e| e.borrow().enabled) + TestExtensionsTestValue::get().enabled } } @@ -339,19 +340,19 @@ impl Convert> for Test { /// A filter whose filter function can be swapped at runtime. pub struct TestFilter; -thread_local! { - static CALL_FILTER: RefCell bool> = RefCell::new(|_| true); +parameter_types! { + static CallFilterTestValue: fn(&Call) -> bool = (|_| true); } impl TestFilter { pub fn set_filter(filter: fn(&Call) -> bool) { - CALL_FILTER.with(|fltr| *fltr.borrow_mut() = filter); + CallFilterTestValue::mutate(|fltr| *fltr= filter); } } impl Contains for TestFilter { fn contains(call: &Call) -> bool { - CALL_FILTER.with(|fltr| fltr.borrow()(call)) + CallFilterTestValue::get()(call) } } diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index cd3e1c500db26..6062d6233df8c 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -786,12 +786,12 @@ mod tests { pub struct RuntimeVersion; impl frame_support::traits::Get for RuntimeVersion { fn get() -> sp_version::RuntimeVersion { - RUNTIME_VERSION.with(|v| v.borrow().clone()) + RuntimeVersionTestValues::get().clone() } } - thread_local! { - pub static RUNTIME_VERSION: std::cell::RefCell = + parameter_types! { + pub static RuntimeVersionTestValues: sp_version::RuntimeVersion = Default::default(); } @@ -1187,13 +1187,13 @@ mod tests { #[test] fn runtime_upgraded_should_work() { new_test_ext(1).execute_with(|| { - RUNTIME_VERSION.with(|v| *v.borrow_mut() = Default::default()); + RuntimeVersionTestValues::mutate(|v| *v = Default::default()); // It should be added at genesis assert!(frame_system::LastRuntimeUpgrade::::exists()); assert!(!Executive::runtime_upgraded()); - RUNTIME_VERSION.with(|v| { - *v.borrow_mut() = + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); assert!(Executive::runtime_upgraded()); @@ -1202,8 +1202,8 @@ mod tests { frame_system::LastRuntimeUpgrade::::get(), ); - RUNTIME_VERSION.with(|v| { - *v.borrow_mut() = sp_version::RuntimeVersion { + RuntimeVersionTestValues::mutate(|v| { + *v= sp_version::RuntimeVersion { spec_version: 1, spec_name: "test".into(), ..Default::default() @@ -1215,8 +1215,8 @@ mod tests { frame_system::LastRuntimeUpgrade::::get(), ); - RUNTIME_VERSION.with(|v| { - *v.borrow_mut() = sp_version::RuntimeVersion { + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, spec_name: "test".into(), impl_version: 2, @@ -1264,8 +1264,8 @@ mod tests { fn custom_runtime_upgrade_is_called_before_modules() { new_test_ext(1).execute_with(|| { // Make sure `on_runtime_upgrade` is called. - RUNTIME_VERSION.with(|v| { - *v.borrow_mut() = + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); @@ -1286,8 +1286,8 @@ mod tests { fn event_from_runtime_upgrade_is_included() { new_test_ext(1).execute_with(|| { // Make sure `on_runtime_upgrade` is called. - RUNTIME_VERSION.with(|v| { - *v.borrow_mut() = + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); @@ -1317,8 +1317,8 @@ mod tests { let header = new_test_ext(1).execute_with(|| { // Make sure `on_runtime_upgrade` is called. - RUNTIME_VERSION.with(|v| { - *v.borrow_mut() = + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); @@ -1337,14 +1337,14 @@ mod tests { }); // Reset to get the correct new genesis below. - RUNTIME_VERSION.with(|v| { - *v.borrow_mut() = sp_version::RuntimeVersion { spec_version: 0, ..Default::default() } + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 0, ..Default::default() } }); new_test_ext(1).execute_with(|| { // Make sure `on_runtime_upgrade` is called. - RUNTIME_VERSION.with(|v| { - *v.borrow_mut() = + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); @@ -1359,8 +1359,8 @@ mod tests { fn all_weights_are_recorded_correctly() { new_test_ext(1).execute_with(|| { // Make sure `on_runtime_upgrade` is called for maximum complexity - RUNTIME_VERSION.with(|v| { - *v.borrow_mut() = + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index 399edb3926d82..62d364ecda1dd 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -68,7 +68,6 @@ for OnOffenceHandler pub fn with_on_offence_fractions) -> R>(f: F) -> R { OnOffencePerBill::mutate(|fractions| f(fractions)) - //OnOffencePerBill::get() } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; From 603929df3286e92fe25a55af0535e116c57ac2fc Mon Sep 17 00:00:00 2001 From: Tife Date: Fri, 19 Aug 2022 00:33:01 +0100 Subject: [PATCH 13/29] cargo +nightly fmt --- frame/aura/src/mock.rs | 4 +- frame/contracts/src/exec.rs | 12 +- frame/contracts/src/storage/meter.rs | 157 +++++++++--------- frame/contracts/src/tests.rs | 5 +- frame/executive/src/lib.rs | 20 +-- frame/offences/src/mock.rs | 2 +- frame/staking/src/tests.rs | 5 +- frame/support/test/tests/construct_runtime.rs | 6 +- 8 files changed, 95 insertions(+), 116 deletions(-) diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index e172e8500450f..ad3a05ec3f7ea 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -118,7 +118,7 @@ pub fn new_test_ext(authorities: Vec) -> sp_io::TestExternalities { pallet_aura::GenesisConfig:: { authorities: authorities.into_iter().map(|a| UintAuthorityId(a).to_public_key()).collect(), } - .assimilate_storage(&mut t) - .unwrap(); + .assimilate_storage(&mut t) + .unwrap(); t.into() } diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index 95822982ce21b..52c8e6ef0dc57 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -1454,11 +1454,7 @@ mod tests { _gas_meter: &mut GasMeter, ) -> Result { Loader::mutate(|loader| { - loader - .map - .get(&code_hash) - .cloned() - .ok_or(Error::::CodeNotFound.into()) + loader.map.get(&code_hash).cloned().ok_or(Error::::CodeNotFound.into()) }) } @@ -1871,8 +1867,7 @@ mod tests { let bob_ch = MockLoader::insert(Call, |ctx, _| { // Record the caller for bob. - WitnessedCallerBob - ::mutate(|caller| *caller = Some(ctx.ext.caller().clone())); + WitnessedCallerBob::mutate(|caller| *caller = Some(ctx.ext.caller().clone())); // Call into CHARLIE contract. assert_matches!(ctx.ext.call(0, CHARLIE, 0, vec![], true), Ok(_)); @@ -1880,8 +1875,7 @@ mod tests { }); let charlie_ch = MockLoader::insert(Call, |ctx, _| { // Record the caller for charlie. - WitnessedCallerCharlie - ::mutate(|caller| *caller = Some(ctx.ext.caller().clone())); + WitnessedCallerCharlie::mutate(|caller| *caller = Some(ctx.ext.caller().clone())); exec_success() }); diff --git a/frame/contracts/src/storage/meter.rs b/frame/contracts/src/storage/meter.rs index e8d12c3d502a6..d89208812bcac 100644 --- a/frame/contracts/src/storage/meter.rs +++ b/frame/contracts/src/storage/meter.rs @@ -441,8 +441,8 @@ mod tests { exec::AccountIdOf, tests::{Test, ALICE, BOB, CHARLIE}, }; - use pretty_assertions::assert_eq; use frame_support::parameter_types; + use pretty_assertions::assert_eq; type TestMeter = RawMeter; @@ -486,11 +486,8 @@ mod tests { ) -> Result, DispatchError> { let limit = limit.unwrap_or(42); TestExtTestValue::mutate(|ext| { - ext.limit_checks.push(LimitCheck { - origin: origin.clone(), - limit, - min_leftover, - }) + ext.limit_checks + .push(LimitCheck { origin: origin.clone(), limit, min_leftover }) }); Ok(limit) } @@ -533,15 +530,13 @@ mod tests { TestMeter::new(&ALICE, Some(1_000), 0).unwrap(); - - assert_eq!( - TestExtTestValue::get(), - TestExt { - limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], - ..Default::default() - } - ) - + assert_eq!( + TestExtTestValue::get(), + TestExt { + limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], + ..Default::default() + } + ) } #[test] @@ -556,14 +551,13 @@ mod tests { nested0.charge(&Default::default()).unwrap(); meter.absorb(nested0, &ALICE, &BOB, None); - assert_eq!( - TestExtTestValue::get(), - TestExt { - limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], - ..Default::default() - } - ) - + assert_eq!( + TestExtTestValue::get(), + TestExt { + limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], + ..Default::default() + } + ) } #[test] @@ -581,19 +575,18 @@ mod tests { .unwrap(); meter.absorb(nested0, &ALICE, &BOB, None); - assert_eq!( - TestExtTestValue::get(), - TestExt { - limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], - charges: vec![Charge { - origin: ALICE, - contract: BOB, - amount: Deposit::Charge(::Currency::minimum_balance() * 2), - terminated: false, - }] - } - ) - + assert_eq!( + TestExtTestValue::get(), + TestExt { + limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], + charges: vec![Charge { + origin: ALICE, + contract: BOB, + amount: Deposit::Charge(::Currency::minimum_balance() * 2), + terminated: false, + }] + } + ) } #[test] @@ -636,32 +629,32 @@ mod tests { assert_eq!(nested1_info.storage_deposit, 40); assert_eq!(nested2_info.storage_deposit, min_balance); - assert_eq!( - TestExtTestValue::get(), - TestExt { - limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], - charges: vec![ - Charge { - origin: ALICE, - contract: CHARLIE, - amount: Deposit::Refund(10), - terminated: false - }, - Charge { - origin: ALICE, - contract: CHARLIE, - amount: Deposit::Refund(4), - terminated: false - }, - Charge { - origin: ALICE, - contract: BOB, - amount: Deposit::Charge(2), - terminated: false - } - ] - } - ) + assert_eq!( + TestExtTestValue::get(), + TestExt { + limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], + charges: vec![ + Charge { + origin: ALICE, + contract: CHARLIE, + amount: Deposit::Refund(10), + terminated: false + }, + Charge { + origin: ALICE, + contract: CHARLIE, + amount: Deposit::Refund(4), + terminated: false + }, + Charge { + origin: ALICE, + contract: BOB, + amount: Deposit::Charge(2), + terminated: false + } + ] + } + ) } #[test] @@ -693,25 +686,25 @@ mod tests { meter.absorb(nested0, &ALICE, &BOB, None); drop(meter); - assert_eq!( - TestExtTestValue::get(), - TestExt { - limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], - charges: vec![ - Charge { - origin: ALICE, - contract: CHARLIE, - amount: Deposit::Refund(400), - terminated: true - }, - Charge { - origin: ALICE, - contract: BOB, - amount: Deposit::Charge(12), - terminated: false - } - ] - } - ) + assert_eq!( + TestExtTestValue::get(), + TestExt { + limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], + charges: vec![ + Charge { + origin: ALICE, + contract: CHARLIE, + amount: Deposit::Refund(400), + terminated: true + }, + Charge { + origin: ALICE, + contract: BOB, + amount: Deposit::Charge(12), + terminated: false + } + ] + } + ) } } diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index f9864a29516c5..2d922d587332c 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -169,8 +169,7 @@ impl ChainExtension for TestExtension { 0x8001 => { let env = env.only_in(); TestExtensionsTestValue::mutate(|e| { - e.last_seen_inputs = - (env.val0(), env.val1(), env.val2(), env.val3()) + e.last_seen_inputs = (env.val0(), env.val1(), env.val2(), env.val3()) }); Ok(RetVal::Converging(id)) }, @@ -346,7 +345,7 @@ parameter_types! { impl TestFilter { pub fn set_filter(filter: fn(&Call) -> bool) { - CallFilterTestValue::mutate(|fltr| *fltr= filter); + CallFilterTestValue::mutate(|fltr| *fltr = filter); } } diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 6062d6233df8c..f0c29c41b2ed5 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -1193,8 +1193,7 @@ mod tests { assert!(!Executive::runtime_upgraded()); RuntimeVersionTestValues::mutate(|v| { - *v = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); assert!(Executive::runtime_upgraded()); assert_eq!( @@ -1203,7 +1202,7 @@ mod tests { ); RuntimeVersionTestValues::mutate(|v| { - *v= sp_version::RuntimeVersion { + *v = sp_version::RuntimeVersion { spec_version: 1, spec_name: "test".into(), ..Default::default() @@ -1265,8 +1264,7 @@ mod tests { new_test_ext(1).execute_with(|| { // Make sure `on_runtime_upgrade` is called. RuntimeVersionTestValues::mutate(|v| { - *v = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); Executive::initialize_block(&Header::new( @@ -1287,8 +1285,7 @@ mod tests { new_test_ext(1).execute_with(|| { // Make sure `on_runtime_upgrade` is called. RuntimeVersionTestValues::mutate(|v| { - *v = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); // set block number to non zero so events are not excluded @@ -1318,8 +1315,7 @@ mod tests { let header = new_test_ext(1).execute_with(|| { // Make sure `on_runtime_upgrade` is called. RuntimeVersionTestValues::mutate(|v| { - *v = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); // Let's build some fake block. @@ -1344,8 +1340,7 @@ mod tests { new_test_ext(1).execute_with(|| { // Make sure `on_runtime_upgrade` is called. RuntimeVersionTestValues::mutate(|v| { - *v = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); >>::execute_block(Block::new(header, vec![xt])); @@ -1360,8 +1355,7 @@ mod tests { new_test_ext(1).execute_with(|| { // Make sure `on_runtime_upgrade` is called for maximum complexity RuntimeVersionTestValues::mutate(|v| { - *v = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); let block_number = 1; diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index 62d364ecda1dd..11ef1fe2050ae 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -50,7 +50,7 @@ parameter_types! { } impl offence::OnOffenceHandler -for OnOffenceHandler + for OnOffenceHandler { fn on_offence( _offenders: &[OffenceDetails], diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 274ead2fd993b..8b4daecfab9b6 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -301,10 +301,7 @@ fn rewards_should_work() { start_session(3); assert_eq!(active_era(), 1); - assert_eq!( - mock::RewardRemainderUnbalanced::get(), - maximum_payout - total_payout_0, - ); + assert_eq!(mock::RewardRemainderUnbalanced::get(), maximum_payout - total_payout_0,); assert_eq!( *mock::staking_events().last().unwrap(), Event::EraPaid(0, total_payout_0, maximum_payout - total_payout_0) diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 145609d8d7491..87dc7ac8524ab 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -22,9 +22,11 @@ #![recursion_limit = "128"] use codec::MaxEncodedLen; -use frame_support::traits::{CrateVersion, PalletInfo as _}; +use frame_support::{ + parameter_types, + traits::{CrateVersion, PalletInfo as _}, +}; use scale_info::TypeInfo; -use frame_support::parameter_types; use sp_core::{sr25519, H256}; use sp_runtime::{ generic, From 1055fe60741f5e7adc8859faa0b1ca9bbecd839d Mon Sep 17 00:00:00 2001 From: Tife Date: Fri, 19 Aug 2022 00:41:28 +0100 Subject: [PATCH 14/29] unused import removed --- frame/offences/src/mock.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index 11ef1fe2050ae..1bf59e3c80158 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -40,7 +40,6 @@ use sp_staking::{ offence::{self, DisableStrategy, Kind, OffenceDetails}, SessionIndex, }; -use std::cell::RefCell; pub struct OnOffenceHandler; From 36bd120996bbd569e96b79b71e14c3653e3a7336 Mon Sep 17 00:00:00 2001 From: Tife Date: Fri, 19 Aug 2022 00:48:48 +0100 Subject: [PATCH 15/29] unused import removed --- frame/contracts/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 2d922d587332c..52f33f150e71a 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -50,7 +50,7 @@ use sp_runtime::{ traits::{BlakeTwo256, Convert, Hash, IdentityLookup}, AccountId32, }; -use std::{cell::RefCell, sync::Arc}; +use std:: sync::Arc; use crate as pallet_contracts; From 8cdbdf8cd7f1fd27d7cb6c989b13ae53946de430 Mon Sep 17 00:00:00 2001 From: Tife Date: Fri, 19 Aug 2022 00:58:46 +0100 Subject: [PATCH 16/29] cargo +nightly fmt --- frame/contracts/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 52f33f150e71a..a999dc2129f31 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -50,7 +50,7 @@ use sp_runtime::{ traits::{BlakeTwo256, Convert, Hash, IdentityLookup}, AccountId32, }; -use std:: sync::Arc; +use std::sync::Arc; use crate as pallet_contracts; From d7cd7a0d74fa1814c9861dd50503c9dab31ba1a7 Mon Sep 17 00:00:00 2001 From: Tife Date: Fri, 19 Aug 2022 11:31:26 +0100 Subject: [PATCH 17/29] minor adjustment --- frame/contracts/src/tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index a999dc2129f31..424bfd0125aa1 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -340,18 +340,18 @@ impl Convert> for Test { pub struct TestFilter; parameter_types! { - static CallFilterTestValue: fn(&Call) -> bool = (|_| true); + static CallFilter: fn(&Call) -> bool = (|_| true); } impl TestFilter { pub fn set_filter(filter: fn(&Call) -> bool) { - CallFilterTestValue::mutate(|fltr| *fltr = filter); + CallFilter::mutate(|fltr| *fltr = filter); } } impl Contains for TestFilter { fn contains(call: &Call) -> bool { - CallFilterTestValue::get()(call) + CallFilter::get()(call) } } From 7c166882a4b4502fc66454f90df21c8ff82b3cf8 Mon Sep 17 00:00:00 2001 From: Tife Date: Fri, 19 Aug 2022 22:24:03 +0100 Subject: [PATCH 18/29] updates --- frame/bounties/src/tests.rs | 3 - frame/child-bounties/src/tests.rs | 3 - frame/im-online/src/mock.rs | 32 +++++---- frame/im-online/src/tests.rs | 46 ++++++------- frame/merkle-mountain-range/src/mock.rs | 9 +-- frame/merkle-mountain-range/src/tests.rs | 2 +- frame/scheduler/src/mock.rs | 16 ++--- frame/scored-pool/src/mock.rs | 11 ++-- frame/scored-pool/src/tests.rs | 10 +-- frame/session/src/historical/mod.rs | 7 +- frame/session/src/historical/offchain.rs | 8 +-- frame/session/src/mock.rs | 84 ++++++++++++------------ frame/session/src/tests.rs | 12 ++-- frame/tips/src/tests.rs | 12 ++-- 14 files changed, 122 insertions(+), 133 deletions(-) diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index 5a66310c9ad28..cf4b8d23b0458 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -101,9 +101,6 @@ impl pallet_balances::Config for Test { type AccountStore = System; type WeightInfo = (); } -parameter_types! { - static TentoFourteen: Vec = vec![10,11,12,13,14]; -} parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); pub static Burn: Permill = Permill::from_percent(50); diff --git a/frame/child-bounties/src/tests.rs b/frame/child-bounties/src/tests.rs index fbcd7c0d96fed..3dbafdc33ac0a 100644 --- a/frame/child-bounties/src/tests.rs +++ b/frame/child-bounties/src/tests.rs @@ -104,9 +104,6 @@ impl pallet_balances::Config for Test { type AccountStore = System; type WeightInfo = (); } -parameter_types! { - static TenToFourteen: Vec = vec![10,11,12,13,14]; -} parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 2459f7e748941..95441959db1f4 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -19,7 +19,6 @@ #![cfg(test)] -use std::cell::RefCell; use frame_support::{ parameter_types, @@ -57,18 +56,18 @@ frame_support::construct_runtime!( } ); -thread_local! { - pub static VALIDATORS: RefCell>> = RefCell::new(Some(vec![ +parameter_types! { + pub static Validators: Option> = Some(vec![ 1, 2, 3, - ])); + ]); } pub struct TestSessionManager; impl pallet_session::SessionManager for TestSessionManager { fn new_session(_new_index: SessionIndex) -> Option> { - VALIDATORS.with(|l| l.borrow_mut().take()) + Validators::mutate(|l| l.take()) } fn end_session(_: SessionIndex) {} fn start_session(_: SessionIndex) {} @@ -76,9 +75,8 @@ impl pallet_session::SessionManager for TestSessionManager { impl pallet_session::historical::SessionManager for TestSessionManager { fn new_session(_new_index: SessionIndex) -> Option> { - VALIDATORS.with(|l| { - l.borrow_mut() - .take() + Validators::mutate(|l| { + l.take() .map(|validators| validators.iter().map(|v| (*v, *v)).collect()) }) } @@ -91,15 +89,15 @@ pub type Extrinsic = TestXt; type IdentificationTuple = (u64, u64); type Offence = crate::UnresponsivenessOffence; -thread_local! { - pub static OFFENCES: RefCell, Offence)>> = RefCell::new(vec![]); +parameter_types! { + pub static OFFENCES: Vec<(Vec, Offence)> = vec![]; } /// A mock offence report handler. pub struct OffenceHandler; impl ReportOffence for OffenceHandler { fn report_offence(reporters: Vec, offence: Offence) -> Result<(), OffenceError> { - OFFENCES.with(|l| l.borrow_mut().push((reporters, offence))); + OFFENCES::mutate(|l| l.push((reporters, offence))); Ok(()) } @@ -183,12 +181,12 @@ impl pallet_authorship::Config for Runtime { type EventHandler = ImOnline; } -thread_local! { - pub static MOCK_CURRENT_SESSION_PROGRESS: RefCell>> = RefCell::new(None); +parameter_types! { + pub static MockCurrentSessionProgress: Option> = None; } -thread_local! { - pub static MOCK_AVERAGE_SESSION_LENGTH: RefCell> = RefCell::new(None); +parameter_types! { + pub static MockAverageSessionLength: Option = None; } pub struct TestNextSessionRotation; @@ -196,7 +194,7 @@ pub struct TestNextSessionRotation; impl frame_support::traits::EstimateNextSessionRotation for TestNextSessionRotation { fn average_session_length() -> u64 { // take the mock result if any and return it - let mock = MOCK_AVERAGE_SESSION_LENGTH.with(|p| p.borrow_mut().take()); + let mock = MockAverageSessionLength::mutate(|p| p.take()); mock.unwrap_or(pallet_session::PeriodicSessions::::average_session_length()) } @@ -208,7 +206,7 @@ impl frame_support::traits::EstimateNextSessionRotation for TestNextSession ); // take the mock result if any and return it - let mock = MOCK_CURRENT_SESSION_PROGRESS.with(|p| p.borrow_mut().take()); + let mock = MockCurrentSessionProgress::mutate(|p| p.take()); (mock.unwrap_or(estimate), weight) } diff --git a/frame/im-online/src/tests.rs b/frame/im-online/src/tests.rs index 05e1af169dba9..9497a01bd3933 100644 --- a/frame/im-online/src/tests.rs +++ b/frame/im-online/src/tests.rs @@ -68,7 +68,7 @@ fn should_report_offline_validators() { advance_session(); // enact the change and buffer another one let validators = vec![1, 2, 3, 4, 5, 6]; - VALIDATORS.with(|l| *l.borrow_mut() = Some(validators.clone())); + Validators::mutate(|l| *l = Some(validators.clone())); advance_session(); // when @@ -76,7 +76,8 @@ fn should_report_offline_validators() { advance_session(); // then - let offences = OFFENCES.with(|l| l.replace(vec![])); + let offences = OFFENCES::get(); + OFFENCES::mutate(|l| l.clear()); assert_eq!( offences, vec![( @@ -96,7 +97,8 @@ fn should_report_offline_validators() { advance_session(); // then - let offences = OFFENCES.with(|l| l.replace(vec![])); + let offences = OFFENCES::get(); + OFFENCES::mutate(|l| l.clear()); assert_eq!( offences, vec![( @@ -149,7 +151,7 @@ fn should_mark_online_validator_when_heartbeat_is_received() { new_test_ext().execute_with(|| { advance_session(); // given - VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 3, 4, 5, 6])); + Validators::mutate(|l| *l = Some(vec![1, 2, 3, 4, 5, 6])); assert_eq!(Session::validators(), Vec::::new()); // enact the change and buffer another one advance_session(); @@ -184,7 +186,7 @@ fn late_heartbeat_and_invalid_keys_len_should_fail() { new_test_ext().execute_with(|| { advance_session(); // given - VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 3, 4, 5, 6])); + Validators::mutate(|l| *l = Some(vec![1, 2, 3, 4, 5, 6])); assert_eq!(Session::validators(), Vec::::new()); // enact the change and buffer another one advance_session(); @@ -226,7 +228,7 @@ fn should_generate_heartbeats() { // buffer new validators Session::rotate_session(); // enact the change and buffer another one - VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 3, 4, 5, 6])); + Validators::mutate(|l| *l = Some(vec![1, 2, 3, 4, 5, 6])); Session::rotate_session(); // when @@ -262,7 +264,7 @@ fn should_cleanup_received_heartbeats_on_session_end() { new_test_ext().execute_with(|| { advance_session(); - VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 3])); + Validators::mutate(|l| *l = Some(vec![1, 2, 3])); assert_eq!(Session::validators(), Vec::::new()); // enact the change and buffer another one @@ -293,7 +295,7 @@ fn should_mark_online_validator_when_block_is_authored() { new_test_ext().execute_with(|| { advance_session(); // given - VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 3, 4, 5, 6])); + Validators::mutate(|l| *l = Some(vec![1, 2, 3, 4, 5, 6])); assert_eq!(Session::validators(), Vec::::new()); // enact the change and buffer another one advance_session(); @@ -330,7 +332,7 @@ fn should_not_send_a_report_if_already_online() { ext.execute_with(|| { advance_session(); // given - VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 3, 4, 5, 6])); + Validators::mutate(|l| *l = Some(vec![1, 2, 3, 4, 5, 6])); assert_eq!(Session::validators(), Vec::::new()); // enact the change and buffer another one advance_session(); @@ -393,12 +395,12 @@ fn should_handle_missing_progress_estimates() { Session::rotate_session(); // enact the change and buffer another one - VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![0, 1, 2])); + Validators::mutate(|l| *l = Some(vec![0, 1, 2])); Session::rotate_session(); // we will return `None` on the next call to `estimate_current_session_progress` // and the offchain worker should fallback to checking `HeartbeatAfter` - MOCK_CURRENT_SESSION_PROGRESS.with(|p| *p.borrow_mut() = Some(None)); + MockCurrentSessionProgress::mutate(|p| *p = Some(None)); ImOnline::offchain_worker(block); assert_eq!(state.read().transactions.len(), 3); @@ -427,26 +429,26 @@ fn should_handle_non_linear_session_progress() { // mock the session length as being 10 blocks long, // enact the change and buffer another one - VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![0, 1, 2])); + Validators::mutate(|l| *l = Some(vec![0, 1, 2])); // mock the session length has being 10 which should make us assume the fallback for half // session will be reached by block 5. - MOCK_AVERAGE_SESSION_LENGTH.with(|p| *p.borrow_mut() = Some(10)); + MockAverageSessionLength::mutate(|p| *p = Some(10)); Session::rotate_session(); // if we don't have valid results for the current session progres then // we'll fallback to `HeartbeatAfter` and only heartbeat on block 5. - MOCK_CURRENT_SESSION_PROGRESS.with(|p| *p.borrow_mut() = Some(None)); + MockCurrentSessionProgress::mutate(|p| *p = Some(None)); assert_eq!(ImOnline::send_heartbeats(2).err(), Some(OffchainErr::TooEarly)); - MOCK_CURRENT_SESSION_PROGRESS.with(|p| *p.borrow_mut() = Some(None)); + MockCurrentSessionProgress::mutate(|p| *p = Some(None)); assert!(ImOnline::send_heartbeats(5).ok().is_some()); // if we have a valid current session progress then we'll heartbeat as soon // as we're past 80% of the session regardless of the block number - MOCK_CURRENT_SESSION_PROGRESS - .with(|p| *p.borrow_mut() = Some(Some(Permill::from_percent(81)))); + MockCurrentSessionProgress + ::mutate(|p| *p = Some(Some(Permill::from_percent(81)))); assert!(ImOnline::send_heartbeats(2).ok().is_some()); }); @@ -464,8 +466,8 @@ fn test_does_not_heartbeat_early_in_the_session() { ext.execute_with(|| { // mock current session progress as being 5%. we only randomly start // heartbeating after 10% of the session has elapsed. - MOCK_CURRENT_SESSION_PROGRESS - .with(|p| *p.borrow_mut() = Some(Some(Permill::from_float(0.05)))); + MockCurrentSessionProgress + ::mutate(|p| *p = Some(Some(Permill::from_float(0.05)))); assert_eq!(ImOnline::send_heartbeats(2).err(), Some(OffchainErr::TooEarly)); }); } @@ -483,9 +485,9 @@ fn test_probability_of_heartbeating_increases_with_session_progress() { let set_test = |progress, random: f64| { // the average session length is 100 blocks, therefore the residual // probability of sending a heartbeat is 1% - MOCK_AVERAGE_SESSION_LENGTH.with(|p| *p.borrow_mut() = Some(100)); - MOCK_CURRENT_SESSION_PROGRESS - .with(|p| *p.borrow_mut() = Some(Some(Permill::from_float(progress)))); + MockAverageSessionLength::mutate(|p| *p = Some(100)); + MockCurrentSessionProgress + ::mutate(|p| *p = Some(Some(Permill::from_float(progress)))); let mut seed = [0u8; 32]; let encoded = ((random * Permill::ACCURACY as f64) as u32).encode(); diff --git a/frame/merkle-mountain-range/src/mock.rs b/frame/merkle-mountain-range/src/mock.rs index b2b6821fcd054..46920864e76f5 100644 --- a/frame/merkle-mountain-range/src/mock.rs +++ b/frame/merkle-mountain-range/src/mock.rs @@ -19,6 +19,7 @@ use crate as pallet_mmr; use crate::*; use codec::{Decode, Encode}; +use frame_support::parameter_types; use frame_support::traits::{ConstU32, ConstU64}; use sp_core::H256; use sp_mmr_primitives::{Compact, LeafDataProvider}; @@ -26,7 +27,7 @@ use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup, Keccak256}, }; -use sp_std::{cell::RefCell, prelude::*}; +use sp_std::prelude::*; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -91,14 +92,14 @@ impl LeafData { } } -thread_local! { - pub static LEAF_DATA: RefCell = RefCell::new(Default::default()); +parameter_types! { + pub static LeafDataTestValue: LeafData = Default::default(); } impl LeafDataProvider for LeafData { type LeafData = Self; fn leaf_data() -> Self::LeafData { - LEAF_DATA.with(|r| r.borrow().clone()) + LeafDataTestValue::get().clone() } } diff --git a/frame/merkle-mountain-range/src/tests.rs b/frame/merkle-mountain-range/src/tests.rs index 566a051823d5e..5d8b8a6ff0555 100644 --- a/frame/merkle-mountain-range/src/tests.rs +++ b/frame/merkle-mountain-range/src/tests.rs @@ -42,7 +42,7 @@ fn register_offchain_ext(ext: &mut sp_io::TestExternalities) { fn new_block() -> u64 { let number = frame_system::Pallet::::block_number() + 1; let hash = H256::repeat_byte(number as u8); - LEAF_DATA.with(|r| r.borrow_mut().a = number); + LeafDataTestValue::mutate(|r| r.a = number); frame_system::Pallet::::reset_events(); frame_system::Pallet::::initialize(&number, &hash, &Default::default()); diff --git a/frame/scheduler/src/mock.rs b/frame/scheduler/src/mock.rs index 008105dc737ea..f7748d57073a7 100644 --- a/frame/scheduler/src/mock.rs +++ b/frame/scheduler/src/mock.rs @@ -41,13 +41,13 @@ pub mod logger { use super::{OriginCaller, OriginTrait}; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - use std::cell::RefCell; + use frame_support::parameter_types; - thread_local! { - static LOG: RefCell> = RefCell::new(Vec::new()); + parameter_types! { + static Log: Vec<(OriginCaller, u32)> = Vec::new(); } pub fn log() -> Vec<(OriginCaller, u32)> { - LOG.with(|log| log.borrow().clone()) + Log::get().clone() } #[pallet::pallet] @@ -76,8 +76,8 @@ pub mod logger { #[pallet::weight(*weight)] pub fn log(origin: OriginFor, i: u32, weight: Weight) -> DispatchResult { Self::deposit_event(Event::Logged(i, weight)); - LOG.with(|log| { - log.borrow_mut().push((origin.caller().clone(), i)); + Log::mutate(|log| { + log.push((origin.caller().clone(), i)); }); Ok(()) } @@ -85,8 +85,8 @@ pub mod logger { #[pallet::weight(*weight)] pub fn log_without_filter(origin: OriginFor, i: u32, weight: Weight) -> DispatchResult { Self::deposit_event(Event::Logged(i, weight)); - LOG.with(|log| { - log.borrow_mut().push((origin.caller().clone(), i)); + Log::mutate(|log| { + log.push((origin.caller().clone(), i)); }); Ok(()) } diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 4fef5385eb2c5..c611c60080894 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -30,7 +30,6 @@ use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; -use std::cell::RefCell; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -96,14 +95,14 @@ impl pallet_balances::Config for Test { type WeightInfo = (); } -thread_local! { - pub static MEMBERS: RefCell> = RefCell::new(vec![]); +parameter_types! { + pub static MembersTestValue: Vec = vec![]; } pub struct TestChangeMembers; impl ChangeMembers for TestChangeMembers { fn change_members_sorted(incoming: &[u64], outgoing: &[u64], new: &[u64]) { - let mut old_plus_incoming = MEMBERS.with(|m| m.borrow().to_vec()); + let mut old_plus_incoming = MembersTestValue::get().to_vec(); old_plus_incoming.extend_from_slice(incoming); old_plus_incoming.sort(); @@ -113,13 +112,13 @@ impl ChangeMembers for TestChangeMembers { assert_eq!(old_plus_incoming, new_plus_outgoing); - MEMBERS.with(|m| *m.borrow_mut() = new.to_vec()); + MembersTestValue::mutate(|m| *m = new.to_vec()); } } impl InitializeMembers for TestChangeMembers { fn initialize_members(new_members: &[u64]) { - MEMBERS.with(|m| *m.borrow_mut() = new_members.to_vec()); + MembersTestValue::mutate(|m| *m = new_members.to_vec()); } } diff --git a/frame/scored-pool/src/tests.rs b/frame/scored-pool/src/tests.rs index 7b431160ddfe5..42f0b47e8b940 100644 --- a/frame/scored-pool/src/tests.rs +++ b/frame/scored-pool/src/tests.rs @@ -33,7 +33,7 @@ fn query_membership_works() { assert_eq!(ScoredPool::members(), vec![20, 40]); assert_eq!(Balances::reserved_balance(31), CandidateDeposit::get()); assert_eq!(Balances::reserved_balance(40), CandidateDeposit::get()); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), vec![20, 40]); + assert_eq!(MembersTestValue::get().clone(), vec![20, 40]); }); } @@ -128,7 +128,7 @@ fn kicking_works() { // then assert_eq!(find_in_pool(who), None); assert_eq!(ScoredPool::members(), vec![20, 31]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), ScoredPool::members()); + assert_eq!(MembersTestValue::get().clone(), ScoredPool::members()); assert_eq!(Balances::reserved_balance(who), 0); // deposit must have been returned }); } @@ -152,7 +152,7 @@ fn unscored_entities_must_not_be_used_for_filling_members() { // then // the `None` candidates should not have been filled in assert!(ScoredPool::members().is_empty()); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), ScoredPool::members()); + assert_eq!(MembersTestValue::get().clone(), ScoredPool::members()); }); } @@ -170,7 +170,7 @@ fn refreshing_works() { // then assert_eq!(ScoredPool::members(), vec![15, 40]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), ScoredPool::members()); + assert_eq!(MembersTestValue::get().clone(), ScoredPool::members()); }); } @@ -190,7 +190,7 @@ fn refreshing_happens_every_period() { // then assert_eq!(ScoredPool::members(), vec![15, 40]); - assert_eq!(MEMBERS.with(|m| m.borrow().clone()), ScoredPool::members()); + assert_eq!(MembersTestValue::get().clone(), ScoredPool::members()); }); } diff --git a/frame/session/src/historical/mod.rs b/frame/session/src/historical/mod.rs index c72ab8c210d69..9b175e19a2064 100644 --- a/frame/session/src/historical/mod.rs +++ b/frame/session/src/historical/mod.rs @@ -375,7 +375,7 @@ impl> KeyOwnerProofSystem<(KeyTypeId, D)> for Pallet sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - let keys: Vec<_> = NEXT_VALIDATORS.with(|l| { - l.borrow().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect() - }); + let keys: Vec<_> = NextValidators + ::get().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect(); BasicExternalities::execute_with_storage(&mut t, || { for (ref k, ..) in &keys { frame_system::Pallet::::inc_providers(k); diff --git a/frame/session/src/historical/offchain.rs b/frame/session/src/historical/offchain.rs index 95813d0a70272..9ec4ee7138832 100644 --- a/frame/session/src/historical/offchain.rs +++ b/frame/session/src/historical/offchain.rs @@ -141,7 +141,7 @@ mod tests { use super::*; use crate::{ historical::{onchain, Pallet}, - mock::{force_new_session, set_next_validators, Session, System, Test, NEXT_VALIDATORS}, + mock::{force_new_session, set_next_validators, Session, System, Test, NextValidators}, }; use codec::Encode; @@ -163,9 +163,9 @@ mod tests { .build_storage::() .expect("Failed to create test externalities."); - let keys: Vec<_> = NEXT_VALIDATORS.with(|l| { - l.borrow().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect() - }); + let keys: Vec<_> = NextValidators + ::get().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect(); + BasicExternalities::execute_with_storage(&mut t, || { for (ref k, ..) in &keys { frame_system::Pallet::::inc_providers(k); diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index 7c6cc02c9e785..029a5f306a613 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -22,7 +22,7 @@ use crate as pallet_session; #[cfg(feature = "historical")] use crate::historical as pallet_session_historical; -use std::{cell::RefCell, collections::BTreeMap}; +use std::collections::BTreeMap; use sp_core::{crypto::key_types::DUMMY, H256}; use sp_runtime::{ @@ -103,29 +103,29 @@ frame_support::construct_runtime!( } ); -thread_local! { - pub static VALIDATORS: RefCell> = RefCell::new(vec![1, 2, 3]); - pub static NEXT_VALIDATORS: RefCell> = RefCell::new(vec![1, 2, 3]); - pub static AUTHORITIES: RefCell> = - RefCell::new(vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); - pub static FORCE_SESSION_END: RefCell = RefCell::new(false); - pub static SESSION_LENGTH: RefCell = RefCell::new(2); - pub static SESSION_CHANGED: RefCell = RefCell::new(false); - pub static TEST_SESSION_CHANGED: RefCell = RefCell::new(false); - pub static DISABLED: RefCell = RefCell::new(false); +parameter_types! { + pub static Validators: Vec = vec![1, 2, 3]; + pub static NextValidators: Vec = vec![1, 2, 3]; + pub static Authorities: Vec = + vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]; + pub static ForceSessionEnd: bool = false; + pub static SessionLength: u64 = 2; + pub static SessionChanged: bool = false; + pub static TestSessionChanged: bool = false; + pub static Disabled: bool = false; // Stores if `on_before_session_end` was called - pub static BEFORE_SESSION_END_CALLED: RefCell = RefCell::new(false); - pub static VALIDATOR_ACCOUNTS: RefCell> = RefCell::new(BTreeMap::new()); + pub static BeforeSessionEndCalled: bool = false; + pub static ValidatorAccounts: BTreeMap = BTreeMap::new(); } pub struct TestShouldEndSession; impl ShouldEndSession for TestShouldEndSession { fn should_end_session(now: u64) -> bool { - let l = SESSION_LENGTH.with(|l| *l.borrow()); + let l = SessionLength::get(); now % l == 0 || - FORCE_SESSION_END.with(|l| { - let r = *l.borrow(); - *l.borrow_mut() = false; + ForceSessionEnd::mutate(|l| { + let r = *l; + *l = false; r }) } @@ -140,19 +140,19 @@ impl SessionHandler for TestSessionHandler { validators: &[(u64, T)], _queued_validators: &[(u64, T)], ) { - SESSION_CHANGED.with(|l| *l.borrow_mut() = changed); - AUTHORITIES.with(|l| { - *l.borrow_mut() = validators + SessionChanged::mutate(|l| *l = changed); + Authorities::mutate(|l| { + *l = validators .iter() .map(|(_, id)| id.get::(DUMMY).unwrap_or_default()) .collect() }); } fn on_disabled(_validator_index: u32) { - DISABLED.with(|l| *l.borrow_mut() = true) + Disabled::mutate(|l| *l = true) } fn on_before_session_ending() { - BEFORE_SESSION_END_CALLED.with(|b| *b.borrow_mut() = true); + BeforeSessionEndCalled::mutate(|b| *b = true); } } @@ -161,16 +161,15 @@ impl SessionManager for TestSessionManager { fn end_session(_: SessionIndex) {} fn start_session(_: SessionIndex) {} fn new_session(_: SessionIndex) -> Option> { - if !TEST_SESSION_CHANGED.with(|l| *l.borrow()) { - VALIDATORS.with(|v| { - let mut v = v.borrow_mut(); - *v = NEXT_VALIDATORS.with(|l| l.borrow().clone()); + if !TestSessionChanged::get() { + Validators::mutate(|v| { + *v = NextValidators::get().clone(); Some(v.clone()) }) - } else if DISABLED.with(|l| std::mem::replace(&mut *l.borrow_mut(), false)) { + } else if Disabled::mutate(|l| std::mem::replace(&mut *l, false)) { // If there was a disabled validator, underlying conditions have changed // so we return `Some`. - Some(VALIDATORS.with(|v| v.borrow().clone())) + Some(Validators::get().clone()) } else { None } @@ -188,37 +187,37 @@ impl crate::historical::SessionManager for TestSessionManager { } pub fn authorities() -> Vec { - AUTHORITIES.with(|l| l.borrow().to_vec()) + Authorities::get().to_vec() } pub fn force_new_session() { - FORCE_SESSION_END.with(|l| *l.borrow_mut() = true) + ForceSessionEnd::mutate(|l| *l = true) } pub fn set_session_length(x: u64) { - SESSION_LENGTH.with(|l| *l.borrow_mut() = x) + SessionLength::mutate(|l| *l = x) } pub fn session_changed() -> bool { - SESSION_CHANGED.with(|l| *l.borrow()) + SessionChanged::get() } pub fn set_next_validators(next: Vec) { - NEXT_VALIDATORS.with(|v| *v.borrow_mut() = next); + NextValidators::mutate(|v| *v = next); } pub fn before_session_end_called() -> bool { - BEFORE_SESSION_END_CALLED.with(|b| *b.borrow()) + BeforeSessionEndCalled::get() } pub fn reset_before_session_end_called() { - BEFORE_SESSION_END_CALLED.with(|b| *b.borrow_mut() = false); + BeforeSessionEndCalled::mutate(|b| *b = false); } pub fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - let keys: Vec<_> = NEXT_VALIDATORS - .with(|l| l.borrow().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect()); + let keys: Vec<_> = NextValidators + ::get().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect(); BasicExternalities::execute_with_storage(&mut t, || { for (ref k, ..) in &keys { frame_system::Pallet::::inc_providers(k); @@ -230,10 +229,9 @@ pub fn new_test_ext() -> sp_io::TestExternalities { pallet_session::GenesisConfig:: { keys } .assimilate_storage(&mut t) .unwrap(); - NEXT_VALIDATORS.with(|l| { - let v = l.borrow().iter().map(|&i| (i, i)).collect(); - VALIDATOR_ACCOUNTS.with(|m| *m.borrow_mut() = v); - }); + + let v = NextValidators::get().iter().map(|&i| (i, i)).collect(); + ValidatorAccounts::mutate(|m| *m = v); sp_io::TestExternalities::new(t) } @@ -279,12 +277,12 @@ impl pallet_timestamp::Config for Test { pub struct TestValidatorIdOf; impl TestValidatorIdOf { pub fn set(v: BTreeMap) { - VALIDATOR_ACCOUNTS.with(|m| *m.borrow_mut() = v); + ValidatorAccounts::mutate(|m| *m = v); } } impl Convert> for TestValidatorIdOf { fn convert(x: u64) -> Option { - VALIDATOR_ACCOUNTS.with(|m| m.borrow().get(&x).cloned()) + ValidatorAccounts::get().get(&x).cloned() } } diff --git a/frame/session/src/tests.rs b/frame/session/src/tests.rs index c9d2dbb53d9ba..d700c5c274ed3 100644 --- a/frame/session/src/tests.rs +++ b/frame/session/src/tests.rs @@ -21,8 +21,8 @@ use super::*; use crate::mock::{ authorities, before_session_end_called, force_new_session, new_test_ext, reset_before_session_end_called, session_changed, set_next_validators, set_session_length, - Origin, PreUpgradeMockSessionKeys, Session, System, Test, TestValidatorIdOf, SESSION_CHANGED, - TEST_SESSION_CHANGED, + Origin, PreUpgradeMockSessionKeys, Session, System, Test, TestValidatorIdOf, SessionChanged, + TestSessionChanged, }; use codec::Decode; @@ -35,7 +35,7 @@ use frame_support::{ }; fn initialize_block(block: u64) { - SESSION_CHANGED.with(|l| *l.borrow_mut() = false); + SessionChanged::mutate(|l| *l = false); System::set_block_number(block); Session::on_initialize(block); } @@ -235,7 +235,7 @@ fn session_changed_flag_works() { new_test_ext().execute_with(|| { TestValidatorIdOf::set(vec![(1, 1), (2, 2), (3, 3), (69, 69)].into_iter().collect()); - TEST_SESSION_CHANGED.with(|l| *l.borrow_mut() = true); + TestSessionChanged::mutate(|l| *l = true); force_new_session(); initialize_block(1); @@ -384,8 +384,8 @@ fn upgrade_keys() { use sp_core::crypto::key_types::DUMMY; // This test assumes certain mocks. - assert_eq!(mock::NEXT_VALIDATORS.with(|l| l.borrow().clone()), vec![1, 2, 3]); - assert_eq!(mock::VALIDATORS.with(|l| l.borrow().clone()), vec![1, 2, 3]); + assert_eq!(mock::NextValidators::get().clone(), vec![1, 2, 3]); + assert_eq!(mock::Validators::get().clone(), vec![1, 2, 3]); new_test_ext().execute_with(|| { let pre_one = PreUpgradeMockSessionKeys { a: [1u8; 32], b: [1u8; 64] }; diff --git a/frame/tips/src/tests.rs b/frame/tips/src/tests.rs index bcaa99285d2e7..884c78708b984 100644 --- a/frame/tips/src/tests.rs +++ b/frame/tips/src/tests.rs @@ -19,7 +19,6 @@ #![cfg(test)] -use std::cell::RefCell; use sp_core::H256; use sp_runtime::{ @@ -100,18 +99,17 @@ impl pallet_balances::Config for Test { type AccountStore = System; type WeightInfo = (); } -thread_local! { - static TEN_TO_FOURTEEN: RefCell> = RefCell::new(vec![10,11,12,13,14]); +parameter_types! { + static TenToFourteenTestValue: Vec = vec![10,11,12,13,14]; } pub struct TenToFourteen; impl SortedMembers for TenToFourteen { fn sorted_members() -> Vec { - TEN_TO_FOURTEEN.with(|v| v.borrow().clone()) + TenToFourteenTestValue::get().clone() } #[cfg(feature = "runtime-benchmarks")] fn add(new: &u128) { - TEN_TO_FOURTEEN.with(|v| { - let mut members = v.borrow_mut(); + TenToFourteenTestValue::mutate(|members| { members.push(*new); members.sort(); }) @@ -119,7 +117,7 @@ impl SortedMembers for TenToFourteen { } impl ContainsLengthBound for TenToFourteen { fn max_len() -> usize { - TEN_TO_FOURTEEN.with(|v| v.borrow().len()) + TenToFourteenTestValue::get().len() } fn min_len() -> usize { 0 From 92b05f9b73121bc632f8154600e846f3ecc0f3dc Mon Sep 17 00:00:00 2001 From: Tife Date: Sat, 20 Aug 2022 01:36:09 +0100 Subject: [PATCH 19/29] updates --- frame/timestamp/src/mock.rs | 11 ++++--- .../asset-tx-payment/src/tests.rs | 8 ++--- frame/transaction-payment/src/lib.rs | 29 +++++++++---------- frame/treasury/src/tests.rs | 3 -- 4 files changed, 23 insertions(+), 28 deletions(-) diff --git a/frame/timestamp/src/mock.rs b/frame/timestamp/src/mock.rs index 0da94deb7112a..f6d5101603058 100644 --- a/frame/timestamp/src/mock.rs +++ b/frame/timestamp/src/mock.rs @@ -19,7 +19,6 @@ use super::*; use crate as pallet_timestamp; -use sp_std::cell::RefCell; use frame_support::{ parameter_types, @@ -78,14 +77,14 @@ impl frame_system::Config for Test { type MaxConsumers = ConstU32<16>; } -thread_local! { - pub static CAPTURED_MOMENT: RefCell> = RefCell::new(None); +parameter_types! { + pub static CapturedMoment: Option = None; } pub struct MockOnTimestampSet; impl OnTimestampSet for MockOnTimestampSet { fn on_timestamp_set(moment: Moment) { - CAPTURED_MOMENT.with(|x| *x.borrow_mut() = Some(moment)); + CapturedMoment::mutate(|x| *x = Some(moment)); } } @@ -97,11 +96,11 @@ impl Config for Test { } pub(crate) fn clear_captured_moment() { - CAPTURED_MOMENT.with(|x| *x.borrow_mut() = None); + CapturedMoment::mutate(|x| *x = None); } pub(crate) fn get_captured_moment() -> Option { - CAPTURED_MOMENT.with(|x| *x.borrow()) + CapturedMoment::get() } pub(crate) fn new_test_ext() -> TestExternalities { diff --git a/frame/transaction-payment/asset-tx-payment/src/tests.rs b/frame/transaction-payment/asset-tx-payment/src/tests.rs index 08b17a6bf459c..a97f0eb60e360 100644 --- a/frame/transaction-payment/asset-tx-payment/src/tests.rs +++ b/frame/transaction-payment/asset-tx-payment/src/tests.rs @@ -58,8 +58,8 @@ frame_support::construct_runtime!( const CALL: &::Call = &Call::Balances(BalancesCall::transfer { dest: 2, value: 69 }); -thread_local! { - static EXTRINSIC_BASE_WEIGHT: RefCell = RefCell::new(0); +parameter_types! { + static ExtrinsicBaseWeight: u64 = 0; } pub struct BlockWeights; @@ -68,7 +68,7 @@ impl Get for BlockWeights { frame_system::limits::BlockWeights::builder() .base_block(0) .for_class(DispatchClass::all(), |weights| { - weights.base_extrinsic = EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow()).into(); + weights.base_extrinsic = ExtrinsicBaseWeight::get().into(); }) .for_class(DispatchClass::non_mandatory(), |weights| { weights.max_total = 1024.into(); @@ -229,7 +229,7 @@ impl ExtBuilder { self } fn set_constants(&self) { - EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow_mut() = self.base_weight); + ExtrinsicBaseWeight::mutate(|v| *v = self.base_weight); TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.byte_fee); WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee); } diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 707f7d8a22065..755ffce85051b 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -795,7 +795,6 @@ mod tests { use super::*; use crate as pallet_transaction_payment; - use std::cell::RefCell; use codec::Encode; @@ -835,8 +834,8 @@ mod tests { const CALL: &::Call = &Call::Balances(BalancesCall::transfer { dest: 2, value: 69 }); - thread_local! { - static EXTRINSIC_BASE_WEIGHT: RefCell = RefCell::new(0); + parameter_types! { + static ExtrinsicBaseWeight: u64 = 0; } pub struct BlockWeights; @@ -845,7 +844,7 @@ mod tests { frame_system::limits::BlockWeights::builder() .base_block(0) .for_class(DispatchClass::all(), |weights| { - weights.base_extrinsic = EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow()).into(); + weights.base_extrinsic = ExtrinsicBaseWeight::get().into(); }) .for_class(DispatchClass::non_mandatory(), |weights| { weights.max_total = 1024.into(); @@ -917,9 +916,9 @@ mod tests { } } - thread_local! { - static TIP_UNBALANCED_AMOUNT: RefCell = RefCell::new(0); - static FEE_UNBALANCED_AMOUNT: RefCell = RefCell::new(0); + parameter_types! { + static TipUnbalancedAmount: u64 = 0; + static FeeUnbalancedAmount: u64 = 0; } pub struct DealWithFees; @@ -928,9 +927,9 @@ mod tests { mut fees_then_tips: impl Iterator>, ) { if let Some(fees) = fees_then_tips.next() { - FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow_mut() += fees.peek()); + FeeUnbalancedAmount::mutate(|a| *a += fees.peek()); if let Some(tips) = fees_then_tips.next() { - TIP_UNBALANCED_AMOUNT.with(|a| *a.borrow_mut() += tips.peek()); + TipUnbalancedAmount::mutate(|a| *a += tips.peek()); } } } @@ -976,7 +975,7 @@ mod tests { self } fn set_constants(&self) { - EXTRINSIC_BASE_WEIGHT.with(|v| *v.borrow_mut() = self.base_weight); + ExtrinsicBaseWeight::mutate(|v| *v = self.base_weight); TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.byte_fee); WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee); } @@ -1042,10 +1041,10 @@ mod tests { &Ok(()) )); assert_eq!(Balances::free_balance(1), 100 - 5 - 5 - 10); - assert_eq!(FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow()), 5 + 5 + 10); - assert_eq!(TIP_UNBALANCED_AMOUNT.with(|a| *a.borrow()), 0); + assert_eq!(FeeUnbalancedAmount::get(), 5 + 5 + 10); + assert_eq!(TipUnbalancedAmount::get(), 0); - FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow_mut() = 0); + FeeUnbalancedAmount::mutate(|a| *a = 0); let pre = ChargeTransactionPayment::::from(5 /* tipped */) .pre_dispatch(&2, CALL, &info_from_weight(100), len) @@ -1060,8 +1059,8 @@ mod tests { &Ok(()) )); assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 50 - 5); - assert_eq!(FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow()), 5 + 10 + 50); - assert_eq!(TIP_UNBALANCED_AMOUNT.with(|a| *a.borrow()), 5); + assert_eq!(FeeUnbalancedAmount::get(), 5 + 10 + 50); + assert_eq!(TipUnbalancedAmount::get(), 5); }); } diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index 61eafb652427b..e8a12c603a223 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -94,9 +94,6 @@ impl pallet_balances::Config for Test { type AccountStore = System; type WeightInfo = (); } -thread_local! { - static TEN_TO_FOURTEEN: RefCell> = RefCell::new(vec![10,11,12,13,14]); -} parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); From 7ce4340312e92ddc0db7537648aec1b1bdbed362 Mon Sep 17 00:00:00 2001 From: Tife Date: Sat, 20 Aug 2022 02:18:36 +0100 Subject: [PATCH 20/29] cargo +nightly fmt --- frame/im-online/src/mock.rs | 4 +--- frame/im-online/src/tests.rs | 9 +++------ frame/merkle-mountain-range/src/mock.rs | 6 ++++-- frame/scheduler/src/mock.rs | 3 +-- frame/session/src/historical/mod.rs | 9 ++++++--- frame/session/src/historical/offchain.rs | 9 ++++++--- frame/session/src/mock.rs | 9 ++++++--- frame/session/src/tests.rs | 4 ++-- frame/tips/src/tests.rs | 1 - frame/transaction-payment/src/lib.rs | 1 - frame/treasury/src/tests.rs | 2 -- 11 files changed, 29 insertions(+), 28 deletions(-) diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 95441959db1f4..b6cdcc735e94f 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -19,7 +19,6 @@ #![cfg(test)] - use frame_support::{ parameter_types, traits::{ConstU32, ConstU64}, @@ -76,8 +75,7 @@ impl pallet_session::SessionManager for TestSessionManager { impl pallet_session::historical::SessionManager for TestSessionManager { fn new_session(_new_index: SessionIndex) -> Option> { Validators::mutate(|l| { - l.take() - .map(|validators| validators.iter().map(|v| (*v, *v)).collect()) + l.take().map(|validators| validators.iter().map(|v| (*v, *v)).collect()) }) } fn end_session(_: SessionIndex) {} diff --git a/frame/im-online/src/tests.rs b/frame/im-online/src/tests.rs index 9497a01bd3933..5c42d96f33513 100644 --- a/frame/im-online/src/tests.rs +++ b/frame/im-online/src/tests.rs @@ -447,8 +447,7 @@ fn should_handle_non_linear_session_progress() { // if we have a valid current session progress then we'll heartbeat as soon // as we're past 80% of the session regardless of the block number - MockCurrentSessionProgress - ::mutate(|p| *p = Some(Some(Permill::from_percent(81)))); + MockCurrentSessionProgress::mutate(|p| *p = Some(Some(Permill::from_percent(81)))); assert!(ImOnline::send_heartbeats(2).ok().is_some()); }); @@ -466,8 +465,7 @@ fn test_does_not_heartbeat_early_in_the_session() { ext.execute_with(|| { // mock current session progress as being 5%. we only randomly start // heartbeating after 10% of the session has elapsed. - MockCurrentSessionProgress - ::mutate(|p| *p = Some(Some(Permill::from_float(0.05)))); + MockCurrentSessionProgress::mutate(|p| *p = Some(Some(Permill::from_float(0.05)))); assert_eq!(ImOnline::send_heartbeats(2).err(), Some(OffchainErr::TooEarly)); }); } @@ -486,8 +484,7 @@ fn test_probability_of_heartbeating_increases_with_session_progress() { // the average session length is 100 blocks, therefore the residual // probability of sending a heartbeat is 1% MockAverageSessionLength::mutate(|p| *p = Some(100)); - MockCurrentSessionProgress - ::mutate(|p| *p = Some(Some(Permill::from_float(progress)))); + MockCurrentSessionProgress::mutate(|p| *p = Some(Some(Permill::from_float(progress)))); let mut seed = [0u8; 32]; let encoded = ((random * Permill::ACCURACY as f64) as u32).encode(); diff --git a/frame/merkle-mountain-range/src/mock.rs b/frame/merkle-mountain-range/src/mock.rs index 46920864e76f5..30dd6da3d3b8d 100644 --- a/frame/merkle-mountain-range/src/mock.rs +++ b/frame/merkle-mountain-range/src/mock.rs @@ -19,8 +19,10 @@ use crate as pallet_mmr; use crate::*; use codec::{Decode, Encode}; -use frame_support::parameter_types; -use frame_support::traits::{ConstU32, ConstU64}; +use frame_support::{ + parameter_types, + traits::{ConstU32, ConstU64}, +}; use sp_core::H256; use sp_mmr_primitives::{Compact, LeafDataProvider}; use sp_runtime::{ diff --git a/frame/scheduler/src/mock.rs b/frame/scheduler/src/mock.rs index f7748d57073a7..36a0c3255c16b 100644 --- a/frame/scheduler/src/mock.rs +++ b/frame/scheduler/src/mock.rs @@ -39,9 +39,8 @@ use sp_runtime::{ #[frame_support::pallet] pub mod logger { use super::{OriginCaller, OriginTrait}; - use frame_support::pallet_prelude::*; + use frame_support::{pallet_prelude::*, parameter_types}; use frame_system::pallet_prelude::*; - use frame_support::parameter_types; parameter_types! { static Log: Vec<(OriginCaller, u32)> = Vec::new(); diff --git a/frame/session/src/historical/mod.rs b/frame/session/src/historical/mod.rs index 9b175e19a2064..45b4ba3c0a799 100644 --- a/frame/session/src/historical/mod.rs +++ b/frame/session/src/historical/mod.rs @@ -375,7 +375,7 @@ impl> KeyOwnerProofSystem<(KeyTypeId, D)> for Pallet sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - let keys: Vec<_> = NextValidators - ::get().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect(); + let keys: Vec<_> = NextValidators::get() + .iter() + .cloned() + .map(|i| (i, i, UintAuthorityId(i).into())) + .collect(); BasicExternalities::execute_with_storage(&mut t, || { for (ref k, ..) in &keys { frame_system::Pallet::::inc_providers(k); diff --git a/frame/session/src/historical/offchain.rs b/frame/session/src/historical/offchain.rs index 9ec4ee7138832..ececb8af5ad58 100644 --- a/frame/session/src/historical/offchain.rs +++ b/frame/session/src/historical/offchain.rs @@ -141,7 +141,7 @@ mod tests { use super::*; use crate::{ historical::{onchain, Pallet}, - mock::{force_new_session, set_next_validators, Session, System, Test, NextValidators}, + mock::{force_new_session, set_next_validators, NextValidators, Session, System, Test}, }; use codec::Encode; @@ -163,8 +163,11 @@ mod tests { .build_storage::() .expect("Failed to create test externalities."); - let keys: Vec<_> = NextValidators - ::get().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect(); + let keys: Vec<_> = NextValidators::get() + .iter() + .cloned() + .map(|i| (i, i, UintAuthorityId(i).into())) + .collect(); BasicExternalities::execute_with_storage(&mut t, || { for (ref k, ..) in &keys { diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index 029a5f306a613..4df04c19b40d6 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -216,8 +216,11 @@ pub fn reset_before_session_end_called() { pub fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - let keys: Vec<_> = NextValidators - ::get().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect(); + let keys: Vec<_> = NextValidators::get() + .iter() + .cloned() + .map(|i| (i, i, UintAuthorityId(i).into())) + .collect(); BasicExternalities::execute_with_storage(&mut t, || { for (ref k, ..) in &keys { frame_system::Pallet::::inc_providers(k); @@ -230,7 +233,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { .assimilate_storage(&mut t) .unwrap(); - let v = NextValidators::get().iter().map(|&i| (i, i)).collect(); + let v = NextValidators::get().iter().map(|&i| (i, i)).collect(); ValidatorAccounts::mutate(|m| *m = v); sp_io::TestExternalities::new(t) } diff --git a/frame/session/src/tests.rs b/frame/session/src/tests.rs index d700c5c274ed3..7947a8a670b5a 100644 --- a/frame/session/src/tests.rs +++ b/frame/session/src/tests.rs @@ -21,8 +21,8 @@ use super::*; use crate::mock::{ authorities, before_session_end_called, force_new_session, new_test_ext, reset_before_session_end_called, session_changed, set_next_validators, set_session_length, - Origin, PreUpgradeMockSessionKeys, Session, System, Test, TestValidatorIdOf, SessionChanged, - TestSessionChanged, + Origin, PreUpgradeMockSessionKeys, Session, SessionChanged, System, Test, TestSessionChanged, + TestValidatorIdOf, }; use codec::Decode; diff --git a/frame/tips/src/tests.rs b/frame/tips/src/tests.rs index 884c78708b984..b12885fc59f16 100644 --- a/frame/tips/src/tests.rs +++ b/frame/tips/src/tests.rs @@ -19,7 +19,6 @@ #![cfg(test)] - use sp_core::H256; use sp_runtime::{ testing::Header, diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 755ffce85051b..4445f5c3278ed 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -795,7 +795,6 @@ mod tests { use super::*; use crate as pallet_transaction_payment; - use codec::Encode; use sp_core::H256; diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index e8a12c603a223..8fd3c92edba91 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -19,8 +19,6 @@ #![cfg(test)] -use std::cell::RefCell; - use sp_core::H256; use sp_runtime::{ testing::Header, From 9237c223d68267d7d2019698e4ac2f63acd762bc Mon Sep 17 00:00:00 2001 From: Tife Date: Sat, 20 Aug 2022 02:24:01 +0100 Subject: [PATCH 21/29] cargo +nightly fmt --- frame/transaction-payment/asset-tx-payment/src/tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/frame/transaction-payment/asset-tx-payment/src/tests.rs b/frame/transaction-payment/asset-tx-payment/src/tests.rs index a97f0eb60e360..e5503bbd2cbba 100644 --- a/frame/transaction-payment/asset-tx-payment/src/tests.rs +++ b/frame/transaction-payment/asset-tx-payment/src/tests.rs @@ -33,7 +33,6 @@ use sp_runtime::{ testing::Header, traits::{BlakeTwo256, ConvertInto, IdentityLookup, SaturatedConversion, StaticLookup}, }; -use std::cell::RefCell; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; From ebd5a68db64d3da9c2a91c8bea5449e76207cbdd Mon Sep 17 00:00:00 2001 From: Tife Date: Wed, 24 Aug 2022 16:47:05 +0100 Subject: [PATCH 22/29] take fn implemented --- frame/assets/src/mock.rs | 4 +--- frame/contracts/src/tests.rs | 18 +++++++++--------- frame/support/src/lib.rs | 7 +++++++ 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 10d56dc2275f0..5429c89084e78 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -143,9 +143,7 @@ pub(crate) fn hooks() -> Vec { } pub(crate) fn take_hooks() -> Vec { - let result = Hooks::get(); - Hooks::set(Default::default()); - result + Hooks::take() } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 424bfd0125aa1..c6dd2dbf8004a 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -109,7 +109,7 @@ pub mod test_utils { } parameter_types! { - static TestExtensionsTestValue: TestExtension = Default::default(); + static TestExtensionTestValue: TestExtension = Default::default(); } #[derive(Clone)] @@ -132,15 +132,15 @@ pub struct TempStorageExtension { impl TestExtension { fn disable() { - TestExtensionsTestValue::mutate(|e| e.enabled = false) + TestExtensionTestValue::mutate(|e| e.enabled = false) } fn last_seen_buffer() -> Vec { - TestExtensionsTestValue::get().last_seen_buffer.clone() + TestExtensionTestValue::get().last_seen_buffer.clone() } fn last_seen_inputs() -> (u32, u32, u32, u32) { - TestExtensionsTestValue::get().last_seen_inputs + TestExtensionTestValue::get().last_seen_inputs } } @@ -163,12 +163,12 @@ impl ChainExtension for TestExtension { let mut env = env.buf_in_buf_out(); let input = env.read(8)?; env.write(&input, false, None)?; - TestExtensionsTestValue::mutate(|e| e.last_seen_buffer = input); + TestExtensionTestValue::mutate(|e| e.last_seen_buffer = input); Ok(RetVal::Converging(id)) }, 0x8001 => { let env = env.only_in(); - TestExtensionsTestValue::mutate(|e| { + TestExtensionTestValue::mutate(|e| { e.last_seen_inputs = (env.val0(), env.val1(), env.val2(), env.val3()) }); Ok(RetVal::Converging(id)) @@ -187,7 +187,7 @@ impl ChainExtension for TestExtension { } fn enabled() -> bool { - TestExtensionsTestValue::get().enabled + TestExtensionTestValue::get().enabled } } @@ -205,7 +205,7 @@ impl ChainExtension for RevertingExtension { } fn enabled() -> bool { - TestExtensionsTestValue::get().enabled + TestExtensionTestValue::get().enabled } } @@ -254,7 +254,7 @@ impl ChainExtension for TempStorageExtension { } fn enabled() -> bool { - TestExtensionsTestValue::get().enabled + TestExtensionTestValue::get().enabled } } diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 12e7ce2dc5d70..509dbfa153cf5 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -446,6 +446,13 @@ macro_rules! parameter_types_impl_thread_local { Self::set(current); result } + + /// Get and remove the value. + pub fn take() -> $type { + let current = Self::get(); + Self::set(Default::default()); + current + } } )* } From 8ad342b8b4b17a812495f2f8f3db62e0f9a39058 Mon Sep 17 00:00:00 2001 From: Tife Date: Wed, 24 Aug 2022 17:03:23 +0100 Subject: [PATCH 23/29] update --- frame/election-provider-multi-phase/src/mock.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index 7eff70b47eba5..2664587054ecb 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -241,7 +241,7 @@ impl pallet_balances::Config for Runtime { type WeightInfo = (); } -#[derive(Eq, PartialEq, Debug, Clone, Copy)] +#[derive(Default, Eq, PartialEq, Debug, Clone, Copy)] pub enum MockedWeightInfo { Basic, Complex, From a89a1d7fe406105ae3fb3d7fa9ec14e70df50dfb Mon Sep 17 00:00:00 2001 From: Tife Date: Wed, 24 Aug 2022 17:08:35 +0100 Subject: [PATCH 24/29] update --- frame/election-provider-multi-phase/src/mock.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index 2664587054ecb..302efa461a2c8 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -243,6 +243,7 @@ impl pallet_balances::Config for Runtime { #[derive(Default, Eq, PartialEq, Debug, Clone, Copy)] pub enum MockedWeightInfo { + #[default] Basic, Complex, Real, From 908eb91a2795198b689686d5582ae717a04f446e Mon Sep 17 00:00:00 2001 From: Tife Date: Fri, 26 Aug 2022 08:09:37 +0100 Subject: [PATCH 25/29] Fixes to CallFilter --- frame/contracts/src/tests.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index c6dd2dbf8004a..bb39f65e993c7 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -339,19 +339,32 @@ impl Convert> for Test { /// A filter whose filter function can be swapped at runtime. pub struct TestFilter; +#[derive(Clone)] +pub struct Filters{ + filter: fn(&Call) -> bool +} + +impl Default for Filters{ + fn default() -> Self { + Filters{ + filter: (|_| true) + } + } +} + parameter_types! { - static CallFilter: fn(&Call) -> bool = (|_| true); + static CallFilter: Filters = Default::default(); } impl TestFilter { pub fn set_filter(filter: fn(&Call) -> bool) { - CallFilter::mutate(|fltr| *fltr = filter); + CallFilter::mutate(|fltr| fltr.filter = filter); } } impl Contains for TestFilter { fn contains(call: &Call) -> bool { - CallFilter::get()(call) + (CallFilter::get().filter)(call) } } From 22ef5044c11044e336db48f874f39e9e98aae8b3 Mon Sep 17 00:00:00 2001 From: Tife Date: Fri, 26 Aug 2022 08:11:19 +0100 Subject: [PATCH 26/29] cargo +nightly fmt --- frame/contracts/src/tests.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index bb39f65e993c7..4a0df8255e1ac 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -340,15 +340,13 @@ impl Convert> for Test { pub struct TestFilter; #[derive(Clone)] -pub struct Filters{ - filter: fn(&Call) -> bool +pub struct Filters { + filter: fn(&Call) -> bool, } -impl Default for Filters{ +impl Default for Filters { fn default() -> Self { - Filters{ - filter: (|_| true) - } + Filters { filter: (|_| true) } } } From 48f95b6ed746288fa29ded2d6414ee165d40be23 Mon Sep 17 00:00:00 2001 From: Tife Date: Sat, 27 Aug 2022 06:40:53 +0100 Subject: [PATCH 27/29] final fixes --- frame/im-online/src/mock.rs | 4 ++-- frame/im-online/src/tests.rs | 6 ++---- frame/offences/src/mock.rs | 6 +++--- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index b6cdcc735e94f..d660134099883 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -88,14 +88,14 @@ type IdentificationTuple = (u64, u64); type Offence = crate::UnresponsivenessOffence; parameter_types! { - pub static OFFENCES: Vec<(Vec, Offence)> = vec![]; + pub static Offences: Vec<(Vec, Offence)> = vec![]; } /// A mock offence report handler. pub struct OffenceHandler; impl ReportOffence for OffenceHandler { fn report_offence(reporters: Vec, offence: Offence) -> Result<(), OffenceError> { - OFFENCES::mutate(|l| l.push((reporters, offence))); + Offences::mutate(|l| l.push((reporters, offence))); Ok(()) } diff --git a/frame/im-online/src/tests.rs b/frame/im-online/src/tests.rs index 5c42d96f33513..6ef7cce7c353b 100644 --- a/frame/im-online/src/tests.rs +++ b/frame/im-online/src/tests.rs @@ -76,8 +76,7 @@ fn should_report_offline_validators() { advance_session(); // then - let offences = OFFENCES::get(); - OFFENCES::mutate(|l| l.clear()); + let offences = Offences::take(); assert_eq!( offences, vec![( @@ -97,8 +96,7 @@ fn should_report_offline_validators() { advance_session(); // then - let offences = OFFENCES::get(); - OFFENCES::mutate(|l| l.clear()); + let offences = Offences::take(); assert_eq!( offences, vec![( diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index 1bf59e3c80158..a6e729bebdd6f 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -44,7 +44,7 @@ use sp_staking::{ pub struct OnOffenceHandler; parameter_types! { - pub static OnOffencePerBill: Vec = Default::default(); + pub static OnOffencePerbill: Vec = Default::default(); pub static OffenceWeight: Weight = Default::default(); } @@ -57,7 +57,7 @@ impl offence::OnOffenceHandler _offence_session: SessionIndex, _disable_strategy: DisableStrategy, ) -> Weight { - OnOffencePerBill::mutate(|f| { + OnOffencePerbill::mutate(|f| { *f = slash_fraction.to_vec(); }); @@ -66,7 +66,7 @@ impl offence::OnOffenceHandler } pub fn with_on_offence_fractions) -> R>(f: F) -> R { - OnOffencePerBill::mutate(|fractions| f(fractions)) + OnOffencePerbill::mutate(|fractions| f(fractions)) } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; From 9efdf6ef094a57c0e0305c824b73f1f98513887d Mon Sep 17 00:00:00 2001 From: Tife Date: Wed, 7 Sep 2022 11:14:57 +0100 Subject: [PATCH 28/29] Default changed to $value --- frame/support/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 98cd0828b9bcf..e37318a1c4646 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -455,10 +455,10 @@ macro_rules! parameter_types_impl_thread_local { result } - /// Get and remove the value. + /// Get current value and replace with original set value ($value). pub fn take() -> $type { let current = Self::get(); - Self::set(Default::default()); + Self::set($value); current } } From 7beef9f5647388b58eed6573455589da229b83fe Mon Sep 17 00:00:00 2001 From: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Date: Thu, 8 Sep 2022 11:18:33 +0100 Subject: [PATCH 29/29] 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 e37318a1c4646..55ded6da9c5a1 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -455,7 +455,7 @@ macro_rules! parameter_types_impl_thread_local { result } - /// Get current value and replace with original set value ($value). + /// Get current value and replace with initial value of the parameter type. pub fn take() -> $type { let current = Self::get(); Self::set($value);