Skip to main content

Rust + cargo

方針

  • Rust では、標準のテストランナー(cargo test#[test] 属性)を使う

前提

bash
brew install rust

プロジェクト作成

bash
mkdir -p ~/workdir
cd ~/workdir
cargo new sample-cargo --lib
code sample-cargo

最小のコード

src/lib.rs
pub fn add(a: u64, b: u64) -> u64 {
return a + b;
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn two_plus_three_is_five() {
assert_eq!(add(2, 3), 5);
}
}

決まりごと

  • テスト用のモジュールに #[cfg(test)] 属性をつける
  • テスト関数に #[test] 属性をつける
  • メソッド内で assert_eq! などのマッチメソッドを呼ぶ

実行

bash
cargo test

表示例

成功時

txt
   Compiling sample-cargo v0.1.0 (/Users/takaaki/workdir/sample-cargo)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.12s
Running unittests src/lib.rs (target/debug/deps/sample_cargo-e7ae0abce5e33dac)

running 1 test
test tests::two_plus_three_is_five ... ok

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

Doc-tests sample_cargo

running 0 tests

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

失敗時

txt
   Compiling sample-cargo v0.1.0 (/Users/takaaki/workdir/sample-cargo)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.11s
Running unittests src/lib.rs (target/debug/deps/sample_cargo-e7ae0abce5e33dac)

running 1 test
test tests::two_plus_three_is_five ... FAILED

failures:

---- tests::two_plus_three_is_five stdout ----

thread 'tests::two_plus_three_is_five' (1048249) panicked at src/lib.rs:11:9:
assertion `left == right` failed
left: 6
right: 5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
tests::two_plus_three_is_five

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

error: test failed, to rerun pass `--lib`

以下広告