From 3b45c4ccc3b654d8a25254a56db131ad38755a72 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Sun, 27 Nov 2022 23:49:27 +0100 Subject: [PATCH] Fixed an issue with sorting of keys --- src/content/serialization.rs | 10 +++++++++- .../test_basic__insta_sort_order.snap | 20 +++++++++++++++++++ tests/test_basic.rs | 14 +++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 tests/snapshots/test_basic__insta_sort_order.snap diff --git a/src/content/serialization.rs b/src/content/serialization.rs index e28e138f..cf025b8d 100644 --- a/src/content/serialization.rs +++ b/src/content/serialization.rs @@ -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 }) diff --git a/tests/snapshots/test_basic__insta_sort_order.snap b/tests/snapshots/test_basic__insta_sort_order.snap new file mode 100644 index 00000000..472d1d7d --- /dev/null +++ b/tests/snapshots/test_basic__insta_sort_order.snap @@ -0,0 +1,20 @@ +--- +source: tests/test_basic.rs +expression: m +--- +? - 1 + - 3 +: 4 +? - 1 + - 4 +: 4 +? - 2 + - 3 +: 4 +? - 3 + - 3 +: 4 +? - 9 + - 3 +: 4 + diff --git a/tests/test_basic.rs b/tests/test_basic.rs index 2448cd48..cb699538 100644 --- a/tests/test_basic.rs +++ b/tests/test_basic.rs @@ -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] @@ -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); + }); +}