整合測試

最後更新


把測試放在專案根目錄的 tests/ 資料夾,以「外部使用者」的身分呼叫函式庫的公開 API,確認各部分組合起來能正常運作。

tests/ 目錄


單元測試寫在原始碼旁邊,測單一函式、也能碰私有細節;整合測試(integration test)則站在外面,只能用別人 use 得到的東西。兩者互補:
單元測試整合測試
位置src/ 裡的 #[cfg(test)] mod teststests/*.rs
能測什麼公開與私有項目只有公開 API
編譯方式和函式庫一起編譯每個檔案各自是一個獨立的 crate
需要 #[cfg(test)]需要不需要,Cargo 只在測試時編譯 tests/

第一個整合測試


tests/ 底下每個 .rs 檔都會被編譯成一個獨立的測試執行檔。檔案裡用套件名稱 use 函式庫,就像依賴一個外部 crate。
目錄結構:
  1. wordcount/
  2. ├── Cargo.toml
  3. ├── src/
  4. │ └── lib.rs
  5. └── tests/
  6. └── counting.rs

src/lib.rs:
  1. use std::collections::BTreeMap;
  2. pub fn count_words(text: &str) -> BTreeMap<String, usize> {
  3. let mut counts = BTreeMap::new();
  4. for word in text.split_whitespace() {
  5. *counts.entry(normalize(word)).or_insert(0) += 1;
  6. }
  7. counts
  8. }
  9. fn normalize(word: &str) -> String {
  10. word.trim_matches(|c: char| !c.is_alphanumeric())
  11. .to_lowercase()
  12. }

tests/counting.rs:
  1. use wordcount::count_words;
  2. #[test]
  3. fn counts_repeated_words() {
  4. let counts = count_words("the cat and the hat");
  5. assert_eq!(counts["the"], 2);
  6. assert_eq!(counts["cat"], 1);
  7. }
  8. #[test]
  9. fn ignores_case_and_punctuation() {
  10. let counts = count_words("Rust, rust! RUST.");
  11. assert_eq!(counts.len(), 1);
  12. assert_eq!(counts["rust"], 3);
  13. }

執行 cargo test,輸出:
  1. Compiling wordcount v0.1.0 (/path/to/wordcount)
  2. Finished `test` profile [unoptimized + debuginfo] target(s) in 0.25s
  3. Running unittests src/lib.rs (target/debug/build/wordcount/47da67109e8938e9/out/wordcount-47da67109e8938e9)
  4. running 0 tests
  5. test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  6. Running tests/counting.rs (target/debug/build/wordcount/622f246b72c58949/out/counting-622f246b72c58949)
  7. running 2 tests
  8. test counts_repeated_words ... ok
  9. test ignores_case_and_punctuation ... ok
  10. test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  11. Doc-tests wordcount
  12. running 0 tests
  13. test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

輸出分成三段:unittests src/lib.rs(單元測試)、tests/counting.rs(整合測試)、Doc-tests(文件測試)。Compiling 行實際是專案的絕對路徑,這裡改寫成 /path/to/wordcount;Running 行的雜湊值與各項耗時會因機器而異;測試平行執行,... ok 的順序可能不同。

只能使用公開 API


這段無法編譯:normalize 沒有 pub,整合測試位在函式庫外面,看不到它。
tests/internals.rs:
  1. #[test]
  2. fn normalize_strips_punctuation() {
  3. assert_eq!(wordcount::normalize("Hi!"), "hi");
  4. }

執行 cargo test --test internals,輸出:
  1. error[E0603]: function `normalize` is private
  2. --> tests/internals.rs:3:27
  3. |
  4. 3 | assert_eq!(wordcount::normalize("Hi!"), "hi");
  5. | ^^^^^^^^^ private function
  6. |
  7. note: the function `normalize` is defined here
  8. --> src/lib.rs:11:1
  9. |
  10. 11 | fn normalize(word: &str) -> String {
  11. | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

這正是整合測試的價值:它逼你從使用者的角度檢查 API 是否夠用。私有函式交給同檔的單元測試去測,不要為了測試把它改成 pub。--test 檔名 只編譯並執行 tests/ 底下的那一個檔案。

共用輔助模組


tests/common/mod.rs


多個測試檔常需要同樣的測試資料或輔助函式。把它們放在 tests/common/mod.rs,每個測試檔用 mod common; 引入。
為什麼不寫成 tests/common.rs?因為 tests/ 第一層的每個 .rs 檔都會被當成一個測試 crate,輸出裡會多出一段沒有任何測試的 Running tests/common.rs。放進子目錄的檔案則不會被單獨編譯。
目錄結構:
  1. wordcount/
  2. ├── Cargo.toml
  3. ├── src/
  4. │ └── lib.rs
  5. └── tests/
  6. ├── common/
  7. │ └── mod.rs
  8. ├── counting.rs
  9. ├── ranking.rs
  10. └── sizes.rs

tests/common/mod.rs:
  1. pub fn sample_text() -> &'static str {
  2. "one fish two fish red fish blue fish"
  3. }
  4. pub fn top_word(text: &str) -> (String, usize) {
  5. let counts = wordcount::count_words(text);
  6. counts.into_iter().max_by_key(|(_, n)| *n).unwrap()
  7. }

tests/ranking.rs:
  1. mod common;
  2. #[test]
  3. fn fish_is_most_common() {
  4. let (word, n) = common::top_word(common::sample_text());
  5. assert_eq!(word, "fish");
  6. assert_eq!(n, 4);
  7. }

tests/sizes.rs:
  1. mod common;
  2. use wordcount::count_words;
  3. #[test]
  4. fn sample_has_five_distinct_words() {
  5. let text = common::sample_text();
  6. assert_eq!(count_words(text).len(), 5);
  7. let (_, top) = common::top_word(text);
  8. assert!(top <= text.split_whitespace().count());
  9. }

src/lib.rs 與 tests/counting.rs 同上一節。執行 cargo test --tests(只跑單元與整合測試,略過文件測試),輸出:
  1. Compiling wordcount v0.1.0 (/path/to/wordcount)
  2. Finished `test` profile [unoptimized + debuginfo] target(s) in 0.09s
  3. Running unittests src/lib.rs (target/debug/build/wordcount/47da67109e8938e9/out/wordcount-47da67109e8938e9)
  4. running 0 tests
  5. test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  6. Running tests/counting.rs (target/debug/build/wordcount/622f246b72c58949/out/counting-622f246b72c58949)
  7. running 2 tests
  8. test ignores_case_and_punctuation ... ok
  9. test counts_repeated_words ... ok
  10. test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  11. Running tests/ranking.rs (target/debug/build/wordcount/7dbcb0d1a8924565/out/ranking-7dbcb0d1a8924565)
  12. running 1 test
  13. test fish_is_most_common ... ok
  14. test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  15. Running tests/sizes.rs (target/debug/build/wordcount/735df69356005306/out/sizes-735df69356005306)
  16. running 1 test
  17. test sample_has_five_distinct_words ... ok
  18. test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

注意:common 會被複製進每個引入它的測試 crate 各編譯一次。某個測試檔只用到其中一部分函式時,編譯器會對那個 crate 發出 function ... is never used 的 dead_code 警告;上面讓兩個測試檔都用到兩個輔助函式,所以沒有警告。

binary crate 的測法


把邏輯搬進 lib.rs


只有 src/main.rs 的 binary crate 沒有函式庫可以 use,整合測試寫 use 套件名::... 會得到:
  1. error[E0432]: unresolved import `binonly`
  2. --> tests/t.rs:1:5
  3. |
  4. 1 | use binonly::add;
  5. | ^^^^^^^ use of unresolved module or unlinked crate `binonly`

慣用做法是把邏輯放進 src/lib.rs,main.rs 只負責讀參數、呼叫函式庫、印結果(見 模組系統 的 lib.rs 與 main.rs 並存)。這樣絕大部分的程式都能被整合測試直接呼叫。
目錄結構:
  1. tally/
  2. ├── Cargo.toml
  3. ├── src/
  4. │ ├── lib.rs
  5. │ └── main.rs
  6. └── tests/
  7. ├── cli.rs
  8. └── logic.rs

src/lib.rs:
  1. pub fn summarize(numbers: &[i64]) -> String {
  2. let sum: i64 = numbers.iter().sum();
  3. format!("count={} sum={}", numbers.len(), sum)
  4. }
  5. pub fn parse_args(args: &[String]) -> Result<Vec<i64>, String> {
  6. args.iter()
  7. .map(|a| a.parse::<i64>().map_err(|_| format!("not a number: {}", a)))
  8. .collect()
  9. }

src/main.rs:
  1. use std::env;
  2. use std::process::ExitCode;
  3. fn main() -> ExitCode {
  4. let args: Vec<String> = env::args().skip(1).collect();
  5. match tally::parse_args(&args) {
  6. Ok(nums) => {
  7. println!("{}", tally::summarize(&nums));
  8. ExitCode::SUCCESS
  9. }
  10. Err(e) => {
  11. eprintln!("error: {}", e);
  12. ExitCode::from(2)
  13. }
  14. }
  15. }

tests/logic.rs:
  1. use tally::{parse_args, summarize};
  2. #[test]
  3. fn summarizes_numbers() {
  4. assert_eq!(summarize(&[3, 4, -2]), "count=3 sum=5");
  5. }
  6. #[test]
  7. fn rejects_words() {
  8. let args = vec!["7".to_string(), "x".to_string()];
  9. assert_eq!(parse_args(&args), Err("not a number: x".to_string()));
  10. }

執行 cargo test --test logic,輸出:
  1. Compiling tally v0.1.0 (/path/to/tally)
  2. Finished `test` profile [unoptimized + debuginfo] target(s) in 0.17s
  3. Running tests/logic.rs (target/debug/build/tally/97a44328733ed5cd/out/logic-97a44328733ed5cd)
  4. running 2 tests
  5. test summarizes_numbers ... ok
  6. test rejects_words ... ok
  7. test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

CARGO_BIN_EXE:執行真正的執行檔


main.rs 剩下的部分(參數處理、結束碼、輸出格式)可以直接執行編譯好的程式來測。Cargo 在編譯整合測試時提供 CARGO_BIN_EXE_<執行檔名稱> 環境變數(Rust 1.43 起),值是執行檔的路徑;用 env! 在編譯期取得,再交給 std::process::Command 執行(見 std::process)。
tests/cli.rs:
  1. use std::process::Command;
  2. #[test]
  3. fn prints_summary() {
  4. let out = Command::new(env!("CARGO_BIN_EXE_tally"))
  5. .args(["10", "20"])
  6. .output()
  7. .unwrap();
  8. assert!(out.status.success());
  9. assert_eq!(String::from_utf8_lossy(&out.stdout), "count=2 sum=30\n");
  10. }
  11. #[test]
  12. fn bad_input_exits_with_2() {
  13. let out = Command::new(env!("CARGO_BIN_EXE_tally"))
  14. .arg("ten")
  15. .output()
  16. .unwrap();
  17. assert_eq!(out.status.code(), Some(2));
  18. assert_eq!(
  19. String::from_utf8_lossy(&out.stderr),
  20. "error: not a number: ten\n"
  21. );
  22. }

執行 cargo test --test cli,輸出:
  1. Compiling tally v0.1.0 (/path/to/tally)
  2. Finished `test` profile [unoptimized + debuginfo] target(s) in 0.09s
  3. Running tests/cli.rs (target/debug/build/tally/816a8055e3ae25c8/out/cli-816a8055e3ae25c8)
  4. running 2 tests
  5. test prints_summary ... ok
  6. test bad_input_exits_with_2 ... ok
  7. test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.23s

執行整合測試前,Cargo 會先編譯好 tally 執行檔。因為要啟動外部程序,這組測試花了 0.23s,比直接呼叫函式慢;耗時依機器而異。

重點整理


  • tests/ 下每個 .rs 檔是獨立的 crate,用套件名稱 use 函式庫,只能碰公開 API
  • 私有函式用單元測試測,不要為了整合測試改成 pub
  • 共用輔助程式放 tests/common/mod.rs,各測試檔以 mod common; 引入
  • cargo test --test 檔名 只跑一個整合測試檔,--tests 略過文件測試
  • binary crate 把邏輯移到 lib.rs;要測執行檔本身時用 env!("CARGO_BIN_EXE_名稱") 搭配 Command

資料來源