f-office-xml 0.1.0

Minimal read-only XML tree for Office Open XML and SVG parts.
Documentation
//! Tests of the spans of nodes and of the parse of fragments.

use super::{Document, Error, Limits, NodeId, NodeKind};

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

fn parse(bytes: &[u8]) -> Document {
    Document::parse(bytes, &Limits::default()).unwrap()
}

/// The bytes of a node's span.
fn spanned<'b>(doc: &Document, bytes: &'b [u8], id: NodeId) -> &'b str {
    std::str::from_utf8(&bytes[doc.span(id).unwrap()]).unwrap()
}

#[test]
fn spans_keep_the_markup_of_each_node_as_written() {
    let xml = format!(
        "<?xml version=\"1.0\"?>\r\n<w:document xmlns:w=\"{W}\"><w:p>a\r\nb &amp; c&#x41;<![CDATA[<d>]]></w:p><!--note--><w:e w:val = 'x'/></w:document>"
    );
    let bytes = xml.as_bytes();
    let doc = parse(bytes);
    let root = doc.root().unwrap();
    let declaration = doc.top[0];
    assert_eq!(spanned(&doc, bytes, declaration), "<?xml version=\"1.0\"?>");
    assert_eq!(spanned(&doc, bytes, root), &xml[23..]);
    let [p, comment, e] = doc.children(root) else {
        panic!("{:?}", doc.children(root));
    };
    assert_eq!(
        spanned(&doc, bytes, *p),
        "<w:p>a\r\nb &amp; c&#x41;<![CDATA[<d>]]></w:p>"
    );
    // The text joins its references and its CDATA section, and its span keeps them as written.
    let text = doc.children(*p)[0];
    assert_eq!(doc.text(text), Some("a\nb & cA<d>"));
    assert_eq!(
        spanned(&doc, bytes, text),
        "a\r\nb &amp; c&#x41;<![CDATA[<d>]]>"
    );
    assert_eq!(spanned(&doc, bytes, *comment), "<!--note-->");
    assert_eq!(spanned(&doc, bytes, *e), "<w:e w:val = 'x'/>");
}

#[test]
fn spans_count_the_bytes_of_a_byte_order_mark() {
    let bytes = b"\xEF\xBB\xBF<a><b/></a>";
    let doc = parse(bytes);
    let root = doc.root().unwrap();
    assert_eq!(doc.span(root).unwrap(), 3..bytes.len());
    assert_eq!(spanned(&doc, bytes, doc.children(root)[0]), "<b/>");
}

#[test]
fn gives_no_span_of_a_part_that_is_not_in_utf_8() {
    let declared = parse(b"<?xml version=\"1.0\" encoding=\"windows-1252\"?><a/>");
    let root = declared.root().unwrap();
    assert_eq!(
        declared.span(root),
        Err(Error::NotUtf8("windows-1252".to_owned()))
    );
    // A declaration of UTF-8 in any case keeps the spans.
    let utf8 = parse(b"<?xml version=\"1.0\" encoding=\"Utf-8\"?><a/>");
    assert_eq!(utf8.span(utf8.root().unwrap()), Ok(38..42));
    // A byte order mark of UTF-16 names the encoding even when the bytes parse.
    let utf16: Vec<u8> = [0xFF, 0xFE]
        .into_iter()
        .chain("<a/>".encode_utf16().flat_map(u16::to_le_bytes))
        .collect();
    if let Ok(doc) = Document::parse(&utf16, &Limits::default()) {
        let first = doc.top[0];
        assert_eq!(doc.span(first), Err(Error::NotUtf8("UTF-16".to_owned())));
    }
    // A node of another, larger document is not there.
    let large = parse(b"<a><b/><c/></a>");
    let last = *large.children(large.root().unwrap()).last().unwrap();
    assert_eq!(utf8.span(last), Err(Error::NoSuchNode));
}

#[test]
fn lists_the_nearest_declaration_of_each_prefix_in_scope() {
    let xml = format!(
        r#"<w:document xmlns:w="{W}" xmlns:a="urn:outer" xmlns="urn:default"><w:p xmlns:a="urn:inner"><w:r/></w:p></w:document>"#
    );
    let doc = parse(xml.as_bytes());
    let root = doc.root().unwrap();
    let p = doc.children(root)[0];
    let r = doc.children(p)[0];
    let pairs = |pairs: &[(&str, &str)]| -> Vec<(String, String)> {
        pairs
            .iter()
            .map(|(prefix, uri)| ((*prefix).to_owned(), (*uri).to_owned()))
            .collect()
    };
    let inner = pairs(&[("a", "urn:inner"), ("w", W), ("", "urn:default")]);
    assert_eq!(doc.namespaces_in_scope(p), inner);
    assert_eq!(doc.namespaces_in_scope(r), inner);
    assert_eq!(
        doc.namespaces_in_scope(doc.children(r).first().copied().unwrap_or(r)),
        inner
    );
    assert_eq!(
        doc.namespaces_in_scope(root),
        pairs(&[("w", W), ("a", "urn:outer"), ("", "urn:default")])
    );
}

#[test]
fn parses_the_bytes_of_a_span_with_the_declarations_in_scope() {
    let xml =
        format!(r#"<w:document xmlns:w="{W}"><w:p><w:r w:rsid="1">x</w:r></w:p></w:document>"#);
    let bytes = xml.as_bytes();
    let doc = parse(bytes);
    let root = doc.root().unwrap();
    let p = doc.children(root)[0];
    let in_scope = doc.namespaces_in_scope(root);
    let fragment =
        Document::parse_fragment(&bytes[doc.span(p).unwrap()], &in_scope, &Limits::default())
            .unwrap();
    let [node] = fragment.nodes() else {
        panic!("{:?}", fragment.nodes());
    };
    let parsed = fragment.document();
    assert!(parsed.is(*node, W, "p"));
    let r = parsed.children(*node)[0];
    assert_eq!(parsed.attribute(r, Some(W), "rsid"), Some("1"));
    // The spans of the fragment count from its own first byte.
    assert_eq!(parsed.span(*node), Ok(0..doc.span(p).unwrap().len()));
    assert_eq!(
        std::str::from_utf8(&bytes[doc.span(p).unwrap()][parsed.span(r).unwrap()]),
        Ok(r#"<w:r w:rsid="1">x</w:r>"#)
    );
    // Without the declaration, the prefix is not declared.
    assert_eq!(
        Document::parse_fragment(b"<w:p/>", &[], &Limits::default()).map(|_| ()),
        Err(Error::UndeclaredPrefix("w".to_owned()))
    );
}

/// Whether the parse of a fragment of `bytes` with the declarations `in_scope` fails with a
/// syntax error.
fn syntax_error(bytes: &[u8], in_scope: &[(&str, &str)]) -> bool {
    let in_scope: Vec<(String, String)> = in_scope
        .iter()
        .map(|(prefix, uri)| ((*prefix).to_owned(), (*uri).to_owned()))
        .collect();
    let parsed = Document::parse_fragment(bytes, &in_scope, &Limits::default());
    matches!(parsed, Err(Error::Syntax(_)))
}

#[test]
fn refuses_a_fragment_that_leaves_its_place() {
    assert!(syntax_error(b"</fragment><fragment>", &[]));
    assert!(syntax_error(b"<a>", &[]));
    assert!(syntax_error(b"<x/>", &[("a b", "urn:x")]));
    assert!(syntax_error(b"<q:x/>", &[("q", "urn:\"'")]));
}

#[test]
fn binds_each_uri_as_written() {
    // The URI goes in a quotation mark that it does not hold.
    let quoted = [("q".to_owned(), "urn:\"a&amp;b".to_owned())];
    let fragment = Document::parse_fragment(b"<q:x/>text", &quoted, &Limits::default()).unwrap();
    let parsed = fragment.document();
    assert!(parsed.is(fragment.nodes()[0], "urn:\"a&amp;b", "x"));
    assert!(matches!(
        parsed.kind(fragment.nodes()[1]),
        Some(NodeKind::Text(text)) if text == "text"
    ));
}