Add execute_with to TestExternalities (#3793)

This function executes the given closure in a context where the test
externalities are set. This makes the srml tests easier to write, as the
test externalities need to be created anyway.
This commit is contained in:
Bastian Köcher
2019-10-10 15:01:30 +02:00
committed by GitHub
parent 34c7338211
commit 4dbc9265ee
44 changed files with 2369 additions and 2645 deletions
-1
View File
@@ -3841,7 +3841,6 @@ dependencies = [
"sr-io 2.0.0",
"sr-std 2.0.0",
"substrate-application-crypto 2.0.0",
"substrate-externalities 2.0.0",
"substrate-offchain 2.0.0",
"substrate-primitives 2.0.0",
]
-2
View File
@@ -16,7 +16,6 @@ runtime_io = { package = "sr-io", path = "../sr-io", default-features = false }
log = { version = "0.4.8", optional = true }
paste = "0.1.6"
rand = { version = "0.7.2", optional = true }
externalities = { package = "substrate-externalities", path = "../externalities", optional = true }
impl-trait-for-tuples = "0.1.2"
[dev-dependencies]
@@ -38,5 +37,4 @@ std = [
"primitives/std",
"app-crypto/std",
"rand",
"externalities",
]
-3
View File
@@ -73,9 +73,6 @@ pub use sr_arithmetic::helpers_128bit;
/// Re-export big_uint stiff.
pub use sr_arithmetic::biguint;
#[cfg(feature = "std")]
pub use externalities::set_and_run_with_externalities;
/// An abstraction over justification for a block's validity under a consensus algorithm.
///
/// Essentially a finality proof. The exact formulation will vary between consensus
@@ -512,7 +512,6 @@ impl<'a> HeadersIterator<'a> {
#[cfg(test)]
mod tests {
use super::*;
use crate::set_and_run_with_externalities;
use runtime_io::TestExternalities;
use substrate_offchain::testing;
use primitives::offchain::OffchainExt;
@@ -523,7 +522,7 @@ mod tests {
let mut t = TestExternalities::default();
t.register_extension(OffchainExt::new(offchain));
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
let request: Request = Request::get("http://localhost:1234");
let pending = request
.add_header("X-Auth", "hunter2")
@@ -564,7 +563,7 @@ mod tests {
let mut t = TestExternalities::default();
t.register_extension(OffchainExt::new(offchain));
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
let pending = Request::default()
.method(Method::Post)
.url("http://localhost:1234")
@@ -113,6 +113,13 @@ impl<H: Hasher<Out=H256>, N: ChangesTrieBlockNumber> TestExternalities<H, N> {
self.backend.update(top.chain(children).collect())
}
/// Execute the given closure while `self` is set as externalities.
///
/// Returns the result of the given closure.
pub fn execute_with<R>(&mut self, execute: impl FnOnce() -> R) -> R {
externalities::set_and_run_with_externalities(self, execute)
}
}
impl<H: Hasher<Out=H256>, N: ChangesTrieBlockNumber> std::fmt::Debug for TestExternalities<H, N> {
+8 -17
View File
@@ -321,7 +321,6 @@ mod tests {
use runtime_io::TestExternalities;
use substrate_test_runtime_client::{AccountKeyring, Sr25519Keyring};
use sr_primitives::set_and_run_with_externalities;
use crate::{Header, Transfer, WASM_BINARY};
use primitives::{NeverNativeValue, map, traits::CodeExecutor};
use substrate_executor::{NativeExecutor, WasmExecutionMethod, native_executor_instance};
@@ -371,18 +370,14 @@ mod tests {
extrinsics: vec![],
};
set_and_run_with_externalities(&mut new_test_ext(), || polish_block(&mut b));
new_test_ext().execute_with(|| polish_block(&mut b));
block_executor(b, &mut new_test_ext());
}
#[test]
fn block_import_works_native() {
block_import_works(|b, ext| {
set_and_run_with_externalities(ext, || {
execute_block(b);
});
});
block_import_works(|b, ext| ext.execute_with(|| execute_block(b)));
}
#[test]
@@ -420,7 +415,7 @@ mod tests {
};
let mut dummy_ext = new_test_ext();
set_and_run_with_externalities(&mut dummy_ext, || polish_block(&mut b1));
dummy_ext.execute_with(|| polish_block(&mut b1));
let mut b2 = Block {
header: Header {
@@ -446,26 +441,26 @@ mod tests {
],
};
set_and_run_with_externalities(&mut dummy_ext, || polish_block(&mut b2));
dummy_ext.execute_with(|| polish_block(&mut b2));
drop(dummy_ext);
let mut t = new_test_ext();
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(balance_of(AccountKeyring::Alice.into()), 111);
assert_eq!(balance_of(AccountKeyring::Bob.into()), 0);
});
block_executor(b1, &mut t);
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(balance_of(AccountKeyring::Alice.into()), 42);
assert_eq!(balance_of(AccountKeyring::Bob.into()), 69);
});
block_executor(b2, &mut t);
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(balance_of(AccountKeyring::Alice.into()), 0);
assert_eq!(balance_of(AccountKeyring::Bob.into()), 42);
assert_eq!(balance_of(AccountKeyring::Charlie.into()), 69);
@@ -474,11 +469,7 @@ mod tests {
#[test]
fn block_import_with_transaction_works_native() {
block_import_with_transaction_works(|b, ext| {
set_and_run_with_externalities(ext, || {
execute_block(b);
});
});
block_import_with_transaction_works(|b, ext| ext.execute_with(|| execute_block(b)));
}
#[test]
@@ -72,8 +72,7 @@ mod tests {
use primitives::H256;
use support::{impl_outer_origin, assert_ok, parameter_types};
use sr_primitives::{
set_and_run_with_externalities, traits::{BlakeTwo256, IdentityLookup}, testing::Header,
weights::Weight, Perbill,
traits::{BlakeTwo256, IdentityLookup}, testing::Header, weights::Weight, Perbill,
};
impl_outer_origin! {
@@ -122,7 +121,7 @@ mod tests {
#[test]
fn it_works_for_default_value() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// Just a dummy test for the dummy funtion `do_something`
// calling the `do_something` function with a value 42
assert_ok!(TemplateModule::do_something(Origin::signed(1), 42));
+12 -12
View File
@@ -226,7 +226,7 @@ mod tests {
).0;
assert!(r.is_ok());
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - transfer_fee(&xt()));
assert_eq!(Balances::total_balance(&bob()), 69 * DOLLARS);
});
@@ -262,7 +262,7 @@ mod tests {
).0;
assert!(r.is_ok());
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - transfer_fee(&xt()));
assert_eq!(Balances::total_balance(&bob()), 69 * DOLLARS);
});
@@ -433,7 +433,7 @@ mod tests {
None,
).0.unwrap();
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - transfer_fee(&xt()));
assert_eq!(Balances::total_balance(&bob()), 169 * DOLLARS);
let events = vec![
@@ -468,7 +468,7 @@ mod tests {
None,
).0.unwrap();
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
// NOTE: fees differ slightly in tests that execute more than one block due to the
// weight update. Hence, using `assert_eq_error_rate`.
assert_eq_error_rate!(
@@ -540,7 +540,7 @@ mod tests {
None,
).0.unwrap();
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - transfer_fee(&xt()));
assert_eq!(Balances::total_balance(&bob()), 169 * DOLLARS);
});
@@ -553,7 +553,7 @@ mod tests {
None,
).0.unwrap();
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq_error_rate!(
Balances::total_balance(&alice()),
32 * DOLLARS - 2 * transfer_fee(&xt()),
@@ -715,7 +715,7 @@ mod tests {
None,
).0.unwrap();
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
// Verify that the contract constructor worked well and code of TRANSFER contract is actually deployed.
assert_eq!(
&contracts::ContractInfoOf::<Runtime>::get(addr)
@@ -836,7 +836,7 @@ mod tests {
.expect("Extrinsic could be applied")
.expect("Extrinsic did not fail");
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - 1 * transfer_fee(&xt()));
assert_eq!(Balances::total_balance(&bob()), 69 * DOLLARS);
});
@@ -895,7 +895,7 @@ mod tests {
let mut prev_multiplier = WeightMultiplier::default();
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(System::next_weight_multiplier(), prev_multiplier);
});
@@ -947,7 +947,7 @@ mod tests {
).0.unwrap();
// weight multiplier is increased for next block.
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
let fm = System::next_weight_multiplier();
println!("After a big block: {:?} -> {:?}", prev_multiplier, fm);
assert!(fm > prev_multiplier);
@@ -964,7 +964,7 @@ mod tests {
).0.unwrap();
// weight multiplier is increased for next block.
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
let fm = System::next_weight_multiplier();
println!("After a small block: {:?} -> {:?}", prev_multiplier, fm);
assert!(fm < prev_multiplier);
@@ -1018,7 +1018,7 @@ mod tests {
).0;
assert!(r.is_ok());
sr_primitives::set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(Balances::total_balance(&bob()), (10 + 69) * DOLLARS);
// Components deducted from alice's balances:
// - Weight fee
+9 -12
View File
@@ -244,10 +244,7 @@ mod tests {
use primitives::H256;
// 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.
use sr_primitives::{
Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header,
set_and_run_with_externalities,
};
use sr_primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
impl_outer_origin! {
pub enum Origin for Test {}
@@ -297,7 +294,7 @@ mod tests {
#[test]
fn issuing_asset_units_to_issuer_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_ok!(Assets::issue(Origin::signed(1), 100));
assert_eq!(Assets::balance(0, 1), 100);
});
@@ -305,7 +302,7 @@ mod tests {
#[test]
fn querying_total_supply_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_ok!(Assets::issue(Origin::signed(1), 100));
assert_eq!(Assets::balance(0, 1), 100);
assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50));
@@ -322,7 +319,7 @@ mod tests {
#[test]
fn transferring_amount_above_available_balance_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_ok!(Assets::issue(Origin::signed(1), 100));
assert_eq!(Assets::balance(0, 1), 100);
assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50));
@@ -333,7 +330,7 @@ mod tests {
#[test]
fn transferring_amount_less_than_available_balance_should_not_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_ok!(Assets::issue(Origin::signed(1), 100));
assert_eq!(Assets::balance(0, 1), 100);
assert_ok!(Assets::transfer(Origin::signed(1), 0, 2, 50));
@@ -347,7 +344,7 @@ mod tests {
#[test]
fn transferring_less_than_one_unit_should_not_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_ok!(Assets::issue(Origin::signed(1), 100));
assert_eq!(Assets::balance(0, 1), 100);
assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 0), "transfer amount should be non-zero");
@@ -356,7 +353,7 @@ mod tests {
#[test]
fn transferring_more_units_than_total_supply_should_not_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_ok!(Assets::issue(Origin::signed(1), 100));
assert_eq!(Assets::balance(0, 1), 100);
assert_noop!(Assets::transfer(Origin::signed(1), 0, 2, 101), "origin account balance must be greater than or equal to the transfer amount");
@@ -365,7 +362,7 @@ mod tests {
#[test]
fn destroying_asset_balance_with_positive_balance_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_ok!(Assets::issue(Origin::signed(1), 100));
assert_eq!(Assets::balance(0, 1), 100);
assert_ok!(Assets::destroy(Origin::signed(1), 0));
@@ -374,7 +371,7 @@ mod tests {
#[test]
fn destroying_asset_balance_with_zero_balance_should_not_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_ok!(Assets::issue(Origin::signed(1), 100));
assert_eq!(Assets::balance(0, 2), 0);
assert_noop!(Assets::destroy(Origin::signed(2), 0), "origin balance should be non-zero");
+1 -2
View File
@@ -18,12 +18,11 @@
#![cfg(test)]
use sr_primitives::set_and_run_with_externalities;
use crate::mock::{Aura, new_test_ext};
#[test]
fn initial_values() {
set_and_run_with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || {
new_test_ext(vec![0, 1, 2, 3]).execute_with(|| {
assert_eq!(Aura::last(), 0u64);
assert_eq!(Aura::authorities().len(), 4);
});
@@ -139,7 +139,7 @@ mod tests {
use runtime_io::TestExternalities;
use sr_primitives::{
testing::{Header, UintAuthorityId}, traits::{ConvertInto, IdentityLookup, OpaqueKeys},
Perbill, set_and_run_with_externalities,
Perbill,
};
use support::{impl_outer_origin, parameter_types};
@@ -263,7 +263,7 @@ mod tests {
let mut externalities = TestExternalities::new(t);
externalities.register_extension(KeystoreExt(key_store));
set_and_run_with_externalities(&mut externalities, || {
externalities.execute_with(|| {
assert_eq!(
authority_id,
AuthorityDiscovery::authority_id().expect("Retrieving public key.")
@@ -300,7 +300,7 @@ mod tests {
let mut externalities = TestExternalities::new(t);
externalities.register_extension(KeystoreExt(key_store));
set_and_run_with_externalities(&mut externalities, || {
externalities.execute_with(|| {
assert_eq!(None, AuthorityDiscovery::authority_id());
});
}
@@ -337,7 +337,7 @@ mod tests {
let mut externalities = TestExternalities::new(t);
externalities.register_extension(KeystoreExt(key_store));
set_and_run_with_externalities(&mut externalities, || {
externalities.execute_with(|| {
let payload = String::from("test payload").into_bytes();
let (sig, authority_id) = AuthorityDiscovery::sign(&payload).expect("signature");
+4 -5
View File
@@ -414,8 +414,7 @@ mod tests {
use super::*;
use primitives::H256;
use sr_primitives::{
set_and_run_with_externalities, traits::{BlakeTwo256, IdentityLookup}, testing::Header,
generic::DigestItem, Perbill,
traits::{BlakeTwo256, IdentityLookup}, testing::Header, generic::DigestItem, Perbill,
};
use support::{parameter_types, impl_outer_origin, ConsensusEngineId};
@@ -542,7 +541,7 @@ mod tests {
#[test]
fn prune_old_uncles_works() {
use UncleEntryItem::*;
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let hash = Default::default();
let author = Default::default();
let uncles = vec![
@@ -561,7 +560,7 @@ mod tests {
#[test]
fn rejects_bad_uncles() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let author_a = 69;
struct CanonChain {
@@ -674,7 +673,7 @@ mod tests {
#[test]
fn sets_author_lazily() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let author = 42;
let mut header = seal_header(
create_header(1, Default::default(), [1; 32].into()),
+5 -7
View File
@@ -18,9 +18,7 @@
use super::*;
use mock::{new_test_ext, Babe, Test};
use sr_primitives::{
set_and_run_with_externalities, traits::OnFinalize, testing::{Digest, DigestItem},
};
use sr_primitives::{traits::OnFinalize, testing::{Digest, DigestItem}};
use session::ShouldEndSession;
const EMPTY_RANDOMNESS: [u8; 32] = [
@@ -54,14 +52,14 @@ fn empty_randomness_is_correct() {
#[test]
fn initial_values() {
set_and_run_with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || {
new_test_ext(vec![0, 1, 2, 3]).execute_with(|| {
assert_eq!(Babe::authorities().len(), 4)
})
}
#[test]
fn check_module() {
set_and_run_with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || {
new_test_ext(vec![0, 1, 2, 3]).execute_with(|| {
assert!(!Babe::should_end_session(0), "Genesis does not change sessions");
assert!(!Babe::should_end_session(200000),
"BABE does not include the block number in epoch calculations");
@@ -72,7 +70,7 @@ type System = system::Module<Test>;
#[test]
fn first_block_epoch_zero_start() {
set_and_run_with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || {
new_test_ext(vec![0, 1, 2, 3]).execute_with(|| {
let genesis_slot = 100;
let first_vrf = [1; 32];
let pre_digest = make_pre_digest(
@@ -120,7 +118,7 @@ fn first_block_epoch_zero_start() {
#[test]
fn authority_index() {
set_and_run_with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || {
new_test_ext(vec![0, 1, 2, 3]).execute_with(|| {
assert_eq!(
Babe::find_author((&[(BABE_ENGINE_ID, &[][..])]).into_iter().cloned()), None,
"Trivially invalid authorities are ignored")
+171 -201
View File
@@ -20,7 +20,6 @@
use super::*;
use mock::{Balances, ExtBuilder, Runtime, System, info_from_weight, CALL};
use sr_primitives::set_and_run_with_externalities;
use support::{
assert_noop, assert_ok, assert_err,
traits::{LockableCurrency, LockIdentifier, WithdrawReason, WithdrawReasons,
@@ -34,7 +33,7 @@ const ID_3: LockIdentifier = *b"3 ";
#[test]
fn basic_locking_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || {
ExtBuilder::default().existential_deposit(1).monied(true).build().execute_with(|| {
assert_eq!(Balances::free_balance(&1), 10);
Balances::set_lock(ID_1, &1, 9, u64::max_value(), WithdrawReasons::all());
assert_noop!(
@@ -46,7 +45,7 @@ fn basic_locking_should_work() {
#[test]
fn partial_locking_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || {
ExtBuilder::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all());
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1));
});
@@ -54,7 +53,7 @@ fn partial_locking_should_work() {
#[test]
fn lock_removal_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || {
ExtBuilder::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, u64::max_value(), u64::max_value(), WithdrawReasons::all());
Balances::remove_lock(ID_1, &1);
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1));
@@ -63,7 +62,7 @@ fn lock_removal_should_work() {
#[test]
fn lock_replacement_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || {
ExtBuilder::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, u64::max_value(), u64::max_value(), WithdrawReasons::all());
Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all());
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1));
@@ -72,7 +71,7 @@ fn lock_replacement_should_work() {
#[test]
fn double_locking_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || {
ExtBuilder::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all());
Balances::set_lock(ID_2, &1, 5, u64::max_value(), WithdrawReasons::all());
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1));
@@ -81,7 +80,7 @@ fn double_locking_should_work() {
#[test]
fn combination_locking_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || {
ExtBuilder::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, u64::max_value(), 0, WithdrawReasons::none());
Balances::set_lock(ID_2, &1, 0, u64::max_value(), WithdrawReasons::none());
Balances::set_lock(ID_3, &1, 0, 0, WithdrawReasons::all());
@@ -91,7 +90,7 @@ fn combination_locking_should_work() {
#[test]
fn lock_value_extension_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || {
ExtBuilder::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6),
@@ -112,12 +111,12 @@ fn lock_value_extension_should_work() {
#[test]
fn lock_reasons_should_work() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(1)
.monied(true).transaction_fees(0, 1, 0)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(1)
.monied(true)
.transaction_fees(0, 1, 0)
.build()
.execute_with(|| {
Balances::set_lock(ID_1, &1, 10, u64::max_value(), WithdrawReason::Transfer.into());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 1),
@@ -157,13 +156,12 @@ fn lock_reasons_should_work() {
info_from_weight(1),
0,
).is_err());
}
);
});
}
#[test]
fn lock_block_number_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || {
ExtBuilder::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 10, 2, WithdrawReasons::all());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 1),
@@ -177,7 +175,7 @@ fn lock_block_number_should_work() {
#[test]
fn lock_block_number_extension_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || {
ExtBuilder::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 10, 2, WithdrawReasons::all());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6),
@@ -199,7 +197,7 @@ fn lock_block_number_extension_should_work() {
#[test]
fn lock_reasons_extension_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().existential_deposit(1).monied(true).build(), || {
ExtBuilder::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 10, 10, WithdrawReason::Transfer.into());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6),
@@ -220,14 +218,12 @@ fn lock_reasons_extension_should_work() {
#[test]
fn default_indexing_on_new_accounts_should_not_work2() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(10)
.creation_fee(50)
.monied(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(10)
.creation_fee(50)
.monied(true)
.build()
.execute_with(|| {
assert_eq!(Balances::is_dead_account(&5), true); // account 5 should not exist
// ext_deposit is 10, value is 9, not satisfies for ext_deposit
assert_noop!(
@@ -236,18 +232,16 @@ fn default_indexing_on_new_accounts_should_not_work2() {
);
assert_eq!(Balances::is_dead_account(&5), true); // account 5 should not exist
assert_eq!(Balances::free_balance(&1), 100);
},
);
});
}
#[test]
fn reserved_balance_should_prevent_reclaim_count() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(256 * 1)
.monied(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(256 * 1)
.monied(true)
.build()
.execute_with(|| {
System::inc_account_nonce(&2);
assert_eq!(Balances::is_dead_account(&2), false);
assert_eq!(Balances::is_dead_account(&5), true);
@@ -274,14 +268,13 @@ fn reserved_balance_should_prevent_reclaim_count() {
assert_ok!(Balances::transfer(Some(4).into(), 6, 256 * 1 + 0x69));
assert_eq!(Balances::total_balance(&6), 256 * 1 + 0x69);
assert_eq!(Balances::is_dead_account(&6), false);
},
);
});
}
#[test]
fn reward_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
ExtBuilder::default().monied(true).build().execute_with(|| {
assert_eq!(Balances::total_balance(&1), 10);
assert_ok!(Balances::deposit_into_existing(&1, 10).map(drop));
assert_eq!(Balances::total_balance(&1), 20);
@@ -291,12 +284,11 @@ fn reward_should_work() {
#[test]
fn dust_account_removal_should_work() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(100)
.monied(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(100)
.monied(true)
.build()
.execute_with(|| {
System::inc_account_nonce(&2);
assert_eq!(System::account_nonce(&2), 1);
assert_eq!(Balances::total_balance(&2), 2000);
@@ -305,19 +297,17 @@ fn dust_account_removal_should_work() {
assert_eq!(Balances::total_balance(&2), 0);
assert_eq!(Balances::total_balance(&5), 1901);
assert_eq!(System::account_nonce(&2), 0);
},
);
});
}
#[test]
fn dust_account_removal_should_work2() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(100)
.creation_fee(50)
.monied(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(100)
.creation_fee(50)
.monied(true)
.build()
.execute_with(|| {
System::inc_account_nonce(&2);
assert_eq!(System::account_nonce(&2), 1);
assert_eq!(Balances::total_balance(&2), 2000);
@@ -326,13 +316,12 @@ fn dust_account_removal_should_work2() {
assert_eq!(Balances::total_balance(&2), 0);
assert_eq!(Balances::total_balance(&5), 1851);
assert_eq!(System::account_nonce(&2), 0);
},
);
});
}
#[test]
fn balance_works() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 42);
assert_eq!(Balances::free_balance(&1), 42);
assert_eq!(Balances::reserved_balance(&1), 0);
@@ -345,7 +334,7 @@ fn balance_works() {
#[test]
fn balance_transfer_works() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::transfer(Some(1).into(), 2, 69));
assert_eq!(Balances::total_balance(&1), 42);
@@ -355,7 +344,7 @@ fn balance_transfer_works() {
#[test]
fn force_transfer_works() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_noop!(
Balances::force_transfer(Some(2).into(), 1, 2, 69),
@@ -369,7 +358,7 @@ fn force_transfer_works() {
#[test]
fn reserving_balance_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_eq!(Balances::total_balance(&1), 111);
@@ -386,7 +375,7 @@ fn reserving_balance_should_work() {
#[test]
fn balance_transfer_when_reserved_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 69));
assert_noop!(
@@ -398,7 +387,7 @@ fn balance_transfer_when_reserved_should_not_work() {
#[test]
fn deducting_balance_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 69));
assert_eq!(Balances::free_balance(&1), 42);
@@ -407,7 +396,7 @@ fn deducting_balance_should_work() {
#[test]
fn refunding_balance_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 42);
Balances::set_reserved_balance(&1, 69);
Balances::unreserve(&1, 69);
@@ -418,7 +407,7 @@ fn refunding_balance_should_work() {
#[test]
fn slashing_balance_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 69));
assert!(Balances::slash(&1, 69).1.is_zero());
@@ -430,7 +419,7 @@ fn slashing_balance_should_work() {
#[test]
fn slashing_incomplete_balance_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 42);
assert_ok!(Balances::reserve(&1, 21));
assert_eq!(Balances::slash(&1, 69).1, 27);
@@ -442,7 +431,7 @@ fn slashing_incomplete_balance_should_work() {
#[test]
fn unreserving_balance_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 111));
Balances::unreserve(&1, 42);
@@ -453,7 +442,7 @@ fn unreserving_balance_should_work() {
#[test]
fn slashing_reserved_balance_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 111));
assert_eq!(Balances::slash_reserved(&1, 42).1, 0);
@@ -465,7 +454,7 @@ fn slashing_reserved_balance_should_work() {
#[test]
fn slashing_incomplete_reserved_balance_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 42));
assert_eq!(Balances::slash_reserved(&1, 69).1, 27);
@@ -477,7 +466,7 @@ fn slashing_incomplete_reserved_balance_should_work() {
#[test]
fn transferring_reserved_balance_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 110);
let _ = Balances::deposit_creating(&2, 1);
assert_ok!(Balances::reserve(&1, 110));
@@ -491,7 +480,7 @@ fn transferring_reserved_balance_should_work() {
#[test]
fn transferring_reserved_balance_to_nonexistent_should_fail() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 111);
assert_ok!(Balances::reserve(&1, 111));
assert_noop!(Balances::repatriate_reserved(&1, &2, 42), "beneficiary account must pre-exist");
@@ -500,7 +489,7 @@ fn transferring_reserved_balance_to_nonexistent_should_fail() {
#[test]
fn transferring_incomplete_reserved_balance_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 110);
let _ = Balances::deposit_creating(&2, 1);
assert_ok!(Balances::reserve(&1, 41));
@@ -514,7 +503,7 @@ fn transferring_incomplete_reserved_balance_should_work() {
#[test]
fn transferring_too_high_value_should_not_panic() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
<FreeBalance<Runtime>>::insert(1, u64::max_value());
<FreeBalance<Runtime>>::insert(2, 1);
@@ -530,89 +519,76 @@ fn transferring_too_high_value_should_not_panic() {
#[test]
fn account_create_on_free_too_low_with_other() {
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(100).build(),
|| {
let _ = Balances::deposit_creating(&1, 100);
assert_eq!(<TotalIssuance<Runtime>>::get(), 100);
ExtBuilder::default().existential_deposit(100).build().execute_with(|| {
let _ = Balances::deposit_creating(&1, 100);
assert_eq!(<TotalIssuance<Runtime>>::get(), 100);
// No-op.
let _ = Balances::deposit_creating(&2, 50);
assert_eq!(Balances::free_balance(&2), 0);
assert_eq!(<TotalIssuance<Runtime>>::get(), 100);
}
)
// No-op.
let _ = Balances::deposit_creating(&2, 50);
assert_eq!(Balances::free_balance(&2), 0);
assert_eq!(<TotalIssuance<Runtime>>::get(), 100);
})
}
#[test]
fn account_create_on_free_too_low() {
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(100).build(),
|| {
// No-op.
let _ = Balances::deposit_creating(&2, 50);
assert_eq!(Balances::free_balance(&2), 0);
assert_eq!(<TotalIssuance<Runtime>>::get(), 0);
}
)
ExtBuilder::default().existential_deposit(100).build().execute_with(|| {
// No-op.
let _ = Balances::deposit_creating(&2, 50);
assert_eq!(Balances::free_balance(&2), 0);
assert_eq!(<TotalIssuance<Runtime>>::get(), 0);
})
}
#[test]
fn account_removal_on_free_too_low() {
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(100).build(),
|| {
assert_eq!(<TotalIssuance<Runtime>>::get(), 0);
ExtBuilder::default().existential_deposit(100).build().execute_with(|| {
assert_eq!(<TotalIssuance<Runtime>>::get(), 0);
// Setup two accounts with free balance above the existential threshold.
let _ = Balances::deposit_creating(&1, 110);
let _ = Balances::deposit_creating(&2, 110);
// Setup two accounts with free balance above the existential threshold.
let _ = Balances::deposit_creating(&1, 110);
let _ = Balances::deposit_creating(&2, 110);
assert_eq!(Balances::free_balance(&1), 110);
assert_eq!(Balances::free_balance(&2), 110);
assert_eq!(<TotalIssuance<Runtime>>::get(), 220);
assert_eq!(Balances::free_balance(&1), 110);
assert_eq!(Balances::free_balance(&2), 110);
assert_eq!(<TotalIssuance<Runtime>>::get(), 220);
// Transfer funds from account 1 of such amount that after this transfer
// the balance of account 1 will be below the existential threshold.
// This should lead to the removal of all balance of this account.
assert_ok!(Balances::transfer(Some(1).into(), 2, 20));
// Transfer funds from account 1 of such amount that after this transfer
// the balance of account 1 will be below the existential threshold.
// This should lead to the removal of all balance of this account.
assert_ok!(Balances::transfer(Some(1).into(), 2, 20));
// Verify free balance removal of account 1.
assert_eq!(Balances::free_balance(&1), 0);
assert_eq!(Balances::free_balance(&2), 130);
// Verify free balance removal of account 1.
assert_eq!(Balances::free_balance(&1), 0);
assert_eq!(Balances::free_balance(&2), 130);
// Verify that TotalIssuance tracks balance removal when free balance is too low.
assert_eq!(<TotalIssuance<Runtime>>::get(), 130);
},
);
// Verify that TotalIssuance tracks balance removal when free balance is too low.
assert_eq!(<TotalIssuance<Runtime>>::get(), 130);
});
}
#[test]
fn transfer_overflow_isnt_exploitable() {
set_and_run_with_externalities(
&mut ExtBuilder::default().creation_fee(50).build(),
|| {
// Craft a value that will overflow if summed with `creation_fee`.
let evil_value = u64::max_value() - 49;
ExtBuilder::default().creation_fee(50).build().execute_with(|| {
// Craft a value that will overflow if summed with `creation_fee`.
let evil_value = u64::max_value() - 49;
assert_err!(
Balances::transfer(Some(1).into(), 5, evil_value),
"got overflow after adding a fee to value",
);
}
);
assert_err!(
Balances::transfer(Some(1).into(), 5, evil_value),
"got overflow after adding a fee to value",
);
});
}
#[test]
fn check_vesting_status() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(256)
.monied(true)
.vesting(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(256)
.monied(true)
.vesting(true)
.build()
.execute_with(|| {
assert_eq!(System::block_number(), 1);
let user1_free_balance = Balances::free_balance(&1);
let user2_free_balance = Balances::free_balance(&2);
@@ -663,19 +639,17 @@ fn check_vesting_status() {
assert_eq!(Balances::vesting_balance(&2), 0); // Account 2 has fully vested by block 30
assert_eq!(Balances::vesting_balance(&12), 0); // Account 2 has fully vested by block 30
}
);
});
}
#[test]
fn unvested_balance_should_not_transfer() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(10)
.monied(true)
.vesting(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(10)
.monied(true)
.vesting(true)
.build()
.execute_with(|| {
assert_eq!(System::block_number(), 1);
let user1_free_balance = Balances::free_balance(&1);
assert_eq!(user1_free_balance, 100); // Account 1 has free balance
@@ -685,38 +659,34 @@ fn unvested_balance_should_not_transfer() {
Balances::transfer(Some(1).into(), 2, 56),
"vesting balance too high to send value",
); // Account 1 cannot send more than vested amount
}
);
});
}
#[test]
fn vested_balance_should_transfer() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(10)
.monied(true)
.vesting(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(10)
.monied(true)
.vesting(true)
.build()
.execute_with(|| {
assert_eq!(System::block_number(), 1);
let user1_free_balance = Balances::free_balance(&1);
assert_eq!(user1_free_balance, 100); // Account 1 has free balance
// Account 1 has only 5 units vested at block 1 (plus 50 unvested)
assert_eq!(Balances::vesting_balance(&1), 45);
assert_ok!(Balances::transfer(Some(1).into(), 2, 55));
}
);
});
}
#[test]
fn extra_balance_should_transfer() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(10)
.monied(true)
.vesting(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(10)
.monied(true)
.vesting(true)
.build()
.execute_with(|| {
assert_eq!(System::block_number(), 1);
assert_ok!(Balances::transfer(Some(3).into(), 1, 100));
assert_ok!(Balances::transfer(Some(3).into(), 2, 100));
@@ -734,19 +704,17 @@ fn extra_balance_should_transfer() {
// Account 2 has no units vested at block 1, but gained 100
assert_eq!(Balances::vesting_balance(&2), 200);
assert_ok!(Balances::transfer(Some(2).into(), 3, 100)); // Account 2 can send extra units gained
}
);
});
}
#[test]
fn liquid_funds_should_transfer_with_delayed_vesting() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(256)
.monied(true)
.vesting(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(256)
.monied(true)
.vesting(true)
.build()
.execute_with(|| {
assert_eq!(System::block_number(), 1);
let user12_free_balance = Balances::free_balance(&12);
@@ -764,62 +732,64 @@ fn liquid_funds_should_transfer_with_delayed_vesting() {
// Account 12 can still send liquid funds
assert_ok!(Balances::transfer(Some(12).into(), 3, 256 * 5));
}
);
});
}
#[test]
fn signed_extension_take_fees_work() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(10)
.transaction_fees(10, 1, 5)
.monied(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(10)
.transaction_fees(10, 1, 5)
.monied(true)
.build()
.execute_with(|| {
let len = 10;
assert!(TakeFees::<Runtime>::from(0).pre_dispatch(&1, CALL, info_from_weight(5), len).is_ok());
assert!(
TakeFees::<Runtime>::from(0)
.pre_dispatch(&1, CALL, info_from_weight(5), len)
.is_ok()
);
assert_eq!(Balances::free_balance(&1), 100 - 20 - 25);
assert!(TakeFees::<Runtime>::from(5 /* tipped */).pre_dispatch(&1, CALL, info_from_weight(3), len).is_ok());
assert!(
TakeFees::<Runtime>::from(5 /* tipped */)
.pre_dispatch(&1, CALL, info_from_weight(3), len)
.is_ok()
);
assert_eq!(Balances::free_balance(&1), 100 - 20 - 25 - 20 - 5 - 15);
}
);
});
}
#[test]
fn signed_extension_take_fees_is_bounded() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.existential_deposit(1000)
.transaction_fees(0, 0, 1)
.monied(true)
.build(),
|| {
ExtBuilder::default()
.existential_deposit(1000)
.transaction_fees(0, 0, 1)
.monied(true)
.build()
.execute_with(|| {
use sr_primitives::weights::Weight;
// maximum weight possible
assert!(TakeFees::<Runtime>::from(0).pre_dispatch(&1, CALL, info_from_weight(Weight::max_value()), 10).is_ok());
assert!(
TakeFees::<Runtime>::from(0)
.pre_dispatch(&1, CALL, info_from_weight(Weight::max_value()), 10)
.is_ok()
);
// fee will be proportional to what is the actual maximum weight in the runtime.
assert_eq!(
Balances::free_balance(&1),
(10000 - <Runtime as system::Trait>::MaximumBlockWeight::get()) as u64
);
}
);
});
}
#[test]
fn burn_must_work() {
set_and_run_with_externalities(
&mut ExtBuilder::default()
.monied(true)
.build(),
|| {
let init_total_issuance = Balances::total_issuance();
let imbalance = Balances::burn(10);
assert_eq!(Balances::total_issuance(), init_total_issuance - 10);
drop(imbalance);
assert_eq!(Balances::total_issuance(), init_total_issuance);
}
);
ExtBuilder::default().monied(true).build().execute_with(|| {
let init_total_issuance = Balances::total_issuance();
let imbalance = Balances::burn(10);
assert_eq!(Balances::total_issuance(), init_total_issuance - 10);
drop(imbalance);
assert_eq!(Balances::total_issuance(), init_total_issuance);
});
}
+28 -16
View File
@@ -384,8 +384,8 @@ mod tests {
use hex_literal::hex;
use primitives::H256;
use sr_primitives::{
set_and_run_with_externalities, Perbill,
traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, testing::Header, BuildStorage,
Perbill, traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, testing::Header,
BuildStorage,
};
use crate as collective;
@@ -451,7 +451,7 @@ mod tests {
#[test]
fn motions_basic_environment_works() {
set_and_run_with_externalities(&mut make_ext(), || {
make_ext().execute_with(|| {
System::set_block_number(1);
assert_eq!(Collective::members(), vec![1, 2, 3]);
assert_eq!(Collective::proposals(), Vec::<H256>::new());
@@ -464,7 +464,7 @@ mod tests {
#[test]
fn removal_of_old_voters_votes_works() {
set_and_run_with_externalities(&mut make_ext(), || {
make_ext().execute_with(|| {
System::set_block_number(1);
let proposal = make_proposal(42);
let hash = BlakeTwo256::hash_of(&proposal);
@@ -498,7 +498,7 @@ mod tests {
#[test]
fn removal_of_old_voters_votes_works_with_set_members() {
set_and_run_with_externalities(&mut make_ext(), || {
make_ext().execute_with(|| {
System::set_block_number(1);
let proposal = make_proposal(42);
let hash = BlakeTwo256::hash_of(&proposal);
@@ -532,7 +532,7 @@ mod tests {
#[test]
fn propose_works() {
set_and_run_with_externalities(&mut make_ext(), || {
make_ext().execute_with(|| {
System::set_block_number(1);
let proposal = make_proposal(42);
let hash = proposal.blake2_256().into();
@@ -561,7 +561,7 @@ mod tests {
#[test]
fn motions_ignoring_non_collective_proposals_works() {
set_and_run_with_externalities(&mut make_ext(), || {
make_ext().execute_with(|| {
System::set_block_number(1);
let proposal = make_proposal(42);
assert_noop!(
@@ -573,29 +573,35 @@ mod tests {
#[test]
fn motions_ignoring_non_collective_votes_works() {
set_and_run_with_externalities(&mut make_ext(), || {
make_ext().execute_with(|| {
System::set_block_number(1);
let proposal = make_proposal(42);
let hash: H256 = proposal.blake2_256().into();
assert_ok!(Collective::propose(Origin::signed(1), 3, Box::new(proposal.clone())));
assert_noop!(Collective::vote(Origin::signed(42), hash.clone(), 0, true), "voter not a member");
assert_noop!(
Collective::vote(Origin::signed(42), hash.clone(), 0, true),
"voter not a member",
);
});
}
#[test]
fn motions_ignoring_bad_index_collective_vote_works() {
set_and_run_with_externalities(&mut make_ext(), || {
make_ext().execute_with(|| {
System::set_block_number(3);
let proposal = make_proposal(42);
let hash: H256 = proposal.blake2_256().into();
assert_ok!(Collective::propose(Origin::signed(1), 3, Box::new(proposal.clone())));
assert_noop!(Collective::vote(Origin::signed(2), hash.clone(), 1, true), "mismatched index");
assert_noop!(
Collective::vote(Origin::signed(2), hash.clone(), 1, true),
"mismatched index",
);
});
}
#[test]
fn motions_revoting_works() {
set_and_run_with_externalities(&mut make_ext(), || {
make_ext().execute_with(|| {
System::set_block_number(1);
let proposal = make_proposal(42);
let hash: H256 = proposal.blake2_256().into();
@@ -604,13 +610,19 @@ mod tests {
Collective::voting(&hash),
Some(Votes { index: 0, threshold: 2, ayes: vec![1], nays: vec![] })
);
assert_noop!(Collective::vote(Origin::signed(1), hash.clone(), 0, true), "duplicate vote ignored");
assert_noop!(
Collective::vote(Origin::signed(1), hash.clone(), 0, true),
"duplicate vote ignored",
);
assert_ok!(Collective::vote(Origin::signed(1), hash.clone(), 0, false));
assert_eq!(
Collective::voting(&hash),
Some(Votes { index: 0, threshold: 2, ayes: vec![], nays: vec![1] })
);
assert_noop!(Collective::vote(Origin::signed(1), hash.clone(), 0, false), "duplicate vote ignored");
assert_noop!(
Collective::vote(Origin::signed(1), hash.clone(), 0, false),
"duplicate vote ignored",
);
assert_eq!(System::events(), vec![
EventRecord {
@@ -640,7 +652,7 @@ mod tests {
#[test]
fn motions_disapproval_works() {
set_and_run_with_externalities(&mut make_ext(), || {
make_ext().execute_with(|| {
System::set_block_number(1);
let proposal = make_proposal(42);
let hash: H256 = proposal.blake2_256().into();
@@ -683,7 +695,7 @@ mod tests {
#[test]
fn motions_approval_works() {
set_and_run_with_externalities(&mut make_ext(), || {
make_ext().execute_with(|| {
System::set_block_number(1);
let proposal = make_proposal(42);
let hash: H256 = proposal.blake2_256().into();
+178 -203
View File
@@ -807,7 +807,6 @@ mod tests {
account_db::AccountDb, gas::GasMeter, tests::{ExtBuilder, Test},
exec::{ExecReturnValue, ExecError, STATUS_SUCCESS}, CodeHash, Config,
};
use sr_primitives::set_and_run_with_externalities;
use std::{cell::RefCell, rc::Rc, collections::HashMap, marker::PhantomData};
use assert_matches::assert_matches;
@@ -933,7 +932,7 @@ mod tests {
exec_success()
});
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.instantiate_contract(&BOB, exec_ch).unwrap();
@@ -953,7 +952,7 @@ mod tests {
let dest = BOB;
// This test verifies that base fee for call is taken.
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let vm = MockVm::new();
let loader = MockLoader::empty();
let cfg = Config::preload();
@@ -971,7 +970,7 @@ mod tests {
});
// This test verifies that base fee for instantiation is taken.
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let mut loader = MockLoader::empty();
let code = loader.insert(|_| exec_success());
@@ -1001,7 +1000,7 @@ mod tests {
let vm = MockVm::new();
let loader = MockLoader::empty();
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
ctx.overlay.set_balance(&origin, 100);
@@ -1033,7 +1032,7 @@ mod tests {
|_| Ok(ExecReturnValue { status: 1, data: Vec::new() })
);
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
ctx.overlay.instantiate_contract(&BOB, return_ch).unwrap();
@@ -1061,93 +1060,84 @@ mod tests {
// This test sends 50 units of currency to a non-existent account.
// This should lead to creation of a new account thus
// a fee should be charged.
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(15).build(),
|| {
let vm = MockVm::new();
let loader = MockLoader::empty();
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
ctx.overlay.set_balance(&origin, 100);
ctx.overlay.set_balance(&dest, 0);
ExtBuilder::default().existential_deposit(15).build().execute_with(|| {
let vm = MockVm::new();
let loader = MockLoader::empty();
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
ctx.overlay.set_balance(&origin, 100);
ctx.overlay.set_balance(&dest, 0);
let mut gas_meter = GasMeter::<Test>::with_limit(1000, 1);
let mut gas_meter = GasMeter::<Test>::with_limit(1000, 1);
let result = ctx.call(dest, 50, &mut gas_meter, vec![]);
assert_matches!(result, Ok(_));
let result = ctx.call(dest, 50, &mut gas_meter, vec![]);
assert_matches!(result, Ok(_));
let mut toks = gas_meter.tokens().iter();
match_tokens!(
toks,
ExecFeeToken::Call,
TransferFeeToken {
kind: TransferFeeKind::AccountCreate,
gas_price: 1u64
},
);
},
);
let mut toks = gas_meter.tokens().iter();
match_tokens!(
toks,
ExecFeeToken::Call,
TransferFeeToken {
kind: TransferFeeKind::AccountCreate,
gas_price: 1u64
},
);
});
// This one is similar to the previous one but transfer to an existing account.
// In this test we expect that a regular transfer fee is charged.
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(15).build(),
|| {
let vm = MockVm::new();
let loader = MockLoader::empty();
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
ctx.overlay.set_balance(&origin, 100);
ctx.overlay.set_balance(&dest, 15);
ExtBuilder::default().existential_deposit(15).build().execute_with(|| {
let vm = MockVm::new();
let loader = MockLoader::empty();
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
ctx.overlay.set_balance(&origin, 100);
ctx.overlay.set_balance(&dest, 15);
let mut gas_meter = GasMeter::<Test>::with_limit(1000, 1);
let mut gas_meter = GasMeter::<Test>::with_limit(1000, 1);
let result = ctx.call(dest, 50, &mut gas_meter, vec![]);
assert_matches!(result, Ok(_));
let result = ctx.call(dest, 50, &mut gas_meter, vec![]);
assert_matches!(result, Ok(_));
let mut toks = gas_meter.tokens().iter();
match_tokens!(
toks,
ExecFeeToken::Call,
TransferFeeToken {
kind: TransferFeeKind::Transfer,
gas_price: 1u64
},
);
},
);
let mut toks = gas_meter.tokens().iter();
match_tokens!(
toks,
ExecFeeToken::Call,
TransferFeeToken {
kind: TransferFeeKind::Transfer,
gas_price: 1u64
},
);
});
// This test sends 50 units of currency as an endownment to a newly
// instantiated contract.
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(15).build(),
|| {
let mut loader = MockLoader::empty();
let code = loader.insert(|_| exec_success());
ExtBuilder::default().existential_deposit(15).build().execute_with(|| {
let mut loader = MockLoader::empty();
let code = loader.insert(|_| exec_success());
let vm = MockVm::new();
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
let vm = MockVm::new();
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
ctx.overlay.set_balance(&origin, 100);
ctx.overlay.set_balance(&dest, 15);
ctx.overlay.set_balance(&origin, 100);
ctx.overlay.set_balance(&dest, 15);
let mut gas_meter = GasMeter::<Test>::with_limit(1000, 1);
let mut gas_meter = GasMeter::<Test>::with_limit(1000, 1);
let result = ctx.instantiate(50, &mut gas_meter, &code, vec![]);
assert_matches!(result, Ok(_));
let result = ctx.instantiate(50, &mut gas_meter, &code, vec![]);
assert_matches!(result, Ok(_));
let mut toks = gas_meter.tokens().iter();
match_tokens!(
toks,
ExecFeeToken::Instantiate,
TransferFeeToken {
kind: TransferFeeKind::ContractInstantiate,
gas_price: 1u64
},
);
},
);
let mut toks = gas_meter.tokens().iter();
match_tokens!(
toks,
ExecFeeToken::Instantiate,
TransferFeeToken {
kind: TransferFeeKind::ContractInstantiate,
gas_price: 1u64
},
);
});
}
#[test]
@@ -1160,7 +1150,7 @@ mod tests {
let vm = MockVm::new();
let loader = MockLoader::empty();
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
ctx.overlay.set_balance(&origin, 0);
@@ -1194,7 +1184,7 @@ mod tests {
|_| Ok(ExecReturnValue { status: STATUS_SUCCESS, data: vec![1, 2, 3, 4] })
);
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
ctx.overlay.instantiate_contract(&BOB, return_ch).unwrap();
@@ -1225,7 +1215,7 @@ mod tests {
|_| Ok(ExecReturnValue { status: 1, data: vec![1, 2, 3, 4] })
);
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
ctx.overlay.instantiate_contract(&BOB, return_ch).unwrap();
@@ -1253,7 +1243,7 @@ mod tests {
});
// This one tests passing the input data into a contract via call.
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.instantiate_contract(&BOB, input_data_ch).unwrap();
@@ -1278,7 +1268,7 @@ mod tests {
});
// This one tests passing the input data into a contract via instantiate.
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
@@ -1322,7 +1312,7 @@ mod tests {
exec_success()
});
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.instantiate_contract(&BOB, recurse_ch).unwrap();
@@ -1366,7 +1356,7 @@ mod tests {
exec_success()
});
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader);
@@ -1408,7 +1398,7 @@ mod tests {
exec_success()
});
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.instantiate_contract(&BOB, bob_ch).unwrap();
@@ -1432,23 +1422,20 @@ mod tests {
let mut loader = MockLoader::empty();
let dummy_ch = loader.insert(|_| exec_success());
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(15).build(),
|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ExtBuilder::default().existential_deposit(15).build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
assert_matches!(
ctx.instantiate(
0, // <- zero endowment
&mut GasMeter::<Test>::with_limit(10000, 1),
&dummy_ch,
vec![],
),
Err(_)
);
}
);
assert_matches!(
ctx.instantiate(
0, // <- zero endowment
&mut GasMeter::<Test>::with_limit(10000, 1),
&dummy_ch,
vec![],
),
Err(_)
);
});
}
#[test]
@@ -1460,38 +1447,35 @@ mod tests {
|_| Ok(ExecReturnValue { status: STATUS_SUCCESS, data: vec![80, 65, 83, 83] })
);
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(15).build(),
|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.set_balance(&ALICE, 1000);
ExtBuilder::default().existential_deposit(15).build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.set_balance(&ALICE, 1000);
let instantiated_contract_address = assert_matches!(
ctx.instantiate(
100,
&mut GasMeter::<Test>::with_limit(10000, 1),
&dummy_ch,
vec![],
),
Ok((address, ref output)) if output.data == vec![80, 65, 83, 83] => address
);
let instantiated_contract_address = assert_matches!(
ctx.instantiate(
100,
&mut GasMeter::<Test>::with_limit(10000, 1),
&dummy_ch,
vec![],
),
Ok((address, ref output)) if output.data == vec![80, 65, 83, 83] => address
);
// Check that the newly created account has the expected code hash and
// there are instantiation event.
assert_eq!(ctx.overlay.get_code_hash(&instantiated_contract_address).unwrap(), dummy_ch);
assert_eq!(&ctx.events(), &[
DeferredAction::DepositEvent {
event: RawEvent::Transfer(ALICE, instantiated_contract_address, 100),
topics: Vec::new(),
},
DeferredAction::DepositEvent {
event: RawEvent::Instantiated(ALICE, instantiated_contract_address),
topics: Vec::new(),
}
]);
}
);
// Check that the newly created account has the expected code hash and
// there are instantiation event.
assert_eq!(ctx.overlay.get_code_hash(&instantiated_contract_address).unwrap(), dummy_ch);
assert_eq!(&ctx.events(), &[
DeferredAction::DepositEvent {
event: RawEvent::Transfer(ALICE, instantiated_contract_address, 100),
topics: Vec::new(),
},
DeferredAction::DepositEvent {
event: RawEvent::Instantiated(ALICE, instantiated_contract_address),
topics: Vec::new(),
}
]);
});
}
#[test]
@@ -1503,28 +1487,25 @@ mod tests {
|_| Ok(ExecReturnValue { status: 1, data: vec![70, 65, 73, 76] })
);
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(15).build(),
|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.set_balance(&ALICE, 1000);
ExtBuilder::default().existential_deposit(15).build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.set_balance(&ALICE, 1000);
let instantiated_contract_address = assert_matches!(
ctx.instantiate(
100,
&mut GasMeter::<Test>::with_limit(10000, 1),
&dummy_ch,
vec![],
),
Ok((address, ref output)) if output.data == vec![70, 65, 73, 76] => address
);
let instantiated_contract_address = assert_matches!(
ctx.instantiate(
100,
&mut GasMeter::<Test>::with_limit(10000, 1),
&dummy_ch,
vec![],
),
Ok((address, ref output)) if output.data == vec![70, 65, 73, 76] => address
);
// Check that the account has not been created.
assert!(ctx.overlay.get_code_hash(&instantiated_contract_address).is_none());
assert!(ctx.events().is_empty());
}
);
// Check that the account has not been created.
assert!(ctx.overlay.get_code_hash(&instantiated_contract_address).is_none());
assert!(ctx.events().is_empty());
});
}
#[test]
@@ -1551,40 +1532,37 @@ mod tests {
}
});
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(15).build(),
|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.set_balance(&ALICE, 1000);
ctx.overlay.instantiate_contract(&BOB, instantiator_ch).unwrap();
ExtBuilder::default().existential_deposit(15).build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.set_balance(&ALICE, 1000);
ctx.overlay.instantiate_contract(&BOB, instantiator_ch).unwrap();
assert_matches!(
ctx.call(BOB, 20, &mut GasMeter::<Test>::with_limit(1000, 1), vec![]),
Ok(_)
);
assert_matches!(
ctx.call(BOB, 20, &mut GasMeter::<Test>::with_limit(1000, 1), vec![]),
Ok(_)
);
let instantiated_contract_address = instantiated_contract_address.borrow().as_ref().unwrap().clone();
let instantiated_contract_address = instantiated_contract_address.borrow().as_ref().unwrap().clone();
// Check that the newly created account has the expected code hash and
// there are instantiation event.
assert_eq!(ctx.overlay.get_code_hash(&instantiated_contract_address).unwrap(), dummy_ch);
assert_eq!(&ctx.events(), &[
DeferredAction::DepositEvent {
event: RawEvent::Transfer(ALICE, BOB, 20),
topics: Vec::new(),
},
DeferredAction::DepositEvent {
event: RawEvent::Transfer(BOB, instantiated_contract_address, 15),
topics: Vec::new(),
},
DeferredAction::DepositEvent {
event: RawEvent::Instantiated(BOB, instantiated_contract_address),
topics: Vec::new(),
},
]);
}
);
// Check that the newly created account has the expected code hash and
// there are instantiation event.
assert_eq!(ctx.overlay.get_code_hash(&instantiated_contract_address).unwrap(), dummy_ch);
assert_eq!(&ctx.events(), &[
DeferredAction::DepositEvent {
event: RawEvent::Transfer(ALICE, BOB, 20),
topics: Vec::new(),
},
DeferredAction::DepositEvent {
event: RawEvent::Transfer(BOB, instantiated_contract_address, 15),
topics: Vec::new(),
},
DeferredAction::DepositEvent {
event: RawEvent::Instantiated(BOB, instantiated_contract_address),
topics: Vec::new(),
},
]);
});
}
#[test]
@@ -1613,29 +1591,26 @@ mod tests {
}
});
set_and_run_with_externalities(
&mut ExtBuilder::default().existential_deposit(15).build(),
|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.set_balance(&ALICE, 1000);
ctx.overlay.instantiate_contract(&BOB, instantiator_ch).unwrap();
ExtBuilder::default().existential_deposit(15).build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
ctx.overlay.set_balance(&ALICE, 1000);
ctx.overlay.instantiate_contract(&BOB, instantiator_ch).unwrap();
assert_matches!(
ctx.call(BOB, 20, &mut GasMeter::<Test>::with_limit(1000, 1), vec![]),
Ok(_)
);
assert_matches!(
ctx.call(BOB, 20, &mut GasMeter::<Test>::with_limit(1000, 1), vec![]),
Ok(_)
);
// The contract wasn't instantiated so we don't expect to see an instantiation
// event here.
assert_eq!(&ctx.events(), &[
DeferredAction::DepositEvent {
event: RawEvent::Transfer(ALICE, BOB, 20),
topics: Vec::new(),
},
]);
}
);
// The contract wasn't instantiated so we don't expect to see an instantiation
// event here.
assert_eq!(&ctx.events(), &[
DeferredAction::DepositEvent {
event: RawEvent::Transfer(ALICE, BOB, 20),
topics: Vec::new(),
},
]);
});
}
#[test]
@@ -1649,7 +1624,7 @@ mod tests {
exec_success()
});
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
let cfg = Config::preload();
let mut ctx = ExecutionContext::top_level(ALICE, &cfg, &vm, &loader);
File diff suppressed because it is too large Load Diff
+35 -38
View File
@@ -976,10 +976,7 @@ mod tests {
traits::Contains
};
use primitives::H256;
use sr_primitives::{
set_and_run_with_externalities, traits::{BlakeTwo256, IdentityLookup, Bounded},
testing::Header, Perbill,
};
use sr_primitives::{traits::{BlakeTwo256, IdentityLookup, Bounded}, testing::Header, Perbill};
use balances::BalanceLock;
use system::EnsureSignedBy;
@@ -1101,7 +1098,7 @@ mod tests {
#[test]
fn params_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_eq!(Democracy::referendum_count(), 0);
assert_eq!(Balances::free_balance(&42), 0);
assert_eq!(Balances::total_issuance(), 210);
@@ -1133,7 +1130,7 @@ mod tests {
#[test]
fn external_and_public_interleaving_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(Democracy::external_propose(
Origin::signed(2),
@@ -1246,7 +1243,7 @@ mod tests {
#[test]
fn emergency_cancel_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let r = Democracy::inject_referendum(
2,
@@ -1275,7 +1272,7 @@ mod tests {
#[test]
fn veto_external_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(Democracy::external_propose(
Origin::signed(2),
@@ -1335,7 +1332,7 @@ mod tests {
#[test]
fn external_referendum_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_noop!(Democracy::external_propose(
Origin::signed(1),
@@ -1364,7 +1361,7 @@ mod tests {
#[test]
fn external_majority_referendum_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_noop!(Democracy::external_propose_majority(
Origin::signed(1),
@@ -1389,7 +1386,7 @@ mod tests {
#[test]
fn external_default_referendum_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_noop!(Democracy::external_propose_default(
Origin::signed(3),
@@ -1414,7 +1411,7 @@ mod tests {
#[test]
fn fast_track_referendum_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let h = BlakeTwo256::hash_of(&set_balance_proposal(2));
assert_noop!(Democracy::fast_track(Origin::signed(5), h, 3, 2), "no proposal made");
@@ -1438,7 +1435,7 @@ mod tests {
#[test]
fn fast_track_referendum_fails_when_no_simple_majority() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let h = BlakeTwo256::hash_of(&set_balance_proposal(2));
assert_ok!(Democracy::external_propose(
@@ -1454,7 +1451,7 @@ mod tests {
#[test]
fn locked_for_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_ok!(propose_set_balance(1, 2, 2));
assert_ok!(propose_set_balance(1, 4, 4));
@@ -1467,7 +1464,7 @@ mod tests {
#[test]
fn single_proposal_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance(1, 2, 1));
assert!(Democracy::referendum_info(0).is_none());
@@ -1514,7 +1511,7 @@ mod tests {
#[test]
fn cancel_queued_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance(1, 2, 1));
@@ -1538,7 +1535,7 @@ mod tests {
#[test]
fn proxy_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_eq!(Democracy::proxy(10), None);
assert_ok!(Democracy::set_proxy(Origin::signed(1), 10));
assert_eq!(Democracy::proxy(10), Some(1));
@@ -1568,7 +1565,7 @@ mod tests {
#[test]
fn single_proposal_should_work_with_proxy() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance(1, 2, 1));
@@ -1588,7 +1585,7 @@ mod tests {
#[test]
fn single_proposal_should_work_with_delegation() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance(1, 2, 1));
@@ -1613,7 +1610,7 @@ mod tests {
#[test]
fn single_proposal_should_work_with_cyclic_delegation() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance(1, 2, 1));
@@ -1640,7 +1637,7 @@ mod tests {
#[test]
/// If transactor already voted, delegated vote is overwriten.
fn single_proposal_should_work_with_vote_and_delegation() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance(1, 2, 1));
@@ -1666,7 +1663,7 @@ mod tests {
#[test]
fn single_proposal_should_work_with_undelegation() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance(1, 2, 1));
@@ -1695,7 +1692,7 @@ mod tests {
#[test]
/// If transactor voted, delegated vote is overwriten.
fn single_proposal_should_work_with_delegation_and_vote() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance(1, 2, 1));
@@ -1726,7 +1723,7 @@ mod tests {
#[test]
fn deposit_for_proposals_should_be_taken() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_ok!(propose_set_balance(1, 2, 5));
assert_ok!(Democracy::second(Origin::signed(2), 0));
@@ -1741,7 +1738,7 @@ mod tests {
#[test]
fn deposit_for_proposals_should_be_returned() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_ok!(propose_set_balance(1, 2, 5));
assert_ok!(Democracy::second(Origin::signed(2), 0));
@@ -1757,7 +1754,7 @@ mod tests {
#[test]
fn proposal_with_deposit_below_minimum_should_not_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_noop!(propose_set_balance(1, 2, 0), "value too low");
});
@@ -1765,7 +1762,7 @@ mod tests {
#[test]
fn poor_proposer_should_not_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_noop!(propose_set_balance(1, 2, 11), "proposer\'s balance too low");
});
@@ -1773,7 +1770,7 @@ mod tests {
#[test]
fn poor_seconder_should_not_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
assert_ok!(propose_set_balance(2, 2, 11));
assert_noop!(Democracy::second(Origin::signed(1), 0), "seconder\'s balance too low");
@@ -1782,7 +1779,7 @@ mod tests {
#[test]
fn runners_up_should_come_after() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
assert_ok!(propose_set_balance(1, 2, 2));
assert_ok!(propose_set_balance(1, 4, 4));
@@ -1798,7 +1795,7 @@ mod tests {
#[test]
fn simple_passing_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
1,
@@ -1821,7 +1818,7 @@ mod tests {
#[test]
fn cancel_referendum_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
1,
@@ -1841,7 +1838,7 @@ mod tests {
#[test]
fn simple_failing_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
1,
@@ -1864,7 +1861,7 @@ mod tests {
#[test]
fn controversial_voting_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
1,
@@ -1890,7 +1887,7 @@ mod tests {
#[test]
fn delayed_enactment_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
1,
@@ -1918,7 +1915,7 @@ mod tests {
#[test]
fn controversial_low_turnout_voting_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
1,
@@ -1940,7 +1937,7 @@ mod tests {
#[test]
fn passing_low_turnout_voting_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(&42), 0);
assert_eq!(Balances::total_issuance(), 210);
@@ -1966,7 +1963,7 @@ mod tests {
#[test]
fn lock_voting_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(0);
let r = Democracy::inject_referendum(
1,
@@ -2026,7 +2023,7 @@ mod tests {
#[test]
fn lock_voting_should_work_with_delegation() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
let r = Democracy::inject_referendum(
1,
+38 -40
View File
@@ -594,7 +594,7 @@ mod tests {
use primitives::H256;
use sr_primitives::{
Perbill, testing::Header, BuildStorage,
traits::{BlakeTwo256, IdentityLookup, Block as BlockT}, set_and_run_with_externalities
traits::{BlakeTwo256, IdentityLookup, Block as BlockT},
};
use crate as elections;
@@ -770,7 +770,7 @@ mod tests {
#[test]
fn params_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_eq!(Elections::desired_members(), 2);
assert_eq!(Elections::term_duration(), 5);
@@ -790,7 +790,7 @@ mod tests {
#[test]
fn simple_candidate_submission_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert!(Elections::is_candidate(&1).is_err());
assert!(Elections::is_candidate(&2).is_err());
@@ -817,7 +817,7 @@ mod tests {
#[test]
fn simple_candidate_submission_with_no_votes_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert_ok!(Elections::submit_candidacy(Origin::signed(1)));
@@ -844,7 +844,7 @@ mod tests {
#[test]
fn dupe_candidate_submission_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert_ok!(Elections::submit_candidacy(Origin::signed(1)));
assert_eq!(Elections::candidates(), vec![1]);
@@ -858,7 +858,7 @@ mod tests {
#[test]
fn member_candidacy_submission_should_not_work() {
// critically important to make sure that outgoing candidates and losers are not mixed up.
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::vote(Origin::signed(2), vec![5], 20));
@@ -878,7 +878,7 @@ mod tests {
#[test]
fn poor_candidate_submission_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert_noop!(
Elections::submit_candidacy(Origin::signed(7)),
@@ -889,7 +889,7 @@ mod tests {
#[test]
fn simple_voting_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert_eq!(balances(&2), (20, 0));
@@ -903,7 +903,7 @@ mod tests {
#[test]
fn can_vote_with_custom_stake() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert_eq!(balances(&2), (20, 0));
@@ -917,7 +917,7 @@ mod tests {
#[test]
fn can_update_votes_and_stake() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(balances(&2), (20, 0));
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
@@ -938,7 +938,7 @@ mod tests {
#[test]
fn cannot_vote_for_no_candidate() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_noop!(
Elections::vote(Origin::signed(2), vec![], 20),
"cannot vote when no candidates or members exist"
@@ -949,7 +949,7 @@ mod tests {
#[test]
fn can_vote_for_old_members_even_when_no_new_candidates() {
// let allowed_votes = candidates_count as usize + Self::members().len()
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
@@ -967,7 +967,7 @@ mod tests {
#[test]
fn cannot_vote_for_more_than_candidates() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
@@ -980,7 +980,7 @@ mod tests {
#[test]
fn cannot_vote_for_less_than_ed() {
set_and_run_with_externalities(&mut ExtBuilder::default().voter_bond(8).build(), || {
ExtBuilder::default().voter_bond(8).build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
@@ -993,7 +993,7 @@ mod tests {
#[test]
fn can_vote_for_more_than_total_balance_but_moot() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
@@ -1006,7 +1006,7 @@ mod tests {
#[test]
fn remove_voter_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().voter_bond(8).build(), || {
ExtBuilder::default().voter_bond(8).build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::vote(Origin::signed(2), vec![5], 20));
@@ -1031,14 +1031,14 @@ mod tests {
#[test]
fn non_voter_remove_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_noop!(Elections::remove_voter(Origin::signed(3)), "must be a voter");
});
}
#[test]
fn dupe_remove_should_fail() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::vote(Origin::signed(2), vec![5], 20));
@@ -1051,7 +1051,7 @@ mod tests {
#[test]
fn removed_voter_should_not_be_counted() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
assert_ok!(Elections::submit_candidacy(Origin::signed(3)));
@@ -1071,7 +1071,7 @@ mod tests {
#[test]
fn reporter_must_be_voter() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_noop!(
Elections::report_defunct_voter(Origin::signed(1), 2),
"reporter must be a voter",
@@ -1081,7 +1081,7 @@ mod tests {
#[test]
fn can_detect_defunct_voter() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
@@ -1116,7 +1116,7 @@ mod tests {
#[test]
fn report_voter_should_work_and_earn_reward() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
@@ -1148,8 +1148,7 @@ mod tests {
#[test]
fn report_voter_should_slash_when_bad_report() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
@@ -1174,13 +1173,12 @@ mod tests {
assert_eq!(balances(&4), (35, 5));
assert_eq!(balances(&5), (45, 3));
});
});
}
#[test]
fn simple_voting_rounds_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
assert_ok!(Elections::submit_candidacy(Origin::signed(3)));
@@ -1215,7 +1213,7 @@ mod tests {
#[test]
fn defunct_voter_will_be_counted() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
// This guy's vote is pointless for this round.
@@ -1243,7 +1241,7 @@ mod tests {
#[test]
fn only_desired_seats_are_chosen() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
assert_ok!(Elections::submit_candidacy(Origin::signed(3)));
@@ -1264,7 +1262,7 @@ mod tests {
#[test]
fn phragmen_should_not_self_vote() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
@@ -1279,7 +1277,7 @@ mod tests {
#[test]
fn runners_up_should_be_kept() {
set_and_run_with_externalities(&mut ExtBuilder::default().desired_runners_up(2).build(), || {
ExtBuilder::default().desired_runners_up(2).build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
assert_ok!(Elections::submit_candidacy(Origin::signed(3)));
@@ -1306,7 +1304,7 @@ mod tests {
#[test]
fn runners_up_should_be_next_candidates() {
set_and_run_with_externalities(&mut ExtBuilder::default().desired_runners_up(2).build(), || {
ExtBuilder::default().desired_runners_up(2).build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
assert_ok!(Elections::submit_candidacy(Origin::signed(3)));
@@ -1333,7 +1331,7 @@ mod tests {
#[test]
fn runners_up_lose_bond_once_outgoing() {
set_and_run_with_externalities(&mut ExtBuilder::default().desired_runners_up(1).build(), || {
ExtBuilder::default().desired_runners_up(1).build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
assert_ok!(Elections::submit_candidacy(Origin::signed(2)));
@@ -1364,7 +1362,7 @@ mod tests {
#[test]
fn current_members_are_always_implicitly_next_candidate() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
@@ -1400,7 +1398,7 @@ mod tests {
fn election_state_is_uninterrupted() {
// what I mean by uninterrupted:
// given no input or stimulants the same members are re-elected.
set_and_run_with_externalities(&mut ExtBuilder::default().desired_runners_up(2).build(), || {
ExtBuilder::default().desired_runners_up(2).build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
assert_ok!(Elections::submit_candidacy(Origin::signed(3)));
@@ -1433,7 +1431,7 @@ mod tests {
#[test]
fn remove_members_triggers_election() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
@@ -1459,7 +1457,7 @@ mod tests {
#[test]
fn seats_should_be_released_when_no_vote() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
assert_ok!(Elections::submit_candidacy(Origin::signed(3)));
@@ -1493,7 +1491,7 @@ mod tests {
#[test]
fn outgoing_will_get_the_bond_back() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(balances(&5), (50, 0));
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
@@ -1519,7 +1517,7 @@ mod tests {
#[test]
fn losers_will_lose_the_bond() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
assert_ok!(Elections::submit_candidacy(Origin::signed(3)));
@@ -1542,7 +1540,7 @@ mod tests {
#[test]
fn incoming_outgoing_are_reported() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
assert_ok!(Elections::submit_candidacy(Origin::signed(5)));
@@ -1587,7 +1585,7 @@ mod tests {
#[test]
fn invalid_votes_are_moot() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(4)));
assert_ok!(Elections::submit_candidacy(Origin::signed(3)));
+2 -3
View File
@@ -25,8 +25,7 @@ use support::{
};
use primitives::H256;
use sr_primitives::{
Perbill, BuildStorage, set_and_run_with_externalities, testing::Header,
traits::{BlakeTwo256, IdentityLookup, Block as BlockT},
Perbill, BuildStorage, testing::Header, traits::{BlakeTwo256, IdentityLookup, Block as BlockT},
};
use crate as elections;
@@ -283,7 +282,7 @@ pub(crate) fn locks(who: &u64) -> Vec<u64> {
pub(crate) fn new_test_ext_with_candidate_holes() -> runtime_io::TestExternalities {
let mut t = ExtBuilder::default().build();
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
<elections::Candidates<Test>>::put(vec![0, 0, 1]);
elections::CandidateCount::put(1);
<elections::RegisterInfoOf<Test>>::insert(1, (0, 2));
+142 -125
View File
@@ -22,11 +22,10 @@ use crate::mock::*;
use crate::*;
use support::{assert_ok, assert_err, assert_noop};
use sr_primitives::set_and_run_with_externalities;
#[test]
fn params_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_eq!(Elections::next_vote_from(1), 4);
assert_eq!(Elections::next_vote_from(4), 4);
@@ -53,7 +52,7 @@ fn params_should_work() {
#[test]
fn chunking_bool_to_flag_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(Elections::bool_to_flag(vec![]), vec![]);
assert_eq!(Elections::bool_to_flag(vec![false]), vec![0]);
assert_eq!(Elections::bool_to_flag(vec![true]), vec![1]);
@@ -98,7 +97,7 @@ fn chunking_bool_to_flag_should_work() {
#[test]
fn chunking_voter_set_growth_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
// create 65. 64 (set0) + 1 (set1)
@@ -122,7 +121,7 @@ fn chunking_voter_set_growth_should_work() {
#[test]
fn chunking_voter_set_reclaim_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
(1..=129).for_each(|i| vote(i, 0));
@@ -159,7 +158,7 @@ fn chunking_voter_set_reclaim_should_work() {
#[test]
fn chunking_approvals_set_growth_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
// create candidates and voters.
(1..=250).for_each(|i| create_candidate(i, (i-1) as u32));
(1..=250).for_each(|i| vote(i, i as usize));
@@ -221,7 +220,7 @@ fn chunking_approvals_set_growth_should_work() {
#[test]
fn chunking_cell_status_works() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
(1..=63).for_each(|i| vote(i, 0));
@@ -240,7 +239,7 @@ fn chunking_cell_status_works() {
#[test]
fn chunking_voter_index_does_not_take_holes_into_account() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
// create 65. 64 (set0) + 1 (set1)
@@ -265,7 +264,7 @@ fn chunking_voter_index_does_not_take_holes_into_account() {
#[test]
fn chunking_approval_storage_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::submit_candidacy(Origin::signed(3), 1));
@@ -285,7 +284,7 @@ fn chunking_approval_storage_should_work() {
#[test]
fn voting_initial_set_approvals_ignores_voter_index() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
// Last argument is essentially irrelevant. You might get or miss a tip.
@@ -299,7 +298,7 @@ fn voting_initial_set_approvals_ignores_voter_index() {
}
#[test]
fn voting_bad_approval_index_slashes_voters_and_bond_reduces_stake() {
set_and_run_with_externalities(&mut ExtBuilder::default().voting_fee(5).voter_bond(2).build(), || {
ExtBuilder::default().voting_fee(5).voter_bond(2).build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
(1..=63).for_each(|i| vote(i, 0));
@@ -329,7 +328,7 @@ fn voting_bad_approval_index_slashes_voters_and_bond_reduces_stake() {
#[test]
fn voting_subsequent_set_approvals_checks_voter_index() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::set_approvals(Origin::signed(3), vec![], 0, 0, 30));
@@ -353,7 +352,7 @@ fn voting_subsequent_set_approvals_checks_voter_index() {
#[test]
fn voting_cannot_lock_less_than_limit() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_noop!(
@@ -366,7 +365,7 @@ fn voting_cannot_lock_less_than_limit() {
#[test]
fn voting_locking_more_than_total_balance_is_moot() {
set_and_run_with_externalities(&mut ExtBuilder::default().voter_bond(2).build(), || {
ExtBuilder::default().voter_bond(2).build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_eq!(balances(&3), (30, 0));
@@ -382,7 +381,7 @@ fn voting_locking_more_than_total_balance_is_moot() {
#[test]
fn voting_locking_stake_and_reserving_bond_works() {
set_and_run_with_externalities(&mut ExtBuilder::default().voter_bond(2).build(), || {
ExtBuilder::default().voter_bond(2).build().execute_with(|| {
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0));
assert_eq!(balances(&2), (20, 0));
@@ -408,7 +407,7 @@ fn voting_locking_stake_and_reserving_bond_works() {
#[test]
fn voting_without_any_candidate_count_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_eq!(Elections::candidates().len(), 0);
@@ -422,7 +421,7 @@ fn voting_without_any_candidate_count_should_not_work() {
#[test]
fn voting_setting_an_approval_vote_count_more_than_candidate_count_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0));
@@ -437,7 +436,7 @@ fn voting_setting_an_approval_vote_count_more_than_candidate_count_should_not_wo
#[test]
fn voting_resubmitting_approvals_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0));
@@ -456,7 +455,7 @@ fn voting_resubmitting_approvals_should_work() {
#[test]
fn voting_retracting_voter_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0));
@@ -501,7 +500,7 @@ fn voting_retracting_voter_should_work() {
#[test]
fn voting_invalid_retraction_index_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_ok!(Elections::submit_candidacy(Origin::signed(3), 0));
@@ -514,7 +513,7 @@ fn voting_invalid_retraction_index_should_not_work() {
#[test]
fn voting_overflow_retraction_index_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_ok!(Elections::submit_candidacy(Origin::signed(3), 0));
@@ -525,7 +524,7 @@ fn voting_overflow_retraction_index_should_not_work() {
#[test]
fn voting_non_voter_retraction_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_ok!(Elections::submit_candidacy(Origin::signed(3), 0));
@@ -536,7 +535,7 @@ fn voting_non_voter_retraction_should_not_work() {
#[test]
fn retracting_inactive_voter_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20));
@@ -570,7 +569,7 @@ fn retracting_inactive_voter_should_work() {
#[test]
fn retracting_inactive_voter_with_other_candidates_in_slots_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().voter_bond(2).build(), || {
ExtBuilder::default().voter_bond(2).build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20));
@@ -605,7 +604,7 @@ fn retracting_inactive_voter_with_other_candidates_in_slots_should_work() {
#[test]
fn retracting_inactive_voter_with_bad_reporter_index_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20));
@@ -634,7 +633,7 @@ fn retracting_inactive_voter_with_bad_reporter_index_should_not_work() {
#[test]
fn retracting_inactive_voter_with_bad_target_index_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20));
@@ -663,7 +662,7 @@ fn retracting_inactive_voter_with_bad_target_index_should_not_work() {
#[test]
fn retracting_active_voter_should_slash_reporter() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::submit_candidacy(Origin::signed(3), 1));
@@ -711,7 +710,7 @@ fn retracting_active_voter_should_slash_reporter() {
#[test]
fn retracting_inactive_voter_by_nonvoter_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20));
@@ -740,7 +739,7 @@ fn retracting_inactive_voter_by_nonvoter_should_not_work() {
#[test]
fn candidacy_simple_candidate_submission_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert_eq!(Elections::candidate_reg_info(1), None);
@@ -768,7 +767,7 @@ fn candidacy_simple_candidate_submission_should_work() {
fn candidacy_submission_using_free_slot_should_work() {
let mut t = new_test_ext_with_candidate_holes();
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
System::set_block_number(1);
assert_eq!(Elections::candidates(), vec![0, 0, 1]);
@@ -784,7 +783,7 @@ fn candidacy_submission_using_free_slot_should_work() {
fn candidacy_submission_using_alternative_free_slot_should_work() {
let mut t = new_test_ext_with_candidate_holes();
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
System::set_block_number(1);
assert_eq!(Elections::candidates(), vec![0, 0, 1]);
@@ -800,7 +799,7 @@ fn candidacy_submission_using_alternative_free_slot_should_work() {
fn candidacy_submission_not_using_free_slot_should_not_work() {
let mut t = new_test_ext_with_candidate_holes();
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
System::set_block_number(1);
assert_noop!(
Elections::submit_candidacy(Origin::signed(4), 3),
@@ -811,7 +810,7 @@ fn candidacy_submission_not_using_free_slot_should_not_work() {
#[test]
fn candidacy_bad_candidate_slot_submission_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert_noop!(
@@ -823,7 +822,7 @@ fn candidacy_bad_candidate_slot_submission_should_not_work() {
#[test]
fn candidacy_non_free_candidate_slot_submission_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0));
@@ -837,7 +836,7 @@ fn candidacy_non_free_candidate_slot_submission_should_not_work() {
#[test]
fn candidacy_dupe_candidate_submission_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0));
@@ -851,7 +850,7 @@ fn candidacy_dupe_candidate_submission_should_not_work() {
#[test]
fn candidacy_poor_candidate_submission_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_eq!(Elections::candidates(), Vec::<u64>::new());
assert_noop!(
@@ -863,7 +862,7 @@ fn candidacy_poor_candidate_submission_should_not_work() {
#[test]
fn election_voting_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0));
@@ -892,7 +891,7 @@ fn election_voting_should_work() {
#[test]
fn election_proxy_voting_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(1);
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 0));
@@ -933,7 +932,7 @@ fn election_proxy_voting_should_work() {
#[test]
fn election_simple_tally_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert!(!Elections::presentation_active());
@@ -972,7 +971,7 @@ fn election_simple_tally_should_work() {
#[test]
fn election_seats_should_be_released() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 1));
@@ -1006,7 +1005,7 @@ fn election_seats_should_be_released() {
#[test]
fn election_presentations_with_zero_staked_deposit_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20));
@@ -1022,7 +1021,7 @@ fn election_presentations_with_zero_staked_deposit_should_not_work() {
#[test]
fn election_double_presentations_should_be_punished() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert!(Balances::can_slash(&4, 10));
System::set_block_number(4);
@@ -1045,7 +1044,7 @@ fn election_double_presentations_should_be_punished() {
#[test]
fn election_presenting_for_double_election_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_eq!(Elections::submit_candidacy(Origin::signed(2), 0), Ok(()));
assert_ok!(Elections::set_approvals(Origin::signed(2), vec![true], 0, 0, 20));
@@ -1072,7 +1071,7 @@ fn election_presenting_for_double_election_should_not_work() {
#[test]
fn election_presenting_loser_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0));
assert_ok!(Elections::set_approvals(Origin::signed(6), vec![true], 0, 0, 60));
@@ -1105,7 +1104,7 @@ fn election_presenting_loser_should_not_work() {
#[test]
fn election_presenting_loser_first_should_not_matter() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0));
assert_ok!(Elections::set_approvals(Origin::signed(6), vec![true], 0, 0, 60));
@@ -1137,7 +1136,7 @@ fn election_presenting_loser_first_should_not_matter() {
#[test]
fn election_present_outside_of_presentation_period_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert!(!Elections::presentation_active());
assert_noop!(
@@ -1149,7 +1148,7 @@ fn election_present_outside_of_presentation_period_should_not_work() {
#[test]
fn election_present_with_invalid_vote_index_should_not_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(2), 0));
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 1));
@@ -1165,33 +1164,35 @@ fn election_present_with_invalid_vote_index_should_not_work() {
#[test]
fn election_present_when_presenter_is_poor_should_not_work() {
let test_present = |p| {
set_and_run_with_externalities(&mut ExtBuilder::default()
ExtBuilder::default()
.voting_fee(5)
.voter_bond(2)
.bad_presentation_punishment(p)
.build(),
|| {
System::set_block_number(4);
let _ = Balances::make_free_balance_be(&1, 15);
assert!(!Elections::presentation_active());
.build()
.execute_with(|| {
System::set_block_number(4);
let _ = Balances::make_free_balance_be(&1, 15);
assert!(!Elections::presentation_active());
assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0)); // -3
assert_eq!(Balances::free_balance(&1), 12);
assert_ok!(Elections::set_approvals(Origin::signed(1), vec![true], 0, 0, 15)); // -2 -5
assert_ok!(Elections::end_block(System::block_number()));
// -3
assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0));
assert_eq!(Balances::free_balance(&1), 12);
// -2 -5
assert_ok!(Elections::set_approvals(Origin::signed(1), vec![true], 0, 0, 15));
assert_ok!(Elections::end_block(System::block_number()));
System::set_block_number(6);
assert_eq!(Balances::free_balance(&1), 5);
assert_eq!(Balances::reserved_balance(&1), 5);
if p > 5 {
assert_noop!(Elections::present_winner(
Origin::signed(1), 1, 10, 0),
"presenter must have sufficient slashable funds"
);
} else {
assert_ok!(Elections::present_winner(Origin::signed(1), 1, 10, 0));
}
});
System::set_block_number(6);
assert_eq!(Balances::free_balance(&1), 5);
assert_eq!(Balances::reserved_balance(&1), 5);
if p > 5 {
assert_noop!(Elections::present_winner(
Origin::signed(1), 1, 10, 0),
"presenter must have sufficient slashable funds"
);
} else {
assert_ok!(Elections::present_winner(Origin::signed(1), 1, 10, 0));
}
});
};
test_present(4);
test_present(6);
@@ -1199,7 +1200,7 @@ fn election_present_when_presenter_is_poor_should_not_work() {
#[test]
fn election_invalid_present_tally_should_slash() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert!(!Elections::presentation_active());
assert_eq!(Balances::total_balance(&4), 40);
@@ -1219,7 +1220,7 @@ fn election_invalid_present_tally_should_slash() {
#[test]
fn election_runners_up_should_be_kept() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert!(!Elections::presentation_active());
@@ -1280,7 +1281,7 @@ fn election_runners_up_should_be_kept() {
#[test]
fn election_second_tally_should_use_runners_up() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
System::set_block_number(4);
assert_ok!(Elections::submit_candidacy(Origin::signed(1), 0));
assert_ok!(Elections::set_approvals(Origin::signed(6), vec![true], 0, 0, 60));
@@ -1335,7 +1336,7 @@ fn election_second_tally_should_use_runners_up() {
#[test]
fn election_loser_candidates_bond_gets_slashed() {
set_and_run_with_externalities(&mut ExtBuilder::default().desired_seats(1).build(), || {
ExtBuilder::default().desired_seats(1).build().execute_with(|| {
System::set_block_number(4);
assert!(!Elections::presentation_active());
@@ -1374,7 +1375,7 @@ fn election_loser_candidates_bond_gets_slashed() {
#[test]
fn pot_accumulating_weight_and_decaying_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().balance_factor(10).build(), || {
ExtBuilder::default().balance_factor(10).build().execute_with(|| {
System::set_block_number(4);
assert!(!Elections::presentation_active());
@@ -1502,7 +1503,7 @@ fn pot_accumulating_weight_and_decaying_should_work() {
#[test]
fn pot_winning_resets_accumulated_pot() {
set_and_run_with_externalities(&mut ExtBuilder::default().balance_factor(10).build(), || {
ExtBuilder::default().balance_factor(10).build().execute_with(|| {
System::set_block_number(4);
assert!(!Elections::presentation_active());
@@ -1564,72 +1565,88 @@ fn pot_winning_resets_accumulated_pot() {
#[test]
fn pot_resubmitting_approvals_stores_pot() {
set_and_run_with_externalities(&mut ExtBuilder::default()
ExtBuilder::default()
.voter_bond(0)
.voting_fee(0)
.balance_factor(10)
.build(),
|| { System::set_block_number(4);
assert!(!Elections::presentation_active());
.build()
.execute_with(|| {
System::set_block_number(4);
assert!(!Elections::presentation_active());
assert_ok!(Elections::submit_candidacy(Origin::signed(6), 0));
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 1));
assert_ok!(Elections::submit_candidacy(Origin::signed(1), 2));
assert_ok!(Elections::submit_candidacy(Origin::signed(6), 0));
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 1));
assert_ok!(Elections::submit_candidacy(Origin::signed(1), 2));
assert_ok!(Elections::set_approvals(Origin::signed(6), vec![true, false, false], 0, 0, 600));
assert_ok!(Elections::set_approvals(Origin::signed(5), vec![false, true, false], 0, 1, 500));
assert_ok!(Elections::set_approvals(Origin::signed(1), vec![false, false, true], 0, 2, 100));
assert_ok!(
Elections::set_approvals(Origin::signed(6), vec![true, false, false], 0, 0, 600),
);
assert_ok!(
Elections::set_approvals(Origin::signed(5), vec![false, true, false], 0, 1, 500),
);
assert_ok!(
Elections::set_approvals(Origin::signed(1), vec![false, false, true], 0, 2, 100),
);
assert_ok!(Elections::end_block(System::block_number()));
assert_ok!(Elections::end_block(System::block_number()));
System::set_block_number(6);
assert!(Elections::presentation_active());
System::set_block_number(6);
assert!(Elections::presentation_active());
assert_eq!(Elections::present_winner(Origin::signed(6), 6, 600, 0), Ok(()));
assert_eq!(Elections::present_winner(Origin::signed(5), 5, 500, 0), Ok(()));
assert_eq!(Elections::present_winner(Origin::signed(1), 1, 100, 0), Ok(()));
assert_eq!(Elections::leaderboard(), Some(vec![(0, 0), (100, 1), (500, 5), (600, 6)]));
assert_ok!(Elections::end_block(System::block_number()));
assert_eq!(Elections::present_winner(Origin::signed(6), 6, 600, 0), Ok(()));
assert_eq!(Elections::present_winner(Origin::signed(5), 5, 500, 0), Ok(()));
assert_eq!(Elections::present_winner(Origin::signed(1), 1, 100, 0), Ok(()));
assert_eq!(Elections::leaderboard(), Some(vec![(0, 0), (100, 1), (500, 5), (600, 6)]));
assert_ok!(Elections::end_block(System::block_number()));
assert_eq!(Elections::members(), vec![(6, 11), (5, 11)]);
assert_eq!(Elections::members(), vec![(6, 11), (5, 11)]);
System::set_block_number(12);
assert_ok!(Elections::retract_voter(Origin::signed(6), 0));
assert_ok!(Elections::retract_voter(Origin::signed(5), 1));
assert_ok!(Elections::submit_candidacy(Origin::signed(6), 0));
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 1));
assert_ok!(Elections::set_approvals(Origin::signed(6), vec![true, false, false], 1, 0, 600));
assert_ok!(Elections::set_approvals(Origin::signed(5), vec![false, true, false], 1, 1, 500));
// give 1 some new high balance
let _ = Balances::make_free_balance_be(&1, 997);
assert_ok!(Elections::set_approvals(Origin::signed(1), vec![false, false, true], 1, 2, 1000));
assert_eq!(Elections::voter_info(1).unwrap(),
VoterInfo {
stake: 1000, // 997 + 3 which is candidacy bond.
pot: Elections::get_offset(100, 1),
last_active: 1,
last_win: 1,
}
);
assert_ok!(Elections::end_block(System::block_number()));
System::set_block_number(12);
assert_ok!(Elections::retract_voter(Origin::signed(6), 0));
assert_ok!(Elections::retract_voter(Origin::signed(5), 1));
assert_ok!(Elections::submit_candidacy(Origin::signed(6), 0));
assert_ok!(Elections::submit_candidacy(Origin::signed(5), 1));
assert_ok!(
Elections::set_approvals(Origin::signed(6), vec![true, false, false], 1, 0, 600),
);
assert_ok!(
Elections::set_approvals(Origin::signed(5), vec![false, true, false], 1, 1, 500),
);
// give 1 some new high balance
let _ = Balances::make_free_balance_be(&1, 997);
assert_ok!(
Elections::set_approvals(Origin::signed(1), vec![false, false, true], 1, 2, 1000),
);
assert_eq!(Elections::voter_info(1).unwrap(),
VoterInfo {
stake: 1000, // 997 + 3 which is candidacy bond.
pot: Elections::get_offset(100, 1),
last_active: 1,
last_win: 1,
}
);
assert_ok!(Elections::end_block(System::block_number()));
assert_eq!(Elections::members(), vec![(6, 11), (5, 11)]);
assert_eq!(Elections::members(), vec![(6, 11), (5, 11)]);
System::set_block_number(14);
assert!(Elections::presentation_active());
assert_eq!(Elections::present_winner(Origin::signed(6), 6, 600, 1), Ok(()));
assert_eq!(Elections::present_winner(Origin::signed(5), 5, 500, 1), Ok(()));
assert_eq!(Elections::present_winner(Origin::signed(1), 1, 1000 + 96 /* pot */, 1), Ok(()));
assert_eq!(Elections::leaderboard(), Some(vec![(0, 0), (500, 5), (600, 6), (1096, 1)]));
assert_ok!(Elections::end_block(System::block_number()));
System::set_block_number(14);
assert!(Elections::presentation_active());
assert_eq!(Elections::present_winner(Origin::signed(6), 6, 600, 1), Ok(()));
assert_eq!(Elections::present_winner(Origin::signed(5), 5, 500, 1), Ok(()));
assert_eq!(
Elections::present_winner(Origin::signed(1), 1, 1000 + 96 /* pot */, 1),
Ok(()),
);
assert_eq!(Elections::leaderboard(), Some(vec![(0, 0), (500, 5), (600, 6), (1096, 1)]));
assert_ok!(Elections::end_block(System::block_number()));
assert_eq!(Elections::members(), vec![(1, 19), (6, 19)]);
})
assert_eq!(Elections::members(), vec![(1, 19), (6, 19)]);
})
}
#[test]
fn pot_get_offset_should_work() {
set_and_run_with_externalities(&mut ExtBuilder::default().build(), || {
ExtBuilder::default().build().execute_with(|| {
assert_eq!(Elections::get_offset(100, 0), 0);
assert_eq!(Elections::get_offset(100, 1), 96);
assert_eq!(Elections::get_offset(100, 2), 96 + 93);
@@ -1653,7 +1670,7 @@ fn pot_get_offset_should_work() {
#[test]
fn pot_get_offset_with_zero_decay() {
set_and_run_with_externalities(&mut ExtBuilder::default().decay_ratio(0).build(), || {
ExtBuilder::default().decay_ratio(0).build().execute_with(|| {
assert_eq!(Elections::get_offset(100, 0), 0);
assert_eq!(Elections::get_offset(100, 1), 0);
assert_eq!(Elections::get_offset(100, 2), 0);
+4 -4
View File
@@ -638,7 +638,7 @@ mod tests {
// 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.
use sr_primitives::{
set_and_run_with_externalities, Perbill, weights::GetDispatchInfo, testing::Header,
Perbill, weights::GetDispatchInfo, testing::Header,
traits::{BlakeTwo256, OnInitialize, OnFinalize, IdentityLookup},
};
@@ -719,7 +719,7 @@ mod tests {
#[test]
fn it_works_for_optional_value() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// Check that GenesisBuilder works properly.
assert_eq!(Example::dummy(), Some(42));
@@ -740,7 +740,7 @@ mod tests {
#[test]
fn it_works_for_default_value() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_eq!(Example::foo(), 24);
assert_ok!(Example::accumulate_foo(Origin::signed(1), 1));
assert_eq!(Example::foo(), 25);
@@ -749,7 +749,7 @@ mod tests {
#[test]
fn signed_ext_watch_dummy_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let call = <Call<Test>>::set_dummy(10);
let info = DispatchInfo::default();
+9 -10
View File
@@ -298,7 +298,6 @@ mod tests {
generic::Era, Perbill, DispatchError, weights::Weight, testing::{Digest, Header, Block},
traits::{Bounded, Header as HeaderT, BlakeTwo256, IdentityLookup, ConvertInto},
transaction_validity::{InvalidTransaction, UnknownTransaction}, ApplyError,
set_and_run_with_externalities,
};
use support::{
impl_outer_event, impl_outer_origin, parameter_types, impl_outer_dispatch,
@@ -420,7 +419,7 @@ mod tests {
let xt = sr_primitives::testing::TestXt(sign_extra(1, 0, 0), Call::Balances(BalancesCall::transfer(2, 69)));
let weight = xt.get_dispatch_info().weight as u64;
let mut t = runtime_io::TestExternalities::new(t);
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
Executive::initialize_block(&Header::new(
1,
H256::default(),
@@ -446,7 +445,7 @@ mod tests {
#[test]
fn block_import_works() {
set_and_run_with_externalities(&mut new_test_ext(1), || {
new_test_ext(1).execute_with(|| {
Executive::execute_block(Block {
header: Header {
parent_hash: [69u8; 32].into(),
@@ -463,7 +462,7 @@ mod tests {
#[test]
#[should_panic]
fn block_import_of_bad_state_root_fails() {
set_and_run_with_externalities(&mut new_test_ext(1), || {
new_test_ext(1).execute_with(|| {
Executive::execute_block(Block {
header: Header {
parent_hash: [69u8; 32].into(),
@@ -480,7 +479,7 @@ mod tests {
#[test]
#[should_panic]
fn block_import_of_bad_extrinsic_root_fails() {
set_and_run_with_externalities(&mut new_test_ext(1), || {
new_test_ext(1).execute_with(|| {
Executive::execute_block(Block {
header: Header {
parent_hash: [69u8; 32].into(),
@@ -499,7 +498,7 @@ mod tests {
let mut t = new_test_ext(1);
// bad nonce check!
let xt = sr_primitives::testing::TestXt(sign_extra(1, 30, 0), Call::Balances(BalancesCall::transfer(33, 69)));
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
Executive::initialize_block(&Header::new(
1,
H256::default(),
@@ -521,7 +520,7 @@ mod tests {
let encoded_len = encoded.len() as Weight;
let limit = AvailableBlockRatio::get() * MaximumBlockWeight::get();
let num_to_exhaust_block = limit / encoded_len;
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
Executive::initialize_block(&Header::new(
1,
H256::default(),
@@ -557,7 +556,7 @@ mod tests {
let x2 = sr_primitives::testing::TestXt(sign_extra(1, 2, 0), Call::Balances(BalancesCall::transfer(33, 0)));
let len = xt.clone().encode().len() as u32;
let mut t = new_test_ext(1);
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(<system::Module<Runtime>>::all_extrinsics_weight(), 0);
assert_eq!(<system::Module<Runtime>>::all_extrinsics_weight(), 0);
@@ -581,7 +580,7 @@ mod tests {
let xt = sr_primitives::testing::TestXt(None, Call::Balances(BalancesCall::set_balance(33, 69, 69)));
let mut t = new_test_ext(1);
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
assert_eq!(Executive::validate_transaction(xt.clone()), Ok(Default::default()));
assert_eq!(
Executive::apply_extrinsic(xt),
@@ -599,7 +598,7 @@ mod tests {
let id: LockIdentifier = *b"0 ";
let execute_with_lock = |lock: WithdrawReasons| {
let mut t = new_test_ext(1);
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
<balances::Module<Runtime> as LockableCurrency<u64>>::set_lock(
id,
&1,
+4 -4
View File
@@ -250,7 +250,7 @@ mod tests {
use runtime_io::TestExternalities;
use primitives::H256;
use sr_primitives::{
set_and_run_with_externalities, testing::Header, Perbill,
testing::Header, Perbill,
traits::{BlakeTwo256, IdentityLookup, OnFinalize, Header as HeaderT},
};
use support::{assert_ok, impl_outer_origin, parameter_types};
@@ -322,7 +322,7 @@ mod tests {
#[test]
fn median_works() {
let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
set_and_run_with_externalities(&mut TestExternalities::new(t), || {
TestExternalities::new(t).execute_with(|| {
FinalityTracker::update_hint(Some(500));
assert_eq!(FinalityTracker::median(), 250);
assert!(NOTIFICATIONS.with(|n| n.borrow().is_empty()));
@@ -332,7 +332,7 @@ mod tests {
#[test]
fn notifies_when_stalled() {
let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
set_and_run_with_externalities(&mut TestExternalities::new(t), || {
TestExternalities::new(t).execute_with(|| {
let mut parent_hash = System::parent_hash();
for i in 2..106 {
System::initialize(&i, &parent_hash, &Default::default(), &Default::default());
@@ -351,7 +351,7 @@ mod tests {
#[test]
fn recent_notifications_prevent_stalling() {
let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
set_and_run_with_externalities(&mut TestExternalities::new(t), || {
TestExternalities::new(t).execute_with(|| {
let mut parent_hash = System::parent_hash();
for i in 2..106 {
System::initialize(&i, &parent_hash, &Default::default(), &Default::default());
File diff suppressed because it is too large Load Diff
+7 -7
View File
@@ -18,7 +18,7 @@
#![cfg(test)]
use sr_primitives::{set_and_run_with_externalities, testing::Digest, traits::{Header, OnFinalize}};
use sr_primitives::{testing::Digest, traits::{Header, OnFinalize}};
use crate::mock::*;
use system::{EventRecord, Phase};
use codec::{Decode, Encode};
@@ -27,7 +27,7 @@ use super::*;
#[test]
fn authorities_change_logged() {
set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || {
new_test_ext(vec![(1, 1), (2, 1), (3, 1)]).execute_with(|| {
System::initialize(&1, &Default::default(), &Default::default(), &Default::default());
Grandpa::schedule_change(to_authorities(vec![(4, 1), (5, 1), (6, 1)]), 0, None).unwrap();
@@ -55,7 +55,7 @@ fn authorities_change_logged() {
#[test]
fn authorities_change_logged_after_delay() {
set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || {
new_test_ext(vec![(1, 1), (2, 1), (3, 1)]).execute_with(|| {
System::initialize(&1, &Default::default(), &Default::default(), &Default::default());
Grandpa::schedule_change(to_authorities(vec![(4, 1), (5, 1), (6, 1)]), 1, None).unwrap();
Grandpa::on_finalize(1);
@@ -88,7 +88,7 @@ fn authorities_change_logged_after_delay() {
#[test]
fn cannot_schedule_change_when_one_pending() {
set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || {
new_test_ext(vec![(1, 1), (2, 1), (3, 1)]).execute_with(|| {
System::initialize(&1, &Default::default(), &Default::default(), &Default::default());
Grandpa::schedule_change(to_authorities(vec![(4, 1), (5, 1), (6, 1)]), 1, None).unwrap();
assert!(<PendingChange<Test>>::exists());
@@ -131,7 +131,7 @@ fn new_decodes_from_old() {
#[test]
fn dispatch_forced_change() {
set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || {
new_test_ext(vec![(1, 1), (2, 1), (3, 1)]).execute_with(|| {
System::initialize(&1, &Default::default(), &Default::default(), &Default::default());
Grandpa::schedule_change(
to_authorities(vec![(4, 1), (5, 1), (6, 1)]),
@@ -203,7 +203,7 @@ fn dispatch_forced_change() {
#[test]
fn schedule_pause_only_when_live() {
set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || {
new_test_ext(vec![(1, 1), (2, 1), (3, 1)]).execute_with(|| {
// we schedule a pause at block 1 with delay of 1
System::initialize(&1, &Default::default(), &Default::default(), &Default::default());
Grandpa::schedule_pause(1).unwrap();
@@ -238,7 +238,7 @@ fn schedule_pause_only_when_live() {
#[test]
fn schedule_resume_only_when_paused() {
set_and_run_with_externalities(&mut new_test_ext(vec![(1, 1), (2, 1), (3, 1)]), || {
new_test_ext(vec![(1, 1), (2, 1), (3, 1)]).execute_with(|| {
System::initialize(&1, &Default::default(), &Default::default(), &Default::default());
// the set is currently live, resuming it is an error
+6 -7
View File
@@ -23,8 +23,7 @@ use crate::mock::*;
use offchain::testing::TestOffchainExt;
use primitives::offchain::{OpaquePeerId, OffchainExt};
use support::{dispatch, assert_noop};
use sr_primitives::{set_and_run_with_externalities, testing::UintAuthorityId};
use sr_primitives::testing::UintAuthorityId;
#[test]
fn test_unresponsiveness_slash_fraction() {
@@ -48,7 +47,7 @@ fn test_unresponsiveness_slash_fraction() {
#[test]
fn should_report_offline_validators() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let block = 1;
System::set_block_number(block);
@@ -124,7 +123,7 @@ fn heartbeat(
#[test]
fn should_mark_online_validator_when_heartbeat_is_received() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
advance_session();
// given
VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 3, 4, 5, 6]));
@@ -159,7 +158,7 @@ fn should_mark_online_validator_when_heartbeat_is_received() {
#[test]
fn late_heartbeat_should_fail() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
advance_session();
// given
VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 4, 4, 5, 6]));
@@ -182,7 +181,7 @@ fn should_generate_heartbeats() {
let (offchain, state) = TestOffchainExt::new();
ext.register_extension(OffchainExt::new(offchain));
set_and_run_with_externalities(&mut ext, || {
ext.execute_with(|| {
// given
let block = 1;
System::set_block_number(block);
@@ -218,7 +217,7 @@ fn should_generate_heartbeats() {
#[test]
fn should_cleanup_received_heartbeats_on_session_end() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
advance_session();
VALIDATORS.with(|l| *l.borrow_mut() = Some(vec![1, 2, 3]));
+26 -39
View File
@@ -20,61 +20,48 @@
use super::*;
use crate::mock::{Indices, new_test_ext, make_account, kill_account, TestIsDeadAccount};
use sr_primitives::set_and_run_with_externalities;
#[test]
fn indexing_lookup_should_work() {
set_and_run_with_externalities(
&mut new_test_ext(),
|| {
assert_eq!(Indices::lookup_index(0), Some(1));
assert_eq!(Indices::lookup_index(1), Some(2));
assert_eq!(Indices::lookup_index(2), Some(3));
assert_eq!(Indices::lookup_index(3), Some(4));
assert_eq!(Indices::lookup_index(4), None);
},
);
new_test_ext().execute_with(|| {
assert_eq!(Indices::lookup_index(0), Some(1));
assert_eq!(Indices::lookup_index(1), Some(2));
assert_eq!(Indices::lookup_index(2), Some(3));
assert_eq!(Indices::lookup_index(3), Some(4));
assert_eq!(Indices::lookup_index(4), None);
});
}
#[test]
fn default_indexing_on_new_accounts_should_work() {
set_and_run_with_externalities(
&mut new_test_ext(),
|| {
assert_eq!(Indices::lookup_index(4), None);
make_account(5);
assert_eq!(Indices::lookup_index(4), Some(5));
},
);
new_test_ext().execute_with(|| {
assert_eq!(Indices::lookup_index(4), None);
make_account(5);
assert_eq!(Indices::lookup_index(4), Some(5));
});
}
#[test]
fn reclaim_indexing_on_new_accounts_should_work() {
set_and_run_with_externalities(
&mut new_test_ext(),
|| {
assert_eq!(Indices::lookup_index(1), Some(2));
assert_eq!(Indices::lookup_index(4), None);
new_test_ext().execute_with(|| {
assert_eq!(Indices::lookup_index(1), Some(2));
assert_eq!(Indices::lookup_index(4), None);
kill_account(2); // index 1 no longer locked to id 2
kill_account(2); // index 1 no longer locked to id 2
make_account(1 + 256); // id 257 takes index 1.
assert_eq!(Indices::lookup_index(1), Some(257));
},
);
make_account(1 + 256); // id 257 takes index 1.
assert_eq!(Indices::lookup_index(1), Some(257));
});
}
#[test]
fn alive_account_should_prevent_reclaim() {
set_and_run_with_externalities(
&mut new_test_ext(),
|| {
assert!(!TestIsDeadAccount::is_dead_account(&2));
assert_eq!(Indices::lookup_index(1), Some(2));
assert_eq!(Indices::lookup_index(4), None);
new_test_ext().execute_with(|| {
assert!(!TestIsDeadAccount::is_dead_account(&2));
assert_eq!(Indices::lookup_index(1), Some(2));
assert_eq!(Indices::lookup_index(4), None);
make_account(1 + 256); // id 257 takes index 1.
assert_eq!(Indices::lookup_index(4), Some(257));
},
);
make_account(1 + 256); // id 257 takes index 1.
assert_eq!(Indices::lookup_index(4), Some(257));
});
}
+6 -9
View File
@@ -196,10 +196,7 @@ mod tests {
use primitives::H256;
// 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 requried.
use sr_primitives::{
Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header,
set_and_run_with_externalities,
};
use sr_primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
use system::EnsureSignedBy;
impl_outer_origin! {
@@ -293,7 +290,7 @@ mod tests {
#[test]
fn query_membership_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_eq!(Membership::members(), vec![10, 20, 30]);
assert_eq!(MEMBERS.with(|m| m.borrow().clone()), vec![10, 20, 30]);
});
@@ -301,7 +298,7 @@ mod tests {
#[test]
fn add_member_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_noop!(Membership::add_member(Origin::signed(5), 15), "bad origin");
assert_noop!(Membership::add_member(Origin::signed(1), 10), "already a member");
assert_ok!(Membership::add_member(Origin::signed(1), 15));
@@ -312,7 +309,7 @@ mod tests {
#[test]
fn remove_member_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_noop!(Membership::remove_member(Origin::signed(5), 20), "bad origin");
assert_noop!(Membership::remove_member(Origin::signed(2), 15), "not a member");
assert_ok!(Membership::remove_member(Origin::signed(2), 20));
@@ -323,7 +320,7 @@ mod tests {
#[test]
fn swap_member_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_noop!(Membership::swap_member(Origin::signed(5), 10, 25), "bad origin");
assert_noop!(Membership::swap_member(Origin::signed(3), 15, 25), "not a member");
assert_noop!(Membership::swap_member(Origin::signed(3), 10, 30), "already a member");
@@ -337,7 +334,7 @@ mod tests {
#[test]
fn reset_members_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_noop!(Membership::reset_members(Origin::signed(1), vec![20, 40, 30]), "bad origin");
assert_ok!(Membership::reset_members(Origin::signed(4), vec![20, 40, 30]));
assert_eq!(Membership::members(), vec![20, 30, 40]);
+7 -8
View File
@@ -24,11 +24,10 @@ use crate::mock::{
offence_reports,
};
use system::{EventRecord, Phase};
use sr_primitives::set_and_run_with_externalities;
#[test]
fn should_report_an_authority_and_trigger_on_offence() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let time_slot = 42;
assert_eq!(offence_reports(KIND, time_slot), vec![]);
@@ -51,7 +50,7 @@ fn should_report_an_authority_and_trigger_on_offence() {
#[test]
fn should_calculate_the_fraction_correctly() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let time_slot = 42;
assert_eq!(offence_reports(KIND, time_slot), vec![]);
@@ -83,7 +82,7 @@ fn should_calculate_the_fraction_correctly() {
#[test]
fn should_not_report_the_same_authority_twice_in_the_same_slot() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let time_slot = 42;
assert_eq!(offence_reports(KIND, time_slot), vec![]);
@@ -113,7 +112,7 @@ fn should_not_report_the_same_authority_twice_in_the_same_slot() {
#[test]
fn should_report_in_different_time_slot() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let time_slot = 42;
assert_eq!(offence_reports(KIND, time_slot), vec![]);
@@ -143,7 +142,7 @@ fn should_report_in_different_time_slot() {
#[test]
fn should_deposit_event() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let time_slot = 42;
assert_eq!(offence_reports(KIND, time_slot), vec![]);
@@ -171,7 +170,7 @@ fn should_deposit_event() {
#[test]
fn doesnt_deposit_event_for_dups() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let time_slot = 42;
assert_eq!(offence_reports(KIND, time_slot), vec![]);
@@ -208,7 +207,7 @@ fn doesnt_deposit_event_for_dups() {
fn should_properly_count_offences() {
// We report two different authorities for the same issue. Ultimately, the 1st authority
// should have `count` equal 2 and the count of the 2nd one should be equal to 1.
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let time_slot = 42;
assert_eq!(offence_reports(KIND, time_slot), vec![]);
@@ -155,7 +155,6 @@ mod tests {
use primitives::H256;
use sr_primitives::{
Perbill, traits::{BlakeTwo256, OnInitialize, Header as _, IdentityLookup}, testing::Header,
set_and_run_with_externalities,
};
use support::{impl_outer_origin, parameter_types, traits::Randomness};
@@ -222,7 +221,7 @@ mod tests {
#[test]
fn test_random_material_parital() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let genesis_hash = System::parent_hash();
setup_blocks(38);
@@ -236,7 +235,7 @@ mod tests {
#[test]
fn test_random_material_filled() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let genesis_hash = System::parent_hash();
setup_blocks(81);
@@ -251,7 +250,7 @@ mod tests {
#[test]
fn test_random_material_filled_twice() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let genesis_hash = System::parent_hash();
setup_blocks(162);
@@ -266,7 +265,7 @@ mod tests {
#[test]
fn test_random() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
setup_blocks(162);
assert_eq!(System::block_number(), 162);
+17 -17
View File
@@ -20,7 +20,7 @@ use super::*;
use mock::*;
use support::{assert_ok, assert_noop};
use sr_primitives::{set_and_run_with_externalities, traits::OnInitialize};
use sr_primitives::traits::OnInitialize;
type ScoredPool = Module<Test>;
type System = system::Module<Test>;
@@ -31,7 +31,7 @@ const INDEX_ERR: &str = "index does not match requested account";
#[test]
fn query_membership_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_eq!(ScoredPool::members(), vec![20, 40]);
assert_eq!(Balances::reserved_balance(&31), CandidateDeposit::get());
assert_eq!(Balances::reserved_balance(&40), CandidateDeposit::get());
@@ -41,7 +41,7 @@ fn query_membership_works() {
#[test]
fn submit_candidacy_must_not_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_noop!(
ScoredPool::submit_candidacy(Origin::signed(99)),
"balance too low to submit candidacy"
@@ -55,7 +55,7 @@ fn submit_candidacy_must_not_work() {
#[test]
fn submit_candidacy_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let who = 15;
@@ -70,7 +70,7 @@ fn submit_candidacy_works() {
#[test]
fn scoring_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let who = 15;
let score = 99;
@@ -88,7 +88,7 @@ fn scoring_works() {
#[test]
fn scoring_same_element_with_same_score_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let who = 31;
let index = find_in_pool(who).expect("entity must be in pool") as u32;
@@ -108,7 +108,7 @@ fn scoring_same_element_with_same_score_works() {
#[test]
fn kicking_works_only_for_authorized() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let who = 40;
let index = find_in_pool(who).expect("entity must be in pool") as u32;
assert_noop!(ScoredPool::kick(Origin::signed(99), who, index), "bad origin");
@@ -117,7 +117,7 @@ fn kicking_works_only_for_authorized() {
#[test]
fn kicking_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let who = 40;
assert_eq!(Balances::reserved_balance(&who), CandidateDeposit::get());
@@ -137,7 +137,7 @@ fn kicking_works() {
#[test]
fn unscored_entities_must_not_be_used_for_filling_members() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
// we submit a candidacy, score will be `None`
assert_ok!(ScoredPool::submit_candidacy(Origin::signed(15)));
@@ -162,7 +162,7 @@ fn unscored_entities_must_not_be_used_for_filling_members() {
#[test]
fn refreshing_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let who = 15;
assert_ok!(ScoredPool::submit_candidacy(Origin::signed(who)));
@@ -180,7 +180,7 @@ fn refreshing_works() {
#[test]
fn refreshing_happens_every_period() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
System::set_block_number(1);
assert_ok!(ScoredPool::submit_candidacy(Origin::signed(15)));
@@ -200,7 +200,7 @@ fn refreshing_happens_every_period() {
#[test]
fn withdraw_candidacy_must_only_work_for_members() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let who = 77;
let index = 0;
assert_noop!( ScoredPool::withdraw_candidacy(Origin::signed(who), index), INDEX_ERR);
@@ -209,7 +209,7 @@ fn withdraw_candidacy_must_only_work_for_members() {
#[test]
fn oob_index_should_abort() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let who = 40;
let oob_index = ScoredPool::pool().len() as u32;
assert_noop!(ScoredPool::withdraw_candidacy(Origin::signed(who), oob_index), OOB_ERR);
@@ -220,7 +220,7 @@ fn oob_index_should_abort() {
#[test]
fn index_mismatches_should_abort() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let who = 40;
let index = 3;
assert_noop!(ScoredPool::withdraw_candidacy(Origin::signed(who), index), INDEX_ERR);
@@ -231,7 +231,7 @@ fn index_mismatches_should_abort() {
#[test]
fn withdraw_unscored_candidacy_must_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let who = 5;
@@ -246,7 +246,7 @@ fn withdraw_unscored_candidacy_must_work() {
#[test]
fn withdraw_scored_candidacy_must_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let who = 40;
assert_eq!(Balances::reserved_balance(&who), CandidateDeposit::get());
@@ -264,7 +264,7 @@ fn withdraw_scored_candidacy_must_work() {
#[test]
fn candidacy_resubmitting_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// given
let who = 15;
+3 -5
View File
@@ -313,9 +313,7 @@ impl<T: Trait, D: AsRef<[u8]>> support::traits::KeyOwnerProofSystem<(KeyTypeId,
mod tests {
use super::*;
use primitives::crypto::key_types::DUMMY;
use sr_primitives::{
traits::OnInitialize, testing::UintAuthorityId, set_and_run_with_externalities,
};
use sr_primitives::{traits::OnInitialize, testing::UintAuthorityId};
use crate::mock::{
NEXT_VALIDATORS, force_new_session,
set_next_validators, Test, System, Session,
@@ -336,7 +334,7 @@ mod tests {
#[test]
fn generated_proof_is_good() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
set_next_validators(vec![1, 2]);
force_new_session();
@@ -377,7 +375,7 @@ mod tests {
#[test]
fn prune_up_to_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
for i in 1..101u64 {
set_next_validators(vec![i]);
force_new_session();
+11 -14
View File
@@ -681,9 +681,7 @@ mod tests {
use super::*;
use support::assert_ok;
use primitives::crypto::key_types::DUMMY;
use sr_primitives::{
traits::OnInitialize, set_and_run_with_externalities, testing::UintAuthorityId,
};
use sr_primitives::{traits::OnInitialize, testing::UintAuthorityId};
use mock::{
NEXT_VALIDATORS, SESSION_CHANGED, TEST_SESSION_CHANGED, authorities, force_new_session,
set_next_validators, set_session_length, session_changed, Test, Origin, System, Session,
@@ -708,7 +706,7 @@ mod tests {
#[test]
fn simple_setup_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]);
assert_eq!(Session::validators(), vec![1, 2, 3]);
});
@@ -716,7 +714,7 @@ mod tests {
#[test]
fn put_get_keys() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
Session::put_keys(&10, &UintAuthorityId(10).into());
assert_eq!(Session::load_keys(&10), Some(UintAuthorityId(10).into()));
})
@@ -725,7 +723,7 @@ mod tests {
#[test]
fn keys_cleared_on_kill() {
let mut ext = new_test_ext();
set_and_run_with_externalities(&mut ext, || {
ext.execute_with(|| {
assert_eq!(Session::validators(), vec![1, 2, 3]);
assert_eq!(Session::load_keys(&1), Some(UintAuthorityId(1).into()));
@@ -742,7 +740,7 @@ mod tests {
fn authorities_should_track_validators() {
reset_before_session_end_called();
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
set_next_validators(vec![1, 2]);
force_new_session();
initialize_block(1);
@@ -793,7 +791,7 @@ mod tests {
#[test]
fn should_work_with_early_exit() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
set_session_length(10);
initialize_block(1);
@@ -816,7 +814,7 @@ mod tests {
#[test]
fn session_change_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// Block 1: No change
initialize_block(1);
assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]);
@@ -846,7 +844,7 @@ mod tests {
#[test]
fn duplicates_are_not_allowed() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::set_block_number(1);
Session::on_initialize(1);
assert!(Session::set_keys(Origin::signed(4), UintAuthorityId(1).into(), vec![]).is_err());
@@ -861,7 +859,7 @@ mod tests {
fn session_changed_flag_works() {
reset_before_session_end_called();
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
TEST_SESSION_CHANGED.with(|l| *l.borrow_mut() = true);
force_new_session();
@@ -950,7 +948,7 @@ mod tests {
#[test]
fn session_keys_generate_output_works_as_set_keys_input() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let new_keys = mock::MockSessionKeys::generate(None);
assert_ok!(
Session::set_keys(
@@ -964,7 +962,7 @@ mod tests {
#[test]
fn return_true_if_more_than_third_is_disabled() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
set_next_validators(vec![1, 2, 3, 4, 5, 6, 7]);
force_new_session();
initialize_block(1);
@@ -977,6 +975,5 @@ mod tests {
assert_eq!(Session::disable_index(2), true);
assert_eq!(Session::disable_index(3), true);
});
}
}
+2 -2
View File
@@ -340,8 +340,8 @@ impl ExtBuilder {
keys: validators.iter().map(|x| (*x, UintAuthorityId(*x))).collect(),
}.assimilate_storage(&mut storage);
let mut ext = storage.into();
sr_primitives::set_and_run_with_externalities(&mut ext, || {
let mut ext = runtime_io::TestExternalities::from(storage);
ext.execute_with(|| {
let validators = Session::validators();
SESSION.with(|x|
*x.borrow_mut() = (validators.clone(), HashSet::new())
File diff suppressed because it is too large Load Diff
+8 -9
View File
@@ -173,10 +173,10 @@ macro_rules! assert_err {
#[macro_export]
#[cfg(feature = "std")]
macro_rules! assert_ok {
( $x:expr ) => {
( $x:expr $(,)? ) => {
assert_eq!($x, Ok(()));
};
( $x:expr, $y:expr ) => {
( $x:expr, $y:expr $(,)? ) => {
assert_eq!($x, Ok($y));
}
}
@@ -236,7 +236,6 @@ pub use serde::{Serialize, Deserialize};
mod tests {
use super::*;
use codec::{Codec, EncodeLike};
use sr_primitives::set_and_run_with_externalities;
use srml_metadata::{
DecodeDifferent, StorageEntryMetadata, StorageMetadata, StorageEntryType,
StorageEntryModifier, DefaultByteGetter, StorageHasher,
@@ -288,7 +287,7 @@ mod tests {
#[test]
fn linked_map_issue_3318() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
OptionLinkedMap::insert(1, 1);
assert_eq!(OptionLinkedMap::get(1), Some(1));
OptionLinkedMap::insert(1, 2);
@@ -298,7 +297,7 @@ mod tests {
#[test]
fn linked_map_swap_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
OptionLinkedMap::insert(0, 0);
OptionLinkedMap::insert(1, 1);
OptionLinkedMap::insert(2, 2);
@@ -327,7 +326,7 @@ mod tests {
#[test]
fn linked_map_basic_insert_remove_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// initialized during genesis
assert_eq!(Map::get(&15u32), 42u64);
@@ -353,7 +352,7 @@ mod tests {
#[test]
fn linked_map_enumeration_and_head_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_eq!(Map::head(), Some(15));
assert_eq!(Map::enumerate().collect::<Vec<_>>(), vec![(15, 42)]);
// insert / remove
@@ -405,7 +404,7 @@ mod tests {
#[test]
fn double_map_basic_insert_remove_remove_prefix_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
type DoubleMap = DataDM;
// initialized during genesis
assert_eq!(DoubleMap::get(&15u32, &16u32), 42u64);
@@ -445,7 +444,7 @@ mod tests {
#[test]
fn double_map_append_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
type DoubleMap = AppendableDM<Test>;
let key1 = 17u32;
@@ -759,7 +759,6 @@ mod test3 {
#[allow(dead_code)]
mod test_append_and_len {
use runtime_io::TestExternalities;
use sr_primitives::set_and_run_with_externalities;
use codec::{Encode, Decode};
pub trait Trait {
@@ -801,7 +800,7 @@ mod test_append_and_len {
#[test]
fn default_for_option() {
set_and_run_with_externalities(&mut TestExternalities::default(), || {
TestExternalities::default().execute_with(|| {
assert_eq!(OptionVec::get(), None);
assert_eq!(JustVec::get(), vec![]);
});
@@ -809,7 +808,7 @@ mod test_append_and_len {
#[test]
fn append_works() {
set_and_run_with_externalities(&mut TestExternalities::default(), || {
TestExternalities::default().execute_with(|| {
let _ = MapVec::append(1, [1, 2, 3].iter());
let _ = MapVec::append(1, [4, 5].iter());
assert_eq!(MapVec::get(1), vec![1, 2, 3, 4, 5]);
@@ -822,7 +821,7 @@ mod test_append_and_len {
#[test]
fn append_works_for_default() {
set_and_run_with_externalities(&mut TestExternalities::default(), || {
TestExternalities::default().execute_with(|| {
assert_eq!(JustVecWithDefault::get(), vec![6, 9]);
let _ = JustVecWithDefault::append([1].iter());
assert_eq!(JustVecWithDefault::get(), vec![6, 9, 1]);
@@ -839,7 +838,7 @@ mod test_append_and_len {
#[test]
fn append_or_put_works() {
set_and_run_with_externalities(&mut TestExternalities::default(), || {
TestExternalities::default().execute_with(|| {
let _ = MapVec::append_or_insert(1, &[1, 2, 3][..]);
let _ = MapVec::append_or_insert(1, &[4, 5][..]);
assert_eq!(MapVec::get(1), vec![1, 2, 3, 4, 5]);
@@ -856,7 +855,7 @@ mod test_append_and_len {
#[test]
fn len_works() {
set_and_run_with_externalities(&mut TestExternalities::default(), || {
TestExternalities::default().execute_with(|| {
JustVec::put(&vec![1, 2, 3, 4]);
OptionVec::put(&vec![1, 2, 3, 4, 5]);
MapVec::insert(1, &vec![1, 2, 3, 4, 5, 6]);
@@ -871,7 +870,7 @@ mod test_append_and_len {
#[test]
fn len_works_for_default() {
set_and_run_with_externalities(&mut TestExternalities::default(), || {
TestExternalities::default().execute_with(|| {
// vec
assert_eq!(JustVec::get(), vec![]);
assert_eq!(JustVec::decode_len(), Ok(0));
@@ -15,10 +15,7 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
#![recursion_limit="128"]
use sr_primitives::{
generic, BuildStorage, traits::{BlakeTwo256, Block as _, Verify},
set_and_run_with_externalities,
};
use sr_primitives::{generic, BuildStorage, traits::{BlakeTwo256, Block as _, Verify}};
use support::{
Parameter, traits::Get, parameter_types,
metadata::{
@@ -331,7 +328,7 @@ fn storage_instance_independance() {
#[test]
fn storage_with_instance_basic_operation() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
type Value = module2::Value<Runtime, module2::Instance1>;
type Map = module2::Map<module2::Instance1>;
type LinkedMap = module2::LinkedMap<module2::Instance1>;
+2 -4
View File
@@ -18,9 +18,7 @@ use criterion::{Criterion, criterion_group, criterion_main, black_box};
use srml_system as system;
use support::{decl_module, decl_event, impl_outer_origin, impl_outer_event};
use primitives::H256;
use sr_primitives::{
set_and_run_with_externalities, Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header,
};
use sr_primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
mod module {
use super::*;
@@ -89,7 +87,7 @@ fn new_test_ext() -> runtime_io::TestExternalities {
fn deposit_events(n: usize) {
let mut t = new_test_ext();
set_and_run_with_externalities(&mut t, || {
t.execute_with(|| {
for _ in 0..n {
module::Module::<Runtime>::deposit_event(
module::Event::Complex(vec![1, 2, 3], 2, 3, 899)
+19 -17
View File
@@ -1091,10 +1091,7 @@ impl<T: Trait> Lookup for ChainContext<T> {
mod tests {
use super::*;
use primitives::H256;
use sr_primitives::{
traits::{BlakeTwo256, IdentityLookup}, testing::Header, DispatchError,
set_and_run_with_externalities,
};
use sr_primitives::{traits::{BlakeTwo256, IdentityLookup}, testing::Header, DispatchError};
use support::{impl_outer_origin, parameter_types};
impl_outer_origin! {
@@ -1164,7 +1161,7 @@ mod tests {
#[test]
fn deposit_event_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
System::initialize(&1, &[0u8; 32].into(), &[0u8; 32].into(), &Default::default());
System::note_finished_extrinsics();
System::deposit_event(1u16);
@@ -1201,10 +1198,15 @@ mod tests {
#[test]
fn deposit_event_topics() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
const BLOCK_NUMBER: u64 = 1;
System::initialize(&BLOCK_NUMBER, &[0u8; 32].into(), &[0u8; 32].into(), &Default::default());
System::initialize(
&BLOCK_NUMBER,
&[0u8; 32].into(),
&[0u8; 32].into(),
&Default::default(),
);
System::note_finished_extrinsics();
let topics = vec![
@@ -1261,7 +1263,7 @@ mod tests {
#[test]
fn prunes_block_hash_mappings() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// simulate import of 15 blocks
for n in 1..=15 {
System::initialize(
@@ -1294,7 +1296,7 @@ mod tests {
#[test]
fn signed_ext_check_nonce_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
<AccountNonce<Test>>::insert(1, 1);
let info = DispatchInfo::default();
let len = 0_usize;
@@ -1312,7 +1314,7 @@ mod tests {
#[test]
fn signed_ext_check_weight_works_normal_tx() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let normal_limit = normal_weight_limit();
let small = DispatchInfo { weight: 100, ..Default::default() };
let medium = DispatchInfo {
@@ -1339,7 +1341,7 @@ mod tests {
#[test]
fn signed_ext_check_weight_fee_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let free = DispatchInfo { weight: 0, ..Default::default() };
let len = 0_usize;
@@ -1352,7 +1354,7 @@ mod tests {
#[test]
fn signed_ext_check_weight_max_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let max = DispatchInfo { weight: Weight::max_value(), ..Default::default() };
let len = 0_usize;
let normal_limit = normal_weight_limit();
@@ -1366,7 +1368,7 @@ mod tests {
#[test]
fn signed_ext_check_weight_works_operational_tx() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let normal = DispatchInfo { weight: 100, ..Default::default() };
let op = DispatchInfo { weight: 100, class: DispatchClass::Operational };
let len = 0_usize;
@@ -1389,7 +1391,7 @@ mod tests {
#[test]
fn signed_ext_check_weight_priority_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let normal = DispatchInfo { weight: 100, class: DispatchClass::Normal };
let op = DispatchInfo { weight: 100, class: DispatchClass::Operational };
let len = 0_usize;
@@ -1410,7 +1412,7 @@ mod tests {
#[test]
fn signed_ext_check_weight_block_size_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let normal = DispatchInfo::default();
let normal_limit = normal_weight_limit() as usize;
let reset_check_weight = |tx, s, f| {
@@ -1434,7 +1436,7 @@ mod tests {
#[test]
fn signed_ext_check_era_should_work() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// future
assert_eq!(
CheckEra::<Test>::from(Era::mortal(4, 2)).additional_signed().err().unwrap(),
@@ -1450,7 +1452,7 @@ mod tests {
#[test]
fn signed_ext_check_era_should_change_longevity() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let normal = DispatchInfo { weight: 100, class: DispatchClass::Normal };
let len = 0_usize;
let ext = (
+4 -7
View File
@@ -324,10 +324,7 @@ mod tests {
use support::{impl_outer_origin, assert_ok, parameter_types};
use runtime_io::TestExternalities;
use primitives::H256;
use sr_primitives::{
Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header,
set_and_run_with_externalities,
};
use sr_primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
impl_outer_origin! {
pub enum Origin for Test {}
@@ -372,7 +369,7 @@ mod tests {
#[test]
fn timestamp_works() {
let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
set_and_run_with_externalities(&mut TestExternalities::new(t), || {
TestExternalities::new(t).execute_with(|| {
Timestamp::set_timestamp(42);
assert_ok!(Timestamp::dispatch(Call::set(69), Origin::NONE));
assert_eq!(Timestamp::now(), 69);
@@ -383,7 +380,7 @@ mod tests {
#[should_panic(expected = "Timestamp must be updated only once in the block")]
fn double_timestamp_should_fail() {
let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
set_and_run_with_externalities(&mut TestExternalities::new(t), || {
TestExternalities::new(t).execute_with(|| {
Timestamp::set_timestamp(42);
assert_ok!(Timestamp::dispatch(Call::set(69), Origin::NONE));
let _ = Timestamp::dispatch(Call::set(70), Origin::NONE);
@@ -394,7 +391,7 @@ mod tests {
#[should_panic(expected = "Timestamp must increment by at least <MinimumPeriod> between sequential blocks")]
fn block_period_minimum_enforced() {
let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
set_and_run_with_externalities(&mut TestExternalities::new(t), || {
TestExternalities::new(t).execute_with(|| {
Timestamp::set_timestamp(42);
let _ = Timestamp::dispatch(Call::set(46), Origin::NONE);
});
+16 -17
View File
@@ -358,8 +358,7 @@ mod tests {
use support::{assert_noop, assert_ok, impl_outer_origin, parameter_types};
use primitives::H256;
use sr_primitives::{
traits::{BlakeTwo256, OnFinalize, IdentityLookup}, set_and_run_with_externalities,
testing::Header, assert_eq_error_rate,
traits::{BlakeTwo256, OnFinalize, IdentityLookup}, testing::Header, assert_eq_error_rate,
};
impl_outer_origin! {
@@ -446,7 +445,7 @@ mod tests {
#[test]
fn genesis_config_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_eq!(Treasury::pot(), 0);
assert_eq!(Treasury::proposal_count(), 0);
});
@@ -454,7 +453,7 @@ mod tests {
#[test]
fn minting_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
// Check that accumulate works when we have Some value in Dummy already.
Treasury::on_dilution(100, 100);
assert_eq!(Treasury::pot(), 100);
@@ -465,7 +464,7 @@ mod tests {
fn minting_works_2() {
let tests = [(1, 10), (1, 20), (40, 130), (2, 66), (2, 67), (2, 100), (2, 101), (2, 134)];
for &(minted, portion) in &tests {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let init_total_issuance = Balances::total_issuance();
Treasury::on_dilution(minted, portion);
@@ -489,7 +488,7 @@ mod tests {
#[test]
fn spend_proposal_takes_min_deposit() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_ok!(Treasury::propose_spend(Origin::signed(0), 1, 3));
assert_eq!(Balances::free_balance(&0), 99);
assert_eq!(Balances::reserved_balance(&0), 1);
@@ -498,7 +497,7 @@ mod tests {
#[test]
fn spend_proposal_takes_proportional_deposit() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3));
assert_eq!(Balances::free_balance(&0), 95);
assert_eq!(Balances::reserved_balance(&0), 5);
@@ -507,14 +506,14 @@ mod tests {
#[test]
fn spend_proposal_fails_when_proposer_poor() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_noop!(Treasury::propose_spend(Origin::signed(2), 100, 3), "Proposer's balance too low");
});
}
#[test]
fn accepted_spend_proposal_ignored_outside_spend_period() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
Treasury::on_dilution(100, 100);
assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3));
@@ -528,7 +527,7 @@ mod tests {
#[test]
fn unused_pot_should_diminish() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
let init_total_issuance = Balances::total_issuance();
Treasury::on_dilution(100, 100);
assert_eq!(Balances::total_issuance(), init_total_issuance + 100);
@@ -541,7 +540,7 @@ mod tests {
#[test]
fn rejected_spend_proposal_ignored_on_spend_period() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
Treasury::on_dilution(100, 100);
assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3));
@@ -555,7 +554,7 @@ mod tests {
#[test]
fn reject_already_rejected_spend_proposal_fails() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
Treasury::on_dilution(100, 100);
assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3));
@@ -566,21 +565,21 @@ mod tests {
#[test]
fn reject_non_existant_spend_proposal_fails() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_noop!(Treasury::reject_proposal(Origin::ROOT, 0), "No proposal at that index");
});
}
#[test]
fn accept_non_existant_spend_proposal_fails() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_noop!(Treasury::approve_proposal(Origin::ROOT, 0), "No proposal at that index");
});
}
#[test]
fn accept_already_rejected_spend_proposal_fails() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
Treasury::on_dilution(100, 100);
assert_ok!(Treasury::propose_spend(Origin::signed(0), 100, 3));
@@ -591,7 +590,7 @@ mod tests {
#[test]
fn accepted_spend_proposal_enacted_on_spend_period() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
Treasury::on_dilution(100, 100);
assert_eq!(Treasury::pot(), 100);
@@ -606,7 +605,7 @@ mod tests {
#[test]
fn pot_underflow_should_not_diminish() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
Treasury::on_dilution(100, 100);
assert_ok!(Treasury::propose_spend(Origin::signed(0), 150, 3));
+2 -5
View File
@@ -65,10 +65,7 @@ mod tests {
use support::{assert_ok, assert_noop, impl_outer_origin, parameter_types, impl_outer_dispatch};
use primitives::H256;
use sr_primitives::{
Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header,
set_and_run_with_externalities,
};
use sr_primitives::{Perbill, traits::{BlakeTwo256, IdentityLookup}, testing::Header};
impl_outer_origin! {
pub enum Origin for Test {}
@@ -150,7 +147,7 @@ mod tests {
#[test]
fn batch_works() {
set_and_run_with_externalities(&mut new_test_ext(), || {
new_test_ext().execute_with(|| {
assert_eq!(Balances::free_balance(1), 10);
assert_eq!(Balances::free_balance(2), 0);
assert_noop!(Utility::batch(Origin::signed(1), vec![