Cargo test without linking

Hello!

So, I am building a Rust OS and I am currently writing the testing suite for it. While cargo build works as expected (without linking), cargo test fails with exception "linking with rust-lld failed." It is important to mention that my makefile performs multiple linking steps and therefore I need to generate a non-linked binary after I run cargo test. Is that currently possible in Rust?

cargo test passes the --test option to rustc, which compiles the code with crate-type = bin and links against libtest, and they are required to built with panic = unwind by default.

although you can use a custom test harness to replace libtest, by sepecifying harness = false in Cargo.toml, you can even try the unstable command line option -Z panic-abort-tests, I don't think you can change the crate-type (e.g. to something like staticlib or cdylib), it is hardcoded to be bin.

the build script can emit a cargo:rustc-link-arg-tests=FLAG line to affect how the tests are links. maybe you can do some tricks in build.rs to emulate your custom build process? what exact build steps do you use?

The procedure of compiling the Kernel does many (many) things, including building the user file system, compiling assembly code (via NASM) and linking it to the rest of the Kernel, moving the kernel .text and .data to different regions in memory (to make use of virtual memory). I will try your suggestions to see if I can do away with cargo test. If not, I will probably have to "simulate" the testing procedure via the usage of features.

If I am to recreate cargo test, one functionality I would love to have is to be able to loop through all testing functions (functions with the test feature) and run them individually, like you can do by re-implementing the Rust test functionality in a no_std environment. Is there an easy way to achieve this?

You could take a look at Testing | Writing an OS in Rust for how to use the unstable custom_test_frameworks feature.

I tried it out, but it also uses cargo test. I can't use the cfg(test) without building in --test mode, and I can't use --test because it tries to link, which I cannot allow due to my build process. I would have to use cfg(feature = "test"), which does not give me a simple way of collecting all tests under a single loop...

You could build up your own test harness which isn't tied to cargo's and rustc's test infrastructure (don't use #[test]) You could use something like Distributed Slice to register the individual tests with your harness.

That could work. I see distributed slice makes it easy to collect all testing harnesses back into a single, central place. I will try it out, thank you!