mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-11 09:31:12 +00:00
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:
@@ -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<HashMap<(u32, u64), u64>> = RefCell::new(Default::default());
|
||||
static HOOKS: RefCell<Vec<Hook>> = RefCell::new(Default::default());
|
||||
parameter_types! {
|
||||
static Frozen: HashMap<(u32, u64), u64> = Default::default();
|
||||
static Hooks: Vec<Hook> = Default::default();
|
||||
}
|
||||
|
||||
pub struct TestFreezer;
|
||||
impl FrozenBalance<u32, u64, u64> for TestFreezer {
|
||||
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) {
|
||||
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<Hook> {
|
||||
HOOKS.with(|h| h.borrow().clone())
|
||||
Hooks::get().clone()
|
||||
}
|
||||
|
||||
pub(crate) fn take_hooks() -> Vec<Hook> {
|
||||
HOOKS.with(|h| h.take())
|
||||
Hooks::take()
|
||||
}
|
||||
|
||||
pub(crate) fn new_test_ext() -> sp_io::TestExternalities {
|
||||
|
||||
@@ -30,7 +30,6 @@ use sp_runtime::{
|
||||
testing::{Header, UintAuthorityId},
|
||||
traits::IdentityLookup,
|
||||
};
|
||||
use sp_std::cell::RefCell;
|
||||
|
||||
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
|
||||
type Block = frame_system::mocking::MockBlock<Test>;
|
||||
@@ -86,18 +85,17 @@ impl pallet_timestamp::Config for Test {
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static DISABLED_VALIDATORS: RefCell<Vec<AuthorityIndex>> = RefCell::new(Default::default());
|
||||
parameter_types! {
|
||||
static DisabledValidatorTestValue: Vec<AuthorityIndex> = 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()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Vec<u128>> = 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);
|
||||
|
||||
@@ -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<Vec<u128>> = 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);
|
||||
|
||||
@@ -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<MockLoader> = RefCell::new(MockLoader::default());
|
||||
parameter_types! {
|
||||
static Loader: MockLoader = MockLoader::default();
|
||||
}
|
||||
|
||||
fn events() -> Vec<Event<Test>> {
|
||||
@@ -1420,8 +1420,8 @@ mod tests {
|
||||
refcount: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockLoader {
|
||||
#[derive(Default, Clone)]
|
||||
pub struct MockLoader {
|
||||
map: HashMap<CodeHash<Test>, MockExecutable>,
|
||||
counter: u64,
|
||||
}
|
||||
@@ -1431,8 +1431,7 @@ mod tests {
|
||||
func_type: ExportedFunction,
|
||||
f: impl Fn(MockCtx, &MockExecutable) -> ExecResult + 'static,
|
||||
) -> CodeHash<Test> {
|
||||
LOADER.with(|loader| {
|
||||
let mut loader = loader.borrow_mut();
|
||||
Loader::mutate(|loader| {
|
||||
// Generate code hashes as monotonically increasing values.
|
||||
let hash = <Test as frame_system::Config>::Hash::from_low_u64_be(loader.counter);
|
||||
loader.counter += 1;
|
||||
@@ -1445,8 +1444,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn increment_refcount(code_hash: CodeHash<Test>) -> Result<(), DispatchError> {
|
||||
LOADER.with(|loader| {
|
||||
let mut loader = loader.borrow_mut();
|
||||
Loader::mutate(|loader| {
|
||||
match loader.map.entry(code_hash) {
|
||||
Entry::Vacant(_) => Err(<Error<Test>>::CodeNotFound)?,
|
||||
Entry::Occupied(mut entry) => entry.get_mut().refcount += 1,
|
||||
@@ -1457,8 +1455,7 @@ mod tests {
|
||||
|
||||
fn decrement_refcount(code_hash: CodeHash<Test>) {
|
||||
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<Test>,
|
||||
_gas_meter: &mut GasMeter<Test>,
|
||||
) -> Result<Self, DispatchError> {
|
||||
LOADER.with(|loader| {
|
||||
loader
|
||||
.borrow_mut()
|
||||
.map
|
||||
.get(&code_hash)
|
||||
.cloned()
|
||||
.ok_or(Error::<Test>::CodeNotFound.into())
|
||||
Loader::mutate(|loader| {
|
||||
loader.map.get(&code_hash).cloned().ok_or(Error::<Test>::CodeNotFound.into())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1531,14 +1523,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
thread_local! {
|
||||
static TEST_DATA: RefCell<Vec<usize>> = RefCell::new(vec![0]);
|
||||
parameter_types! {
|
||||
static TestData: Vec<usize> = vec![0];
|
||||
}
|
||||
|
||||
let value = Default::default();
|
||||
let mut gas_meter = GasMeter::<Test>::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<bool> = 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<Option<AccountIdOf<Test>>> = RefCell::new(None);
|
||||
static WITNESSED_CALLER_CHARLIE: RefCell<Option<AccountIdOf<Test>>> = RefCell::new(None);
|
||||
parameter_types! {
|
||||
static WitnessedCallerBob: Option<AccountIdOf<Test>> = None;
|
||||
static WitnessedCallerCharlie: Option<AccountIdOf<Test>> = 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]
|
||||
|
||||
@@ -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<Test, TestExt, Root>;
|
||||
|
||||
thread_local! {
|
||||
static TEST_EXT: RefCell<TestExt> = RefCell::new(Default::default());
|
||||
parameter_types! {
|
||||
static TestExtTestValue: TestExt = Default::default();
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
struct LimitCheck {
|
||||
origin: AccountIdOf<Test>,
|
||||
limit: BalanceOf<Test>,
|
||||
min_leftover: BalanceOf<Test>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
struct Charge {
|
||||
origin: AccountIdOf<Test>,
|
||||
contract: AccountIdOf<Test>,
|
||||
@@ -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<LimitCheck>,
|
||||
charges: Vec<Charge>,
|
||||
}
|
||||
@@ -485,12 +485,9 @@ mod tests {
|
||||
min_leftover: BalanceOf<Test>,
|
||||
) -> Result<BalanceOf<Test>, 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<Test>,
|
||||
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<Test>) -> ContractInfo<Test> {
|
||||
@@ -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(<Test as Config>::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(<Test as Config>::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
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<TestExtension> = Default::default();
|
||||
parameter_types! {
|
||||
static TestExtensionTestValue: TestExtension = Default::default();
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TestExtension {
|
||||
enabled: bool,
|
||||
last_seen_buffer: Vec<u8>,
|
||||
@@ -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<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) {
|
||||
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 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<Test> for TestExtension {
|
||||
}
|
||||
|
||||
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 {
|
||||
TEST_EXTENSION.with(|e| e.borrow().enabled)
|
||||
TestExtensionTestValue::get().enabled
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,7 +259,7 @@ impl ChainExtension<Test> for TempStorageExtension {
|
||||
}
|
||||
|
||||
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.
|
||||
pub struct TestFilter;
|
||||
|
||||
thread_local! {
|
||||
static CALL_FILTER: RefCell<fn(&Call) -> 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<Call> for TestFilter {
|
||||
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 = ();
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Debug, Clone, Copy)]
|
||||
#[derive(Default, Eq, PartialEq, Debug, Clone, Copy)]
|
||||
pub enum MockedWeightInfo {
|
||||
#[default]
|
||||
Basic,
|
||||
Complex,
|
||||
Real,
|
||||
|
||||
@@ -835,12 +835,12 @@ mod tests {
|
||||
pub struct RuntimeVersion;
|
||||
impl frame_support::traits::Get<sp_version::RuntimeVersion> 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<sp_version::RuntimeVersion> =
|
||||
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::<Runtime>::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::<Runtime>::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::<Runtime>::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() }
|
||||
});
|
||||
|
||||
<Executive as ExecuteBlock<Block<TestXt>>>::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;
|
||||
|
||||
@@ -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<Option<Vec<u64>>> = RefCell::new(Some(vec![
|
||||
parameter_types! {
|
||||
pub static Validators: Option<Vec<u64>> = Some(vec![
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
]));
|
||||
]);
|
||||
}
|
||||
|
||||
pub struct TestSessionManager;
|
||||
impl pallet_session::SessionManager<u64> for TestSessionManager {
|
||||
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 start_session(_: SessionIndex) {}
|
||||
@@ -76,10 +74,8 @@ impl pallet_session::SessionManager<u64> for TestSessionManager {
|
||||
|
||||
impl pallet_session::historical::SessionManager<u64, u64> for TestSessionManager {
|
||||
fn new_session(_new_index: SessionIndex) -> Option<Vec<(u64, u64)>> {
|
||||
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<Call, ()>;
|
||||
type IdentificationTuple = (u64, u64);
|
||||
type Offence = crate::UnresponsivenessOffence<IdentificationTuple>;
|
||||
|
||||
thread_local! {
|
||||
pub static OFFENCES: RefCell<Vec<(Vec<u64>, Offence)>> = RefCell::new(vec![]);
|
||||
parameter_types! {
|
||||
pub static Offences: Vec<(Vec<u64>, Offence)> = vec![];
|
||||
}
|
||||
|
||||
/// A mock offence report handler.
|
||||
pub struct OffenceHandler;
|
||||
impl ReportOffence<u64, IdentificationTuple, Offence> for OffenceHandler {
|
||||
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(())
|
||||
}
|
||||
|
||||
@@ -183,12 +179,12 @@ impl pallet_authorship::Config for Runtime {
|
||||
type EventHandler = ImOnline;
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
pub static MOCK_CURRENT_SESSION_PROGRESS: RefCell<Option<Option<Permill>>> = RefCell::new(None);
|
||||
parameter_types! {
|
||||
pub static MockCurrentSessionProgress: Option<Option<Permill>> = None;
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
pub static MOCK_AVERAGE_SESSION_LENGTH: RefCell<Option<u64>> = RefCell::new(None);
|
||||
parameter_types! {
|
||||
pub static MockAverageSessionLength: Option<u64> = None;
|
||||
}
|
||||
|
||||
pub struct TestNextSessionRotation;
|
||||
@@ -196,7 +192,7 @@ pub struct TestNextSessionRotation;
|
||||
impl frame_support::traits::EstimateNextSessionRotation<u64> 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::<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
|
||||
let mock = MOCK_CURRENT_SESSION_PROGRESS.with(|p| p.borrow_mut().take());
|
||||
let mock = MockCurrentSessionProgress::mutate(|p| p.take());
|
||||
|
||||
(mock.unwrap_or(estimate), weight)
|
||||
}
|
||||
|
||||
@@ -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::<u64>::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::<u64>::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::<u64>::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::<u64>::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::<u64>::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();
|
||||
|
||||
@@ -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<Test>;
|
||||
type Block = frame_system::mocking::MockBlock<Test>;
|
||||
@@ -91,14 +94,14 @@ impl LeafData {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
pub static LEAF_DATA: RefCell<LeafData> = 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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ fn register_offchain_ext(ext: &mut sp_io::TestExternalities) {
|
||||
fn new_block() -> Weight {
|
||||
let number = frame_system::Pallet::<Test>::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::<Test>::reset_events();
|
||||
frame_system::Pallet::<Test>::initialize(&number, &hash, &Default::default());
|
||||
|
||||
@@ -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<Vec<Perbill>> = RefCell::new(Default::default());
|
||||
pub static OFFENCE_WEIGHT: RefCell<Weight> = RefCell::new(Default::default());
|
||||
parameter_types! {
|
||||
pub static OnOffencePerbill: Vec<Perbill> = Default::default();
|
||||
pub static OffenceWeight: Weight = Default::default();
|
||||
}
|
||||
|
||||
impl<Reporter, Offender> offence::OnOffenceHandler<Reporter, Offender, Weight>
|
||||
@@ -58,16 +57,16 @@ impl<Reporter, Offender> offence::OnOffenceHandler<Reporter, Offender, Weight>
|
||||
_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: 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>;
|
||||
|
||||
@@ -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<Vec<(OriginCaller, u32)>> = 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<T>, 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<T>, 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(())
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ use sp_runtime::{
|
||||
testing::Header,
|
||||
traits::{BlakeTwo256, IdentityLookup},
|
||||
};
|
||||
use std::cell::RefCell;
|
||||
|
||||
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
|
||||
type Block = frame_system::mocking::MockBlock<Test>;
|
||||
@@ -96,14 +95,14 @@ impl pallet_balances::Config for Test {
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
pub static MEMBERS: RefCell<Vec<u64>> = RefCell::new(vec![]);
|
||||
parameter_types! {
|
||||
pub static MembersTestValue: Vec<u64> = vec![];
|
||||
}
|
||||
|
||||
pub struct TestChangeMembers;
|
||||
impl ChangeMembers<u64> 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<u64> 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<u64> 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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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());
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -375,7 +375,7 @@ impl<T: Config, D: AsRef<[u8]>> KeyOwnerProofSystem<(KeyTypeId, D)> for Pallet<T
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
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};
|
||||
@@ -389,9 +389,11 @@ pub(crate) mod tests {
|
||||
|
||||
pub(crate) fn new_test_ext() -> sp_io::TestExternalities {
|
||||
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().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::<Test>::inc_providers(k);
|
||||
|
||||
@@ -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::<Test>()
|
||||
.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::<Test>::inc_providers(k);
|
||||
|
||||
@@ -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<Vec<u64>> = RefCell::new(vec![1, 2, 3]);
|
||||
pub static NEXT_VALIDATORS: RefCell<Vec<u64>> = RefCell::new(vec![1, 2, 3]);
|
||||
pub static AUTHORITIES: RefCell<Vec<UintAuthorityId>> =
|
||||
RefCell::new(vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]);
|
||||
pub static FORCE_SESSION_END: RefCell<bool> = RefCell::new(false);
|
||||
pub static SESSION_LENGTH: RefCell<u64> = RefCell::new(2);
|
||||
pub static SESSION_CHANGED: RefCell<bool> = RefCell::new(false);
|
||||
pub static TEST_SESSION_CHANGED: RefCell<bool> = RefCell::new(false);
|
||||
pub static DISABLED: RefCell<bool> = RefCell::new(false);
|
||||
parameter_types! {
|
||||
pub static Validators: Vec<u64> = vec![1, 2, 3];
|
||||
pub static NextValidators: Vec<u64> = vec![1, 2, 3];
|
||||
pub static Authorities: Vec<UintAuthorityId> =
|
||||
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<bool> = RefCell::new(false);
|
||||
pub static VALIDATOR_ACCOUNTS: RefCell<BTreeMap<u64, u64>> = RefCell::new(BTreeMap::new());
|
||||
pub static BeforeSessionEndCalled: bool = false;
|
||||
pub static ValidatorAccounts: BTreeMap<u64, u64> = BTreeMap::new();
|
||||
}
|
||||
|
||||
pub struct TestShouldEndSession;
|
||||
impl ShouldEndSession<u64> 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<u64> 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::<UintAuthorityId>(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<u64> for TestSessionManager {
|
||||
fn end_session(_: SessionIndex) {}
|
||||
fn start_session(_: SessionIndex) {}
|
||||
fn new_session(_: SessionIndex) -> Option<Vec<u64>> {
|
||||
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<u64, u64> for TestSessionManager {
|
||||
}
|
||||
|
||||
pub fn authorities() -> Vec<UintAuthorityId> {
|
||||
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<u64>) {
|
||||
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::<Test>().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::<Test>::inc_providers(k);
|
||||
@@ -230,10 +232,9 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
|
||||
pallet_session::GenesisConfig::<Test> { 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<u64, u64>) {
|
||||
VALIDATOR_ACCOUNTS.with(|m| *m.borrow_mut() = v);
|
||||
ValidatorAccounts::mutate(|m| *m = v);
|
||||
}
|
||||
}
|
||||
impl Convert<u64, Option<u64>> for TestValidatorIdOf {
|
||||
fn convert(x: u64) -> Option<u64> {
|
||||
VALIDATOR_ACCOUNTS.with(|m| m.borrow().get(&x).cloned())
|
||||
ValidatorAccounts::get().get(&x).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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] };
|
||||
|
||||
@@ -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<u128> = RefCell::new(0);
|
||||
parameter_types! {
|
||||
pub static RewardRemainderUnbalanced: u128 = 0;
|
||||
}
|
||||
|
||||
pub struct RewardRemainderMock;
|
||||
|
||||
impl OnUnbalanced<NegativeImbalanceOf<Test>> for RewardRemainderMock {
|
||||
fn on_nonzero_unbalanced(amount: NegativeImbalanceOf<Test>) {
|
||||
REWARD_REMAINDER_UNBALANCED.with(|v| {
|
||||
*v.borrow_mut() += amount.peek();
|
||||
RewardRemainderUnbalanced::mutate(|v| {
|
||||
*v += amount.peek();
|
||||
});
|
||||
drop(amount);
|
||||
}
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -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, 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"]
|
||||
|
||||
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<u32> = 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]
|
||||
|
||||
@@ -26,7 +26,6 @@ use sp_runtime::{
|
||||
traits::{BlakeTwo256, IdentityLookup},
|
||||
BuildStorage,
|
||||
};
|
||||
use sp_std::cell::RefCell;
|
||||
|
||||
type UncheckedExtrinsic = mocking::MockUncheckedExtrinsic<Test>;
|
||||
type Block = mocking::MockBlock<Test>;
|
||||
@@ -79,14 +78,14 @@ parameter_types! {
|
||||
limits::BlockLength::max_with_normal_ratio(1024, NORMAL_DISPATCH_RATIO);
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
pub static KILLED: RefCell<Vec<u64>> = RefCell::new(vec![]);
|
||||
parameter_types! {
|
||||
pub static Killed: Vec<u64> = vec![];
|
||||
}
|
||||
|
||||
pub struct RecordKilled;
|
||||
impl OnKilledAccount<u64> for RecordKilled {
|
||||
fn on_killed_account(who: &u64) {
|
||||
KILLED.with(|r| r.borrow_mut().push(*who))
|
||||
Killed::mutate(|r| r.push(*who))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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]);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Option<Moment>> = RefCell::new(None);
|
||||
parameter_types! {
|
||||
pub static CapturedMoment: Option<Moment> = None;
|
||||
}
|
||||
|
||||
pub struct MockOnTimestampSet;
|
||||
impl OnTimestampSet<Moment> 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<Moment> {
|
||||
CAPTURED_MOMENT.with(|x| *x.borrow())
|
||||
CapturedMoment::get()
|
||||
}
|
||||
|
||||
pub(crate) fn new_test_ext() -> TestExternalities {
|
||||
|
||||
@@ -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<Vec<u128>> = RefCell::new(vec![10,11,12,13,14]);
|
||||
parameter_types! {
|
||||
static TenToFourteenTestValue: Vec<u128> = vec![10,11,12,13,14];
|
||||
}
|
||||
pub struct TenToFourteen;
|
||||
impl SortedMembers<u128> for TenToFourteen {
|
||||
fn sorted_members() -> Vec<u128> {
|
||||
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<u128> 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
|
||||
|
||||
@@ -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<Runtime>;
|
||||
type Block = frame_system::mocking::MockBlock<Runtime>;
|
||||
@@ -58,8 +57,8 @@ frame_support::construct_runtime!(
|
||||
const CALL: &<Runtime as frame_system::Config>::Call =
|
||||
&Call::Balances(BalancesCall::transfer { dest: 2, value: 69 });
|
||||
|
||||
thread_local! {
|
||||
static EXTRINSIC_BASE_WEIGHT: RefCell<Weight> = RefCell::new(Weight::zero());
|
||||
parameter_types! {
|
||||
static ExtrinsicBaseWeight: Weight = Weight::zero();
|
||||
}
|
||||
|
||||
pub struct BlockWeights;
|
||||
@@ -68,7 +67,7 @@ impl Get<frame_system::limits::BlockWeights> 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);
|
||||
}
|
||||
|
||||
@@ -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: &<Runtime as frame_system::Config>::Call =
|
||||
&Call::Balances(BalancesCall::transfer { dest: 2, value: 69 });
|
||||
|
||||
thread_local! {
|
||||
static EXTRINSIC_BASE_WEIGHT: RefCell<Weight> = 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<u64> = RefCell::new(0);
|
||||
static FEE_UNBALANCED_AMOUNT: RefCell<u64> = 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<Item = pallet_balances::NegativeImbalance<Runtime>>,
|
||||
) {
|
||||
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::<Runtime>::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);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Vec<u128>> = 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);
|
||||
|
||||
Reference in New Issue
Block a user