|
| 1 | +//! Conditionally compiling tests with std and our executable with no_std. |
| 2 | +//! |
| 3 | +//! Rust's built in unit testing framework requires the standard library, |
| 4 | +//! but we need to build our final executable with no_std. |
| 5 | +//! The testing framework also generates a `main` method, so we need to only use the `#[entry]` |
| 6 | +//! annotation when building our final image. |
| 7 | +//! For more information on why this example works, see this excellent blog post. |
| 8 | +//! https://os.phil-opp.com/unit-testing/ |
| 9 | +//! |
| 10 | +//! Running this example: |
| 11 | +//! |
| 12 | +//! Ensure there are no targets specified under `[build]` in `.cargo/config` |
| 13 | +//! In order to make this work, we lose the convenience of having a default target that isn't the |
| 14 | +//! host. |
| 15 | +//! |
| 16 | +//! cargo build --example test_on_host --target thumbv7m-none-eabi |
| 17 | +//! cargo test --example test_on_host |
| 18 | +
|
| 19 | +#![cfg_attr(test, allow(unused_imports))] |
| 20 | + |
| 21 | +#![cfg_attr(not(test), no_std)] |
| 22 | +#![cfg_attr(not(test), no_main)] |
| 23 | + |
| 24 | +// pick a panicking behavior |
| 25 | +#[cfg(not(test))] |
| 26 | +extern crate panic_halt; // you can put a breakpoint on `rust_begin_unwind` to catch panics |
| 27 | +// extern crate panic_abort; // requires nightly |
| 28 | +// extern crate panic_itm; // logs messages over ITM; requires ITM support |
| 29 | +// extern crate panic_semihosting; // logs messages to the host stderr; requires a debugger |
| 30 | + |
| 31 | +use cortex_m::asm; |
| 32 | +use cortex_m_rt::entry; |
| 33 | + |
| 34 | +#[cfg(not(test))] |
| 35 | +#[entry] |
| 36 | +fn main() -> ! { |
| 37 | + asm::nop(); // To not have main optimize to abort in release mode, remove when you add code |
| 38 | + |
| 39 | + loop { |
| 40 | + // your code goes here |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +fn add(a: i32, b: i32) -> i32 { |
| 45 | + a + b |
| 46 | +} |
| 47 | + |
| 48 | +#[cfg(test)] |
| 49 | +mod test { |
| 50 | + use super::*; |
| 51 | + |
| 52 | + #[test] |
| 53 | + fn foo() { |
| 54 | + println!("tests work!"); |
| 55 | + assert!(2 == add(1,1)); |
| 56 | + } |
| 57 | +} |
0 commit comments