test_on_host.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. #![cfg_attr(test, allow(unused_imports))]
  19. #![cfg_attr(not(test), no_std)]
  20. #![cfg_attr(not(test), no_main)]
  21. // pick a panicking behavior
  22. #[cfg(not(test))]
  23. use panic_halt as _; // you can put a breakpoint on `rust_begin_unwind` to catch panics
  24. // use panic_abort as _; // requires nightly
  25. // use panic_itm as _; // logs messages over ITM; requires ITM support
  26. // use panic_semihosting as _; // logs messages to the host stderr; requires a debugger
  27. use cortex_m::asm;
  28. use cortex_m_rt::entry;
  29. #[cfg(not(test))]
  30. #[entry]
  31. fn main() -> ! {
  32. asm::nop(); // To not have main optimize to abort in release mode, remove when you add code
  33. loop {
  34. // your code goes here
  35. }
  36. }
  37. fn add(a: i32, b: i32) -> i32 {
  38. a + b
  39. }
  40. #[cfg(test)]
  41. mod test {
  42. use super::*;
  43. #[test]
  44. fn foo() {
  45. println!("tests work!");
  46. assert!(2 == add(1,1));
  47. }
  48. }