Rust – il linguaggio – 45


Continuo, oggi qui: /usr/local/share/doc/rust/html/book/testing.html.


Bella la citazione di Dijkstra (la trovate là); ci sarebbe anche da citare Wirth ma dovrei googlare (o recuperare un manuale che chissà dov’è finito).
Let’s talk about how to test Rust code. What we will not be talking about is the right way to test Rust code. There are many schools of thought regarding the right and wrong way to write tests. All of these approaches use the same basic tools, and so we’ll show you the syntax for using them.

L’attributo test

At its simplest, a test in Rust is a function that’s annotated with the test attribute. Let’s make a new project with Cargo called adder:


Cargo will automatically generate a simple test when you make a new project. Here’s the contents of src/


Note the #[test]. This attribute indicates that this is a test function. It currently has no body. That’s good enough to pass! We can run the tests with cargo test:


Cargo compiled and ran our tests. There are two sets of output here: one for the test we wrote, and another for documentation tests. We’ll talk about those later. For now, see this line:

test it_works ... ok

Note the it_works. This comes from the name of our function:

fn it_works() {

We also get a summary line:

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

So why does our do-nothing test pass? Any test which doesn’t panic! passes, and any test that does panic! fails. Let’s make our test fail:

fn it_works() {


Rust indicates that our test failed:

test it_works ... FAILED

And that’s reflected in the summary line:

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured

We also get a non-zero status code. We can use $? on OS X and Linux:


On Windows, if you’re using cmd: echo %ERRORLEVEL%.

This is useful if you want to integrate cargo test into other tooling.

We can invert our test’s failure with another attribute: should_panic:

fn it_works() {


Rust provides another macro, assert_eq!, that compares two arguments for equality, non riporto il test.

should_panic tests can be fragile, as it’s hard to guarantee that the test didn’t fail for an unexpected reason. To help with this, an optional expected parameter can be added to the should_panic attribute. The test harness will make sure that the failure message contains the provided text. A safer version of the example above would be:

#[should_panic(expected = "assertion failed")]
fn it_works() {
    assert_eq!("Hello", "world");

That’s all there is to the basics! Let’s write one ‘real’ test:

pub fn add_two(a: i32) -> i32 {
    a + 2

fn it_works() {
    assert_eq!(4, add_two(2));

This is a very common use of assert_eq!: call some function with some known arguments and compare it to the expected output.

Sarà che sono vecchio ma preferisco non automatizzare troppo; io uso dei print nelle funzioni che voglio verificare.

L’attributo ignore

Sometimes a few specific tests can be very time-consuming to execute. These can be disabled by default by using the ignore attribute:

fn it_works() {
    assert_eq!(4, add_two(2));

fn expensive_test() {
    // code that takes an hour to run

Now we run our tests and see that it_works is run, but expensive_test is not.

The expensive tests can be run explicitly using cargo test -- --ignored.
The --ignored argument is an argument to the test binary, and not to Cargo, which is why the command is cargo test -- --ignored.

Il modulo tests

There is one way in which our existing example is not idiomatic: it’s missing the tests module. The idiomatic way of writing our example looks like this: –No non copio/provo/riporto. Se del caso è là.

Lo stesso vale per la directory tests e la documentazione che viene automaticamente prodotta. Troppo specifico per il mio esame :mrgreen:

Posta un commento o usa questo indirizzo per il trackback.



Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di

Stai commentando usando il tuo account Chiudi sessione /  Modifica )

Google photo

Stai commentando usando il tuo account Google. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...

Questo sito utilizza Akismet per ridurre lo spam. Scopri come vengono elaborati i dati derivati dai commenti.

%d blogger hanno fatto clic su Mi Piace per questo: