//! Envelope versioning and guarded decoding. #![allow( clippy::unwrap_used, reason = "a test aborts on failure, which is the intent" )] use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use super::{CURRENT_VERSION, FormatError, from_ron, from_ron_with_migrations, to_ron}; use crate::migrate::{MigrateError, Migration}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] struct Document { answer: f64, } /// A step from version 0 to version 1: add one to `answer`. fn add_one(mut value: ron::Value) -> Result { let ron::Value::Map(ref mut document) = value else { return Err(MigrateError::step(0, "document is not a map")); }; let Some(answer) = document.get_mut(&ron::Value::from("answer")) else { return Err(MigrateError::step(0, "document has no answer")); }; let ron::Value::Number(number) = answer else { return Err(MigrateError::step(0, "answer is not a number")); }; let incremented = (*number).into_f64() + 1.0; *answer = ron::Value::from(incremented); Ok(value) } fn steps() -> BTreeMap { let mut steps = BTreeMap::new(); let _previous = steps.insert(0, add_one as Migration); steps } #[test] fn a_payload_round_trips_at_the_current_version() { let text = to_ron(&Document { answer: 42.0 }).unwrap(); assert!(text.contains("format_version: 1")); assert!(text.contains("payload:")); let document: Document = from_ron(&text).unwrap(); assert_eq!(document, Document { answer: 42.0 }); } #[test] fn a_newer_version_is_rejected() { let text = format!( "(format_version: {}, payload: (answer: 1.0))", CURRENT_VERSION + 1 ); let error = from_ron::(&text).unwrap_err(); assert!(matches!(error, FormatError::TooNew { .. })); } #[test] fn an_older_version_needs_a_registered_step() { let text = "(format_version: 0, payload: (answer: 41.0))"; let error = from_ron::(text).unwrap_err(); assert!(matches!( error, FormatError::Migration(MigrateError::MissingStep { version: 0, .. }) )); } #[test] fn an_older_version_is_migrated_before_decoding() { let text = "(format_version: 0, payload: (answer: 41.0))"; let document: Document = from_ron_with_migrations(text, &steps()).unwrap(); assert_eq!(document, Document { answer: 42.0 }); } #[test] fn a_payload_of_the_wrong_shape_is_a_decode_error() { let text = "(format_version: 1, payload: 7.0)"; let error = from_ron::(text).unwrap_err(); assert!(matches!(error, FormatError::Decode(_))); } #[test] fn malformed_text_is_a_parse_error() { let error = from_ron::("this is not RON").unwrap_err(); assert!(matches!(error, FormatError::Parse(_))); }