The #[test] attribute

The #[test] attribute

How to generate test binaries by #[test] attributes in Rust

5adf99f4151eed6672480564b244396a?s=128

Daichi Mukai

July 20, 2019
Tweet

Transcript

  1. The The #[test] #[test] attribute attribute

  2. //! test.rs #[test] fn my_test() { assert!(2 + 2 ==

    4); }
  3. $ rustc --test test.rs $ ./test running 1 test test

    my_test ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0
  4. どういう仕組み︖ どういう仕組み︖ $ rustc --emit=asm --test rust.rs $ wc -l

    test.rs 4 test.rs $ wc -l test.s 2406 test.s
  5. HIR HIR Rust のコンパイル︓ 1. Rust source 2. HIR 3.

    MIR 4. LLVM IR 5. Machine code HIR を⾒てみる $ rustc +nightly --test -Z unpretty=hir test.rs
  6. STEP1. RE-EXPORT STEP1. RE-EXPORT どうやって crate root から test_my_priv_func を⾒

    るか︖ mod my_priv_func { fn my_priv_func() -> bool { true } #[test] fn test_my_priv_func() { assert!(my_priv_func()); } }
  7. pub にして re-exportする mod my_priv_func { fn my_priv_func() -> bool

    { true } // 正確には少し違う pub fn test_my_priv_func() { assert!(my_priv_func()); } pub mod __test_reexports { pub use super::test_my_priv_func; } }
  8. STEP2. HARNESS GENERATION STEP2. HARNESS GENERATION テスト⽤の main #[main] pub

    fn main() { extern crate test; test::test_main_static(&[&path::to::test1, /*...*/]); }
  9. STEP3. TEST OBJECT STEP3. TEST OBJECT GENERATION GENERATION test::TestDesc で

    configuration を指定できる pub struct TestDesc { pub name: TestName, pub ignore: bool, pub should_panic: ShouldPanic, pub allow_fail: bool, }