# 單元測試

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

## 寫第一個測試

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

### #[test] 與 cargo test

`cargo new --lib` 產生的 `src/lib.rs` 本來就附一個測試範例。下面換成購物車小計的函式與兩個測試。

目錄結構：

```text
cart/
├── Cargo.toml
└── src/
    └── lib.rs
```

`src/lib.rs`：

```rust
pub fn subtotal(prices: &[u32]) -> u32 {
    prices.iter().sum()
}

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

    #[test]
    fn sums_all_prices() {
        assert_eq!(subtotal(&[100, 250, 50]), 400);
    }

    #[test]
    fn empty_cart_is_zero() {
        assert_eq!(subtotal(&[]), 0);
    }
}
```

執行 `cargo test`，輸出：

```text
   Compiling cart v0.1.0 (/path/to/cart)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.17s
     Running unittests src/lib.rs (target/debug/build/cart/5106ed74a4c4c761/out/cart-5106ed74a4c4c761)

running 2 tests
test tests::empty_cart_is_zero ... ok
test tests::sums_all_prices ... ok

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

   Doc-tests cart

running 0 tests

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` 是文件註解裡的範例測試，見 [文件測試](/testing-doc)；之後的範例改用 `cargo test --lib` 只跑單元測試

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

`#[cfg(test)]` 表示「只在執行 `cargo test` 時才編譯這段」，所以測試程式碼與測試專用的輔助函式不會進到正式的執行檔裡。`tests` 是一般的子模組，`use super::*;` 把上一層的項目全部引入（見 [模組系統](/modules-system)）。子模組看得到父模組的私有項目，因此單元測試可以直接測沒有 `pub` 的函式。

`src/lib.rs`：

```rust
pub fn total(prices: &[u32], coupon: &str) -> u32 {
    let sum: u32 = prices.iter().sum();
    sum - discount(sum, coupon)
}

fn discount(sum: u32, coupon: &str) -> u32 {
    match coupon {
        "HALF" => sum / 2,
        "TEN" => 10,
        _ => 0,
    }
}

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

    fn sample_cart() -> Vec<u32> {
        vec![120, 80]
    }

    #[test]
    fn private_discount_half() {
        assert_eq!(discount(200, "HALF"), 100);
    }

    #[test]
    fn unknown_coupon_gives_nothing() {
        assert_eq!(total(&sample_cart(), "???"), 200);
    }
}
```

依序執行 `cargo test --lib` 與 `cargo build`，輸出：

```text
   Compiling cart v0.1.0 (/path/to/cart)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.14s
     Running unittests src/lib.rs (target/debug/build/cart/5106ed74a4c4c761/out/cart-5106ed74a4c4c761)

running 2 tests
test tests::private_discount_half ... ok
test tests::unknown_coupon_gives_nothing ... ok

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

   Compiling cart v0.1.0 (/path/to/cart)
    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 == b` | `left` 與 `right` 的值 |
| `assert_ne!(a, b)` | `a != b` | `left` 與 `right` 的值 |

三個巨集都可以在最後加上格式字串與參數當作自訂訊息，像 `println!` 一樣。`assert_eq!` 與 `assert_ne!` 需要兩邊的型別實作 `PartialEq` 與 `Debug`（見 [std::cmp](/pkg-cmp) 與 [std::fmt](/pkg-fmt)）。

沿用上一個範例的 `total` 與 `discount`，把 `tests` 模組換成：

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

    #[test]
    fn coupon_lowers_total() {
        let t = total(&[300], "TEN");
        assert!(t < 300, "expected a discount, got {}", t);
        assert_ne!(t, 0);
    }

    #[test]
    fn half_price() {
        let t = total(&[99], "HALF");
        assert_eq!(t, 49, "99 with HALF should be 49");
    }
}
```

執行 `cargo test --lib`，輸出：

```text
   Compiling cart v0.1.0 (/path/to/cart)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.08s
     Running unittests src/lib.rs (target/debug/build/cart/5106ed74a4c4c761/out/cart-5106ed74a4c4c761)

running 2 tests
test tests::coupon_lowers_total ... ok
test tests::half_price ... FAILED

failures:

---- tests::half_price stdout ----

thread 'tests::half_price' (<執行緒 ID>) panicked at src/lib.rs:28:9:
assertion `left == right` failed: 99 with HALF should be 49
  left: 50
 right: 49
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::half_price

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

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`：

```rust
pub struct Shelf {
    items: u32,
}

impl Shelf {
    pub fn new(items: u32) -> Shelf {
        Shelf { items }
    }

    pub fn take(&mut self, n: u32) -> u32 {
        if n > self.items {
            panic!("only {} left, cannot take {}", self.items, n);
        }
        self.items -= n;
        self.items
    }
}

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

    #[test]
    #[should_panic(expected = "cannot take 5")]
    fn taking_too_many_panics() {
        let mut s = Shelf::new(3);
        s.take(5);
    }

    #[test]
    #[should_panic(expected = "cannot take 2")]
    fn wrong_expectation() {
        let mut s = Shelf::new(3);
        s.take(1);
    }
}
```

執行 `cargo test --lib`，輸出（省略開頭的 `Compiling`、`Finished`、`Running` 三行）：

```text
running 2 tests
test tests::wrong_expectation - should panic ... FAILED
test tests::taking_too_many_panics - should panic ... ok

failures:

---- tests::wrong_expectation stdout ----
note: test did not panic as expected at src/lib.rs:32:8

failures:
    tests::wrong_expectation

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

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

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

### 回傳 Result 的測試

測試函式也可以回傳 `Result<(), E>`：回傳 `Ok(())` 算通過，回傳 `Err` 算失敗。好處是可以在測試裡用 `?`，不必每一步都 `unwrap`（見 [Result](/errors-result)）。要檢查「應該得到 `Err`」時，則用 `assert!(x.is_err())`。

`config/src/lib.rs`：

```rust
use std::num::ParseIntError;

pub fn parse_port(s: &str) -> Result<u16, ParseIntError> {
    s.trim().parse::<u16>()
}

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

    #[test]
    fn reads_port() -> Result<(), ParseIntError> {
        let port = parse_port(" 8080 ")?;
        assert_eq!(port, 8080);
        Ok(())
    }

    #[test]
    fn err_fails_the_test() -> Result<(), ParseIntError> {
        let port = parse_port("70000")?;
        assert_eq!(port, 0);
        Ok(())
    }

    #[test]
    fn huge_port_is_err() {
        assert!(parse_port("70000").is_err());
    }
}
```

執行 `cargo test --lib`，輸出（省略開頭的 `Compiling`、`Finished`、`Running` 三行）：

```text
running 3 tests
test tests::reads_port ... ok
test tests::huge_port_is_err ... ok
test tests::err_fails_the_test ... FAILED

failures:

---- tests::err_fails_the_test stdout ----
Error: ParseIntError { kind: PosOverflow }


failures:
    tests::err_fails_the_test

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

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`：

```rust
pub fn km_to_m(km: u32) -> u32 {
    km * 1000
}

pub fn m_to_cm(m: u32) -> u32 {
    m * 100
}

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

    #[test]
    fn km_basic() {
        assert_eq!(km_to_m(3), 3000);
    }

    #[test]
    fn km_zero() {
        assert_eq!(km_to_m(0), 0);
    }

    #[test]
    fn m_basic() {
        assert_eq!(m_to_cm(2), 200);
    }

    #[test]
    #[ignore = "slow: checks every value"]
    fn m_exhaustive() {
        for m in 0..10_000_000 {
            assert_eq!(m_to_cm(m) / 100, m);
        }
    }
}
```

依序執行四個指令：

```text
$ cargo test --lib
$ cargo test --lib km
$ cargo test --lib -- --exact tests::m_basic
$ cargo test --lib -- --ignored
```

輸出（省略每次開頭的 `Finished` 與 `Running` 行）：

```text
running 4 tests
test tests::m_exhaustive ... ignored, slow: checks every value
test tests::km_basic ... ok
test tests::km_zero ... ok
test tests::m_basic ... ok

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

running 2 tests
test tests::km_basic ... ok
test tests::km_zero ... ok

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

running 1 test
test tests::m_basic ... ok

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

running 1 test
test tests::m_exhaustive ... ok

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` 處理慢速測試

## 資料來源

- [The Rust Programming Language（章節架構參考）](https://doc.rust-lang.org/book/)
- [The Rust Reference](https://doc.rust-lang.org/reference/)
- [Rust 標準庫文件](https://doc.rust-lang.org/std/)
- [Rust 官方部落格](https://blog.rust-lang.org/)
