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
use clap::arg_enum;
use colored::*;
use diff;
use failure::{bail, Error};
use failure_derive::Fail;
use itertools::*;
use junit_report::{Duration, Report, TestCase, TestSuite};
use serde::{Deserialize, Serialize};
use serde_json as json;
use std::path::PathBuf;
use std::process::Command;
use std::str::from_utf8;
use std::time;
use termize;

const PASSED: &str = "TEST RUN PASSED";
const FAILED: &str = "TEST RUN FAILED";
const ARROW_DOWN: char = '▼';
const ARROW_UP: char = '▲';

#[derive(Debug, Fail)]
enum NixTestError {
    #[fail(display = "There was a problem running your nix tests.\n\n    {}", msg)]
    Running { msg: String },
}

/// Evaluates a nix file containing test expressions.
/// This uses `nix-instantiate --eval --strict` underthehood.
pub fn run(test_file: PathBuf) -> Result<TestResult, Error> {
    let run_test_nix = include_str!("./runTest.nix");
    let out = Command::new("sh")
        .arg("-c")
        .arg(format!(
            "nix-instantiate \
             --json --eval --strict \
             -E '{run_test_nix}' \
             --arg testFile {test_file:#?}",
            test_file = test_file.canonicalize()?,
            run_test_nix = run_test_nix
        ))
        .output()
        .map_err(|msg| NixTestError::Running {
            msg: msg.to_string(),
        })?;
    if out.status.success() {
        Ok(json::from_str(from_utf8(&out.stdout)?)?)
    } else {
        bail!(NixTestError::Running {
            msg: from_utf8(&out.stderr)?.to_string()
        })
    }
}

arg_enum! {
    #[derive(PartialEq, Debug)]
    /// Reporter used to `format` the output of `run`ning the tests.
    pub enum Reporter {
        Human,
        Json,
        Junit
    }
}

/// TestResult of running tests. Contains a field for all passed and failed tests.
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TestResult {
    passed: Vec<PassedTest>,
    failed: Vec<FailedTest>,
}

impl TestResult {
    /// Check if all tests were successful.
    pub fn successful(&self) -> bool {
        self.failed.is_empty()
    }

    /// Format the test result given a reporter.
    pub fn format(&self, now: time::Duration, reporter: Reporter) -> Result<String, Error> {
        match reporter {
            Reporter::Json => Ok(self.json()),
            Reporter::Human => self.human(now),
            Reporter::Junit => self.junit(),
        }
    }

    fn json(&self) -> String {
        json::to_string(&self).unwrap()
    }

    fn human(&self, now: time::Duration) -> Result<String, Error> {
        Ok(format!(
            "
    {failed_tests}
    {status}

    {durationLabel} {duration} ms
    {passedLabel}   {passed_count} 
    {failedLabel}   {failed_count}

",
            status = self.status().underline(),
            durationLabel = "Duration:".dimmed(),
            passedLabel = "Passed:".dimmed(),
            failedLabel = "Failed:".dimmed(),
            duration = now.as_millis(),
            passed_count = self.passed.len(),
            failed_count = self.failed.len(),
            failed_tests = self.failed_to_human()?
        ))
    }

    fn failed_to_human(&self) -> Result<String, Error> {
        let mut failed_tests = String::new();
        for test in &self.failed {
            failed_tests.push_str(&test.human()?);
            failed_tests.push('\n');
        }
        Ok(failed_tests)
    }

    fn junit(&self) -> Result<String, Error> {
        let mut report = Report::new();
        let mut test_suite = TestSuite::new("nix tests"); // TODO use file name and allow multiple files?
        test_suite.add_testcases(self.to_testcases());
        report.add_testsuite(test_suite);
        let mut out: Vec<u8> = Vec::new();
        report.write_xml(&mut out)?;
        Ok(from_utf8(&out)?.to_string())
    }

    fn to_testcases(&self) -> Vec<TestCase> {
        let mut testcases = vec![];
        for test in &self.passed {
            testcases.push(test.junit());
        }
        for test in &self.failed {
            testcases.push(test.junit());
        }
        testcases
    }

    fn status(&self) -> ColoredString {
        if self.successful() {
            PASSED.green()
        } else {
            FAILED.red()
        }
    }
}

#[test]
fn status_passed_test() {
    assert_eq!(
        TestResult {
            passed: vec![],
            failed: vec![]
        }
        .status(),
        PASSED.green()
    )
}

#[test]
fn status_failed_test() {
    assert_eq!(
        TestResult {
            passed: vec![],
            failed: vec![FailedTest {
                expected: "".to_string(),
                result: "".to_string(),
                failed_test: "".to_string()
            }]
        }
        .status(),
        FAILED.red()
    )
}

trait JunitTest {
    fn junit(&self) -> TestCase;
    fn format_result(&self) -> String;
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct FailedTest {
    expected: String,
    failed_test: String,
    result: String,
}

impl FailedTest {
    fn human(&self) -> Result<String, Error> {
        let result_diff = render_diff(ARROW_UP, &self.result, &self.expected);
        let expected_diff = render_diff(ARROW_DOWN, &self.expected, &self.result);
        let indent = 8;
        Ok(format!(
            "
    {name}

        {result}
        ╷
        │ Expect.equal
        ╵
        {expected}
        ",
            name = ("✗ ".to_owned() + &self.failed_test).red(),
            result = with_diff(&self.result, &result_diff, indent),
            expected = with_diff(&expected_diff, &self.expected, indent)
        )
        .to_string())
    }
}

fn render_diff(symbol: char, left: &str, right: &str) -> String {
    let mut rendered = String::new();
    for diff in diff::chars(left, right) {
        match diff {
            diff::Result::Left(_) => rendered.push(symbol),
            diff::Result::Right(_) => (),
            diff::Result::Both(_, _) => rendered.push(' '),
        }
    }
    rendered
}

fn with_diff(first: &str, second: &str, indent: usize) -> String {
    let width = termize::dimensions().map(|t| t.1).unwrap_or(80);
    sub_strings(first, width - indent)
        .into_iter()
        .interleave(sub_strings(second, width - indent))
        .join(&format!("\n{}", " ".repeat(indent)))
}

fn sub_strings(source: &str, sub_size: usize) -> Vec<String> {
    source
        .chars()
        .chunks(sub_size)
        .into_iter()
        .map(Iterator::collect)
        .collect::<Vec<_>>()
}

impl JunitTest for FailedTest {
    fn junit(&self) -> TestCase {
        TestCase::failure(
            &self.failed_test,
            Duration::zero(),
            "Equals",
            &self.format_result(),
        )
    }
    fn format_result(&self) -> String {
        format!(
            "Actual: {result} Expected: {expected}",
            result = self.result,
            expected = self.expected
        )
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct PassedTest {
    passed_test: String,
}

impl JunitTest for PassedTest {
    fn junit(&self) -> TestCase {
        TestCase::success(&self.passed_test, Duration::zero())
    }
    fn format_result(&self) -> String {
        String::new()
    }
}