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>
This commit is contained in:
Boluwatife Bakre
2022-09-08 11:46:25 +01:00
committed by GitHub
parent bec123a50f
commit 3ec4d13e9f
32 changed files with 378 additions and 402 deletions
+17 -12
View File
@@ -21,7 +21,7 @@ use super::*;
use crate as pallet_assets; use crate as pallet_assets;
use frame_support::{ use frame_support::{
construct_runtime, construct_runtime, parameter_types,
traits::{ConstU32, ConstU64, GenesisBuild}, traits::{ConstU32, ConstU64, GenesisBuild},
}; };
use sp_core::H256; use sp_core::H256;
@@ -101,44 +101,49 @@ impl Config for Test {
type Extra = (); type Extra = ();
} }
use std::{cell::RefCell, collections::HashMap}; use std::collections::HashMap;
#[derive(Copy, Clone, Eq, PartialEq, Debug)] #[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub(crate) enum Hook { pub enum Hook {
Died(u32, u64), Died(u32, u64),
} }
thread_local! { parameter_types! {
static FROZEN: RefCell<HashMap<(u32, u64), u64>> = RefCell::new(Default::default()); static Frozen: HashMap<(u32, u64), u64> = Default::default();
static HOOKS: RefCell<Vec<Hook>> = RefCell::new(Default::default()); static Hooks: Vec<Hook> = Default::default();
} }
pub struct TestFreezer; pub struct TestFreezer;
impl FrozenBalance<u32, u64, u64> for TestFreezer { impl FrozenBalance<u32, u64, u64> for TestFreezer {
fn frozen_balance(asset: u32, who: &u64) -> Option<u64> { fn frozen_balance(asset: u32, who: &u64) -> Option<u64> {
FROZEN.with(|f| f.borrow().get(&(asset, *who)).cloned()) Frozen::get().get(&(asset, *who)).cloned()
} }
fn died(asset: u32, who: &u64) { 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. // Sanity check: dead accounts have no balance.
assert!(Assets::balance(asset, *who).is_zero()); assert!(Assets::balance(asset, *who).is_zero());
} }
} }
pub(crate) fn set_frozen_balance(asset: u32, who: u64, amount: u64) { 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) { 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<Hook> { pub(crate) fn hooks() -> Vec<Hook> {
HOOKS.with(|h| h.borrow().clone()) Hooks::get().clone()
} }
pub(crate) fn take_hooks() -> Vec<Hook> { pub(crate) fn take_hooks() -> Vec<Hook> {
HOOKS.with(|h| h.take()) Hooks::take()
} }
pub(crate) fn new_test_ext() -> sp_io::TestExternalities { pub(crate) fn new_test_ext() -> sp_io::TestExternalities {
+6 -8
View File
@@ -30,7 +30,6 @@ use sp_runtime::{
testing::{Header, UintAuthorityId}, testing::{Header, UintAuthorityId},
traits::IdentityLookup, traits::IdentityLookup,
}; };
use sp_std::cell::RefCell;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>; type Block = frame_system::mocking::MockBlock<Test>;
@@ -86,18 +85,17 @@ impl pallet_timestamp::Config for Test {
type WeightInfo = (); type WeightInfo = ();
} }
thread_local! { parameter_types! {
static DISABLED_VALIDATORS: RefCell<Vec<AuthorityIndex>> = RefCell::new(Default::default()); static DisabledValidatorTestValue: Vec<AuthorityIndex> = Default::default();
} }
pub struct MockDisabledValidators; pub struct MockDisabledValidators;
impl MockDisabledValidators { impl MockDisabledValidators {
pub fn disable_validator(index: AuthorityIndex) { pub fn disable_validator(index: AuthorityIndex) {
DISABLED_VALIDATORS.with(|v| { DisabledValidatorTestValue::mutate(|v| {
let mut disabled = v.borrow_mut(); if let Err(i) = v.binary_search(&index) {
if let Err(i) = disabled.binary_search(&index) { v.insert(i, index);
disabled.insert(i, index);
} }
}) })
} }
@@ -105,7 +103,7 @@ impl MockDisabledValidators {
impl DisabledValidators for MockDisabledValidators { impl DisabledValidators for MockDisabledValidators {
fn is_disabled(index: AuthorityIndex) -> bool { fn is_disabled(index: AuthorityIndex) -> bool {
DISABLED_VALIDATORS.with(|v| v.borrow().binary_search(&index).is_ok()) DisabledValidatorTestValue::get().binary_search(&index).is_ok()
} }
} }
-4
View File
@@ -21,7 +21,6 @@
use super::*; use super::*;
use crate as pallet_bounties; use crate as pallet_bounties;
use std::cell::RefCell;
use frame_support::{ use frame_support::{
assert_noop, assert_ok, assert_noop, assert_ok,
@@ -102,9 +101,6 @@ impl pallet_balances::Config for Test {
type AccountStore = System; type AccountStore = System;
type WeightInfo = (); type WeightInfo = ();
} }
thread_local! {
static TEN_TO_FOURTEEN: RefCell<Vec<u128>> = RefCell::new(vec![10,11,12,13,14]);
}
parameter_types! { parameter_types! {
pub const ProposalBond: Permill = Permill::from_percent(5); pub const ProposalBond: Permill = Permill::from_percent(5);
pub static Burn: Permill = Permill::from_percent(50); pub static Burn: Permill = Permill::from_percent(50);
@@ -21,7 +21,6 @@
use super::*; use super::*;
use crate as pallet_child_bounties; use crate as pallet_child_bounties;
use std::cell::RefCell;
use frame_support::{ use frame_support::{
assert_noop, assert_ok, assert_noop, assert_ok,
@@ -105,9 +104,6 @@ impl pallet_balances::Config for Test {
type AccountStore = System; type AccountStore = System;
type WeightInfo = (); type WeightInfo = ();
} }
thread_local! {
static TEN_TO_FOURTEEN: RefCell<Vec<u128>> = RefCell::new(vec![10,11,12,13,14]);
}
parameter_types! { parameter_types! {
pub const ProposalBond: Permill = Permill::from_percent(5); pub const ProposalBond: Permill = Permill::from_percent(5);
pub const Burn: Permill = Permill::from_percent(50); pub const Burn: Permill = Permill::from_percent(50);
+24 -35
View File
@@ -1376,7 +1376,7 @@ mod tests {
}; };
use assert_matches::assert_matches; use assert_matches::assert_matches;
use codec::{Decode, Encode}; 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 frame_system::{EventRecord, Phase};
use hex_literal::hex; use hex_literal::hex;
use pallet_contracts_primitives::ReturnFlags; use pallet_contracts_primitives::ReturnFlags;
@@ -1393,8 +1393,8 @@ mod tests {
type MockStack<'a> = Stack<'a, Test, MockExecutable>; type MockStack<'a> = Stack<'a, Test, MockExecutable>;
thread_local! { parameter_types! {
static LOADER: RefCell<MockLoader> = RefCell::new(MockLoader::default()); static Loader: MockLoader = MockLoader::default();
} }
fn events() -> Vec<Event<Test>> { fn events() -> Vec<Event<Test>> {
@@ -1420,8 +1420,8 @@ mod tests {
refcount: u64, refcount: u64,
} }
#[derive(Default)] #[derive(Default, Clone)]
struct MockLoader { pub struct MockLoader {
map: HashMap<CodeHash<Test>, MockExecutable>, map: HashMap<CodeHash<Test>, MockExecutable>,
counter: u64, counter: u64,
} }
@@ -1431,8 +1431,7 @@ mod tests {
func_type: ExportedFunction, func_type: ExportedFunction,
f: impl Fn(MockCtx, &MockExecutable) -> ExecResult + 'static, f: impl Fn(MockCtx, &MockExecutable) -> ExecResult + 'static,
) -> CodeHash<Test> { ) -> CodeHash<Test> {
LOADER.with(|loader| { Loader::mutate(|loader| {
let mut loader = loader.borrow_mut();
// Generate code hashes as monotonically increasing values. // Generate code hashes as monotonically increasing values.
let hash = <Test as frame_system::Config>::Hash::from_low_u64_be(loader.counter); let hash = <Test as frame_system::Config>::Hash::from_low_u64_be(loader.counter);
loader.counter += 1; loader.counter += 1;
@@ -1445,8 +1444,7 @@ mod tests {
} }
fn increment_refcount(code_hash: CodeHash<Test>) -> Result<(), DispatchError> { fn increment_refcount(code_hash: CodeHash<Test>) -> Result<(), DispatchError> {
LOADER.with(|loader| { Loader::mutate(|loader| {
let mut loader = loader.borrow_mut();
match loader.map.entry(code_hash) { match loader.map.entry(code_hash) {
Entry::Vacant(_) => Err(<Error<Test>>::CodeNotFound)?, Entry::Vacant(_) => Err(<Error<Test>>::CodeNotFound)?,
Entry::Occupied(mut entry) => entry.get_mut().refcount += 1, Entry::Occupied(mut entry) => entry.get_mut().refcount += 1,
@@ -1457,8 +1455,7 @@ mod tests {
fn decrement_refcount(code_hash: CodeHash<Test>) { fn decrement_refcount(code_hash: CodeHash<Test>) {
use std::collections::hash_map::Entry::Occupied; use std::collections::hash_map::Entry::Occupied;
LOADER.with(|loader| { Loader::mutate(|loader| {
let mut loader = loader.borrow_mut();
let mut entry = match loader.map.entry(code_hash) { let mut entry = match loader.map.entry(code_hash) {
Occupied(e) => e, Occupied(e) => e,
_ => panic!("code_hash does not exist"), _ => panic!("code_hash does not exist"),
@@ -1478,13 +1475,8 @@ mod tests {
_schedule: &Schedule<Test>, _schedule: &Schedule<Test>,
_gas_meter: &mut GasMeter<Test>, _gas_meter: &mut GasMeter<Test>,
) -> Result<Self, DispatchError> { ) -> Result<Self, DispatchError> {
LOADER.with(|loader| { Loader::mutate(|loader| {
loader loader.map.get(&code_hash).cloned().ok_or(Error::<Test>::CodeNotFound.into())
.borrow_mut()
.map
.get(&code_hash)
.cloned()
.ok_or(Error::<Test>::CodeNotFound.into())
}) })
} }
@@ -1531,14 +1523,14 @@ mod tests {
#[test] #[test]
fn it_works() { fn it_works() {
thread_local! { parameter_types! {
static TEST_DATA: RefCell<Vec<usize>> = RefCell::new(vec![0]); static TestData: Vec<usize> = vec![0];
} }
let value = Default::default(); let value = Default::default();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT); let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
let exec_ch = MockLoader::insert(Call, |_ctx, _executable| { 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() 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] #[test]
@@ -1841,16 +1833,15 @@ mod tests {
fn max_depth() { fn max_depth() {
// This test verifies that when we reach the maximal depth creation of an // This test verifies that when we reach the maximal depth creation of an
// yet another context fails. // yet another context fails.
thread_local! { parameter_types! {
static REACHED_BOTTOM: RefCell<bool> = RefCell::new(false); static ReachedBottom: bool = false;
} }
let value = Default::default(); let value = Default::default();
let recurse_ch = MockLoader::insert(Call, |ctx, _| { let recurse_ch = MockLoader::insert(Call, |ctx, _| {
// Try to call into yourself. // Try to call into yourself.
let r = ctx.ext.call(Weight::zero(), BOB, 0, vec![], true); let r = ctx.ext.call(Weight::zero(), BOB, 0, vec![], true);
REACHED_BOTTOM.with(|reached_bottom| { ReachedBottom::mutate(|reached_bottom| {
let mut reached_bottom = reached_bottom.borrow_mut();
if !*reached_bottom { if !*reached_bottom {
// We are first time here, it means we just reached bottom. // We are first time here, it means we just reached bottom.
// Verify that we've got proper error and set `reached_bottom`. // Verify that we've got proper error and set `reached_bottom`.
@@ -1891,15 +1882,14 @@ mod tests {
let origin = ALICE; let origin = ALICE;
let dest = BOB; let dest = BOB;
thread_local! { parameter_types! {
static WITNESSED_CALLER_BOB: RefCell<Option<AccountIdOf<Test>>> = RefCell::new(None); static WitnessedCallerBob: Option<AccountIdOf<Test>> = None;
static WITNESSED_CALLER_CHARLIE: RefCell<Option<AccountIdOf<Test>>> = RefCell::new(None); static WitnessedCallerCharlie: Option<AccountIdOf<Test>> = None;
} }
let bob_ch = MockLoader::insert(Call, |ctx, _| { let bob_ch = MockLoader::insert(Call, |ctx, _| {
// Record the caller for bob. // Record the caller for bob.
WITNESSED_CALLER_BOB WitnessedCallerBob::mutate(|caller| *caller = Some(ctx.ext.caller().clone()));
.with(|caller| *caller.borrow_mut() = Some(ctx.ext.caller().clone()));
// Call into CHARLIE contract. // Call into CHARLIE contract.
assert_matches!(ctx.ext.call(Weight::zero(), CHARLIE, 0, vec![], true), Ok(_)); 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, _| { let charlie_ch = MockLoader::insert(Call, |ctx, _| {
// Record the caller for charlie. // Record the caller for charlie.
WITNESSED_CALLER_CHARLIE WitnessedCallerCharlie::mutate(|caller| *caller = Some(ctx.ext.caller().clone()));
.with(|caller| *caller.borrow_mut() = Some(ctx.ext.caller().clone()));
exec_success() exec_success()
}); });
@@ -1932,8 +1921,8 @@ mod tests {
assert_matches!(result, Ok(_)); assert_matches!(result, Ok(_));
}); });
WITNESSED_CALLER_BOB.with(|caller| assert_eq!(*caller.borrow(), Some(origin))); assert_eq!(WitnessedCallerBob::get(), Some(origin));
WITNESSED_CALLER_CHARLIE.with(|caller| assert_eq!(*caller.borrow(), Some(dest))); assert_eq!(WitnessedCallerCharlie::get(), Some(dest));
} }
#[test] #[test]
+85 -98
View File
@@ -441,23 +441,23 @@ mod tests {
exec::AccountIdOf, exec::AccountIdOf,
tests::{Test, ALICE, BOB, CHARLIE}, tests::{Test, ALICE, BOB, CHARLIE},
}; };
use frame_support::parameter_types;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use std::cell::RefCell;
type TestMeter = RawMeter<Test, TestExt, Root>; type TestMeter = RawMeter<Test, TestExt, Root>;
thread_local! { parameter_types! {
static TEST_EXT: RefCell<TestExt> = RefCell::new(Default::default()); static TestExtTestValue: TestExt = Default::default();
} }
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq, Clone)]
struct LimitCheck { struct LimitCheck {
origin: AccountIdOf<Test>, origin: AccountIdOf<Test>,
limit: BalanceOf<Test>, limit: BalanceOf<Test>,
min_leftover: BalanceOf<Test>, min_leftover: BalanceOf<Test>,
} }
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq, Clone)]
struct Charge { struct Charge {
origin: AccountIdOf<Test>, origin: AccountIdOf<Test>,
contract: AccountIdOf<Test>, contract: AccountIdOf<Test>,
@@ -465,8 +465,8 @@ mod tests {
terminated: bool, terminated: bool,
} }
#[derive(Default, Debug, PartialEq, Eq)] #[derive(Default, Debug, PartialEq, Eq, Clone)]
struct TestExt { pub struct TestExt {
limit_checks: Vec<LimitCheck>, limit_checks: Vec<LimitCheck>,
charges: Vec<Charge>, charges: Vec<Charge>,
} }
@@ -485,12 +485,9 @@ mod tests {
min_leftover: BalanceOf<Test>, min_leftover: BalanceOf<Test>,
) -> Result<BalanceOf<Test>, DispatchError> { ) -> Result<BalanceOf<Test>, DispatchError> {
let limit = limit.unwrap_or(42); let limit = limit.unwrap_or(42);
TEST_EXT.with(|ext| { TestExtTestValue::mutate(|ext| {
ext.borrow_mut().limit_checks.push(LimitCheck { ext.limit_checks
origin: origin.clone(), .push(LimitCheck { origin: origin.clone(), limit, min_leftover })
limit,
min_leftover,
})
}); });
Ok(limit) Ok(limit)
} }
@@ -501,8 +498,8 @@ mod tests {
amount: &DepositOf<Test>, amount: &DepositOf<Test>,
terminated: bool, terminated: bool,
) { ) {
TEST_EXT.with(|ext| { TestExtTestValue::mutate(|ext| {
ext.borrow_mut().charges.push(Charge { ext.charges.push(Charge {
origin: origin.clone(), origin: origin.clone(),
contract: contract.clone(), contract: contract.clone(),
amount: amount.clone(), amount: amount.clone(),
@@ -513,7 +510,7 @@ mod tests {
} }
fn clear_ext() { fn clear_ext() {
TEST_EXT.with(|ext| ext.borrow_mut().clear()) TestExtTestValue::mutate(|ext| ext.clear())
} }
fn new_info(deposit: BalanceOf<Test>) -> ContractInfo<Test> { fn new_info(deposit: BalanceOf<Test>) -> ContractInfo<Test> {
@@ -533,15 +530,13 @@ mod tests {
TestMeter::new(&ALICE, Some(1_000), 0).unwrap(); TestMeter::new(&ALICE, Some(1_000), 0).unwrap();
TEST_EXT.with(|ext| { assert_eq!(
assert_eq!( TestExtTestValue::get(),
*ext.borrow(), TestExt {
TestExt { limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }],
limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], ..Default::default()
..Default::default() }
} )
)
});
} }
#[test] #[test]
@@ -556,15 +551,13 @@ mod tests {
nested0.charge(&Default::default()).unwrap(); nested0.charge(&Default::default()).unwrap();
meter.absorb(nested0, &ALICE, &BOB, None); meter.absorb(nested0, &ALICE, &BOB, None);
TEST_EXT.with(|ext| { assert_eq!(
assert_eq!( TestExtTestValue::get(),
*ext.borrow(), TestExt {
TestExt { limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }],
limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], ..Default::default()
..Default::default() }
} )
)
});
} }
#[test] #[test]
@@ -582,20 +575,18 @@ mod tests {
.unwrap(); .unwrap();
meter.absorb(nested0, &ALICE, &BOB, None); meter.absorb(nested0, &ALICE, &BOB, None);
TEST_EXT.with(|ext| { assert_eq!(
assert_eq!( TestExtTestValue::get(),
*ext.borrow(), TestExt {
TestExt { limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }],
limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], charges: vec![Charge {
charges: vec![Charge { origin: ALICE,
origin: ALICE, contract: BOB,
contract: BOB, amount: Deposit::Charge(<Test as Config>::Currency::minimum_balance() * 2),
amount: Deposit::Charge(<Test as Config>::Currency::minimum_balance() * 2), terminated: false,
terminated: false, }]
}] }
} )
)
});
} }
#[test] #[test]
@@ -638,34 +629,32 @@ mod tests {
assert_eq!(nested1_info.storage_deposit, 40); assert_eq!(nested1_info.storage_deposit, 40);
assert_eq!(nested2_info.storage_deposit, min_balance); assert_eq!(nested2_info.storage_deposit, min_balance);
TEST_EXT.with(|ext| { assert_eq!(
assert_eq!( TestExtTestValue::get(),
*ext.borrow(), TestExt {
TestExt { limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }],
limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], charges: vec![
charges: vec![ Charge {
Charge { origin: ALICE,
origin: ALICE, contract: CHARLIE,
contract: CHARLIE, amount: Deposit::Refund(10),
amount: Deposit::Refund(10), terminated: false
terminated: false },
}, Charge {
Charge { origin: ALICE,
origin: ALICE, contract: CHARLIE,
contract: CHARLIE, amount: Deposit::Refund(4),
amount: Deposit::Refund(4), terminated: false
terminated: false },
}, Charge {
Charge { origin: ALICE,
origin: ALICE, contract: BOB,
contract: BOB, amount: Deposit::Charge(2),
amount: Deposit::Charge(2), terminated: false
terminated: false }
} ]
] }
} )
)
});
} }
#[test] #[test]
@@ -697,27 +686,25 @@ mod tests {
meter.absorb(nested0, &ALICE, &BOB, None); meter.absorb(nested0, &ALICE, &BOB, None);
drop(meter); drop(meter);
TEST_EXT.with(|ext| { assert_eq!(
assert_eq!( TestExtTestValue::get(),
*ext.borrow(), TestExt {
TestExt { limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }],
limit_checks: vec![LimitCheck { origin: ALICE, limit: 1_000, min_leftover: 0 }], charges: vec![
charges: vec![ Charge {
Charge { origin: ALICE,
origin: ALICE, contract: CHARLIE,
contract: CHARLIE, amount: Deposit::Refund(400),
amount: Deposit::Refund(400), terminated: true
terminated: true },
}, Charge {
Charge { origin: ALICE,
origin: ALICE, contract: BOB,
contract: BOB, amount: Deposit::Charge(12),
amount: Deposit::Charge(12), terminated: false
terminated: false }
} ]
] }
} )
)
});
} }
} }
+28 -17
View File
@@ -51,7 +51,7 @@ use sp_runtime::{
traits::{BlakeTwo256, Convert, Hash, IdentityLookup}, traits::{BlakeTwo256, Convert, Hash, IdentityLookup},
AccountId32, AccountId32,
}; };
use std::{cell::RefCell, sync::Arc}; use std::sync::Arc;
use crate as pallet_contracts; use crate as pallet_contracts;
@@ -113,10 +113,11 @@ pub mod test_utils {
} }
} }
thread_local! { parameter_types! {
static TEST_EXTENSION: RefCell<TestExtension> = Default::default(); static TestExtensionTestValue: TestExtension = Default::default();
} }
#[derive(Clone)]
pub struct TestExtension { pub struct TestExtension {
enabled: bool, enabled: bool,
last_seen_buffer: Vec<u8>, last_seen_buffer: Vec<u8>,
@@ -136,15 +137,15 @@ pub struct TempStorageExtension {
impl TestExtension { impl TestExtension {
fn disable() { fn disable() {
TEST_EXTENSION.with(|e| e.borrow_mut().enabled = false) TestExtensionTestValue::mutate(|e| e.enabled = false)
} }
fn last_seen_buffer() -> Vec<u8> { fn last_seen_buffer() -> Vec<u8> {
TEST_EXTENSION.with(|e| e.borrow().last_seen_buffer.clone()) TestExtensionTestValue::get().last_seen_buffer.clone()
} }
fn last_seen_inputs() -> (u32, u32, u32, u32) { 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<Test> for TestExtension {
let mut env = env.buf_in_buf_out(); let mut env = env.buf_in_buf_out();
let input = env.read(8)?; let input = env.read(8)?;
env.write(&input, false, None)?; 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)) Ok(RetVal::Converging(id))
}, },
0x8001 => { 0x8001 => {
let env = env.only_in(); let env = env.only_in();
TEST_EXTENSION.with(|e| { TestExtensionTestValue::mutate(|e| {
e.borrow_mut().last_seen_inputs = e.last_seen_inputs = (env.val0(), env.val1(), env.val2(), env.val3())
(env.val0(), env.val1(), env.val2(), env.val3())
}); });
Ok(RetVal::Converging(id)) Ok(RetVal::Converging(id))
}, },
@@ -192,7 +192,7 @@ impl ChainExtension<Test> for TestExtension {
} }
fn enabled() -> bool { fn enabled() -> bool {
TEST_EXTENSION.with(|e| e.borrow().enabled) TestExtensionTestValue::get().enabled
} }
} }
@@ -210,7 +210,7 @@ impl ChainExtension<Test> for RevertingExtension {
} }
fn enabled() -> bool { fn enabled() -> bool {
TEST_EXTENSION.with(|e| e.borrow().enabled) TestExtensionTestValue::get().enabled
} }
} }
@@ -259,7 +259,7 @@ impl ChainExtension<Test> for TempStorageExtension {
} }
fn enabled() -> bool { fn enabled() -> bool {
TEST_EXTENSION.with(|e| e.borrow().enabled) TestExtensionTestValue::get().enabled
} }
} }
@@ -344,19 +344,30 @@ impl Convert<Weight, BalanceOf<Self>> for Test {
/// A filter whose filter function can be swapped at runtime. /// A filter whose filter function can be swapped at runtime.
pub struct TestFilter; pub struct TestFilter;
thread_local! { #[derive(Clone)]
static CALL_FILTER: RefCell<fn(&Call) -> bool> = RefCell::new(|_| true); 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 { impl TestFilter {
pub fn set_filter(filter: fn(&Call) -> bool) { pub fn set_filter(filter: fn(&Call) -> bool) {
CALL_FILTER.with(|fltr| *fltr.borrow_mut() = filter); CallFilter::mutate(|fltr| fltr.filter = filter);
} }
} }
impl Contains<Call> for TestFilter { impl Contains<Call> for TestFilter {
fn contains(call: &Call) -> bool { fn contains(call: &Call) -> bool {
CALL_FILTER.with(|fltr| fltr.borrow()(call)) (CallFilter::get().filter)(call)
} }
} }
@@ -241,8 +241,9 @@ impl pallet_balances::Config for Runtime {
type WeightInfo = (); type WeightInfo = ();
} }
#[derive(Eq, PartialEq, Debug, Clone, Copy)] #[derive(Default, Eq, PartialEq, Debug, Clone, Copy)]
pub enum MockedWeightInfo { pub enum MockedWeightInfo {
#[default]
Basic, Basic,
Complex, Complex,
Real, Real,
+22 -28
View File
@@ -835,12 +835,12 @@ mod tests {
pub struct RuntimeVersion; pub struct RuntimeVersion;
impl frame_support::traits::Get<sp_version::RuntimeVersion> for RuntimeVersion { impl frame_support::traits::Get<sp_version::RuntimeVersion> for RuntimeVersion {
fn get() -> sp_version::RuntimeVersion { fn get() -> sp_version::RuntimeVersion {
RUNTIME_VERSION.with(|v| v.borrow().clone()) RuntimeVersionTestValues::get().clone()
} }
} }
thread_local! { parameter_types! {
pub static RUNTIME_VERSION: std::cell::RefCell<sp_version::RuntimeVersion> = pub static RuntimeVersionTestValues: sp_version::RuntimeVersion =
Default::default(); Default::default();
} }
@@ -1239,14 +1239,13 @@ mod tests {
#[test] #[test]
fn runtime_upgraded_should_work() { fn runtime_upgraded_should_work() {
new_test_ext(1).execute_with(|| { 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 // It should be added at genesis
assert!(frame_system::LastRuntimeUpgrade::<Runtime>::exists()); assert!(frame_system::LastRuntimeUpgrade::<Runtime>::exists());
assert!(!Executive::runtime_upgraded()); assert!(!Executive::runtime_upgraded());
RUNTIME_VERSION.with(|v| { RuntimeVersionTestValues::mutate(|v| {
*v.borrow_mut() = *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
}); });
assert!(Executive::runtime_upgraded()); assert!(Executive::runtime_upgraded());
assert_eq!( assert_eq!(
@@ -1254,8 +1253,8 @@ mod tests {
frame_system::LastRuntimeUpgrade::<Runtime>::get(), frame_system::LastRuntimeUpgrade::<Runtime>::get(),
); );
RUNTIME_VERSION.with(|v| { RuntimeVersionTestValues::mutate(|v| {
*v.borrow_mut() = sp_version::RuntimeVersion { *v = sp_version::RuntimeVersion {
spec_version: 1, spec_version: 1,
spec_name: "test".into(), spec_name: "test".into(),
..Default::default() ..Default::default()
@@ -1267,8 +1266,8 @@ mod tests {
frame_system::LastRuntimeUpgrade::<Runtime>::get(), frame_system::LastRuntimeUpgrade::<Runtime>::get(),
); );
RUNTIME_VERSION.with(|v| { RuntimeVersionTestValues::mutate(|v| {
*v.borrow_mut() = sp_version::RuntimeVersion { *v = sp_version::RuntimeVersion {
spec_version: 1, spec_version: 1,
spec_name: "test".into(), spec_name: "test".into(),
impl_version: 2, impl_version: 2,
@@ -1316,9 +1315,8 @@ mod tests {
fn custom_runtime_upgrade_is_called_before_modules() { fn custom_runtime_upgrade_is_called_before_modules() {
new_test_ext(1).execute_with(|| { new_test_ext(1).execute_with(|| {
// Make sure `on_runtime_upgrade` is called. // Make sure `on_runtime_upgrade` is called.
RUNTIME_VERSION.with(|v| { RuntimeVersionTestValues::mutate(|v| {
*v.borrow_mut() = *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
}); });
Executive::initialize_block(&Header::new( Executive::initialize_block(&Header::new(
@@ -1338,9 +1336,8 @@ mod tests {
fn event_from_runtime_upgrade_is_included() { fn event_from_runtime_upgrade_is_included() {
new_test_ext(1).execute_with(|| { new_test_ext(1).execute_with(|| {
// Make sure `on_runtime_upgrade` is called. // Make sure `on_runtime_upgrade` is called.
RUNTIME_VERSION.with(|v| { RuntimeVersionTestValues::mutate(|v| {
*v.borrow_mut() = *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
}); });
// set block number to non zero so events are not excluded // 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(|| { let header = new_test_ext(1).execute_with(|| {
// Make sure `on_runtime_upgrade` is called. // Make sure `on_runtime_upgrade` is called.
RUNTIME_VERSION.with(|v| { RuntimeVersionTestValues::mutate(|v| {
*v.borrow_mut() = *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
}); });
// Let's build some fake block. // Let's build some fake block.
@@ -1389,15 +1385,14 @@ mod tests {
}); });
// Reset to get the correct new genesis below. // Reset to get the correct new genesis below.
RUNTIME_VERSION.with(|v| { RuntimeVersionTestValues::mutate(|v| {
*v.borrow_mut() = sp_version::RuntimeVersion { spec_version: 0, ..Default::default() } *v = sp_version::RuntimeVersion { spec_version: 0, ..Default::default() }
}); });
new_test_ext(1).execute_with(|| { new_test_ext(1).execute_with(|| {
// Make sure `on_runtime_upgrade` is called. // Make sure `on_runtime_upgrade` is called.
RUNTIME_VERSION.with(|v| { RuntimeVersionTestValues::mutate(|v| {
*v.borrow_mut() = *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
}); });
<Executive as ExecuteBlock<Block<TestXt>>>::execute_block(Block::new(header, vec![xt])); <Executive as ExecuteBlock<Block<TestXt>>>::execute_block(Block::new(header, vec![xt]));
@@ -1411,9 +1406,8 @@ mod tests {
fn all_weights_are_recorded_correctly() { fn all_weights_are_recorded_correctly() {
new_test_ext(1).execute_with(|| { new_test_ext(1).execute_with(|| {
// Make sure `on_runtime_upgrade` is called for maximum complexity // Make sure `on_runtime_upgrade` is called for maximum complexity
RUNTIME_VERSION.with(|v| { RuntimeVersionTestValues::mutate(|v| {
*v.borrow_mut() = *v = sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
sp_version::RuntimeVersion { spec_version: 1, ..Default::default() }
}); });
let block_number = 1; let block_number = 1;
+15 -19
View File
@@ -19,8 +19,6 @@
#![cfg(test)] #![cfg(test)]
use std::cell::RefCell;
use frame_support::{ use frame_support::{
parameter_types, parameter_types,
traits::{ConstU32, ConstU64}, traits::{ConstU32, ConstU64},
@@ -57,18 +55,18 @@ frame_support::construct_runtime!(
} }
); );
thread_local! { parameter_types! {
pub static VALIDATORS: RefCell<Option<Vec<u64>>> = RefCell::new(Some(vec![ pub static Validators: Option<Vec<u64>> = Some(vec![
1, 1,
2, 2,
3, 3,
])); ]);
} }
pub struct TestSessionManager; pub struct TestSessionManager;
impl pallet_session::SessionManager<u64> for TestSessionManager { impl pallet_session::SessionManager<u64> for TestSessionManager {
fn new_session(_new_index: SessionIndex) -> Option<Vec<u64>> { fn new_session(_new_index: SessionIndex) -> Option<Vec<u64>> {
VALIDATORS.with(|l| l.borrow_mut().take()) Validators::mutate(|l| l.take())
} }
fn end_session(_: SessionIndex) {} fn end_session(_: SessionIndex) {}
fn start_session(_: SessionIndex) {} fn start_session(_: SessionIndex) {}
@@ -76,10 +74,8 @@ impl pallet_session::SessionManager<u64> for TestSessionManager {
impl pallet_session::historical::SessionManager<u64, u64> for TestSessionManager { impl pallet_session::historical::SessionManager<u64, u64> for TestSessionManager {
fn new_session(_new_index: SessionIndex) -> Option<Vec<(u64, u64)>> { fn new_session(_new_index: SessionIndex) -> Option<Vec<(u64, u64)>> {
VALIDATORS.with(|l| { Validators::mutate(|l| {
l.borrow_mut() l.take().map(|validators| validators.iter().map(|v| (*v, *v)).collect())
.take()
.map(|validators| validators.iter().map(|v| (*v, *v)).collect())
}) })
} }
fn end_session(_: SessionIndex) {} fn end_session(_: SessionIndex) {}
@@ -91,15 +87,15 @@ pub type Extrinsic = TestXt<Call, ()>;
type IdentificationTuple = (u64, u64); type IdentificationTuple = (u64, u64);
type Offence = crate::UnresponsivenessOffence<IdentificationTuple>; type Offence = crate::UnresponsivenessOffence<IdentificationTuple>;
thread_local! { parameter_types! {
pub static OFFENCES: RefCell<Vec<(Vec<u64>, Offence)>> = RefCell::new(vec![]); pub static Offences: Vec<(Vec<u64>, Offence)> = vec![];
} }
/// A mock offence report handler. /// A mock offence report handler.
pub struct OffenceHandler; pub struct OffenceHandler;
impl ReportOffence<u64, IdentificationTuple, Offence> for OffenceHandler { impl ReportOffence<u64, IdentificationTuple, Offence> for OffenceHandler {
fn report_offence(reporters: Vec<u64>, offence: Offence) -> Result<(), OffenceError> { fn report_offence(reporters: Vec<u64>, offence: Offence) -> Result<(), OffenceError> {
OFFENCES.with(|l| l.borrow_mut().push((reporters, offence))); Offences::mutate(|l| l.push((reporters, offence)));
Ok(()) Ok(())
} }
@@ -183,12 +179,12 @@ impl pallet_authorship::Config for Runtime {
type EventHandler = ImOnline; type EventHandler = ImOnline;
} }
thread_local! { parameter_types! {
pub static MOCK_CURRENT_SESSION_PROGRESS: RefCell<Option<Option<Permill>>> = RefCell::new(None); pub static MockCurrentSessionProgress: Option<Option<Permill>> = None;
} }
thread_local! { parameter_types! {
pub static MOCK_AVERAGE_SESSION_LENGTH: RefCell<Option<u64>> = RefCell::new(None); pub static MockAverageSessionLength: Option<u64> = None;
} }
pub struct TestNextSessionRotation; pub struct TestNextSessionRotation;
@@ -196,7 +192,7 @@ pub struct TestNextSessionRotation;
impl frame_support::traits::EstimateNextSessionRotation<u64> for TestNextSessionRotation { impl frame_support::traits::EstimateNextSessionRotation<u64> for TestNextSessionRotation {
fn average_session_length() -> u64 { fn average_session_length() -> u64 {
// take the mock result if any and return it // 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::<Period, Offset>::average_session_length()) mock.unwrap_or(pallet_session::PeriodicSessions::<Period, Offset>::average_session_length())
} }
@@ -208,7 +204,7 @@ impl frame_support::traits::EstimateNextSessionRotation<u64> for TestNextSession
); );
// take the mock result if any and return it // 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) (mock.unwrap_or(estimate), weight)
} }
+19 -22
View File
@@ -68,7 +68,7 @@ fn should_report_offline_validators() {
advance_session(); advance_session();
// enact the change and buffer another one // enact the change and buffer another one
let validators = vec![1, 2, 3, 4, 5, 6]; 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(); advance_session();
// when // when
@@ -76,7 +76,7 @@ fn should_report_offline_validators() {
advance_session(); advance_session();
// then // then
let offences = OFFENCES.with(|l| l.replace(vec![])); let offences = Offences::take();
assert_eq!( assert_eq!(
offences, offences,
vec![( vec![(
@@ -96,7 +96,7 @@ fn should_report_offline_validators() {
advance_session(); advance_session();
// then // then
let offences = OFFENCES.with(|l| l.replace(vec![])); let offences = Offences::take();
assert_eq!( assert_eq!(
offences, offences,
vec![( vec![(
@@ -149,7 +149,7 @@ fn should_mark_online_validator_when_heartbeat_is_received() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
advance_session(); advance_session();
// given // 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::<u64>::new()); assert_eq!(Session::validators(), Vec::<u64>::new());
// enact the change and buffer another one // enact the change and buffer another one
advance_session(); advance_session();
@@ -184,7 +184,7 @@ fn late_heartbeat_and_invalid_keys_len_should_fail() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
advance_session(); advance_session();
// given // 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::<u64>::new()); assert_eq!(Session::validators(), Vec::<u64>::new());
// enact the change and buffer another one // enact the change and buffer another one
advance_session(); advance_session();
@@ -226,7 +226,7 @@ fn should_generate_heartbeats() {
// buffer new validators // buffer new validators
Session::rotate_session(); Session::rotate_session();
// enact the change and buffer another one // 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(); Session::rotate_session();
// when // when
@@ -262,7 +262,7 @@ fn should_cleanup_received_heartbeats_on_session_end() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
advance_session(); 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::<u64>::new()); assert_eq!(Session::validators(), Vec::<u64>::new());
// enact the change and buffer another one // 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(|| { new_test_ext().execute_with(|| {
advance_session(); advance_session();
// given // 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::<u64>::new()); assert_eq!(Session::validators(), Vec::<u64>::new());
// enact the change and buffer another one // enact the change and buffer another one
advance_session(); advance_session();
@@ -330,7 +330,7 @@ fn should_not_send_a_report_if_already_online() {
ext.execute_with(|| { ext.execute_with(|| {
advance_session(); advance_session();
// given // 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::<u64>::new()); assert_eq!(Session::validators(), Vec::<u64>::new());
// enact the change and buffer another one // enact the change and buffer another one
advance_session(); advance_session();
@@ -393,12 +393,12 @@ fn should_handle_missing_progress_estimates() {
Session::rotate_session(); Session::rotate_session();
// enact the change and buffer another one // 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(); Session::rotate_session();
// we will return `None` on the next call to `estimate_current_session_progress` // we will return `None` on the next call to `estimate_current_session_progress`
// and the offchain worker should fallback to checking `HeartbeatAfter` // 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); ImOnline::offchain_worker(block);
assert_eq!(state.read().transactions.len(), 3); 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, // mock the session length as being 10 blocks long,
// enact the change and buffer another one // 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 // mock the session length has being 10 which should make us assume the fallback for half
// session will be reached by block 5. // 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(); Session::rotate_session();
// if we don't have valid results for the current session progres then // if we don't have valid results for the current session progres then
// we'll fallback to `HeartbeatAfter` and only heartbeat on block 5. // 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)); 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()); assert!(ImOnline::send_heartbeats(5).ok().is_some());
// if we have a valid current session progress then we'll heartbeat as soon // 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 // as we're past 80% of the session regardless of the block number
MOCK_CURRENT_SESSION_PROGRESS MockCurrentSessionProgress::mutate(|p| *p = Some(Some(Permill::from_percent(81))));
.with(|p| *p.borrow_mut() = Some(Some(Permill::from_percent(81))));
assert!(ImOnline::send_heartbeats(2).ok().is_some()); assert!(ImOnline::send_heartbeats(2).ok().is_some());
}); });
@@ -464,8 +463,7 @@ fn test_does_not_heartbeat_early_in_the_session() {
ext.execute_with(|| { ext.execute_with(|| {
// mock current session progress as being 5%. we only randomly start // mock current session progress as being 5%. we only randomly start
// heartbeating after 10% of the session has elapsed. // heartbeating after 10% of the session has elapsed.
MOCK_CURRENT_SESSION_PROGRESS MockCurrentSessionProgress::mutate(|p| *p = Some(Some(Permill::from_float(0.05))));
.with(|p| *p.borrow_mut() = Some(Some(Permill::from_float(0.05))));
assert_eq!(ImOnline::send_heartbeats(2).err(), Some(OffchainErr::TooEarly)); 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| { let set_test = |progress, random: f64| {
// the average session length is 100 blocks, therefore the residual // the average session length is 100 blocks, therefore the residual
// probability of sending a heartbeat is 1% // probability of sending a heartbeat is 1%
MOCK_AVERAGE_SESSION_LENGTH.with(|p| *p.borrow_mut() = Some(100)); MockAverageSessionLength::mutate(|p| *p = Some(100));
MOCK_CURRENT_SESSION_PROGRESS MockCurrentSessionProgress::mutate(|p| *p = Some(Some(Permill::from_float(progress))));
.with(|p| *p.borrow_mut() = Some(Some(Permill::from_float(progress))));
let mut seed = [0u8; 32]; let mut seed = [0u8; 32];
let encoded = ((random * Permill::ACCURACY as f64) as u32).encode(); let encoded = ((random * Permill::ACCURACY as f64) as u32).encode();
@@ -19,14 +19,17 @@ use crate as pallet_mmr;
use crate::*; use crate::*;
use codec::{Decode, Encode}; use codec::{Decode, Encode};
use frame_support::traits::{ConstU32, ConstU64}; use frame_support::{
parameter_types,
traits::{ConstU32, ConstU64},
};
use sp_core::H256; use sp_core::H256;
use sp_mmr_primitives::{Compact, LeafDataProvider}; use sp_mmr_primitives::{Compact, LeafDataProvider};
use sp_runtime::{ use sp_runtime::{
testing::Header, testing::Header,
traits::{BlakeTwo256, IdentityLookup, Keccak256}, traits::{BlakeTwo256, IdentityLookup, Keccak256},
}; };
use sp_std::{cell::RefCell, prelude::*}; use sp_std::prelude::*;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>; type Block = frame_system::mocking::MockBlock<Test>;
@@ -91,14 +94,14 @@ impl LeafData {
} }
} }
thread_local! { parameter_types! {
pub static LEAF_DATA: RefCell<LeafData> = RefCell::new(Default::default()); pub static LeafDataTestValue: LeafData = Default::default();
} }
impl LeafDataProvider for LeafData { impl LeafDataProvider for LeafData {
type LeafData = Self; type LeafData = Self;
fn leaf_data() -> Self::LeafData { fn leaf_data() -> Self::LeafData {
LEAF_DATA.with(|r| r.borrow().clone()) LeafDataTestValue::get().clone()
} }
} }
@@ -42,7 +42,7 @@ fn register_offchain_ext(ext: &mut sp_io::TestExternalities) {
fn new_block() -> Weight { fn new_block() -> Weight {
let number = frame_system::Pallet::<Test>::block_number() + 1; let number = frame_system::Pallet::<Test>::block_number() + 1;
let hash = H256::repeat_byte(number as u8); 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::<Test>::reset_events(); frame_system::Pallet::<Test>::reset_events();
frame_system::Pallet::<Test>::initialize(&number, &hash, &Default::default()); frame_system::Pallet::<Test>::initialize(&number, &hash, &Default::default());
+7 -8
View File
@@ -40,13 +40,12 @@ use sp_staking::{
offence::{self, DisableStrategy, Kind, OffenceDetails}, offence::{self, DisableStrategy, Kind, OffenceDetails},
SessionIndex, SessionIndex,
}; };
use std::cell::RefCell;
pub struct OnOffenceHandler; pub struct OnOffenceHandler;
thread_local! { parameter_types! {
pub static ON_OFFENCE_PERBILL: RefCell<Vec<Perbill>> = RefCell::new(Default::default()); pub static OnOffencePerbill: Vec<Perbill> = Default::default();
pub static OFFENCE_WEIGHT: RefCell<Weight> = RefCell::new(Default::default()); pub static OffenceWeight: Weight = Default::default();
} }
impl<Reporter, Offender> offence::OnOffenceHandler<Reporter, Offender, Weight> impl<Reporter, Offender> offence::OnOffenceHandler<Reporter, Offender, Weight>
@@ -58,16 +57,16 @@ impl<Reporter, Offender> offence::OnOffenceHandler<Reporter, Offender, Weight>
_offence_session: SessionIndex, _offence_session: SessionIndex,
_disable_strategy: DisableStrategy, _disable_strategy: DisableStrategy,
) -> Weight { ) -> Weight {
ON_OFFENCE_PERBILL.with(|f| { OnOffencePerbill::mutate(|f| {
*f.borrow_mut() = slash_fraction.to_vec(); *f = slash_fraction.to_vec();
}); });
OFFENCE_WEIGHT.with(|w| *w.borrow()) OffenceWeight::get()
} }
} }
pub fn with_on_offence_fractions<R, F: FnOnce(&mut Vec<Perbill>) -> R>(f: F) -> R { pub fn with_on_offence_fractions<R, F: FnOnce(&mut Vec<Perbill>) -> 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<Runtime>; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Runtime>;
+8 -9
View File
@@ -39,15 +39,14 @@ use sp_runtime::{
#[frame_support::pallet] #[frame_support::pallet]
pub mod logger { pub mod logger {
use super::{OriginCaller, OriginTrait}; use super::{OriginCaller, OriginTrait};
use frame_support::pallet_prelude::*; use frame_support::{pallet_prelude::*, parameter_types};
use frame_system::pallet_prelude::*; use frame_system::pallet_prelude::*;
use std::cell::RefCell;
thread_local! { parameter_types! {
static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new()); static Log: Vec<(OriginCaller, u32)> = Vec::new();
} }
pub fn log() -> Vec<(OriginCaller, u32)> { pub fn log() -> Vec<(OriginCaller, u32)> {
LOG.with(|log| log.borrow().clone()) Log::get().clone()
} }
#[pallet::pallet] #[pallet::pallet]
@@ -76,8 +75,8 @@ pub mod logger {
#[pallet::weight(*weight)] #[pallet::weight(*weight)]
pub fn log(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult { pub fn log(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {
Self::deposit_event(Event::Logged(i, weight)); Self::deposit_event(Event::Logged(i, weight));
LOG.with(|log| { Log::mutate(|log| {
log.borrow_mut().push((origin.caller().clone(), i)); log.push((origin.caller().clone(), i));
}); });
Ok(()) Ok(())
} }
@@ -85,8 +84,8 @@ pub mod logger {
#[pallet::weight(*weight)] #[pallet::weight(*weight)]
pub fn log_without_filter(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult { pub fn log_without_filter(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {
Self::deposit_event(Event::Logged(i, weight)); Self::deposit_event(Event::Logged(i, weight));
LOG.with(|log| { Log::mutate(|log| {
log.borrow_mut().push((origin.caller().clone(), i)); log.push((origin.caller().clone(), i));
}); });
Ok(()) Ok(())
} }
+5 -6
View File
@@ -30,7 +30,6 @@ use sp_runtime::{
testing::Header, testing::Header,
traits::{BlakeTwo256, IdentityLookup}, traits::{BlakeTwo256, IdentityLookup},
}; };
use std::cell::RefCell;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>; type Block = frame_system::mocking::MockBlock<Test>;
@@ -96,14 +95,14 @@ impl pallet_balances::Config for Test {
type WeightInfo = (); type WeightInfo = ();
} }
thread_local! { parameter_types! {
pub static MEMBERS: RefCell<Vec<u64>> = RefCell::new(vec![]); pub static MembersTestValue: Vec<u64> = vec![];
} }
pub struct TestChangeMembers; pub struct TestChangeMembers;
impl ChangeMembers<u64> for TestChangeMembers { impl ChangeMembers<u64> for TestChangeMembers {
fn change_members_sorted(incoming: &[u64], outgoing: &[u64], new: &[u64]) { 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.extend_from_slice(incoming);
old_plus_incoming.sort(); old_plus_incoming.sort();
@@ -113,13 +112,13 @@ impl ChangeMembers<u64> for TestChangeMembers {
assert_eq!(old_plus_incoming, new_plus_outgoing); 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<u64> for TestChangeMembers { impl InitializeMembers<u64> for TestChangeMembers {
fn initialize_members(new_members: &[u64]) { fn initialize_members(new_members: &[u64]) {
MEMBERS.with(|m| *m.borrow_mut() = new_members.to_vec()); MembersTestValue::mutate(|m| *m = new_members.to_vec());
} }
} }
+5 -5
View File
@@ -33,7 +33,7 @@ fn query_membership_works() {
assert_eq!(ScoredPool::members(), vec![20, 40]); assert_eq!(ScoredPool::members(), vec![20, 40]);
assert_eq!(Balances::reserved_balance(31), CandidateDeposit::get()); assert_eq!(Balances::reserved_balance(31), CandidateDeposit::get());
assert_eq!(Balances::reserved_balance(40), 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 // then
assert_eq!(find_in_pool(who), None); assert_eq!(find_in_pool(who), None);
assert_eq!(ScoredPool::members(), vec![20, 31]); 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 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 // then
// the `None` candidates should not have been filled in // the `None` candidates should not have been filled in
assert!(ScoredPool::members().is_empty()); 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 // then
assert_eq!(ScoredPool::members(), vec![15, 40]); 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 // then
assert_eq!(ScoredPool::members(), vec![15, 40]); assert_eq!(ScoredPool::members(), vec![15, 40]);
assert_eq!(MEMBERS.with(|m| m.borrow().clone()), ScoredPool::members()); assert_eq!(MembersTestValue::get().clone(), ScoredPool::members());
}); });
} }
@@ -375,7 +375,7 @@ impl<T: Config, D: AsRef<[u8]>> KeyOwnerProofSystem<(KeyTypeId, D)> for Pallet<T
pub(crate) mod tests { pub(crate) mod tests {
use super::*; use super::*;
use crate::mock::{ use crate::mock::{
force_new_session, set_next_validators, Session, System, Test, NEXT_VALIDATORS, force_new_session, set_next_validators, NextValidators, Session, System, Test,
}; };
use sp_runtime::{key_types::DUMMY, testing::UintAuthorityId}; use sp_runtime::{key_types::DUMMY, testing::UintAuthorityId};
@@ -389,9 +389,11 @@ pub(crate) mod tests {
pub(crate) fn new_test_ext() -> sp_io::TestExternalities { pub(crate) fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap(); let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let keys: Vec<_> = NEXT_VALIDATORS.with(|l| { let keys: Vec<_> = NextValidators::get()
l.borrow().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect() .iter()
}); .cloned()
.map(|i| (i, i, UintAuthorityId(i).into()))
.collect();
BasicExternalities::execute_with_storage(&mut t, || { BasicExternalities::execute_with_storage(&mut t, || {
for (ref k, ..) in &keys { for (ref k, ..) in &keys {
frame_system::Pallet::<Test>::inc_providers(k); frame_system::Pallet::<Test>::inc_providers(k);
@@ -141,7 +141,7 @@ mod tests {
use super::*; use super::*;
use crate::{ use crate::{
historical::{onchain, Pallet}, 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; use codec::Encode;
@@ -163,9 +163,12 @@ mod tests {
.build_storage::<Test>() .build_storage::<Test>()
.expect("Failed to create test externalities."); .expect("Failed to create test externalities.");
let keys: Vec<_> = NEXT_VALIDATORS.with(|l| { let keys: Vec<_> = NextValidators::get()
l.borrow().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect() .iter()
}); .cloned()
.map(|i| (i, i, UintAuthorityId(i).into()))
.collect();
BasicExternalities::execute_with_storage(&mut t, || { BasicExternalities::execute_with_storage(&mut t, || {
for (ref k, ..) in &keys { for (ref k, ..) in &keys {
frame_system::Pallet::<Test>::inc_providers(k); frame_system::Pallet::<Test>::inc_providers(k);
+44 -43
View File
@@ -22,7 +22,7 @@ use crate as pallet_session;
#[cfg(feature = "historical")] #[cfg(feature = "historical")]
use crate::historical as pallet_session_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_core::{crypto::key_types::DUMMY, H256};
use sp_runtime::{ use sp_runtime::{
@@ -103,29 +103,29 @@ frame_support::construct_runtime!(
} }
); );
thread_local! { parameter_types! {
pub static VALIDATORS: RefCell<Vec<u64>> = RefCell::new(vec![1, 2, 3]); pub static Validators: Vec<u64> = vec![1, 2, 3];
pub static NEXT_VALIDATORS: RefCell<Vec<u64>> = RefCell::new(vec![1, 2, 3]); pub static NextValidators: Vec<u64> = vec![1, 2, 3];
pub static AUTHORITIES: RefCell<Vec<UintAuthorityId>> = pub static Authorities: Vec<UintAuthorityId> =
RefCell::new(vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)];
pub static FORCE_SESSION_END: RefCell<bool> = RefCell::new(false); pub static ForceSessionEnd: bool = false;
pub static SESSION_LENGTH: RefCell<u64> = RefCell::new(2); pub static SessionLength: u64 = 2;
pub static SESSION_CHANGED: RefCell<bool> = RefCell::new(false); pub static SessionChanged: bool = false;
pub static TEST_SESSION_CHANGED: RefCell<bool> = RefCell::new(false); pub static TestSessionChanged: bool = false;
pub static DISABLED: RefCell<bool> = RefCell::new(false); pub static Disabled: bool = false;
// Stores if `on_before_session_end` was called // Stores if `on_before_session_end` was called
pub static BEFORE_SESSION_END_CALLED: RefCell<bool> = RefCell::new(false); pub static BeforeSessionEndCalled: bool = false;
pub static VALIDATOR_ACCOUNTS: RefCell<BTreeMap<u64, u64>> = RefCell::new(BTreeMap::new()); pub static ValidatorAccounts: BTreeMap<u64, u64> = BTreeMap::new();
} }
pub struct TestShouldEndSession; pub struct TestShouldEndSession;
impl ShouldEndSession<u64> for TestShouldEndSession { impl ShouldEndSession<u64> for TestShouldEndSession {
fn should_end_session(now: u64) -> bool { fn should_end_session(now: u64) -> bool {
let l = SESSION_LENGTH.with(|l| *l.borrow()); let l = SessionLength::get();
now % l == 0 || now % l == 0 ||
FORCE_SESSION_END.with(|l| { ForceSessionEnd::mutate(|l| {
let r = *l.borrow(); let r = *l;
*l.borrow_mut() = false; *l = false;
r r
}) })
} }
@@ -140,19 +140,19 @@ impl SessionHandler<u64> for TestSessionHandler {
validators: &[(u64, T)], validators: &[(u64, T)],
_queued_validators: &[(u64, T)], _queued_validators: &[(u64, T)],
) { ) {
SESSION_CHANGED.with(|l| *l.borrow_mut() = changed); SessionChanged::mutate(|l| *l = changed);
AUTHORITIES.with(|l| { Authorities::mutate(|l| {
*l.borrow_mut() = validators *l = validators
.iter() .iter()
.map(|(_, id)| id.get::<UintAuthorityId>(DUMMY).unwrap_or_default()) .map(|(_, id)| id.get::<UintAuthorityId>(DUMMY).unwrap_or_default())
.collect() .collect()
}); });
} }
fn on_disabled(_validator_index: u32) { fn on_disabled(_validator_index: u32) {
DISABLED.with(|l| *l.borrow_mut() = true) Disabled::mutate(|l| *l = true)
} }
fn on_before_session_ending() { 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<u64> for TestSessionManager {
fn end_session(_: SessionIndex) {} fn end_session(_: SessionIndex) {}
fn start_session(_: SessionIndex) {} fn start_session(_: SessionIndex) {}
fn new_session(_: SessionIndex) -> Option<Vec<u64>> { fn new_session(_: SessionIndex) -> Option<Vec<u64>> {
if !TEST_SESSION_CHANGED.with(|l| *l.borrow()) { if !TestSessionChanged::get() {
VALIDATORS.with(|v| { Validators::mutate(|v| {
let mut v = v.borrow_mut(); *v = NextValidators::get().clone();
*v = NEXT_VALIDATORS.with(|l| l.borrow().clone());
Some(v.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 // If there was a disabled validator, underlying conditions have changed
// so we return `Some`. // so we return `Some`.
Some(VALIDATORS.with(|v| v.borrow().clone())) Some(Validators::get().clone())
} else { } else {
None None
} }
@@ -188,37 +187,40 @@ impl crate::historical::SessionManager<u64, u64> for TestSessionManager {
} }
pub fn authorities() -> Vec<UintAuthorityId> { pub fn authorities() -> Vec<UintAuthorityId> {
AUTHORITIES.with(|l| l.borrow().to_vec()) Authorities::get().to_vec()
} }
pub fn force_new_session() { 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) { 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 { pub fn session_changed() -> bool {
SESSION_CHANGED.with(|l| *l.borrow()) SessionChanged::get()
} }
pub fn set_next_validators(next: Vec<u64>) { pub fn set_next_validators(next: Vec<u64>) {
NEXT_VALIDATORS.with(|v| *v.borrow_mut() = next); NextValidators::mutate(|v| *v = next);
} }
pub fn before_session_end_called() -> bool { pub fn before_session_end_called() -> bool {
BEFORE_SESSION_END_CALLED.with(|b| *b.borrow()) BeforeSessionEndCalled::get()
} }
pub fn reset_before_session_end_called() { 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 { pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap(); let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let keys: Vec<_> = NEXT_VALIDATORS let keys: Vec<_> = NextValidators::get()
.with(|l| l.borrow().iter().cloned().map(|i| (i, i, UintAuthorityId(i).into())).collect()); .iter()
.cloned()
.map(|i| (i, i, UintAuthorityId(i).into()))
.collect();
BasicExternalities::execute_with_storage(&mut t, || { BasicExternalities::execute_with_storage(&mut t, || {
for (ref k, ..) in &keys { for (ref k, ..) in &keys {
frame_system::Pallet::<Test>::inc_providers(k); frame_system::Pallet::<Test>::inc_providers(k);
@@ -230,10 +232,9 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
pallet_session::GenesisConfig::<Test> { keys } pallet_session::GenesisConfig::<Test> { keys }
.assimilate_storage(&mut t) .assimilate_storage(&mut t)
.unwrap(); .unwrap();
NEXT_VALIDATORS.with(|l| {
let v = l.borrow().iter().map(|&i| (i, i)).collect(); let v = NextValidators::get().iter().map(|&i| (i, i)).collect();
VALIDATOR_ACCOUNTS.with(|m| *m.borrow_mut() = v); ValidatorAccounts::mutate(|m| *m = v);
});
sp_io::TestExternalities::new(t) sp_io::TestExternalities::new(t)
} }
@@ -279,12 +280,12 @@ impl pallet_timestamp::Config for Test {
pub struct TestValidatorIdOf; pub struct TestValidatorIdOf;
impl TestValidatorIdOf { impl TestValidatorIdOf {
pub fn set(v: BTreeMap<u64, u64>) { pub fn set(v: BTreeMap<u64, u64>) {
VALIDATOR_ACCOUNTS.with(|m| *m.borrow_mut() = v); ValidatorAccounts::mutate(|m| *m = v);
} }
} }
impl Convert<u64, Option<u64>> for TestValidatorIdOf { impl Convert<u64, Option<u64>> for TestValidatorIdOf {
fn convert(x: u64) -> Option<u64> { fn convert(x: u64) -> Option<u64> {
VALIDATOR_ACCOUNTS.with(|m| m.borrow().get(&x).cloned()) ValidatorAccounts::get().get(&x).cloned()
} }
} }
+6 -6
View File
@@ -21,8 +21,8 @@ use super::*;
use crate::mock::{ use crate::mock::{
authorities, before_session_end_called, force_new_session, new_test_ext, authorities, before_session_end_called, force_new_session, new_test_ext,
reset_before_session_end_called, session_changed, set_next_validators, set_session_length, reset_before_session_end_called, session_changed, set_next_validators, set_session_length,
Origin, PreUpgradeMockSessionKeys, Session, System, Test, TestValidatorIdOf, SESSION_CHANGED, Origin, PreUpgradeMockSessionKeys, Session, SessionChanged, System, Test, TestSessionChanged,
TEST_SESSION_CHANGED, TestValidatorIdOf,
}; };
use codec::Decode; use codec::Decode;
@@ -35,7 +35,7 @@ use frame_support::{
}; };
fn initialize_block(block: u64) { fn initialize_block(block: u64) {
SESSION_CHANGED.with(|l| *l.borrow_mut() = false); SessionChanged::mutate(|l| *l = false);
System::set_block_number(block); System::set_block_number(block);
Session::on_initialize(block); Session::on_initialize(block);
} }
@@ -235,7 +235,7 @@ fn session_changed_flag_works() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
TestValidatorIdOf::set(vec![(1, 1), (2, 2), (3, 3), (69, 69)].into_iter().collect()); 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(); force_new_session();
initialize_block(1); initialize_block(1);
@@ -384,8 +384,8 @@ fn upgrade_keys() {
use sp_core::crypto::key_types::DUMMY; use sp_core::crypto::key_types::DUMMY;
// This test assumes certain mocks. // This test assumes certain mocks.
assert_eq!(mock::NEXT_VALIDATORS.with(|l| l.borrow().clone()), vec![1, 2, 3]); assert_eq!(mock::NextValidators::get().clone(), vec![1, 2, 3]);
assert_eq!(mock::VALIDATORS.with(|l| l.borrow().clone()), vec![1, 2, 3]); assert_eq!(mock::Validators::get().clone(), vec![1, 2, 3]);
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
let pre_one = PreUpgradeMockSessionKeys { a: [1u8; 32], b: [1u8; 64] }; let pre_one = PreUpgradeMockSessionKeys { a: [1u8; 32], b: [1u8; 64] };
+4 -5
View File
@@ -37,7 +37,6 @@ use sp_runtime::{
traits::{IdentityLookup, Zero}, traits::{IdentityLookup, Zero},
}; };
use sp_staking::offence::{DisableStrategy, OffenceDetails, OnOffenceHandler}; use sp_staking::offence::{DisableStrategy, OffenceDetails, OnOffenceHandler};
use std::cell::RefCell;
pub const INIT_TIMESTAMP: u64 = 30_000; pub const INIT_TIMESTAMP: u64 = 30_000;
pub const BLOCK_TIME: u64 = 1000; pub const BLOCK_TIME: u64 = 1000;
@@ -216,16 +215,16 @@ parameter_types! {
pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(75); pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(75);
} }
thread_local! { parameter_types! {
pub static REWARD_REMAINDER_UNBALANCED: RefCell<u128> = RefCell::new(0); pub static RewardRemainderUnbalanced: u128 = 0;
} }
pub struct RewardRemainderMock; pub struct RewardRemainderMock;
impl OnUnbalanced<NegativeImbalanceOf<Test>> for RewardRemainderMock { impl OnUnbalanced<NegativeImbalanceOf<Test>> for RewardRemainderMock {
fn on_nonzero_unbalanced(amount: NegativeImbalanceOf<Test>) { fn on_nonzero_unbalanced(amount: NegativeImbalanceOf<Test>) {
REWARD_REMAINDER_UNBALANCED.with(|v| { RewardRemainderUnbalanced::mutate(|v| {
*v.borrow_mut() += amount.peek(); *v += amount.peek();
}); });
drop(amount); drop(amount);
} }
+2 -5
View File
@@ -301,10 +301,7 @@ fn rewards_should_work() {
start_session(3); start_session(3);
assert_eq!(active_era(), 1); assert_eq!(active_era(), 1);
assert_eq!( assert_eq!(mock::RewardRemainderUnbalanced::get(), maximum_payout - total_payout_0,);
mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()),
maximum_payout - total_payout_0,
);
assert_eq!( assert_eq!(
*mock::staking_events().last().unwrap(), *mock::staking_events().last().unwrap(),
Event::EraPaid(0, total_payout_0, maximum_payout - total_payout_0) Event::EraPaid(0, total_payout_0, maximum_payout - total_payout_0)
@@ -340,7 +337,7 @@ fn rewards_should_work() {
mock::start_active_era(2); mock::start_active_era(2);
assert_eq!( assert_eq!(
mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()), mock::RewardRemainderUnbalanced::get(),
maximum_payout * 2 - total_payout_0 - total_payout_1, maximum_payout * 2 - total_payout_0 - total_payout_1,
); );
assert_eq!( assert_eq!(
+15
View File
@@ -446,6 +446,21 @@ macro_rules! parameter_types_impl_thread_local {
pub fn set(t: $type) { pub fn set(t: $type) {
[<$name:snake:upper>].with(|v| *v.borrow_mut() = t); [<$name:snake:upper>].with(|v| *v.borrow_mut() = t);
} }
/// Mutate the internal value in place.
pub fn mutate<R, F: FnOnce(&mut $type) -> 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
}
} }
)* )*
} }
@@ -22,7 +22,10 @@
#![recursion_limit = "128"] #![recursion_limit = "128"]
use codec::MaxEncodedLen; use codec::MaxEncodedLen;
use frame_support::traits::{CrateVersion, PalletInfo as _}; use frame_support::{
parameter_types,
traits::{CrateVersion, PalletInfo as _},
};
use scale_info::TypeInfo; use scale_info::TypeInfo;
use sp_core::{sr25519, H256}; use sp_core::{sr25519, H256};
use sp_runtime::{ use sp_runtime::{
@@ -30,14 +33,13 @@ use sp_runtime::{
traits::{BlakeTwo256, Verify}, traits::{BlakeTwo256, Verify},
DispatchError, ModuleError, DispatchError, ModuleError,
}; };
use sp_std::cell::RefCell;
mod system; mod system;
pub trait Currency {} pub trait Currency {}
thread_local! { parameter_types! {
pub static INTEGRITY_TEST_EXEC: RefCell<u32> = RefCell::new(0); pub static IntegrityTestExec: u32 = 0;
} }
mod module1 { mod module1 {
@@ -95,7 +97,7 @@ mod module2 {
} }
fn integrity_test() { 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() { 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] #[test]
fn integrity_test_works() { fn integrity_test_works() {
__construct_runtime_integrity_test::runtime_integrity_tests(); __construct_runtime_integrity_test::runtime_integrity_tests();
assert_eq!(INTEGRITY_TEST_EXEC.with(|i| *i.borrow()), 2); assert_eq!(IntegrityTestExec::get(), 2);
} }
#[test] #[test]
+3 -4
View File
@@ -26,7 +26,6 @@ use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup}, traits::{BlakeTwo256, IdentityLookup},
BuildStorage, BuildStorage,
}; };
use sp_std::cell::RefCell;
type UncheckedExtrinsic = mocking::MockUncheckedExtrinsic<Test>; type UncheckedExtrinsic = mocking::MockUncheckedExtrinsic<Test>;
type Block = mocking::MockBlock<Test>; type Block = mocking::MockBlock<Test>;
@@ -79,14 +78,14 @@ parameter_types! {
limits::BlockLength::max_with_normal_ratio(1024, NORMAL_DISPATCH_RATIO); limits::BlockLength::max_with_normal_ratio(1024, NORMAL_DISPATCH_RATIO);
} }
thread_local! { parameter_types! {
pub static KILLED: RefCell<Vec<u64>> = RefCell::new(vec![]); pub static Killed: Vec<u64> = vec![];
} }
pub struct RecordKilled; pub struct RecordKilled;
impl OnKilledAccount<u64> for RecordKilled { impl OnKilledAccount<u64> for RecordKilled {
fn on_killed_account(who: &u64) { fn on_killed_account(who: &u64) {
KILLED.with(|r| r.borrow_mut().push(*who)) Killed::mutate(|r| r.push(*who))
} }
} }
+2 -2
View File
@@ -55,9 +55,9 @@ fn stored_map_works() {
System::dec_consumers(&0); System::dec_consumers(&0);
assert!(!System::is_provider_required(&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_ok!(System::remove(&0));
assert_eq!(KILLED.with(|r| r.borrow().clone()), vec![0u64]); assert_eq!(Killed::get(), vec![0u64]);
}); });
} }
+5 -6
View File
@@ -19,7 +19,6 @@
use super::*; use super::*;
use crate as pallet_timestamp; use crate as pallet_timestamp;
use sp_std::cell::RefCell;
use frame_support::{ use frame_support::{
parameter_types, parameter_types,
@@ -78,14 +77,14 @@ impl frame_system::Config for Test {
type MaxConsumers = ConstU32<16>; type MaxConsumers = ConstU32<16>;
} }
thread_local! { parameter_types! {
pub static CAPTURED_MOMENT: RefCell<Option<Moment>> = RefCell::new(None); pub static CapturedMoment: Option<Moment> = None;
} }
pub struct MockOnTimestampSet; pub struct MockOnTimestampSet;
impl OnTimestampSet<Moment> for MockOnTimestampSet { impl OnTimestampSet<Moment> for MockOnTimestampSet {
fn on_timestamp_set(moment: Moment) { 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() { 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<Moment> { pub(crate) fn get_captured_moment() -> Option<Moment> {
CAPTURED_MOMENT.with(|x| *x.borrow()) CapturedMoment::get()
} }
pub(crate) fn new_test_ext() -> TestExternalities { pub(crate) fn new_test_ext() -> TestExternalities {
+5 -8
View File
@@ -19,8 +19,6 @@
#![cfg(test)] #![cfg(test)]
use std::cell::RefCell;
use sp_core::H256; use sp_core::H256;
use sp_runtime::{ use sp_runtime::{
testing::Header, testing::Header,
@@ -100,18 +98,17 @@ impl pallet_balances::Config for Test {
type AccountStore = System; type AccountStore = System;
type WeightInfo = (); type WeightInfo = ();
} }
thread_local! { parameter_types! {
static TEN_TO_FOURTEEN: RefCell<Vec<u128>> = RefCell::new(vec![10,11,12,13,14]); static TenToFourteenTestValue: Vec<u128> = vec![10,11,12,13,14];
} }
pub struct TenToFourteen; pub struct TenToFourteen;
impl SortedMembers<u128> for TenToFourteen { impl SortedMembers<u128> for TenToFourteen {
fn sorted_members() -> Vec<u128> { fn sorted_members() -> Vec<u128> {
TEN_TO_FOURTEEN.with(|v| v.borrow().clone()) TenToFourteenTestValue::get().clone()
} }
#[cfg(feature = "runtime-benchmarks")] #[cfg(feature = "runtime-benchmarks")]
fn add(new: &u128) { fn add(new: &u128) {
TEN_TO_FOURTEEN.with(|v| { TenToFourteenTestValue::mutate(|members| {
let mut members = v.borrow_mut();
members.push(*new); members.push(*new);
members.sort(); members.sort();
}) })
@@ -119,7 +116,7 @@ impl SortedMembers<u128> for TenToFourteen {
} }
impl ContainsLengthBound for TenToFourteen { impl ContainsLengthBound for TenToFourteen {
fn max_len() -> usize { fn max_len() -> usize {
TEN_TO_FOURTEEN.with(|v| v.borrow().len()) TenToFourteenTestValue::get().len()
} }
fn min_len() -> usize { fn min_len() -> usize {
0 0
@@ -33,7 +33,6 @@ use sp_runtime::{
testing::Header, testing::Header,
traits::{BlakeTwo256, ConvertInto, IdentityLookup, SaturatedConversion, StaticLookup}, traits::{BlakeTwo256, ConvertInto, IdentityLookup, SaturatedConversion, StaticLookup},
}; };
use std::cell::RefCell;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Runtime>; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Runtime>;
type Block = frame_system::mocking::MockBlock<Runtime>; type Block = frame_system::mocking::MockBlock<Runtime>;
@@ -58,8 +57,8 @@ frame_support::construct_runtime!(
const CALL: &<Runtime as frame_system::Config>::Call = const CALL: &<Runtime as frame_system::Config>::Call =
&Call::Balances(BalancesCall::transfer { dest: 2, value: 69 }); &Call::Balances(BalancesCall::transfer { dest: 2, value: 69 });
thread_local! { parameter_types! {
static EXTRINSIC_BASE_WEIGHT: RefCell<Weight> = RefCell::new(Weight::zero()); static ExtrinsicBaseWeight: Weight = Weight::zero();
} }
pub struct BlockWeights; pub struct BlockWeights;
@@ -68,7 +67,7 @@ impl Get<frame_system::limits::BlockWeights> for BlockWeights {
frame_system::limits::BlockWeights::builder() frame_system::limits::BlockWeights::builder()
.base_block(Weight::zero()) .base_block(Weight::zero())
.for_class(DispatchClass::all(), |weights| { .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| { .for_class(DispatchClass::non_mandatory(), |weights| {
weights.max_total = Weight::from_ref_time(1024).into(); weights.max_total = Weight::from_ref_time(1024).into();
@@ -235,7 +234,7 @@ impl ExtBuilder {
self self
} }
fn set_constants(&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); TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.byte_fee);
WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee); WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee);
} }
+14 -16
View File
@@ -810,8 +810,6 @@ mod tests {
use super::*; use super::*;
use crate as pallet_transaction_payment; use crate as pallet_transaction_payment;
use std::cell::RefCell;
use codec::Encode; use codec::Encode;
use sp_core::H256; use sp_core::H256;
@@ -850,8 +848,8 @@ mod tests {
const CALL: &<Runtime as frame_system::Config>::Call = const CALL: &<Runtime as frame_system::Config>::Call =
&Call::Balances(BalancesCall::transfer { dest: 2, value: 69 }); &Call::Balances(BalancesCall::transfer { dest: 2, value: 69 });
thread_local! { parameter_types! {
static EXTRINSIC_BASE_WEIGHT: RefCell<Weight> = RefCell::new(Weight::zero()); static ExtrinsicBaseWeight: Weight = Weight::zero();
} }
pub struct BlockWeights; pub struct BlockWeights;
@@ -860,7 +858,7 @@ mod tests {
frame_system::limits::BlockWeights::builder() frame_system::limits::BlockWeights::builder()
.base_block(Weight::zero()) .base_block(Weight::zero())
.for_class(DispatchClass::all(), |weights| { .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| { .for_class(DispatchClass::non_mandatory(), |weights| {
weights.max_total = Weight::from_ref_time(1024).into(); weights.max_total = Weight::from_ref_time(1024).into();
@@ -932,9 +930,9 @@ mod tests {
} }
} }
thread_local! { parameter_types! {
static TIP_UNBALANCED_AMOUNT: RefCell<u64> = RefCell::new(0); static TipUnbalancedAmount: u64 = 0;
static FEE_UNBALANCED_AMOUNT: RefCell<u64> = RefCell::new(0); static FeeUnbalancedAmount: u64 = 0;
} }
pub struct DealWithFees; pub struct DealWithFees;
@@ -943,9 +941,9 @@ mod tests {
mut fees_then_tips: impl Iterator<Item = pallet_balances::NegativeImbalance<Runtime>>, mut fees_then_tips: impl Iterator<Item = pallet_balances::NegativeImbalance<Runtime>>,
) { ) {
if let Some(fees) = fees_then_tips.next() { 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() { 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 self
} }
fn set_constants(&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); TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.byte_fee);
WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee); WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee);
} }
@@ -1074,10 +1072,10 @@ mod tests {
&Ok(()) &Ok(())
)); ));
assert_eq!(Balances::free_balance(1), 100 - 5 - 5 - 10); assert_eq!(Balances::free_balance(1), 100 - 5 - 5 - 10);
assert_eq!(FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow()), 5 + 5 + 10); assert_eq!(FeeUnbalancedAmount::get(), 5 + 5 + 10);
assert_eq!(TIP_UNBALANCED_AMOUNT.with(|a| *a.borrow()), 0); assert_eq!(TipUnbalancedAmount::get(), 0);
FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow_mut() = 0); FeeUnbalancedAmount::mutate(|a| *a = 0);
let pre = ChargeTransactionPayment::<Runtime>::from(5 /* tipped */) let pre = ChargeTransactionPayment::<Runtime>::from(5 /* tipped */)
.pre_dispatch(&2, CALL, &info_from_weight(Weight::from_ref_time(100)), len) .pre_dispatch(&2, CALL, &info_from_weight(Weight::from_ref_time(100)), len)
@@ -1092,8 +1090,8 @@ mod tests {
&Ok(()) &Ok(())
)); ));
assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 50 - 5); 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!(FeeUnbalancedAmount::get(), 5 + 10 + 50);
assert_eq!(TIP_UNBALANCED_AMOUNT.with(|a| *a.borrow()), 5); assert_eq!(TipUnbalancedAmount::get(), 5);
}); });
} }
-5
View File
@@ -19,8 +19,6 @@
#![cfg(test)] #![cfg(test)]
use std::cell::RefCell;
use sp_core::H256; use sp_core::H256;
use sp_runtime::{ use sp_runtime::{
testing::Header, testing::Header,
@@ -94,9 +92,6 @@ impl pallet_balances::Config for Test {
type AccountStore = System; type AccountStore = System;
type WeightInfo = (); type WeightInfo = ();
} }
thread_local! {
static TEN_TO_FOURTEEN: RefCell<Vec<u128>> = RefCell::new(vec![10,11,12,13,14]);
}
parameter_types! { parameter_types! {
pub const ProposalBond: Permill = Permill::from_percent(5); pub const ProposalBond: Permill = Permill::from_percent(5);
pub const Burn: Permill = Permill::from_percent(50); pub const Burn: Permill = Permill::from_percent(50);