能否让Rust测试不在特定OS运行?如何仅在Linux执行?
Question 1: Can I write Rust tests that don't run on specific operating systems?
Absolutely! Rust’s conditional compilation system (via the cfg attribute) makes this straightforward. You have two main options:
- Exclude tests entirely from certain OSes (they won’t be compiled or show up in test results at all)
- Ignore tests on specific OSes (they’ll appear as "skipped" in test output instead of being excluded)
Question 2: How to make my existing test run only on Linux, not Windows?
For your provided test code, you can add the #[cfg(target_os = "linux")] attribute directly to the test function to restrict it to Linux. Here’s the modified version:
#[cfg(test)] mod tests { #[test] #[cfg(target_os = "linux")] fn test_something() { // content of test function } }
This tells the Rust compiler to only include test_something when building for Linux. On Windows, this test won’t be compiled at all, so it won’t appear in your test runs.
If you prefer to have the test show up as "skipped" (instead of being completely excluded) on non-Linux systems, use the ignore attribute with a conditional:
#[cfg(test)] mod tests { #[test] #[cfg_attr(not(target_os = "linux"), ignore)] fn test_something() { // content of test function } }
This way, the test is compiled on all OSes but only runs on Linux—on Windows, it’ll be marked as skipped in your test output.
内容的提问来源于stack exchange,提问作者ka s

