Crate similar_asserts

source ·
Expand description

similar-asserts is a crate that enhances the default assertion experience by using similar for diffing. On failed assertions it renders out a colorized diff to the terminal.

It comes with a handful of macros to replace std::assert_eq! with:


use similar_asserts::assert_eq;
assert_eq!((1..3).collect::<Vec<_>>(), vec![1, 2]);

Optionally the assertion macros also let you “name” the left and right side which will produce slightly more explicit output:

use similar_asserts::assert_eq;
assert_eq!(expected: vec![1, 2], actual: (1..3).collect::<Vec<_>>());

Feature Flags

  • unicode enable improved character matching (enabled by default)
  • serde turns on support for serde.

Faster Builds

This crate works best if you add it as dev-dependency only. To make your code still compile you can use conditional uses that override the default uses for the assert_eq! macro from the stdlib:

use similar_asserts::assert_eq;

Since similar_asserts uses the similar library for diffing you can also enable optimziation for them in all build types for quicker diffing. Add this to your Cargo.toml:

opt-level = 3

String Truncation

By default the assertion only shows 200 characters. This can be changed with the SIMILAR_ASSERTS_MAX_STRING_LENGTH environment variable. Setting it to 0 disables all truncation, otherwise it sets the maximum number of characters before truncation kicks in.

Manual Diff Printing

If you want to build your own comparison macros and you need a quick and simple way to render diffs, you can use the SimpleDiff type and display it:

use similar_asserts::SimpleDiff;
panic!("Not equal\n\n{}", SimpleDiff::from_str("a\nb\n", "b\nb\n", "left", "right"));