Rust unit tests

From warpdotdev/warp · View interactive version

Rust unit tests is an AI agent skill from the GitHub repository warpdotdev/warp. Write, improve, and run Rust unit tests in the warp Rust codebase.

How to use this skill

Skill file

Rust Unit Tests in warp

Scope

What to unit test

Default to a unit test when the logic is deterministic and reachable without booting the app:

Prefer unit tests for anything that fits: they are fast, deterministic, and point straight at the failure.

When a unit test is the wrong level

Be honest about this codebase. Warp is a terminal emulator with a GPU renderer, PTY and shell integration, and IPC. The common "80% unit tests" heuristic assumes a business-logic-heavy system where units exchange messages and transform data. Large parts of this repo are not that, and forcing them under a unit test usually means mocking away the only thing that could actually break.

Escalate to a higher level when any of these hold:

Where to go instead:

Before escalating, try splitting the problem. Most "untestable" code is a thin shell of IO wrapped around logic that tests fine once separated: extract the decision-making into a pure function, unit test that, and let an integration test cover the thin shell that remains. That is usually cheaper than either a heavily stubbed unit test or a full app-boot test.

That said, weigh the indirection on its own merits. Code that is hard to test is sometimes genuinely badly designed — if extracting the logic would make the code clearer regardless of testing, do it. If the seam would exist only to satisfy a test, don't.

When NOT to write a unit test

Tests cost real maintenance, and a bad test costs more than no test. Skip or delete these:

Don't chase a coverage number. Coverage says a line executed, not that anything was verified, and a target reliably turns into a ceiling.

Where unit tests live

#[cfg(test)]
#[path = "filename_tests.rs"] // or "mod_tests.rs"
mod tests;

Writing good tests

Aim for a test you never touch again unless the behavior changes. Refactors, new features, and bug fixes should not require editing existing tests; only a deliberate behavior change should. If a refactor breaks your tests, that is usually a defect in the tests.

Test behavior through the public API

Exercise the unit the way its callers do. Reaching into private state makes the test fail on refactors no caller would notice. If a helper type exists only to serve one or two callers, test it through them rather than directly.

Assert on state, not on interactions

Assert what the system is after the action, not which functions it called to get there.

// Brittle: still passes if the entry is dropped right after insertion, and
// fails on an equivalent refactor that calls a different internal method.
assert!(recorder.saw_call_to_insert(id));

// Better: asserts the outcome the caller actually cares about.
store.insert(id, entry.clone());
assert_eq!(store.get(id), Some(&entry));

One behavior per test, named after that behavior

The test name is often the only thing visible in a failure report, so make it a sentence about behavior rather than about the method:

#[test]
fn parses_utf8_sequence_when_valid() { /* ... */ }

#[test]
fn returns_replacement_char_for_invalid_utf8() { /* ... */ }

If the name needs an "and", you are testing two behaviors — split it. Structure the body as arrange / act / assert, separated by blank lines.

Keep the test complete and concise

Everything a reader needs to understand the result belongs in the test body; everything irrelevant belongs out of it. Prefer a builder or helper constructor that takes only the fields the test cares about over one large shared fixture. If a test asserts on a specific value, set that value in the test rather than inheriting it from shared setup.

Prefer duplication over indirection

Test code has no tests of its own, so it has to be obviously correct on inspection. Some repetition is a fair price for a test that reads top to bottom. Extract a helper when it removes noise, not merely to remove repetition.

No logic in tests

No conditionals, loops, arithmetic, or string concatenation to compute an expected value. Write expected values literally — computing them re-implements the code under test and can reproduce the same bug in the assertion.

Make failures diagnosable

Repo-specific

Test doubles: prefer real code, then fakes

Work down this list and stop at the first option that is fast and deterministic:

  1. The real implementation. The default for value types and pure logic. Running real collaborator code is what makes a test meaningful, and a failure caused by a real dependency's bug is a true positive worth having.
  2. A fake the repo already provides. These are maintained alongside the real thing, so they don't drift the way hand-rolled doubles do: warpui::App::test, VirtualFS, TerminalModel::mock(..), TestBlockListBuilder/TestBlockBuilder, Appearance::mock(), and FeatureFlag::X.override_enabled(..). See "Common helpers to use" below for usage.
  3. A stubbed return value, only to push the unit into a state you cannot otherwise reach, such as a rare error branch. Each stub should map to an assertion in the same test. Needing many stubs is a signal the unit does too much.
  4. Asserting that a call happened, as a last resort, and only for state-changing effects (a write, a send, a spawn) whose result you cannot observe any other way. Never assert on calls to pure getters — the return value is already covered by whatever you assert next.

Keeping tests deterministic

A flaky test is worse than no test: once people learn to re-run a red test, they stop trusting every other test too. Fix the cause instead of adding retries.

If you can't make a test deterministic quickly, quarantine it (#[ignore] with a linked issue) rather than leaving an intermittently red test in the suite — and treat that as debt to pay down, not a place to leave it.

Async and feature-gated code

Quickstart harness (UI/model tests)

use warpui::App;
// In app crate tests prefer `crate::test_util::...`; from other crates use `warp::test_util::...`.
use warp::test_util::{terminal::initialize_app_for_terminal_view, add_window_with_terminal};

#[test]
fn example() {
    App::test((), |mut app| async move {
        // One-time app setup for terminal/view tests
        initialize_app_for_terminal_view(&mut app); // includes settings init
        let term = add_window_with_terminal(&mut app, None);

        // Act
        term.update(&mut app, |view, _ctx| {
            view.model.lock().simulate_block("ls", "out");
        });

        // Assert
        term.read(&app, |view, _ctx| {
            assert!(view.model.lock().block_list().len() > 0);
        });
    })
}

TUI element tests

Tests for the headless TUI render an element tree to text lines rather than drawing pixels. Use warpui_core::elements::tui::test_support::render_to_lines and TuiBuffer::to_lines, and keep them in *_tests.rs files next to the source in crates/warp_tui and crates/warpui_core/src/elements/tui. They are plain unit tests and do NOT use the GUI integration / real-display / computer_use framework. See the tui-testing skill for details. The warpui::App::test harness above still applies to shared model logic that both front-ends use.

Common helpers to use

use virtual_fs::{VirtualFS, Stub};
VirtualFS::test("case", |_dirs, mut fs| {
    fs.with_files(vec![Stub::FileWithContent("path/file.txt", "contents")]);
    // run logic and assert
});
use warp::features::FeatureFlag; // or `use crate::features::FeatureFlag;` inside the app crate
let _flag = FeatureFlag::CreatingSharedSessions.override_enabled(true);
assert_lines_approx_eq!(actual_lines, INLINE_BANNER_HEIGHT);

Running unit tests

cargo nextest run --no-fail-fast --workspace
cargo nextest run -p <crate_name>
cargo nextest run -E 'test(<substring>)'
cargo test --doc

Final validation order

After the relevant tests pass, run Clippy, fix its findings, and then format once:

cargo clippy -p <package_name> --all-targets --tests -- -D warnings
./script/format

Do not rerun tests or Clippy after formatting, and do not add a full ./script/presubmit run, unless the user, task, or approved spec explicitly requires it. Follow the repository's Implementation Validation Order in AGENTS.md for invalidation and follow-up changes.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.