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
use clap::arg_enum;
use colored::*;
use junit_report::{Duration, Report, TestCase, TestSuite};
use serde::{Deserialize, Serialize};
use serde_json;
use std::path::PathBuf;
use std::process::Command;
use std::str::from_utf8;
use std::time;

const PASSED: &str = "TEST RUN PASSED";
const FAILED: &str = "TEST RUN FAILED";

/// Evaluates a nix file containing test expressions.
/// This uses `nix-instantiate --eval --strict` underthehood.
pub fn run(test_file: PathBuf) -> Result<TestResult, String> {
    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().unwrap(),
            run_test_nix = run_test_nix
        ))
        .output()
        .map_err(|e| format!("{:#?}", e))?;
    if out.status.success() {
        Ok(serde_json::from_str(from_utf8(&out.stdout).unwrap()).unwrap())
    } else {
        Err(format!(
            "Running tests failed.\n\n    {}\n",
            from_utf8(&out.stderr).unwrap()
        ))
    }
}

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 {
    /// Format the test result given a reporter.
    pub fn successful(&self) -> bool {
        self.failed.is_empty()
    }

    pub fn format(&self, now: time::Duration, reporter: Reporter) -> String {
        match reporter {
            Reporter::Json => self.json(),
            Reporter::Human => self.human(now),
            Reporter::Junit => self.junit(),
        }
    }

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

    fn human(&self, now: time::Duration) -> String {
        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) -> String {
        let mut failed_tests = String::new();
        for test in &self.failed {
            failed_tests = format!("{}{}\n", failed_tests, test.human());
        }
        failed_tests
    }

    fn junit(&self) -> String {
        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).unwrap();
        from_utf8(&out).unwrap().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 Test {
    fn junit(&self) -> TestCase;
}

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

impl FailedTest {
    fn human(&self) -> String {
        format!(
            "
    {name}

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

impl Test for FailedTest {
    fn junit(&self) -> TestCase {
        TestCase::failure(&self.failed_test, Duration::zero(), "Equals", &self.human())
    }
}

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

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