use proptest::prelude::*;
use super::*;
use crate::parse::Fields;
type Rows = Vec<(String, String)>;
fn rows(out: &Fields<'_>) -> Rows {
out.as_slice()
.iter()
.map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
.collect()
}
fn parsed(xml: &Xml, doc: &str) -> Rows {
let mut out = Fields::new();
let result = xml.parse(doc.as_bytes(), &mut out);
assert_eq!(
result.as_ref().ok(),
Some(&Parsed::Done),
"{doc}: {result:?}"
);
rows(&out)
}
fn want(pairs: &[(&str, &str)]) -> Rows {
pairs
.iter()
.map(|(n, v)| ((*n).to_owned(), (*v).to_owned()))
.collect()
}
const EVENT: &str = concat!(
r#"<Event xmlns="http://schemas.example.com/event"><System>"#,
r#"<EventID Qualifiers="0">4624</EventID><Computer>dc01</Computer></System>"#,
r#"<EventData><Data Name="TargetUserName">alice</Data><Data Name="LogonType" x="1">3</Data>"#,
r#"<Data>bare</Data><Data Name=" ">blank</Data></EventData></Event>"#,
);
#[test]
fn a_document_writes_the_fields_its_table_says() {
let cases: &[(&str, &[(&str, &str)])] = &[
("<a/>", &[("a", "")]),
("<a></a>", &[("a", "")]),
("<a><!--c--></a>", &[("a", "")]),
(r#"<a x="1"></a>"#, &[("a.@x", "1"), ("a", "")]),
("<a>t</a>", &[("a", "t")]),
("<a> t </a>", &[("a", " t ")]),
("<a><b/></a>", &[("a.b", "")]),
("<a> <b/> </a>", &[("a.b", "")]),
("<a> x <b/> y </a>", &[("a.b", ""), ("a", " x y ")]),
("<a><![CDATA[ ]]></a>", &[("a", " ")]),
("<a><![CDATA[ ]]><b/></a>", &[("a.b", ""), ("a", " ")]),
("<a>1 < 2 AB</a>", &[("a", "1 < 2 AB")]),
("<a>x<![CDATA[<y>]]>z</a>", &[("a", "x<y>z")]),
(
r#"<a x="1 & 2" y='q"'><b>1</b><b>2</b><c><d>3</d></c></a>"#,
&[
("a.@x", "1 & 2"),
("a.@y", "q\""),
("a.b", "1"),
("a.b", "2"),
("a.c.d", "3"),
],
),
(
r#"<n:a xmlns:n="urn:x" n:k="v" xmlns="urn:y"><n:b>1</n:b></n:a>"#,
&[("a.@k", "v"), ("a.b", "1")],
),
(
"\u{feff}<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- c -->\n<a>1</a>\n<?pi x?>\n",
&[("a", "1")],
),
(
r#"<a.b x.y="1" z="2"><c.d>3</c.d><e/></a.b>"#,
&[
(r#"["a.b"]["@x.y"]"#, "1"),
(r#"["a.b"].@z"#, "2"),
(r#"["a.b"]["c.d"]"#, "3"),
(r#"["a.b"].e"#, ""),
],
),
(
"<caf\u{e9} na\u{ef}ve=\"\u{fc}\">\u{e9}</caf\u{e9}>",
&[("caf\u{e9}.@na\u{ef}ve", "\u{fc}"), ("caf\u{e9}", "\u{e9}")],
),
(
EVENT,
&[
("Event.System.EventID.@Qualifiers", "0"),
("Event.System.EventID", "4624"),
("Event.System.Computer", "dc01"),
("Event.EventData.Data.@Name", "TargetUserName"),
("Event.EventData.Data", "alice"),
("Event.EventData.Data.@Name", "LogonType"),
("Event.EventData.Data.@x", "1"),
("Event.EventData.Data", "3"),
("Event.EventData.Data", "bare"),
("Event.EventData.Data.@Name", " "),
("Event.EventData.Data", "blank"),
],
),
];
let xml = Xml::new();
for (doc, fields) in cases {
assert_eq!(parsed(&xml, doc), want(fields), "{doc}");
}
}
#[test]
fn a_keyed_element_is_named_by_its_attribute() {
let config = XmlParserConfig {
keyed: vec![Keyed {
path: "Event.EventData.Data".to_owned(),
attribute: "Name".to_owned(),
}],
};
let xml = Xml::with_config("xml:events", &config).unwrap();
assert_eq!(xml.name(), "xml:events");
assert_eq!(
parsed(&xml, EVENT)[3..],
want(&[
("Event.EventData.TargetUserName", "alice"),
("Event.EventData.LogonType.@x", "1"),
("Event.EventData.LogonType", "3"),
("Event.EventData.Data", "bare"),
("Event.EventData.Data.@Name", " "),
("Event.EventData.Data", "blank"),
])
);
let nested = r#"<Event><EventData><Data Name="a&b"><v>1</v></Data></EventData></Event>"#;
assert_eq!(
parsed(&xml, nested),
want(&[("Event.EventData.a&b.v", "1")])
);
let dotted = r#"<Event><EventData><Data Name="a.b"><v>1</v></Data></EventData></Event>"#;
assert_eq!(
parsed(&xml, dotted),
want(&[(r#"Event.EventData["a.b"].v"#, "1")])
);
for path in [r#"r["a.b"]"#, r#"["r"]["a.b"]"#] {
let config = XmlParserConfig {
keyed: vec![Keyed {
path: path.to_owned(),
attribute: "k".to_owned(),
}],
};
let xml = Xml::with_config("xml", &config).unwrap();
assert_eq!(
parsed(&xml, r#"<r><a.b k="x">1</a.b><a><b k="y"/></a></r>"#),
want(&[("r.x", "1"), ("r.a.b.@k", "y"), ("r.a.b", "")]),
"{path}"
);
}
let config = XmlParserConfig {
keyed: vec![
Keyed {
path: "r.a".to_owned(),
attribute: "k".to_owned(),
},
Keyed {
path: "r.a.a".to_owned(),
attribute: "p".to_owned(),
},
],
};
let xml = Xml::with_config("xml", &config).unwrap();
let doc = concat!(
r#"<r><a k="one" n:k="two" xmlns:n="urn:n"><a xmlns:p="urn:p" p="in"/></a>"#,
r#"<b><a k="no"/></b><a k="three"/></r>"#,
);
assert_eq!(
parsed(&xml, doc),
want(&[
("r.one.@k", "two"),
("r.one.in", ""),
("r.b.a.@k", "no"),
("r.b.a", ""),
("r.three", ""),
])
);
let rule = |path: &str, attribute: &str| Keyed {
path: path.to_owned(),
attribute: attribute.to_owned(),
};
let build = |name: &str, keyed: Vec<Keyed>| Xml::with_config(name, &XmlParserConfig { keyed });
for (name, keyed, error) in [
("xml", vec![rule("a..b", "k")], "is empty"),
("xml", vec![rule(r#"a[""]"#, "k")], "is empty"),
(
"xml",
vec![rule(r#"a["b"]"#, "k"), rule("a.b", "j")],
"two keyed rules",
),
("xml", vec![rule("", "k")], "is empty"),
("xml", vec![rule("a", "")], "is empty"),
(
"xml",
vec![rule("a", "k"), rule("a", "j")],
"two keyed rules",
),
("json:x", vec![], "is not `xml`"),
("xml:Bad", vec![], "is not `xml`"),
] {
let message = build(name, keyed).unwrap_err().to_string();
assert!(message.contains(error), "{name}: {message}");
}
}
#[test]
fn a_value_is_borrowed_unless_it_was_put_together() {
let doc = r#"<a x="1" y="&">t<b>1 < 2</b><c><![CDATA[z]]></c><d> p <e/> q </d></a>"#;
let mut out = Fields::new();
Xml::new().parse(doc.as_bytes(), &mut out).unwrap();
let input = doc.as_bytes().as_ptr_range();
let mut borrowed = Vec::new();
for (name, value) in out.as_slice() {
if let Cow::Borrowed(bytes) = value.bytes {
let span = bytes.as_ptr_range();
assert!(
bytes.is_empty() || (input.start <= span.start && span.end <= input.end),
"{name}"
);
borrowed.push(name.as_str());
}
}
assert_eq!(borrowed, ["a.@x", "a.c", "a.d.e", "a"]);
}
fn refused(xml: &Xml, input: &[u8]) -> Result<Parsed, ParseError> {
let mut out = Fields::new();
out.field("before", FieldValue::borrowed(b"kept", Hint::Text));
let result = xml.parse(input, &mut out);
out.field("probe", FieldValue::borrowed(b"", Hint::Text));
let names: Vec<&str> = out.as_slice().iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(
names,
["before", "probe"],
"{:?}",
String::from_utf8_lossy(input)
);
result
}
#[test]
fn what_is_not_a_document_is_no_match_and_a_broken_one_says_why() {
let xml = Xml::new();
for input in [
&b""[..],
b"plain",
b"<",
b"<1",
b"<134>Oct 30 fw01 x",
b" <a/>",
b"\xEF\xBB\xBF",
b"< a/>",
b"{\"a\":1}",
] {
assert_eq!(
refused(&xml, input).ok(),
Some(Parsed::NoMatch),
"{input:?}"
);
assert!(!xml.signature().may_match(input), "{input:?}");
}
let cases: &[(&[u8], &str)] = &[
(b"<a>", "never closed"),
(b"<a></b>", "isn't well formed"),
(b"<a/><b/>", "a second root"),
(b"<a/>x", "text outside"),
(b"<a/><![CDATA[y]]>", "text outside"),
(b"<a/>&", "text outside"),
(b"<!DOCTYPE a><a/>", "DOCTYPE"),
(b"<a> </a>", "reference"),
(b"<a>�</a>", "reference"),
(b"<a>&#+65;</a>", "reference"),
(b"<a>&#x+41;</a>", "reference"),
(b"<a>&#x;</a>", "reference"),
(b"<a x=\"&#-1;\"/>", "reference"),
(b"<a x=\"&\"/>", "reference"),
(b"<a x=\"&bogus;\"/>", "reference"),
(b"<a xmlns:x=\"&bogus;\"/>", "reference"),
(b"<a><b y=\"1\" x=\"&bogus;\"/></a>", "reference"),
(b"<a x=\"1\" x=\"2\"/>", "attribute"),
(b"<a x=1/>", "attribute"),
(b"<?xml version=\"1.1\"?><a/>", "declaration"),
(
b"<?xml version=\"1.0\" encoding=\"UTF-16\"?><a/>",
"declaration",
),
(b"<a/><?xml version=\"1.0\"?>", "declaration"),
(b"<!-- a -- b --><a/>", "isn't well formed"),
(b"<!-- only a comment -->", "no root"),
(b"<a>\xff</a>", "isn't UTF-8"),
(b"<a><b>1</b>", "never closed"),
];
for (input, reason) in cases {
match refused(&xml, input) {
Err(ParseError::Malformed {
reason: got,
offset,
}) => {
assert!(got.contains(reason), "{input:?}: {got}");
assert!(offset <= input.len(), "{input:?}: {offset}");
}
other => panic!("{:?}: {other:?}", String::from_utf8_lossy(input)),
}
assert!(xml.signature().may_match(input), "{input:?}");
}
}
#[test]
fn an_error_says_where_in_the_input_given() {
let xml = Xml::new();
for (input, offset) in [
(&b"<a> </a>"[..], 3),
(b"\xEF\xBB\xBF<a> </a>", 6),
(b"<a><b x=\"&bogus;\"/></a>", 3),
(b"<a>1</a><b/>", 8),
(b"<a>\xff</a>", 3),
] {
match refused(&xml, input) {
Err(ParseError::Malformed { offset: got, .. }) => assert_eq!(got, offset, "{input:?}"),
other => panic!("{input:?}: {other:?}"),
}
}
}
#[test]
fn depth_attributes_and_names_are_bounded() {
let xml = Xml::new();
let nest = |depth: usize| format!("{}x{}", "<a>".repeat(depth), "</a>".repeat(depth));
assert_eq!(parsed(&xml, &nest(MAX_DEPTH)).len(), 1);
let attributes = |count: usize| {
let all = (0..count).fold(String::new(), |all, i| all + &format!(" k{i}=\"\""));
format!("<a{all}/>")
};
assert_eq!(
parsed(&xml, &attributes(MAX_ATTRIBUTES)).len(),
MAX_ATTRIBUTES + 1
);
let name = "n".repeat(20);
let deep = format!(
"{}{}{}",
format!("<{name}>").repeat(60),
"<x/>".repeat(2000),
format!("</{name}>").repeat(60)
);
for (doc, what) in [
(nest(MAX_DEPTH + 1), "depth"),
(attributes(MAX_ATTRIBUTES + 1), "attributes"),
(deep, "name bytes"),
] {
match refused(&xml, doc.as_bytes()) {
Err(ParseError::Limit { what: got }) => assert!(got.contains(what), "{got}"),
other => panic!("{what}: {other:?}"),
}
}
}
fn element(depth: u32) -> BoxedStrategy<String> {
let name = prop::sample::select(vec!["a", "b", "c", "item"]);
let text = prop::sample::select(vec!["x", "two words", "1 < 2", "\u{e9}t\u{e9}", "42"]);
let attributes =
prop::sample::subsequence(vec![" x=\"1\"", " y=\"a b\"", " z=\"&\""], 0..=3)
.prop_map(|chosen| chosen.concat());
let leaf =
(name.clone(), attributes.clone(), text).prop_map(|(n, a, t)| format!("<{n}{a}>{t}</{n}>"));
if depth == 0 {
return leaf.boxed();
}
let named = |kid: &str| kid[1..].split([' ', '>']).next().map(str::to_owned);
let children = prop::collection::vec(element(depth - 1), 1..4).prop_map(move |mut kids| {
kids.sort_by_key(|kid| named(kid));
kids.join("\n ")
});
let container =
(name, attributes, children).prop_map(|(n, a, kids)| format!("<{n}{a}>\n {kids}\n</{n}>"));
prop_oneof![leaf, container].boxed()
}
#[cfg(feature = "xml")]
fn from_json(path: &str, value: &serde_json::Value, out: &mut Rows) {
let serde_json::Value::Object(object) = value else {
out.push((path.to_owned(), value.as_str().unwrap().to_owned()));
return;
};
for (key, value) in object {
match (key.as_str(), value) {
("_xml", _) => {}
("#text", text) => out.push((path.to_owned(), text.as_str().unwrap().to_owned())),
(attribute, text) if attribute.starts_with('@') => {
out.push((
format!("{path}.{attribute}"),
text.as_str().unwrap().to_owned(),
));
}
(child, serde_json::Value::Array(values)) => {
for value in values {
from_json(&format!("{path}.{child}"), value, out);
}
}
(other, value) => panic!("{other}: {value}"),
}
}
}
proptest! {
#[cfg(feature = "xml")]
#[test]
fn the_parser_agrees_with_to_json_where_it_loses_nothing(doc in element(3)) {
let json = crate::xml::to_json(doc.as_bytes(), &crate::xml::XmlConfig::default()).unwrap();
let json: serde_json::Value = serde_json::from_slice(&json).unwrap();
let root = json["_xml"]["element"].as_str().unwrap().to_owned();
let mut theirs = Rows::new();
from_json(&root, &json, &mut theirs);
let mut ours = parsed(&Xml::new(), &doc);
theirs.sort();
ours.sort();
prop_assert_eq!(ours, theirs, "{}", doc);
}
#[test]
fn a_damaged_document_is_refused_whole(
doc in element(3),
at in any::<prop::sample::Index>(),
byte in any::<u8>(),
) {
let mut bytes = doc.into_bytes();
let at = at.index(bytes.len());
bytes[at] = byte;
let xml = Xml::new();
let mut out = Fields::new();
let result = xml.parse(&bytes, &mut out);
if !matches!(result, Ok(Parsed::Done)) {
prop_assert!(out.is_empty());
}
out.field("probe", FieldValue::borrowed(b"", Hint::Text));
prop_assert_eq!(out.as_slice().last().unwrap().0.as_str(), "probe");
let fired = xml.signature().may_match(&bytes);
prop_assert!(fired || matches!(result, Ok(Parsed::NoMatch)));
}
}