1#![cfg_attr(all(coverage_nightly, test), feature(coverage_attribute))]
42#![forbid(unsafe_code)]
43#![warn(missing_docs)]
44
45pub(crate) use jubarte_dom::ooxml;
49pub use jubarte_dom::{ids, namespaces, util, xmllinq};
50pub use jubarte_opc::{admission, opc, strict_translation};
51pub(crate) use jubarte_opc::{
52 builtin_styles, data_stores, markup_simplifier, numbering, validate_dom,
53};
54#[cfg(feature = "render")]
56pub(crate) use jubarte_opc::{borders, table_dom};
57pub use jubarte_redlines::{comparer, document_comparer, revision_processor};
58
59pub mod append;
61pub mod audit;
63pub mod changes;
65#[doc(hidden)]
67pub mod comment_settlement;
68pub mod comments;
70pub mod debug;
72#[cfg(feature = "render")]
74pub mod fields;
75pub mod inspect;
77pub mod scrub;
79pub mod validate;
81
82#[cfg(test)]
83#[cfg_attr(all(coverage_nightly, test), coverage(off))]
84pub(crate) mod corpus {
85 pub(crate) fn fixtures() -> Vec<(String, Vec<u8>)> {
88 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures");
89 let mut out = Vec::new();
90 let mut stack = vec![root.clone()];
91 while let Some(dir) = stack.pop() {
92 for entry in std::fs::read_dir(&dir).expect("fixtures") {
93 let path = entry.expect("entry").path();
94 if path.is_dir() {
95 stack.push(path);
96 } else if path.extension().is_some_and(|e| e == "docx") {
97 let name = path
100 .strip_prefix(&root)
101 .unwrap()
102 .components()
103 .map(|c| c.as_os_str().to_string_lossy())
104 .collect::<Vec<_>>()
105 .join("/");
106 out.push((name, std::fs::read(&path).expect("read")));
107 }
108 }
109 }
110 out.sort();
111 out
112 }
113
114 pub(crate) fn sample() -> Vec<(String, Vec<u8>)> {
117 fixtures().into_iter().step_by(8).collect()
118 }
119
120 fn all_checks() -> crate::debug::Options {
121 use crate::debug::{Check, Options};
122 Options {
123 checks: vec![
124 Check::Orphans,
125 Check::Fields,
126 Check::Bookmarks,
127 Check::Package,
128 Check::Structure,
129 Check::Ids,
130 Check::Styles,
131 Check::Chains,
132 Check::Elements,
133 Check::Textbox,
134 Check::Text,
135 Check::Xml,
136 Check::Runs,
137 Check::Changes,
138 Check::Tables,
139 Check::StyleDefs,
140 Check::Numbering,
141 ],
142 ..Options::default()
143 }
144 }
145
146 #[test]
148 fn every_report_finds_a_file_equal_to_itself() {
149 let opts = all_checks();
150 let files = sample();
151 assert!(files.len() > 20, "{}", files.len());
152 for (name, bytes) in &files {
153 let diff = crate::debug::diff::diff(&[("a", bytes), ("b", bytes)], &Default::default())
154 .unwrap_or_else(|e| panic!("{name}: {e}"));
155 assert_eq!(diff, "files: a · b\nno differences\n", "{name}");
156 let report = crate::debug::report(bytes, Some(bytes), &opts)
157 .unwrap_or_else(|e| panic!("{name}: {e}"));
158 for line in report.lines() {
159 assert!(
160 line.ends_with(" identical") || line.ends_with(": 0 differ"),
161 "{name}: {line}"
162 );
163 }
164 let single =
165 crate::debug::report(bytes, None, &opts).unwrap_or_else(|e| panic!("{name}: {e}"));
166 assert!(!single.is_empty(), "{name}");
167 }
168 }
169
170 #[test]
173 fn neighbouring_fixtures_compare_without_error() {
174 let opts = all_checks();
175 let files = sample();
176 for pair in files.windows(2) {
177 let ((a_name, a), (b_name, b)) = (&pair[0], &pair[1]);
178 let three =
179 crate::debug::diff::diff(&[("a", a), ("b", b), ("c", a)], &Default::default())
180 .unwrap_or_else(|e| panic!("{a_name} {b_name}: {e}"));
181 assert!(
182 three.starts_with("files: a · b · c\n"),
183 "{a_name} {b_name}: {three}"
184 );
185 crate::debug::report(a, Some(b), &opts)
186 .unwrap_or_else(|e| panic!("{a_name} {b_name}: {e}"));
187 }
188 }
189
190 #[test]
194 fn the_readers_accept_every_readable_fixture() {
195 for (name, bytes) in sample() {
196 let changes = crate::changes::list_changes(&bytes);
197 let readable = changes.is_ok();
198 assert_eq!(
199 crate::comments::list_comments(&bytes).is_ok(),
200 readable,
201 "{name}"
202 );
203 assert_eq!(crate::inspect::snapshot(&bytes).is_ok(), readable, "{name}");
204 #[cfg(feature = "render")]
205 assert_eq!(crate::audit::audit(&bytes, &[]).is_ok(), readable, "{name}");
206 assert_eq!(
207 crate::audit::audit_report_with(&bytes, &[], None).is_ok(),
208 readable,
209 "{name}"
210 );
211 assert_eq!(
212 crate::validate::validate(&bytes).is_ok(),
213 readable,
214 "{name}"
215 );
216 if let Ok(changes) = changes {
217 let logical = crate::changes::list_logical_changes_tolerant(&bytes).unwrap();
218 assert!(logical.len() <= changes.len(), "{name}");
219 }
220 }
221 }
222
223 #[test]
227 fn validation_findings_print_and_repair_on_every_other_fixture() {
228 for (name, bytes) in fixtures().into_iter().step_by(2) {
229 let Ok(findings) = crate::validate::validate(&bytes) else {
230 assert!(crate::changes::list_changes(&bytes).is_err(), "{name}");
231 continue;
232 };
233 let text = crate::validate::findings_text(&findings);
234 for f in &findings {
235 assert!(text.contains(&f.code), "{name}: {}", f.code);
236 }
237 assert_eq!(
238 crate::validate::identities(&bytes, &findings).len(),
239 findings.len(),
240 "{name}"
241 );
242 if !findings.iter().any(|f| f.repairable) {
243 continue;
244 }
245 let repaired =
246 crate::validate::repair(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
247 assert_ne!(repaired.docx, bytes, "{name}");
248 let after =
249 crate::validate::validate(&repaired.docx).unwrap_or_else(|e| panic!("{name}: {e}"));
250 assert!(!after.iter().any(|f| f.repairable), "{name}: {after:?}");
251 }
252 }
253
254 #[test]
257 fn a_full_scrub_leaves_no_comment_and_one_author() {
258 for (name, bytes) in fixtures().into_iter().step_by(3) {
259 let Ok(out) = crate::scrub::scrub(&bytes, &crate::scrub::ScrubOptions::default())
260 else {
261 continue;
262 };
263 assert!(
264 crate::comments::list_comments(&out).unwrap().is_empty(),
265 "{name}"
266 );
267 for change in crate::changes::list_changes(&out).unwrap() {
268 assert!(
269 change.author.as_deref().is_none_or(|a| a == "Author"),
270 "{name}: {:?}",
271 change.author
272 );
273 }
274 }
275 }
276
277 #[test]
280 fn audits_and_field_updates_keep_packages_readable() {
281 for (name, bytes) in fixtures().into_iter().step_by(4) {
282 let readable = crate::changes::list_changes(&bytes).is_ok();
283 let report = crate::audit::audit_report_with(&bytes, &[], None);
284 assert_eq!(report.is_ok(), readable, "{name}");
285 #[cfg(feature = "render")]
286 if let Ok(updated) = crate::fields::update_fields(&bytes) {
287 assert!(
288 crate::changes::list_changes(&updated.docx).is_ok(),
289 "{name}"
290 );
291 assert!(updated.page_count >= 1, "{name}");
292 }
293 }
294 }
295
296 const RICH: [&str; 2] = ["agent-view/received.docx", "f1/word-redline.docx"];
297
298 fn rich() -> Vec<(String, Vec<u8>)> {
299 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures");
300 RICH.iter()
301 .map(|name| {
302 (
303 (*name).to_string(),
304 std::fs::read(root.join(name)).expect("fixture"),
305 )
306 })
307 .collect()
308 }
309
310 fn rewrite(bytes: &[u8], edit: impl Fn(&str, String) -> Option<String>) -> Vec<u8> {
312 let mut pkg = crate::opc::PartFs::open(bytes).expect("open");
313 for part in pkg.parts() {
314 if !part.starts_with("word/") || !part.ends_with(".xml") {
315 continue;
316 }
317 let Some(xml) = pkg.part_string(&part) else {
318 continue;
319 };
320 if let Some(new) = edit(&part, xml) {
321 pkg.set_part(&part, new.into_bytes());
322 }
323 }
324 pkg.to_zip().expect("zip")
325 }
326
327 fn with_noise(bytes: &[u8]) -> Vec<u8> {
329 rewrite(bytes, |_, xml| {
330 Some(xml.replace("><", "><!--n--><?jr n?><"))
331 })
332 }
333
334 #[test]
335 fn comments_and_instructions_between_tags_change_no_reading() {
336 for (name, bytes) in rich() {
337 let noisy = with_noise(&bytes);
338 assert_ne!(noisy, bytes);
339 let changes =
340 |b: &[u8]| crate::changes::changes_text(&crate::changes::list_changes(b).unwrap());
341 assert_eq!(changes(&noisy), changes(&bytes), "{name}");
342 let logical = |b: &[u8]| {
343 crate::changes::changes_text(&crate::changes::list_logical_changes(b).unwrap())
344 };
345 assert_eq!(logical(&noisy), logical(&bytes), "{name}");
346 let comments = |b: &[u8]| {
347 crate::comments::comments_text(&crate::comments::list_comments(b).unwrap())
348 };
349 assert_eq!(comments(&noisy), comments(&bytes), "{name}");
350 let text = |b: &[u8]| crate::debug::document_text(b).unwrap();
351 assert_eq!(text(&noisy), text(&bytes), "{name}");
352 let md = |b: &[u8]| crate::inspect::markdown(b).unwrap();
353 assert_eq!(md(&noisy), md(&bytes), "{name}");
354 }
355 }
356
357 #[test]
361 fn noise_between_tags_reaches_every_reader_unchanged() {
362 let opts = all_checks();
363 for (name, bytes) in rich() {
364 let noisy = with_noise(&bytes);
365 let codes = |b: &[u8]| {
366 let mut c: Vec<String> = crate::validate::validate(b)
367 .unwrap()
368 .into_iter()
369 .map(|f| f.code)
370 .collect();
371 c.sort();
372 c
373 };
374 assert_eq!(codes(&noisy), codes(&bytes), "{name}");
375 let report = crate::debug::report(&bytes, Some(&noisy), &opts).unwrap();
376 for line in report.lines() {
377 assert!(
378 line.ends_with(" identical") || line.ends_with(": 0 differ"),
379 "{name}: {line}"
380 );
381 }
382 let audit = |b: &[u8]| {
383 crate::audit::audit_report_with(b, &[], None)
384 .unwrap()
385 .findings
386 .len()
387 };
388 assert_eq!(audit(&noisy), audit(&bytes), "{name}");
389 let scrubbed =
390 crate::scrub::scrub(&noisy, &crate::scrub::ScrubOptions::default()).unwrap();
391 assert!(
392 crate::comments::list_comments(&scrubbed)
393 .unwrap()
394 .is_empty(),
395 "{name}"
396 );
397 #[cfg(feature = "render")]
398 {
399 let fields = |b: &[u8]| crate::fields::update_fields(b).unwrap().fields.len();
400 assert_eq!(fields(&noisy), fields(&bytes), "{name}");
401 }
402 let appended =
403 crate::append::append_documents(&noisy, &noisy, &Default::default()).unwrap();
404 let before = crate::changes::list_changes(&bytes).unwrap().len();
405 assert!(
406 crate::changes::list_changes(&appended.docx).unwrap().len() >= before,
407 "{name}"
408 );
409 }
410 }
411
412 #[test]
416 fn parts_with_no_root_element_are_refused_or_read_as_empty() {
417 let opts = all_checks();
418 for (name, bytes) in rich() {
419 let gone = rewrite(&bytes, |_, _| {
420 Some("<?xml version=\"1.0\"?><!--gone-->".to_string())
421 });
422 assert!(
423 crate::changes::list_changes(&gone).unwrap().is_empty(),
424 "{name}"
425 );
426 let refusal = "word/document.xml: missing or incomplete XML root";
427 let comments = crate::comments::list_comments(&gone)
428 .unwrap_err()
429 .to_string();
430 assert!(comments.contains(refusal), "{name}: {comments}");
431 assert!(crate::inspect::snapshot(&gone).is_err(), "{name}");
432 let audit = crate::audit::audit_report_with(&gone, &[], None)
433 .unwrap_err()
434 .to_string();
435 assert!(audit.contains(refusal), "{name}: {audit}");
436 assert!(
437 !crate::debug::report(&gone, None, &opts).unwrap().is_empty(),
438 "{name}"
439 );
440 let diff =
441 crate::debug::diff::diff(&[("a", &bytes), ("b", &gone)], &Default::default())
442 .unwrap();
443 assert!(
444 diff.starts_with("files: a · b\n") && diff.contains("word/document.xml"),
445 "{name}"
446 );
447 }
448 }
449
450 pub(crate) fn word_redlines() -> Vec<(String, Vec<u8>, Vec<u8>)> {
452 let mut out = Vec::new();
453 let all = fixtures();
454 for (name, bytes) in &all {
455 let original = if let Some(stem) = name.strip_suffix("_word_redline.docx") {
456 format!("{stem}_a.docx")
457 } else if let Some(dir) = name.strip_suffix("word-redline.docx") {
458 format!("{dir}original.docx")
459 } else {
460 continue;
461 };
462 if let Some((_, before)) = all.iter().find(|(n, _)| *n == original) {
463 out.push((name.clone(), before.clone(), bytes.clone()));
464 }
465 }
466 out
467 }
468
469 fn codes(findings: Vec<crate::validate::Finding>) -> Vec<String> {
470 findings.into_iter().map(|f| f.code).collect()
471 }
472
473 #[test]
477 fn word_redlines_audit_as_their_authors_edits() {
478 let pairs = word_redlines();
479 assert!(pairs.len() >= 10, "{}", pairs.len());
480 for (name, before, after) in pairs {
481 let authors: std::collections::BTreeSet<String> = crate::changes::list_changes(&after)
482 .unwrap()
483 .into_iter()
484 .filter_map(|c| c.author)
485 .collect();
486 assert!(
487 crate::validate::audit_tracked(&before, &before, "Nobody")
488 .unwrap()
489 .is_empty(),
490 "{name}"
491 );
492 let other = codes(crate::validate::audit_tracked(&before, &after, "Nobody").unwrap());
493 assert!(
494 other.iter().any(|c| c == "FOREIGN_AUTHOR"),
495 "{name}: {other:?}"
496 );
497 assert!(
498 other
499 .iter()
500 .all(|c| c == "FOREIGN_AUTHOR" || c == "UNTRACKED_EDIT"),
501 "{name}: {other:?}"
502 );
503 if authors.len() == 1 && authors.contains("Comparison") {
504 let own = crate::validate::audit_tracked(&before, &after, "Comparison").unwrap();
505 assert!(own.is_empty(), "{name}: {own:?}");
506 let rules = crate::validate::validate_with(
507 &after,
508 &["edits"],
509 Some((&before, "Comparison")),
510 None,
511 )
512 .unwrap();
513 assert!(rules.is_empty(), "{name}: {rules:?}");
514 }
515 }
516 }
517
518 #[test]
519 fn rule_selection_refuses_what_it_cannot_run() {
520 let (_, before, after) = word_redlines().remove(0);
521 let unknown =
522 crate::validate::validate_with(&after, &["nonsense"], None, None).unwrap_err();
523 assert!(unknown.to_string().contains("nonsense"), "{unknown}");
524 let alone = crate::validate::validate_with(&after, &["edits"], None, None).unwrap_err();
525 assert!(alone.to_string().contains("needs --author"), "{alone}");
526 let audit =
527 crate::validate::validate_with(&after, &["a11y"], Some((&before, "Nobody")), None)
528 .unwrap();
529 assert!(
530 audit.iter().any(|f| f.code == "FOREIGN_AUTHOR"),
531 "{audit:?}"
532 );
533 }
534
535 const COMMENT_DAMAGE: &[(&str, &str, &str, &str, &str)] = &[
540 (
541 "parent cycle",
542 "word/commentsExtended.xml",
543 "w15:paraId=\"11A5D0F2\" w15:done",
544 "w15:paraId=\"11A5D0F2\" w15:paraIdParent=\"33767091\" w15:done",
545 "COMMENT_PARENT_CYCLE",
546 ),
547 (
548 "own parent",
549 "word/commentsExtended.xml",
550 "w15:paraId=\"214DA01E\" w15:done",
551 "w15:paraId=\"214DA01E\" w15:paraIdParent=\"214DA01E\" w15:done",
552 "COMMENT_PARENT_CYCLE",
553 ),
554 (
555 "unknown parent",
556 "word/commentsExtended.xml",
557 "w15:paraIdParent=\"11A5D0F2\"",
558 "w15:paraIdParent=\"DEADBEEF\"",
559 "COMMENT_METADATA_MISMATCH",
560 ),
561 (
562 "one durable id",
563 "word/commentsIds.xml",
564 "4500665B",
565 "15907BBC",
566 "COMMENT_METADATA_MISMATCH",
567 ),
568 (
569 "bad durable id",
570 "word/commentsIds.xml",
571 "6C9BB659",
572 "XYZ",
573 "COMMENT_PARTS_INCONSISTENT",
574 ),
575 (
576 "unknown para",
577 "word/commentsIds.xml",
578 "w16cid:paraId=\"214DA01E\"",
579 "w16cid:paraId=\"0BADF00D\"",
580 "COMMENT_METADATA_MISMATCH",
581 ),
582 (
583 "idless start",
584 "word/document.xml",
585 "<w:commentRangeStart w:id=\"5\"/>",
586 "<w:commentRangeStart/>",
587 "COMMENT_RANGE_UNPAIRED",
588 ),
589 (
590 "idless reference",
591 "word/document.xml",
592 "<w:commentReference w:id=\"11\"/>",
593 "<w:commentReference/>",
594 "COMMENT_UNANCHORED",
595 ),
596 (
597 "unknown reference",
598 "word/document.xml",
599 "<w:commentReference w:id=\"6\"/>",
600 "<w:commentReference w:id=\"99\"/>",
601 "COMMENT_ANCHOR_ORPHAN",
602 ),
603 (
604 "no end",
605 "word/document.xml",
606 "<w:commentRangeEnd w:id=\"11\"/>",
607 "",
608 "COMMENT_RANGE_UNPAIRED",
609 ),
610 (
611 "no start",
612 "word/document.xml",
613 "<w:commentRangeStart w:id=\"6\"/>",
614 "",
615 "COMMENT_RANGE_UNPAIRED",
616 ),
617 (
618 "no author",
619 "word/comments.xml",
620 "w:author=\"Ann Counsel\"",
621 "",
622 "",
623 ),
624 (
625 "idless comment",
626 "word/comments.xml",
627 "<w:comment w:id=\"11\"",
628 "<w:comment",
629 "COMMENT_RANGE_ORPHAN",
630 ),
631 ];
632
633 fn damaged(bytes: &[u8], part: &str, from: &str, to: &str) -> Vec<u8> {
634 let mut pkg = crate::opc::PartFs::open(bytes).expect("open");
635 let xml = pkg.part_string(part).expect(part);
636 assert!(xml.contains(from), "{part} lacks {from}");
637 pkg.set_part(part, xml.replace(from, to).into_bytes());
638 pkg.to_zip().expect("zip")
639 }
640
641 #[test]
644 fn damaged_comment_parts_are_reported_and_still_read() {
645 let opts = all_checks();
646 let (_, bytes) = rich().remove(0);
647 let ids = |b: &[u8]| -> Vec<u32> {
648 crate::comments::list_comments(b)
649 .unwrap()
650 .iter()
651 .map(|c| c.id)
652 .collect()
653 };
654 let original = ids(&bytes);
655 assert_eq!(original, [5, 6, 11]);
656 let baseline = codes(crate::validate::validate(&bytes).unwrap());
657 let carry = crate::append::AppendOptions {
658 comments: crate::append::AppendComments::Carry,
659 ..Default::default()
660 };
661 for (label, part, from, to, code) in COMMENT_DAMAGE {
662 let b = damaged(&bytes, part, from, to);
663 assert!(ids(&b).iter().all(|id| original.contains(id)), "{label}");
664 let found = codes(crate::validate::validate(&b).unwrap());
665 let count = |list: &[String]| list.iter().filter(|c| c == code).count();
666 if !code.is_empty() {
667 assert!(count(&found) > count(&baseline), "{label}: {found:?}");
668 }
669 crate::debug::report(&b, None, &opts).unwrap_or_else(|e| panic!("{label}: {e}"));
670 let scrubbed = crate::scrub::scrub(&b, &crate::scrub::ScrubOptions::default()).unwrap();
671 assert!(ids(&scrubbed).is_empty(), "{label}");
672 let appended = crate::append::append_documents(&b, &b, &carry).unwrap();
673 crate::comments::list_comments(&appended.docx)
674 .unwrap_or_else(|e| panic!("{label}: {e}"));
675 assert!(!crate::inspect::markdown(&b).unwrap().is_empty(), "{label}");
676 }
677 }
678
679 #[test]
682 fn diff_options_narrow_and_widen_the_listing() {
683 use crate::debug::diff::{DiffOptions, diff};
684 let (_, before, after) = word_redlines()
685 .into_iter()
686 .find(|(n, ..)| n.starts_with("f4/"))
687 .unwrap();
688 let files = [("a", &before[..]), ("b", &after[..])];
689 let plain = diff(&files, &DiffOptions::default()).unwrap();
690 let raw = diff(
691 &files,
692 &DiffOptions {
693 raw: true,
694 ..Default::default()
695 },
696 )
697 .unwrap();
698 assert!(raw.len() >= plain.len());
699 let full = diff(
700 &files,
701 &DiffOptions {
702 full: true,
703 ..Default::default()
704 },
705 )
706 .unwrap();
707 assert!(full.len() >= plain.len());
708 let one = diff(
709 &files,
710 &DiffOptions {
711 limit: 1,
712 ..Default::default()
713 },
714 )
715 .unwrap();
716 assert!(one.len() <= plain.len());
717 let styles = diff(
718 &files,
719 &DiffOptions {
720 part: Some("styles".into()),
721 ..Default::default()
722 },
723 )
724 .unwrap();
725 assert!(!styles.contains("word/document.xml"), "{styles}");
726 let normal = diff(
727 &files,
728 &DiffOptions {
729 style: Some("normal".into()),
730 ..Default::default()
731 },
732 )
733 .unwrap();
734 assert!(normal.starts_with("files: a · b"));
735 let none = diff(
736 &files,
737 &DiffOptions {
738 para_text: Some("\u{1}never".into()),
739 ..Default::default()
740 },
741 )
742 .unwrap();
743 assert!(none.len() <= plain.len());
744 assert!(diff(&files[..1], &DiffOptions::default()).is_err());
745 }
746
747 #[test]
749 fn report_options_narrow_the_two_file_views() {
750 use crate::debug::{Check, Options, report};
751 let (_, before, after) = word_redlines()
752 .into_iter()
753 .find(|(n, ..)| n.starts_with("f4/"))
754 .unwrap();
755 let checks = vec![
756 Check::Text,
757 Check::Xml,
758 Check::Runs,
759 Check::Changes,
760 Check::Tables,
761 Check::Textbox,
762 ];
763 let wide = report(
764 &before,
765 Some(&after),
766 &Options {
767 checks: checks.clone(),
768 context: 2,
769 full_lines: true,
770 ..Options::default()
771 },
772 )
773 .unwrap();
774 let narrow = report(
775 &before,
776 Some(&after),
777 &Options {
778 checks: checks.clone(),
779 part: Some("document".into()),
780 limit: 1,
781 ..Options::default()
782 },
783 )
784 .unwrap();
785 assert!(!wide.is_empty() && !narrow.is_empty());
786 let grep = report(
787 &after,
788 None,
789 &Options {
790 checks,
791 grep: Some("the".into()),
792 ..Options::default()
793 },
794 )
795 .unwrap();
796 assert!(!grep.is_empty());
797 let nothing = report(
798 &after,
799 None,
800 &Options {
801 checks: vec![Check::Xml],
802 part: Some("\u{1}none".into()),
803 ..Options::default()
804 },
805 )
806 .unwrap();
807 assert!(!nothing.contains("<w:"), "{nothing}");
808 }
809
810 fn without_story_parts(bytes: &[u8]) -> Vec<u8> {
811 let mut pkg = crate::opc::PartFs::open(bytes).expect("open");
812 for part in pkg.parts() {
813 let stem = part.trim_start_matches("word/");
814 if ["header", "footer", "footnotes", "endnotes", "comments"]
815 .iter()
816 .any(|s| stem.starts_with(s))
817 {
818 pkg.remove_part(&part);
819 }
820 }
821 pkg.to_zip().expect("zip")
822 }
823
824 #[test]
828 fn related_story_parts_that_are_missing() {
829 let opts = all_checks();
830 for (name, bytes) in rich() {
831 let b = without_story_parts(&bytes);
832 let found = crate::validate::validate(&b).unwrap();
833 let has = |code: &str| found.iter().any(|f| f.code == code);
834 assert!(
835 has("MISSING_REL_TARGET") && has("OVERRIDE_WITHOUT_PART"),
836 "{name}"
837 );
838 let repaired = crate::validate::repair(&b).unwrap();
839 assert!(!repaired.repaired.is_empty(), "{name}");
840 assert!(
841 repaired
842 .repaired
843 .iter()
844 .all(|r| found.iter().any(|f| f.code == r.code)),
845 "{name}"
846 );
847 assert_eq!(
848 crate::validate::validate(&repaired.docx).unwrap().len(),
849 repaired.remaining.len(),
850 "{name}"
851 );
852 assert!(
853 !crate::changes::list_changes(&b).unwrap().is_empty(),
854 "{name}"
855 );
856 assert!(
857 crate::comments::list_comments(&b).unwrap().is_empty(),
858 "{name}"
859 );
860 crate::debug::report(&b, Some(&bytes), &opts).unwrap();
861 crate::scrub::scrub(&b, &crate::scrub::ScrubOptions::default()).unwrap();
862 crate::append::append_documents(&bytes, &b, &Default::default()).unwrap();
863 assert_eq!(
864 crate::inspect::markdown(&b).is_ok(),
865 crate::audit::audit_report_with(&b, &[], None).is_ok(),
866 "{name}"
867 );
868 }
869 }
870
871 #[test]
874 fn paragraph_ids_past_words_range_are_renumbered() {
875 let (_, bytes) = rich().remove(0);
876 let high = rewrite(&bytes, |_, xml| Some(xml.replace("11A5D0F2", "91A5D0F2")));
877 let found = codes(crate::validate::validate(&high).unwrap());
878 let base = codes(crate::validate::validate(&bytes).unwrap());
879 assert!(found.len() > base.len(), "{found:?}");
880 let repaired = crate::validate::repair(&high).unwrap();
881 assert!(!repaired.repaired.is_empty(), "{found:?}");
882 let after = crate::comments::list_comments(&repaired.docx).unwrap();
883 assert_eq!(after.len(), 3);
884 }
885
886 fn with_permission(bytes: &[u8]) -> Vec<u8> {
887 rewrite(bytes, |part, xml| {
888 (part == "word/document.xml").then(|| {
889 xml.replacen(
890 "<w:body>",
891 "<w:body><w:permStart w:id=\"7\" w:edGrp=\"everyone\"/>",
892 1,
893 )
894 .replacen("<w:sectPr", "<w:permEnd w:id=\"7\"/><w:sectPr", 1)
895 })
896 })
897 }
898
899 #[test]
902 fn dropped_permission_ranges_are_reported() {
903 let (name, before, after) = word_redlines()
904 .into_iter()
905 .find(|(n, ..)| n.contains("case28"))
906 .unwrap();
907 let dropped = |b: &[u8], a: &[u8]| {
908 codes(crate::validate::audit_tracked(b, a, "Comparison").unwrap())
909 .iter()
910 .filter(|c| *c == "PERMISSION_RANGE_DROPPED")
911 .count()
912 };
913 let granted = with_permission(&before);
914 assert!(dropped(&granted, &after) > 0, "{name}");
915 assert_eq!(dropped(&granted, &with_permission(&after)), 0, "{name}");
916 assert_eq!(dropped(&before, &after), 0, "{name}");
917 }
918
919 #[test]
922 fn revisions_inside_comments_name_their_comment() {
923 let (_, bytes) = rich().remove(0);
924 let ins = |id: &str, text: &str| {
925 format!(
926 "<w:ins w:id=\"{id}\" w:author=\"R\" w:date=\"2026-01-01T00:00:00Z\"><w:r><w:t>{text}</w:t></w:r></w:ins>"
927 )
928 };
929 let one = damaged(
930 &bytes,
931 "word/comments.xml",
932 "<w:t>Disagree.</w:t></w:r>",
933 &format!("<w:t>Disagree.</w:t></w:r>{}", ins("900", " Strongly.")),
934 );
935 let bodies = crate::changes::comment_bodies(&one).unwrap();
936 assert_eq!(bodies.comments.len(), 3);
937 assert_eq!(
938 bodies.owners.values().flatten().collect::<Vec<_>>(),
939 [&"6".to_string()]
940 );
941 let shared = damaged(
942 &one,
943 "word/comments.xml",
944 "<w:t>Add a three-year survival period?</w:t></w:r>",
945 &format!(
946 "<w:t>Add a three-year survival period?</w:t></w:r>{}",
947 ins("900", " Or two.")
948 ),
949 );
950 let bodies = crate::changes::comment_bodies(&shared).unwrap();
951 assert_eq!(bodies.owners.len(), 1);
952 assert_eq!(bodies.owners.values().next(), Some(&None));
953 let none = crate::changes::comment_bodies(&without_story_parts(&bytes)).unwrap();
954 assert!(none.comments.is_empty() && none.owners.is_empty());
955 }
956
957 #[test]
960 fn wrapped_body_content_is_read_through_its_wrappers() {
961 let (_, bytes) = rich().remove(0);
962 let extra = concat!(
963 "<w:sdt><w:sdtPr/><w:sdtContent><w:p><w:r><w:t>Inside a control</w:t></w:r></w:p></w:sdtContent></w:sdt>",
964 "<w:p><mc:AlternateContent xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\">",
965 "<mc:Choice Requires=\"w14\"><w:r><w:t>Chosen text</w:t></w:r></mc:Choice>",
966 "<mc:Fallback><w:r><w:t>Fallback text</w:t></w:r></mc:Fallback></mc:AlternateContent></w:p>",
967 "<w:p><w:r><x:foo xmlns:x=\"urn:x\"/><w:t>Foreign run</w:t></w:r></w:p>",
968 );
969 let wrapped = damaged(
970 &bytes,
971 "word/document.xml",
972 "<w:body>",
973 &format!("<w:body>{extra}"),
974 );
975 let md = crate::inspect::markdown(&wrapped).unwrap();
976 for text in ["Inside a control", "Chosen text", "Foreign run"] {
977 assert!(md.contains(text), "{text}: {md}");
978 }
979 assert!(!md.contains("Fallback text"), "{md}");
980 let paragraphs = crate::inspect::paragraphs(&wrapped).unwrap().len();
981 assert_eq!(
982 paragraphs,
983 crate::inspect::paragraphs(&bytes).unwrap().len() + 3
984 );
985 }
986
987 #[test]
991 fn appending_varied_documents_keeps_the_first_whole() {
992 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures");
993 let names = [
994 "agent-view/received.docx",
995 "f1/word-redline.docx",
996 "nested_table/hf_b.docx",
997 "f4/original.docx",
998 "redline-inpi/modified-new-2.docx",
999 ];
1000 let files: Vec<Vec<u8>> = names
1001 .iter()
1002 .map(|n| std::fs::read(root.join(n)).unwrap())
1003 .collect();
1004 let count = |b: &[u8]| crate::changes::list_changes(b).unwrap().len();
1005 let breaks = [
1006 crate::append::SectionBreak::NextPage,
1007 crate::append::SectionBreak::Continuous,
1008 crate::append::SectionBreak::None,
1009 ];
1010 for (i, a) in files.iter().enumerate() {
1011 for (j, b) in files.iter().enumerate() {
1012 if i == j {
1013 continue;
1014 }
1015 let options = crate::append::AppendOptions {
1016 section_break: breaks[(i + j) % 3],
1017 keep_sections: (i + j) % 2 == 0,
1018 comments: if i % 2 == 0 {
1019 crate::append::AppendComments::Carry
1020 } else {
1021 crate::append::AppendComments::Drop
1022 },
1023 };
1024 let label = format!("{} + {}", names[i], names[j]);
1025 let out = crate::append::append_documents(a, b, &options)
1026 .unwrap_or_else(|e| panic!("{label}: {e}"));
1027 let joined = count(&out.docx);
1028 assert!(
1029 joined >= count(a) && joined <= count(a) + count(b),
1030 "{label}: {joined}"
1031 );
1032 crate::validate::validate(&out.docx).unwrap_or_else(|e| panic!("{label}: {e}"));
1033 }
1034 }
1035 }
1036
1037 fn with_styles(bytes: &[u8], styles: &str) -> Vec<u8> {
1038 let xml = format!(
1039 "<?xml version=\"1.0\"?><w:styles xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">{styles}</w:styles>"
1040 );
1041 rewrite(bytes, |part, _| {
1042 (part == "word/styles.xml").then(|| xml.clone())
1043 })
1044 }
1045
1046 #[test]
1051 fn the_style_named_normal_carries_the_language() {
1052 let (_, bytes) = rich().remove(0);
1053 let no_settings_lang = rewrite(&bytes, |part, xml| {
1054 (part == "word/settings.xml").then(|| xml.replace("w:themeFontLang", "w:noFontLang"))
1055 });
1056 let normal = |lang: &str| {
1057 format!(
1058 "<w:docDefaults><w:pPrDefault/></w:docDefaults>\
1059 <w:style w:type=\"paragraph\"><w:name w:val=\"Orphan\"/></w:style>\
1060 <w:style w:type=\"paragraph\" w:styleId=\"style0\"><w:name w:val=\"Normal\"/><w:rPr>{lang}</w:rPr></w:style>"
1061 )
1062 };
1063 let codes = |styles: &str| {
1064 crate::audit::audit_report_with(&with_styles(&no_settings_lang, styles), &[], None)
1065 .unwrap()
1066 .findings
1067 .into_iter()
1068 .map(|f| f.code)
1069 .collect::<Vec<_>>()
1070 };
1071 assert_eq!(
1072 codes(&normal("<w:lang w:val=\"en-US\"/>")),
1073 Vec::<String>::new()
1074 );
1075 assert_eq!(codes(&normal("")), ["MISSING_LANG"]);
1076 assert!(
1077 crate::audit::audit_report_with(&bytes, &[], None)
1078 .unwrap()
1079 .findings
1080 .is_empty()
1081 );
1082 }
1083
1084 #[test]
1086 fn an_empty_inline_content_control_adds_no_text() {
1087 let (_, bytes) = rich().remove(0);
1088 let sdt = damaged(
1089 &bytes,
1090 "word/document.xml",
1091 "<w:body>",
1092 "<w:body><w:p><w:sdt><w:sdtPr/></w:sdt><w:r><w:t>After control</w:t></w:r></w:p>",
1093 );
1094 let md = crate::inspect::markdown(&sdt).unwrap();
1095 assert!(md.starts_with("[p0] After control\n"), "{md}");
1096 }
1097}