Files
book/testing.html
T

515 lines
23 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="{% block description %}{% endblock %}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="">
<link rel="stylesheet" href="book.css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- Font Awesome -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<!-- MathJax -->
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<!-- Fetch JQuery from CDN but have a local fallback -->
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
}
</script>
</head>
<body>
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme = localStorage.getItem('theme');
if (theme == null) { theme = 'light'; }
$('body').removeClass().addClass(theme);
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var sidebar = localStorage.getItem('sidebar');
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
</script>
<div id="sidebar" class="sidebar">
<ul class="chapter"><li><a href="introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="hello-world.html"><strong>1.2.</strong> Hello, World!</a></li><li><a href="design.html"><strong>1.3.</strong> The Design of Rust</a></li></ul></li><li><a href="tutorial.html"><strong>2.</strong> Tutorial</a></li><li><a href="basics.html"><strong>3.</strong> The Basics</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong>3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="if.html"><strong>3.5.</strong> `if`</a></li><li><a href="loops.html"><strong>3.6.</strong> Loops</a></li></ul></li><li><a href="ownership-and-borrowing.html"><strong>4.</strong> Ownership & borrowing</a></li><li><ul class="section"><li><a href="ownership.html"><strong>4.1.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="lifetimes.html"><strong>4.3.</strong> Lifetimes</a></li></ul></li><li><a href="basic-data-types.html"><strong>5.</strong> Basic Data Types</a></li><li><ul class="section"><li><a href="structs.html"><strong>5.1.</strong> Structs</a></li><li><a href="enums.html"><strong>5.2.</strong> Enums</a></li></ul></li><li><a href="crates-and-modules.html"><strong>6.</strong> Crates & Modules</a></li><li><a href="error-handling.html"><strong>7.</strong> Error Handling</a></li><li><a href="basic-collections.html"><strong>8.</strong> Basic Collections</a></li><li><ul class="section"><li><a href="vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="hashmap.html"><strong>8.3.</strong> `HashMap<K, V>`</a></li></ul></li><li><a href="traits.html"><strong>9.</strong> Traits</a></li><li><a href="closures.html"><strong>10.</strong> Closures</a></li><li><a href="iterators.html"><strong>11.</strong> Iterators</a></li><li><a href="io.html"><strong>12.</strong> I/O</a></li><li><ul class="section"><li><a href="read-and-write.html"><strong>12.1.</strong> `Read` & `Write`</a></li><li><a href="fs.html"><strong>12.2.</strong> `std::fs`</a></li><li><a href="path.html"><strong>12.3.</strong> `std::path`</a></li><li><a href="env.html"><strong>12.4.</strong> `std::env`</a></li></ul></li><li><a href="testing.html" class="active"><strong>13.</strong> Testing</a></li><li><a href="smart-pointers.html"><strong>14.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="deref.html"><strong>14.1.</strong> `Deref`</a></li><li><a href="deref-coercions.html"><strong>14.2.</strong> `Deref` coercions</a></li><li><a href="box.html"><strong>14.3.</strong> `Box<T>`</a></li><li><a href="rc.html"><strong>14.4.</strong> `Rc<T>`</a></li></ul></li><li><a href="concurrency.html"><strong>15.</strong> Concurrency</a></li><li><ul class="section"><li><a href="threads.html"><strong>15.1.</strong> Threads</a></li><li><a href="send-and-sync.html"><strong>15.2.</strong> `Send` & `Sync`</a></li><li><a href="arc.html"><strong>15.3.</strong> `Arc<T>`</a></li><li><a href="mutex.html"><strong>15.4.</strong> `Mutex<T>`</a></li><li><a href="channels.html"><strong>15.5.</strong> `Channels`</a></li></ul></li><li><a href="unsafe-rust.html"><strong>16.</strong> Unsafe Rust</a></li><li><ul class="section"><li><a href="raw-pointers.html"><strong>16.1.</strong> Raw Pointers</a></li><li><a href="transmute.html"><strong>16.2.</strong> transmute</a></li></ul></li><li><a href="ffi.html"><strong>17.</strong> FFI</a></li><li><ul class="section"><li><a href="conditional-compilation.html"><strong>17.1.</strong> Conditional Compilation</a></li><li><a href="bindings-to-c.html"><strong>17.2.</strong> Bindings to C</a></li><li><a href="using-rust-from-other-languages.html"><strong>17.3.</strong> Using Rust from Other Languages</a></li><li><a href="static.html"><strong>17.4.</strong> `static`</a></li></ul></li><li><a href="cargo.html"><strong>18.</strong> Cargo</a></li><li><ul class="section"><li><a href="cratesio.html"><strong>18.1.</strong> Crates.io</a></li></ul></li><li><a href="advanced-type-system-features.html"><strong>19.</strong> Advanced Type System Features</a></li><li><ul class="section"><li><a href="associated-types.html"><strong>19.1.</strong> Associated Types</a></li><li><a href="trait-objects.html"><strong>19.2.</strong> Trait Objects</a></li><li><a href="ufcs.html"><strong>19.3.</strong> UFCS</a></li><li><a href="coherence.html"><strong>19.4.</strong> Coherence</a></li></ul></li><li><a href="interior-mutability.html"><strong>20.</strong> Interior mutability</a></li><li><ul class="section"><li><a href="cell.html"><strong>20.1.</strong> `Cell<T>`</a></li><li><a href="refcell.html"><strong>20.2.</strong> `RefCell<T>`</a></li></ul></li><li><a href="macros.html"><strong>21.</strong> Macros</a></li><li><a href="nightly-rust.html"><strong>22.</strong> Nightly Rust</a></li></ul>
</div>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar" class="menu-bar">
<div class="left-buttons">
<i id="sidebar-toggle" class="fa fa-bars"></i>
<i id="theme-toggle" class="fa fa-paint-brush"></i>
</div>
<h1 class="menu-title"></h1>
<div class="right-buttons">
<i id="print-button" class="fa fa-print" title="Print this book"></i>
</div>
</div>
<div id="content" class="content">
<h1>Testing</h1>
<blockquote>
<p>Program testing can be a very effective way to show the presence of bugs, but
it is hopelessly inadequate for showing their absence.</p>
<p>Edsger W. Dijkstra, &quot;The Humble Programmer&quot; (1972)</p>
</blockquote>
<p>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.</p>
<h1>The <code>test</code> attribute</h1>
<p>At its simplest, a test in Rust is a function that's annotated with the <code>test</code>
attribute. Let's make a new project with Cargo called <code>adder</code>:</p>
<pre><code class="language-bash">$ cargo new adder
$ cd adder
</code></pre>
<p>Cargo will automatically generate a simple test when you make a new project.
Here's the contents of <code>src/lib.rs</code>:</p>
<pre><code class="language-rust">#[test]
fn it_works() {
}
</code></pre>
<p>Note the <code>#[test]</code>. 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
<code>cargo test</code>:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>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:</p>
<pre><code class="language-text">test it_works ... ok
</code></pre>
<p>Note the <code>it_works</code>. This comes from the name of our function:</p>
<pre><code class="language-rust">fn it_works() {
# }
</code></pre>
<p>We also get a summary line:</p>
<pre><code class="language-text">test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>So why does our do-nothing test pass? Any test which doesn't <code>panic!</code> passes,
and any test that does <code>panic!</code> fails. Let's make our test fail:</p>
<pre><code class="language-rust">#[test]
fn it_works() {
assert!(false);
}
</code></pre>
<p><code>assert!</code> is a macro provided by Rust which takes one argument: if the argument
is <code>true</code>, nothing happens. If the argument is <code>false</code>, it <code>panic!</code>s. Let's run
our tests again:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test it_works ... FAILED
failures:
---- it_works stdout ----
thread 'it_works' panicked at 'assertion failed: false', /home/steve/tmp/adder/src/lib.rs:3
failures:
it_works
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
thread '&lt;main&gt;' panicked at 'Some tests failed', /home/steve/src/rust/src/libtest/lib.rs:247
</code></pre>
<p>Rust indicates that our test failed:</p>
<pre><code class="language-text">test it_works ... FAILED
</code></pre>
<p>And that's reflected in the summary line:</p>
<pre><code class="language-text">test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
</code></pre>
<p>We also get a non-zero status code. We can use <code>$?</code> on OS X and Linux:</p>
<pre><code class="language-bash">$ echo $?
101
</code></pre>
<p>On Windows, if you’re using <code>cmd</code>:</p>
<pre><code class="language-bash">&gt; echo %ERRORLEVEL%
</code></pre>
<p>And if you’re using PowerShell:</p>
<pre><code class="language-bash">&gt; echo $LASTEXITCODE # the code itself
&gt; echo $? # a boolean, fail or succeed
</code></pre>
<p>This is useful if you want to integrate <code>cargo test</code> into other tooling.</p>
<p>We can invert our test's failure with another attribute: <code>should_panic</code>:</p>
<pre><code class="language-rust">#[test]
#[should_panic]
fn it_works() {
assert!(false);
}
</code></pre>
<p>This test will now succeed if we <code>panic!</code> and fail if we complete. Let's try it:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Rust provides another macro, <code>assert_eq!</code>, that compares two arguments for
equality:</p>
<pre><code class="language-rust">#[test]
#[should_panic]
fn it_works() {
assert_eq!(&quot;Hello&quot;, &quot;world&quot;);
}
</code></pre>
<p>Does this test pass or fail? Because of the <code>should_panic</code> attribute, it
passes:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p><code>should_panic</code> 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 <code>expected</code>
parameter can be added to the <code>should_panic</code> attribute. The test harness will
make sure that the failure message contains the provided text. A safer version
of the example above would be:</p>
<pre><code class="language-rust">#[test]
#[should_panic(expected = &quot;assertion failed&quot;)]
fn it_works() {
assert_eq!(&quot;Hello&quot;, &quot;world&quot;);
}
</code></pre>
<p>That's all there is to the basics! Let's write one 'real' test:</p>
<pre><code class="language-rust,ignore">pub fn add_two(a: i32) -&gt; i32 {
a + 2
}
#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
</code></pre>
<p>This is a very common use of <code>assert_eq!</code>: call some function with
some known arguments and compare it to the expected output.</p>
<h1>The <code>ignore</code> attribute</h1>
<p>Sometimes a few specific tests can be very time-consuming to execute. These
can be disabled by default by using the <code>ignore</code> attribute:</p>
<pre><code class="language-rust">#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
#[test]
#[ignore]
fn expensive_test() {
// code that takes an hour to run
}
</code></pre>
<p>Now we run our tests and see that <code>it_works</code> is run, but <code>expensive_test</code> is
not:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 2 tests
test expensive_test ... ignored
test it_works ... ok
test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>The expensive tests can be run explicitly using <code>cargo test -- --ignored</code>:</p>
<pre><code class="language-bash">$ cargo test -- --ignored
Running target/adder-91b3e234d4ed382a
running 1 test
test expensive_test ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>The <code>--ignored</code> argument is an argument to the test binary, and not to Cargo,
which is why the command is <code>cargo test -- --ignored</code>.</p>
<h1>The <code>tests</code> module</h1>
<p>There is one way in which our existing example is not idiomatic: it's
missing the <code>tests</code> module. The idiomatic way of writing our example
looks like this:</p>
<pre><code class="language-rust,ignore">pub fn add_two(a: i32) -&gt; i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::add_two;
#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
}
</code></pre>
<p>There's a few changes here. The first is the introduction of a <code>mod tests</code> with
a <code>cfg</code> attribute. The module allows us to group all of our tests together, and
to also define helper functions if needed, that don't become a part of the rest
of our crate. The <code>cfg</code> attribute only compiles our test code if we're
currently trying to run the tests. This can save compile time, and also ensures
that our tests are entirely left out of a normal build.</p>
<p>The second change is the <code>use</code> declaration. Because we're in an inner module,
we need to bring our test function into scope. This can be annoying if you have
a large module, and so this is a common use of globs. Let's change our
<code>src/lib.rs</code> to make use of it:</p>
<pre><code class="language-rust,ignore">pub fn add_two(a: i32) -&gt; i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
}
</code></pre>
<p>Note the different <code>use</code> line. Now we run our tests:</p>
<pre><code class="language-bash">$ cargo test
Updating registry `https://github.com/rust-lang/crates.io-index`
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>It works!</p>
<p>The current convention is to use the <code>tests</code> module to hold your &quot;unit-style&quot;
tests. Anything that just tests one small bit of functionality makes sense to
go here. But what about &quot;integration-style&quot; tests instead? For that, we have
the <code>tests</code> directory.</p>
<h1>The <code>tests</code> directory</h1>
<p>To write an integration test, let's make a <code>tests</code> directory, and
put a <code>tests/lib.rs</code> file inside, with this as its contents:</p>
<pre><code class="language-rust,ignore">extern crate adder;
#[test]
fn it_works() {
assert_eq!(4, adder::add_two(2));
}
</code></pre>
<p>This looks similar to our previous tests, but slightly different. We now have
an <code>extern crate adder</code> at the top. This is because the tests in the <code>tests</code>
directory are an entirely separate crate, and so we need to import our library.
This is also why <code>tests</code> is a suitable place to write integration-style tests:
they use the library like any other consumer of it would.</p>
<p>Let's run them:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Running target/lib-c18e7d3494509e74
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Now we have three sections: our previous test is also run, as well as our new
one.</p>
<p>That's all there is to the <code>tests</code> directory. The <code>tests</code> module isn't needed
here, since the whole thing is focused on tests.</p>
<p>Let's finally check out that third section: documentation tests.</p>
<h1>Documentation tests</h1>
<p>Nothing is better than documentation with examples. Nothing is worse than
examples that don't actually work, because the code has changed since the
documentation has been written. To this end, Rust supports automatically
running examples in your documentation (<strong>note:</strong> this only works in library
crates, not binary crates). Here's a fleshed-out <code>src/lib.rs</code> with examples:</p>
<pre><code class="language-rust,ignore">//! The `adder` crate provides functions that add numbers to other numbers.
//!
//! # Examples
//!
//! ```
//! assert_eq!(4, adder::add_two(2));
//! ```
/// This function adds two to its argument.
///
/// # Examples
///
/// ```
/// use adder::add_two;
///
/// assert_eq!(4, add_two(2));
/// ```
pub fn add_two(a: i32) -&gt; i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
}
</code></pre>
<p>Note the module-level documentation with <code>//!</code> and the function-level
documentation with <code>///</code>. Rust's documentation supports Markdown in comments,
and so triple graves mark code blocks. It is conventional to include the
<code># Examples</code> section, exactly like that, with examples following.</p>
<p>Let's run the tests again:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/steve/tmp/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Running target/lib-c18e7d3494509e74
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 2 tests
test add_two_0 ... ok
test _0 ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Now we have all three kinds of tests running! Note the names of the
documentation tests: the <code>_0</code> is generated for the module test, and <code>add_two_0</code>
for the function test. These will auto increment with names like <code>add_two_1</code> as
you add more examples.</p>
<p>We haven’t covered all of the details with writing documentation tests. For more,
please see the <a href="documentation.html">Documentation chapter</a></p>
<p>One final note: documentation tests <em>cannot</em> be run on binary crates.
To see more on file arrangement see the <a href="crates-and-modules.html">Crates and
Modules</a> section.</p>
</div>
<!-- Mobile navigation buttons -->
<a href="env.html" class="mobile-nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="smart-pointers.html" class="mobile-nav-chapters next">
<i class="fa fa-angle-right"></i>
</a>
</div>
<a href="env.html" class="nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="smart-pointers.html" class="nav-chapters next">
<i class="fa fa-angle-right"></i>
</a>
</div>
<!-- Local fallback for Font Awesome -->
<script>
if ($(".fa").css("font-family") !== "FontAwesome") {
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
}
</script>
<script src="highlight.js"></script>
<script src="book.js"></script>
</body>
</html>