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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! A collection of useful assertions and other utilities for writing
//! tests in Rust.

use std::any::Any;
use std::ops::Deref;

/// Get the panic message as a `&str`, if available
///
/// While a panic value can be any type, *usually* it is either a `String`
/// or a `str`, hidden inside a `Box<dyn Any + Send + Sync>` (see
/// [`std::thread::Result`] for more info). This function gets the panic
/// message as an &str (if available) from a panic value.
///
/// ```
/// use std::panic::catch_unwind;
/// use cool_asserts::get_panic_message;
///
/// let result = catch_unwind(|| panic!("{}, {}!", "Hello", "World"));
/// let panic = result.unwrap_err();
/// let message = get_panic_message(&panic).unwrap();
///
/// assert_eq!(message, "Hello, World!");
#[inline]
pub fn get_panic_message(panic: &Box<dyn Any + Send>) -> Option<&str> {
    panic.downcast_ref::<String>()
        .map(String::as_str)
        .or_else(|| panic.downcast_ref::<&'static str>().map(Deref::deref))
}

#[cfg(test)]
mod test_get_panic_message {
    use std::panic::catch_unwind;
    use super::get_panic_message;

    #[test]
    fn str_message() {
        let result = catch_unwind(|| panic!("Hello, World!"))
            .expect_err("Function didn't panic????");
        assert_eq!(get_panic_message(&result), Some("Hello, World!"));
    }

    #[test]
    fn string_message() {
        let result = catch_unwind(|| panic!("Hello, World!".to_string()))
            .expect_err("Function didn't panic????");
        assert_eq!(get_panic_message(&result), Some("Hello, World!"));
    }

    #[test]
    fn formatted_message() {
        let result = catch_unwind(|| panic!("{}, {}!", "Hello", "World"))
            .expect_err("Function didn't panic????");
        assert_eq!(get_panic_message(&result), Some("Hello, World!"));
    }

    #[test]
    fn other_message() {
        let result = catch_unwind(|| panic!(25))
            .expect_err("Function didn't panic????");
        assert_eq!(get_panic_message(&result), None);
    }
}

/// Compute the max of list of expressions.
///
/// This is given as a macro so that it can be fully evaluated at compile
/// time.
///
/// It guarantees that:
///
/// - All the expressions are evaluated in order, if relevant
/// - Each expression is only evaluated once.
#[macro_export]
#[doc(hidden)]
macro_rules! max {
    ($value:expr $(,)?) => ($value);
    ($lhs:expr $(, $tail:expr)+ $(,)?) => {{
        let lhs = $lhs;
        let tail = $crate::max!($($tail),+);
        if lhs < tail { tail } else { lhs }
    }}
}

/// Get a partial format string for assertion_failure given the spec
#[macro_export]
#[doc(hidden)]
macro_rules! make_assertion_failure_fmt {
    () => {"\n {:>padding$}: {}"};
    (debug) => {"\n {:>padding$}: {:?}"};
}

#[macro_export]
#[doc(hidden)]
macro_rules! make_assertion_failure_tail {
    () => {};
    ($($_arg:tt)+) => {
        "\n  {}"
    };
}

/// Panic with an assertion failure message
///
/// This macro is used in failing assertions to issue a panic with a message
/// in a standardized format, which includes:
///
/// - A static description of what went wrong.
/// - The file and line number of the error.
/// - Optionally, key-value components of the failed assertion (for example,
///   the `lhs` and `rhs` of a failed `assert_eq!`). These components are
///   visually aligned for an easier debugging experience.
/// - Optionally, a trailing formatted message.
///
/// The format of this macro is designed to be similar to the message printed
/// by [`assert_eq!`] or [`assert_ne!`]. The exact output is not currently
/// guaranteed to be identical with matching semver versions, though this may
/// change in the future.
///
/// # Example:
///
/// ```
/// use std::panic::catch_unwind;
/// use cool_asserts::{assertion_failure, get_panic_message};
///
/// let result = catch_unwind(|| assertion_failure!(
///     "Assertion Message",
///     // Add key-value data to the debug message
///     key: 10,
///
///     // Use the "debug" keyword to debug-print something.
///     // Additionally, notice in the output that the key and long-key
///     // are visually aligned.
///     long_key debug: "Hello\tWorld!";
///
///     // After a semicolon, add a trailing format message
///     "Trailing message: {}, {}!", "Hello", "World"
/// ));
/// let panic = result.unwrap_err();
/// let message = get_panic_message(&panic).unwrap();
/// assert_eq!(
///     message,
///  r#"assertion failed at src/lib.rs:7: `(Assertion Message)`
///       key: 10
///  long_key: "Hello\tWorld!"
///   Trailing message: Hello, World!"#
///    );
/// ```
#[macro_export]
macro_rules! assertion_failure {
    ($message:literal $($(, $key:ident $($spec:ident)?: $value:expr)+)? $(; $($fmt:tt)+)? ) => {
        panic!(
            concat!(
                "assertion failed at {file}:{line}: `(", $message, ")`",
                $($($crate::make_assertion_failure_fmt!($($spec)?),)+)?
                $($crate::make_assertion_failure_tail!($($fmt)+),)?
            ),
            $($(stringify!($key), $value,)+)?
            $(format_args!($($fmt)+),)?
            $(padding = $crate::max!($(stringify!($key).len(),)+),)?
            file=file!(),
            line=line!(),
        )
    };

    ($message:literal $($(, $key:ident $($spec:ident)?: $value:expr)+)? ,) => {
        $crate::assertion_failure!($message $($(, $key $($spec)?: $value)+)?)
    };

    ($message:literal $($(, $key:ident $($spec:ident)?: $value:expr)+)? ;) => {
        $crate::assertion_failure!($message $($(, $key $($spec)?: $value)+)?)
    };
}

#[cfg(test)]
mod assertion_failure_tests {
    use super::{assertion_failure, assert_panics};
    #[test]
    fn just_message() {
        assert_panics!(
            assertion_failure!("Failure Message"),
            includes("assertion failed at"),
            includes("Failure Message"),
            excludes("\n"),
        )
    }

    #[test]
    fn keys_aligned() {
        assert_panics!(
            assertion_failure!(
                "Failure Message",
                key: 10,
                long_key: 20,
            ),
            includes("assertion failed at"),
            includes("Failure Message"),
            includes("     key: 10\n"),
            includes("long_key: 20"),
        );
    }

    #[test]
    fn keys_trailing_fmt() {
        assert_panics!(
            assertion_failure!(
                "Failure Message",
                key: 10,
                long_key: 20;
                "{}, {}!", "Hello", "World"
            ),
            includes("assertion failed at"),
            includes("Failure Message"),
            includes("     key: 10\n"),
            includes("long_key: 20\n"),
            includes("\n  Hello, World!")
        );
    }
}

/// Assert that the value of an expression matches a given pattern.
///
/// This assertion checks that the value of an expression matches a pattern.
/// It panics if the expression does not match.
///
/// Optionally, provide a block with `=> { <block> }`; the block will be run
/// with the matched pattern if the match was successful. This allows running
/// additional assertions on the matched pattern.
///
/// You can also add a trailing format message that will be included with
/// the panic in the event of an assertion failure, just like with
/// [`assert_eq!`].
///
/// # Example
///
/// ```
/// use cool_asserts::{assert_matches, assert_panics};
///
/// assert_panics!{
///     assert_matches!(Some(10), None),
///     includes("value does not match pattern"),
/// }
///
/// assert_matches!(Some(10), Some(x) => {
///     assert_eq!(x, 10);
/// })
/// ```
#[macro_export]
macro_rules! assert_matches {
    ($expression:expr, $pattern:pat $(if $guard:expr)? $(=> $block:expr)?, ) => {
        $crate::assert_matches!($expression, $pattern $(if $guard)? $(=> $block)?)
    };
    ($expression:expr, $pattern:pat $(if $guard:expr)? $(=> $block:expr)? $(, $($fmt_arg:tt)+)?) => ({
        match $expression {
            $pattern $(if $guard)? => { $($block)? },
            v => $crate::assertion_failure!(
                "value does not match pattern",
                value debug: v,
                pattern: stringify!($pattern $(if $guard)?)
                $(; $($fmt_arg)+)?
            )
        }
    });
}

#[cfg(test)]
mod test_assert_matches {
    use super::{assert_matches, assert_panics};

    #[derive(Debug)]
    struct TestStruct {
        x: isize,
        y: isize,
    }

    const TEST_VALUE: Option<TestStruct> = Some(TestStruct { x: 10, y: 20 });

    #[test]
    fn basic_case() {
        assert_matches!(TEST_VALUE, Some(_));
    }

    #[test]
    fn trailing_comma() {
        assert_matches!(TEST_VALUE, Some(_),);
    }

    #[test]
    fn basic_guard() {
        assert_matches!(TEST_VALUE, Some(v) if v.y == 20);
    }

    #[test]
    fn basic_block() {
        assert_matches!(TEST_VALUE, Some(v) => {
            assert_eq!(v.x, 10);
        })
    }

    #[test]
    fn basic_guard_block() {
        assert_matches!(TEST_VALUE, Some(v) if v.y == 20 => {
            assert_eq!(v.x, 10);
        })
    }

    #[test]
    fn basic_failure() {
        assert_panics!(
            assert_matches!(TEST_VALUE, None),
            includes("assertion failed"),
            includes("value does not match pattern"),
            includes("pattern: None"),
            includes(&format!("value: {:?}", TEST_VALUE))
        );
    }

    #[test]
    fn basic_guard_failure() {
        assert_panics!(
            assert_matches!(TEST_VALUE, Some(v) if v.y == 0),
            includes("assertion failed"),
            includes("value does not match pattern"),
            includes("pattern: Some(v) if v.y == 0"),
            includes(&format!("value: {:?}", TEST_VALUE))
        );
    }

    #[test]
    fn basic_block_failure() {
        assert_panics!(
            assert_matches!(TEST_VALUE, None => {panic!("Custom Panic")}),
            includes("assertion failed"),
            includes("value does not match pattern"),
            includes("pattern: None"),
            includes(&format!("value: {:?}", TEST_VALUE)),
            excludes("Custom Panic"),
        );
    }

    #[test]
    fn failure_in_block() {
        assert_panics!(
            assert_matches!(TEST_VALUE, Some(TestStruct{..}) => {panic!("Custom Panic")}),
            includes("Custom Panic"),
            excludes("assertion failed"),
            excludes("value does not match pattern"),
        )
    }
}

/// Assert that an expression panics.
///
/// This macro asserts that a given expression panics. If the expression
/// doesn't panic, this macro will panic, with a description including the
/// expression itself, as well as the return value of the expression.
///
/// This macro is intended to replace `#[should_panic]` in rust tests:
///
/// - It allows for checking that a particular expression or statement panics,
///   rather than an entire test function.
/// - It allows checking for the presence or absence of multiple substrings.
/// `should_panic` can only test for a single substring (with `expected`),
/// and can't test for absence at all.
///
/// ## Examples
///
/// ```
/// use cool_asserts::assert_panics;
///
/// assert_panics!({
///     let _x = 1 + 2;
///     panic!("Panic Message");
/// });
/// ```
/// ```should_panic
/// use cool_asserts::assert_panics;
///
/// assert_panics!(1 + 2);
/// ```
///
/// # Substring checking
///
/// Optionally, provide a list of conditions of the form `includes(pattern)`
/// or `excludes(pattern)`. If given, the assertion will check that the
/// panic message contains or does not contain each of the given patterns.
/// It uses [`str::contains`], which means that anything
/// implementing [`Pattern`][::std::str::Pattern] can be used as a matcher.
///
/// ## Examples
///
/// ```
/// use cool_asserts::assert_panics;
///
/// assert_panics!(
///     panic!("Custom message: {}", "message"),
///     includes("message: message"),
///     includes("Custom"),
///     excludes("Foo"),
/// );
/// ```
///
/// ```should_panic
/// // THIS EXAMPLE PANICS
///
/// use cool_asserts::assert_panics;
///
/// // The expression panics, which passes the assertion, but it fails
/// // the message test, which means the overall assertion fails.
/// assert_panics!(
///     panic!("Message"),
///     excludes("Message")
/// );
/// ```
///
/// # Generic message testing
///
/// If the `includes(..)` and `excludes(..)` are not powerful enough,
/// `assert_panics` can also accept a closure as an argument. If the expression
/// panics, the closure is called with the panic message as an `&str`. This
/// closure can contain any additional assertions you wish to perform on the
/// panic message.
///
/// ## Examples
///
/// ```
/// use cool_asserts::assert_panics;
///
/// assert_panics!(panic!("{}, {}!", "Hello", "World"), |msg| {
///     assert_eq!(msg, "Hello, World!")
/// });
/// ```
/// ```
/// use cool_asserts::assert_panics;
///
/// assert_panics!(
///     assert_panics!(
///         panic!("Message"),
///         |msg| panic!("Custom Message")
///     ),
///     includes("Custom Message"),
///     excludes("assertion failed")
/// )
/// ```
///
/// # Generic panic values
///
/// If you need to test panics that aren't event messages– that is, that aren't
/// [`String`] or `&str` values provided by most panics (including most
/// assertions)– you can provide a reference type in the closure. The macro
/// will attermpt to cast the panic value to that type. It will fail the
/// assertion if the type doesn't match; otherwise the closure will be called.
///
/// ```
/// use cool_asserts::assert_panics;
///
/// assert_panics!(panic!(10i64), |value: &i64| {
///     assert_eq!(value, &10);
/// })
/// ```
///
/// ```
/// use cool_asserts::assert_panics;
///
/// assert_panics!(
///     assert_panics!(
///         panic!(10i64),
///         |value: &i32| {
///             panic!("CUSTOM PANIC");
///         }
///     ),
///     includes("expression panic type mismatch"),
///     includes("i32"),
///     // Currently, type_name of Any returns &dyn Any, rather than the actual type
///     // includes("i64"),
///     excludes("expression didn't panic"),
///     excludes("CUSTOM PANIC")
/// );
/// ```
#[macro_export]
macro_rules! assert_panics {
    ($expression:expr, |$panic:ident: Box<$(dyn)? Any $(+ Send)? $(+ 'static)?>| $body:expr) => (
        match ::std::panic::catch_unwind(|| {$expression}) {
            Ok(result) => $crate::assertion_failure!(
                "expression didn't panic",
                expression: stringify!($expression),
                returned debug: result
            ),
            Err($panic) => {
                $body
            }
        }
    );

    ($expression:expr, |$msg:ident $(: &str)?| $body:expr) => (
        $crate::assert_panics!($expression, |panic: Box<dyn Any>| {
            let $msg: &str = $crate::get_panic_message(&panic)
                .unwrap_or_else(|| $crate::assertion_failure!(
                    "expression panic type wasn't String or &str",
                    expression: stringify!($expression),
                ));

            { $body }
        })
    );

    ($expression:expr, |$value:ident: &$type:ty| $body:expr) => (
        $crate::assert_panics!($expression, |panic: Box<dyn Any>| {
            fn ref_type_name<T: ?Sized>(_value: &T) -> &'static str {
                ::core::any::type_name::<T>()
            }

            let $value: &$type = panic.downcast_ref()
                .unwrap_or_else(|| $crate::assertion_failure!(
                    "expression panic type mismatch",
                    expression: stringify!($expression),
                    expected: stringify!($type),
                    actual: ref_type_name(&panic),
                )
            );
            { $body }
        })
    );

    ($expression:expr $(,)?) => (
        $crate::assert_panics!($expression, |_panic: Box<dyn Any>| {})
    );


    ($expression:expr $(, $rule:ident($arg:expr))+ $(,)?) => {
        $crate::assert_panics!($expression, |msg| {
            $($crate::check_rule!($expression, msg, $rule($arg));)+
        })
    }
}

#[macro_export]
#[doc(hidden)]
macro_rules! check_rule {
    ($expression:expr, $msg:ident, includes($incl:expr)) => (
        if !$msg.contains($incl) {
            $crate::assertion_failure!(
                "panic message didn't include expected string",
                expression: stringify!($expression),
                message debug: $msg,
                expected debug: $incl,
            );
        }
    );

    ($expression:expr, $msg:ident, excludes($excl:expr)) => (
        if $msg.contains($excl) {
            $crate::assertion_failure!(
                "panic message included disallowed string",
                expression: stringify!($expression),
                message debug: $msg,
                disallowed debug: $excl,
            );
        }
    );
}

#[cfg(test)]
mod test_assert_panics {
    use super::assert_panics;
    mod bootstrap_tests {
        use super::assert_panics;

        // We use a few should_panic tests to bootstrap– ensure that assert_panics
        // basically works– then we do the more complex testing with itself.
        // If all these tests pass, assert_panics has at least enough working
        // that it can test itself more thoroughly.
        #[test]
        fn passes_with_panic() {
            assert_panics!(panic!());
        }

        #[test]
        #[should_panic(expected="expression didn't panic")]
        fn fails_without_panic() {
            assert_panics!(1 + 1);
        }

        #[test]
        #[should_panic(expected="panic message didn't include expected string")]
        fn fails_without_substring() {
            assert_panics!(panic!("{} {}", "This", "Message"), includes("That Message"))
        }

        #[test]
        #[should_panic(expected="panic message included disallowed string")]
        fn fails_with_substring() {
            assert_panics!(panic!("{} {}", "This", "Message"), excludes("Message"))
        }
    }

    #[test]
    fn fails_without_panic() {
        assert_panics!(
            assert_panics!(1 + 1),
            includes("assertion failed at"),
            includes("expression didn't panic"),
            includes("expression: 1 + 1"),
            includes("returned: 2")
        );
    }

    #[test]
    fn fails_without_substring() {
        assert_panics!(
            assert_panics!(
                panic!("{} {}", "This", "Message"),
                includes("That Message")
            ),
            includes("assertion failed at"),
            excludes("expression didn't panic"),
            includes("panic message didn't include expected string"),
            includes("expression: panic!(\"{} {}\", \"This\", \"Message\")"),
            includes("message: \"This Message\""),
            includes("expected: \"That Message\""),
        );
    }

    #[test]
    fn fails_with_substring() {
        assert_panics!(
            assert_panics!(
                panic!("{} {}", "This", "Message"),
                excludes("Message")
            ),
            includes("assertion failed at"),
            excludes("expression didn't panic"),
            includes("panic message included disallowed string"),
            includes("expression: panic!(\"{} {}\", \"This\", \"Message\")"),
            includes("message: \"This Message\""),
            includes("disallowed: \"Message\""),
        );
    }

    #[test]
    fn string_closure() {
        assert_panics!(panic!("{}, {}!", "Hello", "World"), |msg| {
            assert_eq!(msg, "Hello, World!");
        })
    }

    #[test]
    fn str_closure() {
        assert_panics!(panic!("Hello, World!"), |msg| {
            assert_eq!(msg, "Hello, World!");
        })
    }

    #[test]
    fn str_closure_mismatch() {
        assert_panics!(
            assert_panics!(panic!(32), |_msg| {
                panic!("CUSTOM PANIC");
            }),
            includes("assertion failed at"),
            includes("expression panic type wasn't String or &str"),
            excludes("CUSTOM PANIC")
        )
    }

    #[test]
    fn str_closure_panics() {
        assert_panics!(
            assert_panics!(panic!("Hello, World!"), |_msg| {
                panic!("NOPE");
            }),
            includes("NOPE"),
            excludes("Hello, World!"),
        );
    }

    #[test]
    fn typed_closure() {
        assert_panics!(panic!(244 as i32), |value: &i32| {
            assert_eq!(value, &244);
        })
    }

    #[test]
    fn typed_closure_mismatch() {
        assert_panics!(
            assert_panics!(panic!(244 as i32), |_value: &i64| {
                panic!("CUSTOM PANIC")
            }),
            excludes("CUSTOM PANIC"),
            includes("expression panic type mismatch"),
            includes("expression: panic!(244 as i32)"),
            includes("expected: i64"),
        );
    }
}