test-better-core 0.2.1

Core error and result types (`TestError`, `TestResult`) for the test-better testing library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! The [`TestError`] data model: the single source of truth for a test failure.
//!
//! A `TestError` carries structured data, never pre-rendered text. Two consumers
//! read it:
//!
//! - the human renderer ([`Display`]/[`Debug`], see [`crate::render`]);
//! - tooling and the runner, via [`TestError::to_structured`].

use std::borrow::Cow;
use std::fmt;
use std::panic::Location;

use crate::trace::TraceEntry;

/// The category of a [`TestError`].
///
/// The kind selects the headline of the rendered failure and lets tooling group
/// failures (a setup failure is not the same as an assertion miss).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ErrorKind {
    /// An assertion did not hold (the common case).
    Assertion,
    /// Test setup failed before the assertions could run (fixtures).
    Setup,
    /// An operation did not complete within its deadline.
    Timeout,
    /// A snapshot did not match its stored value.
    Snapshot,
    /// A property failed for some generated input.
    Property,
    /// A failure that does not fit the other kinds, including errors propagated
    /// from non-`test-better` code via `?`.
    Custom,
}

impl ErrorKind {
    /// The headline shown on the first line of a rendered failure.
    #[must_use]
    pub fn headline(self) -> &'static str {
        match self {
            ErrorKind::Assertion => "assertion failed",
            ErrorKind::Setup => "test setup failed",
            ErrorKind::Timeout => "timed out",
            ErrorKind::Snapshot => "snapshot mismatch",
            ErrorKind::Property => "property failed",
            ErrorKind::Custom => "test failed",
        }
    }
}

/// One human-readable frame in a [`TestError`]'s context chain.
///
/// Frames render in the order they were added, so the chain reads from the
/// outermost circumstance to the innermost.
#[derive(Debug, Clone)]
pub struct ContextFrame {
    /// The "while doing X" description.
    pub message: Cow<'static, str>,
    /// Where the frame was attached, when known.
    pub location: Option<&'static Location<'static>>,
}

impl ContextFrame {
    /// Creates a frame, capturing the caller's location.
    #[track_caller]
    #[must_use]
    pub fn new(message: impl Into<Cow<'static, str>>) -> Self {
        Self {
            message: message.into(),
            location: Some(Location::caller()),
        }
    }
}

/// Structured detail attached to a [`TestError`] beyond its message.
#[derive(Debug)]
#[non_exhaustive]
pub enum Payload {
    /// A comparison failure carrying the expected and actual values, and an
    /// optional structural diff.
    ExpectedActual {
        /// `Debug`-rendered expected value.
        expected: String,
        /// `Debug`-rendered actual value.
        actual: String,
        /// Optional pre-rendered diff between the two.
        diff: Option<String>,
    },
    /// Several failures collected together (soft assertions).
    Multiple(Vec<TestError>),
    /// An error propagated from outside `test-better`, preserved so its source
    /// chain stays walkable.
    Other(Box<dyn std::error::Error + Send + Sync>),
}

/// A test failure.
///
/// Every fallible `test-better` operation produces a `TestError` on the error
/// path, so `?` is the single control-flow operator of a test.
///
/// # Note on the `message` field
///
/// An earlier design sketch had `TestError` without a top-level `message`.
/// A dedicated `message` field is kept here instead of overloading the first
/// context frame: the message answers *what* failed, while context frames
/// answer *while doing what*. This deviation is recorded in `CHANGELOG.md`.
pub struct TestError {
    /// The failure category.
    pub kind: ErrorKind,
    /// What failed, when there is a concise statement of it.
    pub message: Option<Cow<'static, str>>,
    /// Where the failure originated (`#[track_caller]` capture).
    pub location: &'static Location<'static>,
    /// The context chain, outermost first.
    pub context: Vec<ContextFrame>,
    /// The in-test breadcrumbs ([`Trace`](crate::Trace)) that were active when
    /// this error was built, oldest first. Empty when no `Trace` was in scope.
    pub trace: Vec<TraceEntry>,
    /// Structured detail, when applicable.
    ///
    /// Boxed so `TestError` stays small: it is returned by value through every
    /// `?` in a test, and [`Payload::ExpectedActual`] would otherwise inline
    /// three `String`s into the struct.
    pub payload: Option<Box<Payload>>,
}

impl TestError {
    /// Builds a bare error at an explicit location. Internal: the public
    /// surface is the `#[track_caller]` constructors, which capture the
    /// caller's location for themselves.
    pub(crate) fn at(kind: ErrorKind, location: &'static Location<'static>) -> Self {
        Self {
            kind,
            message: None,
            location,
            context: Vec::new(),
            // Snapshot the active `Trace` (if any) at construction time, so the
            // error carries the breadcrumbs that led up to the failure.
            trace: crate::trace::snapshot(),
            payload: None,
        }
    }

    /// Creates a bare error of the given `kind`, capturing the caller's location.
    #[track_caller]
    #[must_use]
    pub fn new(kind: ErrorKind) -> Self {
        Self::at(kind, Location::caller())
    }

    /// Creates an [`ErrorKind::Assertion`] error with the given message.
    ///
    /// This is the common path for a hand-written failure: `return
    /// Err(TestError::assertion("..."))`.
    #[track_caller]
    #[must_use]
    pub fn assertion(message: impl Into<Cow<'static, str>>) -> Self {
        Self::at(ErrorKind::Assertion, Location::caller()).with_message(message)
    }

    /// Creates an [`ErrorKind::Custom`] error with the given message, for a
    /// failure that does not fit a more specific kind.
    #[track_caller]
    #[must_use]
    pub fn custom(message: impl Into<Cow<'static, str>>) -> Self {
        Self::at(ErrorKind::Custom, Location::caller()).with_message(message)
    }

    /// Creates an [`ErrorKind::Assertion`] error from a mismatched
    /// expected/actual pair, capturing each value's `Debug` representation into
    /// a [`Payload::ExpectedActual`].
    #[track_caller]
    #[must_use]
    pub fn from_expected_actual(expected: impl fmt::Debug, actual: impl fmt::Debug) -> Self {
        Self::at(ErrorKind::Assertion, Location::caller()).with_payload(Payload::ExpectedActual {
            expected: format!("{expected:?}"),
            actual: format!("{actual:?}"),
            diff: None,
        })
    }

    /// Sets the [`message`](Self::message), consuming and returning `self`.
    #[must_use]
    pub fn with_message(mut self, message: impl Into<Cow<'static, str>>) -> Self {
        self.message = Some(message.into());
        self
    }

    /// Overrides the [`kind`](Self::kind), consuming and returning `self`.
    ///
    /// This is how a failure is re-categorized after the fact: the `#[fixture]`
    /// macro uses it to turn whatever a fixture body produced into an
    /// [`ErrorKind::Setup`] failure, so a setup problem never masquerades as an
    /// assertion miss.
    #[must_use]
    pub fn with_kind(mut self, kind: ErrorKind) -> Self {
        self.kind = kind;
        self
    }

    /// Overrides the [`location`](Self::location), consuming and returning
    /// `self`.
    ///
    /// The `#[track_caller]` constructors capture the caller's location for
    /// themselves, so this is rarely needed. It exists for the case where the
    /// location must be captured separately from where the error is built: an
    /// `async fn` cannot be `#[track_caller]`, so the async `check!` methods
    /// capture [`Location::caller`] synchronously at the call site and thread
    /// it through here once the awaited assertion has a result.
    #[must_use]
    pub fn with_location(mut self, location: &'static Location<'static>) -> Self {
        self.location = location;
        self
    }

    /// Sets the [`payload`](Self::payload), consuming and returning `self`.
    #[must_use]
    pub fn with_payload(mut self, payload: Payload) -> Self {
        self.payload = Some(Box::new(payload));
        self
    }

    /// Appends a context frame, consuming and returning `self`.
    #[must_use]
    pub fn with_context_frame(mut self, frame: ContextFrame) -> Self {
        self.context.push(frame);
        self
    }

    /// Appends a context frame in place.
    pub fn push_context(&mut self, frame: ContextFrame) {
        self.context.push(frame);
    }
}

impl fmt::Display for TestError {
    /// Renders the failure as plain text, never colored.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        crate::render::render(self, f, false)
    }
}

impl fmt::Debug for TestError {
    /// Renders the full pretty failure message, so the stock `cargo test`
    /// harness (which prints returned errors with `{:?}`) is already useful.
    /// Unlike `Display`, this may emit ANSI
    /// color, gated by the process-wide [`ColorChoice`](crate::ColorChoice).
    ///
    /// When the `cargo test-better` runner is driving the run (it sets
    /// [`RUNNER_ENV`](crate::RUNNER_ENV)), a trailing marker line carrying the
    /// structured failure is appended after the human-readable render, for the
    /// runner's structured-output channel. An ordinary `cargo test` run never
    /// sets that variable, so it never sees that line.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        crate::render::render(self, f, crate::color::color_enabled())?;
        crate::runner::write_structured_marker(self, f)
    }
}

impl std::error::Error for TestError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self.payload.as_deref() {
            Some(Payload::Other(inner)) => Some(inner.as_ref()),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{OrFail, TestResult};
    use test_better_matchers::{check, eq, is_true};

    #[track_caller]
    fn sample_assertion() -> TestError {
        TestError::new(ErrorKind::Assertion).with_message("values differ")
    }

    #[test]
    fn new_captures_caller_location() -> TestResult {
        let line = line!() + 1;
        let error = TestError::new(ErrorKind::Assertion);
        check!(error.location.line())
            .satisfies(eq(line))
            .or_fail()?;
        check!(error.location.file().ends_with("error.rs"))
            .satisfies(is_true())
            .or_fail()?;
        Ok(())
    }

    #[test]
    fn display_includes_headline_message_and_location() -> TestResult {
        let rendered = sample_assertion().to_string();
        check!(rendered.contains("assertion failed: values differ"))
            .satisfies(is_true())
            .or_fail()?;
        check!(rendered.contains("  at "))
            .satisfies(is_true())
            .or_fail()?;
        Ok(())
    }

    #[test]
    fn debug_matches_display() -> TestResult {
        // `Debug` may colorize off the global `ColorChoice`; hold the lock so a
        // concurrent color test cannot flip it mid-render.
        let _guard = crate::color::TEST_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let error = sample_assertion();
        // `Debug` also appends the structured-output marker line when the
        // runner is driving the run (`RUNNER_ENV` set); compare only the
        // human-readable render, which is what `Display` produces.
        let debug = format!("{error:?}");
        let human = debug
            .split_once(crate::STRUCTURED_MARKER)
            .map_or(debug.as_str(), |(before, _)| before.trim_end());
        check!(human)
            .satisfies(eq(format!("{error}").as_str()))
            .or_fail()?;
        Ok(())
    }

    #[test]
    fn context_frames_render_in_order() -> TestResult {
        let error = sample_assertion()
            .with_context_frame(ContextFrame::new("creating user"))
            .with_context_frame(ContextFrame::new("loading profile"));
        let rendered = error.to_string();
        let first = rendered
            .find("creating user")
            .or_fail_with("first frame present")?;
        let second = rendered
            .find("loading profile")
            .or_fail_with("second frame present")?;
        check!(first < second).satisfies(is_true()).or_fail()?;
        Ok(())
    }

    #[test]
    fn error_source_walks_into_payload_other() -> TestResult {
        let io = std::io::Error::new(std::io::ErrorKind::NotFound, "missing file");
        let error = TestError::new(ErrorKind::Custom).with_payload(Payload::Other(Box::new(io)));
        let source =
            std::error::Error::source(&error).or_fail_with("source is the wrapped io error")?;
        check!(source.to_string())
            .satisfies(eq("missing file".to_string()))
            .or_fail()?;
        Ok(())
    }

    #[test]
    fn expected_actual_payload_renders_both_values() -> TestResult {
        let error = TestError::new(ErrorKind::Assertion).with_payload(Payload::ExpectedActual {
            expected: "4".to_string(),
            actual: "5".to_string(),
            diff: None,
        });
        let rendered = error.to_string();
        check!(rendered.contains("expected: 4"))
            .satisfies(is_true())
            .or_fail()?;
        check!(rendered.contains("actual: 5"))
            .satisfies(is_true())
            .or_fail()?;
        Ok(())
    }

    #[test]
    fn multiple_payload_renders_every_sub_failure() -> TestResult {
        let error = TestError::new(ErrorKind::Assertion).with_payload(Payload::Multiple(vec![
            TestError::new(ErrorKind::Assertion).with_message("first"),
            TestError::new(ErrorKind::Assertion).with_message("second"),
        ]));
        let rendered = error.to_string();
        check!(rendered.contains("first"))
            .satisfies(is_true())
            .or_fail()?;
        check!(rendered.contains("second"))
            .satisfies(is_true())
            .or_fail()?;
        Ok(())
    }

    #[test]
    fn assertion_constructor_sets_kind_message_and_caller_location() -> TestResult {
        let line = line!() + 1;
        let error = TestError::assertion("values differ");
        check!(error.kind)
            .satisfies(eq(ErrorKind::Assertion))
            .or_fail()?;
        check!(error.message.as_deref())
            .satisfies(eq(Some("values differ")))
            .or_fail()?;
        check!(error.location.line())
            .satisfies(eq(line))
            .or_fail()?;
        check!(error.location.file().ends_with("error.rs"))
            .satisfies(is_true())
            .or_fail()?;
        Ok(())
    }

    #[test]
    fn custom_constructor_sets_kind_message_and_caller_location() -> TestResult {
        let line = line!() + 1;
        let error = TestError::custom("something off");
        check!(error.kind)
            .satisfies(eq(ErrorKind::Custom))
            .or_fail()?;
        check!(error.message.as_deref())
            .satisfies(eq(Some("something off")))
            .or_fail()?;
        check!(error.location.line())
            .satisfies(eq(line))
            .or_fail()?;
        check!(error.location.file().ends_with("error.rs"))
            .satisfies(is_true())
            .or_fail()?;
        Ok(())
    }

    #[test]
    fn from_expected_actual_captures_debug_values_and_caller_location() -> TestResult {
        let line = line!() + 1;
        let error = TestError::from_expected_actual(4, 5);
        check!(error.kind)
            .satisfies(eq(ErrorKind::Assertion))
            .or_fail()?;
        check!(error.location.line())
            .satisfies(eq(line))
            .or_fail()?;
        match error.payload.map(|payload| *payload) {
            Some(Payload::ExpectedActual {
                expected,
                actual,
                diff,
            }) => {
                check!(expected).satisfies(eq("4".to_string())).or_fail()?;
                check!(actual).satisfies(eq("5".to_string())).or_fail()?;
                check!(diff.is_none()).satisfies(is_true()).or_fail()?;
            }
            other => panic!("expected ExpectedActual, got {other:?}"),
        }
        Ok(())
    }
}