Skip to content

Commit

Permalink
Fixed an issue with sorting of keys
Browse files Browse the repository at this point in the history
  • Loading branch information
mitsuhiko committed Nov 27, 2022
1 parent 89f2c2f commit 828ef04
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/content/serialization.rs
Expand Up @@ -50,7 +50,15 @@ impl Content {
pub(crate) fn sort_maps(&mut self) {
self.walk(&mut |content| {
if let Content::Map(ref mut items) = content {
items.sort_by(|a, b| a.0.as_key().cmp(&b.0.as_key()));
// try to compare by key first, if that fails compare by the
// object value. That way some values normalize, and if we
// can't normalize we still have a stable order.
items.sort_by(|a, b| match (a.0.as_key(), b.0.as_key()) {
(Key::Other, _) | (_, Key::Other) => {
a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal)
}
(ref a, ref b) => a.cmp(b),
})
}
true
})
Expand Down
14 changes: 14 additions & 0 deletions tests/test_basic.rs
Expand Up @@ -3,6 +3,7 @@ use insta::assert_json_snapshot;
#[cfg(feature = "yaml")]
use insta::assert_yaml_snapshot;
use insta::{assert_debug_snapshot, assert_display_snapshot};
use std::collections::HashMap;
use std::fmt;

#[test]
Expand Down Expand Up @@ -89,3 +90,16 @@ fn test_u128_json() {
let x: u128 = u128::from(u64::MAX) * 2;
assert_json_snapshot!(&x, @"36893488147419103230");
}

#[test]
fn insta_sort_order() {
let mut m = HashMap::new();
m.insert((1, 3), 4);
m.insert((2, 3), 4);
m.insert((1, 4), 4);
m.insert((3, 3), 4);
m.insert((9, 3), 4);
insta::with_settings!({sort_maps =>true}, {
insta::assert_yaml_snapshot!(m);
});
}

0 comments on commit 828ef04

Please sign in to comment.