পাঠ ১১.২

Test কীভাবে run হবে control করা

Controlling How Tests Are Run

cargo test code compile করে test binary বানায় এবং run করে। Default — সব test parallel-এ চলে এবং passing test-এর output capture (hidden) করে।

cargo test বনাম test binary args

কিছু option cargo test-এর জন্য, কিছু binary (test runner)-এর জন্য। Separator --:

$ cargo test --help        # cargo test-এর option
$ cargo test -- --help     # test binary-র option

Parallel বনাম consecutive

Default parallel — দ্রুত feedback। কিন্তু test-এ shared state (file, env var, working dir) থাকলে interfere করতে পারে।

সবগুলো একে একে চালাতে:

$ cargo test -- --test-threads=1

Slower, কিন্তু safe। আদর্শ সমাধান — প্রতিটা test আলাদা file/env দিয়ে independent করো; এই flag last resort।

println! output দেখা

Default-এ test pass করলে println! capture হয় (hidden)। Fail করলে দেখায়। সব test-এর print দেখতে চাইলে:

$ cargo test -- --show-output

Subset of tests by name

Sample lib:

pub fn add_two(a: u64) -> u64 {
    a + 2
}

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

    #[test]
    fn add_two_and_two() {
        let result = add_two(2);
        assert_eq!(result, 4);
    }

    #[test]
    fn add_three_and_two() {
        let result = add_two(3);
        assert_eq!(result, 5);
    }

    #[test]
    fn one_hundred() {
        let result = add_two(100);
        assert_eq!(result, 102);
    }
}

Single test

$ cargo test one_hundred
running 1 test
test tests::one_hundred ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out

Filter — partial match

$ cargo test add
running 2 tests
test tests::add_three_and_two ... ok
test tests::add_two_and_two ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out

নাম-এ "add" থাকা test-গুলো ran। Module-এর নাম-ও test-এর full name-এর অংশ — তাই module-এর নাম দিলেই সেই module-এর সব test।

#[ignore] দিয়ে slow test বাদ

কিছু test slow — সাধারণ cargo test-এ skip চাও:

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

    #[test]
    fn it_works() {
        let result = add(2, 2);
        assert_eq!(result, 4);
    }

    #[test]
    #[ignore]
    fn expensive_test() {
        // code that takes an hour to run
    }
}
running 2 tests
test tests::expensive_test ... ignored
test tests::it_works ... ok

শুধু ignored test:

$ cargo test -- --ignored

সব (ignored সহ):

$ cargo test -- --include-ignored

এই পাঠ থেকে যা শিখলে

  • -- এর আগে cargo arg, পরে test binary arg।
  • Default parallel; --test-threads=1 consecutive।
  • --show-output — passing test-এর print দেখাও।
  • cargo test name — exact বা partial match।
  • #[ignore] + --ignored / --include-ignored