Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
A test is a function that checks your code behaves as you expect. Tests catch bugs before they reach your users — and they let you refactor boldly without breaking anything.
Rust ships its testing framework directly: cargo test compiles your
project and runs all test functions.
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
// → test it_works ... ok
}
}
#[test] marks a function as a test#[cfg(test)] says: compile this module only during cargo testassert_eq! checks equality; fails otherwisecargo test reports the number of passing and failing tests at the end.
cfg(test) keeps tests out of the build
#[cfg(test)] ensures test code is only compiled when testing — not in your
normal cargo build or cargo run. So your tests don't bloat the shipped
binary.
Check: What does #[cfg(test)] do?
Answer: It compiles the code only when cargo test runs
#[cfg(test)] compiles test code exclusively during cargo test, so tests don't end up in normal builds.
⚠ Common mistake: Without
#[test]above the function, your test never runs —cargo teststill reports a greentest result: ok, but with0 passed. A quick look at the summary reveals it:running 0 testsmeans the attribute is missing.
Takeaways:
assert!(condition) — fails if the condition is falseassert_eq!(left, right) — checks equality; shows both values on failureassert_ne!(left, right) — checks inequalitypanic!(...) — aborts immediately (test fails)#[test]
fn test_assertions() {
assert!(1 + 1 == 2);
assert_eq!(2 * 3, 6);
assert_ne!(5, 6);
}
On failure assert_eq! shows both values. For your own message, append one:
#[test]
fn with_message() {
let value = 3;
assert_eq!(value, 4, "value {} was not 4", value);
// → panic: assertion 'left == right' failed: value 3 was not 4
}
Why assert_eq! needs Debug output
assert_eq! and assert_ne! require the types to implement Debug and
PartialEq. Most standard types already do; for your own structs you derive
them with #[derive(Debug, PartialEq)].
Check: What does assert_eq! show on failure?
Answer: Both values (left and right) so you can compare them
assert_eq! shows both values (thanks to Debug) on failure, so you immediately see how they differ.
⚠ Common mistake:
assert_eq!(0.1 + 0.2, 0.3)fails because0.1 + 0.2is0.30000000000000004in binary. Compare floats with a tolerance: take the difference, apply.abs(), and check it against a small epsilon — exact equality is almost never what you mean with floating-point numbers.
Takeaways:
Sometimes code should deliberately panic (e.g. on invalid input). With
#[should_panic] you mark a test that only passes if it panics:
#[test]
#[should_panic(expected = "empty")]
fn panic_on_empty_input() {
let v: Vec<i32> = vec![];
if v.is_empty() {
panic!("List is empty");
}
let _ = v[0];
}
expected checks that the panic message contains the text — so you catch
accidental panics from other causes.
A test can also return a Result. Then Ok(()) = pass, Err(_) = fail. This
lets you use ? in tests:
#[test]
fn with_result() -> Result<(), String> {
let s = "42".parse::<i32>();
s.map(|_| ()).map_err(|e| format!("{e}"))
}
should_panic catches only the expected panic
#[should_panic(expected = "...")] ensures the panic really comes from the
expected place. Without expected the test would also pass if a panic
occurred elsewhere — e.g. in test setup.
Check: When does a test with #[should_panic] pass?
Answer: When the code in the test panics
#[should_panic] marks a test that only passes when the tested code triggers a panic. With expected you also check the message.
⚠ Common mistake:
expected = "empty"only checks that this exact substring appears in the panic message — case included. If the code panics withList is Empty(capital E), the test fails despite the panic. Quote a literal snippet from the actual panic message.
Takeaways:
Unit tests check individual functions or modules in isolation — without
side effects like files or network. By convention they live in the same file
as the code, in a #[cfg(test)] module:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*; // brings add into scope
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
}
Because the test module is inside the file, it can also test private functions and fields — an advantage of same-file unit tests.
use super:: brings everything up*
use super::*; imports all items of the parent module (the file the test
lives in) into the test scope. So you can call add(2, 3) directly instead of
super::add(2, 3).
Check: Where do unit tests conventionally live?
Answer: In the same file as the code, in a #[cfg(test)] module
Unit tests conventionally live in the same file, in a #[cfg(test)] mod tests. That lets them test private items too.
⚠ Common mistake: Without
use super::*;in the test module the compiler can't find your code:error[E0425]: cannot find function 'add' in this scope. The function lives in the parent module of the file, not in thetestsmodule itself.
Takeaways:
Integration tests check your library like an external user — only
through the public API. They live in the tests/ folder, outside of
src/:
project/
├── src/
│ └── lib.rs
└── tests/
└── integration_test.rs
// tests/integration_test.rs
use my_crate::add;
#[test]
fn test_add_public() {
assert_eq!(add(2, 3), 5);
}
Each file in tests/ is its own crate that imports your library like a
user. You must make the functions pub.
Only the public API is reachable
Integration tests see only the pub items of your library. That's
intentional: they test what your real users use. Private details stay hidden —
unit tests are responsible for those.
Check: What can integration tests see, unlike unit tests?
Answer: Only the public (pub) API of the library
Integration tests import your crate like a user and thus see only pub items. Private details stay invisible.
⚠ Common mistake: Putting shared helpers into
tests/common.rsbackfires: Cargo compiles every file intests/as its own test binary and runs it — so your helper file gets its own test run too. Usetests/common/mod.rsinstead, and the helper stays an ordinary library.
Takeaways:
cargo test — runs all testscargo test name — runs only tests whose name contains namecargo test -- --test-threads=1 — tests one at a time (not parallel)cargo test -- --nocapture — shows println! output of testscargo test -- --ignored — runs only the ignored testsWith #[ignore] you skip a test during cargo test (useful for slow tests):
#[test]
#[ignore]
fn very_slow() {
// expensive, run only when needed
}
With cargo test -- --ignored you run only those.
Understanding test threads
By default tests run in parallel on multiple threads — faster, but shared
state (files, globals) can interfere. With --test-threads=1 they run
sequentially, which helps with shared resources.
Check: How do you run only tests whose name contains 'foo'?
Answer: cargo test foo
cargo test foo filters tests by name: it runs all tests whose name contains the text 'foo'.
⚠ Common mistake:
cargo test --test-threads=1without the--separator fails — the flag belongs to the test binary, not to Cargo. The correct form iscargo test -- --test-threads=1; only after the--do arguments reach the tests.
Takeaways:
You secure a function with unit and integration tests:
maximum(numbers: &[i32]) -> Option<i32> that returns the
largest element (or None for an empty slice).#[cfg(test)] module with unit tests:
None#[should_panic] test that checks a deliberately panicking helper
function really panics.lib.rs) and write an integration test in
the tests/ folder that calls maximum through the public API.cargo test and confirm all tests are green.This connects #[test], assertions, should_panic, unit and integration
tests.
Recipes from this module
#[test] in a #[cfg(test)] moduleassert!, assert_eq!, assert_ne!#[should_panic(expected = "...")]tests/ folder, own cratecargo testScenario: The price sum
Beyond unit tests: formal verification
Unit tests check examples — formal verification proves that no input can break your program. Rust's type system is already a lightweight proof system: the borrow checker proves that no use-after-free can occur.
Current research goes further:
Tests check what you can imagine. Verification checks what you cannot imagine. For security-critical code, both are needed.
⚠ Common mistake:
let mut max = 0;passes every test with positive numbers and collapses on negative input:maximum(&[-5, -2])then wrongly returnsSome(0)instead ofSome(-2). Start from the first element and handle the empty slice withNone.
Takeaways:
Course navigation: ← Module 14 · All 27 modules · Module 16 →