This repository was archived by the owner on Dec 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathoutput.rs
More file actions
485 lines (441 loc) · 13.7 KB
/
Copy pathoutput.rs
File metadata and controls
485 lines (441 loc) · 13.7 KB
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
extern crate regex;
use self::errors::*;
pub use self::errors::{Error, ErrorKind};
use diff;
use difference::Changeset;
use std::fmt;
use std::process;
use std::rc;
#[derive(Clone, PartialEq, Eq)]
pub enum Content {
Str(String),
Bytes(Vec<u8>),
}
impl fmt::Debug for Content {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Content::Str(ref data) => write!(f, "{}", data),
Content::Bytes(ref data) => write!(f, "{:?}", data),
}
}
}
impl<'a> From<&'a str> for Content {
fn from(data: &'a str) -> Self {
Content::Str(data.into())
}
}
impl<'a> From<&'a [u8]> for Content {
fn from(data: &'a [u8]) -> Self {
Content::Bytes(data.into())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct IsPredicate {
pub expect: Content,
pub expected_result: bool,
}
impl IsPredicate {
pub fn verify(&self, got: &[u8]) -> Result<()> {
match self.expect {
Content::Str(ref expect) => {
self.verify_str(expect, String::from_utf8_lossy(got).as_ref())
}
Content::Bytes(ref expect) => self.verify_bytes(expect, got),
}
}
fn verify_bytes(&self, expect: &[u8], got: &[u8]) -> Result<()> {
let result = expect == got;
if result != self.expected_result {
if self.expected_result {
bail!(ErrorKind::BytesDoesntMatch(
expect.to_owned(),
got.to_owned(),
));
} else {
bail!(ErrorKind::BytesMatches(got.to_owned()));
}
}
Ok(())
}
fn verify_str(&self, expect: &str, got: &str) -> Result<()> {
let differences = Changeset::new(expect.trim(), got.trim(), "\n");
let result = differences.distance == 0;
if result != self.expected_result {
if self.expected_result {
let nice_diff = diff::render(&differences)?;
bail!(ErrorKind::StrDoesntMatch(
expect.to_owned(),
got.to_owned(),
nice_diff
));
} else {
bail!(ErrorKind::StrMatches(got.to_owned()));
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ContainsPredicate {
pub expect: Content,
pub expected_result: bool,
}
fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack
.windows(needle.len())
.position(|window| window == needle)
}
#[test]
fn test_find_subsequence() {
assert_eq!(find_subsequence(b"qwertyuiop", b"tyu"), Some(4));
assert_eq!(find_subsequence(b"qwertyuiop", b"asd"), None);
}
impl ContainsPredicate {
pub fn verify(&self, got: &[u8]) -> Result<()> {
match self.expect {
Content::Str(ref expect) => {
self.verify_str(expect, String::from_utf8_lossy(got).as_ref())
}
Content::Bytes(ref expect) => self.verify_bytes(expect, got),
}
}
pub fn verify_bytes(&self, expect: &[u8], got: &[u8]) -> Result<()> {
let result = find_subsequence(got, expect).is_some();
if result != self.expected_result {
if self.expected_result {
bail!(ErrorKind::BytesDoesntContain(
expect.to_owned(),
got.to_owned()
));
} else {
bail!(ErrorKind::BytesContains(expect.to_owned(), got.to_owned()));
}
}
Ok(())
}
pub fn verify_str(&self, expect: &str, got: &str) -> Result<()> {
let result = got.contains(expect);
if result != self.expected_result {
if self.expected_result {
bail!(ErrorKind::StrDoesntContain(
expect.to_owned(),
got.to_owned()
));
} else {
bail!(ErrorKind::StrContains(expect.to_owned(), got.to_owned()));
}
}
Ok(())
}
}
#[derive(Clone)]
struct FnPredicate {
pub pred: rc::Rc<Fn(&str) -> bool>,
pub msg: String,
}
impl FnPredicate {
pub fn verify(&self, got: &[u8]) -> Result<()> {
let got = String::from_utf8_lossy(got);
let pred = &self.pred;
if !pred(&got) {
let err: Error = ErrorKind::PredicateFailed(got.into_owned(), self.msg.clone()).into();
bail!(err);
}
Ok(())
}
}
impl fmt::Debug for FnPredicate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.msg)
}
}
#[derive(Debug, Clone)]
struct RegexPredicate {
regex: regex::Regex,
times: u32,
}
impl RegexPredicate {
fn verify(&self, got: &[u8]) -> Result<()> {
let conversion = String::from_utf8_lossy(got);
let got = conversion.as_ref();
if self.times == 0 {
let result = self.regex.is_match(got);
if !result {
bail!(ErrorKind::OutputDoesntMatchRegexExactTimes(
String::from(self.regex.as_str()),
got.into(),
1,
1
));
}
} else {
let regex_matches = self.regex.captures_iter(got).count();
if regex_matches != (self.times as usize) {
bail!(ErrorKind::OutputDoesntMatchRegexExactTimes(
String::from(self.regex.as_str()),
got.into(),
self.times,
regex_matches,
));
}
}
Ok(())
}
}
#[derive(Debug, Clone)]
enum ContentPredicate {
Is(IsPredicate),
Contains(ContainsPredicate),
Fn(FnPredicate),
Regex(RegexPredicate),
}
impl ContentPredicate {
pub fn verify(&self, got: &[u8]) -> Result<()> {
match *self {
ContentPredicate::Is(ref pred) => pred.verify(got),
ContentPredicate::Contains(ref pred) => pred.verify(got),
ContentPredicate::Fn(ref pred) => pred.verify(got),
ContentPredicate::Regex(ref pred) => pred.verify(got),
}
}
}
/// Assertions for command output.
#[derive(Debug, Clone)]
pub struct Output {
pred: ContentPredicate,
}
impl Output {
/// Expect the command's output to **contain** `output`.
///
/// # Examples
///
/// ```rust
/// extern crate assert_cli;
///
/// assert_cli::Assert::command(&["echo"])
/// .with_args(&["42"])
/// .stdout().contains("42")
/// .unwrap();
/// ```
pub fn contains<O: Into<Content>>(output: O) -> Self {
let pred = ContainsPredicate {
expect: output.into(),
expected_result: true,
};
Self::new(ContentPredicate::Contains(pred))
}
/// Expect the command to output **exactly** this `output`.
///
/// # Examples
///
/// ```rust
/// extern crate assert_cli;
///
/// assert_cli::Assert::command(&["echo"])
/// .with_args(&["42"])
/// .stdout().is("42")
/// .unwrap();
/// ```
pub fn is<O: Into<Content>>(output: O) -> Self {
let pred = IsPredicate {
expect: output.into(),
expected_result: true,
};
Self::new(ContentPredicate::Is(pred))
}
/// Expect the command to **match** this `output`.
///
/// # Examples
///
/// ```rust
/// extern crate assert_cli;
///
/// assert_cli::Assert::command(&["echo"])
/// .with_args(&["42"])
/// .stdout().matches("[0-9]{2}")
/// .unwrap();
/// ```
pub fn matches(output: String) -> Self {
let pred = RegexPredicate {
regex: regex::Regex::new(&output).unwrap(),
times: 0,
};
Self::new(ContentPredicate::Regex(pred))
}
/// Expect the command to **match** this `output` exacly `nmatches` times.
///
/// # Examples
///
/// ```rust
/// extern crate assert_cli;
///
/// assert_cli::Assert::command(&["echo"])
/// .with_args(&["42"])
/// .stdout().matches_ntimes("[0-9]{1}", 2)
/// .unwrap();
/// ```
pub fn matches_ntimes(output: String, nmatches: u32) -> Self {
let pred = RegexPredicate {
regex: regex::Regex::new(&output).unwrap(),
times: nmatches,
};
Self::new(ContentPredicate::Regex(pred))
}
/// Expect the command's output to not **contain** `output`.
///
/// # Examples
///
/// ```rust
/// extern crate assert_cli;
///
/// assert_cli::Assert::command(&["echo"])
/// .with_args(&["42"])
/// .stdout().doesnt_contain("73")
/// .unwrap();
/// ```
pub fn doesnt_contain<O: Into<Content>>(output: O) -> Self {
let pred = ContainsPredicate {
expect: output.into(),
expected_result: false,
};
Self::new(ContentPredicate::Contains(pred))
}
/// Expect the command to output to not be **exactly** this `output`.
///
/// # Examples
///
/// ```rust
/// extern crate assert_cli;
///
/// assert_cli::Assert::command(&["echo"])
/// .with_args(&["42"])
/// .stdout().isnt("73")
/// .unwrap();
/// ```
pub fn isnt<O: Into<Content>>(output: O) -> Self {
let pred = IsPredicate {
expect: output.into(),
expected_result: false,
};
Self::new(ContentPredicate::Is(pred))
}
/// Expect the command output to satisfy the given predicate.
///
/// # Examples
///
/// ```rust
/// extern crate assert_cli;
///
/// assert_cli::Assert::command(&["echo", "-n", "42"])
/// .stdout().satisfies(|x| x.len() == 2, "bad length")
/// .unwrap();
/// ```
pub fn satisfies<F, M>(pred: F, msg: M) -> Self
where
F: 'static + Fn(&str) -> bool,
M: Into<String>,
{
let pred = FnPredicate {
pred: rc::Rc::new(pred),
msg: msg.into(),
};
Self::new(ContentPredicate::Fn(pred))
}
fn new(pred: ContentPredicate) -> Self {
Self { pred }
}
pub(crate) fn verify(&self, got: &[u8]) -> Result<()> {
self.pred.verify(got)
}
}
#[derive(Debug, Clone, Copy)]
pub enum OutputKind {
StdOut,
StdErr,
}
impl OutputKind {
pub fn select(self, o: &process::Output) -> &[u8] {
match self {
OutputKind::StdOut => &o.stdout,
OutputKind::StdErr => &o.stderr,
}
}
}
#[derive(Debug, Clone)]
pub struct OutputPredicate {
kind: OutputKind,
pred: Output,
}
impl OutputPredicate {
pub fn new(kind: OutputKind, pred: Output) -> Self {
Self { kind, pred }
}
pub(crate) fn verify(&self, got: &process::Output) -> Result<()> {
let got = self.kind.select(got);
self.pred
.verify(got)
.chain_err(|| ErrorKind::OutputMismatch(self.kind))
}
}
mod errors {
error_chain! {
foreign_links {
Fmt(::std::fmt::Error);
}
errors {
StrDoesntContain(expected: String, got: String) {
description("Output was not as expected")
display("expected to contain {:?}\noutput=```{}```", expected, got)
}
BytesDoesntContain(expected: Vec<u8>, got: Vec<u8>) {
description("Output was not as expected")
display("expected to contain {:?}\noutput=```{:?}```", expected, got)
}
StrContains(expected: String, got: String) {
description("Output was not as expected")
display("expected to not contain {:?}\noutput=```{}```", expected, got)
}
BytesContains(expected: Vec<u8>, got: Vec<u8>) {
description("Output was not as expected")
display("expected to not contain {:?}\noutput=```{:?}```", expected, got)
}
StrDoesntMatch(expected: String, got: String, diff: String) {
description("Output was not as expected")
display("diff:\n{}", diff)
}
BytesDoesntMatch(expected: Vec<u8>, got: Vec<u8>) {
description("Output was not as expected")
display("expected=```{:?}```\noutput=```{:?}```", expected, got)
}
StrMatches(got: String) {
description("Output was not as expected")
display("expected to not match\noutput=```{}```", got)
}
BytesMatches(got: Vec<u8>) {
description("Output was not as expected")
display("expected to not match\noutput=```{:?}```", got)
}
PredicateFailed(got: String, msg: String) {
description("Output predicate failed")
display("{}\noutput=```{}```", msg, got)
}
/* Adding a single error more makes this break, using the bottom one temporarily
OutputDoesntMatchRegex(regex: String, got: String) {
description("Expected to regex to match")
display("expected {}\n to match output=```{}```", regex, got)
}
*/
OutputDoesntMatchRegexExactTimes(regex: String, got: String, expected_times: u32, got_times: usize) {
description("Expected to regex to match exact number of times")
display("expected {}\n to match output=```{}``` {} times instead of {} times", regex, got, expected_times, got_times)
}
OutputMismatch(kind: super::OutputKind) {
description("Output was not as expected")
display(
"Unexpected {:?}",
kind
)
}
}
}
}