summaryrefslogtreecommitdiff
path: root/dhall/src/tests.rs
blob: 659317f7293478bce4175eb3f8ae5490f889a74c (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#[cfg(not(test))]
use assert_eq as assert_eq_pretty;
#[cfg(test)]
use pretty_assertions::assert_eq as assert_eq_pretty;

macro_rules! assert_eq_display {
    ($left:expr, $right:expr) => {{
        match (&$left, &$right) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    panic!(
                        r#"assertion failed: `(left == right)`
 left: `{}`,
right: `{}`"#,
                        left_val, right_val
                    )
                }
            }
        }
    }};
}

/// Wrapper around string slice that makes debug output `{:?}` to print string same way as `{}`.
/// Used in different `assert*!` macros in combination with `pretty_assertions` crate to make
/// test failures to show nice diffs.
#[derive(PartialEq, Eq)]
#[doc(hidden)]
pub struct PrettyString(String);

/// Make diff to display string as multi-line string
impl std::fmt::Debug for PrettyString {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

macro_rules! assert_eq_pretty_str {
    ($left:expr, $right:expr) => {
        assert_eq_pretty!(
            PrettyString($left.to_string()),
            PrettyString($right.to_string())
        );
    };
}

use std::fs::File;
use std::io::{Read, Write};
use std::path::PathBuf;

use crate::error::{Error, Result};
use crate::syntax::binary;
use crate::{Normalized, NormalizedExpr, Parsed, Resolved};

#[allow(dead_code)]
enum Test {
    ParserSuccess(TestFile, TestFile),
    ParserFailure(TestFile),
    Printer(TestFile, TestFile),
    BinaryEncoding(TestFile, TestFile),
    BinaryDecodingSuccess(TestFile, TestFile),
    BinaryDecodingFailure(TestFile),
    ImportSuccess(TestFile, TestFile),
    ImportFailure(TestFile),
    ImportError(TestFile, TestFile),
    TypeInferenceSuccess(TestFile, TestFile),
    TypeInferenceFailure(TestFile),
    TypeError(TestFile, TestFile),
    Normalization(TestFile, TestFile),
    AlphaNormalization(TestFile, TestFile),
}

#[allow(dead_code)]
enum TestFile {
    Source(&'static str),
    Binary(&'static str),
    UI(&'static str),
}

impl TestFile {
    pub fn path(&self) -> PathBuf {
        match self {
            TestFile::Source(path)
            | TestFile::Binary(path)
            | TestFile::UI(path) => PathBuf::from(path),
        }
    }

    /// Parse the target file
    pub fn parse(&self) -> Result<Parsed> {
        match self {
            TestFile::Source(_) => Parsed::parse_file(&self.path()),
            TestFile::Binary(_) => Parsed::parse_binary_file(&self.path()),
            TestFile::UI(_) => panic!("Can't parse a UI test file"),
        }
    }
    /// Parse and resolve the target file
    pub fn resolve(&self) -> Result<Resolved> {
        Ok(self.parse()?.resolve()?)
    }
    /// Parse, resolve, tck and normalize the target file
    pub fn normalize(&self) -> Result<Normalized> {
        Ok(self.resolve()?.typecheck()?.normalize())
    }

    /// Check that the provided expression matches the file contents.
    pub fn compare(&self, expr: impl Into<NormalizedExpr>) -> Result<()> {
        let expr = expr.into();
        let expected = self.parse()?.to_expr();
        assert_eq_display!(expr, expected);
        Ok(())
    }
    /// Check that the provided expression matches the file contents.
    pub fn compare_debug(&self, expr: impl Into<NormalizedExpr>) -> Result<()> {
        let expr = expr.into();
        let expected = self.parse()?.to_expr();
        assert_eq_pretty!(expr, expected);
        Ok(())
    }
    /// Check that the provided expression matches the file contents.
    pub fn compare_binary(
        &self,
        expr: impl Into<NormalizedExpr>,
    ) -> Result<()> {
        match self {
            TestFile::Binary(_) => {}
            _ => panic!("This is not a binary file"),
        }
        let expr_data = binary::encode(&expr.into())?;
        let expected_data = {
            let mut data = Vec::new();
            File::open(&self.path())?.read_to_end(&mut data)?;
            data
        };

        // Compare bit-by-bit
        if expr_data != expected_data {
            use serde_cbor::de::from_slice;
            use serde_cbor::value::Value;
            // use std::io::Write;
            // File::create(&expected)?.write_all(&expr_data)?;
            // Pretty-print difference
            assert_eq_pretty!(
                from_slice::<Value>(&expr_data).unwrap(),
                from_slice::<Value>(&expected_data).unwrap()
            );
            // If difference was not visible in the cbor::Value, compare normally.
            assert_eq!(expr_data, expected_data);
        }
        Ok(())
    }
}

#[allow(dead_code)]
fn run_test_stringy_error(test: Test) -> std::result::Result<(), String> {
    run_test(test).map_err(|e| e.to_string())?;
    Ok(())
}

fn run_test(test: Test) -> Result<()> {
    use self::Test::*;
    match test {
        ParserSuccess(expr, expected) => {
            let expr = expr.parse()?;
            // This exercices both parsing and binary decoding
            expected.compare_debug(expr)?;
        }
        ParserFailure(expr) => {
            let err = expr.parse().unwrap_err();
            match &err {
                Error::Parse(_) => {}
                Error::IO(e) if e.kind() == std::io::ErrorKind::InvalidData => {
                }
                e => panic!("Expected parse error, got: {:?}", e),
            }
        }
        BinaryEncoding(expr, expected) => {
            let expr = expr.parse()?;
            expected.compare_binary(expr)?;
        }
        BinaryDecodingSuccess(expr, expected) => {
            let expr = expr.parse()?;
            expected.compare_debug(expr)?;
        }
        BinaryDecodingFailure(expr) => {
            expr.parse().unwrap_err();
        }
        Printer(expr, _) => {
            let expected = expr.parse()?;
            // Round-trip pretty-printer
            let expr: Parsed = Parsed::parse_str(&expected.to_string())?;
            assert_eq!(expr, expected);
        }
        ImportSuccess(expr, expected) => {
            let expr = expr.normalize()?;
            expected.compare(expr)?;
        }
        ImportFailure(expr) => {
            expr.parse()?.resolve().unwrap_err();
        }
        // Checks the output of the type error against a text file. If the text file doesn't exist,
        // we instead write to it the output we got. This makes it easy to update those files: just
        // `rm -r dhall/tests/type-errors` and run the tests again.
        ImportError(expr, expected) => {
            let base_path = expected.path();
            let error_file_path =
                PathBuf::from("tests/errors/import/").join(base_path);

            let err: Error = expr.parse()?.resolve().unwrap_err().into();
            if error_file_path.is_file() {
                let expected_msg = std::fs::read_to_string(error_file_path)?;
                let msg = format!("{}\n", err);
                assert_eq_pretty_str!(msg, expected_msg);
            } else {
                std::fs::create_dir_all(error_file_path.parent().unwrap())?;
                let mut file = File::create(error_file_path)?;
                writeln!(file, "{}", err)?;
            }
        }
        TypeInferenceSuccess(expr, expected) => {
            let ty = expr.resolve()?.typecheck()?.get_type()?;
            expected.compare(ty)?;
        }
        TypeInferenceFailure(expr) => {
            expr.resolve()?.typecheck().unwrap_err();
        }
        // Checks the output of the type error against a text file. If the text file doesn't exist,
        // we instead write to it the output we got. This makes it easy to update those files: just
        // `rm -r dhall/tests/type-errors` and run the tests again.
        TypeError(expr, expected) => {
            let base_path = expected.path();
            let error_file_path =
                PathBuf::from("tests/type-errors/").join(base_path);

            let err: Error = expr.resolve()?.typecheck().unwrap_err().into();

            if error_file_path.is_file() {
                let expected_msg = std::fs::read_to_string(error_file_path)?;
                let msg = format!("{}\n", err);
                assert_eq_pretty_str!(msg, expected_msg);
            } else {
                std::fs::create_dir_all(error_file_path.parent().unwrap())?;
                let mut file = File::create(error_file_path)?;
                writeln!(file, "{}", err)?;
            }
        }
        Normalization(expr, expected) => {
            let expr = expr.normalize()?;
            expected.compare(expr)?;
        }
        AlphaNormalization(expr, expected) => {
            let expr = expr.normalize()?.to_expr_alpha();
            expected.compare(expr)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod spec {
    macro_rules! make_spec_test {
        ($type:expr, $name:ident) => {
            #[test]
            #[allow(non_snake_case)]
            fn $name() {
                use crate::tests::Test::*;
                use crate::tests::*;
                match run_test_stringy_error($type) {
                    Ok(_) => {}
                    Err(s) => panic!(s),
                }
            }
        };
    }

    // See build.rs
    include!(concat!(env!("OUT_DIR"), "/spec_tests.rs"));
}