11 - tests Flashcards
How to make sure that a test function panics with a specific panic message?
add: #[should_panic(expected = "panic because...")] before function signature.
How to make a test fail if it returns an Err(error)?
Add return type to the function signature like so: #[test] fn test_func() -> Result
*You can change String to the desire error type
By default, how many threads would run by calling “cargo test”?
By default, any test run in parallel, each test runs in its own thread.
How can we run test serially?
We can run test serially with the following command:
cargo test – –test-threads=1
*test-threads is an argument given to the resulting binary
How to show stdout output of a test function?
run:
cargo test – –show-output
How can you run a specific test? how can you run a specific test module?
run:
cargo test test_function_name
cargo test test_module_name::
*you can also specify part of the name, and all the function that match the pattern will be tested
How can you ignore a specific test? how can you run only the ignored tests?
to ignore a specific test - add above its signature: #[ignore]
to test all ignored tests, run:
cargo test – –ignored
When will a test module code be compiled? will cargo build do it?
Cargo will only compile the test code under #[cfg(test)] when we run cargo test.
Cargo build won’t do it.
Why there is no need to make internal_adder public for the test modules?
fn internal_adder(a: i32, b: i32) -> i32 { a + b }
#[cfg(test)] mod tests { use super::*;
#[test] fn internal() { assert_eq!(4, internal_adder(2, 2)); } }
Because in Rust, because child module are able to access anything in their parent module, even private fields. (in the example code, tests module is the child)
What is the convention of the location of unit tests in rust?
The convention is that unit test go in the same files as the code you’re testing.
*We use [cfg(test)] to specify that they shouldn’t be included in the compiled result
Where does integration tests are written in Rust?
In Rust, integration tests are entirely external to your library.
We create a tests directory at the top level of our project directory, next to src. Cargo knows to look for integration test files in this directory.
Do integration tests need the #[cfg(test)] annotation?
No, because of their known location. Cargo knows to look for integration test files in the “tests” directory.
What does cargo do with the files in the tests directory?
Cargo will compile each of the files as an individual crate.
The following code won’t compile. Why?
in tests/integration_test.rs: use adder; #[test] fn it_adds_two() { assert_eq!(4, adder::add_two(2)); }
in sec/lib.rs:
fn add_two(a: i32) -> i32 {
a + 2
}
because add_two must be public. In tests directory we test only the public API, and can’t access private functions.
How to run only integration tests?
cargo test –test –integration_test