Debian Codegraph @

src/assertions/equal.rs

raw symbols SCIP
1 use crate::string_diff::colored_diff;
2 use colored::*;
3
4 /// Trait used to turn types into a string we can then diff to show pretty
5 /// assertions. This allows customizations for certain types to make the
6 /// generated strings more human readable.
7 pub trait FormattableForComparison {
8 fn format(&self) -> String;
9 }
10
11 #[cfg(not(feature = "custom_comparison_formatters"))]
12 mod specialization {
13 use super::FormattableForComparison;
14 use std::fmt::Debug;
15
16 impl<T> FormattableForComparison for T
17 where
18 T: Debug,
19 {
20 fn format(&self) -> String {
21 format!("{:#?}", self)
22 }
23 }
24 }
25
26 #[cfg(feature = "custom_comparison_formatters")]
27 mod specialization {
28 use super::FormattableForComparison;
29 use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
30 use std::fmt::Debug;
31
32 impl<T> FormattableForComparison for T
33 where
34 T: Debug,
35 {
36 default fn format(&self) -> String {
37 format!("{:#?}", self)
38 }
39 }
40
41 /// Specialize for HashMaps if the key is `Ord` - doing a diff with
42 /// sorted keys will highlight only the values that have changed
43 /// rather than showing ordering differences.
44 impl<K, V> FormattableForComparison for &HashMap<K, V>
45 where
46 K: Debug + Ord,
47 V: Debug,
48 {
49 fn format(&self) -> String {
50 let sorted = self.iter().collect::<BTreeMap<_, _>>();
51 format!("{:#?}", sorted)
52 }
53 }
54
55 /// Specialize for HashSets if the key is `Ord` - doing a diff with
56 /// sorted keys will highlight only the values that have changed
57 /// rather than showing ordering differences.
58 impl<T, S> FormattableForComparison for &HashSet<T, S>
59 where
60 T: Debug + Ord,
61 {
62 fn format(&self) -> String {
63 let sorted = self.iter().collect::<BTreeSet<_>>();
64 format!("{:#?}", sorted)
65 }
66 }
67 }
68
69 pub fn assert_equal<
70 T1: FormattableForComparison + PartialEq,
71 T2: FormattableForComparison + PartialEq,
72 >(
73 left: T1,
74 right: T2,
75 fail: bool,
76 ) -> Option<String> {
77 if fail {
78 let diff_string = colored_diff(&left.format(), &right.format())
79 .unwrap_or_else(|| "no visual difference between values".to_string());
80
81 let message = format!(
82 "
83 Expected `{left_desc}` to equal `{right_desc}`:
84 {diff_string}",
85 left_desc = "Left".red(),
86 right_desc = "Right".green(),
87 diff_string = &diff_string
88 );
89
90 Some(message)
91 } else {
92 None
93 }
94 }