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
//! This crate includes macros for comparing two JSON values. It is designed to give much
//! more helpful error messages than the standard [`assert_eq!`]. It basically does a diff of the
//! two objects and tells you the exact differences. This is useful when asserting that two large
//! JSON objects are the same.
//!
//! It uses the [`serde_json::Value`] type to represent JSON.
//!
//! [`serde_json::Value`]: https://docs.serde.rs/serde_json/value/enum.Value.html
//! [`assert_eq!`]: https://doc.rust-lang.org/std/macro.assert_eq.html
//!
//! ## Install
//!
//! ```toml
//! [dependencies]
//! assert-json-diff = "0.2.1"
//! ```
//!
//! ## Partial matching
//!
//! If you want to assert that one JSON value is "included" in another use
//! [`assert_json_include`](macro.assert_json_include.html):
//!
//! ```should_panic
//! #[macro_use]
//! extern crate assert_json_diff;
//! #[macro_use]
//! extern crate serde_json;
//!
//! fn main() {
//!     let a = json!({
//!         "data": {
//!             "users": [
//!                 {
//!                     "id": 1,
//!                     "country": {
//!                         "name": "Denmark"
//!                     }
//!                 },
//!                 {
//!                     "id": 24,
//!                     "country": {
//!                         "name": "Denmark"
//!                     }
//!                 }
//!             ]
//!         }
//!     });
//!
//!     let b = json!({
//!         "data": {
//!             "users": [
//!                 {
//!                     "id": 1,
//!                     "country": {
//!                         "name": "Sweden"
//!                     }
//!                 },
//!                 {
//!                     "id": 2,
//!                     "country": {
//!                         "name": "Denmark"
//!                     }
//!                 }
//!             ]
//!         }
//!     });
//!
//!     assert_json_include!(actual: a, expected: b)
//! }
//! ```
//!
//! This will panic with the error message:
//!
//! ```text
//! json atoms at path ".data.users[0].country.name" are not equal:
//!     expected:
//!         "Sweden"
//!     actual:
//!         "Denmark"
//!
//! json atoms at path ".data.users[1].id" are not equal:
//!     expected:
//!         2
//!     actual:
//!         24
//! ```
//!
//! [`assert_json_include`](macro.assert_json_include.html) allows extra data in `actual` but not in `expected`. That is so you can verify just a part
//! of the JSON without having to specify the whole thing. For example this test passes:
//!
//! ```
//! #[macro_use]
//! extern crate assert_json_diff;
//! #[macro_use]
//! extern crate serde_json;
//!
//! fn main() {
//!     assert_json_include!(
//!         actual: json!({
//!             "a": { "b": 1 },
//!         }),
//!         expected: json!({
//!             "a": {},
//!         })
//!     )
//! }
//! ```
//!
//! However `expected` cannot contain additional data so this test fails:
//!
//! ```should_panic
//! #[macro_use]
//! extern crate assert_json_diff;
//! #[macro_use]
//! extern crate serde_json;
//!
//! fn main() {
//!     assert_json_include!(
//!         actual: json!({
//!             "a": {},
//!         }),
//!         expected: json!({
//!             "a": { "b": 1 },
//!         })
//!     )
//! }
//! ```
//!
//! That will print
//!
//! ```text
//! json atom at path ".a.b" is missing from actual
//! ```
//!
//! ## Exact matching
//!
//! If you want to ensure two JSON values are *exactly* the same, use [`assert_json_eq`](macro.assert_json_eq.html).
//!
//! ```rust,should_panic
//! #[macro_use]
//! extern crate assert_json_diff;
//! #[macro_use]
//! extern crate serde_json;
//!
//! fn main() {
//!     assert_json_eq!(
//!         json!({ "a": { "b": 1 } }),
//!         json!({ "a": {} })
//!     )
//! }
//! ```
//!
//! This will panic with the error message:
//!
//! ```text
//! json atom at path ".a.b" is missing from lhs
//! ```

#![deny(
    missing_docs,
    unused_imports,
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unstable_features,
    unused_import_braces,
    unused_qualifications
)]
#![doc(html_root_url = "https://docs.rs/assert-json-diff/0.2.1")]

extern crate serde;
#[allow(unused_imports)]
#[macro_use]
extern crate serde_json;

use serde::{Serialize, Serializer};
use serde_json::Value;
use std::collections::HashSet;
use std::default::Default;
use std::fmt;

mod core_ext;
use core_ext::{Indent, Indexes};

/// The macro used to compare two JSON values for an inclusive match.
///
/// It allows `actual` to contain additional data. If you want an exact match use
/// [`assert_json_eq`](macro.assert_json_eq.html) instead.
///
/// See [crate documentation](index.html) for examples.
#[macro_export]
macro_rules! assert_json_include {
    (actual: $actual:expr, expected: $expected:expr) => {{
        use $crate::{Actual, Comparison, Expected};
        let actual: serde_json::Value = $actual;
        let expected: serde_json::Value = $expected;
        let comparison = Comparison::Include(Actual::new(actual), Expected::new(expected));
        if let Err(error) = $crate::assert_json_no_panic(comparison) {
            panic!("\n\n{}\n\n", error);
        }
    }};
    (expected: $expected:expr, actual: $actual:expr) => {{
        $crate::assert_json_include!(actual: $actual, expected: $expected)
    }};
}

/// The macro used to compare two JSON values for an exact match.
///
/// If you want an inclusive match use [`assert_json_include`](macro.assert_json_include.html) instead.
///
/// See [crate documentation](index.html) for examples.
#[macro_export]
macro_rules! assert_json_eq {
    ($lhs:expr, $rhs:expr) => {{
        use $crate::{Actual, Comparison, Expected};
        let lhs: serde_json::Value = $lhs;
        let rhs: serde_json::Value = $rhs;
        let comparison = Comparison::Exact(lhs, rhs);
        if let Err(error) = $crate::assert_json_no_panic(comparison) {
            panic!("\n\n{}\n\n", error);
        }
    }};
}

/// Perform the matching and return the error text rather than panicing.
///
/// The [macros](index.html#macros) call this function and panics if the result is an `Err(_)`
#[doc(hidden)]
pub fn assert_json_no_panic(comparison: Comparison) -> Result<(), String> {
    let mut errors = MatchErrors::default();
    match comparison {
        Comparison::Include(actual, expected) => {
            partial_match_at_path(actual, expected, Path::Root, &mut errors);
        }

        Comparison::Exact(lhs, rhs) => {
            exact_match_at_path(lhs, rhs, Path::Root, &mut errors);
        }
    }
    errors.to_output()
}

/// The type of comparison you want to make.
///
/// The [macros](index.html#macros) use this type, but you shouldn't have to use it explicitly.
#[doc(hidden)]
#[derive(Debug)]
pub enum Comparison {
    /// An inclusive match. Allows additional data in actual, but not in expected.
    Include(Actual, Expected),

    /// An exact match.
    Exact(Value, Value),
}

/// A wrapper for the actual value in a match.
///
/// The purpose of this wrapper is to not mix up the actual and expected values.
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct Actual(Value);

impl std::ops::Deref for Actual {
    type Target = Value;
    fn deref(&self) -> &Value {
        &self.0
    }
}

impl Actual {
    /// Create a new value from a [`serde_json::Value`].
    ///
    /// [`serde_json::Value`]: https://docs.serde.rs/serde_json/value/enum.Value.html
    pub fn new(value: Value) -> Self {
        Actual(value)
    }
}

impl Serialize for Actual {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <Value>::serialize(self, serializer)
    }
}

impl From<Value> for Actual {
    fn from(v: Value) -> Actual {
        Actual(v)
    }
}

/// A wrapper for the expected value in a match.
///
/// The purpose of this wrapper is to not mix up the actual and expected values.
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct Expected(Value);

impl Expected {
    /// Create a new value from a [`serde_json::Value`].
    ///
    /// [`serde_json::Value`]: https://docs.serde.rs/serde_json/value/enum.Value.html
    pub fn new(value: Value) -> Self {
        Expected(value)
    }
}

impl std::ops::Deref for Expected {
    type Target = Value;
    fn deref(&self) -> &Value {
        &self.0
    }
}

impl Serialize for Expected {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        <Value>::serialize(self, serializer)
    }
}

impl From<Value> for Expected {
    fn from(v: Value) -> Expected {
        Expected(v)
    }
}

enum Either<A, B> {
    Left(A),
    Right(B),
}

fn partial_match_at_path(actual: Actual, expected: Expected, path: Path, errors: &mut MatchErrors) {
    if let Some(expected) = expected.as_object() {
        let keys = expected.keys();
        match_with_keys(keys, &actual, expected, path, errors);
    } else if let Some(expected) = expected.as_array() {
        let keys = if expected.is_empty() {
            vec![]
        } else {
            expected.indexes()
        };

        match_with_keys(keys.iter(), &actual, expected, path, errors);
    } else {
        if expected.0 != actual.0 {
            errors.push(ErrorType::NotEq(
                Either::Left((actual.clone(), expected.clone())),
                path,
            ));
        }
    }
}

fn match_with_keys<
    Key: Copy,
    Keys: Iterator<Item = Key>,
    Path: Dot<Key>,
    ActualCollection: Collection<Key, Item = ActualValue>,
    ActualValue: Clone + Into<Actual>,
    ExpectedCollection: Collection<Key, Item = ExpectedValue>,
    ExpectedValue: Clone + Into<Expected>,
>(
    keys: Keys,
    actual: &ActualCollection,
    expected: &ExpectedCollection,
    path: Path,
    errors: &mut MatchErrors,
) {
    for key in keys {
        match (expected.get(key), actual.get(key)) {
            (Some(expected), Some(actual)) => {
                partial_match_at_path(
                    actual.clone().into(),
                    expected.clone().into(),
                    path.dot(key),
                    errors,
                );
            }

            (Some(_), None) => {
                errors.push(ErrorType::MissingPath(Either::Left(path.dot(key))));
            }

            (None, _) => unreachable!(),
        }
    }
}

fn exact_match_at_path(lhs: Value, rhs: Value, path: Path, errors: &mut MatchErrors) {
    if let (Some(lhs), Some(rhs)) = (lhs.as_object(), rhs.as_object()) {
        let keys = lhs
            .keys()
            .chain(rhs.keys())
            .map(|s| s.to_string())
            .collect::<HashSet<String>>();

        exact_match_with_keys(keys.iter(), lhs, rhs, path, errors);
    } else if let (Some(lhs), Some(rhs)) = (lhs.as_array(), rhs.as_array()) {
        let lhs_keys = lhs.indexes();
        let rhs_keys = rhs.indexes();
        let keys = lhs_keys
            .iter()
            .chain(rhs_keys.iter())
            .map(|s| s.clone())
            .collect::<HashSet<usize>>();

        exact_match_with_keys(keys.iter(), lhs, rhs, path, errors);
    } else {
        if lhs != rhs {
            errors.push(ErrorType::NotEq(
                Either::Right((lhs.clone(), rhs.clone())),
                path,
            ));
        }
    }
}

fn exact_match_with_keys<
    Key: Copy,
    Keys: Iterator<Item = Key>,
    Path: Dot<Key>,
    ValueCollection: Collection<Key, Item = Value>,
>(
    keys: Keys,
    lhs: &ValueCollection,
    rhs: &ValueCollection,
    path: Path,
    errors: &mut MatchErrors,
) {
    for key in keys {
        match (lhs.get(key), rhs.get(key)) {
            (Some(lhs), Some(rhs)) => {
                exact_match_at_path(
                    lhs.clone().into(),
                    rhs.clone().into(),
                    path.dot(key),
                    errors,
                );
            }

            (Some(_), None) => {
                errors.push(ErrorType::MissingPath(Either::Right((
                    path.dot(key),
                    SideWithoutPath::Rhs,
                ))));
            }

            (None, Some(_)) => {
                errors.push(ErrorType::MissingPath(Either::Right((
                    path.dot(key),
                    SideWithoutPath::Lhs,
                ))));
            }

            (None, None) => unreachable!(),
        }
    }
}

trait Collection<Idx> {
    type Item;
    fn get(&self, index: Idx) -> Option<&Self::Item>;
}

impl<'a> Collection<&'a String> for serde_json::Map<String, Value> {
    type Item = Value;

    fn get(&self, index: &'a String) -> Option<&Self::Item> {
        self.get(index)
    }
}

impl<'a> Collection<&'a usize> for Vec<Value> {
    type Item = Value;

    fn get(&self, index: &'a usize) -> Option<&Self::Item> {
        <[Value]>::get(self, index.clone())
    }
}

impl<'a> Collection<&'a String> for Actual {
    type Item = Value;

    fn get(&self, index: &'a String) -> Option<&Self::Item> {
        <Value>::get(self, index.clone())
    }
}

impl<'a> Collection<&'a usize> for Actual {
    type Item = Value;

    fn get(&self, index: &'a usize) -> Option<&Self::Item> {
        <Value>::get(self, index.clone())
    }
}

#[derive(Clone)]
enum Path {
    Root,
    Trail(Vec<PathComp>),
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Path::Root => write!(f, "(root)"),
            Path::Trail(trail) => write!(
                f,
                "{}",
                trail
                    .iter()
                    .map(|comp| comp.to_string())
                    .collect::<Vec<_>>()
                    .join("")
            ),
        }
    }
}

impl Path {
    fn extend(&self, next: PathComp) -> Path {
        match self {
            Path::Root => Path::Trail(vec![next]),
            Path::Trail(trail) => {
                let mut trail = trail.clone();
                trail.push(next);
                Path::Trail(trail)
            }
        }
    }
}

trait Dot<T> {
    fn dot(&self, next: T) -> Path;
}

impl<'a> Dot<&'a String> for Path {
    fn dot(&self, next: &'a String) -> Path {
        let comp = PathComp::String(next.to_string());
        self.extend(comp)
    }
}

impl<'a> Dot<&'a str> for Path {
    fn dot(&self, next: &'a str) -> Path {
        let comp = PathComp::String(next.to_string());
        self.extend(comp)
    }
}

impl Dot<usize> for Path {
    fn dot(&self, next: usize) -> Path {
        let comp = PathComp::Index(next);
        self.extend(comp)
    }
}

impl<'a> Dot<&'a usize> for Path {
    fn dot(&self, next: &'a usize) -> Path {
        let comp = PathComp::Index(next.clone());
        self.extend(comp)
    }
}

#[derive(Clone)]
enum PathComp {
    String(String),
    Index(usize),
}

impl fmt::Display for PathComp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PathComp::String(s) => write!(f, ".{}", s),
            PathComp::Index(i) => write!(f, "[{}]", i),
        }
    }
}

struct MatchErrors {
    errors: Vec<ErrorType>,
}

impl Default for MatchErrors {
    fn default() -> Self {
        MatchErrors { errors: vec![] }
    }
}

impl MatchErrors {
    fn to_output(self) -> Result<(), String> {
        if self.errors.is_empty() {
            Ok(())
        } else {
            let messages = self
                .errors
                .iter()
                .map(|error| match error {
                    ErrorType::NotEq(Either::Left((actual, expected)), path) => format!(
                        r#"json atoms at path "{}" are not equal:
    expected:
{}
    actual:
{}"#,
                        path,
                        serde_json::to_string_pretty(expected)
                            .expect("failed to pretty print JSON")
                            .indent(8),
                        serde_json::to_string_pretty(actual)
                            .expect("failed to pretty print JSON")
                            .indent(8),
                    ),

                    ErrorType::NotEq(Either::Right((lhs, rhs)), path) => format!(
                        r#"json atoms at path "{}" are not equal:
    lhs:
{}
    rhs:
{}"#,
                        path,
                        serde_json::to_string_pretty(lhs)
                            .expect("failed to pretty print JSON")
                            .indent(8),
                        serde_json::to_string_pretty(rhs)
                            .expect("failed to pretty print JSON")
                            .indent(8),
                    ),
                    ErrorType::MissingPath(Either::Left(path)) => {
                        format!(r#"json atom at path "{}" is missing from actual"#, path)
                    }
                    ErrorType::MissingPath(Either::Right((path, SideWithoutPath::Lhs))) => {
                        format!(r#"json atom at path "{}" is missing from lhs"#, path)
                    }
                    ErrorType::MissingPath(Either::Right((path, SideWithoutPath::Rhs))) => {
                        format!(r#"json atom at path "{}" is missing from rhs"#, path)
                    }
                })
                .collect::<Vec<_>>();
            Err(messages.join("\n\n"))
        }
    }

    fn push(&mut self, error: ErrorType) {
        self.errors.push(error);
    }
}

enum ErrorType {
    NotEq(Either<(Actual, Expected), (Value, Value)>, Path),
    MissingPath(Either<Path, (Path, SideWithoutPath)>),
}

enum SideWithoutPath {
    Lhs,
    Rhs,
}

#[cfg(test)]
mod tests {
    #[macro_use]
    use super::*;

    #[test]
    fn boolean_root() {
        let result = test_partial_match(Actual(json!(true)), Expected(json!(true)));
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(Actual(json!(false)), Expected(json!(false)));
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(Actual(json!(false)), Expected(json!(true)));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "(root)" are not equal:
    expected:
        true
    actual:
        false"#),
        );

        let result = test_partial_match(Actual(json!(true)), Expected(json!(false)));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "(root)" are not equal:
    expected:
        false
    actual:
        true"#),
        );
    }

    #[test]
    fn string_root() {
        let result = test_partial_match(Actual(json!("true")), Expected(json!("true")));
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(Actual(json!("false")), Expected(json!("false")));
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(Actual(json!("false")), Expected(json!("true")));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "(root)" are not equal:
    expected:
        "true"
    actual:
        "false""#),
        );

        let result = test_partial_match(Actual(json!("true")), Expected(json!("false")));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "(root)" are not equal:
    expected:
        "false"
    actual:
        "true""#),
        );
    }

    #[test]
    fn number_root() {
        let result = test_partial_match(Actual(json!(1)), Expected(json!(1)));
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(Actual(json!(0)), Expected(json!(0)));
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(Actual(json!(0)), Expected(json!(1)));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "(root)" are not equal:
    expected:
        1
    actual:
        0"#),
        );

        let result = test_partial_match(Actual(json!(1)), Expected(json!(0)));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "(root)" are not equal:
    expected:
        0
    actual:
        1"#),
        );
    }

    #[test]
    fn null_root() {
        let result = test_partial_match(Actual(json!(null)), Expected(json!(null)));
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(Actual(json!(null)), Expected(json!(1)));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "(root)" are not equal:
    expected:
        1
    actual:
        null"#),
        );

        let result = test_partial_match(Actual(json!(1)), Expected(json!(null)));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "(root)" are not equal:
    expected:
        null
    actual:
        1"#),
        );
    }

    #[test]
    fn into_object() {
        let result =
            test_partial_match(Actual(json!({ "a": true })), Expected(json!({ "a": true })));
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(
            Actual(json!({ "a": false })),
            Expected(json!({ "a": true })),
        );
        assert_output_eq(
            result,
            Err(r#"json atoms at path ".a" are not equal:
    expected:
        true
    actual:
        false"#),
        );

        let result = test_partial_match(
            Actual(json!({ "a": { "b": true } })),
            Expected(json!({ "a": { "b": true } })),
        );
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(
            Actual(json!({ "a": true })),
            Expected(json!({ "a": { "b": true } })),
        );
        assert_output_eq(
            result,
            Err(r#"json atom at path ".a.b" is missing from actual"#),
        );

        let result = test_partial_match(Actual(json!({})), Expected(json!({ "a": true })));
        assert_output_eq(
            result,
            Err(r#"json atom at path ".a" is missing from actual"#),
        );

        let result = test_partial_match(
            Actual(json!({ "a": { "b": true } })),
            Expected(json!({ "a": true })),
        );
        assert_output_eq(
            result,
            Err(r#"json atoms at path ".a" are not equal:
    expected:
        true
    actual:
        {
          "b": true
        }"#),
        );
    }

    #[test]
    fn into_array() {
        let result = test_partial_match(Actual(json!([1])), Expected(json!([1])));
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(Actual(json!([2])), Expected(json!([1])));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "[0]" are not equal:
    expected:
        1
    actual:
        2"#),
        );

        let result = test_partial_match(Actual(json!([1, 2, 4])), Expected(json!([1, 2, 3])));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "[2]" are not equal:
    expected:
        3
    actual:
        4"#),
        );

        let result = test_partial_match(
            Actual(json!({ "a": [1, 2, 3]})),
            Expected(json!({ "a": [1, 2, 4]})),
        );
        assert_output_eq(
            result,
            Err(r#"json atoms at path ".a[2]" are not equal:
    expected:
        4
    actual:
        3"#),
        );

        let result = test_partial_match(
            Actual(json!({ "a": [1, 2, 3]})),
            Expected(json!({ "a": [1, 2]})),
        );
        assert_output_eq(result, Ok(()));

        let result = test_partial_match(
            Actual(json!({ "a": [1, 2]})),
            Expected(json!({ "a": [1, 2, 3]})),
        );
        assert_output_eq(
            result,
            Err(r#"json atom at path ".a[2]" is missing from actual"#),
        );
    }

    #[test]
    fn exact_matching() {
        let result = test_exact_match(json!(true), json!(true));
        assert_output_eq(result, Ok(()));

        let result = test_exact_match(json!("s"), json!("s"));
        assert_output_eq(result, Ok(()));

        let result = test_exact_match(json!("a"), json!("b"));
        assert_output_eq(
            result,
            Err(r#"json atoms at path "(root)" are not equal:
    lhs:
        "a"
    rhs:
        "b""#),
        );

        let result = test_exact_match(
            json!({ "a": [1, { "b": 2 }] }),
            json!({ "a": [1, { "b": 3 }] }),
        );
        assert_output_eq(
            result,
            Err(r#"json atoms at path ".a[1].b" are not equal:
    lhs:
        2
    rhs:
        3"#),
        );
    }

    #[test]
    fn exact_match_output_message() {
        let result = test_exact_match(json!({ "a": { "b": 1 } }), json!({ "a": {} }));
        assert_output_eq(
            result,
            Err(r#"json atom at path ".a.b" is missing from rhs"#),
        );

        let result = test_exact_match(json!({ "a": {} }), json!({ "a": { "b": 1 } }));
        assert_output_eq(
            result,
            Err(r#"json atom at path ".a.b" is missing from lhs"#),
        );
    }

    fn assert_output_eq(actual: Result<(), String>, expected: Result<(), &str>) {
        match (actual, expected) {
            (Ok(()), Ok(())) => return,

            (Err(actual_error), Ok(())) => {
                println!("Did not expect error, but got");
                println!("{}", actual_error);
            }

            (Ok(()), Err(expected_error)) => {
                let expected_error = expected_error.to_string();
                println!("Expected error, but did not get one. Expected error:");
                println!("{}", expected_error);
            }

            (Err(actual_error), Err(expected_error)) => {
                let expected_error = expected_error.to_string();
                if actual_error == expected_error {
                    return;
                } else {
                    println!("Errors didn't match");
                    println!("Expected:");
                    println!("{}", expected_error);
                    println!("Got:");
                    println!("{}", actual_error);
                }
            }
        }

        panic!("assertion error, see stdout");
    }

    fn test_partial_match(actual: Actual, expected: Expected) -> Result<(), String> {
        let comparison = Comparison::Include(actual, expected);
        assert_json_no_panic(comparison)
    }

    fn test_exact_match(lhs: Value, rhs: Value) -> Result<(), String> {
        let comparison = Comparison::Exact(lhs, rhs);
        assert_json_no_panic(comparison)
    }
}