Skip to main content

Crate test_better

Crate test_better 

Source
Expand description

test-better: Result-returning Rust tests with ?.

test-better makes a test that returns TestResult and uses ? strictly better than a panicking one: a failure is a value that carries the expression that failed, the values involved, the source location, and the context you attached on the way down.

This is the facade crate, the one users depend on. It re-exports the public surface of the workspace’s focused crates (test-better-core, test-better-matchers, and so on) so a test file needs a single dependency and, ideally, a single use:

use test_better::prelude::*;

fn parse_port(input: &str) -> Option<u16> {
    input.parse().ok()
}

// `or_fail_with` is the `?`-friendly stand-in for a panicking unwrap;
// `check!` captures the expression text so a failure names `port`,
// not just its value.
let port = parse_port("8080").or_fail_with("8080 is a valid port")?;
check!(port).satisfies(eq(8080))?;
check!(port).violates(lt(1024))?;

In a real test file the body above is a #[test] fn ... -> TestResult ending in Ok(()). See the prelude for the one import a test file needs, and the cookbook for writing custom matchers. The prose guide (Getting Started, migrating from the stock assertion macros, async, property, snapshot, and fixture testing) is the test-better book under book/.

Modules§

cookbook
How to write a custom matcher: see the cookbook module. Custom matcher cookbook.
prelude
The one use a test file should need: use test_better::prelude::*;.

Macros§

check
Captures an expression and its source text for assertion with a matcher.
define_matcher
Defines a custom matcher from a predicate and a description.
matches_struct
Matches a struct by applying an inner matcher to each named field.
matches_tuple
Matches a tuple struct by applying an inner matcher to each positional field.
matches_variant
Matches an enum value against a specific variant, applying an inner matcher to each of that variant’s fields.
property
Checks that a property holds for every generated input.

Structs§

ArbitraryStrategy
A Strategy that generates values of T through quickcheck::Arbitrary.
Backoff
The inter-probe sleep schedule for eventually and eventually_blocking.
ContextFrame
One human-readable frame in a TestError’s context chain.
Description
A composable description of a matcher’s expectation.
Elapsed
The error returned by run_within when the future outlives its limit.
GenError
An opaque error from a strategy that could not produce a value.
InlineLocation
Where an inline-snapshot call sits in the source: enough for the test-better-accept binary to find the literal and rewrite it.
InlineSnapshotFailure
An inline snapshot did not match and UPDATE_SNAPSHOTS was unset.
Items
An eager Sequence wrapper around an iterator’s collected items.
MatchResult
The structured outcome of Matcher::check.
Mismatch
Why a value failed a matcher: what was expected, what was found, and an optional diff between the two.
PropertyConfig
How a property run is configured.
PropertyFailure
A property that did not hold.
ProptestTree
Adapts a proptest value tree to the seam’s ValueTree.
QuickcheckTree
Adapts quickcheck’s linear shrink iterator to the seam’s ValueTree.
Redactions
An ordered set of text rewrites applied to a value before it is compared against (or written to) a snapshot.
Runner
The per-run state a Strategy draws from: the random number generator and the backend’s bookkeeping.
SoftAsserter
The recorder passed to a soft closure.
SoftScope
A context sub-scope of a SoftAsserter, returned by SoftAsserter::context.
SourceLocation
A source location, owned and serializable (the plain-data form of std::panic::Location).
StructuredContextFrame
The plain-data form of crate::ContextFrame.
StructuredError
The plain-data, owned, serializable mirror of TestError.
Subject
A value under test, paired with the source text of the expression that produced it.
TestError
A test failure.
Trace
A scoped collector of in-test breadcrumbs.

Enums§

ColorChoice
When rendered failures should use ANSI color.
ErrorKind
The category of a TestError.
Payload
Structured detail attached to a TestError beyond its message.
SnapshotFailure
Why a snapshot assertion did not pass.
SnapshotMode
Whether a snapshot assertion compares against the stored file or rewrites it.
StructuredPayload
The plain-data form of Payload.
TraceEntry
One breadcrumb recorded on a Trace.

Constants§

RUNNER_ENV
The environment variable the runner sets on the cargo test it spawns.
STRUCTURED_MARKER
The sentinel that brackets the JSON structured-error payload on its own line in captured test output. Chosen to be unmistakable in prose and to sit alone on a line.

Traits§

ContainsAll
A tuple of matchers, all over the same Item, for contains_all.
ContextExt
Attaches context to the failure path of a Result or the None of an Option.
Float
A floating-point type the numeric matchers operate on.
Matcher
A reusable expectation about a value of type T.
MatcherTuple
A tuple of matchers, all targeting the same type T.
OrFail
Converts a fallible value into a TestResult, producing a TestError on the failure path.
RuntimeAvailable
A marker trait, implemented for every type when (and only when) a runtime feature is enabled.
Sequence
An ordered run of items a collection matcher can inspect.
Strategy
A source of values of type T, with shrinking, for property testing.
ValueTree
A single generated value that can be shrunk toward a simpler one.

Functions§

all_of
Matches when every matcher in the tuple matches.
always_matches
A matcher that matches every value, for testing matcher machinery.
any
The default Strategy for a type: proptest’s any::<T>(), surfaced through the seam.
any_of
Matches when at least one matcher in the tuple matches.
arbitrary
Bridges a quickcheck::Arbitrary type into the seam as a Strategy<T>.
assert_inline_snapshot
Compares actual against the inline-snapshot literal raw.
assert_snapshot
Compares actual against the snapshot for module_path/name, with the snapshot directory resolved as tests/snapshots under the current working directory and the mode read from UPDATE_SNAPSHOTS.
assert_snapshot_in
Compares actual against (or, in Update mode, writes it to) the snapshot file for module_path/name under dir.
at_least_one
Matches a sequence in which at least one item satisfies matcher.
between
Matches a float in the inclusive range low..=high.
close_to
Matches a float within tolerance of value (the comparison is |actual - value| <= tolerance).
color_choice
Returns the process-wide ColorChoice.
contains
Matches a sequence that contains at least one item satisfying matcher.
contains_all
Matches a sequence in which every matcher in the tuple is satisfied by some item (each matcher independently; one item may satisfy several).
contains_in_order
Matches a sequence that contains items satisfying matchers in order, not necessarily contiguously.
contains_str
Matches a string that contains needle as a substring.
diff_lines
Renders a line-oriented diff between expected and actual.
ends_with
Matches a string that ends with suffix.
eq
Matches a value equal to expected.
err
Matches an Err whose contained value satisfies inner.
eventually
Retries probe until it resolves to true, or fails once timeout elapses.
eventually_blocking
The runtime-free eventually: retries probe until it returns true or timeout elapses, sleeping between attempts with std::thread::sleep.
eventually_blocking_with
eventually_blocking with an explicit Backoff schedule instead of the default.
eventually_with
eventually with an explicit Backoff schedule instead of the default.
every
Matches a sequence in which every item satisfies matcher.
for_all
Asserts that property holds for every value drawn from strategy, using Config::default and a reproducible Runner.
for_all_with
Asserts that property holds for every value drawn from strategy, with an explicit Config and Runner.
ge
Matches a value greater than or equal to expected.
gt
Matches a value strictly greater than expected.
have_len
Matches a sequence with exactly n items.
is_empty
Matches a sequence with no items.
is_false
Matches false.
is_finite
Matches a float that is finite (neither infinite nor NaN).
is_nan
Matches a float that is NaN.
is_not_empty
Matches a sequence with at least one item.
is_true
Matches true.
items
Collects an iterator into an Items wrapper that implements Sequence.
le
Matches a value less than or equal to expected.
lt
Matches a value strictly less than expected.
matches_regex
Matches a string that the regular expression pattern finds a match in.
ne
Matches a value not equal to expected.
never_matches
A matcher that matches no value, for testing matcher machinery.
none
Matches None.
normalize_inline_literal
Normalizes an inline-snapshot literal to the text it actually stands for.
not
Matches when matcher does not match.
ok
Matches an Ok whose contained value satisfies inner.
parse_pending_patch
Parses a pending-patch file body back into its parts: the source file, the call-site line and column, and the new snapshot value.
pending_patch_dir
The directory pending inline-snapshot patches are written to and read from: target/test-better-pending/ under the workspace root.
predicate
Matches a value for which pred returns true.
set_color_choice
Sets the process-wide ColorChoice for rendered failures.
snapshot_path
The path of the snapshot file for module_path and name under dir.
soft
Runs f in a soft-assertion scope.
some
Matches a Some whose contained value satisfies inner.
starts_with
Matches a string that starts with prefix.

Type Aliases§

TestResult
The result type returned by test-better tests and helpers.

Attribute Macros§

fixture
Marks a fn() -> TestResult<T> as a fixture: a reusable piece of test setup whose failures surface as ErrorKind::Setup, never as assertion misses.
test_case
Generates one #[test] per #[test_case(..)] line on a function.
test_with_fixtures
Turns a test whose parameters are fixtures into a runnable #[test].