assert-str 0.3.0

Macros for asserting multiline strings
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Macros for asserting multiline [`String`] and [`&str`] values.
//!
//! The API mirrors the standard library's [`assert_eq!`] / [`assert_ne!`], but
//! before comparing, both operands are normalized so that differences which are
//! usually noise get ignored. Every macro treats `\n` and `\r\n` as equivalent;
//! the `trim` and `trim_all` variants additionally normalize whitespace. The
//! left and right operands may be different types (`&str`, [`String`],
//! `&String`, …).
//!
//! # Macros
//!
//! Each `*_eq!` asserts equality and each `*_ne!` asserts inequality after
//! applying the normalization below. All accept an optional trailing format
//! message, like [`assert_eq!`].
//!
//! | Macros | Normalization applied before comparing |
//! | ------ | --------------------------------------- |
//! | [`assert_str_eq!`] / [`assert_str_ne!`] | Line endings only (`\n` ≡ `\r\n`). |
//! | [`assert_str_trim_eq!`] / [`assert_str_trim_ne!`] | Line endings, plus each line trimmed and blank lines dropped. |
//! | [`assert_str_trim_all_eq!`] / [`assert_str_trim_all_ne!`] | All whitespace removed, anywhere in the string. |
//!
//! The same normalization is available directly via [`normalize`] and [`Mode`]
//! for reuse outside of assertions.
//!
//! This crate has no dependencies and contains no `unsafe` code
//! (`#![forbid(unsafe_code)]`).
//!
//! [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
//! [`&str`]: https://doc.rust-lang.org/std/primitive.str.html
#![forbid(unsafe_code)]

/// Normalization strategy shared by all of the assertion macros.
///
/// It is exposed so the exact same normalization the macros use can be reused
/// outside of assertions -- for example to pre-process snapshots, build
/// whitespace-insensitive hash/sort keys, or write your own comparison via
/// [`normalize`].
///
/// This enum is `#[non_exhaustive]`: additional modes may be added in future
/// releases without a breaking change.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Mode {
    /// Compare line by line, treating `\n` and `\r\n` as equivalent. A single
    /// trailing newline is ignored (a consequence of [`str::lines`]).
    Lines,
    /// Like [`Mode::Lines`], but additionally trims each line and drops empty
    /// lines.
    Trim,
    /// Removes **all** whitespace anywhere in the string (spaces, tabs, and
    /// line breaks). Useful for comparing minified and pretty-printed formats.
    TrimAll,
}

/// Normalizes `s` according to `mode`, returning the canonical form that the
/// assertion macros compare.
///
/// # Examples
///
/// ```
/// use assert_str::{normalize, Mode};
///
/// assert_eq!(normalize("a\r\nb", Mode::Lines), "a\nb");
/// assert_eq!(normalize("  a \n\n b ", Mode::Trim), "a\nb");
/// assert_eq!(normalize("a b\nc", Mode::TrimAll), "abc");
/// ```
pub fn normalize(s: &str, mode: Mode) -> String {
    match mode {
        Mode::Lines => s.lines().collect::<Vec<_>>().join("\n"),
        Mode::Trim => s
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .collect::<Vec<_>>()
            .join("\n"),
        Mode::TrimAll => s.split_whitespace().collect(),
    }
}

/// Implementation detail shared by the assertion macros. Not part of the
/// public API -- use the macros instead.
///
/// It is `pub` only so the exported macros can reach it as
/// `$crate::assert_str_impl`; `#[track_caller]` keeps panics pointing at the
/// call site rather than at this crate.
#[doc(hidden)]
#[track_caller]
pub fn assert_str_impl(
    left: impl AsRef<str>,
    right: impl AsRef<str>,
    mode: Mode,
    negated: bool,
    args: Option<core::fmt::Arguments<'_>>,
) {
    let left = normalize(left.as_ref(), mode);
    let right = normalize(right.as_ref(), mode);

    // `negated` selects the failing condition: `assert_str_eq!` fails when the
    // normalized forms differ, `assert_str_ne!` fails when they are equal.
    if (left == right) == negated {
        let op = if negated { "!=" } else { "==" };
        match args {
            Some(args) => panic!(
                "assertion failed: `(left {op} right)`\n  left: `{left}`,\n right: `{right}`: {args}"
            ),
            None => panic!(
                "assertion failed: `(left {op} right)`\n  left: `{left}`,\n right: `{right}`"
            ),
        }
    }
}

/// Asserts that multiline strings([`&str`] or [`String`]) are identical. It
/// ignores different new line characters for different OSes: `\n` or `\r\n`.
///
/// # Examples
///
/// Test on equality of two strings generated on different OSes:
///
/// ```
/// use assert_str::assert_str_eq;
/// assert_str_eq!("This string\nEnd", "This string\r\nEnd", "Responses should be equal");
/// ```
///
/// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
/// [`&str`]: https://doc.rust-lang.org/std/primitive.str.html
#[macro_export]
macro_rules! assert_str_eq {
    ($left:expr, $right:expr $(,)?) => {
        $crate::assert_str_impl(&$left, &$right, $crate::Mode::Lines, false, ::core::option::Option::None)
    };
    ($left:expr, $right:expr, $($arg:tt)+) => {
        $crate::assert_str_impl(
            &$left,
            &$right,
            $crate::Mode::Lines,
            false,
            ::core::option::Option::Some(::core::format_args!($($arg)+)),
        )
    };
}

/// Asserts that multiline strings([`&str`] or [`String`]) are not identical. It
/// ignores different new line characters for different OSes: `\n` or `\r\n`.
///
/// # Examples
///
/// Test on inequality of two strings generated on different OSes:
///
/// ```
/// use assert_str::assert_str_ne;
/// assert_str_ne!("This string\nEnd", "This string\r\nFinalEnd", "Responses should not be equal");
/// ```
///
/// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
/// [`&str`]: https://doc.rust-lang.org/std/primitive.str.html
#[macro_export]
macro_rules! assert_str_ne {
    ($left:expr, $right:expr $(,)?) => {
        $crate::assert_str_impl(&$left, &$right, $crate::Mode::Lines, true, ::core::option::Option::None)
    };
    ($left:expr, $right:expr, $($arg:tt)+) => {
        $crate::assert_str_impl(
            &$left,
            &$right,
            $crate::Mode::Lines,
            true,
            ::core::option::Option::Some(::core::format_args!($($arg)+)),
        )
    };
}

/// Asserts that multiline strings([`&str`] or [`String`]) are identical when
/// every line is trimmed and empty lines are removed. It ignores different
/// new line characters for different OSes: `\n` or `\r\n`.
///
/// # Examples
///
/// Test on equality of two trimmed strings generated on different OSes:
///
/// ```
/// use assert_str::assert_str_trim_eq;
/// assert_str_trim_eq!("<html>\t \n\t<head> \n\t</head></html>",
///     "<html>\r\n<head>\r\n</head></html>", "Responses should be equal");
/// ```
///
/// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
/// [`&str`]: https://doc.rust-lang.org/std/primitive.str.html
#[macro_export]
macro_rules! assert_str_trim_eq {
    ($left:expr, $right:expr $(,)?) => {
        $crate::assert_str_impl(&$left, &$right, $crate::Mode::Trim, false, ::core::option::Option::None)
    };
    ($left:expr, $right:expr, $($arg:tt)+) => {
        $crate::assert_str_impl(
            &$left,
            &$right,
            $crate::Mode::Trim,
            false,
            ::core::option::Option::Some(::core::format_args!($($arg)+)),
        )
    };
}

/// Asserts that multiline strings([`&str`] or [`String`]) are not identical
/// when every line is trimmed and empty lines are removed. It ignores different
/// new line characters for different OSes: `\n` or `\r\n`.
///
/// # Examples
///
/// Test on inequality of two trimmed strings:
///
/// ```
/// use assert_str::assert_str_trim_ne;
/// assert_str_trim_ne!("<html>\t \n\t<head> \n\t</head></html>",
///     "<HTML><head></head></html>", "Responses should not be equal");
/// ```
///
/// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
/// [`&str`]: https://doc.rust-lang.org/std/primitive.str.html
#[macro_export]
macro_rules! assert_str_trim_ne {
    ($left:expr, $right:expr $(,)?) => {
        $crate::assert_str_impl(&$left, &$right, $crate::Mode::Trim, true, ::core::option::Option::None)
    };
    ($left:expr, $right:expr, $($arg:tt)+) => {
        $crate::assert_str_impl(
            &$left,
            &$right,
            $crate::Mode::Trim,
            true,
            ::core::option::Option::Some(::core::format_args!($($arg)+)),
        )
    };
}

/// Asserts that multiline strings([`&str`] or [`String`]) are identical after
/// removing **all** whitespace (spaces, tabs, and line breaks, anywhere in the
/// string). Useful for comparing minified and pretty-printed formats.
///
/// # Examples
///
/// Test on equality of two strings ignoring all whitespace:
///
/// ```
/// use assert_str::assert_str_trim_all_eq;
/// assert_str_trim_all_eq!("<html>\t \n\t<head> \n\t</head></html>",
///     "<html><head></head></html>", "Responses should be equal");
/// ```
///
/// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
/// [`&str`]: https://doc.rust-lang.org/std/primitive.str.html
#[macro_export]
macro_rules! assert_str_trim_all_eq {
    ($left:expr, $right:expr $(,)?) => {
        $crate::assert_str_impl(&$left, &$right, $crate::Mode::TrimAll, false, ::core::option::Option::None)
    };
    ($left:expr, $right:expr, $($arg:tt)+) => {
        $crate::assert_str_impl(
            &$left,
            &$right,
            $crate::Mode::TrimAll,
            false,
            ::core::option::Option::Some(::core::format_args!($($arg)+)),
        )
    };
}

/// Asserts that multiline strings([`&str`] or [`String`]) are not identical after
/// removing **all** whitespace (spaces, tabs, and line breaks, anywhere in the
/// string). Useful for comparing minified and pretty-printed formats.
///
/// # Examples
///
/// Test on inequality of two strings ignoring all whitespace:
///
/// ```
/// use assert_str::assert_str_trim_all_ne;
/// assert_str_trim_all_ne!("<html>\t \n\t<head> \n\t</head></html>",
///     "<HTML><head></head></html>", "Responses should not be equal");
/// ```
///
/// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
/// [`&str`]: https://doc.rust-lang.org/std/primitive.str.html
#[macro_export]
macro_rules! assert_str_trim_all_ne {
    ($left:expr, $right:expr $(,)?) => {
        $crate::assert_str_impl(&$left, &$right, $crate::Mode::TrimAll, true, ::core::option::Option::None)
    };
    ($left:expr, $right:expr, $($arg:tt)+) => {
        $crate::assert_str_impl(
            &$left,
            &$right,
            $crate::Mode::TrimAll,
            true,
            ::core::option::Option::Some(::core::format_args!($($arg)+)),
        )
    };
}

#[cfg(test)]
mod tests {
    // Several tests pass `.to_owned()` values on purpose: they exercise that the
    // macros accept owned `String`s as well as `&str`/`&String`. That is part of
    // the contract, so the conversions are intentional rather than redundant.
    #![allow(clippy::unnecessary_to_owned)]

    #[test]
    fn cross_str_equal_simple() {
        assert_str_eq!("Line\nLine2", "Line\r\nLine2");
        assert_str_eq!("Line\nLine2".to_owned(), "Line\r\nLine2");
        assert_str_eq!("Line\nLine2", "Line\r\nLine2".to_owned());
        assert_str_eq!("Line\nLine2".to_owned(), "Line\r\nLine2".to_owned());
        assert_str_eq!("Line\nLine2", "Line\r\nLine2",);
    }

    #[test]
    fn cross_str_equal_message() {
        assert_str_eq!("Line\nLine2".to_owned(), "Line\r\nLine2", "Message");
        assert_str_eq!("Line\nLine2", "Line\r\nLine2".to_owned(), "Message");
        assert_str_eq!("L\nLine2".to_owned(), "L\r\nLine2".to_owned(), "Message");
        assert_str_eq!("Line\nLine2", "Line\r\nLine2", "Message");
    }

    #[test]
    fn cross_str_not_equal_simple() {
        assert_str_ne!("Line\nLine2", "Line\r\nLine");
        assert_str_ne!("Line\nLine2".to_owned(), "Line\r\nLine");
        assert_str_ne!("Line\nLine2", "Line\r\nLine".to_owned());
        assert_str_ne!("Line\nLine2", "Line\r\nLine",);
    }

    #[test]
    fn cross_str_not_equal_message() {
        assert_str_ne!("Line\nLine2".to_owned(), "Line\r\nLine", "Message");
        assert_str_ne!("Line\nLine2", "Line\r\nLine".to_owned(), "Message");
        assert_str_ne!("L\nLine2".to_owned(), "L\r\nLine".to_owned(), "Message");
        assert_str_ne!("Line\nLine2", "Line\r\nLine", "Message");
    }

    #[test]
    fn cross_str_trim_equal() {
        let left = "String  \n Line ".to_owned();
        let right = "String\r\nLine".to_owned();
        assert_str_trim_eq!(left, right);
        assert_str_trim_eq!(&left, right);
        assert_str_trim_eq!(left, &right);
        assert_str_trim_eq!(&left, &right);
        assert_str_trim_eq!(left, right,);
    }

    #[test]
    fn cross_str_trim_equal_message() {
        let left = "String  \n Line ".to_owned();
        let right = "String\r\nLine".to_owned();
        assert_str_trim_eq!(&left, right, "Message");
        assert_str_trim_eq!(left, &right, "Message");
        assert_str_trim_eq!(left, right, "Message");
        assert_str_trim_eq!(&left, &right, "Message");
    }

    #[test]
    fn cross_str_trim_not_equal() {
        let left = "String  \n Line ".to_owned();
        let right = "String\r\n12".to_owned();
        assert_str_trim_ne!(left, right);
        assert_str_trim_ne!(&left, right);
        assert_str_trim_ne!(left, &right);
        assert_str_trim_ne!(&left, &right);
        assert_str_trim_ne!(left, right,);
    }

    #[test]
    fn cross_str_trim_not_equal_message() {
        let left = "String  \n Line ".to_owned();
        let right = "String\r\n12".to_owned();
        assert_str_trim_ne!(left, right, "Message");
        assert_str_trim_ne!(&left, right, "Message");
        assert_str_trim_ne!(left, &right, "Message");
        assert_str_trim_ne!(&left, &right, "Message");
    }

    #[test]
    fn cross_str_trim_all_equal() {
        let left = "String  \n Line ".to_owned();
        let right = "String\r\nLine".to_owned();
        assert_str_trim_all_eq!(left, right);
        assert_str_trim_all_eq!(&left, right);
        assert_str_trim_all_eq!(left, &right);
        assert_str_trim_all_eq!(&left, &right);
        assert_str_trim_all_eq!(left, right,);
    }

    #[test]
    fn cross_str_trim_all_equal_message() {
        let left = "String  \n Line ".to_owned();
        let right = "StringLine".to_owned();
        assert_str_trim_all_eq!(&left, right, "Message");
        assert_str_trim_all_eq!(left, &right, "Message");
        assert_str_trim_all_eq!(left, right, "Message");
        assert_str_trim_all_eq!(&left, &right, "Message");
    }

    #[test]
    fn cross_str_trim_all_not_equal() {
        let left = "String  \n Line ".to_owned();
        let right = "Stringline".to_owned();
        assert_str_trim_all_ne!(left, right);
        assert_str_trim_all_ne!(&left, right);
        assert_str_trim_all_ne!(left, &right);
        assert_str_trim_all_ne!(&left, &right);
        assert_str_trim_all_ne!(left, right,);
    }

    #[test]
    fn cross_str_trim_all_not_equal_message() {
        let left = "String  \n Line ".to_owned();
        let right = "String12".to_owned();
        assert_str_trim_all_ne!(left, right, "Message");
        assert_str_trim_all_ne!(&left, right, "Message");
        assert_str_trim_all_ne!(left, &right, "Message");
        assert_str_trim_all_ne!(&left, &right, "Message");
    }

    // Regression tests for the `trim_all` semantics bugs.
    //
    // `trim_all` must remove ALL whitespace (its documented contract: "removes all
    // whitespace including between tags"). Previously the 2-arg and trailing-comma
    // arms used `trim_eq` semantics (line-based, internal whitespace preserved) and
    // the trailing-comma arm even delegated to the wrong macro, so these inputs --
    // which differ only by internal whitespace -- were wrongly reported unequal.
    #[test]
    fn trim_all_eq_ignores_internal_whitespace() {
        assert_str_trim_all_eq!("a b", "ab");
        assert_str_trim_all_eq!("a b", "ab",);
        assert_str_trim_all_eq!("a b", "ab", "internal whitespace must be ignored");
    }

    // `trim_all_ne` must use `trim_all` semantics on every arm too (the trailing-comma
    // arm previously delegated to `assert_str_trim_ne!`).
    #[test]
    fn trim_all_ne_uses_trim_all_semantics() {
        assert_str_trim_all_ne!("abc", "x y z");
        assert_str_trim_all_ne!("abc", "x y z",);
        assert_str_trim_all_ne!("abc", "x y z", "content differs after removing whitespace");
    }

    // Failure paths: verify each macro panics when the assertion is violated and
    // that the panic message keeps the documented format on every arm.
    #[test]
    #[should_panic(expected = "assertion failed: `(left == right)`")]
    fn eq_panics_when_different() {
        assert_str_eq!("a", "b");
    }

    #[test]
    #[should_panic(expected = " right: `b`: custom 42")]
    fn eq_panics_with_custom_message() {
        assert_str_eq!("a", "b", "custom {}", 42);
    }

    #[test]
    #[should_panic(expected = "assertion failed: `(left != right)`")]
    fn ne_panics_when_equal() {
        assert_str_ne!("a\nb", "a\r\nb");
    }

    #[test]
    #[should_panic(expected = "assertion failed: `(left == right)`")]
    fn trim_eq_panics_when_different() {
        assert_str_trim_eq!(" a \n b ", "a\nc");
    }

    // Regression (needs `should_panic`, so it could not live in the bug-fix PR):
    // the trailing-comma `trim_all_ne` arm used to delegate to `assert_str_trim_ne!`
    // and would NOT panic here. With correct `trim_all` semantics `"a b"` and `"ab"`
    // are equal, so `ne` must panic.
    #[test]
    #[should_panic(expected = "assertion failed: `(left != right)`")]
    fn trim_all_ne_trailing_comma_panics_on_whitespace_only_difference() {
        assert_str_trim_all_ne!("a b", "ab",);
    }

    /// Direct unit tests for the public [`normalize`](crate::normalize) function.
    mod normalize_fn {
        use crate::{Mode, normalize};

        #[test]
        fn lines_treats_lf_and_crlf_as_equal() {
            assert_eq!(normalize("a\r\nb", Mode::Lines), "a\nb");
            assert_eq!(normalize("a\nb", Mode::Lines), "a\nb");
        }

        #[test]
        fn lines_absorbs_a_single_trailing_newline() {
            assert_eq!(normalize("a\nb\n", Mode::Lines), "a\nb");
            assert_eq!(normalize("a\nb", Mode::Lines), "a\nb");
        }

        #[test]
        fn trim_strips_line_edges_and_drops_blank_lines() {
            assert_eq!(normalize("  a  \n\n\t b \t", Mode::Trim), "a\nb");
        }

        #[test]
        fn trim_all_removes_every_whitespace_run() {
            assert_eq!(normalize("a b\tc\n d ", Mode::TrimAll), "abcd");
        }

        #[test]
        fn empty_input_normalizes_to_empty() {
            assert_eq!(normalize("", Mode::Lines), "");
            assert_eq!(normalize("", Mode::Trim), "");
            assert_eq!(normalize("", Mode::TrimAll), "");
        }
    }

    /// Characterization tests documenting current normalization behaviour on
    /// tricky Unicode / whitespace inputs. These pin down *what the crate does
    /// today* (not necessarily what it should ideally do) so any future change
    /// is a deliberate one.
    mod behaviour_edge_cases {
        use crate::{Mode, normalize};

        // `str::lines()` only splits on `\n` and `\r\n`. A classic-Mac bare `\r`
        // is therefore NOT treated as a line break and is preserved.
        #[test]
        fn bare_carriage_return_is_not_a_line_break() {
            assert_eq!(normalize("a\rb", Mode::Lines), "a\rb");
        }

        // Unicode LINE SEPARATOR (U+2028) is likewise not split by `lines()`.
        #[test]
        fn unicode_line_separator_is_not_split_by_lines() {
            assert_eq!(normalize("a\u{2028}b", Mode::Lines), "a\u{2028}b");
        }

        // A byte-order mark is not whitespace, so no mode strips it.
        #[test]
        fn byte_order_mark_is_preserved() {
            assert_eq!(normalize("\u{feff}hi", Mode::TrimAll), "\u{feff}hi");
        }

        // `trim`/`split_whitespace` use the full Unicode `White_Space` set, so a
        // non-breaking space IS treated as whitespace and removed by `TrimAll`.
        #[test]
        fn non_breaking_space_is_whitespace() {
            assert_eq!(normalize("a\u{a0}b", Mode::TrimAll), "ab");
        }

        // A zero-width space is NOT `White_Space`, so it survives normalization.
        #[test]
        fn zero_width_space_is_preserved() {
            assert_eq!(normalize("a\u{200b}b", Mode::TrimAll), "a\u{200b}b");
        }
    }
}