forked from assert-rs/assert_cmd
/
assert.rs
538 lines (479 loc) · 13.1 KB
/
assert.rs
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! `process::Output` assertions.
use std::fmt;
use std::process;
use std::str;
use predicates;
use predicates::str::PredicateStrExt;
use cmd::dump_buffer;
use errors::output_fmt;
/// Assert the state of an `Output`.
///
/// # Examples
///
/// ```rust
/// use assert_cmd::prelude::*;
///
/// use std::process::Command;
///
/// Command::main_binary()
/// .unwrap()
/// .assert()
/// .success();
/// ```
pub trait OutputAssertExt {
/// Wrap with an interface for that provides assertions on the `process::Output`.
///
/// # Examples
///
/// ```rust
/// use assert_cmd::prelude::*;
///
/// use std::process::Command;
///
/// Command::main_binary()
/// .unwrap()
/// .assert()
/// .success();
/// ```
fn assert(self) -> Assert;
}
impl OutputAssertExt for process::Output {
fn assert(self) -> Assert {
Assert::new(self)
}
}
impl<'c> OutputAssertExt for &'c mut process::Command {
fn assert(self) -> Assert {
let output = self.output().unwrap();
Assert::new(output).set_cmd(format!("{:?}", self))
}
}
/// Assert the state of an `Output`.
///
/// Create an `Assert` through the `OutputAssertExt` trait.
///
/// # Examples
///
/// ```rust
/// use assert_cmd::prelude::*;
///
/// use std::process::Command;
///
/// Command::main_binary()
/// .unwrap()
/// .assert()
/// .success();
/// ```
#[derive(Debug)]
pub struct Assert {
output: process::Output,
cmd: Option<String>,
stdin: Option<Vec<u8>>,
}
impl Assert {
/// Create an `Assert` for a given `Output`.
pub fn new(output: process::Output) -> Self {
Self {
output,
cmd: None,
stdin: None,
}
}
/// Add the command line for additional context.
pub fn set_cmd(mut self, cmd: String) -> Self {
self.cmd = Some(cmd);
self
}
/// Add the `stdn` for additional context.
pub fn set_stdin(mut self, stdin: Vec<u8>) -> Self {
self.stdin = Some(stdin);
self
}
/// Access the contained `std::process::Output`.
pub fn get_output(&self) -> &process::Output {
&self.output
}
// How does user interact with assertion API?
// - On Assert class, using error chaining
// - "Builder" or not? If yes, then do we extend Result?
// - How do we give a helpful unwrap?
// - Build up assertion data and "execute" it, like assert_cli used to? But that was mostly
// from building up before executing the command happened. Now we're doing it
// after-the-fact.
// - Immediately panic in each assertion? Let's give that a try.
/// Ensure the command succeeded.
///
/// # Examples
///
/// ```rust
/// use assert_cmd::prelude::*;
///
/// use std::process::Command;
///
/// Command::main_binary()
/// .unwrap()
/// .assert()
/// .success();
/// ```
pub fn success(self) -> Self {
if !self.output.status.success() {
let actual_code = self.output.status.code().unwrap_or_else(|| {
panic!(
"Unexpected failure.\ncode=<interrupted>\nstderr=```{}```\n{}",
dump_buffer(&self.output.stderr),
self
)
});
panic!(
"Unexpected failure.\ncode-{}\nstderr=```{}```\n{}",
actual_code,
dump_buffer(&self.output.stderr),
self
);
}
self
}
/// Ensure the command failed.
///
/// # Examples
///
/// ```rust
/// use assert_cmd::prelude::*;
///
/// use std::process::Command;
///
/// Command::main_binary()
/// .unwrap()
/// .env("exit", "1")
/// .assert()
/// .failure();
/// ```
pub fn failure(self) -> Self {
if self.output.status.success() {
panic!(
"Unexpected success\nstdout=```{}```\n{}",
dump_buffer(&self.output.stdout),
self
);
}
self
}
/// Ensure the command aborted before returning a code.
pub fn interrupted(self) -> Self {
if self.output.status.code().is_some() {
panic!(
"Unexpected completion\nstdout=```{}```\n{}",
dump_buffer(&self.output.stdout),
self
);
}
self
}
/// Ensure the command returned the expected code.
///
/// # Examples
///
/// ```rust
/// use assert_cmd::prelude::*;
///
/// use std::process::Command;
///
/// Command::main_binary()
/// .unwrap()
/// .env("exit", "42")
/// .assert()
/// .code(42);
/// ```
pub fn code<I, P>(self, pred: I) -> Self
where
I: IntoCodePredicate<P>,
P: predicates::Predicate<i32>,
{
self.code_impl(&pred.into_code())
}
fn code_impl(self, pred: &predicates::Predicate<i32>) -> Self {
let actual_code = self.output.status.code().unwrap_or_else(|| {
panic!(
"Command interrupted\nstderr=```{}```\n{}",
dump_buffer(&self.output.stderr),
self
)
});
if !pred.eval(&actual_code) {
panic!(
"Unexpected return code\nstdout=```{}```\nstderr=```{}```\n{}",
dump_buffer(&self.output.stdout),
dump_buffer(&self.output.stderr),
self
);
}
self
}
/// Ensure the command wrote the expected data to `stdout`.
///
/// # Examples
///
/// ```rust
/// use assert_cmd::prelude::*;
///
/// use std::process::Command;
///
/// Command::main_binary()
/// .unwrap()
/// .env("stdout", "hello")
/// .env("stderr", "world")
/// .assert()
/// .stdout("hello\n");
/// ```
pub fn stdout<I, P>(self, pred: I) -> Self
where
I: IntoOutputPredicate<P>,
P: predicates::Predicate<[u8]>,
{
self.stdout_impl(&pred.into_output())
}
fn stdout_impl(self, pred: &predicates::Predicate<[u8]>) -> Self {
{
let actual = &self.output.stdout;
if !pred.eval(actual) {
panic!("Unexpected stdout\n{}", self);
}
}
self
}
/// Ensure the command wrote the expected data to `stderr`.
///
/// # Examples
///
/// ```rust
/// use assert_cmd::prelude::*;
///
/// use std::process::Command;
///
/// Command::main_binary()
/// .unwrap()
/// .env("stdout", "hello")
/// .env("stderr", "world")
/// .assert()
/// .stderr("world\n");
/// ```
pub fn stderr<I, P>(self, pred: I) -> Self
where
I: IntoOutputPredicate<P>,
P: predicates::Predicate<[u8]>,
{
self.stderr_impl(&pred.into_output())
}
fn stderr_impl(self, pred: &predicates::Predicate<[u8]>) -> Self {
{
let actual = &self.output.stderr;
if !pred.eval(actual) {
panic!("Unexpected stderr\n{}", self);
}
}
self
}
}
impl fmt::Display for Assert {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref cmd) = self.cmd {
writeln!(f, "command=`{}`", cmd)?;
}
if let Some(ref stdin) = self.stdin {
if let Ok(stdin) = str::from_utf8(stdin) {
writeln!(f, "stdin=```{}```", stdin)?;
} else {
writeln!(f, "stdin=```{:?}```", stdin)?;
}
}
output_fmt(&self.output, f)
}
}
/// Used by `Assert::code` to convert `Self` into the needed `Predicate<i32>`.
///
/// # Examples
///
/// ```rust,ignore
/// use assert_cmd::prelude::*;
///
/// use std::process::Command;
///
/// Command::main_binary()
/// .unwrap()
/// .env("exit", "42")
/// .assert()
/// .code(42);
/// // which is equivalent to
/// Command::main_binary()
/// .unwrap()
/// .env("exit", "42")
/// .assert()
/// .code(predicates::ord::eq(42));
/// ```
pub trait IntoCodePredicate<P>
where
P: predicates::Predicate<i32>,
{
/// The type of the predicate being returned.
type Predicate;
/// Convert to a predicate for testing a program's exit code.
fn into_code(self) -> P;
}
impl<P> IntoCodePredicate<P> for P
where
P: predicates::Predicate<i32>,
{
type Predicate = P;
fn into_code(self) -> Self::Predicate {
self
}
}
impl IntoCodePredicate<predicates::ord::EqPredicate<i32>> for i32 {
type Predicate = predicates::ord::EqPredicate<i32>;
fn into_code(self) -> Self::Predicate {
predicates::ord::eq(self)
}
}
impl IntoCodePredicate<predicates::iter::InPredicate<i32>> for Vec<i32> {
type Predicate = predicates::iter::InPredicate<i32>;
fn into_code(self) -> Self::Predicate {
predicates::iter::in_iter(self)
}
}
impl IntoCodePredicate<predicates::iter::InPredicate<i32>> for &'static [i32] {
type Predicate = predicates::iter::InPredicate<i32>;
fn into_code(self) -> Self::Predicate {
predicates::iter::in_iter(self.iter().cloned())
}
}
/// Used by `Assert` to convert Self into the needed `Predicate<[u8]>`.
pub trait IntoOutputPredicate<P>
where
P: predicates::Predicate<[u8]>,
{
/// The type of the predicate being returned.
type Predicate;
/// Convert to a predicate for testing a path.
fn into_output(self) -> P;
}
impl<P> IntoOutputPredicate<P> for P
where
P: predicates::Predicate<[u8]>,
{
type Predicate = P;
fn into_output(self) -> Self::Predicate {
self
}
}
// Keep `predicates` concrete Predicates out of our public API.
/// Predicate used by `IntoOutputPredicate` for bytes
#[derive(Debug)]
pub struct BytesContentOutputPredicate(predicates::ord::EqPredicate<&'static [u8]>);
impl BytesContentOutputPredicate {
pub(crate) fn new(value: &'static [u8]) -> Self {
let pred = predicates::ord::eq(value);
BytesContentOutputPredicate(pred)
}
}
impl predicates::Predicate<[u8]> for BytesContentOutputPredicate {
fn eval(&self, item: &[u8]) -> bool {
self.0.eval(item)
}
}
impl fmt::Display for BytesContentOutputPredicate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl IntoOutputPredicate<BytesContentOutputPredicate> for &'static [u8] {
type Predicate = BytesContentOutputPredicate;
fn into_output(self) -> Self::Predicate {
Self::Predicate::new(self)
}
}
// Keep `predicates` concrete Predicates out of our public API.
/// Predicate used by `IntoOutputPredicate` for `str`
#[derive(Debug, Clone)]
pub struct StrContentOutputPredicate(
predicates::str::Utf8Predicate<predicates::str::DifferencePredicate>,
);
impl StrContentOutputPredicate {
pub(crate) fn new(value: &'static str) -> Self {
let pred = predicates::str::similar(value).from_utf8();
StrContentOutputPredicate(pred)
}
}
impl predicates::Predicate<[u8]> for StrContentOutputPredicate {
fn eval(&self, item: &[u8]) -> bool {
self.0.eval(item)
}
}
impl fmt::Display for StrContentOutputPredicate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl IntoOutputPredicate<StrContentOutputPredicate> for &'static str {
type Predicate = StrContentOutputPredicate;
fn into_output(self) -> Self::Predicate {
Self::Predicate::new(self)
}
}
#[cfg(test)]
mod test {
use super::*;
use predicates::prelude::*;
// Since IntoCodePredicate exists solely for conversion, test it under that scenario to ensure
// it works as expected.
fn convert_code<I, P>(pred: I) -> P
where
I: IntoCodePredicate<P>,
P: predicates::Predicate<i32>,
{
pred.into_code()
}
#[test]
fn into_code_from_pred() {
let pred = convert_code(predicate::eq(10));
assert!(pred.eval(&10));
}
#[test]
fn into_code_from_i32() {
let pred = convert_code(10);
assert!(pred.eval(&10));
}
#[test]
fn into_code_from_vec() {
let pred = convert_code(vec![3, 10]);
assert!(pred.eval(&10));
}
#[test]
fn into_code_from_array() {
let pred = convert_code(&[3, 10] as &[i32]);
assert!(pred.eval(&10));
}
// Since IntoOutputPredicate exists solely for conversion, test it under that scenario to ensure
// it works as expected.
fn convert_output<I, P>(pred: I) -> P
where
I: IntoOutputPredicate<P>,
P: predicates::Predicate<[u8]>,
{
pred.into_output()
}
#[test]
fn into_output_from_pred() {
let pred = convert_output(predicate::eq(b"Hello" as &[u8]));
assert!(pred.eval(b"Hello" as &[u8]));
}
#[test]
fn into_output_from_bytes() {
let pred = convert_output(b"Hello" as &[u8]);
assert!(pred.eval(b"Hello" as &[u8]));
}
#[test]
fn into_output_from_str() {
let pred = convert_output("Hello");
assert!(pred.eval(b"Hello" as &[u8]));
}
}