cargo fmt with stable defaults (#876)

This commit is contained in:
James Wilson
2023-03-21 16:53:47 +00:00
committed by GitHub
parent c63ff6ec6d
commit 7c252fccf7
110 changed files with 663 additions and 1949 deletions
+1 -4
View File
@@ -3,10 +3,7 @@
// see LICENSE for license details.
use crate::test_context;
use codec::{
Compact,
Decode,
};
use codec::{Compact, Decode};
use frame_metadata::RuntimeMetadataPrefixed;
use futures::StreamExt;
+6 -23
View File
@@ -3,31 +3,16 @@
// see LICENSE for license details.
use crate::{
pair_signer,
test_context,
test_context_with,
utils::{
node_runtime,
wait_for_blocks,
},
pair_signer, test_context, test_context_with,
utils::{node_runtime, wait_for_blocks},
};
use assert_matches::assert_matches;
use codec::{
Compact,
Decode,
Encode,
};
use codec::{Compact, Decode, Encode};
use frame_metadata::RuntimeMetadataPrefixed;
use sp_core::storage::well_known_keys;
use sp_keyring::AccountKeyring;
use subxt::{
rpc::types::{
ChainHeadEvent,
FollowEvent,
Initialized,
RuntimeEvent,
RuntimeVersionEvent,
},
rpc::types::{ChainHeadEvent, FollowEvent, Initialized, RuntimeEvent, RuntimeVersionEvent},
tx::Signer,
utils::AccountId32,
};
@@ -260,8 +245,7 @@ async fn external_signing() {
// Sign it (possibly externally).
let signature = alice.sign(&signer_payload);
// Use this to build a signed extrinsic.
let extrinsic =
partial_extrinsic.sign_with_address_and_signature(&alice.address(), &signature);
let extrinsic = partial_extrinsic.sign_with_address_and_signature(&alice.address(), &signature);
// And now submit it.
extrinsic
@@ -417,8 +401,7 @@ async fn chainhead_unstable_body() {
// Expected block's extrinsics scale encoded and hex encoded.
let body = api.rpc().block(Some(hash)).await.unwrap().unwrap();
let extrinsics: Vec<Vec<u8>> =
body.block.extrinsics.into_iter().map(|ext| ext.0).collect();
let extrinsics: Vec<Vec<u8>> = body.block.extrinsics.into_iter().map(|ext| ext.0).collect();
let expected = format!("0x{}", hex::encode(extrinsics.encode()));
assert_matches!(event,
@@ -3,12 +3,7 @@
// see LICENSE for license details.
use regex::Regex;
use subxt_codegen::{
CratePath,
DerivesRegistry,
RuntimeGenerator,
TypeSubstitutes,
};
use subxt_codegen::{CratePath, DerivesRegistry, RuntimeGenerator, TypeSubstitutes};
fn load_test_metadata() -> frame_metadata::RuntimeMetadataPrefixed {
let bytes = test_runtime::METADATA;
@@ -162,7 +157,8 @@ fn check_root_attrs_preserved() {
let doc_str_loc = generated_code
.find("Some root level documentation")
.expect("root docs should be preserved");
let attr_loc = generated_code.find("some_root_attribute") // '#' is space separated in generated output.
let attr_loc = generated_code
.find("some_root_attribute") // '#' is space separated in generated output.
.expect("root attr should be preserved");
let mod_start = generated_code
.find("pub mod api")
@@ -3,21 +3,12 @@
// see LICENSE for license details.
use crate::{
node_runtime::{
self,
balances,
runtime_types,
system,
},
pair_signer,
test_context,
node_runtime::{self, balances, runtime_types, system},
pair_signer, test_context,
};
use codec::Decode;
use sp_keyring::AccountKeyring;
use subxt::utils::{
AccountId32,
MultiAddress,
};
use subxt::utils::{AccountId32, MultiAddress};
#[tokio::test]
async fn tx_basic_transfer() -> Result<(), subxt::Error> {
@@ -87,11 +78,7 @@ async fn tx_basic_transfer() -> Result<(), subxt::Error> {
#[tokio::test]
async fn tx_dynamic_transfer() -> Result<(), subxt::Error> {
use subxt::ext::scale_value::{
At,
Composite,
Value,
};
use subxt::ext::scale_value::{At, Composite, Value};
let alice = pair_signer(AccountKeyring::Alice.pair());
let bob = pair_signer(AccountKeyring::Bob.pair());
@@ -229,8 +216,7 @@ async fn multiple_transfers_work_nonce_incremented() -> Result<(), subxt::Error>
.balances()
.transfer(bob_address.clone(), 10_000);
for _ in 0..3 {
api
.tx()
api.tx()
.sign_and_submit_then_watch_default(&tx, &alice)
.await?
.wait_for_in_block() // Don't need to wait for finalization; this is quicker.
@@ -8,26 +8,16 @@ use crate::{
node_runtime::{
self,
contracts::events,
runtime_types::{
pallet_contracts::wasm::Determinism,
sp_weights::weight_v2::Weight,
},
runtime_types::{pallet_contracts::wasm::Determinism, sp_weights::weight_v2::Weight},
system,
},
test_context,
TestContext,
test_context, TestContext,
};
use sp_core::sr25519::Pair;
use subxt::{
tx::{
PairSigner,
TxProgress,
},
tx::{PairSigner, TxProgress},
utils::MultiAddress,
Config,
Error,
OnlineClient,
SubstrateConfig,
Config, Error, OnlineClient, SubstrateConfig,
};
struct ContractsTestContext {
@@ -113,9 +103,7 @@ impl ContractsTestContext {
.ok_or_else(|| Error::Other("Failed to find a Instantiated event".into()))?;
let _extrinsic_success = events
.find_first::<system::events::ExtrinsicSuccess>()?
.ok_or_else(|| {
Error::Other("Failed to find a ExtrinsicSuccess event".into())
})?;
.ok_or_else(|| Error::Other("Failed to find a ExtrinsicSuccess event".into()))?;
tracing::info!(" Block hash: {:?}", events.block_hash());
tracing::info!(" Code hash: {:?}", code_stored.code_hash);
+5 -16
View File
@@ -6,32 +6,21 @@ use crate::{
node_runtime::{
self,
runtime_types::{
pallet_staking::{
RewardDestination,
ValidatorPrefs,
},
pallet_staking::{RewardDestination, ValidatorPrefs},
sp_arithmetic::per_things::Perbill,
},
staking,
},
pair_signer,
test_context,
pair_signer, test_context,
};
use assert_matches::assert_matches;
use sp_core::{
sr25519,
Pair,
};
use sp_core::{sr25519, Pair};
use sp_keyring::AccountKeyring;
use subxt::error::{
DispatchError,
Error,
};
use subxt::error::{DispatchError, Error};
/// Helper function to generate a crypto pair from seed
fn get_from_seed(seed: &str) -> sr25519::Pair {
sr25519::Pair::from_string(&format!("//{seed}"), None)
.expect("static values are valid; qed")
sr25519::Pair::from_string(&format!("//{seed}"), None).expect("static values are valid; qed")
}
fn default_validator_prefs() -> ValidatorPrefs {
+2 -6
View File
@@ -5,14 +5,10 @@
use crate::{
node_runtime::{
self,
runtime_types::{
self,
sp_weights::weight_v2::Weight,
},
runtime_types::{self, sp_weights::weight_v2::Weight},
sudo,
},
pair_signer,
test_context,
pair_signer, test_context,
};
use sp_keyring::AccountKeyring;
@@ -3,12 +3,8 @@
// see LICENSE for license details.
use crate::{
node_runtime::{
self,
system,
},
pair_signer,
test_context,
node_runtime::{self, system},
pair_signer, test_context,
};
use assert_matches::assert_matches;
use sp_keyring::AccountKeyring;
@@ -2,10 +2,7 @@
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
use crate::{
node_runtime,
test_context,
};
use crate::{node_runtime, test_context};
#[tokio::test]
async fn storage_get_current_timestamp() {
@@ -2,37 +2,17 @@
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
use crate::{
node_runtime,
test_context,
TestContext,
};
use crate::{node_runtime, test_context, TestContext};
use frame_metadata::{
ExtrinsicMetadata,
PalletCallMetadata,
PalletMetadata,
PalletStorageMetadata,
RuntimeMetadataPrefixed,
RuntimeMetadataV14,
StorageEntryMetadata,
StorageEntryModifier,
ExtrinsicMetadata, PalletCallMetadata, PalletMetadata, PalletStorageMetadata,
RuntimeMetadataPrefixed, RuntimeMetadataV14, StorageEntryMetadata, StorageEntryModifier,
StorageEntryType,
};
use scale_info::{
build::{
Fields,
Variants,
},
meta_type,
Path,
Type,
TypeInfo,
};
use subxt::{
Metadata,
OfflineClient,
SubstrateConfig,
build::{Fields, Variants},
meta_type, Path, Type, TypeInfo,
};
use subxt::{Metadata, OfflineClient, SubstrateConfig};
async fn metadata_to_api(
metadata: RuntimeMetadataV14,
@@ -147,9 +127,7 @@ async fn calls_check() {
Variants::new()
.variant("unbond", |v| {
v.index(0).fields(Fields::named().field(|f| {
f.compact::<u128>()
.name("value")
.type_name("BalanceOf<T>")
f.compact::<u128>().name("value").type_name("BalanceOf<T>")
}))
})
.variant("withdraw_unbonded", |v| {
+1 -6
View File
@@ -2,12 +2,7 @@
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
use crate::{
node_runtime,
pair_signer,
test_context,
utils::wait_for_blocks,
};
use crate::{node_runtime, pair_signer, test_context, utils::wait_for_blocks};
use sp_keyring::AccountKeyring;
use subxt::utils::AccountId32;
+6 -10
View File
@@ -2,17 +2,11 @@
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
pub(crate) use crate::{
node_runtime,
TestNodeProcess,
};
pub(crate) use crate::{node_runtime, TestNodeProcess};
use sp_core::sr25519::Pair;
use sp_keyring::AccountKeyring;
use subxt::{
tx::PairSigner,
SubstrateConfig,
};
use subxt::{tx::PairSigner, SubstrateConfig};
/// substrate node should be installed on the $PATH
const SUBSTRATE_NODE_PATH: &str = "substrate";
@@ -20,8 +14,10 @@ const SUBSTRATE_NODE_PATH: &str = "substrate";
pub async fn test_context_with(key: AccountKeyring) -> TestContext {
let path = std::env::var("SUBSTRATE_NODE_PATH").unwrap_or_else(|_| {
if which::which(SUBSTRATE_NODE_PATH).is_err() {
panic!("A substrate binary should be installed on your path for integration tests. \
See https://github.com/paritytech/subxt/tree/master#integration-testing")
panic!(
"A substrate binary should be installed on your path for integration tests. \
See https://github.com/paritytech/subxt/tree/master#integration-testing"
)
}
SUBSTRATE_NODE_PATH.to_string()
});
@@ -4,21 +4,11 @@
use sp_keyring::AccountKeyring;
use std::{
ffi::{
OsStr,
OsString,
},
io::{
BufRead,
BufReader,
Read,
},
ffi::{OsStr, OsString},
io::{BufRead, BufReader, Read},
process,
};
use subxt::{
Config,
OnlineClient,
};
use subxt::{Config, OnlineClient};
/// Spawn a local substrate node for testing subxt.
pub struct TestNodeProcess<R: Config> {
@@ -53,7 +43,7 @@ where
if let Err(err) = self.proc.kill() {
let err = format!("Error killing node process {}: {}", self.proc.id(), err);
tracing::error!("{}", err);
return Err(err)
return Err(err);
}
Ok(())
}
@@ -143,24 +133,21 @@ fn find_substrate_port_from_output(r: impl Read + Send + 'static) -> u16 {
BufReader::new(r)
.lines()
.find_map(|line| {
let line =
line.expect("failed to obtain next line from stdout for port discovery");
let line = line.expect("failed to obtain next line from stdout for port discovery");
// does the line contain our port (we expect this specific output from substrate).
let line_end = line
.rsplit_once("Listening for new connections on 127.0.0.1:")
.or_else(|| {
line.rsplit_once("Running JSON-RPC WS server: addr=127.0.0.1:")
})
.or_else(|| line.rsplit_once("Running JSON-RPC WS server: addr=127.0.0.1:"))
.map(|(_, port_str)| port_str)?;
// trim non-numeric chars from the end of the port part of the line.
let port_str = line_end.trim_end_matches(|b: char| !b.is_ascii_digit());
// expect to have a number here (the chars after '127.0.0.1:') and parse them into a u16.
let port_num = port_str.parse().unwrap_or_else(|_| {
panic!("valid port expected for log line, got '{port_str}'")
});
let port_num = port_str
.parse()
.unwrap_or_else(|_| panic!("valid port expected for log line, got '{port_str}'"));
Some(port_num)
})
@@ -2,10 +2,7 @@
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
use subxt::{
client::OnlineClientT,
Config,
};
use subxt::{client::OnlineClientT, Config};
/// Wait for blocks to be produced before running tests. Waiting for two blocks
/// (the genesis block and another one) seems to be enough to allow tests
+13 -30
View File
@@ -3,17 +3,12 @@
// see LICENSE for license details.
use std::{
env,
fs,
env, fs,
net::TcpListener,
ops::{
Deref,
DerefMut,
},
ops::{Deref, DerefMut},
path::Path,
process::Command,
thread,
time,
thread, time,
};
static SUBSTRATE_BIN_ENV_VAR: &str = "SUBSTRATE_NODE_PATH";
@@ -25,8 +20,7 @@ async fn main() {
async fn run() {
// Select substrate binary to run based on env var.
let substrate_bin =
env::var(SUBSTRATE_BIN_ENV_VAR).unwrap_or_else(|_| "substrate".to_owned());
let substrate_bin = env::var(SUBSTRATE_BIN_ENV_VAR).unwrap_or_else(|_| "substrate".to_owned());
// Run binary.
let port = next_open_port().expect("Cannot spawn substrate: no available ports");
@@ -38,8 +32,10 @@ async fn run() {
let mut cmd = match cmd {
Ok(cmd) => KillOnDrop(cmd),
Err(ref e) if e.kind() == std::io::ErrorKind::NotFound => {
panic!("A substrate binary should be installed on your path for testing purposes. \
See https://github.com/paritytech/subxt/tree/master#integration-testing")
panic!(
"A substrate binary should be installed on your path for testing purposes. \
See https://github.com/paritytech/subxt/tree/master#integration-testing"
)
}
Err(e) => {
panic!("Cannot spawn substrate command '{substrate_bin}': {e}")
@@ -67,7 +63,7 @@ async fn run() {
match res {
Ok(res) => {
let _ = cmd.kill();
break res
break res;
}
_ => {
thread::sleep(time::Duration::from_secs(1 << retries));
@@ -98,8 +94,7 @@ async fn run() {
.expect("Path to metadata should be stringifiable")
);
let runtime_path = Path::new(&out_dir).join("runtime.rs");
fs::write(runtime_path, runtime_api_contents)
.expect("Couldn't write runtime rust output");
fs::write(runtime_path, runtime_api_contents).expect("Couldn't write runtime rust output");
let substrate_path =
which::which(substrate_bin).expect("Cannot resolve path to substrate binary");
@@ -155,26 +150,14 @@ impl Drop for KillOnDrop {
// Use jsonrpsee to obtain metadata from the node.
mod client {
pub use jsonrpsee::{
client_transport::ws::{
InvalidUri,
Receiver,
Sender,
Uri,
WsTransportClientBuilder,
},
client_transport::ws::{InvalidUri, Receiver, Sender, Uri, WsTransportClientBuilder},
core::{
client::{
Client,
ClientBuilder,
},
client::{Client, ClientBuilder},
Error,
},
};
pub use jsonrpsee::core::{
client::ClientT,
rpc_params,
};
pub use jsonrpsee::core::{client::ClientT, rpc_params};
/// Build WS RPC client from URL
pub async fn build(url: &str) -> Result<Client, Error> {
+2 -8
View File
@@ -3,11 +3,7 @@
// see LICENSE for license details.
use crate::utils::{
dispatch_error::{
ArrayDispatchError,
LegacyDispatchError,
NamedFieldDispatchError,
},
dispatch_error::{ArrayDispatchError, LegacyDispatchError, NamedFieldDispatchError},
generate_metadata_from_pallets_custom_dispatch_error,
};
use frame_metadata::RuntimeMetadataPrefixed;
@@ -21,7 +17,5 @@ pub fn metadata_legacy_dispatch_error() -> RuntimeMetadataPrefixed {
}
pub fn metadata_named_field_dispatch_error() -> RuntimeMetadataPrefixed {
generate_metadata_from_pallets_custom_dispatch_error::<NamedFieldDispatchError>(
vec![],
)
generate_metadata_from_pallets_custom_dispatch_error::<NamedFieldDispatchError>(vec![])
}
+1 -4
View File
@@ -3,10 +3,7 @@
// see LICENSE for license details.
use frame_metadata::{
RuntimeMetadataPrefixed,
StorageEntryMetadata,
StorageEntryModifier,
StorageEntryType,
RuntimeMetadataPrefixed, StorageEntryMetadata, StorageEntryModifier, StorageEntryType,
};
use scale_info::meta_type;
+2 -7
View File
@@ -3,13 +3,8 @@
// see LICENSE for license details.
use scale_info::{
build::{
Fields,
Variants,
},
Path,
Type,
TypeInfo,
build::{Fields, Variants},
Path, Type, TypeInfo,
};
/// See the `ModuleErrorType` in `subxt_codegen` for more info on the different DispatchError
+8 -20
View File
@@ -6,27 +6,17 @@ pub mod dispatch_error;
mod metadata_test_runner;
use frame_metadata::{
v14::RuntimeMetadataV14,
ExtrinsicMetadata,
PalletMetadata,
PalletStorageMetadata,
RuntimeMetadataPrefixed,
StorageEntryMetadata,
};
use scale_info::{
meta_type,
IntoPortable,
TypeInfo,
v14::RuntimeMetadataV14, ExtrinsicMetadata, PalletMetadata, PalletStorageMetadata,
RuntimeMetadataPrefixed, StorageEntryMetadata,
};
use scale_info::{meta_type, IntoPortable, TypeInfo};
pub use metadata_test_runner::MetadataTestRunner;
/// Given some pallet metadata, generate a [`RuntimeMetadataPrefixed`] struct.
/// We default to a useless extrinsic type, and register a fake `DispatchError`
/// type matching the generic type param provided.
pub fn generate_metadata_from_pallets_custom_dispatch_error<
DispatchError: TypeInfo + 'static,
>(
pub fn generate_metadata_from_pallets_custom_dispatch_error<DispatchError: TypeInfo + 'static>(
pallets: Vec<PalletMetadata>,
) -> RuntimeMetadataPrefixed {
// We don't care about the extrinsic type.
@@ -69,12 +59,10 @@ pub fn generate_metadata_from_pallets_custom_dispatch_error<
/// Given some pallet metadata, generate a [`RuntimeMetadataPrefixed`] struct.
/// We default to a useless extrinsic type, and register a fake `DispatchError`
/// type so that codegen is happy with the metadata generated.
pub fn generate_metadata_from_pallets(
pallets: Vec<PalletMetadata>,
) -> RuntimeMetadataPrefixed {
generate_metadata_from_pallets_custom_dispatch_error::<
dispatch_error::ArrayDispatchError,
>(pallets)
pub fn generate_metadata_from_pallets(pallets: Vec<PalletMetadata>) -> RuntimeMetadataPrefixed {
generate_metadata_from_pallets_custom_dispatch_error::<dispatch_error::ArrayDispatchError>(
pallets,
)
}
/// Given some storage entries, generate a [`RuntimeMetadataPrefixed`] struct.