assertr 0.5.5

Fluent assertions for the Rust programming language.
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
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
#![cfg_attr(not(feature = "std"), no_std)]
// Allow functions named `is_*`, taking self by value instead of taking self by mutable reference or reference.
#![allow(clippy::wrong_self_convention)]

extern crate alloc;
extern crate core;

use actual::Actual;
use alloc::{borrow::ToOwned, boxed::Box, format, string::String, vec::Vec};
use core::{
    any::Any,
    cell::RefCell,
    fmt::{Debug, Formatter},
    future::Future,
    panic::{RefUnwindSafe, UnwindSafe},
};
use details::WithDetail;
use failure::Fallible;
use mode::{Capture, Mode, Panic};
use std::marker::PhantomData;
use tracking::{AssertionTracking, NumberOfAssertions};

pub mod actual;
#[doc(hidden)]
pub mod assert_that_macro;
pub mod assertions;
pub mod cmp;
pub mod condition;
mod conversion;
pub mod details;
pub mod failure;
pub mod mode;
pub mod tracking;
pub mod util;

pub mod prelude {
    #[cfg(feature = "derive")]
    pub use assertr_derive::AssertrEq;

    pub use crate::AssertThat;
    #[cfg(feature = "fluent")]
    pub use crate::IntoAssertContext;
    pub use crate::any;
    #[allow(deprecated)]
    pub use crate::assert_that;
    #[allow(deprecated)]
    pub use crate::assert_that_owned;
    #[cfg(feature = "std")]
    pub use crate::assert_that_panic_by;
    #[cfg(feature = "std")]
    pub use crate::assert_that_panic_by_async;
    pub use crate::assert_that_type;
    pub use crate::assertions::HasLength;
    pub use crate::assertions::alloc::prelude::*;
    pub use crate::assertions::condition::ConditionAssertions;
    pub use crate::assertions::condition::IterableConditionAssertions;
    pub use crate::assertions::core::prelude::*;
    #[cfg(feature = "http")]
    pub use crate::assertions::http::prelude::*;
    #[cfg(feature = "jiff")]
    pub use crate::assertions::jiff::prelude::*;
    #[cfg(feature = "num")]
    pub use crate::assertions::num::NumAssertions;
    #[cfg(feature = "program")]
    pub use crate::assertions::program::Program;
    #[cfg(feature = "program")]
    pub use crate::assertions::program::ProgramAssertions;
    #[cfg(feature = "program")]
    pub use crate::assertions::program::ProgramAssertionsRequiringPanicMode;
    #[cfg(feature = "reqwest")]
    pub use crate::assertions::reqwest::prelude::*;
    #[cfg(feature = "rootcause")]
    pub use crate::assertions::rootcause::prelude::*;
    #[cfg(feature = "std")]
    pub use crate::assertions::std::prelude::*;
    #[cfg(feature = "tokio")]
    pub use crate::assertions::tokio::prelude::*;
    pub use crate::condition::Condition;
    #[cfg(feature = "serde")]
    pub use crate::conversion::json;
    #[cfg(feature = "serde")]
    pub use crate::conversion::toml;
    pub use crate::eq;
    pub use crate::mode::Mode;
}

pub struct PanicValue(Box<dyn Any>);

/// The main entrypoint into an assertion context for borrowed values.
///
/// Borrows the value, allowing it to be used after the assertion.
///
/// #### Example Usage
/// ```rust,no_run
/// use assertr::prelude::*;
///
/// // This will panic with a descriptive message and a pointer to the actual line of the assertion.
/// assert_that(&3).is_equal_to(4);
///
/// // This instead captures the assertion failure for later inspection.
/// let failures = assert_that(&3)
///     .with_capture()
///     .is_equal_to(4) // This will collect a failure instead of panicking.
///     .capture_failures();
///
/// assert_that(&failures)
///     .has_length(1)
///     .contains("");
/// ```
#[deprecated(
    since = "0.4.4",
    note = "Use the `assert_that!()` macro or the fluent `.must()` / `.verify()` entry points instead."
)]
#[track_caller]
#[must_use]
pub fn assert_that<T>(actual: &T) -> AssertThat<'_, T, Panic> {
    AssertThat::new_panicking(Actual::Borrowed(actual))
}

/// Entrypoint into an assertion context that takes ownership of the value.
///
/// Use this when the assertion requires ownership (e.g. `FnOnce` assertions).
/// For most cases, prefer [`assert_that()`] which borrows instead.
#[deprecated(
    since = "0.4.4",
    note = "Use the `assert_that!()` macro or the fluent `.must_owned()` / `.verify_owned()` entry points instead."
)]
#[track_caller]
#[must_use]
pub fn assert_that_owned<'t, T>(actual: T) -> AssertThat<'t, T, Panic> {
    AssertThat::new_panicking(Actual::Owned(actual))
}

/// Ergonomic macro entrypoint that handles both owned values and references.
///
/// Uses autoref specialization to transparently handle both
/// `assert_that!(owned_value)` and `assert_that!(&borrowed_value)` without
/// requiring the user to think about ownership.
#[macro_export]
macro_rules! assert_that {
    ($e:expr) => {
        $crate::assert_that_macro::Wrap {
            inner: $crate::assert_that_macro::Fallback(core::cell::Cell::new(Some($e))),
        }
        .into_assert_that()
    };
}

#[cfg(feature = "fluent")]
pub trait IntoAssertContext<'t, T> {
    #[must_use]
    fn must(&'t self) -> AssertThat<'t, T, Panic>;
    #[must_use]
    fn must_owned(self) -> AssertThat<'t, T, Panic>;

    #[must_use]
    fn verify(&'t self) -> AssertThat<'t, T, Capture>;
    #[must_use]
    fn verify_owned(self) -> AssertThat<'t, T, Capture>;
}

#[cfg(feature = "fluent")]
impl<'t, T> IntoAssertContext<'t, T> for T {
    fn must(&'t self) -> AssertThat<'t, T, Panic> {
        AssertThat::new_panicking(Actual::Borrowed(self))
    }
    fn must_owned(self) -> AssertThat<'t, T, Panic> {
        AssertThat::new_panicking(Actual::Owned(self))
    }

    fn verify(&'t self) -> AssertThat<'t, T, Capture> {
        AssertThat::new_capturing(Actual::Borrowed(self))
    }
    fn verify_owned(self) -> AssertThat<'t, T, Capture> {
        AssertThat::new_capturing(Actual::Owned(self))
    }
}

#[cfg(feature = "fluent")]
impl<'t, T> IntoAssertContext<'t, T> for &'t T {
    fn must(&'t self) -> AssertThat<'t, T, Panic> {
        AssertThat::new_panicking(Actual::Borrowed(self))
    }
    fn must_owned(self) -> AssertThat<'t, T, Panic> {
        AssertThat::new_panicking(Actual::Borrowed(self))
    }

    fn verify(&'t self) -> AssertThat<'t, T, Capture> {
        AssertThat::new_capturing(Actual::Borrowed(self))
    }
    fn verify_owned(self) -> AssertThat<'t, T, Capture> {
        AssertThat::new_capturing(Actual::Borrowed(self))
    }
}

#[cfg(feature = "fluent")]
impl<'t, T> IntoAssertContext<'t, T> for &'t mut T {
    fn must(&'t self) -> AssertThat<'t, T, Panic> {
        AssertThat::new_panicking(Actual::Borrowed(self))
    }
    fn must_owned(self) -> AssertThat<'t, T, Panic> {
        AssertThat::new_panicking(Actual::Borrowed(self))
    }

    fn verify(&'t self) -> AssertThat<'t, T, Capture> {
        AssertThat::new_capturing(Actual::Borrowed(self))
    }
    fn verify_owned(self) -> AssertThat<'t, T, Capture> {
        AssertThat::new_capturing(Actual::Borrowed(self))
    }
}

#[track_caller]
#[must_use]
#[cfg(feature = "std")]
#[allow(deprecated)]
pub fn assert_that_panic_by<'t, R>(
    fun: impl FnOnce() -> R + 't,
) -> AssertThat<'t, PanicValue, Panic> {
    use crate::prelude::FnOnceAssertions;

    assert_that_owned(fun).panics()
}

// #[track_caller] // This is implied in the default async desugaring.
#[must_use]
#[cfg(feature = "std")]
#[allow(deprecated)]
pub async fn assert_that_panic_by_async<'t, F, Fut, R>(fun: F) -> AssertThat<'t, PanicValue, Panic>
where
    F: FnOnce() -> Fut + 't,
    Fut: Future<Output = R> + UnwindSafe,
{
    use crate::prelude::AsyncFnOnceAssertions;

    assert_that_owned(fun).panics_async().await
}

pub struct Type<T> {
    phantom: PhantomData<T>,
}

impl<T> Type<T> {
    #[must_use]
    pub fn new() -> Self {
        Self {
            phantom: PhantomData,
        }
    }

    #[must_use]
    pub fn get_type_name(&self) -> &'static str {
        std::any::type_name::<T>()
    }

    #[must_use]
    pub fn needs_drop(&self) -> bool {
        std::mem::needs_drop::<T>()
    }

    #[must_use]
    pub fn size(&self) -> usize {
        size_of::<T>()
    }
}

impl<T> Default for Type<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[must_use]
pub fn assert_that_type<T>() -> AssertThat<'static, Type<T>, Panic> {
    AssertThat::new_panicking(Actual::Owned(Type::<T>::new()))
}

/// `AssertThat` is the core structure used for assertions. It allows developers to perform
/// assertions on actual values in a fluent and expressive manner, supporting detailed messages
/// as well as different modes of operation, such as panic or capture modes.
///
/// ### Type Parameters
/// - `'t`: The lifetime of the actual value being asserted.
/// - `T`: The type of the actual value being asserted.
/// - `M`: The assertion mode, implementing the [`Mode`] trait. Examples include `Panic` and `Capture` modes.
///
/// ### Fields
/// - `parent`: A reference to the parent assertion, if this is a derived assertion. Failures will propagate to the root assertion.
/// - `actual`: The value being asserted against.
/// - `subject_name`: An optional subject name for the assertion, allowing for more descriptive error messages.
/// - `detail_messages`: A collection of additional messages that provide context for the assertion.
/// - `print_location`: A boolean indicating whether the source code location of the assertion should be printed on failure.
/// - `number_of_assertions`: Tracks the number of assertions made.
/// - `failures`: A collection of failure messages for assertions in `Capture` mode.
/// - `mode`: The mode used for this assertion, determining behavior on failure.
///
/// ### Key Features
/// - **Fluent API**: Chainable and composable methods for making expressive assertions.
/// - **Detail Messages**: Add custom messages to provide context for failures.
/// - **Modes**:
///     - **Panic Mode**: The default mode where failures result in immediate panics.
///     - **Capture Mode**: Collect failures instead of panicking, useful for batch processing scenarios.
/// - **Derived Assertions**: Assertions derived from parent assertions, facilitating nested or mapped assertions.
///
/// ### Notes
/// - When using `Capture` mode, failures must be captured explicitly.
/// - This struct is designed to handle both simple and complex assertion chaining scenarios.
pub struct AssertThat<'t, T, M: Mode> {
    // Derived assertions can be created. Calling `.fail*` on them should propagate to the root assertion!
    parent: Option<&'t dyn DynAssertThat>,

    actual: Actual<'t, T>,

    subject_name: Option<String>,
    detail_messages: RefCell<Vec<String>>,
    print_location: bool,

    number_of_assertions: RefCell<NumberOfAssertions>,
    failures: RefCell<Vec<String>>,

    mode: RefCell<M>,
}

pub(crate) trait DynAssertThat:
    Fallible + WithDetail + AssertionTracking + UnwindSafe + RefUnwindSafe
{
}
impl<T, M: Mode> DynAssertThat for AssertThat<'_, T, M> {}

impl<T, M: Mode> UnwindSafe for AssertThat<'_, T, M> {}
impl<T, M: Mode> RefUnwindSafe for AssertThat<'_, T, M> {}

impl<'t, T> AssertThat<'t, T, Panic> {
    #[track_caller]
    pub(crate) const fn new_panicking(actual: Actual<'t, T>) -> Self {
        AssertThat {
            parent: None,
            actual,
            subject_name: None,
            detail_messages: RefCell::new(Vec::new()),
            print_location: true,
            number_of_assertions: RefCell::new(NumberOfAssertions::new()),
            failures: RefCell::new(Vec::new()),
            mode: RefCell::new(Panic::DEFAULT),
        }
    }
}

#[cfg(feature = "fluent")]
impl<'t, T> AssertThat<'t, T, Capture> {
    #[track_caller]
    pub(crate) const fn new_capturing(actual: Actual<'t, T>) -> Self {
        AssertThat {
            parent: None,
            actual,
            subject_name: None,
            detail_messages: RefCell::new(Vec::new()),
            print_location: true,
            number_of_assertions: RefCell::new(NumberOfAssertions::new()),
            failures: RefCell::new(Vec::new()),
            mode: RefCell::new(Capture::DEFAULT),
        }
    }
}

impl<T> AssertThat<'_, T, Capture> {
    /// Extracts all assertion failures captured until now.
    ///
    /// Allows this `AssertThat` to be dropped again without raising a panic.
    ///
    /// ```rust
    /// use assertr::prelude::*;
    ///
    /// let failures = 42.verify()
    ///     .be_negative()
    ///     .be_equal_to(43)
    ///     .capture_failures();
    ///
    /// failures.must().have_length(2);
    /// ```
    #[must_use]
    pub fn capture_failures(mut self) -> Vec<String> {
        self.take_failures()
    }

    /// Extracts all assertion failures captured until now.
    ///
    /// Allows this `AssertThat` to be dropped again without raising a panic.
    ///
    /// **Prefer `capture_failures` if you don't require ownership after extraction.**
    ///
    /// # Panics
    ///
    /// Panics if failures have already been captured.
    #[must_use]
    pub fn take_failures(&mut self) -> Vec<String> {
        let mut mode = self.mode.borrow_mut();
        assert!(
            !mode.captured,
            "You can only capture the assertion failures once!"
        );
        mode.captured = true;
        self.failures.take()
    }
}

impl<'t, T, M: Mode> AssertThat<'t, T, M> {
    pub fn actual(&self) -> &T {
        self.actual.borrowed()
    }

    pub(crate) fn replace_actual_with<'u, U>(
        self,
        // Note: Not using an explicit generic typename allows calls like `.map<String>(...)`,
        // requiring only one type, which is the type we want to map to.
        new_actual: Actual<'u, U>,
    ) -> (Actual<'t, T>, AssertThat<'u, U, M>)
    where
        't: 'u,
    {
        let previous_actual: Actual<'t, T> = self.actual;
        let mapped = AssertThat {
            parent: self.parent,
            actual: new_actual,
            subject_name: self.subject_name, // We cannot clone self.subject_name, as the mapper produces what has to be considered a "new" subject!
            detail_messages: self.detail_messages,
            print_location: self.print_location,
            number_of_assertions: self.number_of_assertions,
            failures: self.failures,
            mode: self.mode,
        };
        (previous_actual, mapped)
    }

    pub fn map<U>(
        self,
        // Note: Not using an explicit generic typename allows calls like `.map<String>(...)`,
        // requiring only one type, which is the type we want to map to.
        mapper: impl FnOnce(Actual<T>) -> Actual<U>,
    ) -> AssertThat<'t, U, M> {
        AssertThat {
            parent: self.parent,
            actual: mapper(self.actual),
            subject_name: self.subject_name, // We cannot clone self.subject_name, as the mapper produces what has to be considered a "new" subject!
            detail_messages: self.detail_messages,
            print_location: self.print_location,
            number_of_assertions: self.number_of_assertions,
            failures: self.failures,
            mode: self.mode,
        }
    }

    pub fn map_owned<U>(
        self,
        // Note: Not using an explicit generic typename allows calls like `.map<String>(...)`,
        // requiring only one type, which is the type we want to map to.
        mapper: impl FnOnce(<T as ToOwned>::Owned) -> U,
    ) -> AssertThat<'t, U, M>
    where
        T: ToOwned,
    {
        AssertThat {
            parent: self.parent,
            actual: Actual::Owned(mapper(self.actual.borrowed().to_owned())),
            subject_name: self.subject_name, // We cannot clone self.subject_name, as the mapper produces what has to be considered a "new" subject!
            detail_messages: self.detail_messages,
            print_location: self.print_location,
            number_of_assertions: self.number_of_assertions,
            failures: self.failures,
            mode: self.mode,
        }
    }

    pub async fn map_async<U: 't, Fut>(
        self,
        // Note: Not using an explicit generic typename allows calls like `.map<String>(...)`,
        // requiring only one type, which is the type we want to map to.
        mapper: impl FnOnce(Actual<T>) -> Fut,
    ) -> AssertThat<'t, U, M>
    where
        Fut: Future<Output = U>,
    {
        AssertThat {
            parent: self.parent,
            actual: mapper(self.actual).await.into(),
            subject_name: self.subject_name, // We cannot clone self.subject_name, as the mapper produces what has to be considered a "new" subject!
            detail_messages: self.detail_messages,
            print_location: self.print_location,
            number_of_assertions: self.number_of_assertions,
            failures: self.failures,
            mode: self.mode,
        }
    }

    pub fn derive<'u, U: 'u>(&'t self, mapper: impl FnOnce(&'t T) -> U) -> AssertThat<'u, U, M>
    where
        't: 'u,
    {
        let mut mode = self.mode.replace(M::default());
        mode.set_derived();

        AssertThat {
            parent: Some(self),
            actual: Actual::Owned(mapper(self.actual())),
            subject_name: None, // We cannot clone self.subject_name, as the mapper produces what has to be considered a "new" subject!
            detail_messages: RefCell::new(Vec::new()),
            print_location: self.print_location,
            number_of_assertions: RefCell::new(NumberOfAssertions::new()),
            failures: RefCell::new(Vec::new()),
            mode: RefCell::new(mode),
        }
    }

    pub async fn derive_async<'u, U: 'u, Fut: Future<Output = U>>(
        &'t self,
        mapper: impl FnOnce(&'t T) -> Fut,
    ) -> AssertThat<'u, U, M>
    where
        't: 'u,
    {
        let mut mode = self.mode.replace(M::default());
        mode.set_derived();

        AssertThat {
            parent: Some(self),
            actual: Actual::Owned(mapper(self.actual()).await),
            subject_name: None, // We cannot clone self.subject_name, as the mapper produces what has to be considered a "new" subject!
            detail_messages: RefCell::new(Vec::new()),
            print_location: self.print_location,
            number_of_assertions: RefCell::new(NumberOfAssertions::new()),
            failures: RefCell::new(Vec::new()),
            mode: RefCell::new(mode),
        }
    }

    // It would be nice to optimize this, so that:
    // - we do not need satisfies and satisfies_ref
    // - we use a `for<'a: 'b, 'b>` (see https://users.rust-lang.org/t/why-cant-i-use-lifetime-bounds-in-hrtbs/97277/2) bound for F and A,
    //   telling the compiler that the returned values live shorter than the input.
    // - we can replace () with some type R (return), letting the user write more succinct closures.

    #[allow(clippy::return_self_not_must_use)]
    #[allow(clippy::return_self_not_must_use)]
    pub fn satisfies<U, F, A>(self, mapper: F, assertions: A) -> Self
    where
        for<'a> F: FnOnce(&'a T) -> U,
        for<'a> A: FnOnce(AssertThat<'a, U, M>),
    {
        assertions(self.derive(mapper));
        self
    }

    #[cfg(feature = "fluent")]
    #[allow(clippy::return_self_not_must_use)]
    pub fn satisfy<U, F, A>(self, mapper: F, assertions: A) -> Self
    where
        for<'a> F: FnOnce(&'a T) -> U,
        for<'a> A: FnOnce(AssertThat<'a, U, M>),
    {
        self.satisfies(mapper, assertions)
    }

    #[allow(clippy::return_self_not_must_use)]
    pub fn satisfies_ref<U: ?Sized, F, A>(self, mapper: F, assertions: A) -> Self
    where
        for<'a> F: FnOnce(&'a T) -> &'a U,
        for<'a> A: FnOnce(AssertThat<'a, &'a U, M>),
    {
        assertions(self.derive(mapper));
        self
    }

    /// Gives the `actual` value contained in this assertion a descriptive name.
    /// This name will be part of panic messages when set.
    #[allow(dead_code)]
    #[must_use]
    pub fn with_subject_name(mut self, subject_name: impl Into<String>) -> Self {
        self.subject_name = Some(subject_name.into());
        self
    }

    /// Control whether the location (file, line and column) is shown on assertion failure.
    ///
    /// It can be helpful to call `.with_location(false)` when you want to test a panic message
    /// for exact equality and do not want to be bothered by constantly differing line and column
    /// numbers for the assert-location.
    #[allow(dead_code)]
    #[must_use]
    pub fn with_location(mut self, value: bool) -> Self {
        self.print_location = value;
        self
    }
}

/* Fluent connect */

impl<T, M: Mode> AssertThat<'_, T, M> {
    /// Filler that allows you to add an "and" inside your assertion chain.
    ///
    /// This is completely optional (noop).
    ///
    /// ```
    /// use assertr::prelude::*;
    ///
    /// 42.must().be_positive().and().be_less_than(100);
    /// 42.must().be_positive().be_less_than(100);
    ///
    /// assert_that!(42).is_positive().and().is_less_than(100);
    /// assert_that!(42).is_positive().is_less_than(100);
    /// ```
    #[inline]
    #[allow(clippy::return_self_not_must_use)]
    pub fn and(self) -> Self {
        self
    }
}

/* Mode changes */

impl<'t, T> AssertThat<'t, T, Panic> {
    /// Control whether the location is shown on assertion failure.
    ///
    /// It can be helpful to call `.with_location(false)` when you want to test the panic message for exact equality
    /// and do not want to be bothered by constantly differing line and column numbers fo the assert-location.
    #[allow(dead_code)]
    pub fn with_capture(self) -> AssertThat<'t, T, Capture> {
        AssertThat {
            parent: self.parent,
            actual: self.actual,
            subject_name: self.subject_name,
            detail_messages: self.detail_messages,
            print_location: self.print_location,
            number_of_assertions: self.number_of_assertions,
            failures: self.failures,
            mode: RefCell::new(Capture {
                derived: false,
                captured: false,
            }),
        }
    }
}

impl<'t, T> AssertThat<'t, T, Capture> {
    /// Switch to non-capturing mode.
    ///
    /// Panics if assertion failures were already captured!
    // TODO: Add an easy way in which users can check if assertion failures were recorded.
    //  Or that none were recorded!
    #[allow(deprecated)]
    pub fn without_capture(mut self) -> AssertThat<'t, T, Panic> {
        // Take out all assertion failures, marking the `Capture` as "captured".
        // Assert that no failures exist.
        use crate::assertions::core::length::LengthAssertions;
        assert_that_owned(self.take_failures())
            .with_location(self.print_location)
            .with_subject_name("Assertion failures")
            .with_detail_message(
                "You cannot unwrap the inner value if assertion failures were already recorded!",
            )
            .is_empty();

        AssertThat {
            parent: self.parent,
            actual: self.actual,
            subject_name: self.subject_name,
            detail_messages: self.detail_messages,
            print_location: self.print_location,
            number_of_assertions: self.number_of_assertions,
            failures: self.failures,
            mode: RefCell::new(Panic {
                derived: self.mode.borrow().derived,
            }),
        }
    }
}

/* Unwrapping */

impl<T> AssertThat<'_, T, Panic> {
    /// **Panics** Panics if the actual value was not owned.
    // TODO: We could relax this by having `AssertThat` be generic over the type of actual value.
    #[track_caller]
    pub fn unwrap_inner(self) -> T {
        self.actual.unwrap_owned()
    }
}

impl<T> AssertThat<'_, T, Capture> {
    /// **Panics**
    /// - If assertion errors are present.
    /// - If the actual value is not owned.
    // TODO: We could relax this by having `AssertThat` be generic over the type of actual value.
    #[track_caller]
    pub fn unwrap_inner(self) -> T {
        // Switch to panicking behaviour, asserting that no failures were recorded.
        let panicking = self.without_capture();

        panicking.actual.unwrap_owned()
    }
}

pub struct Differences {
    differences: Vec<String>,
}

impl Default for Differences {
    fn default() -> Self {
        Self::new()
    }
}

impl Differences {
    #[must_use]
    pub fn new() -> Self {
        Self {
            differences: Vec::new(),
        }
    }
}

impl Debug for Differences {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_list()
            .entries(self.differences.iter().map(|it| details::DisplayString(it)))
            .finish()
    }
}

pub struct EqContext {
    differences: Differences,
}

impl Default for EqContext {
    fn default() -> Self {
        Self::new()
    }
}

impl EqContext {
    #[must_use]
    pub fn new() -> Self {
        Self {
            differences: Differences::default(),
        }
    }

    pub fn add_difference(&mut self, difference: String) {
        self.differences.differences.push(difference);
    }

    pub fn add_field_difference(
        &mut self,
        field_name: &str,
        expected: impl Debug,
        actual: impl Debug,
    ) {
        self.differences.differences.push(format!(
            "\"{field_name}\": expected {expected:#?}, but was {actual:#?}"
        ));
    }
}

pub trait AssertrPartialEq<Rhs: ?Sized = Self> {
    /// This method tests for `self` and `other` values to be equal.
    #[must_use]
    fn eq(&self, other: &Rhs, ctx: Option<&mut EqContext>) -> bool;

    /// This method tests for `!=`. The default implementation is almost always
    /// sufficient, and should not be overridden without very good reason.
    #[must_use]
    fn ne(&self, other: &Rhs, ctx: Option<&mut EqContext>) -> bool {
        !self.eq(other, ctx)
    }
}

// AssertrPartialEq must be implemented for each type already being PartialEq,
// so that we can solely rely on, and call, this ctx-enabled version in our assertions.
impl<Rhs: ?Sized, T: PartialEq<Rhs>> AssertrPartialEq<Rhs> for T {
    fn eq(&self, other: &Rhs, _ctx: Option<&mut EqContext>) -> bool {
        PartialEq::eq(self, other)
    }
    fn ne(&self, other: &Rhs, _ctx: Option<&mut EqContext>) -> bool {
        PartialEq::ne(self, other)
    }
}

impl<T1: AssertrPartialEq<T2>, T2> AssertrPartialEq<[T2]> for [T1] {
    fn eq(&self, other: &[T2], mut ctx: Option<&mut EqContext>) -> bool {
        self.len() == other.len()
            && self.iter().enumerate().all(|(i, t1)| {
                other
                    .get(i)
                    .is_some_and(|t2| AssertrPartialEq::eq(t1, t2, ctx.as_deref_mut()))
            })
    }

    fn ne(&self, other: &[T2], ctx: Option<&mut EqContext>) -> bool {
        !Self::eq(self, other, ctx)
    }
}

// Note: T does not necessarily need to be `PartialEq`.
// T might itself be a type we want to compare using AssertrEq instead of PartialEq!
#[derive(Default)]
pub enum Eq<T> {
    #[default]
    Any,
    Eq(T),
}

pub fn eq<T>(v: T) -> Eq<T> {
    Eq::Eq(v)
}

#[must_use]
pub fn any<T>() -> Eq<T> {
    Eq::Any
}

impl<T: Debug> Debug for Eq<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            Eq::Any => f.write_str("Eq::Any"),
            Eq::Eq(v) => f.write_fmt(format_args!("Eq::Eq({v:?})")),
        }
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod tests {
    use alloc::format;
    use indoc::formatdoc;

    use crate::prelude::*;

    #[test]
    fn with_capture_yields_failures_and_does_not_panic() {
        let failures = 42
            .verify()
            .with_location(false)
            .be_greater_than(100)
            .be_equal_to(1)
            .capture_failures();

        assert_that!(failures.as_slice())
            .has_length(2)
            .contains_exactly([
                formatdoc! {"
                    -------- assertr --------
                    Actual: 42

                    is not greater than

                    Expected: 100
                    -------- assertr --------
                "},
                formatdoc! {"
                    -------- assertr --------
                    Expected: 1

                      Actual: 42
                    -------- assertr --------
                "},
            ]);
    }

    #[test]
    fn dropping_a_capturing_assert_panics_when_failures_occurred_which_were_not_captured() {
        let assert = 42.verify().with_location(false).be_equal_to(43);
        assert_that_panic_by(move || drop(assert))
            .has_type::<&str>()
            .is_equal_to("You dropped an `assert_that(..)` value, on which `.with_capture()` was called, without actually capturing the assertion failures using `.capture_failures()`!");
    }

    #[test]
    fn without_capture_switches_to_panic_mode() {
        let assert_capturing = assert_that_owned(42)
            .with_location(false)
            .with_capture()
            // Without this assertion, we would see a panic due to zero assertions being made.
            .is_equal_to(42);

        let _assert_panicking = assert_capturing.without_capture();
    }

    #[test]
    fn without_capture_panics_when_assertion_failures_were_already_recorded() {
        let assert_capturing = assert_that_owned(42)
            .with_location(false)
            .with_capture()
            // This records a failure.
            .is_equal_to(43);

        assert_that_panic_by(move || assert_capturing.without_capture())
            .has_type::<String>()
            .is_equal_to(formatdoc! {r#"
                -------- assertr --------
                Subject: Assertion failures

                Actual: alloc::vec::Vec<alloc::string::String> [
                    "-------- assertr --------\nExpected: 43\n\n  Actual: 42\n-------- assertr --------\n",
                ]

                was expected to be empty, but it is not!

                Details: [
                    You cannot unwrap the inner value if assertion failures were already recorded!,
                ]
                -------- assertr --------
            "#});
    }

    mod unwrap_inner {
        use crate::prelude::*;
        use indoc::formatdoc;

        #[test]
        fn panics_on_borrowed_value_in_panic_mode() {
            let value = String::from("foo");
            let assert = assert_that(&value)
                .with_location(false)
                // Avoid "number-of-assertions not greater 0" panic.
                .is_equal_to("foo");

            assert_that_panic_by(move || assert.unwrap_inner())
                .has_type::<&str>()
                .is_equal_to(formatdoc! {r#"Cannot `unwrap_owned` a borrowed value."#});
        }

        #[test]
        fn panics_on_borrowed_value_in_capture_mode() {
            let value = String::from("foo");
            let assert = assert_that(&value)
                .with_location(false)
                .with_capture()
                // Avoid "number-of-assertions not greater 0" panic.
                .is_equal_to("foo");

            assert_that_panic_by(move || assert.unwrap_inner())
                .has_type::<&str>()
                .is_equal_to(formatdoc! {r#"Cannot `unwrap_owned` a borrowed value."#});
        }

        #[test]
        fn succeeds_on_owned_value_in_panic_mode() {
            let assert = assert_that_owned(42)
                .with_location(false)
                // Avoid "number-of-assertions not greater 0" panic.
                .is_equal_to(42);
            let actual = assert.unwrap_inner();
            actual.must().be_equal_to(42);
        }

        #[test]
        fn succeeds_on_owned_value_in_capture_mode_when_no_failures_were_recorded() {
            let assert = assert_that_owned(42)
                .with_location(false)
                .with_capture()
                .has_display_value("42");
            let actual = assert.unwrap_inner();
            actual.must().be_equal_to(42);
        }

        #[test]
        fn panics_on_owned_value_in_capture_mode_when_failures_were_recorded() {
            let assert = assert_that_owned(42)
                .with_location(false)
                .with_capture()
                // This records a failure.
                .is_equal_to(43);

            assert_that_panic_by(move || assert.unwrap_inner())
            .has_type::<String>()
            .is_equal_to(formatdoc! {r#"
                -------- assertr --------
                Subject: Assertion failures

                Actual: alloc::vec::Vec<alloc::string::String> [
                    "-------- assertr --------\nExpected: 43\n\n  Actual: 42\n-------- assertr --------\n",
                ]

                was expected to be empty, but it is not!

                Details: [
                    You cannot unwrap the inner value if assertion failures were already recorded!,
                ]
                -------- assertr --------
            "#});
        }
    }

    #[cfg(feature = "fluent")]
    #[test]
    fn allows_fluent_entry_into_assertion_context() {
        42.must().be_equal_to(42);
        42.must_owned().be_equal_to(42);

        42.verify()
            .be_equal_to(42)
            .capture_failures()
            .must()
            .be_empty();
        42.verify_owned()
            .be_equal_to(42)
            .capture_failures()
            .must()
            .be_empty();

        assert_that(&42).is_equal_to(42);
        assert_that_owned(42).is_equal_to(42);

        let failures = assert_that(&42)
            .with_capture()
            .is_equal_to(42)
            .capture_failures();
        assert_that!(failures).is_empty();
        let failures = assert_that_owned(42)
            .with_capture()
            .is_equal_to(42)
            .capture_failures();
        assert_that!(failures).is_empty();

        assert_that!(&42).is_equal_to(42);
        assert_that!(42).is_equal_to(42);
    }
}