docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
//! Fixture-based tests for all phases (1–8).
//!
//! Each test loads one or more files from `tests/fixtures/` that were generated
//! by `cargo run --bin gen-fixtures`.  These tests exercise the full public API
//! and verify every case listed in the roadmap "Tests required" sections.

mod common;

// ── Phase 1 — Package fixtures ────────────────────────────────────────────────

/// Load valid-minimal.docx from disk and verify all required parts are present.
#[test]
fn fixture_package_valid_minimal_loads_and_lists_parts() {
    use docx_templating::package::{PackageSource, ZipPackageSource};

    let bytes = common::load_fixture("package/valid-minimal.docx");
    let src = ZipPackageSource::from_bytes(bytes).expect("should load valid-minimal.docx");

    let names = src.part_names().expect("part_names");
    assert!(
        names.iter().any(|n| n == "[Content_Types].xml"),
        "must contain [Content_Types].xml"
    );
    assert!(
        names.iter().any(|n| n == "_rels/.rels"),
        "must contain _rels/.rels"
    );
    assert!(
        names.iter().any(|n| n == "word/document.xml"),
        "must contain word/document.xml"
    );
}

/// Read word/document.xml from valid-minimal.docx and check it is non-empty.
#[test]
fn fixture_package_valid_minimal_document_xml_is_readable() {
    use docx_templating::package::{PackageSource, ZipPackageSource};

    let bytes = common::load_fixture("package/valid-minimal.docx");
    let src = ZipPackageSource::from_bytes(bytes).expect("load");
    let xml = src
        .read_part("word/document.xml")
        .expect("read_part ok")
        .expect("part present");

    assert!(!xml.is_empty(), "document.xml should have content");
    let text = String::from_utf8_lossy(&xml);
    assert!(
        text.contains("Minimal document"),
        "document.xml should contain fixture text"
    );
}

/// Validate package passes for valid-minimal.docx.
#[test]
fn fixture_package_valid_minimal_passes_validation() {
    use docx_templating::docx::validate_package;
    use docx_templating::package::{PackageSource, ZipPackageSource};

    let bytes = common::load_fixture("package/valid-minimal.docx");
    let src = ZipPackageSource::from_bytes(bytes).expect("load");
    let names = src.part_names().expect("part_names");
    assert!(validate_package(&names).is_ok(), "validation must pass");
}

/// missing-document.docx has no word/document.xml — validation must fail.
#[test]
fn fixture_package_missing_document_fails_validation() {
    use docx_templating::docx::validate_package;
    use docx_templating::package::{PackageSource, ZipPackageSource};

    let bytes = common::load_fixture("package/missing-document.docx");
    let src = ZipPackageSource::from_bytes(bytes).expect("load");
    let names = src.part_names().expect("part_names");
    let err = validate_package(&names).unwrap_err();
    assert!(
        err.to_string().contains("word/document.xml"),
        "error should mention missing part, got: {}",
        err
    );
}

/// missing-content-types.docx is missing [Content_Types].xml — validation must fail.
#[test]
fn fixture_package_missing_content_types_fails_validation() {
    use docx_templating::docx::validate_package;
    use docx_templating::package::{PackageSource, ZipPackageSource};

    let bytes = common::load_fixture("package/missing-content-types.docx");
    let src = ZipPackageSource::from_bytes(bytes).expect("load");
    let names = src.part_names().expect("part_names");
    let err = validate_package(&names).unwrap_err();
    assert!(
        err.to_string().contains("[Content_Types].xml"),
        "error should mention missing part, got: {}",
        err
    );
}

/// corrupt-zip.bin must fail to open as a ZipPackageSource.
#[test]
fn fixture_package_corrupt_zip_returns_error() {
    use docx_templating::package::ZipPackageSource;

    let bytes = common::load_fixture("package/corrupt-zip.bin");
    let result = ZipPackageSource::from_bytes(bytes);
    assert!(result.is_err(), "corrupt ZIP must return an error");
}

/// Round-trip: load valid-minimal.docx, write it back out, reload, verify parts.
#[test]
fn fixture_package_round_trip_preserves_all_parts() {
    use docx_templating::package::{
        PackageSource, PackageWriter, ZipPackageSource, ZipPackageWriter,
    };
    use std::io::Cursor;

    let bytes = common::load_fixture("package/valid-minimal.docx");
    let src = ZipPackageSource::from_bytes(bytes).expect("load original");
    let original_names = {
        let mut v = src.part_names().expect("part_names");
        v.sort();
        v
    };

    // Write all parts to a new in-memory ZIP.
    let cursor = Cursor::new(Vec::new());
    let mut writer = ZipPackageWriter::new(cursor);
    for name in &original_names {
        writer.copy_part(&src, name).expect("copy_part");
    }
    let out_cursor = writer.finish_into_inner().expect("finish");

    // Reload.
    let src2 = ZipPackageSource::from_bytes(out_cursor.into_inner()).expect("reload");
    let mut reloaded_names = src2.part_names().expect("part_names");
    reloaded_names.sort();

    assert_eq!(
        original_names, reloaded_names,
        "round-tripped ZIP must contain exactly the same parts"
    );
}

// ── Document XML fixtures ────────────────────────────────────────────────────

/// A document without template syntax must round trip byte identically, so the
/// model preserves runs, whitespace and entity spelling.
fn assert_document_round_trips(path: &str) {
    let xml = common::load_xml_fixture(path);
    let template = common::template_from_document_xml(&xml).expect("load document");
    let rendered = template
        .render(serde_json::json!({}))
        .expect("render document");
    assert_eq!(
        common::extract_document_xml(&rendered),
        String::from_utf8(xml).expect("fixture is UTF-8"),
        "{path} must round trip byte identically"
    );
}

/// simple-text.xml: two adjacent runs survive untouched.
#[test]
fn fixture_xml_simple_text_round_trips() {
    assert_document_round_trips("xml/simple-text.xml");
}

/// split-placeholder.xml: a placeholder split across two runs is stitched and
/// replaced.
#[test]
fn fixture_xml_split_placeholder_renders_across_runs() {
    let xml = common::load_xml_fixture("xml/split-placeholder.xml");
    let template = common::template_from_document_xml(&xml).expect("load document");
    let rendered = template
        .render(serde_json::json!({"name": "Ada"}))
        .expect("render document");
    let output = common::extract_document_xml(&rendered);

    assert!(
        output.contains(">Ada<"),
        "split placeholder must be stitched and replaced: {output}"
    );
    assert!(!output.contains("{{"), "no placeholders may remain");
}

/// whitespace.xml: leading and trailing spaces survive untouched.
#[test]
fn fixture_xml_whitespace_round_trips() {
    assert_document_round_trips("xml/whitespace.xml");
}

/// entities.xml: entity spelling survives untouched.
#[test]
fn fixture_xml_entities_round_trip() {
    assert_document_round_trips("xml/entities.xml");
}

/// nested-table.xml: cell text survives untouched.
#[test]
fn fixture_xml_nested_table_round_trips() {
    assert_document_round_trips("xml/nested-table.xml");
}

// ── Phase 5 — Inline variable fixtures ───────────────────────────────────────

/// simple.docx + simple.json: basic {{name}} replacement end-to-end.
#[test]
fn fixture_inline_simple_variable_replacement() {
    let bytes = common::load_fixture("inline/simple.docx");
    let ctx = common::load_fixture_json("inline/simple.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load template");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        xml.contains("Hello Ada!"),
        "expected 'Hello Ada!', got: {}",
        xml
    );
    assert!(!xml.contains("{{"), "no unresolved placeholders");
}

/// split-run.docx: placeholder split across two runs is correctly resolved.
#[test]
fn fixture_inline_split_run_placeholder() {
    let bytes = common::load_fixture("inline/split-run.docx");
    let ctx = common::load_fixture_json("inline/split-run.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load template");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        xml.contains("INV-1001"),
        "split-run invoice number must resolve, got: {}",
        xml
    );
    assert!(!xml.contains("{{"), "no unresolved placeholders");
}

/// special-characters.docx: & in values must be XML-escaped in output.
#[test]
fn fixture_inline_special_characters_are_escaped() {
    let bytes = common::load_fixture("inline/special-characters.docx");
    let ctx = common::load_fixture_json("inline/special-characters.json");
    // Context: {"company": "Ada & Co", "tag": "R&D"}

    let template = docx_templating::Template::from_bytes(bytes).expect("load template");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    // The library escapes '&' in user values as '&amp;' inside the XML text node.
    // The raw string "&amp;" must appear in the XML output for both values.
    assert!(
        xml.contains("&amp;"),
        "ampersand must be XML-escaped as &amp; in output, got: {}",
        xml
    );
    // Both variable values must appear somewhere in the output.
    assert!(
        xml.contains("Ada") && xml.contains("Co"),
        "company name parts must appear in output, got: {}",
        xml
    );
    assert!(
        xml.contains("R") && xml.contains("D"),
        "tag value parts must appear in output, got: {}",
        xml
    );
    // No raw unescaped & as a lone character followed by a letter (which would be invalid XML).
    // We verify by checking the rendered document parses as a valid ZIP (already done by extract_document_xml).
    assert!(!xml.contains("{{"), "no unresolved placeholders");
}

/// missing-value.docx + MissingValuePolicy::Empty → placeholder replaced with "".
#[test]
fn fixture_inline_missing_value_policy_empty() {
    use docx_templating::{MissingValuePolicy, TemplateOptions};

    let bytes = common::load_fixture("inline/missing-value.docx");
    let ctx = common::load_fixture_json("inline/missing-value.json"); // {}

    let opts = TemplateOptions::default().missing_value_policy(MissingValuePolicy::Empty);
    let template = docx_templating::Template::from_bytes(bytes)
        .expect("load")
        .with_options(opts);
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        !xml.contains("{{"),
        "no unresolved placeholders with Empty policy"
    );
    assert!(
        !xml.contains("missing_key"),
        "key name must not appear in output"
    );
}

/// missing-value.docx + MissingValuePolicy::KeepPlaceholder → original tag preserved.
#[test]
fn fixture_inline_missing_value_policy_keep_placeholder() {
    use docx_templating::{MissingValuePolicy, TemplateOptions};

    let bytes = common::load_fixture("inline/missing-value.docx");
    let ctx = common::load_fixture_json("inline/missing-value.json"); // {}

    let opts = TemplateOptions::default().missing_value_policy(MissingValuePolicy::KeepPlaceholder);
    let template = docx_templating::Template::from_bytes(bytes)
        .expect("load")
        .with_options(opts);
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        xml.contains("missing_key"),
        "KeepPlaceholder must preserve the placeholder text"
    );
}

/// missing-value.docx + MissingValuePolicy::Error (default) → render returns Err.
#[test]
fn fixture_inline_missing_value_policy_error() {
    let bytes = common::load_fixture("inline/missing-value.docx");
    let ctx = common::load_fixture_json("inline/missing-value.json"); // {}

    // Default policy is Error.
    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let result = template.render(ctx);

    assert!(
        result.is_err(),
        "default Error policy must return Err for missing key"
    );
}

/// nested-path.docx: multi-level path {{user.name}} and {{user.address.city}}.
#[test]
fn fixture_inline_nested_path_resolution() {
    let bytes = common::load_fixture("inline/nested-path.docx");
    let ctx = common::load_fixture_json("inline/nested-path.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(xml.contains("Ada"), "user.name must resolve");
    assert!(xml.contains("London"), "user.address.city must resolve");
    assert!(!xml.contains("{{"), "no unresolved placeholders");
}

// ── Phase 6 — Conditional fixtures ───────────────────────────────────────────

/// simple-if.docx with truthy condition → content visible, tags removed.
#[test]
fn fixture_conditional_simple_if_truthy() {
    let bytes = common::load_fixture("conditional/simple-if.docx");
    let ctx = common::load_fixture_json("conditional/simple-if-true.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        xml.contains("Premium content"),
        "truthy branch must be visible"
    );
    assert!(!xml.contains("{%"), "no template tags in output");
}

/// simple-if.docx with falsy condition → content removed, tags removed.
#[test]
fn fixture_conditional_simple_if_falsy() {
    let bytes = common::load_fixture("conditional/simple-if.docx");
    let ctx = common::load_fixture_json("conditional/simple-if-false.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        !xml.contains("Premium content"),
        "content must be removed when falsy"
    );
    assert!(!xml.contains("{%"), "no template tags in output");
}

/// if-else.docx with truthy → then-branch visible, else-branch removed.
#[test]
fn fixture_conditional_if_else_truthy_shows_then_branch() {
    let bytes = common::load_fixture("conditional/if-else.docx");
    let ctx = common::load_fixture_json("conditional/if-else-vip.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(xml.contains("VIP"), "then-branch must be visible");
    assert!(!xml.contains("Standard"), "else-branch must be removed");
    assert!(!xml.contains("{%"), "no template tags");
}

/// if-else.docx with falsy → else-branch visible, then-branch removed.
#[test]
fn fixture_conditional_if_else_falsy_shows_else_branch() {
    let bytes = common::load_fixture("conditional/if-else.docx");
    let ctx = common::load_fixture_json("conditional/if-else-standard.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(xml.contains("Standard"), "else-branch must be visible");
    assert!(!xml.contains("VIP"), "then-branch must be removed");
    assert!(!xml.contains("{%"), "no template tags");
}

/// nested-if.docx: outer true + inner true → both bodies visible.
#[test]
fn fixture_conditional_nested_if_both_true() {
    let bytes = common::load_fixture("conditional/nested-if.docx");
    let ctx = common::load_fixture_json("conditional/nested-if-both-true.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        xml.contains("Premium active user"),
        "inner body must be visible"
    );
    assert!(
        xml.contains("Active user footer"),
        "outer body text must be visible"
    );
    assert!(!xml.contains("{%"), "no template tags");
}

/// nested-if.docx: outer true + inner false → inner body gone, outer text stays.
#[test]
fn fixture_conditional_nested_if_outer_true_inner_false() {
    let bytes = common::load_fixture("conditional/nested-if.docx");
    let ctx = common::load_fixture_json("conditional/nested-if-outer-true-inner-false.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        !xml.contains("Premium active user"),
        "inner body must be removed"
    );
    assert!(
        xml.contains("Active user footer"),
        "outer body text must survive"
    );
    assert!(!xml.contains("{%"), "no template tags");
}

/// nested-if.docx: outer false → everything inside removed.
#[test]
fn fixture_conditional_nested_if_outer_false() {
    let bytes = common::load_fixture("conditional/nested-if.docx");
    let ctx = common::load_fixture_json("conditional/nested-if-outer-false.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        !xml.contains("Premium active user"),
        "inner body must be removed"
    );
    assert!(
        !xml.contains("Active user footer"),
        "outer body must be removed"
    );
    assert!(!xml.contains("{%"), "no template tags");
}

// ── Phase 7 — Paragraph loop fixtures ────────────────────────────────────────

/// simple-paragraph.docx: object array produces one paragraph per item.
#[test]
fn fixture_loop_simple_paragraph_object_array() {
    let bytes = common::load_fixture("loop/simple-paragraph.docx");
    let ctx = common::load_fixture_json("loop/simple-paragraph.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(xml.contains("Alpha"), "first item must appear");
    assert!(xml.contains("Beta"), "second item must appear");
    assert!(xml.contains("Gamma"), "third item must appear");
    assert!(!xml.contains("{%"), "no loop tags");
    assert!(!xml.contains("{{"), "no unresolved placeholders");

    // Order preserved.
    assert!(xml.find("Alpha").unwrap() < xml.find("Beta").unwrap());
    assert!(xml.find("Beta").unwrap() < xml.find("Gamma").unwrap());
}

/// simple-paragraph.docx: paragraph run properties (bold) survive loop duplication.
#[test]
fn fixture_loop_paragraph_formatting_preserved() {
    let bytes = common::load_fixture("loop/simple-paragraph.docx");
    let ctx = common::load_fixture_json("loop/simple-paragraph.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    // The fixture body paragraph has <w:rPr><w:b/></w:rPr> — verify bold property
    // appears in the output (once per duplicated paragraph).
    assert!(
        xml.contains("<w:b/>") || xml.contains("<w:b />") || xml.contains("w:b"),
        "bold run property must survive loop duplication"
    );
}

/// empty-array.docx: empty array removes all loop paragraphs; surrounding text survives.
#[test]
fn fixture_loop_empty_array_removes_loop_paragraphs() {
    let bytes = common::load_fixture("loop/empty-array.docx");
    let ctx = common::load_fixture_json("loop/empty-array.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(xml.contains("Before"), "text before loop must survive");
    assert!(xml.contains("After"), "text after loop must survive");
    assert!(!xml.contains("{%"), "no loop tags");
    assert!(!xml.contains("{{"), "no placeholders");
    assert!(
        !xml.contains("item.name"),
        "loop body template must be gone"
    );
}

/// primitive-array.docx: {{.}} resolves to each primitive value.
#[test]
fn fixture_loop_primitive_array_current_item() {
    let bytes = common::load_fixture("loop/primitive-array.docx");
    let ctx = common::load_fixture_json("loop/primitive-array.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(xml.contains("rust"), "first tag must appear");
    assert!(xml.contains("docx"), "second tag must appear");
    assert!(xml.contains("templating"), "third tag must appear");
    assert!(!xml.contains("{%"), "no loop tags");
    assert!(!xml.contains("{{"), "no placeholders");
}

/// object-array.docx: multiple fields per item all resolve correctly.
#[test]
fn fixture_loop_object_array_multiple_fields() {
    let bytes = common::load_fixture("loop/object-array.docx");
    let ctx = common::load_fixture_json("loop/object-array.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(xml.contains("Widget"), "first product name must appear");
    assert!(xml.contains("9.99"), "first product price must appear");
    assert!(xml.contains("Gadget"), "second product name must appear");
    assert!(xml.contains("14.99"), "second product price must appear");
    assert!(!xml.contains("{%"), "no loop tags");
    assert!(!xml.contains("{{"), "no placeholders");
}

/// non-iterable.docx: context has a string where array is expected → Err.
#[test]
fn fixture_loop_non_iterable_returns_error() {
    let bytes = common::load_fixture("loop/non-iterable.docx");
    let ctx = common::load_fixture_json("loop/non-iterable.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let result = template.render(ctx);

    assert!(result.is_err(), "non-array iterable must produce an error");
}

// ── Phase 8 — Table loop fixtures ────────────────────────────────────────────

/// simple-row-loop.docx: multi-column row loop with header row preserved.
#[test]
fn fixture_table_simple_row_loop_produces_correct_rows() {
    let bytes = common::load_fixture("table/simple-row-loop.docx");
    let ctx = common::load_fixture_json("table/simple-row-loop.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    // Header row must survive.
    assert!(xml.contains("Item"), "header row 'Item' must survive");
    assert!(xml.contains("Qty"), "header row 'Qty' must survive");

    // Both data rows present.
    assert!(xml.contains("Keyboard"), "first item name must appear");
    assert!(xml.contains("Mouse"), "second item name must appear");

    // Quantities.
    assert!(xml.contains('1'.to_string().as_str()), "qty 1 must appear");
    assert!(xml.contains('2'.to_string().as_str()), "qty 2 must appear");

    assert!(!xml.contains("{%"), "no loop tags");
    assert!(!xml.contains("{{"), "no unresolved placeholders");

    // Order preserved.
    assert!(xml.find("Keyboard").unwrap() < xml.find("Mouse").unwrap());
}

/// simple-row-loop.docx: table wrapper element (<w:tbl>) must survive.
#[test]
fn fixture_table_simple_row_loop_table_structure_preserved() {
    let bytes = common::load_fixture("table/simple-row-loop.docx");
    let ctx = common::load_fixture_json("table/simple-row-loop.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        xml.contains("w:tbl"),
        "table element must be present in output"
    );
    // Table properties must survive: the fixture has <w:tblStyle w:val="TableGrid"/>.
    assert!(
        xml.contains("TableGrid") || xml.contains("tblPr"),
        "table properties must survive rendering"
    );
}

/// simple-row-loop.docx: each body row has the same number of cells as the template row.
#[test]
fn fixture_table_row_loop_cell_count_preserved() {
    let bytes = common::load_fixture("table/simple-row-loop.docx");
    let ctx = common::load_fixture_json("table/simple-row-loop.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    // Count <w:tc> openings: header has 2 cells, each of 2 data rows has 2 cells → 6 total.
    // (Template tag rows are removed so only header + 2 data rows remain.)
    let tc_count = xml.matches("w:tc").count();
    assert!(
        tc_count >= 4,
        "each data row must have 2 cells (≥4 w:tc total, got {})",
        tc_count
    );
}

/// empty-loop.docx: empty array removes template rows; header row and table survive.
#[test]
fn fixture_table_empty_loop_removes_template_rows_keeps_header() {
    let bytes = common::load_fixture("table/empty-loop.docx");
    let ctx = common::load_fixture_json("table/empty-loop.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(xml.contains("Header"), "header row must survive empty loop");
    assert!(!xml.contains("{%"), "no loop tags");
    assert!(!xml.contains("{{"), "no placeholders");
    assert!(xml.contains("w:tbl"), "table structure must survive");
}

/// nested-cell-loop.docx: paragraph loop inside a table cell (nested loop).
#[test]
fn fixture_table_nested_cell_loop_renders_inner_items() {
    let bytes = common::load_fixture("table/nested-cell-loop.docx");
    let ctx = common::load_fixture_json("table/nested-cell-loop.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    // Order IDs.
    assert!(xml.contains("O1"), "order O1 must appear");
    assert!(xml.contains("O2"), "order O2 must appear");

    // Items from each order.
    assert!(xml.contains("Pen"), "Pen from O1 must appear");
    assert!(xml.contains("Pad"), "Pad from O1 must appear");
    assert!(xml.contains("Ruler"), "Ruler from O2 must appear");

    assert!(!xml.contains("{%"), "no loop tags");
    assert!(!xml.contains("{{"), "no unresolved placeholders");

    // O1 before O2.
    assert!(xml.find("O1").unwrap() < xml.find("O2").unwrap());
}

// ── Phase 8 — conditional-row: RowRemoval path via {% if %} ──────────────────
//
// This is the key edge case confirmed in the architecture session:
// a `{% if %}` block whose opening and closing tag each occupy their own `<w:tr>`
// must trigger the RowRemoval path in `emit_removal`, not ParagraphRemoval.

/// conditional-row.docx (show=true): always-visible row + conditional row both present.
#[test]
fn fixture_table_conditional_row_truthy_both_rows_visible() {
    let bytes = common::load_fixture("table/conditional-row.docx");
    let ctx = common::load_fixture_json("table/conditional-row-show.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        xml.contains("Always visible row"),
        "static row must always be present"
    );
    assert!(
        xml.contains("Conditional row content"),
        "conditional row must be visible when show_row=true"
    );
    assert!(!xml.contains("{%"), "no template tags in output");
    assert!(xml.contains("w:tbl"), "table structure must survive");
}

/// conditional-row.docx (show=false): only the always-visible row remains.
/// The RowRemoval path removes the tag rows AND the conditional body row.
#[test]
fn fixture_table_conditional_row_falsy_body_row_removed() {
    let bytes = common::load_fixture("table/conditional-row.docx");
    let ctx = common::load_fixture_json("table/conditional-row-hide.json");

    let template = docx_templating::Template::from_bytes(bytes).expect("load");
    let rendered = template.render(ctx).expect("render");
    let xml = common::extract_document_xml(&rendered);

    assert!(
        xml.contains("Always visible row"),
        "static row must survive even when condition is false"
    );
    assert!(
        !xml.contains("Conditional row content"),
        "conditional row content must be removed when show_row=false"
    );
    assert!(
        !xml.contains("{%"),
        "no template tags — tag rows must be removed"
    );
    // Table itself must survive — only inner rows are gone.
    assert!(xml.contains("w:tbl"), "table element must survive");
}

/// conditional-row.docx: the table structure is valid regardless of condition value.
/// Verify <w:tbl> is present in both truthy and falsy renders.
#[test]
fn fixture_table_conditional_row_table_structure_always_valid() {
    let bytes = common::load_fixture("table/conditional-row.docx");

    // Truthy.
    let template = docx_templating::Template::from_bytes(bytes.clone()).expect("load truthy");
    let rendered = template
        .render(common::load_fixture_json("table/conditional-row-show.json"))
        .expect("render truthy");
    assert!(
        common::extract_document_xml(&rendered).contains("w:tbl"),
        "table must be present in truthy render"
    );

    // Falsy.
    let template = docx_templating::Template::from_bytes(bytes).expect("load falsy");
    let rendered = template
        .render(common::load_fixture_json("table/conditional-row-hide.json"))
        .expect("render falsy");
    assert!(
        common::extract_document_xml(&rendered).contains("w:tbl"),
        "table must be present in falsy render"
    );
}

// ── Phase 8 — invalid placement (in-memory, no fixture file needed) ───────────
//
// A for-block whose opening tag is inside one <w:tbl> and closing tag outside
// it cannot be handled — the renderer must return an error rather than produce
// invalid XML.  This is tested with a hand-crafted in-memory document.

/// A for-block that straddles a table boundary must return an error, not panic.
#[test]
fn table_invalid_placement_across_table_boundary_returns_error() {
    use serde_json::json;

    // Opening tag is inside a table cell; body paragraph is outside the table.
    // This is structurally invalid for row-level expansion.
    // The evaluator should either produce UnsupportedBlockPlacement or a non-panicking error.
    let doc_xml =
        br#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:body>
    <w:tbl>
      <w:tr><w:tc><w:p><w:r><w:t>{% for item in items %}</w:t></w:r></w:p></w:tc></w:tr>
    </w:tbl>
    <w:p><w:r><w:t>{{item.name}}{% endfor %}</w:t></w:r></w:p>
  </w:body>
</w:document>"#;

    let mut source = docx_templating::package::InMemoryPackageSource::new();
    source.add_part(
        "[Content_Types].xml",
        br#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"></Types>"#.to_vec(),
    );
    source.add_part(
        "_rels/.rels",
        br#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>"#.to_vec(),
    );
    source.add_part("word/document.xml", doc_xml.to_vec());

    // The template may fail at load time (parse error for mismatched endfor)
    // or at render time — either outcome is acceptable as long as we don't panic.
    let result = docx_templating::Template::from_source(source)
        .and_then(|t| t.render(json!({"items": [{"name": "X"}]})));

    // We only assert it does not panic; the error path is acceptable.
    // If it somehow succeeds, at minimum no template syntax must remain.
    if let Ok(rendered) = result {
        let xml = common::extract_document_xml(&rendered);
        assert!(
            !xml.contains("{%"),
            "if render succeeds, no template tags must remain"
        );
    }
    // If result is Err, that is also correct — the test passes either way.
}