Is there any disorderd arrays Or Do not judge the order when asserting?
Asked
Active
Viewed 113 times
2 Answers
0
What I do is sort
both sides in the assert call itself. This only works if T
implements Ord
.
let result = my_function();
my_function.sort();
let target = vec![];
target.sort();
assert_eq!(result, target);
If your datatype does not support Ord, you can use sort_by
with a FnMut that returns an instance of Ordering
.
Note that this can have issues when there isn't one specific way a vector can be sorted.

John Kugelman
- 349,597
- 67
- 533
- 578

Samathingamajig
- 11,839
- 3
- 12
- 34
0
Convert the Vec
(s) to HashBag
(s) that contains references to the items in the Vec
s. That will disregard the order of items when asserting for equality:
[dependencies]
hashbag = "0.1.9"
#[test]
fn two_vecs_equal_independent_of_item_order() {
use hashbag::HashBag;
let actual = vec![1, 2, 3, 3];
let expected_fail = vec![3, 2, 1];
assert_ne!(
actual.iter().collect::<HashBag<&i32>>(),
expected_fail.iter().collect::<HashBag<&i32>>()
);
let expected_pass = vec![3, 2, 1, 3];
assert_eq!(
actual.iter().collect::<HashBag<&i32>>(),
expected_pass.iter().collect::<HashBag<&i32>>()
);
}

Enselic
- 4,434
- 2
- 30
- 42
-
Note that this fails when a vector has multiple equivalent values – Samathingamajig Jan 09 '23 at 15:53
-
Good catch! I updated the answer to use `HashBag` instead of `HashSet`, which will solve that problem. – Enselic Jan 09 '23 at 16:08