summaryrefslogtreecommitdiffstats
path: root/ffi/tests/c-tests.rs
blob: e5af5c1ffd60cdb8c82ea36b1be8b48e04c5c11f (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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
use anyhow::{Result, Context};
use filetime;

use std::cmp::min;
use std::env::{self, var_os};
use std::ffi::OsStr;
use std::fs;
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::str::FromStr;
use std::mem::replace;

/// Hooks into Rust's test system to extract, compile and run c tests.
#[test]
fn c_doctests() -> Result<()> {
    let stderr = &mut io::stderr();

    // The location of this crate's (i.e., the ffi crate's) source.
    let manifest_dir = PathBuf::from(
        var_os("CARGO_MANIFEST_DIR")
        .as_ref()
        .expect("CARGO_MANIFEST_DIR not set"));

    let src = manifest_dir.join("src");
    let includes = vec![
        manifest_dir.join("../openpgp-ffi/include"),
        manifest_dir.join("include"),
    ];

    // The top-level directory.
    let toplevel = manifest_dir.parent().unwrap();

    // The location of the binaries.
    let target_dir = if let Some(dir) = var_os("CARGO_TARGET_DIR") {
        PathBuf::from(dir)
    } else {
        toplevel.join("target")
    };

    // The debug target.
    let debug = target_dir.join("debug");
    // Where we put our files.
    let target = target_dir.join("c-tests");
    fs::create_dir_all(&target).unwrap();

    // First of all, make sure the shared object is built.
    build_so(toplevel).unwrap();

    let mut n = 0;
    let mut passed = 0;
    for_all_rs(&src, |path| {
        for_all_tests(path, |src, lineno, name, lines, run_it| {
            n += 1;
            write!(stderr, "  test {} ... ", name)?;
            match build(&includes, &debug, &target, src, lineno, name, lines) {
                Ok(_) if ! run_it => {
                    writeln!(stderr, "ok")?;
                    passed += 1;
                },
                Ok(exe) => match run(&debug, &exe) {
                    Ok(()) => {
                        writeln!(stderr, "ok")?;
                        passed += 1;
                    },
                    Err(e) =>
                        writeln!(stderr, "{}", e)?,
                },
                Err(e) =>
                    writeln!(stderr, "{}", e)?,
            }
            Ok(())
        })
    }).unwrap();
    writeln!(stderr, "  test result: {} passed; {} failed", passed, n - passed)?;
    if n != passed {
        panic!("ffi test failures");
    }
    Ok(())
}

/// Builds the shared object.
fn build_so(base: &Path) -> Result<()> {
    let st = Command::new("cargo")
        .current_dir(base)
        .arg("build")
        .arg("--quiet")
        .arg("--package")
        .arg("sequoia-ffi")
        .status().unwrap();
    if ! st.success() {
        return Err(io::Error::new(io::ErrorKind::Other, "compilation failed")
                   .into());
    }

    Ok(())
}

/// Maps the given function `fun` over all Rust files in `src`.
fn for_all_rs<F>(src: &Path, mut fun: F)
                 -> Result<()>
    where F: FnMut(&Path) -> Result<()> {
    let mut dirs = vec![src.to_path_buf()];

    while let Some(dir) = dirs.pop() {
        for entry in fs::read_dir(dir).unwrap() {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() && path.extension() == Some(OsStr::new("rs")) {
                fun(&path)?;
            }
            if path.is_dir() {
                dirs.push(path.clone());
            }
        }
    }
    Ok(())
}

/// If this looks like an exported function, returns its name.
fn exported_function_name(line: &str) -> Option<&str> {
    if line.starts_with("pub extern \"C\" fn ")
        || line.starts_with("fn pgp_")
    {
        let fn_i = line.find("fn ")?;
        let name_start = fn_i + 3;
        (&line[name_start..]).split(|c| !is_valid_identifier(c)).next()
    } else {
        None
    }
}

fn is_valid_identifier(c: char) -> bool {
    char::is_alphanumeric(c) || c == '_'
}

/// Maps the given function `fun` over all tests found in `path`.
///
/// XXX: We need to parse the file properly with syn.
fn for_all_tests<F>(path: &Path, mut fun: F)
                 -> Result<()>
    where F: FnMut(&Path, usize, &str, Vec<String>, bool) -> Result<()> {
    let mut lineno = 0;
    let mut test_starts_at = 0;
    let f = fs::File::open(path)?;
    let reader = io::BufReader::new(f);

    let mut in_test = false;
    let mut test = Vec::new();
    let mut run = false;
    for line in reader.lines() {
        let line = line?;
        lineno += 1;

        if ! in_test {
            if (line.starts_with("/// ```c") || line.starts_with("//! ```c"))
                && ! line.contains("ignore")
            {
                run = ! line.contains("no-run");
                in_test = true;
                test_starts_at = lineno + 1;
                continue;
            }

            if let Some(name) = exported_function_name(&line) {
                if test.len()