expect_json/expect_core/context/
context.rs

1use crate::ExpectJsonResult;
2use crate::expect_core::ContextWith;
3use crate::expect_core::context::ContextPathPart;
4use crate::internals::json_eq;
5use serde_json::Value;
6use std::fmt::Display;
7use std::fmt::Formatter;
8use std::fmt::Result as FmtResult;
9
10#[derive(Clone, Default, Debug, PartialEq)]
11pub struct Context<'c> {
12    stack: Vec<ContextPathPart<'c>>,
13    is_propagated_contains: bool,
14}
15
16impl<'c> Context<'c> {
17    pub(crate) fn new() -> Self {
18        Self::default()
19    }
20
21    pub fn json_eq(&self, received: &'c Value, expected: &'c Value) -> ExpectJsonResult<()> {
22        json_eq(&mut self.clone(), received, expected)
23    }
24
25    pub(crate) fn with_path<'a, P>(&'a mut self, path: P) -> ContextWith<'a, 'c>
26    where
27        P: Into<ContextPathPart<'c>>,
28    {
29        ContextWith::new(self).with_path(path)
30    }
31
32    pub(crate) fn with_propagated_contains<'a>(&'a mut self) -> ContextWith<'a, 'c> {
33        ContextWith::new(self).with_propagated_contains()
34    }
35
36    pub(crate) fn without_propagated_contains<'a>(&'a mut self) -> ContextWith<'a, 'c> {
37        ContextWith::new(self).without_propagated_contains()
38    }
39
40    pub(crate) fn enable_propagated_contains(&mut self) {
41        self.is_propagated_contains = true;
42    }
43
44    pub(crate) fn disable_propagated_contains(&mut self) {
45        self.is_propagated_contains = false;
46    }
47
48    pub(crate) fn is_propagated_contains(&self) -> bool {
49        self.is_propagated_contains
50    }
51
52    pub(crate) fn push<P>(&mut self, path: P)
53    where
54        P: Into<ContextPathPart<'c>>,
55    {
56        self.stack.push(path.into());
57    }
58
59    pub(crate) fn pop(&mut self) {
60        self.stack.pop();
61    }
62
63    pub(crate) fn to_static(&self) -> Context<'static> {
64        let stack = self.stack.iter().map(ContextPathPart::to_static).collect();
65
66        Context { stack, ..*self }
67    }
68}
69
70impl Display for Context<'_> {
71    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
72        write!(formatter, "root")?;
73
74        for path in &self.stack {
75            write!(formatter, "{path}")?;
76        }
77
78        Ok(())
79    }
80}