microsoft/openvmm

Public

mirrored fromhttps://github.com/microsoft/openvmmAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
103c0519b1d721f9b666c6e28a329b0fabff3e37

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

Guide/src/dev_guide/tests/unit.md

80lines · modecode

1# Unit Tests
2
3```admonish tip
4Note: We recommend using [cargo-nextest](https://nexte.st/) to run unit / VMM
5tests. It is a significant improvement over the built-in `cargo test` runner,
6and is the test runner we use in all our CI pipelines.
7
8You can install it locally by running: `cargo install cargo-nextest --locked`
9
10See the [cargo-nextest](https://nexte.st/) documentation for more info.
11```
12
13Unit tests test individual functions or components without pulling in lots of
14ambient infrastructure. In Rust, these are usually written in the same file as
15the product code--this ensures that the test has access to any internal methods
16or state it requires, and it makes it easier to ensure that tests and code are
17updated at the same time.
18
19A typical module with unit tests might look something like this:
20
21```rust
22fn add_5(n: u32) -> u32 {
23 n + 5
24}
25
26#[cfg(test)]
27mod tests {
28 #[test]
29 fn test_add_5() {
30 assert_eq!(add_5(3), 8);
31 }
32}
33```
34
35In the OpenVMM repo, all the unit tests are run on every pull request, on an
36arbitrary build machine. As a result of this approach, it's important that unit
37tests:
38
39- run quickly
40- do not affect the state of the machine that runs them
41- do not take a dependency on machine configuration
42 - e.g: no root/administrator access or virtualization requirement
43
44We may loosen these guidelines over time if it becomes necessary. You can also
45mark tests with `#[ignore]` if they do not meet these guidelines but are useful
46for manual testing.
47
48See the [unit testing section](https://doc.rust-lang.org/rust-by-example/testing/unit_testing.html)
49in "Rust by example" for more details.
50
51## Doc tests
52
53Rust has another type of unit tests known as doc tests. These are unit tests
54that are written in the API documentation comments of public functions. They
55will be run automatically along with the unit tests, so the same guidelines
56apply.
57
58When do you choose a doc test over a unit test?
59
60Doc tests can only access public functionality, and they are intended to
61document the usage of a function or method, not to exhaustively check every
62case. So write doc tests primarily as examples for other developers, and rely on
63unit tests for your main coverage.
64
65An example might look like this:
66
67```rust
68/// Adds 5 to `n`.
69///
70/// ```
71/// assert_eq!(mycrate::add_5(3), 8);
72/// ```
73pub fn add_5(n: u32) -> u32 {
74 n + 5
75}
76```
77
78See the [documentation testing
79section](https://doc.rust-lang.org/rust-by-example/testing/doc_testing.html) in
80Rust by example for more info.
81