Passing CLI argument to a testcase in cargo test

I have a unit test in my code and i want to pass a CLI argument to this particular test. i.e This particular test needs a path value to further proceed. I know that we usually embed these kind argument as values inside testcases. But since I want to try out this testcase with multiple path values and I don't want to compile multiple times the same testcase with different path value, I need to pass CLI argument to this unit testcase. how do i do this?
I know that arguments after -- in cargo test goes to testcases but I need something like this

cargo test --p some_package -- my_unit_test --path path_to_config

AFAIK there is no straightforward way do this, but it makes sense if you think about it -- you want your tests to be reproducible and deterministic, so it is usually the case that test resources are part of your project, and can therefore be statically known as source code. For example, if you have some kind of CI set up, your test files will very much be part of your project.

All in all, it might be good to do something like this:

#[cfg(test)]
mod tests {
    const TEST_FILES: [&'static str, N] = [
        "relative/path/to/file1",
        ...
        "relative/path/to/fileN",
    ];

    #[test]
    fn works_on_files() {
        /// Something with TEST_FILES
    }
}

If you really want the flexibility of adding and removing files without recompiling, then making a small utility subroutine to read files at a known location (e.g., relative/path/to/ above) still relative to your project root might be worth it.

I know it's not what you asked for at all, sorry about that.

2 Likes

in a test crate, you can parse the command line argument just like a binary crate, you just need to skip or ignore the test harness specific flags, such as --nocapture, --color, --format etc.

basically you have two --, one for cargo, one for libtest's main, then you can add whatever command line arguments you like.

#[test]
fn baz() {
	for x in std::env::args() {
		println!("{x}");
	}
}

the output looks like:

❯ cargo test --  baz --nocapture -- --my-config path/to/config/file
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src\lib.rs (target\debug\deps\hello-8454e341a3b6a8ee.exe)

running 1 test
Y:\hello\target\debug\deps\hello-8454e341a3b6a8ee.exe
baz
--nocapture
--
--my-config
path/to/config/file
test baz ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.