rust-test
- Unit
- Integration
- Docs
- Benches
- examples
Unit Test
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
Integration Test
// tests/integration_test.rs
use hello_world;
#[test]
fn it_adds_two() {
assert_eq!(hello_world::add(2, 2), 4);
}
Common Libs
│── tests/
│ ├── common
│ ├── mod.rs
│ ├── integration.rs
common/mod.rs
instead of common.rs
Doc Tests
cargo test --doc
//! # Utils
//! A module help do mathematic calculation
mod utils {
/// Adds two to the given number.
///
/// # Examples
///
/// ```
/// let result = my_crate::add_two(2);
/// assert_eq!(result, 4);
/// ```
/// # Panics
/// # Errors
/// # Safety
pub fn add_two(x: i32) -> i32 {
x + 2
}
}
Benches
unstable 需要用 nightly 版本
cargo test --benches
cargo test --bench xxx;
├── benches/
│ ├── large-input.rs
│ └── multi-file-bench/
│ ├── main.rs
│ └── bench_module.rs
#[test]
#[bench]
fn bench_add_two(b: &mut Bencher) {
b.iter(|| add_two(2));
}
Examples
cargo run --example xxx
cargo test --examples
cargo test --example xxx
├── examples/
│ ├── simple.rs
│ └── multi-file-example/
│ ├── main.rs
│ └── ex_module.rs
目录结构规范
├── Cargo.lock
├── Cargo.toml
├── src/
│ ├── lib.rs
│ ├── main.rs
│ └── bin/ #
│ ├── named-executable.rs
│ ├── another-executable.rs
│ └── multi-file-executable/
│ ├── main.rs
│ └── some_module.rs
├── benches/ # 基准测试
│ ├── large-input.rs
│ └── multi-file-bench/
│ ├── main.rs
│ └── bench_module.rs
├── examples/ # example
│ ├── simple.rs
│ └── multi-file-example/
│ ├── main.rs
│ └── ex_module.rs
└── tests/ # 集成测试
├── some-integration-tests.rs
└── multi-file-test/
├── main.rs
└── test_module.rs
课后习题
结合本堂课内容,参考如下模版 创建并发布一个crate
到crates.io
关注点:
- 单元测试
- 继承测试
- doc 测试
- examples
- 项目规范
https://github.com/ibuidl/template-lib-crate
进阶 修改 ci.yaml
通过 github actions
自动更新 crate