difftreelog
fix periodic tasks always find place
in: master
2 files changed
pallets/scheduler-v2/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler-v2/src/lib.rs
+++ b/pallets/scheduler-v2/src/lib.rs
@@ -96,7 +96,7 @@
BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,
};
use sp_core::H160;
-use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};
+use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*};
pub use weights::WeightInfo;
pub use pallet::*;
@@ -254,9 +254,9 @@
}
impl<T: Config> BlockAgenda<T> {
- fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Option<u32> {
+ fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Result<u32, ScheduledOf<T>> {
if self.free_places == 0 {
- return None;
+ return Err(scheduled);
}
self.free_places = self.free_places.saturating_sub(1);
@@ -264,14 +264,14 @@
if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {
// will always succeed due to the above check.
let _ = self.agenda.try_push(Some(scheduled));
- Some((self.agenda.len() - 1) as u32)
+ Ok((self.agenda.len() - 1) as u32)
} else {
match self.agenda.iter().position(|i| i.is_none()) {
Some(hole_index) => {
self.agenda[hole_index] = Some(scheduled);
- Some(hole_index as u32)
+ Ok(hole_index as u32)
}
- None => unreachable!("free_places > 0; qed"),
+ None => unreachable!("free_places was greater than 0; qed"),
}
}
}
@@ -473,11 +473,6 @@
},
/// The call for the provided hash was not found so the task has been aborted.
CallUnavailable {
- task: TaskAddress<T::BlockNumber>,
- id: Option<[u8; 32]>,
- },
- /// The given task was unable to be renewed since the agenda is full at that block.
- PeriodicFailed {
task: TaskAddress<T::BlockNumber>,
id: Option<[u8; 32]>,
},
@@ -688,12 +683,24 @@
Ok(when)
}
- fn place_task(
+ fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {
+ Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");
+ }
+
+ fn try_place_task(
when: T::BlockNumber,
what: ScheduledOf<T>,
- ) -> Result<TaskAddress<T::BlockNumber>, (DispatchError, ScheduledOf<T>)> {
+ ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
+ Self::place_task(when, what, false)
+ }
+
+ fn place_task(
+ mut when: T::BlockNumber,
+ what: ScheduledOf<T>,
+ is_mandatory: bool,
+ ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
let maybe_name = what.maybe_id;
- let index = Self::push_to_agenda(when, what)?;
+ let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;
let address = (when, index);
if let Some(name) = maybe_name {
Lookup::<T>::insert(name, address)
@@ -706,13 +713,24 @@
}
fn push_to_agenda(
- when: T::BlockNumber,
- what: ScheduledOf<T>,
- ) -> Result<u32, (DispatchError, ScheduledOf<T>)> {
- let mut agenda = Agenda::<T>::get(when);
- let index = agenda
- .try_push(what.clone())
- .ok_or((<Error<T>>::AgendaIsExhausted.into(), what))?;
+ when: &mut T::BlockNumber,
+ mut what: ScheduledOf<T>,
+ is_mandatory: bool,
+ ) -> Result<u32, DispatchError> {
+ let mut agenda;
+
+ let index = loop {
+ agenda = Agenda::<T>::get(*when);
+
+ match agenda.try_push(what) {
+ Ok(index) => break index,
+ Err(returned_what) if is_mandatory => {
+ what = returned_what;
+ when.saturating_inc();
+ }
+ Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),
+ }
+ };
Agenda::<T>::insert(when, agenda);
Ok(index)
@@ -740,7 +758,7 @@
origin,
_phantom: PhantomData,
};
- Self::place_task(when, task).map_err(|x| x.0)
+ Self::try_place_task(when, task)
}
fn do_cancel(
@@ -809,7 +827,7 @@
origin,
_phantom: Default::default(),
};
- Self::place_task(when, task).map_err(|x| x.0)
+ Self::try_place_task(when, task)
}
fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {
@@ -1075,18 +1093,7 @@
task.maybe_periodic = None;
}
let wake = now.saturating_add(period);
- match Self::place_task(wake, task) {
- Ok(_) => {}
- Err((_, task)) => {
- // TODO: Leave task in storage somewhere for it to be rescheduled
- // manually.
- T::Preimages::drop(&task.call);
- Self::deposit_event(Event::PeriodicFailed {
- task: (when, agenda_index),
- id: task.maybe_id,
- });
- }
- }
+ Self::mandatory_place_task(wake, task);
}
_ => {
if let Some(ref id) = task.maybe_id {
pallets/scheduler-v2/src/tests.rsdiffbeforeafterboth1// 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 tests.3637use super::*;38use crate::mock::{39 logger, new_test_ext, root, run_to_block, LoggerCall, RuntimeCall, Scheduler, Test, *,40};41use frame_support::{42 assert_noop, assert_ok,43 traits::{Contains, OnInitialize},44};4546#[test]47fn basic_scheduling_works() {48 new_test_ext().execute_with(|| {49 let call = RuntimeCall::Logger(LoggerCall::log {50 i: 42,51 weight: Weight::from_ref_time(10),52 });53 assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(54 &call55 ));56 assert_ok!(Scheduler::do_schedule(57 DispatchTime::At(4),58 None,59 127,60 root(),61 <ScheduledCall<Test>>::new(call).unwrap(),62 ));63 run_to_block(3);64 assert!(logger::log().is_empty());65 run_to_block(4);66 assert_eq!(logger::log(), vec![(root(), 42u32)]);67 run_to_block(100);68 assert_eq!(logger::log(), vec![(root(), 42u32)]);69 });70}7172#[test]73fn schedule_after_works() {74 new_test_ext().execute_with(|| {75 run_to_block(2);76 let call = RuntimeCall::Logger(LoggerCall::log {77 i: 42,78 weight: Weight::from_ref_time(10),79 });80 assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(81 &call82 ));83 // This will schedule the call 3 blocks after the next block... so block 3 + 3 = 684 assert_ok!(Scheduler::do_schedule(85 DispatchTime::After(3),86 None,87 127,88 root(),89 <ScheduledCall<Test>>::new(call).unwrap(),90 ));91 run_to_block(5);92 assert!(logger::log().is_empty());93 run_to_block(6);94 assert_eq!(logger::log(), vec![(root(), 42u32)]);95 run_to_block(100);96 assert_eq!(logger::log(), vec![(root(), 42u32)]);97 });98}99100#[test]101fn schedule_after_zero_works() {102 new_test_ext().execute_with(|| {103 run_to_block(2);104 let call = RuntimeCall::Logger(LoggerCall::log {105 i: 42,106 weight: Weight::from_ref_time(10),107 });108 assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(109 &call110 ));111 assert_ok!(Scheduler::do_schedule(112 DispatchTime::After(0),113 None,114 127,115 root(),116 <ScheduledCall<Test>>::new(call).unwrap(),117 ));118 // Will trigger on the next block.119 run_to_block(3);120 assert_eq!(logger::log(), vec![(root(), 42u32)]);121 run_to_block(100);122 assert_eq!(logger::log(), vec![(root(), 42u32)]);123 });124}125126#[test]127fn periodic_scheduling_works() {128 new_test_ext().execute_with(|| {129 // at #4, every 3 blocks, 3 times.130 assert_ok!(Scheduler::do_schedule(131 DispatchTime::At(4),132 Some((3, 3)),133 127,134 root(),135 <ScheduledCall<Test>>::new(RuntimeCall::Logger(logger::Call::log {136 i: 42,137 weight: Weight::from_ref_time(10)138 }))139 .unwrap()140 ));141 run_to_block(3);142 assert!(logger::log().is_empty());143 run_to_block(4);144 assert_eq!(logger::log(), vec![(root(), 42u32)]);145 run_to_block(6);146 assert_eq!(logger::log(), vec![(root(), 42u32)]);147 run_to_block(7);148 assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);149 run_to_block(9);150 assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);151 run_to_block(10);152 assert_eq!(153 logger::log(),154 vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]155 );156 run_to_block(100);157 assert_eq!(158 logger::log(),159 vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]160 );161 });162}163164#[test]165fn cancel_named_scheduling_works_with_normal_cancel() {166 new_test_ext().execute_with(|| {167 // at #4.168 Scheduler::do_schedule_named(169 [1u8; 32],170 DispatchTime::At(4),171 None,172 127,173 root(),174 <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {175 i: 69,176 weight: Weight::from_ref_time(10),177 }))178 .unwrap(),179 )180 .unwrap();181 let i = Scheduler::do_schedule(182 DispatchTime::At(4),183 None,184 127,185 root(),186 <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {187 i: 42,188 weight: Weight::from_ref_time(10),189 }))190 .unwrap(),191 )192 .unwrap();193 run_to_block(3);194 assert!(logger::log().is_empty());195 assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));196 assert_ok!(Scheduler::do_cancel(None, i));197 run_to_block(100);198 assert!(logger::log().is_empty());199 });200}201202#[test]203fn cancel_named_periodic_scheduling_works() {204 new_test_ext().execute_with(|| {205 // at #4, every 3 blocks, 3 times.206 Scheduler::do_schedule_named(207 [1u8; 32],208 DispatchTime::At(4),209 Some((3, 3)),210 127,211 root(),212 <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {213 i: 42,214 weight: Weight::from_ref_time(10),215 }))216 .unwrap(),217 )218 .unwrap();219 // same id results in error.220 assert!(Scheduler::do_schedule_named(221 [1u8; 32],222 DispatchTime::At(4),223 None,224 127,225 root(),226 <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {227 i: 69,228 weight: Weight::from_ref_time(10)229 }))230 .unwrap(),231 )232 .is_err());233 // different id is ok.234 Scheduler::do_schedule_named(235 [2u8; 32],236 DispatchTime::At(8),237 None,238 127,239 root(),240 <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {241 i: 69,242 weight: Weight::from_ref_time(10),243 }))244 .unwrap(),245 )246 .unwrap();247 run_to_block(3);248 assert!(logger::log().is_empty());249 run_to_block(4);250 assert_eq!(logger::log(), vec![(root(), 42u32)]);251 run_to_block(6);252 assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));253 run_to_block(100);254 assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);255 });256}257258#[test]259fn scheduler_respects_weight_limits() {260 let max_weight: Weight = <Test as Config>::MaximumWeight::get();261 new_test_ext().execute_with(|| {262 let call = RuntimeCall::Logger(LoggerCall::log {263 i: 42,264 weight: max_weight / 3 * 2,265 });266 assert_ok!(Scheduler::do_schedule(267 DispatchTime::At(4),268 None,269 127,270 root(),271 <ScheduledCall<Test>>::new(call).unwrap(),272 ));273 let call = RuntimeCall::Logger(LoggerCall::log {274 i: 69,275 weight: max_weight / 3 * 2,276 });277 assert_ok!(Scheduler::do_schedule(278 DispatchTime::At(4),279 None,280 127,281 root(),282 <ScheduledCall<Test>>::new(call).unwrap(),283 ));284 // 69 and 42 do not fit together285 run_to_block(4);286 assert_eq!(logger::log(), vec![(root(), 42u32)]);287 run_to_block(5);288 assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);289 });290}291292/// Permanently overweight calls are not deleted but also not executed.293#[test]294fn scheduler_does_not_delete_permanently_overweight_call() {295 let max_weight: Weight = <Test as Config>::MaximumWeight::get();296 new_test_ext().execute_with(|| {297 let call = RuntimeCall::Logger(LoggerCall::log {298 i: 42,299 weight: max_weight,300 });301 assert_ok!(Scheduler::do_schedule(302 DispatchTime::At(4),303 None,304 127,305 root(),306 <ScheduledCall<Test>>::new(call).unwrap(),307 ));308 // Never executes.309 run_to_block(100);310 assert_eq!(logger::log(), vec![]);311312 // Assert the `PermanentlyOverweight` event.313 assert_eq!(314 System::events().last().unwrap().event,315 crate::Event::PermanentlyOverweight {316 task: (4, 0),317 id: None318 }319 .into(),320 );321 // The call is still in the agenda.322 assert!(Agenda::<Test>::get(4)[0].is_some());323 });324}325326#[test]327fn scheduler_handles_periodic_failure() {328 let max_weight: Weight = <Test as Config>::MaximumWeight::get();329 let max_per_block = <Test as Config>::MaxScheduledPerBlock::get();330331 new_test_ext().execute_with(|| {332 let call = RuntimeCall::Logger(LoggerCall::log {333 i: 42,334 weight: (max_weight / 3) * 2,335 });336 let call = <ScheduledCall<Test>>::new(call).unwrap();337338 assert_ok!(Scheduler::do_schedule(339 DispatchTime::At(4),340 Some((4, u32::MAX)),341 127,342 root(),343 call.clone(),344 ));345 // Executes 5 times till block 20.346 run_to_block(20);347 assert_eq!(logger::log().len(), 5);348349 // Block 28 will already be full.350 for _ in 0..max_per_block {351 assert_ok!(Scheduler::do_schedule(352 DispatchTime::At(28),353 None,354 120,355 root(),356 call.clone(),357 ));358 }359360 // Going to block 24 will emit a `PeriodicFailed` event.361 run_to_block(24);362 assert_eq!(logger::log().len(), 6);363364 assert_eq!(365 System::events().last().unwrap().event,366 crate::Event::PeriodicFailed {367 task: (24, 0),368 id: None369 }370 .into(),371 );372 });373}374375#[test]376fn scheduler_respects_priority_ordering() {377 let max_weight: Weight = <Test as Config>::MaximumWeight::get();378 new_test_ext().execute_with(|| {379 let call = RuntimeCall::Logger(LoggerCall::log {380 i: 42,381 weight: max_weight / 3,382 });383 assert_ok!(Scheduler::do_schedule(384 DispatchTime::At(4),385 None,386 1,387 root(),388 <ScheduledCall<Test>>::new(call).unwrap(),389 ));390 let call = RuntimeCall::Logger(LoggerCall::log {391 i: 69,392 weight: max_weight / 3,393 });394 assert_ok!(Scheduler::do_schedule(395 DispatchTime::At(4),396 None,397 0,398 root(),399 <ScheduledCall<Test>>::new(call).unwrap(),400 ));401 run_to_block(4);402 assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);403 });404}405406#[test]407fn scheduler_respects_priority_ordering_with_soft_deadlines() {408 new_test_ext().execute_with(|| {409 let max_weight: Weight = <Test as Config>::MaximumWeight::get();410 let call = RuntimeCall::Logger(LoggerCall::log {411 i: 42,412 weight: max_weight / 5 * 2,413 });414 assert_ok!(Scheduler::do_schedule(415 DispatchTime::At(4),416 None,417 255,418 root(),419 <ScheduledCall<Test>>::new(call).unwrap(),420 ));421 let call = RuntimeCall::Logger(LoggerCall::log {422 i: 69,423 weight: max_weight / 5 * 2,424 });425 assert_ok!(Scheduler::do_schedule(426 DispatchTime::At(4),427 None,428 127,429 root(),430 <ScheduledCall<Test>>::new(call).unwrap(),431 ));432 let call = RuntimeCall::Logger(LoggerCall::log {433 i: 2600,434 weight: max_weight / 5 * 4,435 });436 assert_ok!(Scheduler::do_schedule(437 DispatchTime::At(4),438 None,439 126,440 root(),441 <ScheduledCall<Test>>::new(call).unwrap(),442 ));443444 // 2600 does not fit with 69 or 42, but has higher priority, so will go through445 run_to_block(4);446 assert_eq!(logger::log(), vec![(root(), 2600u32)]);447 // 69 and 42 fit together448 run_to_block(5);449 assert_eq!(450 logger::log(),451 vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]452 );453 });454}455456#[test]457fn on_initialize_weight_is_correct() {458 new_test_ext().execute_with(|| {459 let call_weight = Weight::from_ref_time(25);460461 // Named462 let call = RuntimeCall::Logger(LoggerCall::log {463 i: 3,464 weight: call_weight + Weight::from_ref_time(1),465 });466 assert_ok!(Scheduler::do_schedule_named(467 [1u8; 32],468 DispatchTime::At(3),469 None,470 255,471 root(),472 <ScheduledCall<Test>>::new(call).unwrap(),473 ));474 let call = RuntimeCall::Logger(LoggerCall::log {475 i: 42,476 weight: call_weight + Weight::from_ref_time(2),477 });478 // Anon Periodic479 assert_ok!(Scheduler::do_schedule(480 DispatchTime::At(2),481 Some((1000, 3)),482 128,483 root(),484 <ScheduledCall<Test>>::new(call).unwrap(),485 ));486 let call = RuntimeCall::Logger(LoggerCall::log {487 i: 69,488 weight: call_weight + Weight::from_ref_time(3),489 });490 // Anon491 assert_ok!(Scheduler::do_schedule(492 DispatchTime::At(2),493 None,494 127,495 root(),496 <ScheduledCall<Test>>::new(call).unwrap(),497 ));498 // Named Periodic499 let call = RuntimeCall::Logger(LoggerCall::log {500 i: 2600,501 weight: call_weight + Weight::from_ref_time(4),502 });503 assert_ok!(Scheduler::do_schedule_named(504 [2u8; 32],505 DispatchTime::At(1),506 Some((1000, 3)),507 126,508 root(),509 <ScheduledCall<Test>>::new(call).unwrap(),510 ));511512 // Will include the named periodic only513 assert_eq!(514 Scheduler::on_initialize(1),515 TestWeightInfo::service_agendas_base()516 + TestWeightInfo::service_agenda_base(1)517 + <TestWeightInfo as MarginalWeightInfo>::service_task(None, true, true)518 + TestWeightInfo::execute_dispatch_unsigned()519 + call_weight + Weight::from_ref_time(4)520 );521 assert_eq!(IncompleteSince::<Test>::get(), None);522 assert_eq!(logger::log(), vec![(root(), 2600u32)]);523524 // Will include anon and anon periodic525 assert_eq!(526 Scheduler::on_initialize(2),527 TestWeightInfo::service_agendas_base()528 + TestWeightInfo::service_agenda_base(2)529 + <TestWeightInfo as MarginalWeightInfo>::service_task(None, false, true)530 + TestWeightInfo::execute_dispatch_unsigned()531 + call_weight + Weight::from_ref_time(3)532 + <TestWeightInfo as MarginalWeightInfo>::service_task(None, false, false)533 + TestWeightInfo::execute_dispatch_unsigned()534 + call_weight + Weight::from_ref_time(2)535 );536 assert_eq!(IncompleteSince::<Test>::get(), None);537 assert_eq!(538 logger::log(),539 vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]540 );541542 // Will include named only543 assert_eq!(544 Scheduler::on_initialize(3),545 TestWeightInfo::service_agendas_base()546 + TestWeightInfo::service_agenda_base(1)547 + <TestWeightInfo as MarginalWeightInfo>::service_task(None, true, false)548 + TestWeightInfo::execute_dispatch_unsigned()549 + call_weight + Weight::from_ref_time(1)550 );551 assert_eq!(IncompleteSince::<Test>::get(), None);552 assert_eq!(553 logger::log(),554 vec![555 (root(), 2600u32),556 (root(), 69u32),557 (root(), 42u32),558 (root(), 3u32)559 ]560 );561562 // Will contain none563 let actual_weight = Scheduler::on_initialize(4);564 assert_eq!(565 actual_weight,566 TestWeightInfo::service_agendas_base() + TestWeightInfo::service_agenda_base(0)567 );568 });569}570571#[test]572fn root_calls_works() {573 new_test_ext().execute_with(|| {574 let call = Box::new(RuntimeCall::Logger(LoggerCall::log {575 i: 69,576 weight: Weight::from_ref_time(10),577 }));578 let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {579 i: 42,580 weight: Weight::from_ref_time(10),581 }));582 assert_ok!(Scheduler::schedule_named(583 RuntimeOrigin::root(),584 [1u8; 32],585 4,586 None,587 Some(127),588 call,589 ));590 assert_ok!(Scheduler::schedule(591 RuntimeOrigin::root(),592 4,593 None,594 Some(127),595 call2596 ));597 run_to_block(3);598 // Scheduled calls are in the agenda.599 assert_eq!(Agenda::<Test>::get(4).len(), 2);600 assert!(logger::log().is_empty());601 assert_ok!(Scheduler::cancel_named(RuntimeOrigin::root(), [1u8; 32]));602 assert_ok!(Scheduler::cancel(RuntimeOrigin::root(), 4, 1));603 // Scheduled calls are made NONE, so should not effect state604 run_to_block(100);605 assert!(logger::log().is_empty());606 });607}608609#[test]610fn fails_to_schedule_task_in_the_past() {611 new_test_ext().execute_with(|| {612 run_to_block(3);613614 let call1 = Box::new(RuntimeCall::Logger(LoggerCall::log {615 i: 69,616 weight: Weight::from_ref_time(10),617 }));618 let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {619 i: 42,620 weight: Weight::from_ref_time(10),621 }));622 let call3 = Box::new(RuntimeCall::Logger(LoggerCall::log {623 i: 42,624 weight: Weight::from_ref_time(10),625 }));626627 assert_noop!(628 Scheduler::schedule_named(RuntimeOrigin::root(), [1u8; 32], 2, None, Some(127), call1),629 Error::<Test>::TargetBlockNumberInPast,630 );631632 assert_noop!(633 Scheduler::schedule(RuntimeOrigin::root(), 2, None, Some(127), call2),634 Error::<Test>::TargetBlockNumberInPast,635 );636637 assert_noop!(638 Scheduler::schedule(RuntimeOrigin::root(), 3, None, Some(127), call3),639 Error::<Test>::TargetBlockNumberInPast,640 );641 });642}643644#[test]645fn should_use_origin() {646 new_test_ext().execute_with(|| {647 let call = Box::new(RuntimeCall::Logger(LoggerCall::log {648 i: 69,649 weight: Weight::from_ref_time(10),650 }));651 let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {652 i: 42,653 weight: Weight::from_ref_time(10),654 }));655 assert_ok!(Scheduler::schedule_named(656 system::RawOrigin::Signed(1).into(),657 [1u8; 32],658 4,659 None,660 None,661 call,662 ));663 assert_ok!(Scheduler::schedule(664 system::RawOrigin::Signed(1).into(),665 4,666 None,667 None,668 call2,669 ));670 run_to_block(3);671 // Scheduled calls are in the agenda.672 assert_eq!(Agenda::<Test>::get(4).len(), 2);673 assert!(logger::log().is_empty());674 assert_ok!(Scheduler::cancel_named(675 system::RawOrigin::Signed(1).into(),676 [1u8; 32]677 ));678 assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));679 // Scheduled calls are made NONE, so should not effect state680 run_to_block(100);681 assert!(logger::log().is_empty());682 });683}684685#[test]686fn should_check_origin() {687 new_test_ext().execute_with(|| {688 let call = Box::new(RuntimeCall::Logger(LoggerCall::log {689 i: 69,690 weight: Weight::from_ref_time(10),691 }));692 let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {693 i: 42,694 weight: Weight::from_ref_time(10),695 }));696 assert_noop!(697 Scheduler::schedule_named(698 system::RawOrigin::Signed(2).into(),699 [1u8; 32],700 4,701 None,702 None,703 call704 ),705 BadOrigin706 );707 assert_noop!(708 Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, None, call2),709 BadOrigin710 );711 });712}713714#[test]715fn should_check_origin_for_cancel() {716 new_test_ext().execute_with(|| {717 let call = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {718 i: 69,719 weight: Weight::from_ref_time(10),720 }));721 let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {722 i: 42,723 weight: Weight::from_ref_time(10),724 }));725 assert_ok!(Scheduler::schedule_named(726 system::RawOrigin::Signed(1).into(),727 [1u8; 32],728 4,729 None,730 None,731 call,732 ));733 assert_ok!(Scheduler::schedule(734 system::RawOrigin::Signed(1).into(),735 4,736 None,737 None,738 call2,739 ));740 run_to_block(3);741 // Scheduled calls are in the agenda.742 assert_eq!(Agenda::<Test>::get(4).len(), 2);743 assert!(logger::log().is_empty());744 assert_noop!(745 Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), [1u8; 32]),746 BadOrigin747 );748 assert_noop!(749 Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1),750 BadOrigin751 );752 assert_noop!(753 Scheduler::cancel_named(system::RawOrigin::Root.into(), [1u8; 32]),754 BadOrigin755 );756 assert_noop!(757 Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1),758 BadOrigin759 );760 run_to_block(5);761 assert_eq!(762 logger::log(),763 vec![764 (system::RawOrigin::Signed(1).into(), 69u32),765 (system::RawOrigin::Signed(1).into(), 42u32)766 ]767 );768 });769}770771/// Cancelling a call and then scheduling a second call for the same772/// block results in different addresses.773#[test]774fn schedule_does_not_resuse_addr() {775 new_test_ext().execute_with(|| {776 let call = RuntimeCall::Logger(LoggerCall::log {777 i: 42,778 weight: Weight::from_ref_time(10),779 });780781 // Schedule both calls.782 let addr_1 = Scheduler::do_schedule(783 DispatchTime::At(4),784 None,785 127,786 root(),787 <ScheduledCall<Test>>::new(call.clone()).unwrap(),788 )789 .unwrap();790 // Cancel the call.791 assert_ok!(Scheduler::do_cancel(None, addr_1));792 let addr_2 = Scheduler::do_schedule(793 DispatchTime::At(4),794 None,795 127,796 root(),797 <ScheduledCall<Test>>::new(call).unwrap(),798 )799 .unwrap();800801 // Should not re-use the address.802 assert!(addr_1 != addr_2);803 });804}805806#[test]807fn schedule_agenda_overflows() {808 let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();809810 new_test_ext().execute_with(|| {811 let call = RuntimeCall::Logger(LoggerCall::log {812 i: 42,813 weight: Weight::from_ref_time(10),814 });815 let call = <ScheduledCall<Test>>::new(call).unwrap();816817 // Schedule the maximal number allowed per block.818 for _ in 0..max {819 Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone()).unwrap();820 }821822 // One more time and it errors.823 assert_noop!(824 Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call,),825 <Error<Test>>::AgendaIsExhausted,826 );827828 run_to_block(4);829 // All scheduled calls are executed.830 assert_eq!(logger::log().len() as u32, max);831 });832}833834/// Cancelling and scheduling does not overflow the agenda but fills holes.835#[test]836fn cancel_and_schedule_fills_holes() {837 let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();838 assert!(839 max > 3,840 "This test only makes sense for MaxScheduledPerBlock > 3"841 );842843 new_test_ext().execute_with(|| {844 let call = RuntimeCall::Logger(LoggerCall::log {845 i: 42,846 weight: Weight::from_ref_time(10),847 });848 let call = <ScheduledCall<Test>>::new(call).unwrap();849 let mut addrs = Vec::<_>::default();850851 // Schedule the maximal number allowed per block.852 for _ in 0..max {853 addrs.push(854 Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())855 .unwrap(),856 );857 }858 // Cancel three of them.859 for addr in addrs.into_iter().take(3) {860 Scheduler::do_cancel(None, addr).unwrap();861 }862 // Schedule three new ones.863 for i in 0..3 {864 let (_block, index) =865 Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())866 .unwrap();867 assert_eq!(i, index);868 }869870 run_to_block(4);871 // Maximum number of calls are executed.872 assert_eq!(logger::log().len() as u32, max);873 });874}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 tests.3637use super::*;38use crate::mock::{39 logger, new_test_ext, root, run_to_block, LoggerCall, RuntimeCall, Scheduler, Test, *,40};41use frame_support::{42 assert_noop, assert_ok,43 traits::{Contains, OnInitialize},44};4546#[test]47fn basic_scheduling_works() {48 new_test_ext().execute_with(|| {49 let call = RuntimeCall::Logger(LoggerCall::log {50 i: 42,51 weight: Weight::from_ref_time(10),52 });53 assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(54 &call55 ));56 assert_ok!(Scheduler::do_schedule(57 DispatchTime::At(4),58 None,59 127,60 root(),61 <ScheduledCall<Test>>::new(call).unwrap(),62 ));63 run_to_block(3);64 assert!(logger::log().is_empty());65 run_to_block(4);66 assert_eq!(logger::log(), vec![(root(), 42u32)]);67 run_to_block(100);68 assert_eq!(logger::log(), vec![(root(), 42u32)]);69 });70}7172#[test]73fn schedule_after_works() {74 new_test_ext().execute_with(|| {75 run_to_block(2);76 let call = RuntimeCall::Logger(LoggerCall::log {77 i: 42,78 weight: Weight::from_ref_time(10),79 });80 assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(81 &call82 ));83 // This will schedule the call 3 blocks after the next block... so block 3 + 3 = 684 assert_ok!(Scheduler::do_schedule(85 DispatchTime::After(3),86 None,87 127,88 root(),89 <ScheduledCall<Test>>::new(call).unwrap(),90 ));91 run_to_block(5);92 assert!(logger::log().is_empty());93 run_to_block(6);94 assert_eq!(logger::log(), vec![(root(), 42u32)]);95 run_to_block(100);96 assert_eq!(logger::log(), vec![(root(), 42u32)]);97 });98}99100#[test]101fn schedule_after_zero_works() {102 new_test_ext().execute_with(|| {103 run_to_block(2);104 let call = RuntimeCall::Logger(LoggerCall::log {105 i: 42,106 weight: Weight::from_ref_time(10),107 });108 assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(109 &call110 ));111 assert_ok!(Scheduler::do_schedule(112 DispatchTime::After(0),113 None,114 127,115 root(),116 <ScheduledCall<Test>>::new(call).unwrap(),117 ));118 // Will trigger on the next block.119 run_to_block(3);120 assert_eq!(logger::log(), vec![(root(), 42u32)]);121 run_to_block(100);122 assert_eq!(logger::log(), vec![(root(), 42u32)]);123 });124}125126#[test]127fn periodic_scheduling_works() {128 new_test_ext().execute_with(|| {129 // at #4, every 3 blocks, 3 times.130 assert_ok!(Scheduler::do_schedule(131 DispatchTime::At(4),132 Some((3, 3)),133 127,134 root(),135 <ScheduledCall<Test>>::new(RuntimeCall::Logger(logger::Call::log {136 i: 42,137 weight: Weight::from_ref_time(10)138 }))139 .unwrap()140 ));141 run_to_block(3);142 assert!(logger::log().is_empty());143 run_to_block(4);144 assert_eq!(logger::log(), vec![(root(), 42u32)]);145 run_to_block(6);146 assert_eq!(logger::log(), vec![(root(), 42u32)]);147 run_to_block(7);148 assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);149 run_to_block(9);150 assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);151 run_to_block(10);152 assert_eq!(153 logger::log(),154 vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]155 );156 run_to_block(100);157 assert_eq!(158 logger::log(),159 vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]160 );161 });162}163164#[test]165fn cancel_named_scheduling_works_with_normal_cancel() {166 new_test_ext().execute_with(|| {167 // at #4.168 Scheduler::do_schedule_named(169 [1u8; 32],170 DispatchTime::At(4),171 None,172 127,173 root(),174 <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {175 i: 69,176 weight: Weight::from_ref_time(10),177 }))178 .unwrap(),179 )180 .unwrap();181 let i = Scheduler::do_schedule(182 DispatchTime::At(4),183 None,184 127,185 root(),186 <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {187 i: 42,188 weight: Weight::from_ref_time(10),189 }))190 .unwrap(),191 )192 .unwrap();193 run_to_block(3);194 assert!(logger::log().is_empty());195 assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));196 assert_ok!(Scheduler::do_cancel(None, i));197 run_to_block(100);198 assert!(logger::log().is_empty());199 });200}201202#[test]203fn cancel_named_periodic_scheduling_works() {204 new_test_ext().execute_with(|| {205 // at #4, every 3 blocks, 3 times.206 Scheduler::do_schedule_named(207 [1u8; 32],208 DispatchTime::At(4),209 Some((3, 3)),210 127,211 root(),212 <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {213 i: 42,214 weight: Weight::from_ref_time(10),215 }))216 .unwrap(),217 )218 .unwrap();219 // same id results in error.220 assert!(Scheduler::do_schedule_named(221 [1u8; 32],222 DispatchTime::At(4),223 None,224 127,225 root(),226 <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {227 i: 69,228 weight: Weight::from_ref_time(10)229 }))230 .unwrap(),231 )232 .is_err());233 // different id is ok.234 Scheduler::do_schedule_named(235 [2u8; 32],236 DispatchTime::At(8),237 None,238 127,239 root(),240 <ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {241 i: 69,242 weight: Weight::from_ref_time(10),243 }))244 .unwrap(),245 )246 .unwrap();247 run_to_block(3);248 assert!(logger::log().is_empty());249 run_to_block(4);250 assert_eq!(logger::log(), vec![(root(), 42u32)]);251 run_to_block(6);252 assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));253 run_to_block(100);254 assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);255 });256}257258#[test]259fn scheduler_respects_weight_limits() {260 let max_weight: Weight = <Test as Config>::MaximumWeight::get();261 new_test_ext().execute_with(|| {262 let call = RuntimeCall::Logger(LoggerCall::log {263 i: 42,264 weight: max_weight / 3 * 2,265 });266 assert_ok!(Scheduler::do_schedule(267 DispatchTime::At(4),268 None,269 127,270 root(),271 <ScheduledCall<Test>>::new(call).unwrap(),272 ));273 let call = RuntimeCall::Logger(LoggerCall::log {274 i: 69,275 weight: max_weight / 3 * 2,276 });277 assert_ok!(Scheduler::do_schedule(278 DispatchTime::At(4),279 None,280 127,281 root(),282 <ScheduledCall<Test>>::new(call).unwrap(),283 ));284 // 69 and 42 do not fit together285 run_to_block(4);286 assert_eq!(logger::log(), vec![(root(), 42u32)]);287 run_to_block(5);288 assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);289 });290}291292/// Permanently overweight calls are not deleted but also not executed.293#[test]294fn scheduler_does_not_delete_permanently_overweight_call() {295 let max_weight: Weight = <Test as Config>::MaximumWeight::get();296 new_test_ext().execute_with(|| {297 let call = RuntimeCall::Logger(LoggerCall::log {298 i: 42,299 weight: max_weight,300 });301 assert_ok!(Scheduler::do_schedule(302 DispatchTime::At(4),303 None,304 127,305 root(),306 <ScheduledCall<Test>>::new(call).unwrap(),307 ));308 // Never executes.309 run_to_block(100);310 assert_eq!(logger::log(), vec![]);311312 // Assert the `PermanentlyOverweight` event.313 assert_eq!(314 System::events().last().unwrap().event,315 crate::Event::PermanentlyOverweight {316 task: (4, 0),317 id: None318 }319 .into(),320 );321 // The call is still in the agenda.322 assert!(Agenda::<Test>::get(4).agenda[0].is_some());323 });324}325326#[test]327fn scheduler_periodic_tasks_always_find_place() {328 let max_weight: Weight = <Test as Config>::MaximumWeight::get();329 let max_per_block = <Test as Config>::MaxScheduledPerBlock::get();330331 new_test_ext().execute_with(|| {332 let call = RuntimeCall::Logger(LoggerCall::log {333 i: 42,334 weight: (max_weight / 3) * 2,335 });336 let call = <ScheduledCall<Test>>::new(call).unwrap();337338 assert_ok!(Scheduler::do_schedule(339 DispatchTime::At(4),340 Some((4, u32::MAX)),341 127,342 root(),343 call.clone(),344 ));345 // Executes 5 times till block 20.346 run_to_block(20);347 assert_eq!(logger::log().len(), 5);348349 // Block 28 will already be full.350 for _ in 0..max_per_block {351 assert_ok!(Scheduler::do_schedule(352 DispatchTime::At(28),353 None,354 120,355 root(),356 call.clone(),357 ));358 }359360 run_to_block(24);361 assert_eq!(logger::log().len(), 6);362363 // The periodic task should be postponed364 assert_eq!(<Agenda<Test>>::get(29).agenda.len(), 1);365366 run_to_block(27); // will call on_initialize(28)367 assert_eq!(logger::log().len(), 6);368369 run_to_block(28); // will call on_initialize(29)370 assert_eq!(logger::log().len(), 7);371 });372}373374#[test]375fn scheduler_respects_priority_ordering() {376 let max_weight: Weight = <Test as Config>::MaximumWeight::get();377 new_test_ext().execute_with(|| {378 let call = RuntimeCall::Logger(LoggerCall::log {379 i: 42,380 weight: max_weight / 3,381 });382 assert_ok!(Scheduler::do_schedule(383 DispatchTime::At(4),384 None,385 1,386 root(),387 <ScheduledCall<Test>>::new(call).unwrap(),388 ));389 let call = RuntimeCall::Logger(LoggerCall::log {390 i: 69,391 weight: max_weight / 3,392 });393 assert_ok!(Scheduler::do_schedule(394 DispatchTime::At(4),395 None,396 0,397 root(),398 <ScheduledCall<Test>>::new(call).unwrap(),399 ));400 run_to_block(4);401 assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);402 });403}404405#[test]406fn scheduler_respects_priority_ordering_with_soft_deadlines() {407 new_test_ext().execute_with(|| {408 let max_weight: Weight = <Test as Config>::MaximumWeight::get();409 let call = RuntimeCall::Logger(LoggerCall::log {410 i: 42,411 weight: max_weight / 5 * 2,412 });413 assert_ok!(Scheduler::do_schedule(414 DispatchTime::At(4),415 None,416 255,417 root(),418 <ScheduledCall<Test>>::new(call).unwrap(),419 ));420 let call = RuntimeCall::Logger(LoggerCall::log {421 i: 69,422 weight: max_weight / 5 * 2,423 });424 assert_ok!(Scheduler::do_schedule(425 DispatchTime::At(4),426 None,427 127,428 root(),429 <ScheduledCall<Test>>::new(call).unwrap(),430 ));431 let call = RuntimeCall::Logger(LoggerCall::log {432 i: 2600,433 weight: max_weight / 5 * 4,434 });435 assert_ok!(Scheduler::do_schedule(436 DispatchTime::At(4),437 None,438 126,439 root(),440 <ScheduledCall<Test>>::new(call).unwrap(),441 ));442443 // 2600 does not fit with 69 or 42, but has higher priority, so will go through444 run_to_block(4);445 assert_eq!(logger::log(), vec![(root(), 2600u32)]);446 // 69 and 42 fit together447 run_to_block(5);448 assert_eq!(449 logger::log(),450 vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]451 );452 });453}454455#[test]456fn on_initialize_weight_is_correct() {457 new_test_ext().execute_with(|| {458 let call_weight = Weight::from_ref_time(25);459460 // Named461 let call = RuntimeCall::Logger(LoggerCall::log {462 i: 3,463 weight: call_weight + Weight::from_ref_time(1),464 });465 assert_ok!(Scheduler::do_schedule_named(466 [1u8; 32],467 DispatchTime::At(3),468 None,469 255,470 root(),471 <ScheduledCall<Test>>::new(call).unwrap(),472 ));473 let call = RuntimeCall::Logger(LoggerCall::log {474 i: 42,475 weight: call_weight + Weight::from_ref_time(2),476 });477 // Anon Periodic478 assert_ok!(Scheduler::do_schedule(479 DispatchTime::At(2),480 Some((1000, 3)),481 128,482 root(),483 <ScheduledCall<Test>>::new(call).unwrap(),484 ));485 let call = RuntimeCall::Logger(LoggerCall::log {486 i: 69,487 weight: call_weight + Weight::from_ref_time(3),488 });489 // Anon490 assert_ok!(Scheduler::do_schedule(491 DispatchTime::At(2),492 None,493 127,494 root(),495 <ScheduledCall<Test>>::new(call).unwrap(),496 ));497 // Named Periodic498 let call = RuntimeCall::Logger(LoggerCall::log {499 i: 2600,500 weight: call_weight + Weight::from_ref_time(4),501 });502 assert_ok!(Scheduler::do_schedule_named(503 [2u8; 32],504 DispatchTime::At(1),505 Some((1000, 3)),506 126,507 root(),508 <ScheduledCall<Test>>::new(call).unwrap(),509 ));510511 // Will include the named periodic only512 assert_eq!(513 Scheduler::on_initialize(1),514 TestWeightInfo::service_agendas_base()515 + TestWeightInfo::service_agenda_base(1)516 + <TestWeightInfo as MarginalWeightInfo>::service_task(None, true, true)517 + TestWeightInfo::execute_dispatch_unsigned()518 + call_weight + Weight::from_ref_time(4)519 );520 assert_eq!(IncompleteSince::<Test>::get(), None);521 assert_eq!(logger::log(), vec![(root(), 2600u32)]);522523 // Will include anon and anon periodic524 assert_eq!(525 Scheduler::on_initialize(2),526 TestWeightInfo::service_agendas_base()527 + TestWeightInfo::service_agenda_base(2)528 + <TestWeightInfo as MarginalWeightInfo>::service_task(None, false, true)529 + TestWeightInfo::execute_dispatch_unsigned()530 + call_weight + Weight::from_ref_time(3)531 + <TestWeightInfo as MarginalWeightInfo>::service_task(None, false, false)532 + TestWeightInfo::execute_dispatch_unsigned()533 + call_weight + Weight::from_ref_time(2)534 );535 assert_eq!(IncompleteSince::<Test>::get(), None);536 assert_eq!(537 logger::log(),538 vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]539 );540541 // Will include named only542 assert_eq!(543 Scheduler::on_initialize(3),544 TestWeightInfo::service_agendas_base()545 + TestWeightInfo::service_agenda_base(1)546 + <TestWeightInfo as MarginalWeightInfo>::service_task(None, true, false)547 + TestWeightInfo::execute_dispatch_unsigned()548 + call_weight + Weight::from_ref_time(1)549 );550 assert_eq!(IncompleteSince::<Test>::get(), None);551 assert_eq!(552 logger::log(),553 vec![554 (root(), 2600u32),555 (root(), 69u32),556 (root(), 42u32),557 (root(), 3u32)558 ]559 );560561 // Will contain none562 let actual_weight = Scheduler::on_initialize(4);563 assert_eq!(564 actual_weight,565 TestWeightInfo::service_agendas_base() + TestWeightInfo::service_agenda_base(0)566 );567 });568}569570#[test]571fn root_calls_works() {572 new_test_ext().execute_with(|| {573 let call = Box::new(RuntimeCall::Logger(LoggerCall::log {574 i: 69,575 weight: Weight::from_ref_time(10),576 }));577 let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {578 i: 42,579 weight: Weight::from_ref_time(10),580 }));581 assert_ok!(Scheduler::schedule_named(582 RuntimeOrigin::root(),583 [1u8; 32],584 4,585 None,586 Some(127),587 call,588 ));589 assert_ok!(Scheduler::schedule(590 RuntimeOrigin::root(),591 4,592 None,593 Some(127),594 call2595 ));596 run_to_block(3);597 // Scheduled calls are in the agenda.598 assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);599 assert!(logger::log().is_empty());600 assert_ok!(Scheduler::cancel_named(RuntimeOrigin::root(), [1u8; 32]));601 assert_ok!(Scheduler::cancel(RuntimeOrigin::root(), 4, 1));602 // Scheduled calls are made NONE, so should not effect state603 run_to_block(100);604 assert!(logger::log().is_empty());605 });606}607608#[test]609fn fails_to_schedule_task_in_the_past() {610 new_test_ext().execute_with(|| {611 run_to_block(3);612613 let call1 = Box::new(RuntimeCall::Logger(LoggerCall::log {614 i: 69,615 weight: Weight::from_ref_time(10),616 }));617 let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {618 i: 42,619 weight: Weight::from_ref_time(10),620 }));621 let call3 = Box::new(RuntimeCall::Logger(LoggerCall::log {622 i: 42,623 weight: Weight::from_ref_time(10),624 }));625626 assert_noop!(627 Scheduler::schedule_named(RuntimeOrigin::root(), [1u8; 32], 2, None, Some(127), call1),628 Error::<Test>::TargetBlockNumberInPast,629 );630631 assert_noop!(632 Scheduler::schedule(RuntimeOrigin::root(), 2, None, Some(127), call2),633 Error::<Test>::TargetBlockNumberInPast,634 );635636 assert_noop!(637 Scheduler::schedule(RuntimeOrigin::root(), 3, None, Some(127), call3),638 Error::<Test>::TargetBlockNumberInPast,639 );640 });641}642643#[test]644fn should_use_origin() {645 new_test_ext().execute_with(|| {646 let call = Box::new(RuntimeCall::Logger(LoggerCall::log {647 i: 69,648 weight: Weight::from_ref_time(10),649 }));650 let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {651 i: 42,652 weight: Weight::from_ref_time(10),653 }));654 assert_ok!(Scheduler::schedule_named(655 system::RawOrigin::Signed(1).into(),656 [1u8; 32],657 4,658 None,659 None,660 call,661 ));662 assert_ok!(Scheduler::schedule(663 system::RawOrigin::Signed(1).into(),664 4,665 None,666 None,667 call2,668 ));669 run_to_block(3);670 // Scheduled calls are in the agenda.671 assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);672 assert!(logger::log().is_empty());673 assert_ok!(Scheduler::cancel_named(674 system::RawOrigin::Signed(1).into(),675 [1u8; 32]676 ));677 assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));678 // Scheduled calls are made NONE, so should not effect state679 run_to_block(100);680 assert!(logger::log().is_empty());681 });682}683684#[test]685fn should_check_origin() {686 new_test_ext().execute_with(|| {687 let call = Box::new(RuntimeCall::Logger(LoggerCall::log {688 i: 69,689 weight: Weight::from_ref_time(10),690 }));691 let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {692 i: 42,693 weight: Weight::from_ref_time(10),694 }));695 assert_noop!(696 Scheduler::schedule_named(697 system::RawOrigin::Signed(2).into(),698 [1u8; 32],699 4,700 None,701 None,702 call703 ),704 BadOrigin705 );706 assert_noop!(707 Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, None, call2),708 BadOrigin709 );710 });711}712713#[test]714fn should_check_origin_for_cancel() {715 new_test_ext().execute_with(|| {716 let call = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {717 i: 69,718 weight: Weight::from_ref_time(10),719 }));720 let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {721 i: 42,722 weight: Weight::from_ref_time(10),723 }));724 assert_ok!(Scheduler::schedule_named(725 system::RawOrigin::Signed(1).into(),726 [1u8; 32],727 4,728 None,729 None,730 call,731 ));732 assert_ok!(Scheduler::schedule(733 system::RawOrigin::Signed(1).into(),734 4,735 None,736 None,737 call2,738 ));739 run_to_block(3);740 // Scheduled calls are in the agenda.741 assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);742 assert!(logger::log().is_empty());743 assert_noop!(744 Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), [1u8; 32]),745 BadOrigin746 );747 assert_noop!(748 Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1),749 BadOrigin750 );751 assert_noop!(752 Scheduler::cancel_named(system::RawOrigin::Root.into(), [1u8; 32]),753 BadOrigin754 );755 assert_noop!(756 Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1),757 BadOrigin758 );759 run_to_block(5);760 assert_eq!(761 logger::log(),762 vec![763 (system::RawOrigin::Signed(1).into(), 69u32),764 (system::RawOrigin::Signed(1).into(), 42u32)765 ]766 );767 });768}769770/// Cancelling a call and then scheduling a second call for the same771/// block results in different addresses.772#[test]773fn schedule_does_not_resuse_addr() {774 new_test_ext().execute_with(|| {775 let call = RuntimeCall::Logger(LoggerCall::log {776 i: 42,777 weight: Weight::from_ref_time(10),778 });779780 // Schedule both calls.781 let addr_1 = Scheduler::do_schedule(782 DispatchTime::At(4),783 None,784 127,785 root(),786 <ScheduledCall<Test>>::new(call.clone()).unwrap(),787 )788 .unwrap();789 // Cancel the call.790 assert_ok!(Scheduler::do_cancel(None, addr_1));791 let addr_2 = Scheduler::do_schedule(792 DispatchTime::At(4),793 None,794 127,795 root(),796 <ScheduledCall<Test>>::new(call).unwrap(),797 )798 .unwrap();799800 // Should not re-use the address.801 assert!(addr_1 != addr_2);802 });803}804805#[test]806fn schedule_agenda_overflows() {807 let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();808809 new_test_ext().execute_with(|| {810 let call = RuntimeCall::Logger(LoggerCall::log {811 i: 42,812 weight: Weight::from_ref_time(10),813 });814 let call = <ScheduledCall<Test>>::new(call).unwrap();815816 // Schedule the maximal number allowed per block.817 for _ in 0..max {818 Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone()).unwrap();819 }820821 // One more time and it errors.822 assert_noop!(823 Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call,),824 <Error<Test>>::AgendaIsExhausted,825 );826827 run_to_block(4);828 // All scheduled calls are executed.829 assert_eq!(logger::log().len() as u32, max);830 });831}832833/// Cancelling and scheduling does not overflow the agenda but fills holes.834#[test]835fn cancel_and_schedule_fills_holes() {836 let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();837 assert!(838 max > 3,839 "This test only makes sense for MaxScheduledPerBlock > 3"840 );841842 new_test_ext().execute_with(|| {843 let call = RuntimeCall::Logger(LoggerCall::log {844 i: 42,845 weight: Weight::from_ref_time(10),846 });847 let call = <ScheduledCall<Test>>::new(call).unwrap();848 let mut addrs = Vec::<_>::default();849850 // Schedule the maximal number allowed per block.851 for _ in 0..max {852 addrs.push(853 Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())854 .unwrap(),855 );856 }857 // Cancel three of them.858 for addr in addrs.into_iter().take(3) {859 Scheduler::do_cancel(None, addr).unwrap();860 }861 // Schedule three new ones.862 for i in 0..3 {863 let (_block, index) =864 Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())865 .unwrap();866 assert_eq!(i, index);867 }868869 run_to_block(4);870 // Maximum number of calls are executed.871 assert_eq!(logger::log().len() as u32, max);872 });873}