Skip to content
Snippets Groups Projects
Commit 71da6e96 authored by emostov's avatar emostov Committed by GitHub
Browse files

Add tests to Sudo Pallet (#5963)


* transition treasury to configurable moduleids

* make election module id configurable

* convert runtime and pallet to accept module id config elections-phragmen

* add ModuleId to evm pallet

* change society pallet to configurable module id

* delete commented out module_id

* fix merge residual compile errors

* setup initial mock structure

* establish privelleged function test

* save progress

* first pass new_test_ext

* test sudo to make sure it error when non-root

* add set keys tests

* fix unused result from set_key call

* remove unused imports warnings

* pre master merge

* Expose BlockHashCount on system metadata constants (#5960)

* squash

* fix whitespace

* spelling and whitespace

* a single pesky space

* add logger module to mock

* add logger dispatch to privlleged function

* sub logger in for dummy functions

* create first of several event tests

* first pass at test coverage for events

* comment house keeping

* spell check

* Expose BlockHashCount on system metadata constants (#5960)

* establish privelleged function test

* save progress

* first pass new_test_ext

* test sudo to make sure it error when non-root

* add set keys tests

* fix unused result from set_key call

* remove unused imports warnings

* pre master merge

* squash

* fix whitespace

* spelling and whitespace

* a single pesky space

* add logger module to mock

* add logger dispatch to privlleged function

* sub logger in for dummy functions

* create first of several event tests

* first pass at test coverage for events

* comment house keeping

* implement last_seen_account storage item, event, and, logger function

* create vec account log and use in tests

* allow weight to be passed into account log

* refactor all log dispatchables

* save progress

* complete initial transition to refactored logger

* cleaning

* fix merge residual compile errors

setup initial mock structure

establish privelleged function test

save progress

first pass new_test_ext

test sudo to make sure it error when non-root

add set keys tests

fix unused result from set_key call

parent 5151bd784545ededa6153052a93fcc309f7b3885
author zeke <emostov@middlebury.edu> 1589076740 -0700
committer zeke <emostov@middlebury.edu> 1589350443 -0700

parent 5151bd784545ededa6153052a93fcc309f7b3885
author zeke <emostov@middlebury.edu> 1589076740 -0700
committer zeke <emostov@middlebury.edu> 1589350442 -0700

remove unused imports warnings

fix unused result from set_key call

remove unused imports warnings

pre master merge

Expose BlockHashCount on system metadata constants (#5960)

squash

fix whitespace

spelling and whitespace

a single pesky space

add logger module to mock

add logger dispatch to privlleged function

sub logger in for dummy functions

create first of several event tests

first pass at test coverage for events

comment house keeping

pre master merge

Expose BlockHashCount on system metadata constants (#5960)

Expose BlockHashCount on system metadata constants (#5960)

fix whitespace

spell check

implement last_seen_account storage item, event, and, logger function

create vec account log and use in tests

allow weight to be passed into account log

refactor all log dispatchables

save progress

complete initial transition to refactored logger

cleaning

* clean up

* cleaning

* condense non_privileged logs into 1 fn

* Apply suggestions from code review

Co-authored-by: default avatarJaco Greeff <jacogr@gmail.com>
Co-authored-by: default avatarBastian Köcher <bkchr@users.noreply.github.com>
parent 91d93be9
No related merge requests found
......@@ -95,6 +95,11 @@ use frame_support::{
use frame_support::weights::{Weight, GetDispatchInfo, FunctionOf, Pays};
use frame_system::{self as system, ensure_signed};
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub trait Trait: frame_system::Trait {
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;
......
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Test utilities
use super::*;
use frame_support::{
impl_outer_origin, impl_outer_dispatch, impl_outer_event, parameter_types,
weights::{Weight, DispatchClass}
};
use sp_core::H256;
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys.
use sp_runtime::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
use sp_io;
use crate as sudo;
// Logger module to track execution.
pub mod logger {
use super::*;
use frame_system::ensure_root;
pub trait Trait: system::Trait {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
}
decl_storage! {
trait Store for Module<T: Trait> as Logger {
AccountLog get(fn account_log): Vec<T::AccountId>;
I32Log get(fn i32_log): Vec<i32>;
}
}
decl_event! {
pub enum Event<T> where AccountId = <T as frame_system::Trait>::AccountId {
AppendI32(i32, Weight),
AppendI32AndAccount(AccountId, i32, Weight),
}
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: <T as system::Trait>::Origin {
fn deposit_event() = default;
#[weight = FunctionOf(
|args: (&i32, &Weight)| *args.1,
DispatchClass::Normal,
Pays::Yes,
)]
fn privileged_i32_log(origin, i: i32, weight: Weight){
// Ensure that the `origin` is `Root`.
ensure_root(origin)?;
<I32Log>::append(i);
Self::deposit_event(RawEvent::AppendI32(i, weight));
}
#[weight = FunctionOf(
|args: (&i32, &Weight)| *args.1,
DispatchClass::Normal,
Pays::Yes,
)]
fn non_privileged_log(origin, i: i32, weight: Weight){
// Ensure that the `origin` is some signed account.
let sender = ensure_signed(origin)?;
<I32Log>::append(i);
<AccountLog<T>>::append(sender.clone());
Self::deposit_event(RawEvent::AppendI32AndAccount(sender, i, weight));
}
}
}
}
impl_outer_origin! {
pub enum Origin for Test where system = frame_system {}
}
mod test_events {
pub use crate::Event;
}
impl_outer_event! {
pub enum TestEvent for Test {
system<T>,
sudo<T>,
logger<T>,
}
}
impl_outer_dispatch! {
pub enum Call for Test where origin: Origin {
sudo::Sudo,
logger::Logger,
}
}
// 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! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl frame_system::Trait for Test {
type Origin = Origin;
type Call = Call;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = TestEvent;
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type DbWeight = ();
type BlockExecutionWeight = ();
type ExtrinsicBaseWeight = ();
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
type ModuleToIndex = ();
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
}
// Implement the logger module's `Trait` on the Test runtime.
impl logger::Trait for Test {
type Event = TestEvent;
}
// Implement the sudo module's `Trait` on the Test runtime.
impl Trait for Test {
type Event = TestEvent;
type Call = Call;
}
// Assign back to type variables in order to make dispatched calls of these modules later.
pub type Sudo = Module<Test>;
pub type Logger = logger::Module<Test>;
pub type System = system::Module<Test>;
// New types for dispatchable functions.
pub type SudoCall = sudo::Call<Test>;
pub type LoggerCall = logger::Call<Test>;
// Build test environment by setting the root `key` for the Genesis.
pub fn new_test_ext(root_key: u64) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
GenesisConfig::<Test>{
key: root_key,
}.assimilate_storage(&mut t).unwrap();
t.into()
}
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Tests for the module.
use super::*;
use mock::{
Sudo, SudoCall, Origin, Call, Test, new_test_ext, LoggerCall, Logger, System, TestEvent,
};
use frame_support::{assert_ok, assert_noop};
#[test]
fn test_setup_works() {
// Environment setup, logger storage, and sudo `key` retrieval should work as expected.
new_test_ext(1).execute_with(|| {
assert_eq!(Sudo::key(), 1u64);
assert_eq!(Logger::i32_log(), vec![]);
assert_eq!(Logger::account_log(), vec![]);
});
}
#[test]
fn sudo_basics() {
// Configure a default test environment and set the root `key` to 1.
new_test_ext(1).execute_with(|| {
// A privileged function should work when `sudo` is passed the root `key` as `origin`.
let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log(42, 1_000)));
assert_ok!(Sudo::sudo(Origin::signed(1), call));
assert_eq!(Logger::i32_log(), vec![42i32]);
// A privileged function should not work when `sudo` is passed a non-root `key` as `origin`.
let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log(42, 1_000)));
assert_noop!(Sudo::sudo(Origin::signed(2), call), Error::<Test>::RequireSudo);
});
}
#[test]
fn sudo_emits_events_correctly() {
new_test_ext(1).execute_with(|| {
// Set block number to 1 because events are not emitted on block 0.
System::set_block_number(1);
// Should emit event to indicate success when called with the root `key` and `call` is `Ok`.
let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log(42, 1)));
assert_ok!(Sudo::sudo(Origin::signed(1), call));
let expected_event = TestEvent::sudo(RawEvent::Sudid(Ok(())));
assert!(System::events().iter().any(|a| a.event == expected_event));
})
}
#[test]
fn sudo_unchecked_weight_basics() {
new_test_ext(1).execute_with(|| {
// A privileged function should work when `sudo` is passed the root `key` as origin.
let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log(42, 1_000)));
assert_ok!(Sudo::sudo_unchecked_weight(Origin::signed(1), call, 1_000));
assert_eq!(Logger::i32_log(), vec![42i32]);
// A privileged function should not work when called with a non-root `key`.
let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log(42, 1_000)));
assert_noop!(
Sudo::sudo_unchecked_weight(Origin::signed(2), call, 1_000),
Error::<Test>::RequireSudo,
);
// `I32Log` is unchanged after unsuccessful call.
assert_eq!(Logger::i32_log(), vec![42i32]);
// Controls the dispatched weight.
let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log(42, 1)));
let sudo_unchecked_weight_call = SudoCall::sudo_unchecked_weight(call, 1_000);
let info = sudo_unchecked_weight_call.get_dispatch_info();
assert_eq!(info.weight, 1_000);
});
}
#[test]
fn sudo_unchecked_weight_emits_events_correctly() {
new_test_ext(1).execute_with(|| {
// Set block number to 1 because events are not emitted on block 0.
System::set_block_number(1);
// Should emit event to indicate success when called with the root `key` and `call` is `Ok`.
let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log(42, 1)));
assert_ok!(Sudo::sudo_unchecked_weight(Origin::signed(1), call, 1_000));
let expected_event = TestEvent::sudo(RawEvent::Sudid(Ok(())));
assert!(System::events().iter().any(|a| a.event == expected_event));
})
}
#[test]
fn set_key_basics() {
new_test_ext(1).execute_with(|| {
// A root `key` can change the root `key`
assert_ok!(Sudo::set_key(Origin::signed(1), 2));
assert_eq!(Sudo::key(), 2u64);
});
new_test_ext(1).execute_with(|| {
// A non-root `key` will trigger a `RequireSudo` error and a non-root `key` cannot change the root `key`.
assert_noop!(Sudo::set_key(Origin::signed(2), 3), Error::<Test>::RequireSudo);
});
}
#[test]
fn set_key_emits_events_correctly() {
new_test_ext(1).execute_with(|| {
// Set block number to 1 because events are not emitted on block 0.
System::set_block_number(1);
// A root `key` can change the root `key`.
assert_ok!(Sudo::set_key(Origin::signed(1), 2));
let expected_event = TestEvent::sudo(RawEvent::KeyChanged(1));
assert!(System::events().iter().any(|a| a.event == expected_event));
// Double check.
assert_ok!(Sudo::set_key(Origin::signed(2), 4));
let expected_event = TestEvent::sudo(RawEvent::KeyChanged(2));
assert!(System::events().iter().any(|a| a.event == expected_event));
});
}
#[test]
fn sudo_as_basics() {
new_test_ext(1).execute_with(|| {
// A privileged function will not work when passed to `sudo_as`.
let call = Box::new(Call::Logger(LoggerCall::privileged_i32_log(42, 1_000)));
assert_ok!(Sudo::sudo_as(Origin::signed(1), 2, call));
assert_eq!(Logger::i32_log(), vec![]);
assert_eq!(Logger::account_log(), vec![]);
// A non-privileged function should not work when called with a non-root `key`.
let call = Box::new(Call::Logger(LoggerCall::non_privileged_log(42, 1)));
assert_noop!(Sudo::sudo_as(Origin::signed(3), 2, call), Error::<Test>::RequireSudo);
// A non-privileged function will work when passed to `sudo_as` with the root `key`.
let call = Box::new(Call::Logger(LoggerCall::non_privileged_log(42, 1)));
assert_ok!(Sudo::sudo_as(Origin::signed(1), 2, call));
assert_eq!(Logger::i32_log(), vec![42i32]);
// The correct user makes the call within `sudo_as`.
assert_eq!(Logger::account_log(), vec![2]);
});
}
#[test]
fn sudo_as_emits_events_correctly() {
new_test_ext(1).execute_with(|| {
// Set block number to 1 because events are not emitted on block 0.
System::set_block_number(1);
// A non-privileged function will work when passed to `sudo_as` with the root `key`.
let call = Box::new(Call::Logger(LoggerCall::non_privileged_log(42, 1)));
assert_ok!(Sudo::sudo_as(Origin::signed(1), 2, call));
let expected_event = TestEvent::sudo(RawEvent::SudoAsDone(true));
assert!(System::events().iter().any(|a| a.event == expected_event));
});
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment