Skip to content

Commit

Permalink
Add separate tests for nomination, validation announcment and chilling
Browse files Browse the repository at this point in the history
Merge branch 'staking' of github.com:paritytech/substrate-subxt into staking

* 'staking' of github.com:paritytech/substrate-subxt:
  Ignore the staking tests on CI
  Retry on temporary failures
  Revert "Remove unnecessary use"
  Remove unnecessary use
  Add missing docs
  Add SetCodeWithoutChecksCall (#166)
  Test chill
  Remove dead code
  Hopefully fix CI
  • Loading branch information
dvdplm committed Sep 18, 2020
2 parents 0860bad + d63661f commit 369cb88
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 68 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,4 @@ substrate-subxt-client = { version = "0.4.0", path = "client" }
tempdir = "0.3.7"
test-node = { path = "test-node" }
wabt = "0.10.0"
assert_matches = "1.3"
2 changes: 1 addition & 1 deletion client/run.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/bin/sh
NODE_TEMPLATE=../target/release/test-node
$NODE_TEMPLATE --chain=dev-chain.json --alice -lrpc=debug
$NODE_TEMPLATE --chain=dev-chain.json --alice
3 changes: 1 addition & 2 deletions src/frame/contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ pub struct InstantiatedEvent<T: Contracts> {
}

#[cfg(test)]
#[cfg(feature = "integration-tests")]
mod tests {
use sp_keyring::AccountKeyring;

Expand All @@ -137,7 +138,6 @@ mod tests {
}

#[async_std::test]
#[cfg(feature = "integration-tests")]
async fn tx_put_code() {
env_logger::try_init().ok();

Expand All @@ -161,7 +161,6 @@ mod tests {
}

#[async_std::test]
#[cfg(feature = "integration-tests")]
async fn tx_instantiate() {
env_logger::try_init().ok();
let signer = PairSigner::new(AccountKeyring::Bob.pair());
Expand Down
140 changes: 111 additions & 29 deletions src/frame/staking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,27 +196,122 @@ pub struct NominateCall<T: Staking> {
pub targets: Vec<T::Address>,
}

#[cfg(all(test, feature = "integration-tests"))]
#[cfg(test)]
#[cfg(feature = "integration-tests")]
mod tests {
use super::*;
use crate::{
extrinsic::PairSigner,
runtimes::KusamaRuntime as RT,
ClientBuilder,
};
// use sp_core::{sr25519::Pair, Pair as _};
use crate::{
error::Error,
extrinsic::Signer,
ExtrinsicSuccess,
extrinsic::{
PairSigner,
Signer,
},
frame::{
balances::*,
system::*,
},
runtimes::KusamaRuntime as RT,
ClientBuilder,
Error,
error::RuntimeError,
};
use jsonrpsee::{
client::RequestError,
common::{
Error as RPCError,
ErrorCode,
},
};
use assert_matches::assert_matches;
use sp_keyring::AccountKeyring;

// TODO: I don't think this does the right thing.
macro_rules! retry_trans {
($e: expr) => {
(loop {
match $e.await {
Ok(o) => break o,
Err(Error::Rpc(RequestError::Request(RPCError {
code: ErrorCode::ServerError(1014),
message: m,
data: Some(_),
}))) if m.starts_with("Priority is too low: ") => {}
Err(e) => panic!("Unexpected error: {}", e),
}
})
};
}

#[async_std::test]
async fn test_validate_with_stash_account() -> Result<(), Error> {
env_logger::try_init().ok();
let alice = PairSigner::<RT, _>::new(AccountKeyring::Alice.pair());
let client = ClientBuilder::<RT>::new().build().await?;
let announce_validator = client
.validate_and_watch(&alice, ValidatorPrefs::default())
.await;
assert_matches!(announce_validator, Ok(ExtrinsicSuccess {block: _, extrinsic: _, events}) => {
// TOOD: this is unsatisfying – can we do better?
assert_eq!(events.len(), 3);
});

Ok(())
}
#[async_std::test]
async fn test_nominate() -> Result<(), Error> {
#[ignore]
async fn test_validate_with_controller_account() -> Result<(), Error> {
// TODO: how to set up the controller account for Alice?
Ok(())
}
#[async_std::test]
async fn test_nominate_with_stash_account() -> Result<(), Error> {
env_logger::try_init().ok();
let alice = PairSigner::<RT, _>::new(AccountKeyring::Alice.pair());
let bob = PairSigner::<RT, _>::new(AccountKeyring::Bob.pair());
let client = ClientBuilder::<RT>::new().build().await?;

let nomination = client
.nominate_and_watch(&alice, vec![bob.account_id().clone()])
.await;
assert_matches!(nomination, Ok(ExtrinsicSuccess {block: _, extrinsic: _, events}) => {
// TOOD: this is unsatisfying – can we do better?
assert_eq!(events.len(), 3);
});
Ok(())
}

#[async_std::test]
async fn test_chill_not_possible_for_stash_account() -> Result<(), Error> {
env_logger::try_init().ok();
let alice = PairSigner::<RT, _>::new(AccountKeyring::Alice.pair());
let bob = PairSigner::<RT, _>::new(AccountKeyring::Bob.pair());
let client = ClientBuilder::<RT>::new().build().await?;

client
.nominate_and_watch(&alice, vec![bob.account_id().clone()])
.await?;
let chill = client
.chill_and_watch(&bob)
.await;

assert_matches!(chill, Err(Error::Runtime(RuntimeError::Module(module_err))) => {
assert_eq!(module_err.module, "Staking");
assert_eq!(module_err.error, "NotController");
});
Ok(())
}

#[async_std::test]
#[ignore]
async fn test_chill_is_ok_for_controller_account() -> Result<(), Error> {
// TODO: how to set the controller for Alice?
Ok(())
}

#[async_std::test]
#[ignore]
// NOTE: this is throw-away code to be removed before merge
async fn test_scratchpad() -> Result<(), Error> {
env_logger::try_init().ok();
let alice = PairSigner::<RT, _>::new(AccountKeyring::Alice.pair());
let bob = PairSigner::<RT, _>::new(AccountKeyring::Bob.pair());
Expand All @@ -234,29 +329,16 @@ mod tests {
.nominate(&alice, vec![bob.account_id().clone()])
.await?;
println!("Nom nom: {:?}", o);
let o = client
.validate(&bob, ValidatorPrefs::default())
.await?;
let o = retry_trans!(client.validate(&bob, ValidatorPrefs::default()));
println!("Validator result: {:?}", o);
for &i in &[RewardDestination::Controller] {
for &_i in &[RewardDestination::Controller] {
for &j in &[&bob, &alice] {
println!(
"Transaction result: {:?}",
client.set_payee(j, i).await?
);
let o = retry_trans!(client.validate(&bob, ValidatorPrefs::default()));
println!("Transaction result: {:?}", o);
let o = retry_trans!(client.chill(j));
println!("Transaction result: {:?}", o);
}
}
assert_eq!(
client
.fetch(
&ValidatorsStore {
stash: bob.account_id().clone()
},
None
)
.await?,
None
);
Ok(())
}
}
9 changes: 9 additions & 0 deletions src/frame/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,15 @@ pub struct SetCodeCall<'a, T: System> {
pub code: &'a [u8],
}

/// Arguments for updating the runtime code without checks
#[derive(Clone, Debug, Eq, PartialEq, Call, Encode)]
pub struct SetCodeWithoutChecksCall<'a, T: System> {
/// Runtime marker.
pub _runtime: PhantomData<T>,
/// Runtime wasm blob.
pub code: &'a [u8],
}

/// A phase of a block's execution.
#[derive(Clone, Debug, Eq, PartialEq, Decode)]
pub enum Phase {
Expand Down
21 changes: 10 additions & 11 deletions src/runtimes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
//
// You should have received a copy of the GNU General Public License
// along with substrate-subxt. If not, see <http://www.gnu.org/licenses/>.
#![allow(missing_docs)]

use codec::Encode;
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
Expand Down Expand Up @@ -82,31 +81,31 @@ impl sp_runtime::BoundToRuntimeAppPublic for AuthorityDiscovery {
impl_opaque_keys! {
/// Substrate base runtime keys
pub struct BasicSessionKeys {
//// GRANDPA session key
/// GRANDPA session key
pub grandpa: Grandpa,
//// BABE session key
/// BABE session key
pub babe: Babe,
//// ImOnline session key
/// ImOnline session key
pub im_online: ImOnline,
//// Parachain validation session key
/// Parachain validation session key
pub parachains: Parachains,
//// AuthorityDiscovery session key
/// AuthorityDiscovery session key
pub authority_discovery: AuthorityDiscovery,
}
}

impl_opaque_keys! {
/// Polkadot/Kusama runtime keys
pub struct SessionKeys {
//// GRANDPA session key
/// GRANDPA session key
pub grandpa: Grandpa,
//// BABE session key
/// BABE session key
pub babe: Babe,
//// ImOnline session key
/// ImOnline session key
pub im_online: ImOnline,
//// ParachainValidator session key
/// ParachainValidator session key
pub parachain_validator: Parachains,
//// AuthorityDiscovery session key
/// AuthorityDiscovery session key
pub authority_discovery: AuthorityDiscovery,
}
}
Expand Down
25 changes: 0 additions & 25 deletions test-node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ pub use frame_support::{
StorageValue,
};
pub use pallet_balances::Call as BalancesCall;
pub use pallet_staking::Call as StakingCall;
pub use pallet_timestamp::Call as TimestampCall;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
Expand Down Expand Up @@ -306,30 +305,6 @@ impl pallet_sudo::Trait for Runtime {
type Call = Call;
}

// impl pallet_staking::Trait for Runtime {
// type Currency = Balances;
// type UnixTime = pallet_timestamp::Module<Self>;
// type CurrencyToVote = CurrencyToVoteHandler;
// type RewardRemainder = ();
// type Event = ();
// type Slash = ();
// type Reward = ();
// type SessionsPerEra = ();
// type SlashDeferDuration = ();
// type SlashCancelOrigin = frame_system::EnsureRoot<Self::AccountId>;
// type BondingDuration = ();
// type SessionInterface = Self;
// type RewardCurve = RewardCurve;
// type NextNewSession = Session;
// type ElectionLookahead = ();
// type Call = Call;
// type MaxIterations = MaxIterations;
// type MinSolutionScoreBump = ();
// type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
// type UnsignedPriority = ();
// type WeightInfo = ();
// }

construct_runtime!(
pub enum Runtime where
Block = Block,
Expand Down

0 comments on commit 369cb88

Please sign in to comment.