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
cookbookmodule. Custom matcher cookbook. - prelude
- The one
usea 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§
- Arbitrary
Strategy - A
Strategythat generates values ofTthroughquickcheck::Arbitrary. - Backoff
- The inter-probe sleep schedule for
eventuallyandeventually_blocking. - Context
Frame - 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_withinwhen the future outlives its limit. - GenError
- An opaque error from a strategy that could not produce a value.
- Inline
Location - Where an inline-snapshot call sits in the source: enough for the
test-better-acceptbinary to find the literal and rewrite it. - Inline
Snapshot Failure - An inline snapshot did not match and
UPDATE_SNAPSHOTSwas unset. - Items
- An eager
Sequencewrapper around an iterator’s collected items. - Match
Result - 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.
- Property
Config - How a property run is configured.
- Property
Failure - A property that did not hold.
- Proptest
Tree - Adapts a
proptestvalue tree to the seam’sValueTree. - Quickcheck
Tree - Adapts
quickcheck’s linearshrinkiterator to the seam’sValueTree. - 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
Strategydraws from: the random number generator and the backend’s bookkeeping. - Soft
Asserter - The recorder passed to a
softclosure. - Soft
Scope - A context sub-scope of a
SoftAsserter, returned bySoftAsserter::context. - Source
Location - A source location, owned and serializable (the plain-data form of
std::panic::Location). - Structured
Context Frame - The plain-data form of
crate::ContextFrame. - Structured
Error - The plain-data, owned, serializable mirror of
TestError. - Subject
- A value under test, paired with the source text of the expression that produced it.
- Test
Error - A test failure.
- Trace
- A scoped collector of in-test breadcrumbs.
Enums§
- Color
Choice - When rendered failures should use ANSI color.
- Error
Kind - The category of a
TestError. - Payload
- Structured detail attached to a
TestErrorbeyond its message. - Snapshot
Failure - Why a snapshot assertion did not pass.
- Snapshot
Mode - Whether a snapshot assertion compares against the stored file or rewrites it.
- Structured
Payload - The plain-data form of
Payload. - Trace
Entry - One breadcrumb recorded on a
Trace.
Constants§
- RUNNER_
ENV - The environment variable the runner sets on the
cargo testit 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§
- Contains
All - A tuple of matchers, all over the same
Item, forcontains_all. - Context
Ext - Attaches context to the failure path of a
Resultor theNoneof anOption. - Float
- A floating-point type the numeric matchers operate on.
- Matcher
- A reusable expectation about a value of type
T. - Matcher
Tuple - A tuple of matchers, all targeting the same type
T. - OrFail
- Converts a fallible value into a
TestResult, producing aTestErroron the failure path. - Runtime
Available - 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. - Value
Tree - 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
Strategyfor a type:proptest’sany::<T>(), surfaced through the seam. - any_of
- Matches when at least one matcher in the tuple matches.
- arbitrary
- Bridges a
quickcheck::Arbitrarytype into the seam as aStrategy<T>. - assert_
inline_ snapshot - Compares
actualagainst the inline-snapshot literalraw. - assert_
snapshot - Compares
actualagainst the snapshot formodule_path/name, with the snapshot directory resolved astests/snapshotsunder the current working directory and the mode read fromUPDATE_SNAPSHOTS. - assert_
snapshot_ in - Compares
actualagainst (or, inUpdatemode, writes it to) the snapshot file formodule_path/nameunderdir. - 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
toleranceofvalue(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
matchersin order, not necessarily contiguously. - contains_
str - Matches a string that contains
needleas a substring. - diff_
lines - Renders a line-oriented diff between
expectedandactual. - ends_
with - Matches a string that ends with
suffix. - eq
- Matches a value equal to
expected. - err
- Matches an
Errwhose contained value satisfiesinner. - eventually
- Retries
probeuntil it resolves totrue, or fails oncetimeoutelapses. - eventually_
blocking - The runtime-free
eventually: retriesprobeuntil it returnstrueortimeoutelapses, sleeping between attempts withstd::thread::sleep. - eventually_
blocking_ with eventually_blockingwith an explicitBackoffschedule instead of the default.- eventually_
with eventuallywith an explicitBackoffschedule instead of the default.- every
- Matches a sequence in which every item satisfies
matcher. - for_all
- Asserts that
propertyholds for every value drawn fromstrategy, usingConfig::defaultand a reproducibleRunner. - for_
all_ with - Asserts that
propertyholds for every value drawn fromstrategy, with an explicitConfigandRunner. - 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
nitems. - 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
Itemswrapper that implementsSequence. - 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
patternfinds 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
matcherdoes not match. - ok
- Matches an
Okwhose contained value satisfiesinner. - 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
predreturnstrue. - set_
color_ choice - Sets the process-wide
ColorChoicefor rendered failures. - snapshot_
path - The path of the snapshot file for
module_pathandnameunderdir. - soft
- Runs
fin a soft-assertion scope. - some
- Matches a
Somewhose contained value satisfiesinner. - starts_
with - Matches a string that starts with
prefix.
Type Aliases§
- Test
Result - The result type returned by
test-bettertests and helpers.
Attribute Macros§
- fixture
- Marks a
fn() -> TestResult<T>as a fixture: a reusable piece of test setup whose failures surface asErrorKind::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].