Skip to main content

vortex_array/arrays/
assertions.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5
6use itertools::Itertools;
7
8pub fn format_indices<I: IntoIterator<Item = usize>>(indices: I) -> impl Display {
9    indices.into_iter().format(",")
10}
11
12/// Asserts that the scalar at position `$n` in array `$arr` equals `$expected`.
13///
14/// This is a convenience macro for testing that avoids verbose scalar comparison code.
15///
16/// # Example
17/// ```ignore
18/// let arr = PrimitiveArray::from_iter([1, 2, 3]);
19/// assert_nth_scalar!(arr, 0, 1);
20/// assert_nth_scalar!(arr, 1, 2);
21/// ```
22#[macro_export]
23macro_rules! assert_nth_scalar {
24    ($arr:expr, $n:expr, $expected:expr) => {
25        assert_eq!($arr.scalar_at($n).unwrap(), $expected.try_into().unwrap());
26    };
27}
28
29/// Asserts that the scalar at position `$n` in array `$arr` is null.
30///
31/// # Example
32///
33/// ```ignore
34/// let arr = PrimitiveArray::from_option_iter([Some(1), None, Some(3)]);
35/// assert_nth_scalar_null!(arr, 1);
36/// ```
37#[macro_export]
38macro_rules! assert_nth_scalar_is_null {
39    ($arr:expr, $n:expr) => {
40        assert!(
41            $arr.scalar_at($n).unwrap().is_null(),
42            "expected scalar at index {} to be null, but was {:?}",
43            $n,
44            $arr.scalar_at($n).unwrap()
45        );
46    };
47}
48
49#[macro_export]
50macro_rules! assert_arrays_eq {
51    ($left:expr, $right:expr) => {{
52       let left = $left.clone();
53       let right = $right.clone();
54       if left.dtype() != right.dtype() {
55            panic!(
56                "assertion left == right failed: arrays differ in type: {} != {}.\n  left: {}\n right: {}",
57                left.dtype(),
58                right.dtype(),
59                left.display_values(),
60                right.display_values()
61            )
62        }
63
64        if left.len() != right.len() {
65            panic!(
66                "assertion left == right failed: arrays differ in length: {} != {}.\n  left: {}\n right: {}",
67                left.len(),
68                right.len(),
69                left.display_values(),
70                right.display_values()
71            )
72        }
73        let n = left.len();
74        let mismatched_indices = (0..n)
75            .filter(|i| left.scalar_at(*i).unwrap() != right.scalar_at(*i).unwrap())
76            .collect::<Vec<_>>();
77        if mismatched_indices.len() != 0 {
78            panic!(
79                "assertion left == right failed: arrays do not match at indices: {}.\n  left: {}\n right: {}",
80                $crate::arrays::format_indices(mismatched_indices),
81                left.display_values(),
82                right.display_values()
83            )
84        }
85    }};
86}