cargo icon indicating copy to clipboard operation
cargo copied to clipboard

`cargo test` should support testing individual file(s)

Open rouge8 opened this issue 2 years ago • 1 comments

Problem

I'm trying to run all of the tests for the file I'm currently editing, but cargo test currently has no way to do this.

For unit tests, you can filter tests by module name, but there's no guarantee that only runs tests for the current file, especially for main.rs / lib.rs / mod.rs where the module name is just tests::, which will match any files with a tests:: module.

For integration tests, you can use cargo test --test NAME, but that doesn't work if your integration tests aren't in the top level tests/ directory, e.g. tests/feature1/mytest.rs.

Proposed Solution

Perhaps a cargo test --file FILE option to run tests for a single file. This option could also be repeated to run tests from multiple files.

Notes

No response

rouge8 avatar Jul 24 '22 00:07 rouge8

It's a bit unlucky that Cargo has no knowledge about filesystem in terms of tests. And neither does the underlying test harness libtest. Currently the only way to filter tests I could think of is by their module paths. You can pass arg --list to libtest to inspect all test functions in your target, and then decide which tests you are going to run.

For mod.rs, it should always got a more specific module name, you can use its name to filter, such like cargo test -- my_module::. For modules that are named tests under main.rs/lib.rs, indeed they are harder to tell them apart from others, as passing tests:: might include tests in other files. Yet you always get chances to rename module tests to differentiate them.

weihanglo avatar Jul 24 '22 09:07 weihanglo

I'm going to close as this is unlikely something that is going to be supported. Cargo doesn't control the test running, and the libtest harness doesn't really know about files. I suggest leaning on module names to accomplish the appropriate filtering as suggested by @weihanglo.

ehuss avatar Aug 13 '22 19:08 ehuss