Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Commit

Permalink
Merge branch 'master' into hb-scored-pool-remove-without-storage
Browse files Browse the repository at this point in the history
  • Loading branch information
hbulgarini authored Sep 8, 2022
2 parents 94286dd + 0478535 commit 96f5338
Show file tree
Hide file tree
Showing 31 changed files with 373 additions and 396 deletions.
29 changes: 17 additions & 12 deletions frame/assets/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
14 changes: 6 additions & 8 deletions frame/aura/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>;
Expand Down Expand Up @@ -86,26 +85,25 @@ 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);
}
})
}
}

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()
}
}

Expand Down
4 changes: 0 additions & 4 deletions frame/bounties/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

use super::*;
use crate as pallet_bounties;
use std::cell::RefCell;

use frame_support::{
assert_noop, assert_ok,
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 0 additions & 4 deletions frame/child-bounties/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

use super::*;
use crate as pallet_child_bounties;
use std::cell::RefCell;

use frame_support::{
assert_noop, assert_ok,
Expand Down Expand Up @@ -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);
Expand Down
59 changes: 24 additions & 35 deletions frame/contracts/src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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>> {
Expand All @@ -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,
}
Expand All @@ -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;
Expand All @@ -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,
Expand All @@ -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"),
Expand All @@ -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())
})
}

Expand Down Expand Up @@ -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()
});

Expand All @@ -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]
Expand Down Expand Up @@ -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`.
Expand Down Expand Up @@ -1891,24 +1882,22 @@ 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(_));
exec_success()
});
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()
});

Expand All @@ -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]
Expand Down
Loading

0 comments on commit 96f5338

Please sign in to comment.