docx_templating/
context.rs1#[cfg(test)]
8use crate::syntax::ast::Path;
9use serde::Serialize;
10use serde_json::Value;
11
12#[derive(Debug, Clone)]
30pub struct Context {
31 root: Value,
32}
33
34impl Context {
35 pub fn from_json(value: Value) -> Self {
37 Self { root: value }
38 }
39
40 pub fn from_serialize<T: Serialize + ?Sized>(value: &T) -> crate::Result<Self> {
62 let json = serde_json::to_value(value).map_err(ContextError::Serialization)?;
63 Ok(Self::from_json(json))
64 }
65
66 #[cfg(test)]
75 pub(crate) fn resolve(&self, path: &Path) -> crate::Result<Option<&Value>> {
76 crate::domain::engine::resolve_path(&self.root, path).map_err(crate::Error::from)
77 }
78
79 pub(crate) fn root(&self) -> &Value {
81 &self.root
82 }
83}
84
85impl From<Value> for Context {
86 fn from(value: Value) -> Self {
87 Self::from_json(value)
88 }
89}
90
91impl Default for Context {
92 fn default() -> Self {
94 Self::from_json(Value::Object(serde_json::Map::new()))
95 }
96}
97
98impl Serialize for Context {
99 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
100 where
101 S: serde::Serializer,
102 {
103 self.root.serialize(serializer)
104 }
105}
106
107pub trait IntoContext {
135 fn into_context(self) -> crate::Result<Context>;
143}
144
145impl IntoContext for Context {
146 fn into_context(self) -> crate::Result<Context> {
147 Ok(self)
148 }
149}
150
151impl IntoContext for Value {
152 fn into_context(self) -> crate::Result<Context> {
153 Ok(Context::from_json(self))
154 }
155}
156
157impl<T: Serialize + ?Sized> IntoContext for &T {
158 fn into_context(self) -> crate::Result<Context> {
159 Context::from_serialize(self)
160 }
161}
162
163#[derive(Debug, thiserror::Error)]
165#[non_exhaustive]
166pub enum ContextError {
167 #[error("failed to serialize value to JSON: {0}")]
169 Serialization(#[source] serde_json::Error),
170}
171
172#[cfg(test)]
173mod tests {
174 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
175
176 use super::*;
177 use crate::syntax::ast::PathSegment;
178 use serde::Serialize;
179 use serde_json::json;
180
181 #[test]
182 fn test_from_json() {
183 let ctx = Context::from_json(json!({"name": "Ada"}));
184 assert!(ctx.root().is_object());
185 }
186
187 #[test]
188 fn test_from_value_trait() {
189 let ctx: Context = json!({"name": "Ada"}).into();
190 assert!(ctx.root().is_object());
191 }
192
193 #[test]
194 fn test_from_serialize() {
195 #[derive(Serialize)]
196 struct User {
197 name: String,
198 age: u32,
199 }
200
201 let user = User {
202 name: "Ada".to_string(),
203 age: 36,
204 };
205 let ctx = Context::from_serialize(&user).unwrap();
206
207 let path = Path::field("name");
208 let value = ctx.resolve(&path).unwrap();
209 assert_eq!(value, Some(&json!("Ada")));
210 }
211
212 #[test]
213 fn test_resolve_top_level() {
214 let ctx = Context::from_json(json!({"name": "Ada"}));
215 let path = Path::field("name");
216
217 let value = ctx.resolve(&path).unwrap();
218 assert_eq!(value, Some(&json!("Ada")));
219 }
220
221 #[test]
222 fn test_resolve_nested() {
223 let ctx = Context::from_json(json!({
224 "user": {
225 "name": "Ada",
226 "age": 36
227 }
228 }));
229
230 let path = Path::new(vec![
231 PathSegment::Field("user".to_string()),
232 PathSegment::Field("name".to_string()),
233 ]);
234
235 let value = ctx.resolve(&path).unwrap();
236 assert_eq!(value, Some(&json!("Ada")));
237 }
238
239 #[test]
240 fn test_resolve_missing_returns_none() {
241 let ctx = Context::from_json(json!({"name": "Ada"}));
242 let path = Path::field("missing");
243
244 let value = ctx.resolve(&path).unwrap();
245 assert_eq!(value, None);
246 }
247
248 #[test]
249 fn test_resolve_type_mismatch_errors() {
250 let ctx = Context::from_json(json!({"items": [1, 2, 3]}));
251 let path = Path::new(vec![
252 PathSegment::Field("items".to_string()),
253 PathSegment::Field("name".to_string()),
254 ]);
255
256 let result = ctx.resolve(&path);
257 assert!(result.is_err());
258 }
259
260 #[test]
261 fn test_default_context_is_an_empty_object() {
262 let ctx = Context::default();
263 assert_eq!(ctx.root(), &json!({}));
264 }
265
266 #[test]
267 fn test_context_serializes_as_its_root_value() {
268 let ctx = Context::from_json(json!({"name": "Ada"}));
269 assert_eq!(serde_json::to_value(&ctx).unwrap(), json!({"name": "Ada"}));
270 }
271
272 #[test]
273 fn test_into_context_accepts_a_context() {
274 let ctx = Context::from_json(json!({"name": "Ada"}));
275 assert_eq!(ctx.into_context().unwrap().root(), &json!({"name": "Ada"}));
276 }
277
278 #[test]
279 fn test_into_context_accepts_a_value() {
280 let ctx = json!({"name": "Ada"}).into_context().unwrap();
281 assert_eq!(ctx.root(), &json!({"name": "Ada"}));
282 }
283
284 #[test]
285 fn test_into_context_accepts_a_borrowed_struct() {
286 #[derive(Serialize)]
287 struct User {
288 name: String,
289 }
290
291 let user = User {
292 name: "Ada".to_owned(),
293 };
294
295 let ctx = user.into_context().unwrap();
297 assert_eq!(ctx.root(), &json!({"name": "Ada"}));
298 }
299
300 #[test]
301 fn test_into_context_accepts_a_borrowed_context() {
302 let ctx = Context::from_json(json!({"name": "Ada"}));
303 let copied = (&ctx).into_context().unwrap();
304 assert_eq!(copied.root(), &json!({"name": "Ada"}));
305 }
306}