asserting 0.14.0

Fluent assertions for tests in Rust that are convenient to write and easy to extend.
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
//! Field-by-field recursive comparison of graphs of structs, enums, and tuples.
//!
//! Any type that implements [`serde::Serialize`] can be compared recursively.
//! This is useful for comparing graphs of structs, enums, and tuples.
//! The type to be compared does not need to implement `PartialEq` and `Debug`
//! or any other trait (besides [`serde::Serialize`]).
//!
//! There are several scenarios where recursive comparison is useful:
//!
//! * comparing types that have similar fields, like an entity and a DTO
//!   representation of the same thing in the application's domain.
//! * comparing only fields that are relevant for a specific test case and
//!   ignoring others.
//! * comparing types field-by-field but ignoring fields, where the actual value
//!   may vary like for IDs or timestamps.
//! * comparing types that implement `Serialize` but not `PartialEq` or `Debug`
//!
//! Recursive comparison provides detailed failure reports in case of a failing
//! assertion. The failure details contain a list of fields, for which the
//! actual value is not equal to the expected one. This is another reason why
//! recursive comparison might be the preferred way, especially when comparing
//! structs that have many fields and/or contain nested structs.
//!
//! The recursive comparison mode starts after calling the
//! `using_recursive_comparison` method.
//!
//! Recursive comparison is not symmetrical since it is limited to the fields
//! of the subject (actual value). It gathers the actual fields of the subject
//! and compares them to the corresponding fields having the same name in the
//! expected value.
//!
//! Structs, enums, and tuples in the subject and expected value do not
//! have to be of the exact same type. They are compared field-by-field. As
//! long as the actual and expected fields have the same name and value, they
//! are considered equal. Though primitive types like char, integer, float, and
//! bool have to be of the same type. For example, an actual field of an `u8`
//! value is only equal to the expected field if the names and values are equal
//! and the expected value is of type `u8` too.
//!
//! Recursive comparison is limited down to a max depth of 128 levels,
//! which is the default max depth of [`serde::Serialize`].
//!
//! The recursive comparison mode provides the following capabilities:
//!
//! * [Ignoring fields in the comparison](#ignoring-some-fields)
//! * [Comparing only specified fields](RecursiveComparison::comparing_only_fields)
//! * [Ignoring all fields that are not present in the expected value](#ignoring-not-expected-fields)
//! * [Comparing only relevant fields](#comparing-only-relevant-fields)
//!
//! # Examples
//!
//! ## Comparing structs with several fields and nested structs
//!
//! The following example shows how to compare two structs. The structs are
//! compared field-by-field recursively. The actual and the expected value can
//! be of the same struct type or different struct types. By default, the
//! expected struct must have at least all the fields of the actual struct but
//! can have more fields not present in the actual struct.
//!
//! ```
//! use asserting::prelude::*;
//! use serde::Serialize;
//!
//! #[derive(Serialize)]
//! struct Email {
//!     purpose: String,
//!     address: String,
//! }
//!
//! #[derive(Serialize)]
//! struct Person {
//!     name: String,
//!     email: Vec<Email>,
//!     age: u8,
//! }
//!
//! let person = Person {
//!     name: "Silvia".into(),
//!     email: vec![
//!         Email {
//!             purpose: "main".into(),
//!             address: "silvia@domain.com".into(),
//!         },
//!         Email {
//!             purpose: "private".into(),
//!             address: "silvia@mail.com".into(),
//!         },
//!     ],
//!     age: 25,
//! };
//!
//! assert_that!(person)
//!     .using_recursive_comparison()
//!     .is_equal_to(Person {
//!         name: "Silvia".into(),
//!         email: vec![
//!             Email {
//!                 purpose: "main".into(),
//!                 address: "silvia@domain.com".into(),
//!             },
//!             Email {
//!                 purpose: "private".into(),
//!                 address: "silvia@mail.com".into(),
//!             },
//!         ],
//!         age: 25,
//!     });
//! ```
//!
//! The field-by-field recursive comparison is started by calling the
//! `using_recursive_comparison` method.
//!
//! ## Ignoring some fields
//!
//! We can ignore some fields of the subject, which will be excluded from the
//! field-by-field recursive comparison. To do so, we add the names of the fields
//! that shall be ignored to the configuration of the recursive comparison using
//! either the `ignoring_field` method, which adds one field at a time, or the
//! `ignoring_fields` methods which adds multiple fields at once.
//!
//! ```
//! use asserting::prelude::*;
//! use serde::Serialize;
//!
//! #[derive(Serialize)]
//! struct Address {
//!     street: String,
//!     city: String,
//!     zip: u16,
//! }
//!
//! #[derive(Serialize)]
//! struct Person {
//!     name: String,
//!     age: u8,
//!     address: Address,
//! }
//!
//! let person = Person {
//!     name: "Silvia".into(),
//!     age: 25,
//!     address: Address {
//!         street: "Second Street".into(),
//!         city: "New York".into(),
//!         zip: 12345,
//!     }
//! };
//!
//! assert_that!(&person)
//!     .using_recursive_comparison()
//!     .ignoring_fields(["age", "address.street"])
//!     .is_equal_to(Person {
//!         name: "Silvia".into(),
//!         age: 27,
//!         address: Address {
//!             street: "Main Street".into(),
//!             city: "New York".into(),
//!             zip: 12345,
//!         }
//!     });
//!
//! assert_that!(person)
//!     .using_recursive_comparison()
//!     .ignoring_field("age")
//!     .ignoring_field("address.street")
//!     .is_equal_to(Person {
//!         name: "Silvia".into(),
//!         age: 27,
//!         address: Address {
//!             street: "Main Street".into(),
//!             city: "New York".into(),
//!             zip: 12345,
//!         }
//!     });
//! ```
//!
//! Once a field is ignored, its subfields are ignored as well. In the following
//! example the assertion succeeds because the `address` field is ignored and
//! therefore also the fields `street`, `city`, and `zip` are ignored.
//!
//! ```
//! use asserting::prelude::*;
//! use serde::Serialize;
//! #
//! # #[derive(Serialize)]
//! # struct Address {
//! #     street: String,
//! #     city: String,
//! #     zip: u16,
//! # }
//! #
//! # #[derive(Serialize)]
//! # struct Person {
//! #     name: String,
//! #     age: u8,
//! #     address: Address,
//! # }
//!
//! let person = Person {
//!     name: "Silvia".into(),
//!     age: 25,
//!     address: Address {
//!         street: "Second Street".into(),
//!         city: "Chicago".into(),
//!         zip: 33333,
//!     }
//! };
//!
//! assert_that!(person)
//!     .using_recursive_comparison()
//!     .ignoring_field("address")
//!     .is_equal_to(Person {
//!         name: "Silvia".into(),
//!         age: 25,
//!         address: Address {
//!             street: "Main Street".into(),
//!             city: "New York".into(),
//!             zip: 12345,
//!         }
//!     });
//! ```
//!
//! ## Ignoring not expected fields
//!
//! With field-by-field recursive comparison, it is possible to compare similar
//! structs that share most of their fields but not all, like a domain object,
//! an entity, and a DTO of the same thing.
//!
//! ```
//! use asserting::prelude::*;
//! use serde::Serialize;
//!
//! #[derive(Serialize)]
//! struct PersonEntity {
//!     id: u64,
//!     name: String,
//!     age: u8,
//! }
//!
//! #[derive(Serialize)]
//! struct PersonDto {
//!     name: String,
//!     age: u8,
//! }
//!
//! let person = PersonEntity {
//!     id: 123,
//!     name: "Silvia".into(),
//!     age: 25,
//! };
//!
//! assert_that!(person)
//!     .using_recursive_comparison()
//!     .ignoring_not_expected_fields()
//!     .is_equal_to(PersonDto {
//!         name: "Silvia".into(),
//!         age: 25,
//!     });
//! ```
//!
//! Here we are comparing the subject of type `PersonEntity` with a `PersonDto`.
//! In contrast to the `PersonEntity` the `PersonDto` does not have an `id`
//! field. So we ignore it by using the `ignoring_not_expected_fields`
//! option.
//!
//! ## Comparing only relevant fields
//!
//! In real-world applications, we often have complex types. We might want to
//! write several tests where only some fields or parts of the complex type are
//! of interest. In this case, it can be annoying having to specify all fields
//! of a struct for the expected value. Declaring an additional struct having
//! only the relevant fields is additional boilerplate code.
//!
//! The solution is the [`value!`] macro. It allows us to construct expected
//! values with only the relevant fields. The [`value!`] macro is a convenient
//! way to construct a [`Value`] that serves as the expected value without
//! having to declare a custom type beforehand.
//!
//! If the expected value shall be a [`Value`], we use the `is_equivalent_to`
//! assertion method instead of `is_equal_to`.
//!
//! ```
//! use asserting::prelude::*;
//! use serde::Serialize;
//!
//! #[derive(Serialize)]
//! struct Person {
//!     id: u64,
//!     name: String,
//!     age: u8,
//!     email: Vec<String>,
//! }
//!
//! let person = Person {
//!     id: 456,
//!     name: "Silvia".into(),
//!     age: 25,
//!     email: vec!["silvia@domain.com".to_string()],
//! };
//!
//! assert_that!(person)
//!     .using_recursive_comparison()
//!     .ignoring_not_expected_fields()
//!     .is_equivalent_to(value!({
//!         name: "Silvia",
//!         age: 25_u8,
//!     }));
//! ```
//!
//! [`value!`]: crate::prelude::value
//! [`serde::Serialize`]: Serialize

pub mod path;
pub mod serialize;
pub mod value;

mod macros;

use crate::assertions::{AssertEquality, AssertEquivalence};
use crate::colored::mark_diff_str;
use crate::recursive_comparison::path::Path;
use crate::recursive_comparison::serialize::to_recursive_value;
use crate::recursive_comparison::value::Value;
use crate::spec::{
    AssertFailure, CollectFailures, DiffFormat, DoFail, FailingStrategy, GetFailures, SoftPanic,
    Spec,
};
use crate::std::fmt::{self, Display};
use crate::std::string::{String, ToString};
use crate::std::vec::Vec;
use crate::std::{format, vec};
use serde_core::Serialize;

/// Data of an actual assertion in field-by-field recursive comparison mode.
///
/// It wraps a [`Spec`] and holds additional options for the field-by-field
/// recursive comparison, such as which fields to compare and which to ignore.
///
/// See the [module documentation](crate::recursive_comparison) for details
/// about field-by-field recursive comparison.
pub struct RecursiveComparison<'a, S, R> {
    spec: Spec<'a, S, R>,
    compared_fields: Vec<Path<'a>>,
    ignored_fields: Vec<Path<'a>>,
    ignore_not_expected_fields: bool,
}

impl<S, R> GetFailures for RecursiveComparison<'_, S, R> {
    fn has_failures(&self) -> bool {
        self.spec.has_failures()
    }

    fn failures(&self) -> Vec<AssertFailure> {
        self.spec.failures()
    }

    fn display_failures(&self) -> Vec<String> {
        self.spec.display_failures()
    }
}

impl<S, R> DoFail for RecursiveComparison<'_, S, R>
where
    R: FailingStrategy,
{
    fn do_fail_with(&mut self, failures: impl IntoIterator<Item = AssertFailure>) {
        self.spec.do_fail_with(failures);
    }

    fn do_fail_with_message(&mut self, message: impl Into<String>) {
        self.spec.do_fail_with_message(message);
    }
}

impl<S> SoftPanic for RecursiveComparison<'_, S, CollectFailures> {
    fn soft_panic(&self) {
        self.spec.soft_panic();
    }
}

impl<'a, S, R> RecursiveComparison<'a, S, R> {
    pub(crate) fn new(spec: Spec<'a, S, R>) -> Self {
        Self {
            spec,
            compared_fields: vec![],
            ignored_fields: vec![],
            ignore_not_expected_fields: false,
        }
    }

    /// Adds one field that shall be compared in a field-by-field recursive
    /// comparison.
    ///
    /// This method can be called multiple times to add several paths to the
    /// list of paths to be compared. Each call of this method adds the given
    /// field-path to the list of compared paths.
    ///
    /// Fields are addressed by their path. To learn how to specify a path and
    /// its syntax, see the documentation of the [`Path`] struct.
    ///
    /// If the same path is added to the list of ignored paths, this path is
    /// effectively ignored. Ignored paths take precedence over compared ones.
    #[must_use = "the returned `RecursiveComparison` does nothing unless an assertion method like `is_equal_to` is called"]
    pub fn comparing_only_field(mut self, field_path: impl Into<Path<'a>>) -> Self {
        self.compared_fields.push(field_path.into());
        self
    }

    /// Adds multiple fields to the list of fields to be compared in a
    /// field-by-field recursive comparison.
    ///
    /// This method can be called multiple times. Each call of this method
    /// extends the list of compared fields with the given paths.
    ///
    /// Fields are addressed by their path. To learn how to specify a path and
    /// its syntax, see the documentation of the [`Path`] struct.
    ///
    /// If the same path is added to the list of ignored paths, this path is
    /// effectively ignored. Ignored paths take precedence over compared ones.
    #[must_use = "the returned `RecursiveComparison` does nothing unless an assertion method like `is_equal_to` is called"]
    pub fn comparing_only_fields<P>(
        mut self,
        list_of_field_path: impl IntoIterator<Item = P>,
    ) -> Self
    where
        P: Into<Path<'a>>,
    {
        self.compared_fields
            .extend(list_of_field_path.into_iter().map(Into::into));
        self
    }

    /// Adds one field that shall be ignored in a field-by-field recursive
    /// comparison.
    ///
    /// This method can be called multiple times to add several paths to the
    /// list of paths to be ignored. Each call of this method adds the given
    /// field-path to the list of ignored paths.
    ///
    /// Fields are addressed by their path. To learn how to specify a path and
    /// its syntax, see the documentation of the [`Path`] struct.
    ///
    /// If the same path is added to the list of compared paths, this path is
    /// effectively ignored. Ignored paths take precedence over compared paths.
    #[must_use = "the returned `RecursiveComparison` does nothing unless an assertion method like `is_equal_to` is called"]
    pub fn ignoring_field(mut self, field_path: impl Into<Path<'a>>) -> Self {
        self.ignored_fields.push(field_path.into());
        self
    }

    /// Adds multiple fields to the list of fields to be ignored in a
    /// field-by-field recursive comparison.
    ///
    /// This method can be called multiple times. Each call of this method
    /// extends the list of ignored fields with the given paths.
    ///
    /// Fields are addressed by their path. To learn how to specify a path and
    /// its syntax, see the documentation of the [`Path`] struct.
    ///
    /// If the same path is added to the list of compared paths, this path is
    /// effectively ignored. Ignored paths take precedence over compared paths.
    #[must_use = "the returned `RecursiveComparison` does nothing unless an assertion method like `is_equal_to` is called"]
    pub fn ignoring_fields<P>(mut self, list_of_field_path: impl IntoIterator<Item = P>) -> Self
    where
        P: Into<Path<'a>>,
    {
        self.ignored_fields
            .extend(list_of_field_path.into_iter().map(Into::into));
        self
    }

    /// Specifies that the recursive comparison shall ignore fields that are
    /// not present in the expected value.
    ///
    /// By default, the recursive comparison tries to compare all fields of the
    /// actual value (subject). If a field of the actual value is not present in
    /// the expected value, the assertion fails.
    ///
    /// With this option, we can tell the recursive comparison to ignore fields
    /// that are not present in the expected value. This is useful when not all
    /// fields are relevant to be compared for a specific test case.
    #[must_use = "the returned `RecursiveComparison` does nothing unless an assertion method like `is_equal_to` is called"]
    pub fn ignoring_not_expected_fields(mut self) -> Self {
        self.ignore_not_expected_fields = true;
        self
    }

    fn compare<'b>(&self, actual: &'b Value, expected: &'b Value) -> ComparisonResult<'b> {
        let mut ignored = Vec::new();
        let mut not_expected = Vec::new();
        let mut non_equal = Vec::new();

        for (actual_path, actual_value) in actual.depth_first_iter() {
            if self
                .ignored_fields
                .iter()
                .any(|ignored| actual_path.starts_with(ignored))
                || (!self.compared_fields.is_empty()
                    && !self
                        .compared_fields
                        .iter()
                        .any(|compared| actual_path.starts_with(compared)))
            {
                ignored.push(actual_path);
                continue;
            }
            if let Some(expected_value) = expected.get_path(&actual_path) {
                if actual_value != expected_value {
                    non_equal.push(NonEqual {
                        path: actual_path,
                        actual_value,
                        expected_value,
                    });
                }
            } else if self.ignore_not_expected_fields {
                ignored.push(actual_path);
            } else {
                not_expected.push(NotExpected {
                    path: actual_path,
                    value: actual_value,
                });
            }
        }

        ComparisonResult {
            ignored,
            non_equal,
            not_expected,
        }
    }
}

struct NotExpected<'a> {
    path: Path<'a>,
    value: &'a Value,
}

impl Display for NotExpected<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let NotExpected { path, value } = self;
        write!(f, "{path}: {value:?}")
    }
}

struct NonEqual<'a> {
    path: Path<'a>,
    actual_value: &'a Value,
    expected_value: &'a Value,
}

struct ComparisonResult<'a> {
    ignored: Vec<Path<'a>>,
    non_equal: Vec<NonEqual<'a>>,
    not_expected: Vec<NotExpected<'a>>,
}

impl ComparisonResult<'_> {
    fn has_failure(&self) -> bool {
        !self.non_equal.is_empty() || !self.not_expected.is_empty()
    }
}

fn display_non_equal(non_equal: &NonEqual<'_>, diff_format: &DiffFormat) -> String {
    let NonEqual {
        path,
        actual_value,
        expected_value,
    } = non_equal;
    let mut display_details = String::new();
    let debug_actual = format!("{actual_value:?}");
    let debug_expected = format!("{expected_value:?}");
    display_details.push_str(&path.to_string());
    if debug_actual == debug_expected {
        let (marked_actual_type, marked_expected_type) = mark_diff_str(
            &actual_value.type_name(),
            &expected_value.type_name(),
            diff_format,
        );
        display_details.push_str(": value <");
        display_details.push_str(&debug_actual);
        display_details.push_str("> was equal, but type was <");
        display_details.push_str(&marked_actual_type);
        display_details.push_str("> and expected type is <");
        display_details.push_str(&marked_expected_type);
    } else {
        let (marked_actual, marked_expected) =
            mark_diff_str(&debug_actual, &debug_expected, diff_format);
        display_details.push_str(": expected <");
        display_details.push_str(&marked_expected);
        display_details.push_str("> but was <");
        display_details.push_str(&marked_actual);
    }
    display_details.push('>');
    display_details
}

fn display_compare_details(compared: &ComparisonResult<'_>, diff_format: &DiffFormat) -> String {
    let mut display_details = String::new();
    if !compared.non_equal.is_empty() {
        display_details.push_str("\n  non equal fields:\n");
        for a_non_equal in &compared.non_equal {
            display_details.push_str("    ");
            display_details.push_str(&display_non_equal(a_non_equal, diff_format));
            display_details.push('\n');
        }
    }
    if !compared.not_expected.is_empty() {
        display_details.push_str("\n  the following fields were not expected:\n");
        for a_not_expected in &compared.not_expected {
            display_details.push_str("    ");
            display_details.push_str(&a_not_expected.to_string());
            display_details.push('\n');
        }
    }
    if !compared.ignored.is_empty() {
        display_details.push_str("\n  the following fields were ignored:\n");
        for an_ignored in &compared.ignored {
            display_details.push_str("    ");
            display_details.push_str(&an_ignored.to_string());
            display_details.push('\n');
        }
    }
    display_details
}

impl<S, E, R> AssertEquality<E> for RecursiveComparison<'_, S, R>
where
    S: Serialize,
    E: Serialize,
    R: FailingStrategy,
{
    fn is_equal_to(mut self, expected: E) -> Self {
        let expression = self.spec.expression();
        let actual = to_recursive_value(self.spec.subject())
            .unwrap_or_else(|err| panic!("failed to serialize the subject, reason: {err}"));
        let expected = to_recursive_value(&expected)
            .unwrap_or_else(|err| panic!("failed to serialize the expected value, reason: {err}"));

        let compared = self.compare(&actual, &expected);

        if compared.has_failure() {
            let compare_details = display_compare_details(&compared, self.spec.diff_format());

            self.do_fail_with_message(format!(
                r"expected {expression} to be equal to {expected:?} (using recursive comparison)
   but was: {actual:?}
  expected: {expected:?}
{compare_details}"
            ));
        }
        self
    }

    fn is_not_equal_to(mut self, expected: E) -> Self {
        let expression = self.spec.expression();
        let actual = to_recursive_value(self.spec.subject())
            .unwrap_or_else(|err| panic!("failed to serialize the subject, reason: {err}"));
        let expected = to_recursive_value(&expected)
            .unwrap_or_else(|err| panic!("failed to serialize the expected value, reason: {err}"));

        let compared = self.compare(&actual, &expected);

        if !compared.has_failure() {
            let compare_details = display_compare_details(&compared, self.spec.diff_format());

            self.do_fail_with_message(format!(
                r"expected {expression} to be not equal to {expected:?} (using recursive comparison)
   but was: {actual:?}
  expected: {expected:?}
{compare_details}"
            ));
        }
        self
    }
}

impl<S, R> AssertEquivalence<Value> for RecursiveComparison<'_, S, R>
where
    S: Serialize,
    R: FailingStrategy,
{
    fn is_equivalent_to(mut self, expected: Value) -> Self {
        let expression = self.spec.expression();
        let actual = to_recursive_value(self.spec.subject())
            .unwrap_or_else(|err| panic!("failed to serialize the subject, reason: {err}"));

        let compared = self.compare(&actual, &expected);

        if compared.has_failure() {
            let compare_details = display_compare_details(&compared, self.spec.diff_format());

            self.do_fail_with_message(format!(
                r"expected {expression} to be equivalent to {expected:?} (using recursive comparison)
   but was: {actual:?}
  expected: {expected:?}
{compare_details}"
            ));
        }
        self
    }

    fn is_not_equivalent_to(mut self, expected: Value) -> Self {
        let expression = self.spec.expression();
        let actual = to_recursive_value(self.spec.subject())
            .unwrap_or_else(|err| panic!("failed to serialize the subject, reason: {err}"));

        self.ignore_not_expected_fields = true;
        let compared = self.compare(&actual, &expected);

        if !compared.has_failure() {
            let compare_details = display_compare_details(&compared, self.spec.diff_format());

            self.do_fail_with_message(format!(
                r"expected {expression} to be not equivalent to {expected:?} (using recursive comparison)
   but was: {actual:?}
  expected: {expected:?}
{compare_details}"
            ));
        }
        self
    }
}

#[cfg(test)]
mod tests;