assert-rs 0.1.0

An assertion library that uses types and data to fail tests instead of panicking.
Documentation
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
use core::fmt::{Debug, Display};

use crate::AssertInfo;

#[cfg(feature = "std")]
#[must_use = "assertions do not fire unless returned from a test"]
/// An assertion that has been made about some object.
pub trait Assertion: Debug + Display + std::process::Termination {
    /// `true` if the assertion was true.
    fn test(&self) -> bool;

    /// Wrap the assertion in [`ShouldFail`], inverting its condition.
    fn should_fail(self) -> ShouldFail<Self>
    where
        Self: Sized,
    {
        ShouldFail(self)
    }

    /// Panic if the assertion was false.
    ///
    /// # Panics
    ///
    /// See above.
    #[allow(
        clippy::panic,
        reason = "I agree with you clippy, but some people don't care about panics."
    )]
    fn unwrap(&self) {
        assert!(self.test(), "failed assertion was unwrapped:\n{self}");
    }
}

#[cfg(not(feature = "std"))]
#[must_use = "assertions do not fire unless returned from a test"]
/// An assertion that has been made about some object.
pub trait Assertion: Debug + Display {
    /// `true` if the assertion was true.
    fn test(&self) -> bool;

    /// Wrap the assertion in [`ShouldFail`], inverting its condition.
    fn should_fail(self) -> ShouldFail<Self>
    where
        Self: Sized,
    {
        ShouldFail(self)
    }

    /// Panic if the assertion was false.
    ///
    /// # Panics
    ///
    /// See above.
    #[allow(
        clippy::panic,
        reason = "I agree with you clippy, but some people don't care about panics."
    )]
    fn unwrap(&self) {
        assert!(self.test(), "failed assertion was unwrapped:\n{self}");
    }
}

/// An assertion about two objects `lhs` and `rhs`.
#[must_use = "assertions do not fire unless returned from a test"]
pub struct BinaryAssertion<T, U> {
    lhs: T,
    rhs: U,
    test_result: bool,
    test_repr: &'static str,
    info: AssertInfo,
}

impl<T, U> Display for BinaryAssertion<T, U>
where
    T: Debug,
    U: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let Self {
            lhs,
            rhs,
            test_result: _,
            test_repr,
            info: AssertInfo { file, line, column },
        } = self;

        write!(
            f,
            "assertion starting at {file}:{line}:{column} failed: `{test_repr}`\n lhs: {lhs:?}\n rhs: {rhs:?}"
        )
    }
}

impl<T, U> Debug for BinaryAssertion<T, U>
where
    T: Debug,
    U: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        Display::fmt(self, f)
    }
}

impl<T, U> BinaryAssertion<T, U> {
    pub(crate) const fn new(
        lhs: T,
        rhs: U,
        test_result: bool,
        test_repr: &'static str,
        info: AssertInfo,
    ) -> Self {
        Self {
            lhs,
            rhs,
            test_result,
            test_repr,
            info,
        }
    }
}

#[cfg(feature = "std")]
impl<T, U> std::process::Termination for BinaryAssertion<T, U>
where
    T: Debug,
    U: Debug,
{
    fn report(self) -> std::process::ExitCode {
        if self.test() {
            std::process::ExitCode::SUCCESS
        } else {
            println!("{self}");
            std::process::ExitCode::FAILURE
        }
    }
}

impl<T, U> Assertion for BinaryAssertion<T, U>
where
    T: Debug,
    U: Debug,
{
    fn test(&self) -> bool {
        self.test_result
    }
}

/// An assertion about an object `this`.
#[must_use = "assertions do not fire unless returned from a test"]
pub struct UnaryAssertion<T> {
    this: T,
    test_result: bool,
    test_repr: &'static str,
    info: AssertInfo,
}

impl<T> Display for UnaryAssertion<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let Self {
            this,
            test_result: _,
            test_repr,
            info: AssertInfo { file, line, column },
        } = self;

        write!(
            f,
            "assertion starting at {file}:{line}:{column} failed: `{test_repr}`\nthis: {this:?}"
        )
    }
}

impl<T> Debug for UnaryAssertion<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        Display::fmt(self, f)
    }
}

impl<T> UnaryAssertion<T> {
    pub(crate) const fn new(
        this: T,
        test_result: bool,
        test_repr: &'static str,
        info: AssertInfo,
    ) -> Self {
        Self {
            this,
            test_result,
            test_repr,
            info,
        }
    }
}

#[cfg(feature = "std")]
impl<T> std::process::Termination for UnaryAssertion<T>
where
    T: Debug,
{
    fn report(self) -> std::process::ExitCode {
        if self.test() {
            std::process::ExitCode::SUCCESS
        } else {
            println!("{self}");
            std::process::ExitCode::FAILURE
        }
    }
}

impl<T> Assertion for UnaryAssertion<T>
where
    T: Debug,
{
    fn test(&self) -> bool {
        self.test_result
    }
}

/// An assertion that will unconditionally succeed.
#[must_use = "assertions do not fire unless returned from a test"]
pub struct Succeed {
    info: AssertInfo,
}

impl Display for Succeed {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let AssertInfo { file, line, column } = self.info;

        write!(
            f,
            "assertion starting at {file}:{line}:{column} was forced success"
        )
    }
}

impl Debug for Succeed {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        Display::fmt(self, f)
    }
}

impl Succeed {
    #[doc(hidden)]
    /// Don't use this constructor. Use [`succeed!`] instead.
    pub const fn manual_constructor(file: &'static str, line: u32, column: u32) -> Self {
        Self {
            info: AssertInfo { file, line, column },
        }
    }
}

#[cfg(feature = "std")]
impl std::process::Termination for Succeed {
    fn report(self) -> std::process::ExitCode {
        std::process::ExitCode::SUCCESS
    }
}

impl Assertion for Succeed {
    fn test(&self) -> bool {
        true
    }
}

/// Construct an [`Assertion`] that will always succeed.
///
/// ```no_run
/// #[test]
/// fn succeed() -> impl Assertion {
///     succeed!()
/// }
/// ```
#[macro_export]
macro_rules! succeed {
    () => {
        $crate::assertion::Succeed::manual_constructor(
            ::core::file!(),
            ::core::line!(),
            ::core::column!(),
        )
    };
}

/// An assertion that will unconditionally fail.
#[must_use = "assertions do not fire unless returned from a test"]
pub struct Fail {
    info: AssertInfo,
}

impl Display for Fail {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let AssertInfo { file, line, column } = self.info;

        write!(
            f,
            "assertion starting at {file}:{line}:{column} was forced fail"
        )
    }
}

impl Debug for Fail {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        Display::fmt(self, f)
    }
}

impl Fail {
    #[doc(hidden)]
    /// Don't use this constructor. Use [`fail!`] instead.
    pub const fn manual_constructor(file: &'static str, line: u32, column: u32) -> Self {
        Self {
            info: AssertInfo { file, line, column },
        }
    }
}

#[cfg(feature = "std")]
impl std::process::Termination for Fail {
    fn report(self) -> std::process::ExitCode {
        std::process::ExitCode::FAILURE
    }
}

impl Assertion for Fail {
    fn test(&self) -> bool {
        false
    }
}

/// Construct an [`Assertion`] that will always fail.
///
/// ```no_run
/// #[test]
/// fn fail() -> impl Assertion {
///     fail!().should_fail()
/// }
/// ```
#[macro_export]
macro_rules! fail {
    () => {
        $crate::assertion::Fail::manual_constructor(
            ::core::file!(),
            ::core::line!(),
            ::core::column!(),
        )
    };
}

/// An assertion that will fail if the given assertion was true
/// and succeed if the given assertion was false.
pub struct ShouldFail<A: Assertion>(A);

impl<A: Assertion> Display for ShouldFail<A> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let inner = &self.0;
        write!(f, "assertion expected to fail succeeded:\n{inner}")
    }
}

#[cfg(feature = "std")]
impl<A: Assertion> std::process::Termination for ShouldFail<A> {
    fn report(self) -> std::process::ExitCode {
        if self.0.test() {
            println!("{self}");
            std::process::ExitCode::FAILURE
        } else {
            std::process::ExitCode::SUCCESS
        }
    }
}

impl<A: Assertion> Assertion for ShouldFail<A> {
    fn test(&self) -> bool {
        !self.0.test()
    }
}

impl<A: Assertion> Debug for ShouldFail<A> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        Display::fmt(self, f)
    }
}

#[cfg(feature = "alloc")]
pub use multi_dyn_assertion::MultiDynAssertion;

#[cfg(feature = "alloc")]
mod multi_dyn_assertion {
    use super::{Assertion, Debug, Display};

    extern crate alloc;
    use alloc::boxed::Box;

    /// A group of assertions, possibly of different types, all tested simultaneously.
    ///
    /// These can be created using the [`multi_assert!`](crate::multi_assert) macro.
    /// See its docs for more.
    pub struct MultiDynAssertion<const N: usize>([Box<dyn Assertion>; N]);

    impl<const N: usize> Display for MultiDynAssertion<N> {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            write!(f, "assertion failures in a multi-assert:")?;
            for (i, assertion) in self.0.iter().enumerate() {
                if assertion.test() {
                    write!(f, "\n{i}. [ok]")?;
                } else {
                    writeln!(f, "\n{i}. {assertion}")?;
                }
            }
            Ok(())
        }
    }

    impl<const N: usize> MultiDynAssertion<N> {
        #[must_use]
        #[doc(hidden)]
        /// You can use [`multi_assert!`](crate::multi_assert) with `#[dyn]` instead, but it's not required.
        pub fn new(assertions: [Box<dyn Assertion>; N]) -> Self {
            Self(assertions)
        }
    }

    #[cfg(feature = "std")]
    impl<const N: usize> std::process::Termination for MultiDynAssertion<N> {
        fn report(self) -> std::process::ExitCode {
            if self.test() {
                std::process::ExitCode::SUCCESS
            } else {
                println!("{self}");
                std::process::ExitCode::FAILURE
            }
        }
    }

    impl<const N: usize> Assertion for MultiDynAssertion<N> {
        fn test(&self) -> bool {
            self.0.iter().all(|a| a.test())
        }
    }

    impl<const N: usize> Debug for MultiDynAssertion<N> {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            Display::fmt(self, f)
        }
    }
}

/// A group of assertions, all tested simultaneously.
///
/// These can be created using the [`multi_assert!`](crate::multi_assert) macro.
/// See its docs for more.
pub struct MultiAssertion<A: Assertion, const N: usize>([A; N]);

impl<A: Assertion, const N: usize> Display for MultiAssertion<A, N> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "assertion failures in a multi-assert:")?;
        for (i, assertion) in self.0.iter().enumerate() {
            if assertion.test() {
                write!(f, "\n{i}. [ok]")?;
            } else {
                writeln!(f, "\n{i}. {assertion}")?;
            }
        }
        Ok(())
    }
}

impl<A: Assertion, const N: usize> MultiAssertion<A, N> {
    #[must_use]
    /// You can use [`multi_assert!`](crate::multi_assert) instead, but it's not required.
    pub const fn new(assertions: [A; N]) -> Self {
        Self(assertions)
    }
}

#[cfg(feature = "std")]
impl<A: Assertion, const N: usize> std::process::Termination for MultiAssertion<A, N> {
    fn report(self) -> std::process::ExitCode {
        if self.test() {
            std::process::ExitCode::SUCCESS
        } else {
            println!("{self}");
            std::process::ExitCode::FAILURE
        }
    }
}

impl<A: Assertion, const N: usize> Assertion for MultiAssertion<A, N> {
    fn test(&self) -> bool {
        self.0.iter().all(Assertion::test)
    }
}

impl<A: Assertion, const N: usize> Debug for MultiAssertion<A, N> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        Display::fmt(self, f)
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(doc, doc = include_str!("multi_assert_doc.md"))]
#[macro_export]
macro_rules! multi_assert {
    [#[dyn] $($this:expr),+ $(,)?] => {
        $crate::assertion::MultiDynAssertion::new([
            $(Box::new($this),)+
        ])
    };
    [$($this:expr),+ $(,)?] => {
        $crate::assertion::MultiAssertion::new([
            $($this,)+
        ])
    };
}

#[cfg(not(feature = "alloc"))]
#[cfg_attr(doc, doc = include_str!("multi_assert_doc.md"))]
#[macro_export]
macro_rules! multi_assert {
    [#[dyn] $($this:expr),+ $(,)?] => {
        compile_error!("cannot use #[dyn] if the no_alloc feature is enabled")
    };
    [$($this:expr),+ $(,)?] => {
        $crate::assertion::MultiAssertion::new([
            $($this,)+
        ])
    };
}