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
//! # Test CLI Applications
//!
//! Currently, this crate only includes basic functionality to check the output of a child process
//! is as expected.
//!
//! ## Example
//!
//! Here's a trivial example:
//!
//! ```rust
//! # extern crate assert_cli;
//!
//! assert_cli::assert_cli_output("echo", &["42"], "42").unwrap();
//! ```
//!
//! And here is one that will fail:
//!
//! ```rust,should_panic
//! assert_cli::assert_cli_output("echo", &["42"], "1337").unwrap();
//! ```
//!
//! this will show a nice, colorful diff in your terminal, like this:
//!
//! ```diff
//! -1337
//! +42
//! ```
//!
//! Alternatively, you can use the `assert_cli!` macro:
//!
//! ```rust
//! # #[macro_use] extern crate assert_cli;
//! # fn main() {
//! assert_cli!("echo", &["42"] => Success, "42").unwrap();
//! # }
//! ```
//!
//! All exported functions and the macro return a `Result` containing the
//! `Output` of the process, allowing you to do further custom assertions:
//!
//! ```rust
//! # #[macro_use] extern crate assert_cli;
//! # fn main() {
//! let output = assert_cli!("echo", &["Number 42"] => Success).unwrap();
//! let stdout = std::str::from_utf8(&output.stdout).unwrap();
//! assert!(stdout.contains("42"));
//! # }
//! ```
//!
//! Make sure to include the crate as `#[macro_use] extern crate assert_cli;`.


#![cfg_attr(feature = "dev", feature(plugin))]
#![cfg_attr(feature = "dev", plugin(clippy))]

#![deny(missing_docs)]

extern crate ansi_term;
extern crate difference;

use std::process::{Command, Output};
use std::error::Error;
use std::ffi::OsStr;

mod cli_error;
mod diff;

use cli_error::CliError;


/// Assert a CLI call
///
/// To test that
///
/// ```sh
/// bash -c $BLACK_BOX
/// ```
///
/// exits with the correct exit value. You would call it like this:
///
/// ```rust
/// # extern crate assert_cli;
/// # const BLACK_BOX: &'static str = r#"function test_helper() {\
/// # echo "Launch sequence initiated."; return 0; }; test_helper"#;
/// assert_cli::assert_cli("bash", &["-c", BLACK_BOX]);
/// ```
pub fn assert_cli<S>(cmd: &str, args: &[S]) -> Result<Output, Box<Error>>
    where S: AsRef<OsStr>
{
    let call: Result<Output, Box<Error>> = Command::new(cmd)
                                               .args(args)
                                               .output()
                                               .map_err(From::from);

    call.and_then(|output| {
            if !output.status.success() {
                return Err(From::from(CliError::WrongExitCode(output)));
            }

            Ok(output)
        })
        .map_err(From::from)
}


/// Assert a CLI call returns the expected output.
///
/// To test that
///
/// ```sh
/// bash -c $BLACK_BOX
/// ```
///
/// returns
///
/// ```plain
/// Launch sequence initiated.
/// ```
///
/// you would call it like this:
///
/// ```rust
/// # extern crate assert_cli;
/// # const BLACK_BOX: &'static str = r#"function test_helper() {\
/// # echo "Launch sequence initiated."; return 0; }; test_helper"#;
/// assert_cli::assert_cli_output("bash", &["-c", BLACK_BOX], "Launch sequence initiated.");
/// ```
pub fn assert_cli_output<S>(cmd: &str, args: &[S], expected_output: &str) -> Result<Output, Box<Error>>
    where S: AsRef<OsStr>
{
    let call: Result<Output, Box<Error>> = Command::new(cmd)
                                               .args(args)
                                               .output()
                                               .map_err(From::from);

    call.and_then(|output| {
            if !output.status.success() {
                return Err(From::from(CliError::WrongExitCode(output)));
            }

            {
                let stdout = String::from_utf8_lossy(&output.stdout);
                let (distance, changes) = difference::diff(expected_output.trim(),
                                                           &stdout.trim(),
                                                           "\n");
                if distance > 0 {
                    return Err(From::from(CliError::OutputMissmatch(changes)));
                }
            }

            Ok(output)
        })
        .map_err(From::from)
}

/// Assert a CLI call that fails with a given error code.
///
/// To test that
///
/// ```sh
/// bash -c $BLACK_BOX
/// ```
///
/// fails with an exit code of `42`.
///
/// you would call it like this:
///
/// ```rust
/// # extern crate assert_cli;
/// # const BLACK_BOX: &'static str = r#"function test_helper() {\
/// # >&2 echo "error no 42!"; return 42; }; test_helper"#;
/// assert_cli::assert_cli_error("bash", &["-c", BLACK_BOX], Some(42));
/// ```
pub fn assert_cli_error<S>(cmd: &str,
                                  args: &[S],
                                  error_code: Option<i32>)
                                  -> Result<Output, Box<Error>>
    where S: AsRef<OsStr>
{
    let call: Result<Output, Box<Error>> = Command::new(cmd)
                                               .args(args)
                                               .output()
                                               .map_err(From::from);

    call.and_then(|output| {
            if output.status.success() {
                return Err(From::from(CliError::WrongExitCode(output)));
            }

            match (error_code, output.status.code()) {
                (Some(a), Some(b)) if a != b =>
                    return Err(From::from(CliError::WrongExitCode(output))),
                _ => {}
            }

            Ok(output)
        })
        .map_err(From::from)
}

/// Assert a CLI call that fails the expected `stderr` output and error code.
///
/// To test that
///
/// ```sh
/// bash -c $BLACK_BOX
/// ```
///
/// fails with an exit code of `42` after printing this to `stderr`
///
/// ```plain
/// error no 42!
/// ```
///
/// you would call it like this:
///
/// ```rust
/// # extern crate assert_cli;
/// # const BLACK_BOX: &'static str = r#"function test_helper() {\
/// # >&2 echo "error no 42!"; return 42; }; test_helper"#;
/// assert_cli::assert_cli_output_error("bash", &["-c", BLACK_BOX], Some(42), "error no 42!");
/// ```
pub fn assert_cli_output_error<S>(cmd: &str,
                                  args: &[S],
                                  error_code: Option<i32>,
                                  expected_output: &str)
                                  -> Result<Output, Box<Error>>
    where S: AsRef<OsStr>
{
    let call: Result<Output, Box<Error>> = Command::new(cmd)
                                               .args(args)
                                               .output()
                                               .map_err(From::from);

    call.and_then(|output| {
            if output.status.success() {
                return Err(From::from(CliError::WrongExitCode(output)));
            }

            match (error_code, output.status.code()) {
                (Some(a), Some(b)) if a != b =>
                    return Err(From::from(CliError::WrongExitCode(output))),
                _ => {}
            }

            {
                let stdout = String::from_utf8_lossy(&output.stderr);
                let (distance, changes) = difference::diff(expected_output.trim(),
                                                           &stdout.trim(),
                                                           "\n");
                if distance > 0 {
                    return Err(From::from(CliError::OutputMissmatch(changes)));
                }
            }

            Ok(output)
        })
        .map_err(From::from)
}

/// The `assert_cli!` macro combines the functionality of the other functions in this crate in one
/// short macro.
///
/// ```rust
/// #[macro_use] extern crate assert_cli;
/// # const BLACK_BOX: &'static str = r#"function test_helper() {\
/// # >&2 echo "error no 66!"; return 66; }; test_helper"#;
///
/// fn main() {
///     assert_cli!("true", &[""] => Success).unwrap();
///     assert_cli!("echo", &["42"] => Success, "42").unwrap();
///     assert_cli!("bash", &["-c", BLACK_BOX] => Error 66).unwrap();
///     assert_cli!("bash", &["-c", BLACK_BOX] => Error 66, "error no 66!").unwrap();
/// }
/// ```
///
/// Make sure to include the crate as `#[macro_use] extern crate assert_cli;`.
#[macro_export]
macro_rules! assert_cli {
    ($cmd:expr, $args:expr => Success) => {{
        $crate::assert_cli($cmd, $args)
    }};
    ($cmd:expr, $args:expr => Success, $output:expr) => {{
        $crate::assert_cli_output($cmd, $args, $output)
    }};
    ($cmd:expr, $args:expr => Error, $output:expr) => {{
        $crate::assert_cli_output_error($cmd, $args, None, $output)
    }};
    ($cmd:expr, $args:expr => Error $err:expr, $output:expr) => {{
        $crate::assert_cli_output_error($cmd, $args, Some($err), $output)
    }};
    ($cmd:expr, $args:expr => Error) => {{
        $crate::assert_cli_error($cmd, $args, None)
    }};
    ($cmd:expr, $args:expr => Error $err:expr) => {{
        $crate::assert_cli_error($cmd, $args, Some($err))
    }};
}