Files
docs-rust/ch12/ch12-04-testing-the-librarys-functionality.html
2026-06-22 21:27:36 +05:30

320 lines
17 KiB
HTML
Raw Permalink 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>Adding Functionality with Test Driven Development</title>
</head>
<body>
<!-- Old headings. Do not remove or links may break. -->
<p><a id="developing-the-librarys-functionality-with-test-driven-development"></a></p>
<h2 id="adding-functionality-with-test-driven-development"><a class="header" href="#adding-functionality-with-test-driven-development">Adding Functionality with Test-Driven Development</a></h2>
<p>Now that we have the search logic in <em>src/lib.rs</em> separate from the <code>main</code>
function, its much easier to write tests for the core functionality of our
code. We can call functions directly with various arguments and check return
values without having to call our binary from the command line.</p>
<p>In this section, well add the searching logic to the <code>minigrep</code> program using
the test-driven development (TDD) process with the following steps:</p>
<ol>
<li>Write a test that fails and run it to make sure it fails for the reason you
expect.</li>
<li>Write or modify just enough code to make the new test pass.</li>
<li>Refactor the code you just added or changed and make sure the tests continue
to pass.</li>
<li>Repeat from step 1!</li>
</ol>
<p>Though its just one of many ways to write software, TDD can help drive code
design. Writing the test before you write the code that makes the test pass
helps maintain high test coverage throughout the process.</p>
<p>Well test-drive the implementation of the functionality that will actually do
the searching for the query string in the file contents and produce a list of
lines that match the query. Well add this functionality in a function called
<code>search</code>.</p>
<h3 id="writing-a-failing-test"><a class="header" href="#writing-a-failing-test">Writing a Failing Test</a></h3>
<p>In <em>src/lib.rs</em>, well add a <code>tests</code> module with a test function, as we did in
<a href="../ch11/ch11-01-writing-tests.html#the-anatomy-of-a-test-function">Chapter 11</a><!-- ignore -->. The test function specifies the
behavior we want the <code>search</code> function to have: It will take a query and the
text to search, and it will return only the lines from the text that contain
the query. Listing 12-15 shows this test.</p>
<figure class="listing" id="listing-12-15">
<span class="file-name">Filename: src/lib.rs</span>
<pre><code class="language-rust ignore does_not_compile"><span class="boring">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
</span><span class="boring"> unimplemented!();
</span><span class="boring">}
</span><span class="boring">
</span>// --snip--
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
}</code></pre>
<figcaption><a href="#listing-12-15">Listing 12-15</a>: Creating a failing test for the <code>search</code> function for the functionality we wish we had</figcaption>
</figure>
<p>This test searches for the string <code>"duct"</code>. The text were searching is three
lines, only one of which contains <code>"duct"</code> (note that the backslash after the
opening double quote tells Rust not to put a newline character at the beginning
of the contents of this string literal). We assert that the value returned from
the <code>search</code> function contains only the line we expect.</p>
<p>If we run this test, it will currently fail because the <code>unimplemented!</code> macro
panics with the message “not implemented”. In accordance with TDD principles,
well take a small step of adding just enough code to get the test to not panic
when calling the function by defining the <code>search</code> function to always return an
empty vector, as shown in Listing 12-16. Then, the test should compile and fail
because an empty vector doesnt match a vector containing the line <code>"safe, fast, productive."</code>.</p>
<figure class="listing" id="listing-12-16">
<span class="file-name">Filename: src/lib.rs</span>
<pre><code class="language-rust noplayground">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
vec![]
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn one_result() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<figcaption><a href="#listing-12-16">Listing 12-16</a>: Defining just enough of the <code>search</code> function so that calling it wont panic</figcaption>
</figure>
<p>Now lets discuss why we need to define an explicit lifetime <code>'a</code> in the
signature of <code>search</code> and use that lifetime with the <code>contents</code> argument and
the return value. Recall in <a href="../ch10/ch10-03-lifetime-syntax.html">Chapter 10</a><!-- ignore --> that
the lifetime parameters specify which argument lifetime is connected to the
lifetime of the return value. In this case, we indicate that the returned
vector should contain string slices that reference slices of the argument
<code>contents</code> (rather than the argument <code>query</code>).</p>
<p>In other words, we tell Rust that the data returned by the <code>search</code> function
will live as long as the data passed into the <code>search</code> function in the
<code>contents</code> argument. This is important! The data referenced <em>by</em> a slice needs
to be valid for the reference to be valid; if the compiler assumes were making
string slices of <code>query</code> rather than <code>contents</code>, it will do its safety checking
incorrectly.</p>
<p>If we forget the lifetime annotations and try to compile this function, well
get this error:</p>
<pre><code class="language-console">$ cargo build
Compiling minigrep v0.1.0 (file:///projects/minigrep)
error[E0106]: missing lifetime specifier
--&gt; src/lib.rs:1:51
|
1 | pub fn search(query: &amp;str, contents: &amp;str) -&gt; Vec&lt;&amp;str&gt; {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `query` or `contents`
help: consider introducing a named lifetime parameter
|
1 | pub fn search&lt;'a&gt;(query: &amp;'a str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
| ++++ ++ ++ ++
For more information about this error, try `rustc --explain E0106`.
error: could not compile `minigrep` (lib) due to 1 previous error
</code></pre>
<p>Rust cant know which of the two parameters we need for the output, so we need
to tell it explicitly. Note that the help text suggests specifying the same
lifetime parameter for all the parameters and the output type, which is
incorrect! Because <code>contents</code> is the parameter that contains all of our text
and we want to return the parts of that text that match, we know <code>contents</code> is
the only parameter that should be connected to the return value using the
lifetime syntax.</p>
<p>Other programming languages dont require you to connect arguments to return
values in the signature, but this practice will get easier over time. You might
want to compare this example with the examples in the <a href="../ch10/ch10-03-lifetime-syntax.html#validating-references-with-lifetimes">“Validating References
with Lifetimes”</a><!-- ignore --> section
in Chapter 10.</p>
<h3 id="writing-code-to-pass-the-test"><a class="header" href="#writing-code-to-pass-the-test">Writing Code to Pass the Test</a></h3>
<p>Currently, our test is failing because we always return an empty vector. To fix
that and implement <code>search</code>, our program needs to follow these steps:</p>
<ol>
<li>Iterate through each line of the contents.</li>
<li>Check whether the line contains our query string.</li>
<li>If it does, add it to the list of values were returning.</li>
<li>If it doesnt, do nothing.</li>
<li>Return the list of results that match.</li>
</ol>
<p>Lets work through each step, starting with iterating through lines.</p>
<h4 id="iterating-through-lines-with-the-lines-method"><a class="header" href="#iterating-through-lines-with-the-lines-method">Iterating Through Lines with the <code>lines</code> Method</a></h4>
<p>Rust has a helpful method to handle line-by-line iteration of strings,
conveniently named <code>lines</code>, that works as shown in Listing 12-17. Note that
this wont compile yet.</p>
<figure class="listing" id="listing-12-17">
<span class="file-name">Filename: src/lib.rs</span>
<pre><code class="language-rust ignore does_not_compile">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
for line in contents.lines() {
// do something with line
}
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn one_result() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<figcaption><a href="#listing-12-17">Listing 12-17</a>: Iterating through each line in <code>contents</code></figcaption>
</figure>
<p>The <code>lines</code> method returns an iterator. Well talk about iterators in depth in
<a href="../ch13/ch13-02-iterators.html">Chapter 13</a><!-- ignore -->. But recall that you saw this way
of using an iterator in <a href="../ch03/ch03-05-control-flow.html#looping-through-a-collection-with-for">Listing 3-5</a><!-- ignore -->, where we used a
<code>for</code> loop with an iterator to run some code on each item in a collection.</p>
<h4 id="searching-each-line-for-the-query"><a class="header" href="#searching-each-line-for-the-query">Searching Each Line for the Query</a></h4>
<p>Next, well check whether the current line contains our query string.
Fortunately, strings have a helpful method named <code>contains</code> that does this for
us! Add a call to the <code>contains</code> method in the <code>search</code> function, as shown in
Listing 12-18. Note that this still wont compile yet.</p>
<figure class="listing" id="listing-12-18">
<span class="file-name">Filename: src/lib.rs</span>
<pre><code class="language-rust ignore does_not_compile">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
for line in contents.lines() {
if line.contains(query) {
// do something with line
}
}
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn one_result() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<figcaption><a href="#listing-12-18">Listing 12-18</a>: Adding functionality to see whether the line contains the string in <code>query</code></figcaption>
</figure>
<p>At the moment, were building up functionality. To get the code to compile, we
need to return a value from the body as we indicated we would in the function
signature.</p>
<h4 id="storing-matching-lines"><a class="header" href="#storing-matching-lines">Storing Matching Lines</a></h4>
<p>To finish this function, we need a way to store the matching lines that we want
to return. For that, we can make a mutable vector before the <code>for</code> loop and
call the <code>push</code> method to store a <code>line</code> in the vector. After the <code>for</code> loop,
we return the vector, as shown in Listing 12-19.</p>
<figure class="listing" id="listing-12-19">
<span class="file-name">Filename: src/lib.rs</span>
<pre><code class="language-rust ignore">pub fn search&lt;'a&gt;(query: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
<span class="boring">
</span><span class="boring">#[cfg(test)]
</span><span class="boring">mod tests {
</span><span class="boring"> use super::*;
</span><span class="boring">
</span><span class="boring"> #[test]
</span><span class="boring"> fn one_result() {
</span><span class="boring"> let query = "duct";
</span><span class="boring"> let contents = "\
</span><span class="boring">Rust:
</span><span class="boring">safe, fast, productive.
</span><span class="boring">Pick three.";
</span><span class="boring">
</span><span class="boring"> assert_eq!(vec!["safe, fast, productive."], search(query, contents));
</span><span class="boring"> }
</span><span class="boring">}</span></code></pre>
<figcaption><a href="#listing-12-19">Listing 12-19</a>: Storing the lines that match so that we can return them</figcaption>
</figure>
<p>Now the <code>search</code> function should return only the lines that contain <code>query</code>,
and our test should pass. Lets run the test:</p>
<pre><code class="language-console">$ cargo test
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `test` profile [unoptimized + debuginfo] target(s) in 1.22s
Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 1 test
test tests::one_result ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests minigrep
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
</code></pre>
<p>Our test passed, so we know it works!</p>
<p>At this point, we could consider opportunities for refactoring the
implementation of the search function while keeping the tests passing to
maintain the same functionality. The code in the search function isnt too bad,
but it doesnt take advantage of some useful features of iterators. Well
return to this example in <a href="../ch13/ch13-02-iterators.html">Chapter 13</a><!-- ignore -->, where
well explore iterators in detail, and look at how to improve it.</p>
<p>Now the entire program should work! Lets try it out, first with a word that
should return exactly one line from the Emily Dickinson poem: <em>frog</em>.</p>
<pre><code class="language-console">$ cargo run -- frog poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.38s
Running `target/debug/minigrep frog poem.txt`
How public, like a frog
</code></pre>
<p>Cool! Now lets try a word that will match multiple lines, like <em>body</em>:</p>
<pre><code class="language-console">$ cargo run -- body poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep body poem.txt`
I'm nobody! Who are you?
Are you nobody, too?
How dreary to be somebody!
</code></pre>
<p>And finally, lets make sure that we dont get any lines when we search for a
word that isnt anywhere in the poem, such as <em>monomorphization</em>:</p>
<pre><code class="language-console">$ cargo run -- monomorphization poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep monomorphization poem.txt`
</code></pre>
<p>Excellent! Weve built our own mini version of a classic tool and learned a lot
about how to structure applications. Weve also learned a bit about file input
and output, lifetimes, testing, and command line parsing.</p>
<p>To round out this project, well briefly demonstrate how to work with
environment variables and how to print to standard error, both of which are
useful when youre writing command line programs.</p>
</body>
</html>