docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! Arithmetic expressions in placeholders and conditions.

mod common;

use docx_templating::package::InMemoryPackageSource;
use docx_templating::{Error, RenderError, Template};
use serde_json::{Value, json};

const WORD: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

fn paragraph(text: &str) -> String {
    let text = text
        .replace('&', "&")
        .replace('<', "&lt;")
        .replace('>', "&gt;");
    format!(r#"<w:p><w:r><w:t xml:space="preserve">{text}</w:t></w:r></w:p>"#)
}

fn document(body: &str) -> String {
    format!(
        r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{WORD}"><w:body>{body}</w:body></w:document>"#
    )
}

fn source(document_xml: &str) -> InMemoryPackageSource {
    let mut source = 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", document_xml.as_bytes().to_vec());
    source
}

fn template(body: &str) -> Template<InMemoryPackageSource> {
    Template::from_source(source(&document(body))).expect("template must load")
}

fn render(body: &str, context: Value) -> String {
    let rendered = template(body).render(context).expect("render must succeed");
    common::extract_document_xml(&rendered)
}

fn value_of(expression: &str) -> String {
    let xml = render(
        &paragraph(&format!("BEGIN{{{{{expression}}}}}END")),
        json!({}),
    );
    let start = xml.find("BEGIN").expect("start marker") + "BEGIN".len();
    let end = xml[start..].find("END").expect("end marker") + start;
    xml[start..end].to_owned()
}

fn condition_result(condition: &str, context: Value) -> String {
    let body = format!(
        "{}{}{}{}{}",
        paragraph(&format!("{{% if {condition} %}}")),
        paragraph("yes"),
        paragraph("{% else %}"),
        paragraph("no"),
        paragraph("{% endif %}"),
    );
    render(&body, context)
}

fn assert_true(condition: &str, context: Value) {
    let xml = condition_result(condition, context);
    assert!(xml.contains(">yes<"), "{condition}\n{xml}");
    assert!(!xml.contains(">no<"), "{condition}\n{xml}");
}

fn assert_false(condition: &str, context: Value) {
    let xml = condition_result(condition, context);
    assert!(xml.contains(">no<"), "{condition}\n{xml}");
    assert!(!xml.contains(">yes<"), "{condition}\n{xml}");
}

#[test]
fn addition_and_subtraction_work() {
    assert_eq!(value_of("2 + 3"), "5");
    assert_eq!(value_of("10 - 4"), "6");
    assert_eq!(value_of("1 - 2"), "-1");
}

#[test]
fn multiplication_binds_tighter_than_addition() {
    assert_eq!(value_of("2 + 3 * 4"), "14");
    assert_eq!(value_of("2 * 3 + 4"), "10");
}

#[test]
fn parentheses_override_precedence() {
    assert_eq!(value_of("(2 + 3) * 4"), "20");
    assert_eq!(value_of("2 * (3 + 4)"), "14");
}

#[test]
fn integer_results_stay_integers() {
    assert_eq!(value_of("2 * 3"), "6");
    assert_eq!(value_of("6 / 3"), "2");
    assert_eq!(value_of("10 / 4"), "2.5");
}

#[test]
fn remainder_keeps_the_left_over() {
    assert_eq!(value_of("10 % 3"), "1");
    assert_eq!(value_of("9 % 3"), "0");
    assert_eq!(value_of("10.5 % 3"), "1.5");
}

#[test]
fn unary_minus_negates_a_value() {
    assert_eq!(value_of("0 - 5"), "-5");
    assert_eq!(value_of("-(2 + 3)"), "-5");
    assert_eq!(value_of("-2 * 3"), "-6");

    let xml = render(&paragraph("BEGIN{{-amount}}END"), json!({ "amount": 5 }));
    assert!(xml.contains("BEGIN-5END"), "{xml}");
}

#[test]
fn paths_can_be_operands() {
    let xml = render(
        &paragraph("{{price * quantity}}"),
        json!({ "price": 12.5, "quantity": 4 }),
    );
    assert!(xml.contains(">50<"), "{xml}");
}

#[test]
fn large_integers_keep_full_precision() {
    assert_eq!(value_of("9007199254740993 + 1"), "9007199254740994");
}

#[test]
fn arithmetic_works_in_conditions() {
    assert_true(
        "price * quantity > 100",
        json!({ "price": 10, "quantity": 11 }),
    );
    assert_false(
        "price * quantity > 100",
        json!({ "price": 10, "quantity": 9 }),
    );
    assert_true(
        "subtotal - discount == 80",
        json!({ "subtotal": 100, "discount": 20 }),
    );
    assert_true(
        "(price + tax) * quantity < 50",
        json!({ "price": 10, "tax": 5, "quantity": 3 }),
    );
}

#[test]
fn a_filter_after_arithmetic_formats_the_result() {
    let xml = render(
        &paragraph("{{price * quantity | fixed: 2}}"),
        json!({ "price": 10.5, "quantity": 3 }),
    );
    assert!(xml.contains(">31.50<"), "{xml}");
}

#[test]
fn a_parenthesized_operand_can_be_filtered() {
    let xml = render(
        &paragraph("{{(price | round: 0) * quantity}}"),
        json!({ "price": 10.6, "quantity": 3 }),
    );
    assert!(xml.contains(">33<"), "{xml}");
}

#[test]
fn arithmetic_can_feed_a_loop() {
    let body = format!(
        "{}{}{}",
        paragraph("{% for value in items %}"),
        paragraph("{{value * 2}}"),
        paragraph("{% endfor %}"),
    );
    let xml = render(&body, json!({ "items": [1, 2, 3] }));
    for expected in [">2<", ">4<", ">6<"] {
        assert!(xml.contains(expected), "{expected}\n{xml}");
    }
}

#[test]
fn a_non_numeric_operand_is_a_typed_error() {
    let error = template(&paragraph("{{price * quantity}}"))
        .render(json!({ "price": 10, "quantity": "many" }))
        .expect_err("a string operand must fail");

    assert!(
        matches!(
            error,
            Error::Render(RenderError::ArithmeticType { ref operator, ref actual, .. })
                if operator == "*" && actual == "string"
        ),
        "{error:?}"
    );
}

#[test]
fn division_by_zero_is_a_typed_error() {
    for expression in ["10 / 0", "10 % 0", "10 / divisor", "10 % divisor"] {
        let placeholder = format!("{{{{{expression}}}}}");
        let error = template(&paragraph(&placeholder))
            .render(json!({ "divisor": 0 }))
            .expect_err("division by zero must fail");

        assert!(
            matches!(
                error,
                Error::Render(RenderError::DivisionByZero { ref operator, .. })
                    if operator == "/" || operator == "%"
            ),
            "{expression}: {error:?}"
        );
    }
}

#[test]
fn a_missing_operand_is_a_typed_error() {
    let error = template(&paragraph("{{price * quantity}}"))
        .render(json!({ "price": 10 }))
        .expect_err("null is not a number");

    assert!(
        matches!(
            error,
            Error::Render(RenderError::ArithmeticType { ref operator, .. }) if operator == "*"
        ),
        "{error:?}"
    );
}

#[test]
fn negation_needs_a_number() {
    let error = template(&paragraph("{{-name}}"))
        .render(json!({ "name": "Ada" }))
        .expect_err("a string cannot be negated");

    assert!(
        matches!(
            error,
            Error::Render(RenderError::ArithmeticType { ref operator, .. }) if operator == "-"
        ),
        "{error:?}"
    );
}