Use construct_runtime in tests (#8059)

* impl some more

* add serde

* remove unused

* fix staking fuzz

* fix system bench

Co-authored-by: Shawn Tabrizi <shawntabrizi@gmail.com>
This commit is contained in:
Guillaume Thiolliere
2021-02-06 21:12:46 +01:00
committed by GitHub
parent 4b1460f61f
commit 0ed683ca13
18 changed files with 446 additions and 445 deletions
+3
View File
@@ -1644,6 +1644,7 @@ dependencies = [
"linregress", "linregress",
"parity-scale-codec", "parity-scale-codec",
"paste 1.0.4", "paste 1.0.4",
"serde",
"sp-api", "sp-api",
"sp-io", "sp-io",
"sp-runtime", "sp-runtime",
@@ -4730,6 +4731,7 @@ dependencies = [
"frame-support", "frame-support",
"frame-system", "frame-system",
"parity-scale-codec", "parity-scale-codec",
"serde",
"sp-core", "sp-core",
"sp-io", "sp-io",
"sp-runtime", "sp-runtime",
@@ -5150,6 +5152,7 @@ dependencies = [
"pallet-staking-reward-curve", "pallet-staking-reward-curve",
"pallet-timestamp", "pallet-timestamp",
"parity-scale-codec", "parity-scale-codec",
"serde",
"sp-core", "sp-core",
"sp-io", "sp-io",
"sp-npos-elections", "sp-npos-elections",
+1
View File
@@ -27,6 +27,7 @@ frame-system = { version = "2.0.0", default-features = false, path = "../system"
[dev-dependencies] [dev-dependencies]
hex-literal = "0.3.1" hex-literal = "0.3.1"
serde = "1.0.101"
[features] [features]
default = [ "std" ] default = [ "std" ]
+206 -186
View File
@@ -21,59 +21,65 @@
use super::*; use super::*;
use sp_std::prelude::*; use sp_std::prelude::*;
use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::{H256, Header}}; use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::{H256, Header}, BuildStorage};
use frame_support::{ use frame_support::parameter_types;
dispatch::DispatchResult,
decl_module, decl_storage, impl_outer_origin, assert_ok, assert_err, ensure,
parameter_types, pallet_prelude::Get,
};
use frame_system::{RawOrigin, ensure_signed, ensure_none};
decl_storage! { mod pallet_test {
trait Store for Module<T: Config> as Test where use frame_support::pallet_prelude::Get;
<T as OtherConfig>::OtherEvent: Into<<T as Config>::Event>
frame_support::decl_storage! {
trait Store for Module<T: Config> as Test where
<T as OtherConfig>::OtherEvent: Into<<T as Config>::Event>
{
pub Value get(fn value): Option<u32>;
}
}
frame_support::decl_module! {
pub struct Module<T: Config> for enum Call where
origin: T::Origin, <T as OtherConfig>::OtherEvent: Into<<T as Config>::Event>
{
#[weight = 0]
fn set_value(origin, n: u32) -> frame_support::dispatch::DispatchResult {
let _sender = frame_system::ensure_signed(origin)?;
Value::put(n);
Ok(())
}
#[weight = 0]
fn dummy(origin, _n: u32) -> frame_support::dispatch::DispatchResult {
let _sender = frame_system::ensure_none(origin)?;
Ok(())
}
}
}
pub trait OtherConfig {
type OtherEvent;
}
pub trait Config: frame_system::Config + OtherConfig
where Self::OtherEvent: Into<<Self as Config>::Event>
{ {
Value get(fn value): Option<u32>; type Event;
type LowerBound: Get<u32>;
type UpperBound: Get<u32>;
} }
} }
decl_module! { type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
pub struct Module<T: Config> for enum Call where type Block = frame_system::mocking::MockBlock<Test>;
origin: T::Origin, <T as OtherConfig>::OtherEvent: Into<<T as Config>::Event>
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{ {
#[weight = 0] System: frame_system::{Module, Call, Config, Storage, Event<T>},
fn set_value(origin, n: u32) -> DispatchResult { TestPallet: pallet_test::{Module, Call, Storage},
let _sender = ensure_signed(origin)?;
Value::put(n);
Ok(())
}
#[weight = 0]
fn dummy(origin, _n: u32) -> DispatchResult {
let _sender = ensure_none(origin)?;
Ok(())
}
} }
} );
impl_outer_origin! {
pub enum Origin for Test where system = frame_system {}
}
pub trait OtherConfig {
type OtherEvent;
}
pub trait Config: frame_system::Config + OtherConfig
where Self::OtherEvent: Into<<Self as Config>::Event>
{
type Event;
type LowerBound: Get<u32>;
type UpperBound: Get<u32>;
}
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
impl frame_system::Config for Test { impl frame_system::Config for Test {
type BaseCallFilter = (); type BaseCallFilter = ();
@@ -84,15 +90,15 @@ impl frame_system::Config for Test {
type Index = u64; type Index = u64;
type BlockNumber = u64; type BlockNumber = u64;
type Hash = H256; type Hash = H256;
type Call = (); type Call = Call;
type Hashing = BlakeTwo256; type Hashing = BlakeTwo256;
type AccountId = u64; type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = (); type Event = Event;
type BlockHashCount = (); type BlockHashCount = ();
type Version = (); type Version = ();
type PalletInfo = (); type PalletInfo = PalletInfo;
type AccountData = (); type AccountData = ();
type OnNewAccount = (); type OnNewAccount = ();
type OnKilledAccount = (); type OnKilledAccount = ();
@@ -105,163 +111,177 @@ parameter_types!{
pub const UpperBound: u32 = 100; pub const UpperBound: u32 = 100;
} }
impl Config for Test { impl pallet_test::Config for Test {
type Event = (); type Event = Event;
type LowerBound = LowerBound; type LowerBound = LowerBound;
type UpperBound = UpperBound; type UpperBound = UpperBound;
} }
impl OtherConfig for Test { impl pallet_test::OtherConfig for Test {
type OtherEvent = (); type OtherEvent = Event;
} }
fn new_test_ext() -> sp_io::TestExternalities { fn new_test_ext() -> sp_io::TestExternalities {
frame_system::GenesisConfig::default().build_storage::<Test>().unwrap().into() GenesisConfig::default().build_storage().unwrap().into()
} }
benchmarks!{ mod benchmarks {
where_clause { where <T as OtherConfig>::OtherEvent: Into<<T as Config>::Event> } use sp_std::prelude::*;
use frame_system::RawOrigin;
use super::{Test, pallet_test::{self, Value}, new_test_ext};
use frame_support::{assert_ok, assert_err, ensure, traits::Get, StorageValue};
use crate::{BenchmarkingSetup, BenchmarkParameter, account};
set_value { // Additional used internally by the benchmark macro.
let b in 1 .. 1000; use super::pallet_test::{Call, Config, Module};
let caller = account::<T::AccountId>("caller", 0, 0);
}: _ (RawOrigin::Signed(caller), b.into())
verify {
assert_eq!(Value::get(), Some(b));
}
other_name { crate::benchmarks!{
let b in 1 .. 1000; where_clause {
}: dummy (RawOrigin::None, b.into()) where
<T as pallet_test::OtherConfig>::OtherEvent: Into<<T as pallet_test::Config>::Event>
sort_vector {
let x in 1 .. 10000;
let mut m = Vec::<u32>::new();
for i in (0..x).rev() {
m.push(i);
} }
}: {
m.sort();
} verify {
ensure!(m[0] == 0, "You forgot to sort!")
}
bad_origin { set_value {
let b in 1 .. 1000; let b in 1 .. 1000;
let caller = account::<T::AccountId>("caller", 0, 0); let caller = account::<T::AccountId>("caller", 0, 0);
}: dummy (RawOrigin::Signed(caller), b.into()) }: _ (RawOrigin::Signed(caller), b.into())
verify {
bad_verify { assert_eq!(Value::get(), Some(b));
let x in 1 .. 10000;
let mut m = Vec::<u32>::new();
for i in (0..x).rev() {
m.push(i);
} }
}: { }
verify { other_name {
ensure!(m[0] == 0, "You forgot to sort!") let b in 1 .. 1000;
}: dummy (RawOrigin::None, b.into())
sort_vector {
let x in 1 .. 10000;
let mut m = Vec::<u32>::new();
for i in (0..x).rev() {
m.push(i);
}
}: {
m.sort();
} verify {
ensure!(m[0] == 0, "You forgot to sort!")
}
bad_origin {
let b in 1 .. 1000;
let caller = account::<T::AccountId>("caller", 0, 0);
}: dummy (RawOrigin::Signed(caller), b.into())
bad_verify {
let x in 1 .. 10000;
let mut m = Vec::<u32>::new();
for i in (0..x).rev() {
m.push(i);
}
}: { }
verify {
ensure!(m[0] == 0, "You forgot to sort!")
}
no_components {
let caller = account::<T::AccountId>("caller", 0, 0);
}: set_value(RawOrigin::Signed(caller), 0)
variable_components {
let b in ( T::LowerBound::get() ) .. T::UpperBound::get();
}: dummy (RawOrigin::None, b.into())
} }
no_components { #[test]
let caller = account::<T::AccountId>("caller", 0, 0); fn benchmarks_macro_works() {
}: set_value(RawOrigin::Signed(caller), 0) // Check benchmark creation for `set_value`.
let selected = SelectedBenchmark::set_value;
variable_components { let components = <SelectedBenchmark as BenchmarkingSetup<Test>>::components(&selected);
let b in ( T::LowerBound::get() ) .. T::UpperBound::get(); assert_eq!(components, vec![(BenchmarkParameter::b, 1, 1000)]);
}: dummy (RawOrigin::None, b.into())
}
#[test] let closure = <SelectedBenchmark as BenchmarkingSetup<Test>>::instance(
fn benchmarks_macro_works() { &selected,
// Check benchmark creation for `set_value`. &[(BenchmarkParameter::b, 1)],
let selected = SelectedBenchmark::set_value; true,
).expect("failed to create closure");
let components = <SelectedBenchmark as BenchmarkingSetup<Test>>::components(&selected); new_test_ext().execute_with(|| {
assert_eq!(components, vec![(BenchmarkParameter::b, 1, 1000)]); assert_ok!(closure());
});
}
let closure = <SelectedBenchmark as BenchmarkingSetup<Test>>::instance( #[test]
&selected, fn benchmarks_macro_rename_works() {
&[(BenchmarkParameter::b, 1)], // Check benchmark creation for `other_dummy`.
true, let selected = SelectedBenchmark::other_name;
).expect("failed to create closure"); let components = <SelectedBenchmark as BenchmarkingSetup<Test>>::components(&selected);
assert_eq!(components, vec![(BenchmarkParameter::b, 1, 1000)]);
let closure = <SelectedBenchmark as BenchmarkingSetup<Test>>::instance(
&selected,
&[(BenchmarkParameter::b, 1)],
true,
).expect("failed to create closure");
new_test_ext().execute_with(|| {
assert_ok!(closure());
});
}
#[test]
fn benchmarks_macro_works_for_non_dispatchable() {
let selected = SelectedBenchmark::sort_vector;
let components = <SelectedBenchmark as BenchmarkingSetup<Test>>::components(&selected);
assert_eq!(components, vec![(BenchmarkParameter::x, 1, 10000)]);
let closure = <SelectedBenchmark as BenchmarkingSetup<Test>>::instance(
&selected,
&[(BenchmarkParameter::x, 1)],
true,
).expect("failed to create closure");
new_test_ext().execute_with(|| {
assert_ok!(closure()); assert_ok!(closure());
}); }
}
#[test]
#[test] fn benchmarks_macro_verify_works() {
fn benchmarks_macro_rename_works() { // Check postcondition for benchmark `set_value` is valid.
// Check benchmark creation for `other_dummy`. let selected = SelectedBenchmark::set_value;
let selected = SelectedBenchmark::other_name;
let components = <SelectedBenchmark as BenchmarkingSetup<Test>>::components(&selected); let closure = <SelectedBenchmark as BenchmarkingSetup<Test>>::instance(
assert_eq!(components, vec![(BenchmarkParameter::b, 1, 1000)]); &selected,
&[(BenchmarkParameter::b, 1)],
let closure = <SelectedBenchmark as BenchmarkingSetup<Test>>::instance( true,
&selected, ).expect("failed to create closure");
&[(BenchmarkParameter::b, 1)],
true, new_test_ext().execute_with(|| {
).expect("failed to create closure"); assert_ok!(closure());
});
new_test_ext().execute_with(|| {
assert_ok!(closure()); // Check postcondition for benchmark `bad_verify` is invalid.
}); let selected = SelectedBenchmark::bad_verify;
}
let closure = <SelectedBenchmark as BenchmarkingSetup<Test>>::instance(
#[test] &selected,
fn benchmarks_macro_works_for_non_dispatchable() { &[(BenchmarkParameter::x, 10000)],
let selected = SelectedBenchmark::sort_vector; true,
).expect("failed to create closure");
let components = <SelectedBenchmark as BenchmarkingSetup<Test>>::components(&selected);
assert_eq!(components, vec![(BenchmarkParameter::x, 1, 10000)]); new_test_ext().execute_with(|| {
assert_err!(closure(), "You forgot to sort!");
let closure = <SelectedBenchmark as BenchmarkingSetup<Test>>::instance( });
&selected, }
&[(BenchmarkParameter::x, 1)],
true, #[test]
).expect("failed to create closure"); fn benchmarks_generate_unit_tests() {
new_test_ext().execute_with(|| {
assert_ok!(closure()); assert_ok!(test_benchmark_set_value::<Test>());
} assert_ok!(test_benchmark_other_name::<Test>());
assert_ok!(test_benchmark_sort_vector::<Test>());
#[test] assert_err!(test_benchmark_bad_origin::<Test>(), "Bad origin");
fn benchmarks_macro_verify_works() { assert_err!(test_benchmark_bad_verify::<Test>(), "You forgot to sort!");
// Check postcondition for benchmark `set_value` is valid. assert_ok!(test_benchmark_no_components::<Test>());
let selected = SelectedBenchmark::set_value; assert_ok!(test_benchmark_variable_components::<Test>());
});
let closure = <SelectedBenchmark as BenchmarkingSetup<Test>>::instance( }
&selected,
&[(BenchmarkParameter::b, 1)],
true,
).expect("failed to create closure");
new_test_ext().execute_with(|| {
assert_ok!(closure());
});
// Check postcondition for benchmark `bad_verify` is invalid.
let selected = SelectedBenchmark::bad_verify;
let closure = <SelectedBenchmark as BenchmarkingSetup<Test>>::instance(
&selected,
&[(BenchmarkParameter::x, 10000)],
true,
).expect("failed to create closure");
new_test_ext().execute_with(|| {
assert_err!(closure(), "You forgot to sort!");
});
}
#[test]
fn benchmarks_generate_unit_tests() {
new_test_ext().execute_with(|| {
assert_ok!(test_benchmark_set_value::<Test>());
assert_ok!(test_benchmark_other_name::<Test>());
assert_ok!(test_benchmark_sort_vector::<Test>());
assert_err!(test_benchmark_bad_origin::<Test>(), "Bad origin");
assert_err!(test_benchmark_bad_verify::<Test>(), "You forgot to sort!");
assert_ok!(test_benchmark_no_components::<Test>());
assert_ok!(test_benchmark_variable_components::<Test>());
});
} }
@@ -16,11 +16,10 @@
// limitations under the License. // limitations under the License.
use crate::*; use crate::*;
use crate as example_offchain_worker;
use std::sync::Arc; use std::sync::Arc;
use codec::{Encode, Decode}; use codec::Decode;
use frame_support::{ use frame_support::{assert_ok, parameter_types};
assert_ok, impl_outer_origin, parameter_types,
};
use sp_core::{ use sp_core::{
H256, H256,
offchain::{OffchainExt, TransactionPoolExt, testing}, offchain::{OffchainExt, TransactionPoolExt, testing},
@@ -40,15 +39,21 @@ use sp_runtime::{
}, },
}; };
impl_outer_origin! { type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
pub enum Origin for Test where system = frame_system {} type Block = frame_system::mocking::MockBlock<Test>;
}
// For testing the module, we construct a mock runtime.
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Module, Call, Config, Storage, Event<T>},
Example: example_offchain_worker::{Module, Call, Storage, Event<T>, ValidateUnsigned},
}
);
// For testing the module, we construct most of a mock runtime. This means
// first constructing a configuration type (`Test`) which `impl`s each of the
// configuration traits of modules we want to use.
#[derive(Clone, Eq, PartialEq, Encode, Decode)]
pub struct Test;
parameter_types! { parameter_types! {
pub const BlockHashCount: u64 = 250; pub const BlockHashCount: u64 = 250;
pub BlockWeights: frame_system::limits::BlockWeights = pub BlockWeights: frame_system::limits::BlockWeights =
@@ -60,7 +65,7 @@ impl frame_system::Config for Test {
type BlockLength = (); type BlockLength = ();
type DbWeight = (); type DbWeight = ();
type Origin = Origin; type Origin = Origin;
type Call = (); type Call = Call;
type Index = u64; type Index = u64;
type BlockNumber = u64; type BlockNumber = u64;
type Hash = H256; type Hash = H256;
@@ -68,10 +73,10 @@ impl frame_system::Config for Test {
type AccountId = sp_core::sr25519::Public; type AccountId = sp_core::sr25519::Public;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = (); type Event = Event;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = (); type PalletInfo = PalletInfo;
type AccountData = (); type AccountData = ();
type OnNewAccount = (); type OnNewAccount = ();
type OnKilledAccount = (); type OnKilledAccount = ();
@@ -79,7 +84,7 @@ impl frame_system::Config for Test {
type SS58Prefix = (); type SS58Prefix = ();
} }
type Extrinsic = TestXt<Call<Test>, ()>; type Extrinsic = TestXt<Call, ()>;
type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId; type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
impl frame_system::offchain::SigningTypes for Test { impl frame_system::offchain::SigningTypes for Test {
@@ -88,21 +93,21 @@ impl frame_system::offchain::SigningTypes for Test {
} }
impl<LocalCall> frame_system::offchain::SendTransactionTypes<LocalCall> for Test where impl<LocalCall> frame_system::offchain::SendTransactionTypes<LocalCall> for Test where
Call<Test>: From<LocalCall>, Call: From<LocalCall>,
{ {
type OverarchingCall = Call<Test>; type OverarchingCall = Call;
type Extrinsic = Extrinsic; type Extrinsic = Extrinsic;
} }
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Test where impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Test where
Call<Test>: From<LocalCall>, Call: From<LocalCall>,
{ {
fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>( fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
call: Call<Test>, call: Call,
_public: <Signature as Verify>::Signer, _public: <Signature as Verify>::Signer,
_account: AccountId, _account: AccountId,
nonce: u64, nonce: u64,
) -> Option<(Call<Test>, <Extrinsic as ExtrinsicT>::SignaturePayload)> { ) -> Option<(Call, <Extrinsic as ExtrinsicT>::SignaturePayload)> {
Some((call, (nonce, ()))) Some((call, (nonce, ())))
} }
} }
@@ -114,16 +119,14 @@ parameter_types! {
} }
impl Config for Test { impl Config for Test {
type Event = (); type Event = Event;
type AuthorityId = crypto::TestAuthId; type AuthorityId = crypto::TestAuthId;
type Call = Call<Test>; type Call = Call;
type GracePeriod = GracePeriod; type GracePeriod = GracePeriod;
type UnsignedInterval = UnsignedInterval; type UnsignedInterval = UnsignedInterval;
type UnsignedPriority = UnsignedPriority; type UnsignedPriority = UnsignedPriority;
} }
type Example = Module<Test>;
#[test] #[test]
fn it_aggregates_the_price() { fn it_aggregates_the_price() {
sp_io::TestExternalities::default().execute_with(|| { sp_io::TestExternalities::default().execute_with(|| {
@@ -228,7 +231,7 @@ fn should_submit_signed_transaction_on_chain() {
assert!(pool_state.read().transactions.is_empty()); assert!(pool_state.read().transactions.is_empty());
let tx = Extrinsic::decode(&mut &*tx).unwrap(); let tx = Extrinsic::decode(&mut &*tx).unwrap();
assert_eq!(tx.signature.unwrap().0, 0); assert_eq!(tx.signature.unwrap().0, 0);
assert_eq!(tx.call, Call::submit_price(15523)); assert_eq!(tx.call, Call::Example(crate::Call::submit_price(15523)));
}); });
} }
@@ -272,7 +275,7 @@ fn should_submit_unsigned_transaction_on_chain_for_any_account() {
let tx = pool_state.write().transactions.pop().unwrap(); let tx = pool_state.write().transactions.pop().unwrap();
let tx = Extrinsic::decode(&mut &*tx).unwrap(); let tx = Extrinsic::decode(&mut &*tx).unwrap();
assert_eq!(tx.signature, None); assert_eq!(tx.signature, None);
if let Call::submit_price_unsigned_with_signed_payload(body, signature) = tx.call { if let Call::Example(crate::Call::submit_price_unsigned_with_signed_payload(body, signature)) = tx.call {
assert_eq!(body, price_payload); assert_eq!(body, price_payload);
let signature_valid = <PricePayload< let signature_valid = <PricePayload<
@@ -325,7 +328,7 @@ fn should_submit_unsigned_transaction_on_chain_for_all_accounts() {
let tx = pool_state.write().transactions.pop().unwrap(); let tx = pool_state.write().transactions.pop().unwrap();
let tx = Extrinsic::decode(&mut &*tx).unwrap(); let tx = Extrinsic::decode(&mut &*tx).unwrap();
assert_eq!(tx.signature, None); assert_eq!(tx.signature, None);
if let Call::submit_price_unsigned_with_signed_payload(body, signature) = tx.call { if let Call::Example(crate::Call::submit_price_unsigned_with_signed_payload(body, signature)) = tx.call {
assert_eq!(body, price_payload); assert_eq!(body, price_payload);
let signature_valid = <PricePayload< let signature_valid = <PricePayload<
@@ -360,7 +363,7 @@ fn should_submit_raw_unsigned_transaction_on_chain() {
assert!(pool_state.read().transactions.is_empty()); assert!(pool_state.read().transactions.is_empty());
let tx = Extrinsic::decode(&mut &*tx).unwrap(); let tx = Extrinsic::decode(&mut &*tx).unwrap();
assert_eq!(tx.signature, None); assert_eq!(tx.signature, None);
assert_eq!(tx.call, Call::submit_price_unsigned(1, 15523)); assert_eq!(tx.call, Call::Example(crate::Call::submit_price_unsigned(1, 15523)));
}); });
} }
@@ -21,6 +21,9 @@ sp-runtime = { version = "2.0.0", default-features = false, path = "../../primit
sp-std = { version = "2.0.0", default-features = false, path = "../../primitives/std" } sp-std = { version = "2.0.0", default-features = false, path = "../../primitives/std" }
sp-tasks = { version = "2.0.0", default-features = false, path = "../../primitives/tasks" } sp-tasks = { version = "2.0.0", default-features = false, path = "../../primitives/tasks" }
[dev-dependencies]
serde = { version = "1.0.101" }
[features] [features]
default = ["std"] default = ["std"]
std = [ std = [
+21 -17
View File
@@ -15,23 +15,29 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use crate::*; use crate::{self as pallet_example_parallel, *};
use codec::{Encode, Decode}; use frame_support::parameter_types;
use frame_support::{impl_outer_origin, parameter_types};
use sp_core::H256; use sp_core::H256;
use sp_runtime::{ use sp_runtime::{
Perbill, Perbill, testing::Header,
testing::{Header},
traits::{BlakeTwo256, IdentityLookup}, traits::{BlakeTwo256, IdentityLookup},
}; };
impl_outer_origin! { type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
pub enum Origin for Test where system = frame_system {} type Block = frame_system::mocking::MockBlock<Test>;
}
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Module, Call, Config, Storage, Event<T>},
Example: pallet_example_parallel::{Module, Call, Storage, Event},
}
);
#[derive(Clone, Eq, PartialEq, Encode, Decode)]
pub struct Test;
parameter_types! { parameter_types! {
pub const BlockHashCount: u64 = 250; pub const BlockHashCount: u64 = 250;
pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const AvailableBlockRatio: Perbill = Perbill::one();
@@ -40,8 +46,8 @@ parameter_types! {
impl frame_system::Config for Test { impl frame_system::Config for Test {
type BaseCallFilter = (); type BaseCallFilter = ();
type Origin = Origin; type Origin = Origin;
type Call = (); type Call = Call;
type PalletInfo = (); type PalletInfo = PalletInfo;
type Index = u64; type Index = u64;
type BlockNumber = u64; type BlockNumber = u64;
type Hash = H256; type Hash = H256;
@@ -49,7 +55,7 @@ impl frame_system::Config for Test {
type AccountId = sp_core::sr25519::Public; type AccountId = sp_core::sr25519::Public;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = (); type Event = Event;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type DbWeight = (); type DbWeight = ();
type BlockWeights = (); type BlockWeights = ();
@@ -69,12 +75,10 @@ parameter_types! {
} }
impl Config for Test { impl Config for Test {
type Event = (); type Event = Event;
type Call = Call<Test>; type Call = Call;
} }
type Example = Module<Test>;
#[test] #[test]
fn it_can_enlist() { fn it_can_enlist() {
use sp_core::Pair; use sp_core::Pair;
+36 -33
View File
@@ -707,32 +707,35 @@ mod tests {
use super::*; use super::*;
use frame_support::{ use frame_support::{
assert_ok, impl_outer_origin, parameter_types, impl_outer_dispatch, assert_ok, parameter_types,
weights::{DispatchInfo, GetDispatchInfo}, traits::{OnInitialize, OnFinalize} weights::{DispatchInfo, GetDispatchInfo}, traits::{OnInitialize, OnFinalize}
}; };
use sp_core::H256; use sp_core::H256;
// The testing primitives are very useful for avoiding having to work with signatures // The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required.
use sp_runtime::{ use sp_runtime::{
testing::Header, testing::Header, BuildStorage,
traits::{BlakeTwo256, IdentityLookup}, traits::{BlakeTwo256, IdentityLookup},
}; };
// Reexport crate as its pallet name for construct_runtime.
use crate as pallet_example;
impl_outer_origin! { type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
pub enum Origin for Test where system = frame_system {} type Block = frame_system::mocking::MockBlock<Test>;
}
impl_outer_dispatch! { // For testing the pallet, we construct a mock runtime.
pub enum OuterCall for Test where origin: Origin { frame_support::construct_runtime!(
self::Example, pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Module, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},
Example: pallet_example::{Module, Call, Storage, Config<T>, Event<T>},
} }
} );
// For testing the pallet, we construct most of a mock runtime. This means
// first constructing a configuration type (`Test`) which `impl`s each of the
// configuration traits of pallets we want to use.
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
parameter_types! { parameter_types! {
pub const BlockHashCount: u64 = 250; pub const BlockHashCount: u64 = 250;
pub BlockWeights: frame_system::limits::BlockWeights = pub BlockWeights: frame_system::limits::BlockWeights =
@@ -747,15 +750,15 @@ mod tests {
type Index = u64; type Index = u64;
type BlockNumber = u64; type BlockNumber = u64;
type Hash = H256; type Hash = H256;
type Call = OuterCall; type Call = Call;
type Hashing = BlakeTwo256; type Hashing = BlakeTwo256;
type AccountId = u64; type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = (); type Event = Event;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = (); type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>; type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = (); type OnNewAccount = ();
type OnKilledAccount = (); type OnKilledAccount = ();
@@ -769,29 +772,29 @@ mod tests {
type MaxLocks = (); type MaxLocks = ();
type Balance = u64; type Balance = u64;
type DustRemoval = (); type DustRemoval = ();
type Event = (); type Event = Event;
type ExistentialDeposit = ExistentialDeposit; type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System; type AccountStore = System;
type WeightInfo = (); type WeightInfo = ();
} }
impl Config for Test { impl Config for Test {
type Event = (); type Event = Event;
} }
type System = frame_system::Module<Test>;
type Example = Module<Test>;
// This function basically just builds a genesis storage key/value store according to // This function basically just builds a genesis storage key/value store according to
// our desired mockup. // our desired mockup.
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 t = GenesisConfig {
// We use default for brevity, but you can configure as desired if needed. // We use default for brevity, but you can configure as desired if needed.
pallet_balances::GenesisConfig::<Test>::default().assimilate_storage(&mut t).unwrap(); frame_system: Some(Default::default()),
GenesisConfig::<Test>{ pallet_balances: Some(Default::default()),
dummy: 42, pallet_example: Some(pallet_example::GenesisConfig {
// we configure the map with (key, value) pairs. dummy: 42,
bar: vec![(1, 2), (2, 3)], // we configure the map with (key, value) pairs.
foo: 24, bar: vec![(1, 2), (2, 3)],
}.assimilate_storage(&mut t).unwrap(); foo: 24,
}),
}.build_storage().unwrap();
t.into() t.into()
} }
@@ -828,7 +831,7 @@ mod tests {
#[test] #[test]
fn signed_ext_watch_dummy_works() { fn signed_ext_watch_dummy_works() {
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
let call = <Call<Test>>::set_dummy(10).into(); let call = <pallet_example::Call<Test>>::set_dummy(10).into();
let info = DispatchInfo::default(); let info = DispatchInfo::default();
assert_eq!( assert_eq!(
@@ -847,13 +850,13 @@ mod tests {
#[test] #[test]
fn weights_work() { fn weights_work() {
// must have a defined weight. // must have a defined weight.
let default_call = <Call<Test>>::accumulate_dummy(10); let default_call = <pallet_example::Call<Test>>::accumulate_dummy(10);
let info = default_call.get_dispatch_info(); let info = default_call.get_dispatch_info();
// aka. `let info = <Call<Test> as GetDispatchInfo>::get_dispatch_info(&default_call);` // aka. `let info = <Call<Test> as GetDispatchInfo>::get_dispatch_info(&default_call);`
assert_eq!(info.weight, 0); assert_eq!(info.weight, 0);
// must have a custom weight of `100 * arg = 2000` // must have a custom weight of `100 * arg = 2000`
let custom_call = <Call<Test>>::set_dummy(20); let custom_call = <pallet_example::Call<Test>>::set_dummy(20);
let info = custom_call.get_dispatch_info(); let info = custom_call.get_dispatch_info();
assert_eq!(info.weight, 2000); assert_eq!(info.weight, 2000);
} }
+27 -44
View File
@@ -19,11 +19,11 @@
#![cfg(test)] #![cfg(test)]
use crate::{AuthorityId, AuthorityList, ConsensusLog, Module, Config}; use crate::{AuthorityId, AuthorityList, ConsensusLog, Config, self as pallet_grandpa};
use ::grandpa as finality_grandpa; use ::grandpa as finality_grandpa;
use codec::Encode; use codec::Encode;
use frame_support::{ use frame_support::{
impl_outer_dispatch, impl_outer_event, impl_outer_origin, parameter_types, parameter_types,
traits::{KeyOwnerProofSystem, OnFinalize, OnInitialize}, traits::{KeyOwnerProofSystem, OnFinalize, OnInitialize},
weights::Weight, weights::Weight,
}; };
@@ -40,17 +40,27 @@ use sp_runtime::{
DigestItem, Perbill, DigestItem, Perbill,
}; };
use sp_staking::SessionIndex; use sp_staking::SessionIndex;
use pallet_session::historical as pallet_session_historical;
impl_outer_origin! { type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
pub enum Origin for Test {} type Block = frame_system::mocking::MockBlock<Test>;
}
impl_outer_dispatch! { frame_support::construct_runtime!(
pub enum Call for Test where origin: Origin { pub enum Test where
pallet_grandpa::Grandpa, Block = Block,
pallet_staking::Staking, NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Module, Call, Config, Storage, Event<T>},
Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},
Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},
Staking: pallet_staking::{Module, Call, Config<T>, Storage, Event<T>, ValidateUnsigned},
Session: pallet_session::{Module, Call, Storage, Event, Config<T>},
Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event, ValidateUnsigned},
Offences: pallet_offences::{Module, Call, Storage, Event},
Historical: pallet_session_historical::{Module},
} }
} );
impl_opaque_keys! { impl_opaque_keys! {
pub struct TestSessionKeys { pub struct TestSessionKeys {
@@ -58,20 +68,6 @@ impl_opaque_keys! {
} }
} }
impl_outer_event! {
pub enum TestEvent for Test {
frame_system<T>,
pallet_balances<T>,
pallet_grandpa,
pallet_offences,
pallet_session,
pallet_staking<T>,
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
parameter_types! { parameter_types! {
pub const BlockHashCount: u64 = 250; pub const BlockHashCount: u64 = 250;
pub BlockWeights: frame_system::limits::BlockWeights = pub BlockWeights: frame_system::limits::BlockWeights =
@@ -92,10 +88,10 @@ impl frame_system::Config for Test {
type AccountId = u64; type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = TestEvent; type Event = Event;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = (); type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u128>; type AccountData = pallet_balances::AccountData<u128>;
type OnNewAccount = (); type OnNewAccount = ();
type OnKilledAccount = (); type OnKilledAccount = ();
@@ -119,7 +115,7 @@ parameter_types! {
/// Custom `SessionHandler` since we use `TestSessionKeys` as `Keys`. /// Custom `SessionHandler` since we use `TestSessionKeys` as `Keys`.
impl pallet_session::Config for Test { impl pallet_session::Config for Test {
type Event = TestEvent; type Event = Event;
type ValidatorId = u64; type ValidatorId = u64;
type ValidatorIdOf = pallet_staking::StashOf<Self>; type ValidatorIdOf = pallet_staking::StashOf<Self>;
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>; type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
@@ -155,7 +151,7 @@ impl pallet_balances::Config for Test {
type MaxLocks = (); type MaxLocks = ();
type Balance = u128; type Balance = u128;
type DustRemoval = (); type DustRemoval = ();
type Event = TestEvent; type Event = Event;
type ExistentialDeposit = ExistentialDeposit; type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System; type AccountStore = System;
type WeightInfo = (); type WeightInfo = ();
@@ -197,7 +193,7 @@ parameter_types! {
impl pallet_staking::Config for Test { impl pallet_staking::Config for Test {
type RewardRemainder = (); type RewardRemainder = ();
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type Event = TestEvent; type Event = Event;
type Currency = Balances; type Currency = Balances;
type Slash = (); type Slash = ();
type Reward = (); type Reward = ();
@@ -224,14 +220,14 @@ parameter_types! {
} }
impl pallet_offences::Config for Test { impl pallet_offences::Config for Test {
type Event = TestEvent; type Event = Event;
type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>; type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
type OnOffenceHandler = Staking; type OnOffenceHandler = Staking;
type WeightSoftLimit = OffencesWeightSoftLimit; type WeightSoftLimit = OffencesWeightSoftLimit;
} }
impl Config for Test { impl Config for Test {
type Event = TestEvent; type Event = Event;
type Call = Call; type Call = Call;
type KeyOwnerProofSystem = Historical; type KeyOwnerProofSystem = Historical;
@@ -249,19 +245,6 @@ impl Config for Test {
type WeightInfo = (); type WeightInfo = ();
} }
mod pallet_grandpa {
pub use crate::Event;
}
pub type Balances = pallet_balances::Module<Test>;
pub type Historical = pallet_session::historical::Module<Test>;
pub type Offences = pallet_offences::Module<Test>;
pub type Session = pallet_session::Module<Test>;
pub type Staking = pallet_staking::Module<Test>;
pub type System = frame_system::Module<Test>;
pub type Timestamp = pallet_timestamp::Module<Test>;
pub type Grandpa = Module<Test>;
pub fn grandpa_log(log: ConsensusLog<u64>) -> DigestItem<H256> { pub fn grandpa_log(log: ConsensusLog<u64>) -> DigestItem<H256> {
DigestItem::Consensus(GRANDPA_ENGINE_ID, log.encode()) DigestItem::Consensus(GRANDPA_ENGINE_ID, log.encode())
} }
+1 -1
View File
@@ -19,7 +19,7 @@
#![cfg(test)] #![cfg(test)]
use super::{Call, *}; use super::{Call, Event, *};
use crate::mock::*; use crate::mock::*;
use codec::{Decode, Encode}; use codec::{Decode, Encode};
use fg_primitives::ScheduledChange; use fg_primitives::ScheduledChange;
@@ -20,30 +20,28 @@
#![cfg(test)] #![cfg(test)]
use sp_runtime::traits::IdentityLookup; use sp_runtime::traits::IdentityLookup;
use frame_support::{impl_outer_origin, impl_outer_dispatch, parameter_types}; use frame_support::parameter_types;
type AccountId = u64; type AccountId = u64;
type AccountIndex = u32; type AccountIndex = u32;
type BlockNumber = u64; type BlockNumber = u64;
type Balance = u64; type Balance = u64;
type System = frame_system::Module<Test>; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Balances = pallet_balances::Module<Test>; type Block = frame_system::mocking::MockBlock<Test>;
type Staking = pallet_staking::Module<Test>;
type Session = pallet_session::Module<Test>;
impl_outer_origin! { frame_support::construct_runtime!(
pub enum Origin for Test where system = frame_system {} pub enum Test where
} Block = Block,
NodeBlock = Block,
impl_outer_dispatch! { UncheckedExtrinsic = UncheckedExtrinsic,
pub enum Call for Test where origin: Origin { {
pallet_staking::Staking, System: frame_system::{Module, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},
Staking: pallet_staking::{Module, Call, Config<T>, Storage, Event<T>, ValidateUnsigned},
Session: pallet_session::{Module, Call, Storage, Event, Config<T>},
} }
} );
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Test;
impl frame_system::Config for Test { impl frame_system::Config for Test {
type BaseCallFilter = (); type BaseCallFilter = ();
@@ -59,10 +57,10 @@ impl frame_system::Config for Test {
type AccountId = AccountId; type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = sp_runtime::testing::Header; type Header = sp_runtime::testing::Header;
type Event = (); type Event = Event;
type BlockHashCount = (); type BlockHashCount = ();
type Version = (); type Version = ();
type PalletInfo = (); type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>; type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = (); type OnNewAccount = ();
type OnKilledAccount = (); type OnKilledAccount = ();
@@ -75,7 +73,7 @@ parameter_types! {
impl pallet_balances::Config for Test { impl pallet_balances::Config for Test {
type MaxLocks = (); type MaxLocks = ();
type Balance = Balance; type Balance = Balance;
type Event = (); type Event = Event;
type DustRemoval = (); type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit; type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System; type AccountStore = System;
@@ -123,7 +121,7 @@ impl pallet_session::Config for Test {
type ShouldEndSession = pallet_session::PeriodicSessions<(), ()>; type ShouldEndSession = pallet_session::PeriodicSessions<(), ()>;
type NextSessionRotation = pallet_session::PeriodicSessions<(), ()>; type NextSessionRotation = pallet_session::PeriodicSessions<(), ()>;
type SessionHandler = TestSessionHandler; type SessionHandler = TestSessionHandler;
type Event = (); type Event = Event;
type ValidatorId = AccountId; type ValidatorId = AccountId;
type ValidatorIdOf = pallet_staking::StashOf<Test>; type ValidatorIdOf = pallet_staking::StashOf<Test>;
type DisabledValidatorsThreshold = (); type DisabledValidatorsThreshold = ();
@@ -159,7 +157,7 @@ impl pallet_staking::Config for Test {
type UnixTime = pallet_timestamp::Module<Self>; type UnixTime = pallet_timestamp::Module<Self>;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type RewardRemainder = (); type RewardRemainder = ();
type Event = (); type Event = Event;
type Slash = (); type Slash = ();
type Reward = (); type Reward = ();
type SessionsPerEra = (); type SessionsPerEra = ();
@@ -28,6 +28,12 @@ sp-io ={ version = "2.0.0", path = "../../../primitives/io" }
sp-core = { version = "2.0.0", path = "../../../primitives/core" } sp-core = { version = "2.0.0", path = "../../../primitives/core" }
sp-npos-elections = { version = "2.0.0", path = "../../../primitives/npos-elections" } sp-npos-elections = { version = "2.0.0", path = "../../../primitives/npos-elections" }
sp-runtime = { version = "2.0.0", path = "../../../primitives/runtime" } sp-runtime = { version = "2.0.0", path = "../../../primitives/runtime" }
serde = "1.0.101"
[features]
# Note feature std is required so that impl_opaque_keys derive serde.
default = ["std"]
std = []
[[bin]] [[bin]]
name = "submit_solution" name = "submit_solution"
+21 -23
View File
@@ -17,31 +17,29 @@
//! Mock file for staking fuzzing. //! Mock file for staking fuzzing.
use frame_support::{impl_outer_origin, impl_outer_dispatch, parameter_types}; use frame_support::parameter_types;
type AccountId = u64; type AccountId = u64;
type AccountIndex = u32; type AccountIndex = u32;
type BlockNumber = u64; type BlockNumber = u64;
type Balance = u64; type Balance = u64;
pub type System = frame_system::Module<Test>; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
pub type Balances = pallet_balances::Module<Test>; type Block = frame_system::mocking::MockBlock<Test>;
pub type Staking = pallet_staking::Module<Test>;
pub type Indices = pallet_indices::Module<Test>;
pub type Session = pallet_session::Module<Test>;
impl_outer_origin! { frame_support::construct_runtime!(
pub enum Origin for Test where system = frame_system {} pub enum Test where
} Block = Block,
NodeBlock = Block,
impl_outer_dispatch! { UncheckedExtrinsic = UncheckedExtrinsic,
pub enum Call for Test where origin: Origin { {
staking::Staking, System: frame_system::{Module, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},
Staking: pallet_staking::{Module, Call, Config<T>, Storage, Event<T>, ValidateUnsigned},
Indices: pallet_indices::{Module, Call, Storage, Config<T>, Event<T>},
Session: pallet_session::{Module, Call, Storage, Event, Config<T>},
} }
} );
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Test;
impl frame_system::Config for Test { impl frame_system::Config for Test {
type BaseCallFilter = (); type BaseCallFilter = ();
@@ -57,10 +55,10 @@ impl frame_system::Config for Test {
type AccountId = AccountId; type AccountId = AccountId;
type Lookup = Indices; type Lookup = Indices;
type Header = sp_runtime::testing::Header; type Header = sp_runtime::testing::Header;
type Event = (); type Event = Event;
type BlockHashCount = (); type BlockHashCount = ();
type Version = (); type Version = ();
type PalletInfo = (); type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>; type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = (); type OnNewAccount = ();
type OnKilledAccount = (); type OnKilledAccount = ();
@@ -73,7 +71,7 @@ parameter_types! {
impl pallet_balances::Config for Test { impl pallet_balances::Config for Test {
type MaxLocks = (); type MaxLocks = ();
type Balance = Balance; type Balance = Balance;
type Event = (); type Event = Event;
type DustRemoval = (); type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit; type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System; type AccountStore = System;
@@ -81,7 +79,7 @@ impl pallet_balances::Config for Test {
} }
impl pallet_indices::Config for Test { impl pallet_indices::Config for Test {
type AccountIndex = AccountIndex; type AccountIndex = AccountIndex;
type Event = (); type Event = Event;
type Currency = Balances; type Currency = Balances;
type Deposit = (); type Deposit = ();
type WeightInfo = (); type WeightInfo = ();
@@ -127,7 +125,7 @@ impl pallet_session::Config for Test {
type ShouldEndSession = pallet_session::PeriodicSessions<(), ()>; type ShouldEndSession = pallet_session::PeriodicSessions<(), ()>;
type NextSessionRotation = pallet_session::PeriodicSessions<(), ()>; type NextSessionRotation = pallet_session::PeriodicSessions<(), ()>;
type SessionHandler = TestSessionHandler; type SessionHandler = TestSessionHandler;
type Event = (); type Event = Event;
type ValidatorId = AccountId; type ValidatorId = AccountId;
type ValidatorIdOf = pallet_staking::StashOf<Test>; type ValidatorIdOf = pallet_staking::StashOf<Test>;
type DisabledValidatorsThreshold = (); type DisabledValidatorsThreshold = ();
@@ -163,7 +161,7 @@ impl pallet_staking::Config for Test {
type UnixTime = pallet_timestamp::Module<Self>; type UnixTime = pallet_timestamp::Module<Self>;
type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
type RewardRemainder = (); type RewardRemainder = ();
type Event = (); type Event = Event;
type Slash = (); type Slash = ();
type Reward = (); type Reward = ();
type SessionsPerEra = (); type SessionsPerEra = ();
+14 -13
View File
@@ -17,7 +17,7 @@
use criterion::{Criterion, criterion_group, criterion_main, black_box}; use criterion::{Criterion, criterion_group, criterion_main, black_box};
use frame_system as system; use frame_system as system;
use frame_support::{decl_module, decl_event, impl_outer_origin, impl_outer_event}; use frame_support::{decl_module, decl_event};
use sp_core::H256; use sp_core::H256;
use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header}; use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
@@ -41,16 +41,19 @@ mod module {
); );
} }
impl_outer_origin!{ type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Runtime>;
pub enum Origin for Runtime {} type Block = frame_system::mocking::MockBlock<Runtime>;
}
impl_outer_event! { frame_support::construct_runtime!(
pub enum Event for Runtime { pub enum Runtime where
system<T>, Block = Block,
module, NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Module, Call, Config, Storage, Event<T>},
Module: module::{Module, Call, Event},
} }
} );
frame_support::parameter_types! { frame_support::parameter_types! {
pub const BlockHashCount: u64 = 250; pub const BlockHashCount: u64 = 250;
@@ -63,8 +66,6 @@ frame_support::parameter_types! {
4 * 1024 * 1024, Perbill::from_percent(75), 4 * 1024 * 1024, Perbill::from_percent(75),
); );
} }
#[derive(Clone, Eq, PartialEq)]
pub struct Runtime;
impl system::Config for Runtime { impl system::Config for Runtime {
type BaseCallFilter = (); type BaseCallFilter = ();
type BlockWeights = (); type BlockWeights = ();
@@ -73,7 +74,7 @@ impl system::Config for Runtime {
type Origin = Origin; type Origin = Origin;
type Index = u64; type Index = u64;
type BlockNumber = u64; type BlockNumber = u64;
type Call = (); type Call = Call;
type Hash = H256; type Hash = H256;
type Hashing = BlakeTwo256; type Hashing = BlakeTwo256;
type AccountId = u64; type AccountId = u64;
@@ -82,7 +83,7 @@ impl system::Config for Runtime {
type Event = Event; type Event = Event;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = (); type PalletInfo = PalletInfo;
type AccountData = (); type AccountData = ();
type OnNewAccount = (); type OnNewAccount = ();
type OnKilledAccount = (); type OnKilledAccount = ();
+12 -24
View File
@@ -20,35 +20,23 @@
#![cfg(test)] #![cfg(test)]
use sp_runtime::traits::IdentityLookup; use sp_runtime::traits::IdentityLookup;
use frame_support::{
impl_outer_origin,
dispatch::{Dispatchable, DispatchInfo, PostDispatchInfo},
};
type AccountId = u64; type AccountId = u64;
type AccountIndex = u32; type AccountIndex = u32;
type BlockNumber = u64; type BlockNumber = u64;
impl_outer_origin! { type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
pub enum Origin for Test where system = frame_system {} type Block = frame_system::mocking::MockBlock<Test>;
}
#[derive(Debug, codec::Encode, codec::Decode)] frame_support::construct_runtime!(
pub struct Call; pub enum Test where
Block = Block,
impl Dispatchable for Call { NodeBlock = Block,
type Origin = (); UncheckedExtrinsic = UncheckedExtrinsic,
type Config = (); {
type Info = DispatchInfo; System: frame_system::{Module, Call, Config, Storage, Event<T>},
type PostInfo = PostDispatchInfo;
fn dispatch(self, _origin: Self::Origin)
-> sp_runtime::DispatchResultWithInfo<Self::PostInfo> {
panic!("Do not use dummy implementation for dispatch.");
} }
} );
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Test;
impl frame_system::Config for Test { impl frame_system::Config for Test {
type BaseCallFilter = (); type BaseCallFilter = ();
@@ -64,10 +52,10 @@ impl frame_system::Config for Test {
type AccountId = AccountId; type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = sp_runtime::testing::Header; type Header = sp_runtime::testing::Header;
type Event = (); type Event = Event;
type BlockHashCount = (); type BlockHashCount = ();
type Version = (); type Version = ();
type PalletInfo = (); type PalletInfo = PalletInfo;
type AccountData = (); type AccountData = ();
type OnNewAccount = (); type OnNewAccount = ();
type OnKilledAccount = (); type OnKilledAccount = ();
@@ -110,7 +110,7 @@ mod tests {
let normal = DispatchInfo { weight: 100, class: DispatchClass::Normal, pays_fee: Pays::Yes }; let normal = DispatchInfo { weight: 100, class: DispatchClass::Normal, pays_fee: Pays::Yes };
let len = 0_usize; let len = 0_usize;
let ext = ( let ext = (
crate::CheckWeight::<Test>::default(), crate::CheckWeight::<Test>::new(),
CheckMortality::<Test>::from(Era::mortal(16, 256)), CheckMortality::<Test>::from(Era::mortal(16, 256)),
); );
System::set_block_number(17); System::set_block_number(17);
+21 -31
View File
@@ -15,24 +15,27 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use crate::*; use crate::{self as frame_system, *};
use sp_std::cell::RefCell; use sp_std::cell::RefCell;
use sp_core::H256; use sp_core::H256;
use sp_runtime::{ use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup}, traits::{BlakeTwo256, IdentityLookup},
testing::Header, testing::Header, BuildStorage,
};
use frame_support::{
impl_outer_origin, parameter_types,
weights::PostDispatchInfo,
}; };
use frame_support::parameter_types;
impl_outer_origin! { type UncheckedExtrinsic = mocking::MockUncheckedExtrinsic<Test>;
pub enum Origin for Test where system = super {} type Block = mocking::MockBlock<Test>;
}
#[derive(Clone, Eq, PartialEq, Debug, Default)] frame_support::construct_runtime!(
pub struct Test; pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Module, Call, Config, Storage, Event<T>},
}
);
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
const MAX_BLOCK_WEIGHT: Weight = 1024; const MAX_BLOCK_WEIGHT: Weight = 1024;
@@ -81,20 +84,6 @@ impl OnKilledAccount<u64> for RecordKilled {
fn on_killed_account(who: &u64) { KILLED.with(|r| r.borrow_mut().push(*who)) } fn on_killed_account(who: &u64) { KILLED.with(|r| r.borrow_mut().push(*who)) }
} }
#[derive(Debug, codec::Encode, codec::Decode)]
pub struct Call;
impl Dispatchable for Call {
type Origin = Origin;
type Config = ();
type Info = DispatchInfo;
type PostInfo = PostDispatchInfo;
fn dispatch(self, _origin: Self::Origin)
-> sp_runtime::DispatchResultWithInfo<Self::PostInfo> {
panic!("Do not use dummy implementation for dispatch.");
}
}
impl Config for Test { impl Config for Test {
type BaseCallFilter = (); type BaseCallFilter = ();
type BlockWeights = RuntimeBlockWeights; type BlockWeights = RuntimeBlockWeights;
@@ -108,11 +97,11 @@ impl Config for Test {
type AccountId = u64; type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = Event<Self>; type Event = Event;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type DbWeight = DbWeight; type DbWeight = DbWeight;
type Version = Version; type Version = Version;
type PalletInfo = (); type PalletInfo = PalletInfo;
type AccountData = u32; type AccountData = u32;
type OnNewAccount = (); type OnNewAccount = ();
type OnKilledAccount = RecordKilled; type OnKilledAccount = RecordKilled;
@@ -120,14 +109,15 @@ impl Config for Test {
type SS58Prefix = (); type SS58Prefix = ();
} }
pub type System = Module<Test>; pub type SysEvent = frame_system::Event<Test>;
pub type SysEvent = <Test as Config>::Event;
pub const CALL: &<Test as Config>::Call = &Call; /// A simple call, which one doesn't matter.
pub const CALL: &<Test as Config>::Call = &Call::System(frame_system::Call::set_heap_pages(0u64));
/// Create new externalities for `System` module tests. /// Create new externalities for `System` module tests.
pub fn new_test_ext() -> sp_io::TestExternalities { pub fn new_test_ext() -> sp_io::TestExternalities {
let mut ext: sp_io::TestExternalities = GenesisConfig::default().build_storage::<Test>().unwrap().into(); let mut ext: sp_io::TestExternalities = GenesisConfig::default()
.build_storage().unwrap().into();
// Add to each test the initial weight of a block // Add to each test the initial weight of a block
ext.execute_with(|| System::register_extra_weight_unchecked( ext.execute_with(|| System::register_extra_weight_unchecked(
<Test as crate::Config>::BlockWeights::get().base_block, <Test as crate::Config>::BlockWeights::get().base_block,
+5 -5
View File
@@ -637,7 +637,7 @@ pub trait SignedPayload<T: SigningTypes>: Encode {
mod tests { mod tests {
use super::*; use super::*;
use codec::Decode; use codec::Decode;
use crate::mock::{Test as TestRuntime, Call}; use crate::mock::{Test as TestRuntime, Call, CALL};
use sp_core::offchain::{testing, TransactionPoolExt}; use sp_core::offchain::{testing, TransactionPoolExt};
use sp_runtime::testing::{UintAuthorityId, TestSignature, TestXt}; use sp_runtime::testing::{UintAuthorityId, TestSignature, TestXt};
@@ -708,7 +708,7 @@ mod tests {
public: account.public.clone() public: account.public.clone()
}, },
|_payload, _signature| { |_payload, _signature| {
Call CALL.clone()
} }
); );
@@ -749,7 +749,7 @@ mod tests {
public: account.public.clone() public: account.public.clone()
}, },
|_payload, _signature| { |_payload, _signature| {
Call CALL.clone()
} }
); );
@@ -787,7 +787,7 @@ mod tests {
public: account.public.clone() public: account.public.clone()
}, },
|_payload, _signature| { |_payload, _signature| {
Call CALL.clone()
} }
); );
@@ -827,7 +827,7 @@ mod tests {
public: account.public.clone() public: account.public.clone()
}, },
|_payload, _signature| { |_payload, _signature| {
Call CALL.clone()
} }
); );
+17 -17
View File
@@ -71,7 +71,7 @@ fn deposit_event_should_work() {
vec![ vec![
EventRecord { EventRecord {
phase: Phase::Finalization, phase: Phase::Finalization,
event: SysEvent::CodeUpdated, event: SysEvent::CodeUpdated.into(),
topics: vec![], topics: vec![],
} }
] ]
@@ -99,17 +99,17 @@ fn deposit_event_should_work() {
vec![ vec![
EventRecord { EventRecord {
phase: Phase::Initialization, phase: Phase::Initialization,
event: SysEvent::NewAccount(32), event: SysEvent::NewAccount(32).into(),
topics: vec![], topics: vec![],
}, },
EventRecord { EventRecord {
phase: Phase::ApplyExtrinsic(0), phase: Phase::ApplyExtrinsic(0),
event: SysEvent::KilledAccount(42), event: SysEvent::KilledAccount(42).into(),
topics: vec![] topics: vec![]
}, },
EventRecord { EventRecord {
phase: Phase::ApplyExtrinsic(0), phase: Phase::ApplyExtrinsic(0),
event: SysEvent::ExtrinsicSuccess(Default::default()), event: SysEvent::ExtrinsicSuccess(Default::default()).into(),
topics: vec![] topics: vec![]
}, },
EventRecord { EventRecord {
@@ -117,12 +117,12 @@ fn deposit_event_should_work() {
event: SysEvent::ExtrinsicFailed( event: SysEvent::ExtrinsicFailed(
DispatchError::BadOrigin.into(), DispatchError::BadOrigin.into(),
Default::default() Default::default()
), ).into(),
topics: vec![] topics: vec![]
}, },
EventRecord { EventRecord {
phase: Phase::Finalization, phase: Phase::Finalization,
event: SysEvent::NewAccount(3), event: SysEvent::NewAccount(3).into(),
topics: vec![] topics: vec![]
}, },
] ]
@@ -173,7 +173,7 @@ fn deposit_event_uses_actual_weight() {
weight: 300, weight: 300,
.. Default::default() .. Default::default()
}, },
), ).into(),
topics: vec![] topics: vec![]
}, },
EventRecord { EventRecord {
@@ -183,7 +183,7 @@ fn deposit_event_uses_actual_weight() {
weight: 1000, weight: 1000,
.. Default::default() .. Default::default()
}, },
), ).into(),
topics: vec![] topics: vec![]
}, },
EventRecord { EventRecord {
@@ -193,7 +193,7 @@ fn deposit_event_uses_actual_weight() {
weight: 1000, weight: 1000,
.. Default::default() .. Default::default()
}, },
), ).into(),
topics: vec![] topics: vec![]
}, },
EventRecord { EventRecord {
@@ -204,7 +204,7 @@ fn deposit_event_uses_actual_weight() {
weight: 999, weight: 999,
.. Default::default() .. Default::default()
}, },
), ).into(),
topics: vec![] topics: vec![]
}, },
] ]
@@ -232,9 +232,9 @@ fn deposit_event_topics() {
]; ];
// We deposit a few events with different sets of topics. // We deposit a few events with different sets of topics.
System::deposit_event_indexed(&topics[0..3], SysEvent::NewAccount(1)); System::deposit_event_indexed(&topics[0..3], SysEvent::NewAccount(1).into());
System::deposit_event_indexed(&topics[0..1], SysEvent::NewAccount(2)); System::deposit_event_indexed(&topics[0..1], SysEvent::NewAccount(2).into());
System::deposit_event_indexed(&topics[1..2], SysEvent::NewAccount(3)); System::deposit_event_indexed(&topics[1..2], SysEvent::NewAccount(3).into());
System::finalize(); System::finalize();
@@ -244,17 +244,17 @@ fn deposit_event_topics() {
vec![ vec![
EventRecord { EventRecord {
phase: Phase::Finalization, phase: Phase::Finalization,
event: SysEvent::NewAccount(1), event: SysEvent::NewAccount(1).into(),
topics: topics[0..3].to_vec(), topics: topics[0..3].to_vec(),
}, },
EventRecord { EventRecord {
phase: Phase::Finalization, phase: Phase::Finalization,
event: SysEvent::NewAccount(2), event: SysEvent::NewAccount(2).into(),
topics: topics[0..1].to_vec(), topics: topics[0..1].to_vec(),
}, },
EventRecord { EventRecord {
phase: Phase::Finalization, phase: Phase::Finalization,
event: SysEvent::NewAccount(3), event: SysEvent::NewAccount(3).into(),
topics: topics[1..2].to_vec(), topics: topics[1..2].to_vec(),
} }
] ]
@@ -375,7 +375,7 @@ fn set_code_with_real_wasm_blob() {
System::events(), System::events(),
vec![EventRecord { vec![EventRecord {
phase: Phase::Initialization, phase: Phase::Initialization,
event: SysEvent::CodeUpdated, event: SysEvent::CodeUpdated.into(),
topics: vec![], topics: vec![],
}], }],
); );