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
// Copyright © 2018-19 Qtrac Ltd. All rights reserved.

use crate::plan::counts::Counts;
use crate::plan::{diff, Plan, Test};
use crate::util::{PathBufExt, Which};
use crate::xerr;
use crate::xerror::{xerror, XError, XResult};
use approx::abs_diff_eq;
use log::{debug, error, info};
use rayon::prelude::*;
use std::borrow::Cow;
use std::env;
use std::fs::{self, File};
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use std::thread;
use std::time;

#[derive(Debug)]
enum Outcome {
    Passed,
    Failed,
    Error,
    Generated(u32),
}

impl Plan {
    /// Returns a [`Counts`](struct.Counts.html) holding the number of
    /// tests, passes, fails, and errors.
    ///
    /// If the `RETEST_GENERATE` environment variable is present _and_ set
    /// to `1`, this method calls
    /// [`generate()`](struct.Plan.html#method.generate); otherwise it
    /// calls [`retest()`](struct.Plan.html#method.retest).
    pub fn apply(&self) -> XResult<Counts> {
        let gen = match env::var("RETEST_GENERATE") {
            Ok(value) => value == "1",
            Err(_) => false,
        };
        if gen {
            self.generate()
        } else {
            self.retest()
        }
    }

    /// Returns a [`Counts`](struct.Counts.html) holding the number of
    /// tests, passes, fails, and errors.
    ///
    /// Runs all the tests in the `Plan`. For each test, providing the exit
    /// code/error level is what's expected, any test output is saved to
    /// the _actual_ path and then the original output that was generated
    /// previously in the _expected_ path is compared with the newly saved
    /// output.
    ///
    /// During retesting, logging output is produced (or not) depending on
    /// the logger you are using and the logging level you have set.
    ///
    /// All the fields in the returned [`Counts`](struct.Counts.html) are
    /// used (although some could be 0).
    pub fn retest(&self) -> XResult<Counts> {
        maybe_create_paths(&self.expected_path, &self.actual_path)?;
        let mut counts = Counts::default();
        for reply in self
            .tests
            .par_iter()
            .map(|(u, test)| self.retest_one(*u, &test))
            .collect::<Vec<_>>()
        {
            match reply {
                Ok(reply) => match reply {
                    Outcome::Passed => counts.passed += 1,
                    Outcome::Failed => counts.failed += 1,
                    Outcome::Error => counts.errors += 1,
                    Outcome::Generated(u) => xerr!(
                        "[{: >5}] internal error: generated instead \
                         of tested",
                        u
                    ),
                },
                Err(err) => {
                    counts.errors += 1;
                    error!("ERROR: {}", err);
                }
            };
            counts.total += 1;
        }
        Ok(counts)
    }

    fn retest_one(&self, u: u32, test: &Test) -> XResult<Outcome> {
        let wait = test.wait;
        let expected_filename =
            &test.output_filename(&self.expected_path, &Which::Expected);
        let actual_filename =
            &test.output_filename(&self.actual_path, &Which::Actual);
        let test = test.with_paths(
            &self.expected_path,
            &self.actual_path,
            &Which::Actual,
        );
        debug!("[{: >5}] info:  {}", u, test);
        if !actual_filename.is_empty() {
            // Delete if we can but don't worry
            if fs::remove_file(&actual_filename).is_err() {
                debug!(
                    "[{: >5}] info:  failed to delete \"{}\"",
                    u,
                    &actual_filename.display()
                );
            }
        }
        if !abs_diff_eq!(wait, 0.0) {
            if wait > 0.2 {
                debug!("[{: >5}] waiting {:.3}s before running", u, wait);
            }
            thread::sleep(time::Duration::from_millis(
                (wait.abs() * 1000.0) as u64,
            ));
        }
        let exit_code = run_test(&test)?;
        if exit_code != test.exit_code {
            error!(
                "[{: >5}] FAIL:  expected exit code {} != {}",
                u, test.exit_code, exit_code
            );
            return Ok(Outcome::Failed);
        }
        self.diff(u, &test, &expected_filename, &actual_filename)
    }

    fn diff<P: AsRef<Path>>(
        &self,
        u: u32,
        test: &Test,
        expected_filename: P,
        actual_filename: P,
    ) -> XResult<Outcome> {
        let expected_filename = expected_filename.as_ref();
        let actual_filename = actual_filename.as_ref();
        match diff::is_same(&test, &expected_filename, &actual_filename) {
            Ok(true) => {
                let name = if test.name.is_empty() {
                    "".to_string()
                } else {
                    format!(":  {}", test.name)
                };
                info!("[{: >5}] Pass{}", u, name);
                Ok(Outcome::Passed)
            }
            Ok(false) => {
                error!(
                    "[{: >5}] FAIL:  \"{}\" != \"{}\"",
                    u,
                    &expected_filename.display(),
                    &actual_filename.display()
                );
                Ok(Outcome::Failed)
            }
            Err(err) => {
                error!("[{: >5}] ERROR: {}", u, err);
                Ok(Outcome::Error)
            }
        }
    }

    /// Returns a [`Counts`](struct.Counts.html) holding the number of
    /// tests and fails.
    ///
    /// Runs all the tests in the `Plan`. For each test, any test output is
    /// saved to the _expected_ path.
    ///
    /// During generating, logging output is produced (or not) depending on
    /// the logger you are using and the logging level you have set.
    ///
    /// Only the `total` and `failed` fields in the returned
    /// [`Counts`](struct.Counts.html) are used.
    pub fn generate(&self) -> XResult<Counts> {
        maybe_create_paths(&self.expected_path, &self.actual_path)?;
        let mut counts = Counts::default();
        for reply in self
            .tests
            .par_iter()
            .map(|(u, test)| self.generate_one(*u, &test))
            .collect::<Vec<_>>()
        {
            match reply {
                Ok(reply) => match reply {
                    Outcome::Generated(_) => counts.total += 1,
                    Outcome::Failed => counts.failed += 1,
                    _ => xerr!(
                        "internal error: generated unexpected outcome"
                    ),
                },
                Err(err) => xerr!("ERROR: failed to generate: {}", err),
            }
        }
        Ok(counts)
    }

    fn generate_one(&self, u: u32, test: &Test) -> XResult<Outcome> {
        let test = test.with_paths(
            &self.expected_path,
            &self.actual_path,
            &Which::Expected,
        );
        debug!("[{: >5}] info:  {}", u, test);
        let expected_filename =
            &test.output_filename(&self.expected_path, &Which::Expected);
        if !expected_filename.is_empty() {
            if fs::remove_file(&expected_filename).is_err() {
                debug!(
                    "[{: >5}] info: failed to delete \"{}\"",
                    u,
                    &expected_filename.display()
                );
            }
        }
        let exit_code = run_test(&test)?;
        if exit_code != test.exit_code {
            error!(
                "[{: >5}] FAIL:  expected exit code {} != {}",
                u, test.exit_code, exit_code
            );
            return Ok(Outcome::Failed);
        }
        if test.will_diff() {
            info!(
                "[{: >5}] Generated: \"{}\"",
                u,
                &test
                    .output_filename(
                        &self.expected_path,
                        &Which::Expected
                    )
                    .display()
            );
        } else {
            info!("[{: >5}] Will check exit code: {}", u, test.exit_code);
        }
        Ok(Outcome::Generated(u))
    }
}

fn maybe_create_paths(
    expected_path: &Path,
    actual_path: &Path,
) -> XResult<()> {
    if !expected_path.exists() {
        fs::create_dir_all(&expected_path)?;
        info!("created \"{}\"", expected_path.display());
    }
    if !actual_path.exists() {
        fs::create_dir_all(&actual_path)?;
        info!("created \"{}\"", actual_path.display());
    }
    Ok(())
}

fn run_test(test: &Test) -> XResult<i32> {
    let mut command = Command::new(&test.app);
    command.args(&test.app_args);
    command.stderr(Stdio::null());
    if !test.stdin.is_empty() {
        command.stdin(Stdio::piped());
    }
    let capture = match &test.stdout {
        Some(path) => !path.is_empty(),
        None => false,
    };
    command.stdout(if capture { Stdio::piped() } else { Stdio::null() });
    let mut child = command.spawn().or_else(|err| {
        xerr!("Failed to run \"{}\": {}", test.app.display(), err)
    })?;
    if !test.stdin.is_empty() {
        let stdin = child.stdin.as_mut().ok_or_else(|| {
            XError::new(format!(
                "Failed to read from \"{}\"",
                test.app.display()
            ))
        })?;
        let stdin_filename = match &test.stdin_filename {
            Some(path) => path.to_string_lossy(),
            None => Cow::from(""),
        };
        stdin.write_all(&test.stdin).or_else(|err| {
            xerr!("Failed to write to \"{}\": {}", stdin_filename, err)
        })?;
    }
    let output = child.wait_with_output().or_else(|err| {
        xerr!("Failed to run \"{}\": {}", test.app.display(), err)
    })?;
    if let Some(stdout) = &test.stdout {
        let mut file = File::create(&stdout)?;
        file.write_all(&output.stdout)?;
    }
    match output.status.code() {
        Some(code) => Ok(code),
        None => Ok(-999), // Unix process terminated by signal
    }
}