Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#1682: fix help tests #1734

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions cmd/crates/soroban-test/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ sep5 = { workspace = true }
soroban-cli = { workspace = true }
soroban-rpc = { workspace = true }

either = "1.13.0"
thiserror = "1.0.31"
sha2 = "0.10.6"
assert_cmd = "2.0.4"
Expand Down
8 changes: 5 additions & 3 deletions cmd/crates/soroban-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use std::{ffi::OsString, fmt::Display, path::Path};

use assert_cmd::{assert::Assert, Command};
use assert_fs::{fixture::FixtureError, prelude::PathChild, TempDir};
use either::Either;
use fs_extra::dir::CopyOptions;

use soroban_cli::{
Expand Down Expand Up @@ -202,9 +203,10 @@ impl TestEnv {
source: &str,
) -> Result<String, invoke::Error> {
let cmd = self.cmd_with_config::<I, invoke::Cmd>(command_str, None);
self.run_cmd_with(cmd, source)
.await
.map(|r| r.into_result().unwrap())
self.run_cmd_with(cmd, source).await.map(|r| match r {
Either::Left(help) => help,
Either::Right(tx) => tx.into_result().unwrap(),
})
}

/// A convenience method for using the invoke command.
Expand Down
1 change: 1 addition & 0 deletions cmd/crates/soroban-test/tests/it/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ async fn tuple_help() {
#[tokio::test]
async fn strukt_help() {
let output = invoke_custom("strukt", "--help").await.unwrap();
println!("{output}");
assert!(output.contains("--strukt '{ \"a\": 1, \"b\": true, \"c\": \"hello\" }'",));
assert!(output.contains("This is from the rust doc above the struct Test",));
}
Expand Down
12 changes: 6 additions & 6 deletions cmd/crates/soroban-test/tests/it/integration/hello_world.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use predicates::boolean::PredicateBooleanExt;
use soroban_rpc::GetLatestLedgerResponse;

use soroban_cli::{
commands::{
contract::{self, fetch},
txn_result::TxnResult,
},
config::{address::Address, locator, secret},
config::{locator, secret},
};
use soroban_rpc::GetLatestLedgerResponse;
use soroban_test::{AssertExt, TestEnv, LOCAL_NETWORK_PASSPHRASE};

use crate::integration::util::extend_contract;
Expand All @@ -19,8 +19,8 @@ async fn invoke_view_with_non_existent_source_account() {
let sandbox = &TestEnv::new();
let id = deploy_hello(sandbox).await;
let world = "world";
let mut cmd = hello_world_cmd(&id, world);
let res = sandbox.run_cmd_with(cmd, "").await.unwrap();
let cmd = hello_world_cmd(&id, world);
let res = sandbox.run_cmd_with(cmd, "").await.unwrap().unwrap_right();
assert_eq!(res, TxnResult::Res(format!(r#"["Hello",{world:?}]"#)));
}

Expand Down Expand Up @@ -167,7 +167,7 @@ fn hello_world_cmd(id: &str, arg: &str) -> contract::invoke::Cmd {

async fn invoke_hello_world_with_lib(e: &TestEnv, id: &str) {
let cmd = hello_world_cmd(id, "world");
let res = e.run_cmd_with(cmd, "test").await.unwrap();
let res = e.run_cmd_with(cmd, "test").await.unwrap().unwrap_right();
assert_eq!(res, TxnResult::Res(r#"["Hello","world"]"#.to_string()));
}

Expand Down
3 changes: 2 additions & 1 deletion cmd/crates/soroban-test/tests/it/integration/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ pub async fn deploy_contract(
let res = sandbox
.run_cmd_with(cmd, deployer.unwrap_or("test"))
.await
.unwrap();
.unwrap()
.unwrap_right();
match deploy {
DeployKind::BuildOnly | DeployKind::SimOnly => match res.to_envelope() {
commands::txn_result::TxnEnvelopeResult::TxnEnvelope(e) => {
Expand Down
13 changes: 7 additions & 6 deletions cmd/crates/soroban-test/tests/it/util.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::path::Path;

use either::Either;
use soroban_cli::{
commands::contract,
config::{locator::KeyType, secret::Secret},
};
use soroban_test::{TestEnv, Wasm, TEST_ACCOUNT};
use std::path::Path;

pub const CUSTOM_TYPES: &Wasm = &Wasm::Custom("test-wasms", "test_custom_types");

Expand Down Expand Up @@ -54,10 +54,11 @@ pub async fn invoke_custom(
let mut i: contract::invoke::Cmd =
sandbox.cmd_with_config(&["--id", id, "--", func, arg], None);
i.wasm = Some(wasm.to_path_buf());
sandbox
.run_cmd_with(i, TEST_ACCOUNT)
.await
.map(|r| r.into_result().unwrap())
let s = sandbox.run_cmd_with(i, TEST_ACCOUNT).await;
s.map(|r| match r {
Either::Left(help) => help,
Either::Right(tx) => tx.into_result().unwrap(),
})
}

pub const DEFAULT_CONTRACT_ID: &str = "CDR6QKTWZQYW6YUJ7UP7XXZRLWQPFRV6SWBLQS4ZQOSAF4BOUD77OO5Z";
Expand Down
47 changes: 30 additions & 17 deletions cmd/soroban-cli/src/commands/contract/arg_parsing.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
use crate::xdr::{
self, Hash, InvokeContractArgs, ScAddress, ScSpecEntry, ScSpecFunctionV0, ScSpecTypeDef, ScVal,
ScVec,
};
use clap::error::ErrorKind::DisplayHelp;
use clap::value_parser;
use ed25519_dalek::SigningKey;
use heck::ToKebabCase;
use std::collections::HashMap;
use std::convert::TryInto;
use std::ffi::OsString;
use std::fmt::Debug;
use std::path::PathBuf;

use clap::value_parser;
use ed25519_dalek::SigningKey;
use heck::ToKebabCase;

use crate::xdr::{
self, Hash, InvokeContractArgs, ScAddress, ScSpecEntry, ScSpecFunctionV0, ScSpecTypeDef, ScVal,
ScVec,
};

use crate::commands::contract::arg_parsing::HostFunctionParameters::{HelpMessage, Params};
use crate::commands::txn_result::TxnResult;
use crate::config::{self};
use soroban_spec_tools::Spec;
Expand Down Expand Up @@ -45,12 +45,17 @@ pub enum Error {
MissingFileArg(PathBuf),
}

pub enum HostFunctionParameters {
Params((String, Spec, InvokeContractArgs, Vec<SigningKey>)),
HelpMessage(String),
}

pub fn build_host_function_parameters(
contract_id: &stellar_strkey::Contract,
slop: &[OsString],
spec_entries: &[ScSpecEntry],
config: &config::Args,
) -> Result<(String, Spec, InvokeContractArgs, Vec<SigningKey>), Error> {
) -> Result<HostFunctionParameters, Error> {
let spec = Spec(Some(spec_entries.to_vec()));
let mut cmd = clap::Command::new(contract_id.to_string())
.no_binary_name(true)
Expand All @@ -63,12 +68,20 @@ pub fn build_host_function_parameters(
cmd.build();
let long_help = cmd.render_long_help();

// get_matches_from exits the process if `help`, `--help` or `-h`are passed in the slop
// see clap documentation for more info: https://github.com/clap-rs/clap/blob/v4.1.8/src/builder/command.rs#L631
let mut matches_ = cmd.get_matches_from(slop);
let Some((function, matches_)) = &matches_.remove_subcommand() else {
println!("{long_help}");
std::process::exit(1);
// try_get_matches_from returns an error if `help`, `--help` or `-h`are passed in the slop
// see clap documentation for more info: https://github.com/clap-rs/clap/blob/v4.1.8/src/builder/command.rs#L586
let maybe_matches = cmd.try_get_matches_from(slop);
let Some((function, matches_)) = (match maybe_matches {
Ok(mut matches) => &matches.remove_subcommand(),
Err(e) => {
// to not exit immediately (to be able to fetch help message in tests), check for an error
if e.kind() == DisplayHelp {
return Ok(HelpMessage(e.to_string()));
}
e.exit();
}
}) else {
return Ok(HelpMessage(format!("{long_help}")));
Ifropc marked this conversation as resolved.
Show resolved Hide resolved
};

let func = spec.find_function(function)?;
Expand Down Expand Up @@ -145,7 +158,7 @@ pub fn build_host_function_parameters(
args: final_args,
};

Ok((function.clone(), spec, invoke_args, signers))
Ok(Params((function.clone(), spec, invoke_args, signers)))
}

fn build_custom_cmd(name: &str, spec: &Spec) -> Result<clap::Command, Error> {
Expand Down
83 changes: 46 additions & 37 deletions cmd/soroban-cli/src/commands/contract/deploy/wasm.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
use std::array::TryFromSliceError;
use std::ffi::OsString;
use std::fmt::Debug;
use std::num::ParseIntError;

use crate::xdr::{
AccountId, ContractExecutable, ContractIdPreimage, ContractIdPreimageFromAddress,
CreateContractArgs, CreateContractArgsV2, Error as XdrError, Hash, HostFunction,
Expand All @@ -11,11 +6,17 @@ use crate::xdr::{
VecM, WriteXdr,
};
use clap::{arg, command, Parser};
use itertools::Either;
use itertools::Either::{Left, Right};
use rand::Rng;
use regex::Regex;

use soroban_spec_tools::contract as contract_spec;
use std::array::TryFromSliceError;
use std::ffi::OsString;
use std::fmt::Debug;
use std::num::ParseIntError;

use crate::commands::contract::arg_parsing::HostFunctionParameters;
use crate::{
assembled::simulate_and_assemble_transaction,
commands::{
Expand Down Expand Up @@ -128,26 +129,31 @@ pub enum Error {

impl Cmd {
pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> {
let res = self
.run_against_rpc_server(Some(global_args), None)
.await?
.to_envelope();
let res = self.run_against_rpc_server(Some(global_args), None).await?;
match res {
TxnEnvelopeResult::TxnEnvelope(tx) => println!("{}", tx.to_xdr_base64(Limits::none())?),
TxnEnvelopeResult::Res(contract) => {
let network = self.config.get_network()?;

if let Some(alias) = self.alias.clone() {
self.config.locator.save_contract_id(
&network.network_passphrase,
&contract,
&alias,
)?;
}

println!("{contract}");
Left(help) => {
println!("{help}");
}
Right(res) => match res.to_envelope() {
TxnEnvelopeResult::TxnEnvelope(tx) => {
println!("{}", tx.to_xdr_base64(Limits::none())?);
}
TxnEnvelopeResult::Res(contract) => {
let network = self.config.get_network()?;

if let Some(alias) = self.alias.clone() {
self.config.locator.save_contract_id(
&network.network_passphrase,
&contract,
&alias,
)?;
}

println!("{contract}");
}
},
}

Ok(())
}
}
Expand All @@ -167,14 +173,14 @@ fn alias_validator(alias: &str) -> Result<String, Error> {
#[async_trait::async_trait]
impl NetworkRunnable for Cmd {
type Error = Error;
type Result = TxnResult<stellar_strkey::Contract>;
type Result = Either<String, TxnResult<stellar_strkey::Contract>>;

#[allow(clippy::too_many_lines)]
async fn run_against_rpc_server(
&self,
global_args: Option<&global::Args>,
config: Option<&config::Args>,
) -> Result<TxnResult<stellar_strkey::Contract>, Error> {
) -> Result<Either<String, TxnResult<stellar_strkey::Contract>>, Error> {
let print = Print::new(global_args.map_or(false, |a| a.quiet));
let config = config.unwrap_or(&self.config);
let wasm_hash = if let Some(wasm) = &self.wasm {
Expand Down Expand Up @@ -248,15 +254,18 @@ impl NetworkRunnable for Cmd {
} else {
let mut slop = vec![OsString::from(CONSTRUCTOR_FUNCTION_NAME)];
slop.extend_from_slice(&self.slop);
Some(
arg_parsing::build_host_function_parameters(
&stellar_strkey::Contract(contract_id.0),
&slop,
&entries,
config,
)?
.2,
)
let params = arg_parsing::build_host_function_parameters(
&stellar_strkey::Contract(contract_id.0),
&slop,
&entries,
config,
)?;
match params {
HostFunctionParameters::Params(p) => Some(p.2),
HostFunctionParameters::HelpMessage(h) => {
Ifropc marked this conversation as resolved.
Show resolved Hide resolved
return Ok(Left(h));
}
}
}
} else {
None
Expand All @@ -276,7 +285,7 @@ impl NetworkRunnable for Cmd {

if self.fee.build_only {
print.checkln("Transaction built!");
return Ok(TxnResult::Txn(txn));
return Ok(Right(TxnResult::Txn(txn)));
}

print.infoln("Simulating deploy transaction…");
Expand All @@ -286,7 +295,7 @@ impl NetworkRunnable for Cmd {

if self.fee.sim_only {
print.checkln("Done!");
return Ok(TxnResult::Txn(txn));
return Ok(Right(TxnResult::Txn(txn)));
}

print.globeln("Submitting deploy transaction…");
Expand All @@ -307,7 +316,7 @@ impl NetworkRunnable for Cmd {

print.checkln("Deployed!");

Ok(TxnResult::Res(contract_id))
Ok(Right(TxnResult::Res(contract_id)))
}
}

Expand Down
Loading
Loading