1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-04 05:40:29 +02:00

Move Mockall and GoogleTest slides to Android section (#1533)

After #1528 and #1532, we now have actual slides which showcase the
crates in action. So we can reclaim a few minutes by removing the slide
which mentions Mockall and GoogleTest slide.

The slide mentioned [proptest](https://docs.rs/proptest) and
[rstest](https://docs.rs/rstest) as well. While I'm sure the libraries
are useful, we don't have them imported into AOSP and I've never
personally used them. We should therefore not advertise them yet at this
point since they won't be useful to Android engineers.

Of course we can mention things that are not in AOSP (or in Chromium),
but I think we should do it in the speaker notes at most.
This commit is contained in:
Martin Geisler
2024-03-04 16:25:35 +01:00
committed by GitHub
parent c763932288
commit 1b3984df20
16 changed files with 129 additions and 43 deletions

View File

@ -117,6 +117,11 @@ EOF
pkill -f birthday_server
run_example <<EOF
# ANCHOR: libleftpad_test
atest --host libleftpad_test
# ANCHOR_END: libleftpad_test
EOF
run_example <<EOF
# ANCHOR: hello_rust_logs

37
src/android/testing.md Normal file
View File

@ -0,0 +1,37 @@
# Testing in Android
Building on [Testing](../testing.md), we will now look at how unit tests work in
AOSP. Use the `rust_test` module for your unit tests:
_testing/Android.bp_:
```javascript
{{#include testing/Android.bp}}
```
_testing/src/lib.rs_:
```rust
{{#include testing/src/lib.rs:leftpad}}
```
You can now run the test with
```shell
{{#include build_all.sh:libleftpad_test}}
```
The output looks like this:
```text
INFO: Elapsed time: 2.666s, Critical Path: 2.40s
INFO: 3 processes: 2 internal, 1 linux-sandbox.
INFO: Build completed successfully, 3 total actions
//comprehensive-rust-android/testing:libleftpad_test_host PASSED in 2.3s
PASSED libleftpad_test.tests::long_string (0.0s)
PASSED libleftpad_test.tests::short_string (0.0s)
Test cases: finished with 2 passing and 0 failing out of 2 test cases
```
Notice how you only mention the root of the library crate. Tests are found
recursively in nested modules.

View File

@ -0,0 +1,13 @@
rust_library {
name: "libleftpad",
crate_name: "leftpad",
srcs: ["src/lib.rs"],
}
rust_test {
name: "libleftpad_test",
crate_name: "leftpad_test",
srcs: ["src/lib.rs"],
host_supported: true,
test_suites: ["general-tests"],
}

View File

@ -0,0 +1,21 @@
[package]
name = "android-testing"
version = "0.1.0"
edition = "2021"
publish = false
[[example]]
name = "googletest-example"
crate-type = ["staticlib"]
path = "googletest.rs"
test = true
[[example]]
name = "mockall-example"
crate-type = ["staticlib"]
path = "mockall.rs"
test = true
[dependencies]
googletest = "0.11.0"
mockall = "0.12.1"

View File

@ -0,0 +1,72 @@
---
minutes: 5
---
# GoogleTest
The [GoogleTest](https://docs.rs/googletest/) crate allows for flexible test
assertions using _matchers_:
```rust,ignore
{{#include googletest.rs:test_elements_are}}
```
If we change the last element to `"!"`, the test fails with a structured error
message pin-pointing the error:
<!-- mdbook-xgettext: skip -->
```text
---- test_elements_are stdout ----
Value of: value
Expected: has elements:
0. is equal to "foo"
1. is less than "xyz"
2. starts with prefix "!"
Actual: ["foo", "bar", "baz"],
where element #2 is "baz", which does not start with "!"
at src/testing/googletest.rs:6:5
Error: See failure output above
```
<details>
- GoogleTest is not part of the Rust Playground, so you need to run this example
in a local environment. Use `cargo add googletest` to quickly add it to an
existing Cargo project.
- The `use googletest::prelude::*;` line imports a number of
[commonly used macros and types][prelude].
- This just scratches the surface, there are many builtin matchers.
- A particularly nice feature is that mismatches in multi-line strings are shown
as a diff:
```rust,ignore
{{#include googletest.rs:test_multiline_string_diff}}
```
shows a color-coded diff (colors not shown here):
<!-- mdbook-xgettext: skip -->
```text
Value of: haiku
Expected: is equal to "Memory safety found,\nRust's silly humor guides the way,\nSecure code you'll write."
Actual: "Memory safety found,\nRust's strong typing guides the way,\nSecure code you'll write.",
which isn't equal to "Memory safety found,\nRust's silly humor guides the way,\nSecure code you'll write."
Difference(-actual / +expected):
Memory safety found,
-Rust's strong typing guides the way,
+Rust's silly humor guides the way,
Secure code you'll write.
at src/testing/googletest.rs:17:5
```
- The crate is a Rust port of
[GoogleTest for C++](https://google.github.io/googletest/).
[prelude]: https://docs.rs/googletest/latest/googletest/prelude/index.html
</details>

View File

@ -0,0 +1,25 @@
// ANCHOR: test_elements_are
use googletest::prelude::*;
#[googletest::test]
fn test_elements_are() {
let value = vec!["foo", "bar", "baz"];
expect_that!(value, elements_are!(eq("foo"), lt("xyz"), starts_with("b")));
}
// ANCHOR_END: test_elements_are
#[should_panic]
// ANCHOR: test_multiline_string_diff
#[test]
fn test_multiline_string_diff() {
let haiku = "Memory safety found,\n\
Rust's strong typing guides the way,\n\
Secure code you'll write.";
assert_that!(
haiku,
eq("Memory safety found,\n\
Rust's silly humor guides the way,\n\
Secure code you'll write.")
);
}
// ANCHOR_END: test_multiline_string_diff

View File

@ -0,0 +1,29 @@
// ANCHOR: simple_example
use std::time::Duration;
#[mockall::automock]
pub trait Pet {
fn is_hungry(&self, since_last_meal: Duration) -> bool;
}
#[test]
fn test_robot_dog() {
let mut mock_dog = MockPet::new();
mock_dog.expect_is_hungry().return_const(true);
assert_eq!(mock_dog.is_hungry(Duration::from_secs(10)), true);
}
// ANCHOR_END: simple_example
// ANCHOR: extended_example
#[test]
fn test_robot_cat() {
let mut mock_cat = MockPet::new();
mock_cat
.expect_is_hungry()
.with(mockall::predicate::gt(Duration::from_secs(3 * 3600)))
.return_const(true);
mock_cat.expect_is_hungry().return_const(false);
assert_eq!(mock_cat.is_hungry(Duration::from_secs(1 * 3600)), false);
assert_eq!(mock_cat.is_hungry(Duration::from_secs(5 * 3600)), true);
}
// ANCHOR_END: extended_example

View File

@ -0,0 +1,54 @@
---
minutes: 5
---
# Mocking
For mocking, [Mockall] is a widely used library. You need to refactor your code
to use traits, which you can then quickly mock:
```rust,ignore
{{#include mockall.rs:simple_example}}
```
[Mockall]: https://docs.rs/mockall/
<details>
- Mockall is the recommended mocking library in Android (AOSP). There are other
[mocking libraries available on crates.io](https://crates.io/keywords/mock),
in particular in the area of mocking HTTP services. The other mocking
libraries work in a similar fashion as Mockall, meaning that they make it easy
to get a mock implementation of a given trait.
- Note that mocking is somewhat _controversial_: mocks allow you to completely
isolate a test from its dependencies. The immediate result is faster and more
stable test execution. On the other hand, the mocks can be configured wrongly
and return output different from what the real dependencies would do.
If at all possible, it is recommended that you use the real dependencies. As
an example, many databases allow you to configure an in-memory backend. This
means that you get the correct behavior in your tests, plus they are fast and
will automatically clean up after themselves.
Similarly, many web frameworks allow you to start an in-process server which
binds to a random port on `localhost`. Always prefer this over mocking away
the framework since it helps you test your code in the real environment.
- Mockall is not part of the Rust Playground, so you need to run this example in
a local environment. Use `cargo add mockall` to quickly add Mockall to an
existing Cargo project.
- Mockall has a lot more functionality. In particular, you can set up
expectations which depend on the arguments passed. Here we use this to mock a
cat which becomes hungry 3 hours after the last time it was fed:
```rust,ignore
{{#include mockall.rs:extended_example}}
```
- You can use `.times(n)` to limit the number of times a mock method can be
called to `n` --- the mock will automatically panic when dropped if this isn't
satisfied.
</details>

View File

@ -0,0 +1,36 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: leftpad
//! Left-padding library.
/// Left-pad `s` to `width`.
pub fn leftpad(s: &str, width: usize) -> String {
format!("{s:>width$}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_string() {
assert_eq!(leftpad("foo", 5), " foo");
}
#[test]
fn long_string() {
assert_eq!(leftpad("foobar", 6), "foobar");
}
}