Читаем Rust by Example полностью

/// The next function divides two numbers.

///

/// # Examples

///

/// ```

/// let result = doccomments::div(10, 2);

/// assert_eq!(result, 5);

/// ```

///

/// # Panics

///

/// The function panics if the second argument is zero.

///

/// ```rust,should_panic

/// // panics on division by zero

/// doccomments::div(10, 0);

/// ```

pub fn div(a: i32, b: i32) -> i32 {

if b == 0 {

panic!("Divide-by-zero error");

}

a / b

}

Tests can be run with cargo test:

$ cargo test

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Doc-tests doccomments

running 3 tests

test src/lib.rs - add (line 7) ... ok

test src/lib.rs - div (line 21) ... ok

test src/lib.rs - div (line 31) ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

<p id="motivation_behind_documentation_tests"><strong><a l:href="#motivation_behind_documentation_tests">Motivation behind documentation tests</a></strong></p>

The main purpose of documentation tests is to serve as examples that exercise the functionality, which is one of the most important guidelines. It allows using examples from docs as complete code snippets. But using ? makes compilation fail since main returns unit. The ability to hide some source lines from documentation comes to the rescue: one may write fn try_main() -> Result<(), ErrorType>, hide it and unwrap it in hidden main. Sounds complicated? Here's an example:

/// Using hidden `try_main` in doc tests.

///

/// ```

/// # // hidden lines start with `#` symbol, but they're still compileable!

/// # fn try_main() -> Result<(), String> { // line that wraps the body shown in doc

/// let res = try::try_div(10, 2)?;

/// # Ok(()) // returning from try_main

/// # }

/// # fn main() { // starting main that'll unwrap()

/// # try_main().unwrap(); // calling try_main and unwrapping

/// # // so that test will panic in case of error

/// # }

/// ```

pub fn try_div(a: i32, b: i32) -> Result {

if b == 0 {

Err(String::from("Divide-by-zero"))

} else {

Ok(a / b)

}

}

<p id="see_also_73"><strong><a l:href="#see_also_73">See Also</a></strong></p>

   • RFC505 on documentation style

   • API Guidelines on documentation guidelines

<p id="integration_testing"><strong><a l:href="#integration_testing">Integration testing</a></strong></p>

Unit tests are testing one module in isolation at a time: they're small and can test private code. Integration tests are external to your crate and use only its public interface in the same way any other code would. Their purpose is to test that many parts of your library work correctly together.

Cargo looks for integration tests in tests directory next to src.

File src/lib.rs:

// Define this in a crate called `adder`.

pub fn add(a: i32, b: i32) -> i32 {

a + b

}

File with test: tests/integration_test.rs:

#[test]

fn test_add() {

assert_eq!(adder::add(3, 2), 5);

}

Running tests with cargo test command:

$ cargo test

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Running target/debug/deps/integration_test-bcd60824f5fbfe19

running 1 test

test test_add ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Перейти на страницу:

Похожие книги

Компьютерные сети. 6-е изд.
Компьютерные сети. 6-е изд.

Перед вами шестое издание самой авторитетной книги по современным сетевым технологиям, написанное признанным экспертом Эндрю Таненбаумом в соавторстве со специалистом компании Google Дэвидом Уэзероллом и профессором Чикагского университета Ником Фимстером. Первая версия этого классического труда появилась на свет в далеком 1980 году, и с тех пор каждое издание книги неизменно становилось бестселлером. В книге последовательно изложены основные концепции, определяющие современное состояние компьютерных сетей и тенденции их развития. Авторы подробно объясняют устройство и принципы работы аппаратного и программного обеспечения, рассматривают все аспекты и уровни организации сетей — от физического до прикладного. Изложение теоретических принципов дополняется яркими, показательными примерами функционирования интернета и компьютерных сетей различного типа. Большое внимание уделяется сетевой безопасности. Шестое издание полностью переработано с учетом изменений, произошедших в сфере сетевых технологий за последние годы, и, в частности, освещает такие технологии, как DOCSIS, 4G и 5G, беспроводные сети стандарта 802.11ax, 100-гигабитные сети Ethernet, интернет вещей, современные транспортные протоколы CUBIC TCP, QUIC и BBR, программно-конфигурируемые сети и многое другое.

Дэвид Уэзеролл , Ник Фимстер , Эндрю Таненбаум

Учебные пособия, самоучители