Is there any point in avoiding std when testing a no_std library?

I'm working on adding no_std support to a library of mine, but a large number of tests contain one or two lines each that use ToString and/or format!. At the moment, I'm wrapping these lines in #[cfg(feature = "std")] { ... } so that they're simply ignored when testing with the std feature disabled, but then I ran into problems when I got to some other tests that use rstest, which depends on std.

In an issue about no_std support in rstest, the maintainer stated:

Ok, I did some research and tried to understand better what mean to test something that use #![no_std] and my conclusion is that doesn't have any sense :slight_smile: ... you cannot start test runner and write any assert without std library so when run your test you already have an std dependency.

Is this true? Are "truly no_std" tests impossible? Should I always feel free to use std in tests even when the non-test code is no_std? I know I can use std via #[cfg(test)] extern crate std;, but is this wise?

If your library is no_std because it's pure functionality with no OS interaction, then it should run the same whether std is there or not, and therefore testing with std is fine. If it's no_std because it runs on a platform without std, things might be different, I'm not sure.

1 Like

As a practical matter, I maintain many no_std crates: memchr, aho-corasick, regex-syntax, regex-automata, regex, bstr, csv-core and probably more. Some even support no-alloc configurations. All of them use std in tests. I haven't experienced any particular problem with this approach in my years of doing it.

2 Likes

What do you mean by "truly no_std tests"? Do you have a reason to run tests in an environment without the standard library? Of course it's possible to do so, it's just not ideal. defmt-test is an example.