expect_json/context/
context.rs

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