f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Tests of the named edits on small generated packages: the splices that each edit makes, the
//! faults of each, and the check after on the blocks that the body reader reads from the new
//! main document part.

mod parts;

use f_office_opc::{Limits, Package, PartChange, write_package};
use f_office_xml::{Document, Limits as XmlLimits};

use super::{ExpectedBlocks, NamedEdit, NamedError, NamedFault, NamedPlan, Place, Splice, plan};
use crate::body::Body;
use crate::ns::{self, W};
use crate::quirks::BodyFieldResults;
use crate::reader::PartReader;
use crate::testing::{Builder, DOCUMENT, WordParts as _, docx};
use crate::text_blocks::{TextBlock, TextBlockKind, text_blocks};

/// The styles of the test files: Normal by default, a heading whose next style is Normal, a
/// quote, and a table style.
const STYLES: &str = r#"<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:next w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/></w:style><w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/></w:style>"#;

/// The content types of the test files, which a comment or an image adds to.
const CONTENT_TYPES: &str = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/></Types>"#;

/// A file with `body`: its bytes, its package and its text blocks.
struct File {
    bytes: Vec<u8>,
    blocks: Vec<TextBlock>,
}

impl File {
    fn new(body: &str) -> Self {
        Self::with(body, |builder| builder)
    }

    /// The file of `body` with the parts that `parts` adds.
    fn with(body: &str, parts: impl FnOnce(Builder) -> Builder) -> Self {
        let builder = docx(body)
            .word_part("styles", "styles", "styles.xml", "styles", STYLES)
            .part("[Content_Types].xml", CONTENT_TYPES);
        let bytes = parts(builder).zip().unwrap();
        let blocks = blocks_of(&bytes);
        Self { bytes, blocks }
    }

    fn package(&self) -> Package {
        Package::open(&self.bytes, &Limits::default()).unwrap()
    }

    /// The plan of `edits`, each at its index.
    fn plan(&self, edits: &[NamedEdit]) -> Result<NamedPlan, NamedError> {
        let indexed: Vec<(usize, &NamedEdit)> = edits.iter().enumerate().collect();
        plan(
            &self.package(),
            &self.blocks,
            &indexed,
            &XmlLimits::default(),
        )
    }

    /// The fault of `edits`, with its edit.
    fn fault(&self, edits: &[NamedEdit]) -> (Option<usize>, NamedFault) {
        let NamedError { edit, fault } = self.plan(edits).unwrap_err();
        (edit, fault)
    }

    /// The new file of `edits`, after the check after passes: its main document part and its
    /// text blocks.
    fn edited(&self, edits: &[NamedEdit]) -> (String, Vec<TextBlock>) {
        let (bytes, blocks) = self.edited_file(edits);
        (part_text(&bytes, DOCUMENT), blocks)
    }

    /// The new file of `edits`, with the splices of every part and the new parts, after the
    /// check after passes: its bytes and its text blocks.
    fn edited_file(&self, edits: &[NamedEdit]) -> (Vec<u8>, Vec<TextBlock>) {
        let planned = self.plan(edits).unwrap();
        let package = self.package();
        let mut parts: Vec<(&str, Vec<Splice>)> = vec![(DOCUMENT, planned.splices.clone())];
        for (name, splice) in &planned.related {
            match parts.iter_mut().find(|(part, _)| part == name) {
                Some((_, splices)) => splices.push(splice.clone()),
                None => parts.push((name, vec![splice.clone()])),
            }
        }
        let replaced: Vec<(&str, String)> = parts
            .iter()
            .map(|(name, splices)| (*name, spliced(package.part(name).unwrap(), splices)))
            .collect();
        let changes: Vec<PartChange<'_>> = replaced
            .iter()
            .map(|(name, xml)| PartChange::Replace {
                name,
                data: xml.as_bytes(),
            })
            .chain(planned.new_parts.iter().map(|part| PartChange::Add {
                name: &part.name,
                data: &part.data,
            }))
            .collect();
        let bytes = write_package(&self.bytes, &changes, &Limits::default()).unwrap();
        let edited = Package::open(&bytes, &Limits::default()).unwrap();
        for name in edited.part_names() {
            let data = edited.part(name).unwrap();
            let extension = std::path::Path::new(name).extension();
            if extension.is_some_and(|ext| {
                ext.eq_ignore_ascii_case("xml") || ext.eq_ignore_ascii_case("rels")
            }) {
                Document::parse(data, &XmlLimits::default()).unwrap();
            }
        }
        let blocks = blocks_of(&bytes);
        planned.expected.compare(&blocks).unwrap();
        (bytes, blocks)
    }
}

/// The part `name` of the DOCX file `bytes`, as text.
fn part_text(bytes: &[u8], name: &str) -> String {
    let package = Package::open(bytes, &Limits::default()).unwrap();
    String::from_utf8(package.part(name).unwrap().to_vec()).unwrap()
}

/// The part `bytes` with `splices`.
fn spliced(bytes: &[u8], splices: &[Splice]) -> String {
    let main = bytes;
    let mut splices = splices.to_vec();
    splices.sort_by_key(|splice| (splice.range.start, splice.range.end, splice.edit));
    let mut out = Vec::new();
    let mut cursor = 0;
    for splice in &splices {
        out.extend_from_slice(&main[cursor..splice.range.start]);
        out.extend_from_slice(splice.xml.as_bytes());
        cursor = splice.range.end;
    }
    out.extend_from_slice(&main[cursor..]);
    String::from_utf8(out).unwrap()
}

/// The text blocks of the body of the DOCX file `bytes`, as the body reader numbers them.
fn blocks_of(bytes: &[u8]) -> Vec<TextBlock> {
    let package = Package::open(bytes, &Limits::default()).unwrap();
    let main = package.part(DOCUMENT).unwrap();
    let doc =
        Document::parse_with_aliases(main, &XmlLimits::default(), ns::STRICT_ALIASES).unwrap();
    let body = doc.child(doc.root().unwrap(), W, "body").unwrap();
    let read = Body::read(
        &mut PartReader::new(&doc),
        body,
        (
            crate::reader::settings::ReaderSettings::base()
                .with_body_results(BodyFieldResults::ComputesFields)
                .with_section_ends(crate::quirks::ContinuousSectionEnd::OnlyBlockKeepsLine),
            crate::mode::ModeRules::default(),
        ),
    );
    text_blocks(
        &read.blocks,
        &[],
        (&crate::styles::Styles::without_part(), None),
    )
}

fn at(text: &str) -> crate::Address {
    text.parse().unwrap()
}

fn replace(address: &str, find: &str, with: &str) -> NamedEdit {
    NamedEdit::Replace {
        at: at(address),
        find: find.to_owned(),
        with: with.to_owned(),
    }
}

fn insert(address: &str, place: Place, text: &str, style: Option<&str>) -> NamedEdit {
    NamedEdit::Insert {
        at: at(address),
        place,
        text: text.to_owned(),
        style: style.map(str::to_owned),
    }
}

fn delete(address: &str) -> NamedEdit {
    NamedEdit::Delete { at: at(address) }
}

fn style(address: &str, style: &str) -> NamedEdit {
    NamedEdit::Style {
        at: at(address),
        style: style.to_owned(),
    }
}

/// A paragraph of one run with `text`.
fn p(text: &str) -> String {
    format!(r#"<w:p><w:r><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#)
}

/// The texts of the paragraphs of `blocks`.
fn texts(blocks: &[TextBlock]) -> Vec<&str> {
    blocks
        .iter()
        .filter_map(|block| match &block.kind {
            TextBlockKind::Paragraph { text, .. } => Some(text.as_str()),
            TextBlockKind::Table { .. } => None,
        })
        .collect()
}

/// The style of the paragraph of `blocks` at `address`.
fn style_at<'b>(blocks: &'b [TextBlock], address: &str) -> Option<&'b str> {
    blocks
        .iter()
        .find(|block| block.address == at(address))
        .and_then(|block| match &block.kind {
            TextBlockKind::Paragraph { style, .. } => style.as_deref(),
            TextBlockKind::Table { .. } => None,
        })
}

#[test]
fn replaces_text_across_runs_in_the_formatting_of_the_first_run() {
    let body = r#"<w:p><w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve">Pay in 30 </w:t></w:r><w:r><w:t>days now</w:t></w:r></w:p>"#;
    let file = File::new(body);
    let (xml, blocks) = file.edited(&[replace("p1", "30 days", "45 days")]);
    assert!(
        xml.contains(r#"<w:r><w:rPr><w:b/></w:rPr><w:t>Pay in 45 days</w:t></w:r><w:r><w:t xml:space="preserve"> now</w:t></w:r>"#),
        "{xml}"
    );
    assert_eq!(texts(&blocks), ["Pay in 45 days now"]);
}

#[test]
fn makes_two_replaces_of_one_text_element() {
    let file = File::new(&p("Pay in 30 days now"));
    let (_, blocks) = file.edited(&[replace("p1", "30", "45"), replace("p1", "now", "later")]);
    assert_eq!(texts(&blocks), ["Pay in 45 days later"]);
    assert_eq!(
        file.fault(&[replace("p1", "30 days", "x"), replace("p1", "days", "y")]),
        (Some(1), NamedFault::MatchesOverlap { other: 0 })
    );
}

#[test]
fn refuses_a_find_that_is_not_once_in_the_text() {
    let file = File::new(&p("one and one"));
    assert_eq!(
        file.fault(&[replace("p1", "two", "x")]),
        (Some(0), NamedFault::TextNotFound)
    );
    assert_eq!(
        file.fault(&[replace("p1", "one", "x")]),
        (Some(0), NamedFault::TextAmbiguous { count: 2 })
    );
    assert_eq!(
        file.fault(&[replace("p1", "", "x")]),
        (Some(0), NamedFault::EmptyFind)
    );
    assert_eq!(
        file.fault(&[replace("p1", "and", "a\nb")]),
        (Some(0), NamedFault::BadCharacter('\n'))
    );
}

#[test]
fn refuses_a_match_across_a_tab_or_the_edge_of_a_hyperlink() {
    let body = r#"<w:p><w:r><w:t>a</w:t><w:tab/><w:t>b</w:t></w:r><w:hyperlink r:id="x"><w:r><w:t>link</w:t></w:r></w:hyperlink><w:r><w:t>end</w:t></w:r></w:p>"#;
    let file = File::new(body);
    assert_eq!(
        file.fault(&[replace("p1", "a\tb", "x")]),
        (
            Some(0),
            NamedFault::MatchCrossesElement { element: "w:tab" }
        )
    );
    assert_eq!(
        file.fault(&[replace("p1", "linkend", "x")]),
        (
            Some(0),
            NamedFault::MatchCrossesEdge {
                element: "w:hyperlink"
            }
        )
    );
    let (_, blocks) = file.edited(&[replace("p1", "link", "site")]);
    assert_eq!(texts(&blocks), ["a\tbsiteend"]);
}

#[test]
fn inserts_after_a_heading_a_paragraph_in_the_next_style() {
    let heading = r#"<w:p><w:pPr><w:pStyle w:val="Heading1"/><w:keepNext/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>Title</w:t></w:r></w:p>"#;
    let file = File::new(&format!("{heading}{}", p("Body")));
    let (xml, blocks) = file.edited(&[insert("p1", Place::After, "New\ttext", None)]);
    assert!(
        xml.contains("<w:p><w:pPr><w:keepNext/></w:pPr><w:r><w:t>New</w:t><w:tab/><w:t>text</w:t></w:r></w:p>"),
        "{xml}"
    );
    assert_eq!(texts(&blocks), ["Title", "New\ttext", "Body"]);
    assert_eq!(style_at(&blocks, "p2"), None);
}

#[test]
fn inserts_a_paragraph_that_keeps_its_style_and_formatting_or_takes_the_given_style() {
    let quote = r#"<w:p><w:pPr><w:pStyle w:val="Quote"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>Said</w:t></w:r></w:p>"#;
    let file = File::new(quote);
    let (xml, blocks) = file.edited(&[insert("p1", Place::Before, "Before", None)]);
    assert!(
        xml.contains(r#"<w:p><w:pPr><w:pStyle w:val="Quote"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>Before</w:t></w:r></w:p>"#),
        "{xml}"
    );
    assert_eq!(style_at(&blocks, "p1"), Some("Quote"));
    let (_, given) = file.edited(&[insert("p1", Place::After, "Head", Some("heading 1"))]);
    assert_eq!(style_at(&given, "p2"), Some("Heading1"));
}

#[test]
fn inserts_next_to_a_table_and_in_a_cell() {
    let table = format!(
        "<w:tbl><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>{}",
        p("cell"),
        p("after")
    );
    let file = File::new(&table);
    let edits = [
        insert("t1", Place::After, "below", None),
        insert("t1", Place::Before, "above", None),
        insert("t1/r1/c1/p1", Place::After, "second", None),
    ];
    let (_, blocks) = file.edited(&edits);
    assert_eq!(
        texts(&blocks),
        ["above", "cell", "second", "below", "after"]
    );
}

#[test]
fn puts_two_inserts_at_one_place_in_the_order_of_the_blocks() {
    let file = File::new(&format!("{}{}", p("one"), p("two")));
    let edits = [
        insert("p2", Place::Before, "before two", None),
        insert("p1", Place::After, "after one", None),
    ];
    let (_, blocks) = file.edited(&edits);
    assert_eq!(texts(&blocks), ["one", "after one", "before two", "two"]);
}

#[test]
fn deletes_a_paragraph_a_table_and_a_row() {
    let row = |text: &str| format!("<w:tr><w:tc>{}</w:tc></w:tr>", p(text));
    let body = format!(
        "{}<w:tbl>{}{}</w:tbl>{}<w:tbl>{}</w:tbl>{}",
        p("one"),
        row("a"),
        row("b"),
        p("two"),
        row("c"),
        p("end")
    );
    let file = File::new(&body);
    let (_, blocks) = file.edited(&[delete("p1"), delete("t1/r2"), delete("t2")]);
    assert_eq!(texts(&blocks), ["a", "two", "end"]);
    assert_eq!(
        file.fault(&[delete("t2/r1")]),
        (Some(0), NamedFault::LastRow)
    );
}

#[test]
fn refuses_a_delete_that_leaves_no_last_paragraph_or_breaks_a_section_or_a_range() {
    let cell = format!("<w:tbl><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>", p("only"));
    let section = "<w:p><w:pPr><w:sectPr/></w:pPr></w:p>";
    let bookmark = r#"<w:p><w:bookmarkStart w:id="1" w:name="b"/><w:r><w:t>x</w:t></w:r></w:p>"#;
    let body = format!(
        r#"{cell}{section}{bookmark}<w:p><w:bookmarkEnd w:id="1"/></w:p>{}"#,
        p("end")
    );
    let file = File::new(&body);
    assert_eq!(
        file.fault(&[delete("t1/r1/c1/p1")]),
        (Some(0), NamedFault::NeedsParagraph)
    );
    assert_eq!(
        file.fault(&[delete("p1")]),
        (Some(0), NamedFault::SectionBreak)
    );
    assert_eq!(
        file.fault(&[delete("p2")]),
        (
            Some(0),
            NamedFault::RangeEnd {
                element: "w:bookmarkStart"
            }
        )
    );
    let after_table = File::new(&format!("{cell}{}", p("end")));
    assert_eq!(
        after_table.fault(&[delete("p1")]),
        (Some(0), NamedFault::NeedsParagraph)
    );
}

/// A deleted block with many range marks names the same range as before: a range of one kind
/// and ID is whole when the block holds a start and an end of it, also with two starts, and a
/// start and an end of other kinds with one ID are two open ranges.
#[test]
fn names_the_first_open_range_of_a_deleted_block_with_marks_in_mixed_order() {
    let fault = |marks: &str| {
        let body = format!("<w:p>{marks}<w:r><w:t>x</w:t></w:r></w:p>{}", p("end"));
        File::new(&body).fault(&[delete("p1")])
    };
    let mark = |element: &str, id: u32| format!(r#"<w:{element} w:id="{id}"/>"#);
    let open = |element: &'static str| (Some(0), NamedFault::RangeEnd { element });
    let double_start = [
        mark("permEnd", 3),
        mark("bookmarkEnd", 2),
        mark("bookmarkStart", 2),
        mark("bookmarkStart", 2),
    ]
    .concat();
    assert_eq!(fault(&double_start), open("w:permEnd"));
    let other_kinds = [mark("bookmarkStart", 5), mark("commentRangeEnd", 5)].concat();
    assert_eq!(fault(&other_kinds), open("w:commentRangeEnd"));
    let nested = format!(
        "{}<w:hyperlink>{}<w:r><w:t>y</w:t></w:r>{}</w:hyperlink>{}",
        mark("commentRangeStart", 1),
        mark("permStart", 4),
        mark("permEnd", 4),
        mark("commentRangeEnd", 1),
    );
    let whole = File::new(&format!("<w:p>{nested}</w:p>{}", p("end")));
    let (_, blocks) = whole.edited(&[delete("p1")]);
    assert_eq!(texts(&blocks), ["end"]);
}

#[test]
fn checks_each_delete_against_the_earlier_deletes_of_its_list() {
    let cell = format!(
        "<w:tbl><w:tr><w:tc>{}{}</w:tc></w:tr></w:tbl>",
        p("a"),
        p("b")
    );
    let row = |text| format!("<w:tr><w:tc>{}</w:tc></w:tr>", p(text));
    let rows = format!("<w:tbl>{}{}</w:tbl>", row("c"), row("d"));
    let file = File::new(&format!("{cell}{rows}{}{}", p("e"), p("f")));
    // Both paragraphs of a cell, in either order.
    for list in [
        ["t1/r1/c1/p1", "t1/r1/c1/p2"],
        ["t1/r1/c1/p2", "t1/r1/c1/p1"],
    ] {
        let fault = file.fault(&list.map(delete));
        assert_eq!(fault, (Some(1), NamedFault::NeedsParagraph), "{list:?}");
    }
    // Both paragraphs after the last table of the body, and both rows of a table.
    let paragraphs = file.fault(&[delete("p1"), delete("p2")]);
    assert_eq!(paragraphs, (Some(1), NamedFault::NeedsParagraph));
    let rows = file.fault(&[delete("t2/r1"), delete("t2/r2")]);
    assert_eq!(rows, (Some(1), NamedFault::LastRow));
    // One delete in each place still goes through.
    let (_, blocks) = file.edited(&[delete("t1/r1/c1/p1"), delete("p1"), delete("t2/r1")]);
    assert_eq!(texts(&blocks), ["b", "d", "f"]);
}

#[test]
fn says_that_a_deleted_note_reference_leaves_its_note() {
    let noted = r#"<w:p><w:r><w:footnoteReference w:id="1"/></w:r></w:p>"#;
    let file = File::new(&format!("{noted}{}", p("end")));
    assert!(file.plan(&[delete("p1")]).unwrap().notes_kept);
    assert!(
        !file
            .plan(&[delete("p2")])
            .is_ok_and(|planned| planned.notes_kept)
    );
}

#[test]
fn sets_the_style_of_a_paragraph_with_or_without_properties_and_of_a_table() {
    let table = format!(
        "<w:tbl><w:tblPr/><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>",
        p("cell")
    );
    let styled = r#"<w:p><w:pPr><w:pStyle w:val="Quote"/></w:pPr><w:r><w:t>q</w:t></w:r></w:p>"#;
    let file = File::new(&format!("{}{styled}<w:p/>{table}{}", p("plain"), p("end")));
    let edits = [
        style("p1", "Heading1"),
        style("p2", "heading 1"),
        style("p3", "Quote"),
        style("t1", "Table Grid"),
    ];
    let (xml, blocks) = file.edited(&edits);
    assert_eq!(style_at(&blocks, "p1"), Some("Heading1"));
    assert_eq!(style_at(&blocks, "p2"), Some("Heading1"));
    assert_eq!(style_at(&blocks, "p3"), Some("Quote"));
    assert!(
        xml.contains(r#"<w:tblPr><w:tblStyle w:val="TableGrid"/></w:tblPr>"#),
        "{xml}"
    );
}

#[test]
fn names_the_styles_of_the_kind_when_a_style_is_not_there() {
    let file = File::new(&p("x"));
    let (edit, fault) = file.fault(&[style("p1", "Heading")]);
    assert_eq!(edit, Some(0));
    assert_eq!(
        fault,
        NamedFault::NoSuchStyle {
            style: "Heading".to_owned(),
            kind: "paragraph",
            near: vec!["Heading1".to_owned()],
        }
    );
    assert!(
        fault.to_string().contains("give one of Heading1"),
        "{fault}"
    );
    let (_, fault) = file.fault(&[style("p1", "Caption")]);
    assert_eq!(
        fault,
        NamedFault::NoSuchStyle {
            style: "Caption".to_owned(),
            kind: "paragraph",
            near: Vec::new(),
        }
    );
    assert!(
        fault
            .to_string()
            .contains("give one of the styles of word/styles.xml"),
        "{fault}"
    );
}

#[test]
fn refuses_a_file_with_tracked_changes_and_an_address_that_it_lacks() {
    let tracked = r#"<w:p><w:ins w:id="1" w:author="a"><w:r><w:t>x</w:t></w:r></w:ins></w:p>"#;
    let file = File::new(tracked);
    assert_eq!(
        file.fault(&[delete("p1")]),
        (Some(0), NamedFault::TrackedChanges)
    );
    let plain = File::new(&p("x"));
    assert_eq!(
        plain.fault(&[delete("p9")]),
        (Some(0), NamedFault::NoBlock(at("p9")))
    );
    assert!(matches!(
        plain.fault(&[replace("t1", "x", "y")]),
        (Some(0), NamedFault::NoBlock(_))
    ));
}

#[test]
fn the_check_after_names_the_first_block_that_differs() {
    let file = File::new(&format!("{}{}", p("one"), p("two")));
    let planned = file.plan(&[replace("p2", "two", "three")]).unwrap();
    let mismatch = planned.expected.compare(&file.blocks).unwrap_err();
    assert_eq!(mismatch.at, "p2");
    assert!(
        mismatch.to_string().contains(r#"the text "three""#),
        "{mismatch}"
    );
    let none = ExpectedBlocks::new(&file.blocks, &[]);
    assert_eq!(none.compare(&file.blocks), Ok(()));
}

#[test]
fn takes_no_text_of_an_equation_and_no_match_across_one() {
    let equation = format!(
        r#"<m:oMath xmlns:m="{}"><m:r><m:t>x</m:t></m:r></m:oMath>"#,
        ns::M
    );
    let body = format!("<w:p><w:r><w:t>ab</w:t></w:r>{equation}<w:r><w:t>cd</w:t></w:r></w:p>");
    let file = File::new(&body);
    assert_eq!(
        file.fault(&[replace("p1", "abcd", "y")]),
        (
            Some(0),
            NamedFault::MatchCrossesElement { element: "m:oMath" }
        )
    );
    assert_eq!(
        file.fault(&[replace("p1", "x", "y")]),
        (Some(0), NamedFault::TextNotFoundOutsideEquations)
    );
    let (_, blocks) = file.edited(&[replace("p1", "ab", "AB")]);
    assert!(texts(&blocks)[0].starts_with("AB"), "{:?}", texts(&blocks));
}