I have a mixed embedded project, C and Rust. The rust code is compiled into a staticlib crate and then included in the C project.
Some of the functionality depend on specific hardware on the embedded device that we mock with rust/c functions as necessary in unit tests that run on the build machine. Today we use a feature called testing to switch between the real implementations and the mocks. We knew when we implemented it that we were abusing features since they should be additive. However now I would like to refactor the project so that it works better with RA, clippy and so on. (Basically so that I can use --all-features.)
My idea was to try to compile the staticlib so that cfg(test) is true. Is that possible? Because then I could use something like the following to switch to the mocks:
#[cfg(test)]
use mocks as lib;
#[cfg(not(test))]
use lib;
I tried setting "RUSTFLAGS=--test", but then of course it compiles build scripts and dependencies with that flag.
If you have any other ideas how to switch between real implementations and mocks in a rust staticlib I'm also open for that.
Technically it is being tested, but the unit tests are written in C. But perhaps I should focus on porting the unit tests first. It is a mixed project until everything has been ported. I guess there are no really good examples of what I want to do.
Move all of the functions that you want to mock to module foo.
Create module foo_mocked where you use mocked functions.
In build.rs detect env variable ENABLE_MOCK and depending on its value emit source code that either includes module foo or module foo_mocked in your library.
Note that you can configure build.rs to rerun only when this env variable changes, so in normal development you should not pay the cost of recompiling module foo constantly.
This would allow you to configure features and enabling mocking independently of each other. In your CI you would just enable env variable when you are building a version of your library that you want to test, and for production and development everything stays the same.