單元測試

最後更新


在原始碼旁邊用 #[test] 寫小型測試,以 cargo test 一次執行,確認每個函式的行為符合預期。

寫第一個測試


單元測試(unit test)一次只檢查一小塊程式,通常是一個函式。Rust 把測試框架內建在語言與 Cargo 裡,不需要安裝任何套件:在函式上加 #[test],它就變成測試函式;函式執行完沒有 panic 就算通過,panic 就算失敗。

#[test] 與 cargo test


cargo new --lib 產生的 src/lib.rs 本來就附一個測試範例。下面換成購物車小計的函式與兩個測試。
目錄結構:
  1. cart/
  2. ├── Cargo.toml
  3. └── src/
  4. └── lib.rs

src/lib.rs:
  1. pub fn subtotal(prices: &[u32]) -> u32 {
  2. prices.iter().sum()
  3. }
  4. #[cfg(test)]
  5. mod tests {
  6. use super::*;
  7. #[test]
  8. fn sums_all_prices() {
  9. assert_eq!(subtotal(&[100, 250, 50]), 400);
  10. }
  11. #[test]
  12. fn empty_cart_is_zero() {
  13. assert_eq!(subtotal(&[]), 0);
  14. }
  15. }

執行 cargo test,輸出:
  1. Compiling cart v0.1.0 (/path/to/cart)
  2. Finished `test` profile [unoptimized + debuginfo] target(s) in 0.17s
  3. Running unittests src/lib.rs (target/debug/build/cart/5106ed74a4c4c761/out/cart-5106ed74a4c4c761)
  4. running 2 tests
  5. test tests::empty_cart_is_zero ... ok
  6. test tests::sums_all_prices ... ok
  7. test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  8. Doc-tests cart
  9. running 0 tests
  10. test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

輸出怎麼看:
  • Compiling 行實際是專案的絕對路徑,這裡改寫成 /path/to/cart
  • Running unittests 括號內是測試執行檔,中間的雜湊值每台機器不同
  • 編譯耗時與 finished in 的耗時會因機器而異
  • 測試預設在多個執行緒平行執行,... ok 各行的順序可能和這裡不同
  • Doc-tests 是文件註解裡的範例測試,見 文件測試;之後的範例改用 cargo test --lib 只跑單元測試

#[cfg(test)] 模組:測試私有函式


#[cfg(test)] 表示「只在執行 cargo test 時才編譯這段」,所以測試程式碼與測試專用的輔助函式不會進到正式的執行檔裡。tests 是一般的子模組,use super::*; 把上一層的項目全部引入(見 模組系統)。子模組看得到父模組的私有項目,因此單元測試可以直接測沒有 pub 的函式。
src/lib.rs:
  1. pub fn total(prices: &[u32], coupon: &str) -> u32 {
  2. let sum: u32 = prices.iter().sum();
  3. sum - discount(sum, coupon)
  4. }
  5. fn discount(sum: u32, coupon: &str) -> u32 {
  6. match coupon {
  7. "HALF" => sum / 2,
  8. "TEN" => 10,
  9. _ => 0,
  10. }
  11. }
  12. #[cfg(test)]
  13. mod tests {
  14. use super::*;
  15. fn sample_cart() -> Vec<u32> {
  16. vec![120, 80]
  17. }
  18. #[test]
  19. fn private_discount_half() {
  20. assert_eq!(discount(200, "HALF"), 100);
  21. }
  22. #[test]
  23. fn unknown_coupon_gives_nothing() {
  24. assert_eq!(total(&sample_cart(), "???"), 200);
  25. }
  26. }

依序執行 cargo test --lib 與 cargo build,輸出:
  1. Compiling cart v0.1.0 (/path/to/cart)
  2. Finished `test` profile [unoptimized + debuginfo] target(s) in 0.14s
  3. Running unittests src/lib.rs (target/debug/build/cart/5106ed74a4c4c761/out/cart-5106ed74a4c4c761)
  4. running 2 tests
  5. test tests::private_discount_half ... ok
  6. test tests::unknown_coupon_gives_nothing ... ok
  7. test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  8. Compiling cart v0.1.0 (/path/to/cart)
  9. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.03s

sample_cart 沒有 #[test],是測試用的一般函式,不會被當成測試執行。cargo build 不會編譯 tests 模組,所以沒有「sample_cart 從未使用」的警告。

斷言


assert!、assert_eq!、assert_ne!


斷言(assertion)是「我認為這件事一定成立」的檢查,不成立就 panic,讓測試失敗。
巨集成立條件失敗時印出
assert!(條件)條件為 true條件的原始碼
assert_eq!(a, b)a == bleft 與 right 的值
assert_ne!(a, b)a != bleft 與 right 的值

三個巨集都可以在最後加上格式字串與參數當作自訂訊息,像 println! 一樣。assert_eq! 與 assert_ne! 需要兩邊的型別實作 PartialEq 與 Debug(見 std::cmp 與 std::fmt)。
沿用上一個範例的 total 與 discount,把 tests 模組換成:
  1. #[cfg(test)]
  2. mod tests {
  3. use super::*;
  4. #[test]
  5. fn coupon_lowers_total() {
  6. let t = total(&[300], "TEN");
  7. assert!(t < 300, "expected a discount, got {}", t);
  8. assert_ne!(t, 0);
  9. }
  10. #[test]
  11. fn half_price() {
  12. let t = total(&[99], "HALF");
  13. assert_eq!(t, 49, "99 with HALF should be 49");
  14. }
  15. }

執行 cargo test --lib,輸出:
  1. Compiling cart v0.1.0 (/path/to/cart)
  2. Finished `test` profile [unoptimized + debuginfo] target(s) in 0.08s
  3. Running unittests src/lib.rs (target/debug/build/cart/5106ed74a4c4c761/out/cart-5106ed74a4c4c761)
  4. running 2 tests
  5. test tests::coupon_lowers_total ... ok
  6. test tests::half_price ... FAILED
  7. failures:
  8. ---- tests::half_price stdout ----
  9. thread 'tests::half_price' (<執行緒 ID>) panicked at src/lib.rs:28:9:
  10. assertion `left == right` failed: 99 with HALF should be 49
  11. left: 50
  12. right: 49
  13. note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
  14. failures:
  15. tests::half_price
  16. test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  17. error: test failed, to rerun pass `--lib`

測試抓到一個真實的問題:99 / 2 是整數除法,折扣是 49,結帳金額變成 50。thread 後面括號裡實際是每次不同的執行緒 ID,這裡以 <執行緒 ID> 代替。

其他測試形式


#[should_panic]:預期會 panic


有些函式在輸入不合法時「應該」panic,這種行為也要測。加上 #[should_panic] 後,函式有 panic 才算通過;expected = "文字" 進一步要求 panic 訊息包含這段文字,避免因為別的原因 panic 而誤判通過。
stock/src/lib.rs:
  1. pub struct Shelf {
  2. items: u32,
  3. }
  4. impl Shelf {
  5. pub fn new(items: u32) -> Shelf {
  6. Shelf { items }
  7. }
  8. pub fn take(&mut self, n: u32) -> u32 {
  9. if n > self.items {
  10. panic!("only {} left, cannot take {}", self.items, n);
  11. }
  12. self.items -= n;
  13. self.items
  14. }
  15. }
  16. #[cfg(test)]
  17. mod tests {
  18. use super::*;
  19. #[test]
  20. #[should_panic(expected = "cannot take 5")]
  21. fn taking_too_many_panics() {
  22. let mut s = Shelf::new(3);
  23. s.take(5);
  24. }
  25. #[test]
  26. #[should_panic(expected = "cannot take 2")]
  27. fn wrong_expectation() {
  28. let mut s = Shelf::new(3);
  29. s.take(1);
  30. }
  31. }

執行 cargo test --lib,輸出(省略開頭的 Compiling、Finished、Running 三行):
  1. running 2 tests
  2. test tests::wrong_expectation - should panic ... FAILED
  3. test tests::taking_too_many_panics - should panic ... ok
  4. failures:
  5. ---- tests::wrong_expectation stdout ----
  6. note: test did not panic as expected at src/lib.rs:32:8
  7. failures:
  8. tests::wrong_expectation
  9. test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  10. error: test failed, to rerun pass `--lib`

wrong_expectation 只拿 1 個,沒有 panic,所以失敗。通過的測試即使 panic 了,訊息也會被測試框架收起來,不會印出。何時該用 panic 見 panic!。

回傳 Result 的測試


測試函式也可以回傳 Result<(), E>:回傳 Ok(()) 算通過,回傳 Err 算失敗。好處是可以在測試裡用 ?,不必每一步都 unwrap(見 Result)。要檢查「應該得到 Err」時,則用 assert!(x.is_err())。
config/src/lib.rs:
  1. use std::num::ParseIntError;
  2. pub fn parse_port(s: &str) -> Result<u16, ParseIntError> {
  3. s.trim().parse::<u16>()
  4. }
  5. #[cfg(test)]
  6. mod tests {
  7. use super::*;
  8. #[test]
  9. fn reads_port() -> Result<(), ParseIntError> {
  10. let port = parse_port(" 8080 ")?;
  11. assert_eq!(port, 8080);
  12. Ok(())
  13. }
  14. #[test]
  15. fn err_fails_the_test() -> Result<(), ParseIntError> {
  16. let port = parse_port("70000")?;
  17. assert_eq!(port, 0);
  18. Ok(())
  19. }
  20. #[test]
  21. fn huge_port_is_err() {
  22. assert!(parse_port("70000").is_err());
  23. }
  24. }

執行 cargo test --lib,輸出(省略開頭的 Compiling、Finished、Running 三行):
  1. running 3 tests
  2. test tests::reads_port ... ok
  3. test tests::huge_port_is_err ... ok
  4. test tests::err_fails_the_test ... FAILED
  5. failures:
  6. ---- tests::err_fails_the_test stdout ----
  7. Error: ParseIntError { kind: PosOverflow }
  8. failures:
  9. tests::err_fails_the_test
  10. test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  11. error: test failed, to rerun pass `--lib`

70000 超過 u16 上限 65535,? 把 Err 往外傳,測試印出錯誤的 Debug 格式並判定失敗。
注意:回傳 Result 的測試不能同時加 #[should_panic],這個組合會編譯錯誤。

篩選要跑的測試


名稱篩選、--exact 與 #[ignore]


測試多了以後,常只想跑正在改的那幾個:
指令執行哪些測試
cargo test km名稱(含模組路徑)包含 km 的測試
cargo test -- --exact tests::m_basic名稱完全相同的那一個
cargo test -- --ignored只跑標了 #[ignore] 的測試
cargo test -- --include-ignored全部,包含被忽略的

-- 之後的參數交給測試執行檔,之前的交給 Cargo。很慢或需要特殊環境的測試標上 #[ignore],平常略過,需要時再手動執行;= "原因" 會顯示在輸出中。
units/src/lib.rs:
  1. pub fn km_to_m(km: u32) -> u32 {
  2. km * 1000
  3. }
  4. pub fn m_to_cm(m: u32) -> u32 {
  5. m * 100
  6. }
  7. #[cfg(test)]
  8. mod tests {
  9. use super::*;
  10. #[test]
  11. fn km_basic() {
  12. assert_eq!(km_to_m(3), 3000);
  13. }
  14. #[test]
  15. fn km_zero() {
  16. assert_eq!(km_to_m(0), 0);
  17. }
  18. #[test]
  19. fn m_basic() {
  20. assert_eq!(m_to_cm(2), 200);
  21. }
  22. #[test]
  23. #[ignore = "slow: checks every value"]
  24. fn m_exhaustive() {
  25. for m in 0..10_000_000 {
  26. assert_eq!(m_to_cm(m) / 100, m);
  27. }
  28. }
  29. }

依序執行四個指令:
  1. $ cargo test --lib
  2. $ cargo test --lib km
  3. $ cargo test --lib -- --exact tests::m_basic
  4. $ cargo test --lib -- --ignored

輸出(省略每次開頭的 Finished 與 Running 行):
  1. running 4 tests
  2. test tests::m_exhaustive ... ignored, slow: checks every value
  3. test tests::km_basic ... ok
  4. test tests::km_zero ... ok
  5. test tests::m_basic ... ok
  6. test result: ok. 3 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s
  7. running 2 tests
  8. test tests::km_basic ... ok
  9. test tests::km_zero ... ok
  10. test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s
  11. running 1 test
  12. test tests::m_basic ... ok
  13. test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out; finished in 0.00s
  14. running 1 test
  15. test tests::m_exhaustive ... ok
  16. test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out; finished in 0.06s

filtered out 是被名稱條件排除的數量;耗時依機器而異。

重點整理


  • 函式加 #[test] 就是測試,沒 panic 算通過;cargo test 一次執行全部
  • 單元測試放在同檔的 #[cfg(test)] mod tests,只在測試時編譯,也能測私有函式
  • assert!、assert_eq!、assert_ne! 檢查結果,最後可加自訂訊息
  • #[should_panic(expected = "...")] 測試預期的 panic;回傳 Result 的測試可以用 ?
  • cargo test 名稱 篩選測試,#[ignore] 搭配 -- --ignored 處理慢速測試

資料來源