0

I have a fn main that is parsing arguments via StructOpt .. Args::from_args.

Is there a way to create this Args object without actually starting the executable for testing? Can I just create a Args object directly?

Can I do this for example

fn test_function() {
    let args = Args::default();
    args.param1 = "value1";
    args.param2 = "value2";

    core_function(args);
}

fn main() {
    let args = Args::from_args();
    core_function(args);
}
user855
  • 19,048
  • 38
  • 98
  • 162
  • Is `Args` an external type? Typically you define your own struct and just `#[derive(StructOpt)]` on it, meaning you can initialize it any way you like. – Mac O'Brien Jul 07 '20 at 05:25

1 Answers1

2

Yes, structopt also provides from_iter and from_iter_safe which do what you'd expect: they take iterables of strings, and parse those as if they were CLI args.

All of them really delegate to clap, but semantically from_args just calls from_iter with args_os() as parameter.

from_iter_safe is probably the one you want to use in a test: much like from_args, from_iter will print an error message and immediately exit if a parsing / matching error occurs.

Masklinn
  • 34,759
  • 3
  • 38
  • 57