1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//! Assertions for testing.

extern crate num;

/// Assert that the distance between the absolute values of the corresponding
/// elements of two vectors is smaller than a given value.
pub fn absolute_within(x: &[f64], y: &[f64], delta: f64) {
    use num::traits::Float;

    for (&x, &y) in x.iter().zip(y.iter()) {
        if x.is_finite() && y.is_finite() {
            assert!((x.abs() - y.abs()).abs() < delta, "|{}| !~ |{}|", x, y);
        } else {
            assert!(x == y, "|{}| !~ |{}|", x, y);
        }
    }
}

/// Assert that two vectors are equal.
pub fn equal(x: &[f64], y: &[f64]) {
    for (&x, &y) in x.iter().zip(y.iter()) {
        assert_eq!(x, y);
    }
}

/// Assert that the result is unsuccessful.
pub fn error<S, E>(result: Result<S, E>) {
    match result {
        Ok(..) => assert!(false, "got an OK, expected an error"),
        Err(..) => {},
    }
}

/// Assert that the result is successful.
pub fn success<S, E>(result: Result<S, E>) {
    match result {
        Ok(..) => {},
        Err(..) => assert!(false, "got an error, expected an OK"),
    }
}

/// Assert that the distance between the corresponding elements of two vectors
/// is smaller than a given value.
pub fn within(x: &[f64], y: &[f64], delta: f64) {
    use num::traits::Float;

    for (&x, &y) in x.iter().zip(y.iter()) {
        if x.is_finite() && y.is_finite() {
            assert!((x - y).abs() < delta, "{} !~ {}", x, y);
        } else {
            assert!(x == y, "{} !~ {}", x, y);
        }
    }
}

#[cfg(test)]
mod test {
    struct Success;
    struct Failure;

    #[test]
    fn absolute_within() {
        ::absolute_within(&[1.0, 2.0, 3.0], &[-1.0, 2.0 + 1e-10, -3.0 - 1e-10], 2e-10);
    }

    #[test]
    fn equal() {
        ::equal(&[1.0, 2.0, 3.0], &[1.0, 2.0, 3.0]);
    }

    #[test]
    fn error() {
        fn work() -> Result<Success, Failure> { Err(Failure) }
        ::error(work());
    }

    #[test]
    fn success() {
        fn work() -> Result<Success, Failure> { Ok(Success) }
        ::success(work());
    }

    #[test]
    fn within() {
        ::within(&[1.0, 2.0, 3.0], &[1.0, 2.0 + 1e-10, 3.0 - 1e-10], 2e-10);
    }
}