简体   繁体   中英

Passing arguments to cargo test with clap

The program takes an path to a configuration file. Eg cargo run -- -c path/to/yaml . This does not however work with cargo test. cargo test -- -c path/to/yaml and following error will occur: error: Unrecognized option: 'c' .

Attempts and research

Clap provide a method fn from_args() -> Self , but did not fully know how this would solve the problem. A similar problem was solved by making it a integration test and add

[[test]]
name = "cpp_test"
# path = "tests/cpp_test.rs"   # This is automatic; you can use a different path if you really want to.
harness = false

to the cargo.toml file.
In my case I want to test some functions and thus unit test. I do not believe this would work.

I think the simplest way is to have a fn main_body(args: Args) that does the real work, and then just test main_body by passing the args directly in your source code instead of on the command line.

use clap::Parser; // 3.1.18

#[derive(Parser)]
struct Args {
    #[clap(short, long)]
    name: String,
}

fn main_body(args: Args) -> Result<(), ()> {
    // Your main body here
    Ok(())
}

fn main() -> Result<(), ()> {
    let args = Args::parse();
    main_body(args)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test() {
        let args = Args { name: "Bob".into() };
        assert_eq!(main_body(args), Ok(()));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM