Friday, January 5, 2024

Unit Tests in Rust


Looking at that list of things to do, one seems obviously simpler than the rest and probably more useful in the short to medium term: getting the unit tests to run.

In fact, it's ridiculously easy. I'm not exactly sure where I copied this from now, but the problem is either I chose the wrong place or didn't copy it very well. The line I have which says
#[cfg(tests)]
is plural when in fact is should be singular
#[cfg(test)]
Yup, that's it. The tests now run. I'm not quite sure why Rust doesn't give a warning about this particular mistake. rust-analyzer says that the config "tests" is "disabled", but my thought had been that meant that there was a configuration "tests" which I had specifically - deliberately or accidentally - disabled, and I spent some time looking through my configuration settings before seeing enough examples on the web where it said cfg(test) that it finally sank in that I had a simple typo.

For those wondering, yes, my code under test passed first time. My test had another error in it, which is I had copied across this (extraneous) line as well which wouldn't compile:
    use alloc::collections::btree_map::Values;
And now I get this output:
   Compiling homer_rust v0.1.0 (/home/gareth/Projects/IgnoranceBlog/homer_rust)
    Finished test [unoptimized + debuginfo] target(s) in 0.32s
     Running unittests src/lib.rs (target/debug/deps/homer_rust-6186d6a57da04f90)

running 1 test
test tests::test_set_4_in_1_from_0 ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests homer_rust

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
This is chattier than I would like, but Rust seems to be that way. Also, for those scoring at home, it's worth noting that if I had had this working at the time, I would have written four or five tests to ensure I wrote the correct code. After the fact, especially with my application now working, I'm not going to bother.

This is checked in as RUST_BARE_METAL_TEST_NOT_TESTS.

No comments:

Post a Comment