git.delta.rocks / unique-network / refs/commits / 91c34acacac8

difftreelog

source

pallets/scheduler-v2/src/mock.rs8.1 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Scheduler test environment.3637use super::*;3839use crate as scheduler;40use frame_support::{41	ord_parameter_types, parameter_types,42	traits::{ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnFinalize, OnInitialize},43	weights::constants::RocksDbWeight,44};45use frame_system::{EnsureRoot, RawOrigin};46use sp_core::H256;47use sp_runtime::{48	testing::Header,49	traits::{BlakeTwo256, IdentityLookup},50	Perbill,51};5253// Logger module to track execution.54#[frame_support::pallet]55pub mod logger {56	use super::{OriginCaller, OriginTrait};57	use frame_support::{pallet_prelude::*, parameter_types};58	use frame_system::pallet_prelude::*;5960	parameter_types! {61		static Log: Vec<(OriginCaller, u32)> = Vec::new();62	}63	pub fn log() -> Vec<(OriginCaller, u32)> {64		Log::get().clone()65	}6667	#[pallet::pallet]68	#[pallet::generate_store(pub(super) trait Store)]69	pub struct Pallet<T>(PhantomData<T>);7071	#[pallet::hooks]72	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}7374	#[pallet::config]75	pub trait Config: frame_system::Config {76		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;77	}7879	#[pallet::event]80	#[pallet::generate_deposit(pub(super) fn deposit_event)]81	pub enum Event<T: Config> {82		Logged(u32, Weight),83	}8485	#[pallet::call]86	impl<T: Config> Pallet<T>87	where88		<T as frame_system::Config>::RuntimeOrigin: OriginTrait<PalletsOrigin = OriginCaller>,89	{90		#[pallet::call_index(0)]91		#[pallet::weight(*weight)]92		pub fn log(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {93			Self::deposit_event(Event::Logged(i, weight));94			Log::mutate(|log| {95				log.push((origin.caller().clone(), i));96			});97			Ok(())98		}99100		#[pallet::call_index(1)]101		#[pallet::weight(*weight)]102		pub fn log_without_filter(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {103			Self::deposit_event(Event::Logged(i, weight));104			Log::mutate(|log| {105				log.push((origin.caller().clone(), i));106			});107			Ok(())108		}109	}110}111112type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;113type Block = frame_system::mocking::MockBlock<Test>;114115frame_support::construct_runtime!(116	pub enum Test where117		Block = Block,118		NodeBlock = Block,119		UncheckedExtrinsic = UncheckedExtrinsic,120	{121		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},122		Logger: logger::{Pallet, Call, Event<T>},123		Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},124	}125);126127// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.128pub struct BaseFilter;129impl Contains<RuntimeCall> for BaseFilter {130	fn contains(call: &RuntimeCall) -> bool {131		!matches!(call, RuntimeCall::Logger(LoggerCall::log { .. }))132	}133}134135parameter_types! {136	pub BlockWeights: frame_system::limits::BlockWeights =137		frame_system::limits::BlockWeights::simple_max(138			Weight::from_ref_time(2_000_000_000_000).set_proof_size(u64::MAX)139		);140}141impl system::Config for Test {142	type BaseCallFilter = BaseFilter;143	type BlockWeights = BlockWeights;144	type BlockLength = ();145	type DbWeight = RocksDbWeight;146	type RuntimeOrigin = RuntimeOrigin;147	type RuntimeCall = RuntimeCall;148	type Index = u64;149	type BlockNumber = u64;150	type Hash = H256;151	type Hashing = BlakeTwo256;152	type AccountId = u64;153	type Lookup = IdentityLookup<Self::AccountId>;154	type Header = Header;155	type RuntimeEvent = RuntimeEvent;156	type BlockHashCount = ConstU64<250>;157	type Version = ();158	type PalletInfo = PalletInfo;159	type AccountData = ();160	type OnNewAccount = ();161	type OnKilledAccount = ();162	type SystemWeightInfo = ();163	type SS58Prefix = ();164	type OnSetCode = ();165	type MaxConsumers = ConstU32<16>;166}167impl logger::Config for Test {168	type RuntimeEvent = RuntimeEvent;169}170ord_parameter_types! {171	pub const One: u64 = 1;172}173174pub struct TestWeightInfo;175impl WeightInfo for TestWeightInfo {176	fn service_agendas_base() -> Weight {177		Weight::from_ref_time(0b0000_0001)178	}179	fn service_agenda_base(i: u32) -> Weight {180		Weight::from_ref_time((i << 8) as u64 + 0b0000_0010)181	}182	fn service_task_base() -> Weight {183		Weight::from_ref_time(0b0000_0100)184	}185	fn service_task_periodic() -> Weight {186		Weight::from_ref_time(0b0000_1100)187	}188	fn service_task_named() -> Weight {189		Weight::from_ref_time(0b0001_0100)190	}191	// fn service_task_fetched(s: u32) -> Weight {192	// 	Weight::from_ref_time((s << 8) as u64 + 0b0010_0100)193	// }194	fn execute_dispatch_signed() -> Weight {195		Weight::from_ref_time(0b0100_0000)196	}197	fn execute_dispatch_unsigned() -> Weight {198		Weight::from_ref_time(0b1000_0000)199	}200	fn schedule(_s: u32) -> Weight {201		Weight::from_ref_time(50)202	}203	fn cancel(_s: u32) -> Weight {204		Weight::from_ref_time(50)205	}206	fn schedule_named(_s: u32) -> Weight {207		Weight::from_ref_time(50)208	}209	fn cancel_named(_s: u32) -> Weight {210		Weight::from_ref_time(50)211	}212	fn change_named_priority(_s: u32) -> Weight {213		Weight::from_ref_time(50)214	}215}216parameter_types! {217	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *218		BlockWeights::get().max_block;219}220221pub struct EnsureSignedOneOrRoot;222impl<O: Into<Result<RawOrigin<u64>, O>> + From<RawOrigin<u64>>> EnsureOrigin<O>223	for EnsureSignedOneOrRoot224{225	type Success = ScheduledEnsureOriginSuccess<u64>;226	fn try_origin(o: O) -> Result<Self::Success, O> {227		o.into().and_then(|o| match o {228			RawOrigin::Root => Ok(ScheduledEnsureOriginSuccess::Root),229			RawOrigin::Signed(1) => Ok(ScheduledEnsureOriginSuccess::Signed(1)),230			r => Err(O::from(r)),231		})232	}233}234235pub struct Executor;236impl DispatchCall<Test, sp_core::H160> for Executor {237	fn dispatch_call(238		signer: Option<u64>,239		function: RuntimeCall,240	) -> Result<241		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,242		TransactionValidityError,243	> {244		let origin = match signer {245			Some(who) => RuntimeOrigin::signed(who),246			None => RuntimeOrigin::none(),247		};248		Ok(function.dispatch(origin))249	}250}251252impl Config for Test {253	type RuntimeEvent = RuntimeEvent;254	type RuntimeOrigin = RuntimeOrigin;255	type PalletsOrigin = OriginCaller;256	type RuntimeCall = RuntimeCall;257	type MaximumWeight = MaximumSchedulerWeight;258	type ScheduleOrigin = EnsureSignedOneOrRoot;259	type MaxScheduledPerBlock = ConstU32<10>;260	type WeightInfo = TestWeightInfo;261	type OriginPrivilegeCmp = EqualPrivilegeOnly;262	type Preimages = ();263	type PrioritySetOrigin = EnsureRoot<u64>;264	type CallExecutor = Executor;265}266267pub type LoggerCall = logger::Call<Test>;268269pub type SystemCall = frame_system::Call<Test>;270271pub fn new_test_ext() -> sp_io::TestExternalities {272	let t = system::GenesisConfig::default()273		.build_storage::<Test>()274		.unwrap();275	t.into()276}277278pub fn run_to_block(n: u64) {279	while System::block_number() < n {280		Scheduler::on_finalize(System::block_number());281		System::set_block_number(System::block_number() + 1);282		Scheduler::on_initialize(System::block_number());283	}284}285286pub fn root() -> OriginCaller {287	system::RawOrigin::Root.into()288}