Skip to content

Commit 67df9b9

Browse files
author
Steve Smith
committed
Add sections about concurrency and stdout/err capture to the Testing chapter of the book.
1 parent 7bef60a commit 67df9b9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/doc/book/testing.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -586,3 +586,46 @@ you add more examples.
586586

587587
We haven’t covered all of the details with writing documentation tests. For more,
588588
please see the [Documentation chapter](documentation.html).
589+
590+
# Testing and concurrency
591+
592+
One thing that is important to note when writing tests are run concurrently
593+
using threads (by default the number of threads is equal to the number of CPUs
594+
on the machine). For this reason you should take care that your tests are
595+
written in such a way as to not depend on each-other, or on any shared
596+
state. "Share state" can also include the environment, such as the current
597+
working directory, or environment variables.
598+
599+
If this is an issue it is possible to control this concurrency, either by
600+
setting the environment variable `RUST_TEST_THREADS`, or by passing the argument
601+
`--test-threads` to the tests:
602+
603+
```bash
604+
$ RUST_TEST_THREADS=1 cargo test # Run tests with no concurrency
605+
...
606+
$ cargo test -- --test-threads=1 # Same as above
607+
...
608+
```
609+
610+
# Test output
611+
612+
By default Rust's test library captures and discards output to standard
613+
out/error, e.g. output from `println!()`. This too can be controlled using the
614+
environment or a switch:
615+
616+
617+
```bash
618+
$ RUST_TEST_NOCAPTURE=1 cargo test # Preserve stdout/stderr
619+
...
620+
$ cargo test -- --nocapture # Same as above
621+
...
622+
```
623+
624+
However a better method avoiding capture is to use logging rather than raw
625+
output. Rust has a [standard logging API][log], which provides a frontend to
626+
multiple loggin implementations. This can be used in conjunction with the
627+
default [env_logger] to output any debugging information in a manner that can be
628+
controlled at runtime.
629+
630+
[log]: https://crates.io/crates/log
631+
[env_logger]: https://crates.io/crates/env_logger

0 commit comments

Comments
 (0)