pretty_assertions/
lib.rs

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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! # Pretty Assertions
//!
//! When writing tests in Rust, you'll probably use `assert_eq!(a, b)` _a lot_.
//!
//! If such a test fails, it will present all the details of `a` and `b`.
//! But you have to spot the differences yourself, which is not always straightforward,
//! like here:
//!
//! ![standard assertion](https://raw.githubusercontent.com/colin-kiegel/rust-pretty-assertions/2d2357ff56d22c51a86b2f1cfe6efcee9f5a8081/examples/standard_assertion.png)
//!
//! Wouldn't that task be _much_ easier with a colorful diff?
//!
//! ![pretty assertion](https://raw.githubusercontent.com/colin-kiegel/rust-pretty-assertions/2d2357ff56d22c51a86b2f1cfe6efcee9f5a8081/examples/pretty_assertion.png)
//!
//! Yep — and you only need **one line of code** to make it happen:
//!
//! ```rust
//! use pretty_assertions::{assert_eq, assert_ne};
//! ```
//!
//! <details>
//! <summary>Show the example behind the screenshots above.</summary>
//!
//! ```rust,should_panic
//! // 1. add the `pretty_assertions` dependency to `Cargo.toml`.
//! // 2. insert this line at the top of each module, as needed
//! use pretty_assertions::{assert_eq, assert_ne};
//!
//! #[derive(Debug, PartialEq)]
//! struct Foo {
//!     lorem: &'static str,
//!     ipsum: u32,
//!     dolor: Result<String, String>,
//! }
//!
//! let x = Some(Foo { lorem: "Hello World!", ipsum: 42, dolor: Ok("hey".to_string())});
//! let y = Some(Foo { lorem: "Hello Wrold!", ipsum: 42, dolor: Ok("hey ho!".to_string())});
//!
//! assert_eq!(x, y);
//! ```
//! </details>
//!
//! ## Tip
//!
//! Specify it as [`[dev-dependencies]`](http://doc.crates.io/specifying-dependencies.html#development-dependencies)
//! and it will only be used for compiling tests, examples, and benchmarks.
//! This way the compile time of `cargo build` won't be affected!
//!
//! Also add `#[cfg(test)]` to your `use` statements, like this:
//!
//! ```rust
//! #[cfg(test)]
//! use pretty_assertions::{assert_eq, assert_ne};
//! ```
//!
//! ## Note
//!
//! * Since `Rust 2018` edition, you need to declare
//!   `use pretty_assertions::{assert_eq, assert_ne};` per module.
//!   Before you would write `#[macro_use] extern crate pretty_assertions;`.
//! * The replacement is only effective in your own crate, not in other libraries
//!   you include.
//! * `assert_ne` is also switched to multi-line presentation, but does _not_ show
//!   a diff.
//!
//! ## Features
//!
//! Features provided by the crate are:
//!
//! - `std`: Use the Rust standard library. Enabled by default.
//!   Exactly one of `std` and `alloc` is required.
//! - `alloc`: Use the `alloc` crate.
//!   Exactly one of `std` and `alloc` is required.
//! - `unstable`: opt-in to unstable features that may not follow Semantic Versioning.
//!   Implmenetion behind this feature is subject to change without warning between patch versions.

#![cfg_attr(not(feature = "std"), no_std)]
#![deny(clippy::all, missing_docs, unsafe_code)]

#[cfg(feature = "alloc")]
#[macro_use]
extern crate alloc;
pub use ansi_term::Style;
use core::fmt::{self, Debug, Display};

mod printer;

#[cfg(windows)]
use ctor::*;
#[cfg(windows)]
#[ctor]
fn init() {
    output_vt100::try_init().ok(); // Do not panic on fail
}

/// A comparison of two values.
///
/// Where both values implement `Debug`, the comparison can be displayed as a pretty diff.
///
/// ```
/// use pretty_assertions::Comparison;
///
/// print!("{}", Comparison::new(&123, &134));
/// ```
///
/// The values may have different types, although in practice they are usually the same.
pub struct Comparison<'a, TLeft, TRight>
where
    TLeft: ?Sized,
    TRight: ?Sized,
{
    left: &'a TLeft,
    right: &'a TRight,
}

impl<'a, TLeft, TRight> Comparison<'a, TLeft, TRight>
where
    TLeft: ?Sized,
    TRight: ?Sized,
{
    /// Store two values to be compared in future.
    ///
    /// Expensive diffing is deferred until calling `Debug::fmt`.
    pub fn new(left: &'a TLeft, right: &'a TRight) -> Comparison<'a, TLeft, TRight> {
        Comparison { left, right }
    }
}

impl<'a, TLeft, TRight> Display for Comparison<'a, TLeft, TRight>
where
    TLeft: Debug + ?Sized,
    TRight: Debug + ?Sized,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // To diff arbitary types, render them as debug strings
        let left_debug = format!("{:#?}", self.left);
        let right_debug = format!("{:#?}", self.right);
        // And then diff the debug output
        printer::write_header(f)?;
        printer::write_lines(f, &left_debug, &right_debug)
    }
}

/// A comparison of two strings.
///
/// In contrast to [`Comparison`], which uses the [`core::fmt::Debug`] representation,
/// `StrComparison` uses the string values directly, resulting in multi-line output for multiline strings.
///
/// ```
/// use pretty_assertions::StrComparison;
///
/// print!("{}", StrComparison::new("foo\nbar", "foo\nbaz"));
/// ```
///
/// ## Value type bounds
///
/// Any value that can be referenced as a [`str`] via [`AsRef`] may be used:
///
/// ```
/// use pretty_assertions::StrComparison;
///
/// #[derive(PartialEq)]
/// struct MyString(String);
///
/// impl AsRef<str> for MyString {
///     fn as_ref(&self) -> &str {
///         &self.0
///     }
/// }
///
/// print!(
///     "{}",
///     StrComparison::new(
///         &MyString("foo\nbar".to_owned()),
///         &MyString("foo\nbaz".to_owned()),
///     ),
/// );
/// ```
///
/// The values may have different types, although in practice they are usually the same.
pub struct StrComparison<'a, TLeft, TRight>
where
    TLeft: ?Sized,
    TRight: ?Sized,
{
    left: &'a TLeft,
    right: &'a TRight,
}

impl<'a, TLeft, TRight> StrComparison<'a, TLeft, TRight>
where
    TLeft: AsRef<str> + ?Sized,
    TRight: AsRef<str> + ?Sized,
{
    /// Store two values to be compared in future.
    ///
    /// Expensive diffing is deferred until calling `Debug::fmt`.
    pub fn new(left: &'a TLeft, right: &'a TRight) -> StrComparison<'a, TLeft, TRight> {
        StrComparison { left, right }
    }
}

impl<'a, TLeft, TRight> Display for StrComparison<'a, TLeft, TRight>
where
    TLeft: AsRef<str> + ?Sized,
    TRight: AsRef<str> + ?Sized,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        printer::write_header(f)?;
        printer::write_lines(f, self.left.as_ref(), self.right.as_ref())
    }
}

/// Asserts that two expressions are equal to each other (using [`PartialEq`]).
///
/// On panic, this macro will print a diff derived from [`Debug`] representation of
/// each value.
///
/// This is a drop in replacement for [`core::assert_eq!`].
/// You can provide a custom panic message if desired.
///
/// # Examples
///
/// ```
/// use pretty_assertions::assert_eq;
///
/// let a = 3;
/// let b = 1 + 2;
/// assert_eq!(a, b);
///
/// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
/// ```
#[macro_export]
macro_rules! assert_eq {
    ($left:expr, $right:expr$(,)?) => ({
        $crate::assert_eq!(@ $left, $right, "", "");
    });
    ($left:expr, $right:expr, $($arg:tt)*) => ({
        $crate::assert_eq!(@ $left, $right, ": ", $($arg)+);
    });
    (@ $left:expr, $right:expr, $maybe_colon:expr, $($arg:tt)*) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    use $crate::private::CreateComparison;
                    ::core::panic!("assertion failed: `(left == right)`{}{}\
                       \n\
                       \n{}\
                       \n",
                       $maybe_colon,
                       format_args!($($arg)*),
                       (left_val, right_val).create_comparison()
                    )
                }
            }
        }
    });
}

/// Asserts that two expressions are equal to each other (using [`PartialEq`]).
///
/// On panic, this macro will print a diff derived from each value's [`str`] representation.
/// See [`StrComparison`] for further details.
///
/// This is a drop in replacement for [`core::assert_eq!`].
/// You can provide a custom panic message if desired.
///
/// # Examples
///
/// ```
/// use pretty_assertions::assert_str_eq;
///
/// let a = "foo\nbar";
/// let b = ["foo", "bar"].join("\n");
/// assert_str_eq!(a, b);
///
/// assert_str_eq!(a, b, "we are testing concatenation with {} and {}", a, b);
/// ```
#[macro_export]
macro_rules! assert_str_eq {
    ($left:expr, $right:expr$(,)?) => ({
        $crate::assert_str_eq!(@ $left, $right, "", "");
    });
    ($left:expr, $right:expr, $($arg:tt)*) => ({
        $crate::assert_str_eq!(@ $left, $right, ": ", $($arg)+);
    });
    (@ $left:expr, $right:expr, $maybe_colon:expr, $($arg:tt)*) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    ::core::panic!("assertion failed: `(left == right)`{}{}\
                       \n\
                       \n{}\
                       \n",
                       $maybe_colon,
                       format_args!($($arg)*),
                       $crate::StrComparison::new(left_val, right_val)
                    )
                }
            }
        }
    });
}

/// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
///
/// On panic, this macro will print the values of the expressions with their
/// [`Debug`] representations.
///
/// This is a drop in replacement for [`core::assert_ne!`].
/// You can provide a custom panic message if desired.
///
/// # Examples
///
/// ```
/// use pretty_assertions::assert_ne;
///
/// let a = 3;
/// let b = 2;
/// assert_ne!(a, b);
///
/// assert_ne!(a, b, "we are testing that the values are not equal");
/// ```
#[macro_export]
macro_rules! assert_ne {
    ($left:expr, $right:expr$(,)?) => ({
        $crate::assert_ne!(@ $left, $right, "", "");
    });
    ($left:expr, $right:expr, $($arg:tt)+) => ({
        $crate::assert_ne!(@ $left, $right, ": ", $($arg)+);
    });
    (@ $left:expr, $right:expr, $maybe_colon:expr, $($arg:tt)+) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    ::core::panic!("assertion failed: `(left != right)`{}{}\
                        \n\
                        \n{}:\
                        \n{:#?}\
                        \n\
                        \n",
                        $maybe_colon,
                        format_args!($($arg)+),
                        $crate::Style::new().bold().paint("Both sides"),
                        left_val
                    )
                }
            }
        }
    });
}

/// Asserts that a value matches a pattern.
///
/// On panic, this macro will print a diff derived from [`Debug`] representation of
/// the value, and a string representation of the pattern.
///
/// This is a drop in replacement for [`core::assert_matches::assert_matches!`].
/// You can provide a custom panic message if desired.
///
/// # Examples
///
/// ```
/// use pretty_assertions::assert_matches;
///
/// let a = Some(3);
/// assert_matches!(a, Some(_));
///
/// assert_matches!(a, Some(value) if value > 2, "we are testing {:?} with a pattern", a);
/// ```
///
/// # Features
///
/// Requires the `unstable` feature to be enabled.
///
/// **Please note:** implementation under the `unstable` feature may be changed between
/// patch versions without warning.
#[cfg(feature = "unstable")]
#[macro_export]
macro_rules! assert_matches {
    ($left:expr, $( $pattern:pat )|+ $( if $guard: expr )? $(,)?) => ({
        match $left {
            $( $pattern )|+ $( if $guard )? => {}
            ref left_val => {
                $crate::assert_matches!(
                    @
                    left_val,
                    ::core::stringify!($($pattern)|+ $(if $guard)?),
                    "",
                    ""
                );
            }
        }
    });
    ($left:expr, $( $pattern:pat )|+ $( if $guard: expr )?, $($arg:tt)+) => ({
        match $left {
            $( $pattern )|+ $( if $guard )? => {}
            ref left_val => {
                $crate::assert_matches!(
                    @
                    left_val,
                    ::core::stringify!($($pattern)|+ $(if $guard)?),
                    ": ",
                    $($arg)+
                );
            }
        }

    });
    (@ $left:expr, $right:expr, $maybe_colon:expr, $($arg:tt)*) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
                // Use the Display implementation to display the pattern,
                // as using Debug would add another layer of quotes to the output.
                struct Pattern<'a>(&'a str);
                impl ::core::fmt::Debug for Pattern<'_> {
                    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                        ::core::fmt::Display::fmt(self.0, f)
                    }
                }

                ::core::panic!("assertion failed: `(left matches right)`{}{}\
                   \n\
                   \n{}\
                   \n",
                   $maybe_colon,
                   format_args!($($arg)*),
                   $crate::Comparison::new(left_val, &Pattern(right_val))
                )
            }
        }
    });
}

// Not public API. Used by the expansion of this crate's assert macros.
#[doc(hidden)]
pub mod private {
    #[cfg(feature = "alloc")]
    use alloc::string::String;

    pub trait CompareAsStrByDefault: AsRef<str> {}
    impl CompareAsStrByDefault for str {}
    impl CompareAsStrByDefault for String {}
    impl<T: CompareAsStrByDefault + ?Sized> CompareAsStrByDefault for &T {}

    pub trait CreateComparison {
        type Comparison;
        fn create_comparison(self) -> Self::Comparison;
    }

    impl<'a, T, U> CreateComparison for &'a (T, U) {
        type Comparison = crate::Comparison<'a, T, U>;
        fn create_comparison(self) -> Self::Comparison {
            crate::Comparison::new(&self.0, &self.1)
        }
    }

    impl<'a, T, U> CreateComparison for (&'a T, &'a U)
    where
        T: CompareAsStrByDefault + ?Sized,
        U: CompareAsStrByDefault + ?Sized,
    {
        type Comparison = crate::StrComparison<'a, T, U>;
        fn create_comparison(self) -> Self::Comparison {
            crate::StrComparison::new(self.0, self.1)
        }
    }
}