DAILY DOCDAILY DOC
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
  • rust

    • Rust
    • add
    • 属性(attributes)
    • cargo issue
    • cli
    • build.rs
    • Enums
    • eventEmitter(rust)
    • 格式化输出 std::fmt
    • rust iterator
    • rust 学习计划
    • 生命周期(lifetime)
    • Linked List
    • log
    • macros
    • mem::size_of
    • niche optimization
    • Rust 所有权
    • 模式匹配(pattern matching)
    • module system
    • result & option
    • .rust-analyzer.json
    • rust startup
    • rust-test
    • 可见性(visibility)
    • cargo
    • toml

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关注点:

  1. 单元测试
  2. 继承测试
  3. doc 测试
  4. examples
  5. 项目规范

https://github.com/ibuidl/template-lib-crate

进阶 修改 ci.yaml 通过 github actions 自动更新 crate

Last Updated:
Contributors: rosendo
Prev
rust startup
Next
可见性(visibility)