0

I am developing a cli tool in Rust that takes two arguments and prints them to the console. Here is the code that seems to work when I run it with cargo run:

fn main() {

    #[derive(Debug)]
    struct Cli {
        pattern: String,
        path: std::path::PathBuf,
    }

    let pattern = std::env::args().nth(1).expect("no pattern given");
    let path = std::env::args().nth(2).expect("no path given");
    let args = Cli {
        pattern: pattern,
        path: std::path::PathBuf::from(path),
    };
    println!("{:#?}", args);
}

I'm trying to write an integration that verify it works. Here is what it have, but it just checks that the tool ran without panicking... is there any way to assert that the correct text was printed to the console? Am I wrong for wanting to assert this in my integration test?

use assert_cmd::prelude::*; // Add methods on commands
use predicates::prelude::*; // Used for writing assertions
use std::process::Command; // Run programs

#[test]
fn works_when_passed_two_args() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = Command::cargo_bin("basic_arg_parse")?;

    cmd.arg("foobar").arg("things");
    cmd.assert().success();

    Ok(())
}

#[test]
fn doesnt_work_when_passed_zero_or_one_args() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = Command::cargo_bin("basic_arg_parse")?;

    cmd.assert().failure();

    cmd.arg("foobar");
    cmd.assert().failure();

    Ok(())
}

Also, Here is my Cargo.toml

[package]
name = "basic_arg_parse"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dev-dependencies]
assert_cmd = "2.0.9"
predicates = "3.0.1"
Jim
  • 3,821
  • 1
  • 28
  • 60
  • 2
    Does this answer your question? [How can I test stdin and stdout?](https://stackoverflow.com/questions/28370126/how-can-i-test-stdin-and-stdout) – jthulhu Mar 20 '23 at 18:03
  • 2
    If you're using `Command`, you would use `.output()` to collect the stdout/stderr into `Vec`s that can be inspected. Fortunately, it looks like `.assert()` does that anyway and has a [`.stdout()`](https://docs.rs/assert_cmd/latest/assert_cmd/assert/struct.Assert.html#method.stdout) function that can be used. Did you try that? – kmdreko Mar 20 '23 at 18:46
  • I have to experiment with it to really know, but I think so. Thanks! – Jim Mar 22 '23 at 02:00

0 Answers0