<buttonid="sidebar-toggle"class="icon-button"type="button"title="Toggle Table of Contents"aria-label="Toggle Table of Contents"aria-controls="sidebar">
<ahref="print.html"title="Print this book"aria-label="Print this book">
<iid="print-button"class="fa fa-print"></i>
</a>
</div>
</div>
<divid="search-wrapper"class="hidden">
<formid="searchbar-outer"class="searchbar-outer">
<inputtype="search"name="search"id="searchbar"name="searchbar"placeholder="Search this book ..."aria-controls="searchresults-outer"aria-describedby="searchresults-header">
<p>Testing is a good subject to learn now that we understand modules. Testing your code is very easy in Rust, because you can write tests right next to your code.</p>
<p>The easiest way to start testing is to add <code>#[test]</code> above a function. Here is a simple one:</p>
<p>But if you try to run it in the Playground, it gives an error: <code>error[E0601]: `main` function not found in crate `playground</code>. That's because you don't use <em>Run</em> for tests, you use <em>Test</em>. Also, you don't use a <code>main()</code> function for tests - they go outside. To run this in the Playground, click on <code>···</code> next to <em>RUN</em> and change it to <em>Test</em>. Now if you click on it, it will run the test. (If you have Rust installed already, you will type <code>cargo test</code> to do this)</p>
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
</code></pre>
<p>Let's change <code>assert_eq!(2, 2)</code> to <code>assert_eq!(2, 3)</code> and see what we get. When a test fails you get a lot more information:</p>
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out
</code></pre>
<p><code>assert_eq!(left, right)</code> is the main way to test a function in Rust. If it doesn't work, it will show the different values: left has 2, but right has 3.</p>
<p>What does <code>RUST_BACKTRACE=1</code> mean? This is a setting on your computer to give a lot more information about errors. Luckily the Playground has it too: click on <code>···</code> next to <code>STABLE</code> and set backtrace to <code>ENABLED</code>. If you do that, it will give you <em>a lot</em> of information:</p>
<pre><codeclass="language-text">running 1 test
test two_is_two ... FAILED
failures:
---- two_is_two stdout ----
thread 'two_is_two' panicked at 'assertion failed: 2 == 3', src/lib.rs:3:5
stack backtrace:
0: backtrace::backtrace::libunwind::trace
at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.46/src/backtrace/libunwind.rs:86
1: backtrace::backtrace::trace_unsynchronized
at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.46/src/backtrace/mod.rs:66
2: std::sys_common::backtrace::_print_fmt
at src/libstd/sys_common/backtrace.rs:78
3: <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt
at src/libstd/sys_common/backtrace.rs:59
4: core::fmt::write
at src/libcore/fmt/mod.rs:1076
5: std::io::Write::write_fmt
at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/io/mod.rs:1537
6: std::io::impls::<impl std::io::Write for alloc::boxed::Box<W>>::write_fmt
at src/libstd/io/impls.rs:176
7: std::sys_common::backtrace::_print
at src/libstd/sys_common/backtrace.rs:62
8: std::sys_common::backtrace::print
at src/libstd/sys_common/backtrace.rs:49
9: std::panicking::default_hook::{{closure}}
at src/libstd/panicking.rs:198
10: std::panicking::default_hook
at src/libstd/panicking.rs:215
11: std::panicking::rust_panic_with_hook
at src/libstd/panicking.rs:486
12: std::panicking::begin_panic
at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/panicking.rs:410
13: playground::two_is_two
at src/lib.rs:3
14: playground::two_is_two::{{closure}}
at src/lib.rs:2
15: core::ops::function::FnOnce::call_once
at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libcore/ops/function.rs:232
16: <alloc::boxed::Box<F> as core::ops::function::FnOnce<A>>::call_once
at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/liballoc/boxed.rs:1076
17: <std::panic::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once
at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/panic.rs:318
18: std::panicking::try::do_call
at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/panicking.rs:297
19: std::panicking::try
at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/panicking.rs:274
20: std::panic::catch_unwind
at /rustc/c367798cfd3817ca6ae908ce675d1d99242af148/src/libstd/panic.rs:394
21: test::run_test_in_process
at src/libtest/lib.rs:541
22: test::run_test::run_test_inner::{{closure}}
at src/libtest/lib.rs:450
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
failures:
two_is_two
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out
</code></pre>
<p>You don't need to use a backtrace unless you really can't find where the problem is. But luckily you don't need to understand it all either. If you keep reading, you will eventually see line 13 where it says <code>playground</code> - that's where it talks about your code. Everything else is about what Rust is doing in other libraries to run your program. But these two lines show you that it looked at line 2 and line 3 of playground, which is a hint to check there. Here's that part again:</p>
<p>Edit: Rust improved its backtrace messages in early 2021 to only show the most meaningful information. Now it's much easier to read:</p>
<pre><codeclass="language-text">failures:
---- two_is_two stdout ----
thread 'two_is_two' panicked at 'assertion failed: `(left == right)`
left: `2`,
right: `3`', src/lib.rs:3:5
stack backtrace:
0: rust_begin_unwind
at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/std/src/panicking.rs:493:5
1: core::panicking::panic_fmt
at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/core/src/panicking.rs:92:14
2: playground::two_is_two
at ./src/lib.rs:3:5
3: playground::two_is_two::{{closure}}
at ./src/lib.rs:2:1
4: core::ops::function::FnOnce::call_once
at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/core/src/ops/function.rs:227:5
5: core::ops::function::FnOnce::call_once
at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/core/src/ops/function.rs:227:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
failures:
two_is_two
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
</code></pre>
<p>Now let's turn backtrace off again and return to regular tests. Now we'll write some other functions, and use test functions to test them. Here are a few:</p>
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
</code></pre>
<p>That's not too hard.</p>
<p>Usually you will want to put your tests in their own module. To do this, use the same <code>mod</code> keyword and add <code>#[cfg(test)]</code> above it (remember: <code>cfg</code> means "configure). You also want to continue to write <code>#[test]</code> above each test. This is because later on when you install Rust, you can do more complicated testing. You will be able to run one test, or all of them, or run a few. Also don't forget to write <code>use super::*;</code> because the test module needs to use the functions above it. Now it will look like this:</p>
<p>You might see the words "test-driven development" when reading about Rust or another language. It's one way to write programs, and some people like it while others prefer something else. "Test-driven development" means "writing tests first, then writing the code". When you do this, you will have a lot of tests for everything you want your code to do. Then you start writing the code, and run the tests to see if you did it right. Then the tests are always there to show you if something goes wrong when you add to and rewrite your code. This is pretty easy in Rust because the compiler gives a lot of information about what to fix. Let's write a small example of test-driven development and see what it looks like.</p>
<p>Let's imagine a calculator that takes user input. It can add (+) and it can subtract (-). If the user writes "5 + 6" it should return 11, if the user writes "5 + 6 - 7" it should return 4, and so on. So we'll start with test functions. You can also see that function names in tests are usually quite long. That is because you might run a lot of tests, and you want to understand which tests have failed.</p>
<p>We'll imagine that a single function called <code>math()</code> will do everything. It will return an <code>i32</code> (we won't use floats). Because it needs to return something, we'll just return <code>6</code> every time. Then we will write three test functions. They will all fail, of course. Now the code looks like this:</p>
<p>and all the information about <code>thread 'tests::one_plus_one_is_two' panicked at 'assertion failed: `(left == right)` </code>. We don't need to print it all here.</p>
<p>Now to think about how to make the calculator. We will accept any number, and the symbols <code>+-</code>. We will allow spaces, but nothing else. So let's start with a <code>const</code> that contains all the values. Then we will use <code>.chars()</code> to iterate by character, and <code>.all()</code> to make sure they are all inside.</p>
<p>Then we will add a test that should panic. To do that, add <code>#[should_panic]</code> attribute: now if it panics the test will succeed.</p>
<p>Now when we run the tests we get this result:</p>
<pre><codeclass="language-text">running 4 tests
test tests::one_minus_two_is_minus_one ... FAILED
test tests::one_minus_minus_one_is_two ... FAILED
test tests::panics_when_characters_not_right ... ok
test tests::one_plus_one_is_two ... FAILED
</code></pre>
<p>One succeeded! Our <code>math()</code> function will only accept good input now.</p>
<p>The next step is to write the actual calculator. This is the interesting part about having tests first: the actual code starts much later. First we will put the logic together for the calculator. We want the following:</p>
<ul>
<li>All empty spaces should be removed. This is easy with <code>.filter()</code></li>
<li>The input should turn into a <code>Vec</code> with all the inputs. <code>+</code> doesn't need to be an input, but when the program sees <code>+</code> it should know that the number is done. For example, the input <code>11+1</code> should do something like this: 1) See <code>1</code>, push it into an empty string. 2) See another 1, push it into the string (it is now "11"). 3) See a <code>+</code>, know the number has ended. It will push the string into the vec, then clear the string.</li>
<li>The program must count the number of <code>-</code>. An odd number (1, 3, 5...) will mean subtract, an even number (2, 4, 6...) will mean add. So "1--9" should give 10, not -8.</li>
<li>The program should remove anything after the last number. <code>5+5+++++----</code> is made out of all the characters in <code>OKAY_CHARACTERS</code>, but it should turn to <code>5+5</code>. This is easy with <code>.trim_end_matches()</code>, where you remove anything that matches at the end of a <code>&str</code>.</li>
</ul>
<p>(By the way, <code>.trim_end_matches()</code> and <code>.trim_start_matches()</code> used to be <code>trim_right_matches()</code> and <code>trim_left_matches()</code>. But then people noticed that some languages go from right to left (Persian, Hebrew, etc.) so right and left were wrong. You might still see the older names in some code but they are the same thing.)</p>
<p>First we just want to pass all the tests. After we pass the tests, we can "refactor". Refactor means to make code better, usually through things like structs and enums and methods. Here is our code to make the tests pass:</p>
let input = input.trim_end_matches(|x| "+- ".contains(x)).chars().filter(|x| *x != ' ').collect::<String>(); // Remove + and - at the end, and all spaces
test tests::nine_plus_nine_minus_nine_minus_nine_is_zero ... ok
test tests::one_minus_two_is_minus_one ... ok
test tests::eight_minus_nine_plus_nine_is_eight_even_with_characters_on_the_end ... ok
test tests::one_plus_one_is_two ... ok
test tests::panics_when_characters_not_right ... ok
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
</code></pre>
<p>You can see that there is a back and forth process in test-driven development. It's something like this:</p>
<ul>
<li>First you write all the tests you can think of.</li>
<li>Then you start writing the code.</li>
<li>As you write the code, you get ideas for other tests.</li>
<li>You add the tests, and your tests grow as you go. The more tests you have, the more times your code gets checked.</li>
</ul>
<p>Of course, tests don't check everything and it is wrong to think that "passing all tests = the code is perfect". But tests are great for when you change your code. If you change your code later on and run the tests, if one of them doesn't work you will know what to fix.</p>
<p>Now we can rewrite (refactor) the code a bit. One good way to start is with clippy. If you installed Rust then you can type <code>cargo clippy</code>, and if you're using the Playground then click on <code>TOOLS</code> and select Clippy. Clippy will look at your code and give you tips to make it simpler. Our code doesn't have any mistakes, but it could be better.</p>
<p>Clippy tells us two things:</p>
<pre><codeclass="language-text">warning: this loop could be written as a `for` loop
--> src/lib.rs:44:5
|
44 | while let Some(entry) = math_iter.next() { // Iter through the items
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for entry in math_iter`
|
= note: `#[warn(clippy::while_let_on_iterator)]` on by default
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#while_let_on_iterator
warning: equality checks against true are unnecessary
--> src/lib.rs:53:12
|
53 | if adds == true {
| ^^^^^^^^^^^^ help: try simplifying it as shown: `adds`
|
= note: `#[warn(clippy::bool_comparison)]` on by default
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#bool_comparison
</code></pre>
<p>This is true: <code>for entry in math_iter</code> is much simpler than <code>while let Some(entry) = math_iter.next()</code>. And a <code>for</code> loop is actually an iterator so we don't have any reason to write <code>.iter()</code>. Thanks, clippy! And also we didn't need to make <code>math_iter</code>: we can just write <code>for entry in result_vec</code>.</p>
<p>Now we'll start some real refactoring. Instead of separate variables, we will create a <code>Calculator</code> struct. This will have all the variables we used together. We will change two names to make it more clear. <code>result_vec</code> will become <code>results</code>, and <code>push_string</code> will become <code>current_input</code> (current means "now"). And so far it only has one method: new.</p>
<p>Now our code is actually a bit longer, but easier to read. For example, <code>if adds</code> is now <code>if calculator.adds</code>, which is exactly like reading English. It looks like this:</p>
<p>Finally we add two new methods. One is called <code>.clear()</code> and clears the <code>current_input()</code>. The other one is called <code>push_char()</code> and pushes the input onto <code>current_input()</code>. Here is our refactored code:</p>
<p>This is probably good enough for now. We could write more methods but lines like <code>calculator.results.push(calculator.current_input.clone());</code> are already very clear. Refactoring is best when you can still easily read the code after you are done. You don't want to just refactor to make the code short: <code>clc.clr()</code> is much worse than <code>calculator.clear()</code>, for example.</p>