Skip to content

Commit

Permalink
feat(test-utils): initial mock runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
saiintbrisson committed Dec 9, 2024
1 parent 1158486 commit ceb1468
Show file tree
Hide file tree
Showing 6 changed files with 236 additions and 1 deletion.
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
members = ["node", "runtime", "pallets/*"]
members = ["node", "runtime", "pallets/*", "test-utils"]
resolver = "2"

[workspace.package]
Expand All @@ -9,8 +9,11 @@ edition = "2021"
[workspace.dependencies]
torus-node = { path = "./node", default-features = false }
torus-runtime = { path = "./runtime", default-features = false }

pallet-torus0 = { path = "./pallets/torus0", default-features = false }

test-utils.path = "./test-utils"

polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk.git", tag = "polkadot-stable2409-2", default-features = false }

codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" }
Expand Down
3 changes: 3 additions & 0 deletions pallets/torus0/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@ std = ["codec/std", "polkadot-sdk/std", "scale-info/std"]
codec = { workspace = true, features = ["derive"] }
scale-info = { workspace = true, features = ["derive"] }
polkadot-sdk = { workspace = true, features = ["experimental", "runtime"] }

[dev-dependencies]
test-utils.workspace = true
5 changes: 5 additions & 0 deletions pallets/torus0/tests/foo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#[test]
fn foo() {
let val = test_utils::new_test_ext().execute_with(|| "val");
assert_eq!(val, "val");
}
12 changes: 12 additions & 0 deletions test-utils/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "test-utils"
version = "0.1.0"
authors.workspace = true
edition.workspace = true

[dependencies]
codec.workspace = true
scale-info.workspace = true
polkadot-sdk = { workspace = true, features = ["runtime", "pallet-balances"] }

pallet-torus0.workspace = true
201 changes: 201 additions & 0 deletions test-utils/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
#![allow(non_camel_case_types)]

use polkadot_sdk::{
frame_support::{
self, parameter_types,
traits::{Currency, Everything, Hooks},
},
frame_system, pallet_balances,
polkadot_sdk_frame::runtime::prelude::*,
sp_core::H256,
sp_io,
sp_runtime::traits::{BlakeTwo256, IdentityLookup},
sp_runtime::BuildStorage,
sp_tracing,
};

#[frame_construct_runtime]
mod runtime {
#[runtime::runtime]
#[runtime::derive(RuntimeCall, RuntimeEvent, RuntimeError, RuntimeOrigin)]
pub struct Test;

#[runtime::pallet_index(0)]
pub type System = frame_system::Pallet<Runtime>;

#[runtime::pallet_index(1)]
pub type Balances = pallet_balances::Pallet<Runtime>;

#[runtime::pallet_index(2)]
pub type Torus0 = pallet_torus0::Pallet<Runtime>;
}

pub type Block = frame_system::mocking::MockBlock<Test>;
pub type AccountId = u32;

#[allow(dead_code)]
pub type BalanceCall = pallet_balances::Call<Test>;

#[allow(dead_code)]
pub type TestRuntimeCall = frame_system::Call<Test>;

parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const SS58Prefix: u16 = 888;
}

// Balance of an account.
pub type Balance = u128;

// An index to a block.
pub type BlockNumber = u64;

parameter_types! {
pub const ExistentialDeposit: Balance = 1;
pub const MaxLocks: u32 = 50;
pub const MaxReserves: u32 = 50;
}

impl pallet_torus0::Config for Test {}

impl pallet_balances::Config for Test {
type RuntimeEvent = RuntimeEvent;
type AccountStore = System;
type Balance = Balance;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type MaxLocks = MaxLocks;
type WeightInfo = ();
type MaxReserves = MaxReserves;
type ReserveIdentifier = ();
type RuntimeHoldReason = ();
type FreezeIdentifier = ();
type MaxFreezes = polkadot_sdk::frame_support::traits::ConstU32<16>;
type RuntimeFreezeReason = ();
}

impl frame_system::Config for Test {
type BaseCallFilter = Everything;
type Block = Block;
type BlockWeights = ();
type BlockLength = ();
type AccountId = AccountId;
type RuntimeCall = RuntimeCall;
type Nonce = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type Lookup = IdentityLookup<Self::AccountId>;
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type BlockHashCount = BlockHashCount;
type DbWeight = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = SS58Prefix;
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;

type RuntimeTask = ();
type SingleBlockMigrations = ();
type MultiBlockMigrator = ();
type PreInherents = ();
type PostInherents = ();
type PostTransactions = ();
}

// Utility functions
//===================

const TOKEN_DECIMALS: u32 = 18;

pub const fn to_nano(x: Balance) -> Balance {
x.saturating_add((10 as Balance).pow(TOKEN_DECIMALS))
}

pub const fn from_nano(x: Balance) -> Balance {
x.saturating_div((10 as Balance).pow(TOKEN_DECIMALS))
}

pub fn add_balance(key: AccountId, amount: Balance) {
drop(<Balances as Currency<AccountId>>::deposit_creating(
&key, amount,
));
}

pub fn new_test_ext() -> sp_io::TestExternalities {
new_test_ext_with_block(0)
}

pub fn new_test_ext_with_block(block: BlockNumber) -> sp_io::TestExternalities {
sp_tracing::try_init_simple();
let t = frame_system::GenesisConfig::<Test>::default()
.build_storage()
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(block));
ext
}

pub fn get_origin(key: AccountId) -> RuntimeOrigin {
<<Test as frame_system::Config>::RuntimeOrigin>::signed(key)
}

pub fn step_block(count: BlockNumber) {
let current = System::block_number();
for block in current..current + count {
Torus0::on_finalize(block);
System::on_finalize(block);
System::set_block_number(block + 1);
System::on_initialize(block + 1);
Torus0::on_initialize(block + 1);
}
}

pub fn run_to_block(target: BlockNumber) {
step_block(target - System::block_number());
}

pub fn get_balance(key: AccountId) -> Balance {
<Balances as Currency<AccountId>>::free_balance(&key)
}

pub fn round_first_five(num: u64) -> u64 {
let place_value = 10_u64.pow(num.to_string().len() as u32 - 5);
let first_five = num / place_value;

if first_five % 10 >= 5 {
(first_five / 10 + 1) * place_value * 10
} else {
(first_five / 10) * place_value * 10
}
}

#[macro_export]
macro_rules! assert_ok {
( $x:expr $(,)? ) => {
match $x {
Ok(v) => v,
is => panic!("Expected Ok(_). Got {is:#?}"),
}
};
( $x:expr, $y:expr $(,)? ) => {
assert_eq!($x, Ok($y));
};
}

#[macro_export]
macro_rules! assert_in_range {
($value:expr, $expected:expr, $margin:expr) => {
assert!(
($expected - $margin..=$expected + $margin).contains(&$value),
"value {} is out of range {}..={}",
$value,
$expected,
$margin
);
};
}

0 comments on commit ceb1468

Please sign in to comment.