//! Section printer, note and chapter-number metadata survives DOCX and native JSON saves. use std::io::{Read, Write}; fn docx(body: &str) -> Vec { let root = r#""#; let doc = format!( r#"{body}"# ); let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); for (name, bytes) in [("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())] { zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); zw.write_all(bytes).unwrap(); } zw.finish().unwrap().into_inner() } fn document_xml(bytes: &[u8]) -> String { let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); let mut s = String::new(); z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap(); s } #[test] fn section_metadata_survives_native_json_and_two_docx_save_reopen_cycles() { let input = docx( r#"First sectionSecond section"#, ); let mut document = craft_docx::read(&input).unwrap(); let json = serde_json::to_vec(&document).unwrap(); document = serde_json::from_slice(&json).unwrap(); for cycle in 0..2 { let bytes = craft_docx::write(&document).unwrap(); let xml = document_xml(&bytes); assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); assert!(xml.contains(""), "cycle {cycle}: {xml}"); assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); assert!(xml.contains(r#"w:chapStyle="1" w:chapSep="hyphen""#), "cycle {cycle}: {xml}"); assert!(xml.contains(r#"w:chapStyle="10" w:chapSep="colon""#), "cycle {cycle}: {xml}"); assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14\""), "cycle {cycle}: {xml}"); document = craft_docx::read(&bytes).unwrap(); let json = serde_json::to_vec(&document).unwrap(); document = serde_json::from_slice(&json).unwrap(); } } #[test] fn invalid_section_metadata_is_ignored_and_missing_values_stay_missing() { let bytes = docx( r#"Text"#, ); let mut d = craft_docx::read(&bytes).unwrap(); let xml = document_xml(&craft_docx::write(&d).unwrap()); assert!(!xml.contains("paperSrc"), "{xml}"); assert!(!xml.contains("footnoteColumns"), "{xml}"); assert!(!xml.contains("chapStyle") && !xml.contains("chapSep"), "{xml}"); assert!(!xml.contains("noEndnote"), "{xml}"); d.last_section.footnote_columns = Some(0); let xml = document_xml(&craft_docx::write(&d).unwrap()); assert!(!xml.contains("footnoteColumns"), "{xml}"); }