1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-16 06:10:26 +02:00

Publish Comprehensive Rust 🦀

This commit is contained in:
Martin Geisler
2022-12-21 16:36:30 +01:00
commit c212a473ba
252 changed files with 8047 additions and 0 deletions

20
src/testing/doc-tests.md Normal file
View File

@ -0,0 +1,20 @@
# Documentation Tests
Rust has built-in support for documentation tests:
```rust
/// Shorten string will trip the string to the given length.
///
/// ```
/// use playground::shorten_string;
/// assert_eq!(shorten_string("Hello World", 5), "Hello");
/// assert_eq!(shorten_string("Hello World", 20), "Hello World");
/// ```
pub fn shorten_string(s: &str, length: usize) -> &str {
&s[..std::cmp::min(length, s.len())]
}
```
* Code blocks in `///` comments are automatically seen as Rust code.
* The code will be compiled and executed as part of `cargo test`.
* Test the above code on the [Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c8ce535a3778218fed50c2b4c317d15d).

View File

@ -0,0 +1,16 @@
# Integration Tests
If you want to test your library as a client, use an integration test.
Create a `.rs` file under `tests/`:
```rust,ignore
use my_library::init;
#[test]
fn test_init() {
assert!(init().is_ok());
}
```
These tests only have access to the public API of your crate.

View File

@ -0,0 +1,27 @@
# Test Modules
Unit tests are often put in a nested module (run tests on the
[Playground](https://play.rust-lang.org/)):
```rust,editable
fn helper(a: &str, b: &str) -> String {
format!("{a} {b}")
}
pub fn main() {
println!("{}", helper("Hello", "World"));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_helper() {
assert_eq!(helper("foo", "bar"), "foo bar");
}
}
```
* This lets you unit test private helpers.
* The `#[cfg(test)]` attribute is only active when you run `cargo test`.

29
src/testing/unit-tests.md Normal file
View File

@ -0,0 +1,29 @@
# Unit Tests
Mark unit tests with `#[test]`:
```rust,editable
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(idx) => &text[..idx],
None => &text,
}
}
#[test]
fn test_empty() {
assert_eq!(first_word(""), "");
}
#[test]
fn test_single_word() {
assert_eq!(first_word("Hello"), Some("Hello"));
}
#[test]
fn test_multiple_words() {
assert_eq!(first_word("Hello World"), Some("Hello"));
}
```
Use `cargo test` to find and run the unit tests.