Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed an issue with sorting of keys #304

Merged
merged 1 commit into from Nov 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
20 changes: 20 additions & 0 deletions 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

15 changes: 15 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,17 @@ fn test_u128_json() {
let x: u128 = u128::from(u64::MAX) * 2;
assert_json_snapshot!(&x, @"36893488147419103230");
}

#[cfg(feature = "yaml")]
#[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);
});
}