assert-str
Macros for asserting multiline strings.
assert-str provides drop-in alternatives to assert_eq! / assert_ne! for
comparing multiline &str / String values while ignoring differences that are
usually noise: OS-specific line endings (\n vs \r\n), indentation, and other
whitespace. It is handy for comparing text generated on different platforms, or
a prettified JSON/XML/HTML value against its compact form. The left and right
operands may be different types (&str, String, &String, …).
No dependencies · no unsafe code · MSRV 1.85 (edition 2024).
Usage
Add the dependency — usually as a dev-dependency, since these are test helpers:
[]
= "0.3"
Import the macros:
use ;
use ;
use ;
// …or simply:
use *;
Macros
Each *_eq! macro asserts equality and each *_ne! macro asserts inequality
after applying a normalization. All of them treat \n and \r\n as
equivalent, and — like the standard assert_eq! — accept an optional trailing
format message.
| 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 is trimmed and blank lines are dropped. |
assert_str_trim_all_eq! / assert_str_trim_all_ne! |
All whitespace removed, anywhere in the string. |
Reusable normalization
The same normalization the macros use is also available as a plain function, so you can reuse it outside of assertions — for example to pre-process snapshots, build whitespace-insensitive hash/sort keys, or write your own comparison:
use ;
assert_eq!;
assert_eq!;
assert_eq!;
Mode is #[non_exhaustive], so more normalization modes may be added in
future releases without a breaking change.
Compatibility
assert_str_trim_all_* changed in 0.3.0: it now removes all whitespace
including within a line (matching its documented purpose). If intra-line
whitespace should stay significant, use assert_str_trim_eq! instead. See
CHANGELOG.md for details.
License
Licensed under either of Apache-2.0 or MIT at your option.