From 047853550b19efacf48fffc87077381bc6fb8bb5 Mon Sep 17 00:00:00 2001 From: Boluwatife Bakre Date: Thu, 8 Sep 2022 11:46:25 +0100 Subject: [PATCH] Use parameter_types instead of thread_local for test-setup (#12036) * Edit to Assets. parameter_types * fixes * Test Fixes. WIP * Edits to pallet-aura * Camel Case Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * Implementation of mutate fn * update to pallet-aura * Update to frame-system. Fixes * Update to frame-support-test. CamelCases * Updates to frame- contracts, offences, staking, bounties, child bounties * Edit to mutate fn. Changes to frame-contracts. CamelCase pallet-aura * Edits to frame-contracts & executive * cargo +nightly fmt * unused import removed * unused import removed * cargo +nightly fmt * minor adjustment * updates * updates * cargo +nightly fmt * cargo +nightly fmt * take fn implemented * update * update * Fixes to CallFilter * cargo +nightly fmt * final fixes * Default changed to $value * Update frame/support/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- frame/assets/src/mock.rs | 29 +-- frame/aura/src/mock.rs | 14 +- frame/bounties/src/tests.rs | 4 - frame/child-bounties/src/tests.rs | 4 - frame/contracts/src/exec.rs | 59 +++--- frame/contracts/src/storage/meter.rs | 183 ++++++++---------- frame/contracts/src/tests.rs | 45 +++-- .../election-provider-multi-phase/src/mock.rs | 3 +- frame/executive/src/lib.rs | 50 +++-- frame/im-online/src/mock.rs | 34 ++-- frame/im-online/src/tests.rs | 41 ++-- frame/merkle-mountain-range/src/mock.rs | 13 +- frame/merkle-mountain-range/src/tests.rs | 2 +- frame/offences/src/mock.rs | 15 +- frame/scheduler/src/mock.rs | 17 +- frame/scored-pool/src/mock.rs | 11 +- frame/scored-pool/src/tests.rs | 10 +- frame/session/src/historical/mod.rs | 10 +- frame/session/src/historical/offchain.rs | 11 +- frame/session/src/mock.rs | 87 +++++---- frame/session/src/tests.rs | 12 +- frame/staking/src/mock.rs | 9 +- frame/staking/src/tests.rs | 7 +- frame/support/src/lib.rs | 15 ++ frame/support/test/tests/construct_runtime.rs | 16 +- frame/system/src/mock.rs | 7 +- frame/system/src/tests.rs | 4 +- frame/timestamp/src/mock.rs | 11 +- frame/tips/src/tests.rs | 13 +- .../asset-tx-payment/src/tests.rs | 9 +- frame/transaction-payment/src/lib.rs | 30 ++- frame/treasury/src/tests.rs | 5 - 32 files changed, 378 insertions(+), 402 deletions(-) diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 0fd4dd3281516..5429c89084e78 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_assets; use frame_support::{ - construct_runtime, + construct_runtime, parameter_types, traits::{ConstU32, ConstU64, GenesisBuild}, }; use sp_core::H256; @@ -101,44 +101,49 @@ 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! { + 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.with(|f| f.borrow().get(&(asset, *who)).cloned()) + Frozen::get().get(&(asset, *who)).cloned() } fn died(asset: u32, who: &u64) { - HOOKS.with(|h| h.borrow_mut().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()); } } pub(crate) fn set_frozen_balance(asset: u32, who: u64, amount: u64) { - FROZEN.with(|f| f.borrow_mut().insert((asset, who), amount)); + Frozen::mutate(|v| { + v.insert((asset, who), amount); + }); } pub(crate) fn clear_frozen_balance(asset: u32, who: u64) { - FROZEN.with(|f| f.borrow_mut().remove(&(asset, who))); + Frozen::mutate(|v| { + v.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::take() } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 5023feeaf8aea..5fa298bb008b0 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,18 +85,17 @@ impl pallet_timestamp::Config for Test { type WeightInfo = (); } -thread_local! { - static DISABLED_VALIDATORS: RefCell> = RefCell::new(Default::default()); +parameter_types! { + static DisabledValidatorTestValue: 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); + DisabledValidatorTestValue::mutate(|v| { + if let Err(i) = v.binary_search(&index) { + v.insert(i, index); } }) } @@ -105,7 +103,7 @@ impl MockDisabledValidators { impl DisabledValidators for MockDisabledValidators { fn is_disabled(index: AuthorityIndex) -> bool { - DISABLED_VALIDATORS.with(|v| v.borrow().binary_search(&index).is_ok()) + DisabledValidatorTestValue::get().binary_search(&index).is_ok() } } diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index b4ce039b35fbc..cf4b8d23b0458 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,9 +101,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 static Burn: Permill = Permill::from_percent(50); diff --git a/frame/child-bounties/src/tests.rs b/frame/child-bounties/src/tests.rs index f42715f14bbee..0edee8468b86f 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,9 +104,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); diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index 4ae336a907001..f91be3a9e491c 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -1376,7 +1376,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; @@ -1393,8 +1393,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> { @@ -1420,8 +1420,8 @@ mod tests { refcount: u64, } - #[derive(Default)] - struct MockLoader { + #[derive(Default, Clone)] + pub struct MockLoader { map: HashMap, MockExecutable>, counter: u64, } @@ -1431,8 +1431,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; @@ -1445,8 +1444,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, @@ -1457,8 +1455,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"), @@ -1478,13 +1475,8 @@ mod tests { _schedule: &Schedule, _gas_meter: &mut GasMeter, ) -> Result { - LOADER.with(|loader| { - loader - .borrow_mut() - .map - .get(&code_hash) - .cloned() - .ok_or(Error::::CodeNotFound.into()) + Loader::mutate(|loader| { + loader.map.get(&code_hash).cloned().ok_or(Error::::CodeNotFound.into()) }) } @@ -1531,14 +1523,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() }); @@ -1562,7 +1554,7 @@ mod tests { ); }); - TEST_DATA.with(|data| assert_eq!(*data.borrow(), vec![0, 1])); + assert_eq!(TestData::get(), vec![0, 1]); } #[test] @@ -1841,16 +1833,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(Weight::zero(), 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`. @@ -1891,15 +1882,14 @@ 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(Weight::zero(), CHARLIE, 0, vec![], true), Ok(_)); @@ -1907,8 +1897,7 @@ 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() }); @@ -1932,8 +1921,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..d89208812bcac 100644 --- a/frame/contracts/src/storage/meter.rs +++ b/frame/contracts/src/storage/meter.rs @@ -441,23 +441,23 @@ mod tests { exec::AccountIdOf, tests::{Test, ALICE, BOB, CHARLIE}, }; + use frame_support::parameter_types; use pretty_assertions::assert_eq; - use std::cell::RefCell; 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,12 +485,9 @@ mod tests { min_leftover: BalanceOf, ) -> Result, DispatchError> { let limit = limit.unwrap_or(42); - TEST_EXT.with(|ext| { - ext.borrow_mut().limit_checks.push(LimitCheck { - origin: origin.clone(), - limit, - min_leftover, - }) + TestExtTestValue::mutate(|ext| { + ext.limit_checks + .push(LimitCheck { origin: origin.clone(), limit, min_leftover }) }); Ok(limit) } @@ -501,8 +498,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 +510,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 +530,13 @@ mod tests { TestMeter::new(&ALICE, Some(1_000), 0).unwrap(); - TEST_EXT.with(|ext| { - assert_eq!( - *ext.borrow(), - 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,15 +551,13 @@ mod tests { nested0.charge(&Default::default()).unwrap(); meter.absorb(nested0, &ALICE, &BOB, None); - TEST_EXT.with(|ext| { - assert_eq!( - *ext.borrow(), - 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] @@ -582,20 +575,18 @@ mod tests { .unwrap(); meter.absorb(nested0, &ALICE, &BOB, None); - TEST_EXT.with(|ext| { - assert_eq!( - *ext.borrow(), - 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] @@ -638,34 +629,32 @@ 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(), - 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] @@ -697,27 +686,25 @@ mod tests { meter.absorb(nested0, &ALICE, &BOB, None); drop(meter); - TEST_EXT.with(|ext| { - assert_eq!( - *ext.borrow(), - 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 f65f845f7b9fe..8bca18c5d1c42 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -51,7 +51,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; @@ -113,10 +113,11 @@ pub mod test_utils { } } -thread_local! { - static TEST_EXTENSION: RefCell = Default::default(); +parameter_types! { + static TestExtensionTestValue: TestExtension = Default::default(); } +#[derive(Clone)] pub struct TestExtension { enabled: bool, last_seen_buffer: Vec, @@ -136,15 +137,15 @@ pub struct TempStorageExtension { impl TestExtension { fn disable() { - TEST_EXTENSION.with(|e| e.borrow_mut().enabled = false) + TestExtensionTestValue::mutate(|e| e.enabled = false) } fn last_seen_buffer() -> Vec { - TEST_EXTENSION.with(|e| e.borrow().last_seen_buffer.clone()) + TestExtensionTestValue::get().last_seen_buffer.clone() } fn last_seen_inputs() -> (u32, u32, u32, u32) { - TEST_EXTENSION.with(|e| e.borrow().last_seen_inputs) + TestExtensionTestValue::get().last_seen_inputs } } @@ -167,14 +168,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); + TestExtensionTestValue::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 = - (env.val0(), env.val1(), env.val2(), env.val3()) + TestExtensionTestValue::mutate(|e| { + e.last_seen_inputs = (env.val0(), env.val1(), env.val2(), env.val3()) }); Ok(RetVal::Converging(id)) }, @@ -192,7 +192,7 @@ impl ChainExtension for TestExtension { } fn enabled() -> bool { - TEST_EXTENSION.with(|e| e.borrow().enabled) + TestExtensionTestValue::get().enabled } } @@ -210,7 +210,7 @@ impl ChainExtension for RevertingExtension { } fn enabled() -> bool { - TEST_EXTENSION.with(|e| e.borrow().enabled) + TestExtensionTestValue::get().enabled } } @@ -259,7 +259,7 @@ impl ChainExtension for TempStorageExtension { } fn enabled() -> bool { - TEST_EXTENSION.with(|e| e.borrow().enabled) + TestExtensionTestValue::get().enabled } } @@ -344,19 +344,30 @@ 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); +#[derive(Clone)] +pub struct Filters { + filter: fn(&Call) -> bool, +} + +impl Default for Filters { + fn default() -> Self { + Filters { filter: (|_| true) } + } +} + +parameter_types! { + static CallFilter: Filters = Default::default(); } impl TestFilter { pub fn set_filter(filter: fn(&Call) -> bool) { - CALL_FILTER.with(|fltr| *fltr.borrow_mut() = filter); + CallFilter::mutate(|fltr| fltr.filter = filter); } } impl Contains for TestFilter { fn contains(call: &Call) -> bool { - CALL_FILTER.with(|fltr| fltr.borrow()(call)) + (CallFilter::get().filter)(call) } } diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index 48b76bbb98a8f..4e9672fc1d4f6 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -241,8 +241,9 @@ impl pallet_balances::Config for Runtime { type WeightInfo = (); } -#[derive(Eq, PartialEq, Debug, Clone, Copy)] +#[derive(Default, Eq, PartialEq, Debug, Clone, Copy)] pub enum MockedWeightInfo { + #[default] Basic, Complex, Real, diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 87ed8b93bbf8e..b23342800f8b9 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -835,12 +835,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(); } @@ -1239,14 +1239,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() = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); assert!(Executive::runtime_upgraded()); assert_eq!( @@ -1254,8 +1253,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() @@ -1267,8 +1266,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, @@ -1316,9 +1315,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() = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); Executive::initialize_block(&Header::new( @@ -1338,9 +1336,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() = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); // set block number to non zero so events are not excluded @@ -1369,9 +1366,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() = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); // Let's build some fake block. @@ -1389,15 +1385,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() = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); >>::execute_block(Block::new(header, vec![xt])); @@ -1411,9 +1406,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() = - sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } + RuntimeVersionTestValues::mutate(|v| { + *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() } }); let block_number = 1; diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index b734bd37b6fd4..6ea5a16d64f58 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -19,8 +19,6 @@ #![cfg(test)] -use std::cell::RefCell; - use frame_support::{ parameter_types, traits::{ConstU32, ConstU64}, @@ -57,18 +55,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,10 +74,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() - .map(|validators| validators.iter().map(|v| (*v, *v)).collect()) + Validators::mutate(|l| { + l.take().map(|validators| validators.iter().map(|v| (*v, *v)).collect()) }) } fn end_session(_: SessionIndex) {} @@ -91,15 +87,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 +179,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 +192,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 +204,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..6ef7cce7c353b 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,7 @@ fn should_report_offline_validators() { advance_session(); // then - let offences = OFFENCES.with(|l| l.replace(vec![])); + let offences = Offences::take(); assert_eq!( offences, vec![( @@ -96,7 +96,7 @@ fn should_report_offline_validators() { advance_session(); // then - let offences = OFFENCES.with(|l| l.replace(vec![])); + let offences = Offences::take(); assert_eq!( offences, vec![( @@ -149,7 +149,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 +184,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 +226,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 +262,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 +293,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 +330,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 +393,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 +427,25 @@ 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 +463,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. - 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 +481,8 @@ 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..30dd6da3d3b8d 100644 --- a/frame/merkle-mountain-range/src/mock.rs +++ b/frame/merkle-mountain-range/src/mock.rs @@ -19,14 +19,17 @@ use crate as pallet_mmr; use crate::*; use codec::{Decode, Encode}; -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::{ 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 +94,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 e13f89617bb9a..d6886f90a5da7 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() -> Weight { 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/offences/src/mock.rs b/frame/offences/src/mock.rs index a578a6082cf3e..bf4daf0c89944 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -40,13 +40,12 @@ use sp_staking::{ offence::{self, DisableStrategy, Kind, OffenceDetails}, SessionIndex, }; -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 @@ -58,16 +57,16 @@ 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())) + OnOffencePerbill::mutate(|fractions| f(fractions)) } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; diff --git a/frame/scheduler/src/mock.rs b/frame/scheduler/src/mock.rs index 7bbc628604bc6..1639c9a046142 100644 --- a/frame/scheduler/src/mock.rs +++ b/frame/scheduler/src/mock.rs @@ -39,15 +39,14 @@ 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 std::cell::RefCell; - 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 +75,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 +84,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 e38e0a18b99c8..00c66c3bdefe8 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..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<_> = 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..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, NEXT_VALIDATORS}, + mock::{force_new_session, set_next_validators, NextValidators, Session, System, Test}, }; use codec::Encode; @@ -163,9 +163,12 @@ 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 3044d6558e33e..c1858d0bff774 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,40 @@ 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 +232,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 +280,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..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, SESSION_CHANGED, - TEST_SESSION_CHANGED, + Origin, PreUpgradeMockSessionKeys, Session, SessionChanged, System, Test, TestSessionChanged, + TestValidatorIdOf, }; 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/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 448fbd2382454..969ff8e4e2881 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::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()), - 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) @@ -340,7 +337,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!( diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 3b2a8b3b62fc2..55ded6da9c5a1 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -446,6 +446,21 @@ 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 R>(mutate: F) -> R{ + let mut current = Self::get(); + let result = mutate(&mut current); + Self::set(current); + result + } + + /// Get current value and replace with initial value of the parameter type. + pub fn take() -> $type { + let current = Self::get(); + Self::set($value); + current + } } )* } diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index aed98579a0fd8..04b3dbcedcbf2 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -22,7 +22,10 @@ #![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 sp_core::{sr25519, H256}; use sp_runtime::{ @@ -30,14 +33,13 @@ use sp_runtime::{ 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 +97,7 @@ mod module2 { } fn integrity_test() { - INTEGRITY_TEST_EXEC.with(|i| *i.borrow_mut() += 1); + IntegrityTestExec::mutate(|i| *i += 1); } } } @@ -140,7 +142,7 @@ mod nested { } fn integrity_test() { - INTEGRITY_TEST_EXEC.with(|i| *i.borrow_mut() += 1); + IntegrityTestExec::mutate(|i| *i += 1); } } } @@ -377,7 +379,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 23ab3c2af20b0..09a018e2be70e 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 f82ea338bd146..641cda13b07a4 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]); }); } diff --git a/frame/timestamp/src/mock.rs b/frame/timestamp/src/mock.rs index b4c377cfa30ef..1ea553aa548ec 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/tips/src/tests.rs b/frame/tips/src/tests.rs index bcaa99285d2e7..b12885fc59f16 100644 --- a/frame/tips/src/tests.rs +++ b/frame/tips/src/tests.rs @@ -19,8 +19,6 @@ #![cfg(test)] -use std::cell::RefCell; - use sp_core::H256; use sp_runtime::{ testing::Header, @@ -100,18 +98,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 +116,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 diff --git a/frame/transaction-payment/asset-tx-payment/src/tests.rs b/frame/transaction-payment/asset-tx-payment/src/tests.rs index a17d564d7a334..dd7c086a82469 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; @@ -58,8 +57,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(Weight::zero()); +parameter_types! { + static ExtrinsicBaseWeight: Weight = Weight::zero(); } pub struct BlockWeights; @@ -68,7 +67,7 @@ impl Get for BlockWeights { frame_system::limits::BlockWeights::builder() .base_block(Weight::zero()) .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 = Weight::from_ref_time(1024).into(); @@ -235,7 +234,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 21d516cda1aa6..cbdc9dcb1e846 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -810,8 +810,6 @@ mod tests { use super::*; use crate as pallet_transaction_payment; - use std::cell::RefCell; - use codec::Encode; use sp_core::H256; @@ -850,8 +848,8 @@ mod tests { const CALL: &::Call = &Call::Balances(BalancesCall::transfer { dest: 2, value: 69 }); - thread_local! { - static EXTRINSIC_BASE_WEIGHT: RefCell = RefCell::new(Weight::zero()); + parameter_types! { + static ExtrinsicBaseWeight: Weight = Weight::zero(); } pub struct BlockWeights; @@ -860,7 +858,7 @@ mod tests { frame_system::limits::BlockWeights::builder() .base_block(Weight::zero()) .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 = Weight::from_ref_time(1024).into(); @@ -932,9 +930,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; @@ -943,9 +941,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()); } } } @@ -1002,7 +1000,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); } @@ -1074,10 +1072,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(Weight::from_ref_time(100)), len) @@ -1092,8 +1090,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 bec96daf576e3..c9c6d01f129e6 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, @@ -94,9 +92,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);