Debian Codegraph @

tests/dup_node_into_new_doc_tests.rs

raw symbols SCIP
1 //! Tests for `Document::dup_node_into_new_doc` — duplicating a node
2 //! subtree into a fresh, independent `Document`.
3
4 use libxml::parser::Parser;
5 use libxml::tree::{Document, Node};
6
7 #[test]
8 /// `Document::dup_node_into_new_doc` returns an independent document for
9 /// a still-linked element, and the source / sub doc lifetimes are
10 /// independent (drop one, the other survives).
11 fn dup_node_into_new_doc_basic() {
12 let parser = Parser::default();
13 let src = parser
14 .parse_string(
15 "<root xmlns=\"http://example.com/ns\"><a id=\"x\"><b/></a><c/></root>",
16 )
17 .expect("parse src");
18 let root = src.get_root_element().expect("src root");
19 // pick the <a> child
20 let a = root.get_first_child().expect("first child");
21 let sub = Document::dup_node_into_new_doc(&a).expect("dup");
22 let sub_root = sub.get_root_element().expect("sub root");
23 assert_eq!(sub_root.get_name(), "a");
24 // The sub doc's root is a deep copy — it has the <b> child too.
25 assert!(sub_root.get_first_child().is_some());
26 // Drop the source first; sub must still be valid for serialization.
27 drop(src);
28 let serialized = sub.to_string();
29 assert!(serialized.contains("<a"));
30 assert!(serialized.contains("<b"));
31 }
32
33 #[test]
34 /// Repeated extraction in the same source document — the failure mode
35 /// that motivated this API. `xmlDocCopyNode(src, dst, 1)` returns NULL
36 /// on the second call within one source doc; `dup_node_into_new_doc`
37 /// must succeed for every sibling.
38 fn dup_node_into_new_doc_multi_siblings() {
39 let parser = Parser::default();
40 let src = parser
41 .parse_string(
42 "<root xmlns=\"http://example.com/ns\">\
43 <s id=\"s1\"><t>one</t></s>\
44 <s id=\"s2\"><t>two</t></s>\
45 <s id=\"s3\"><t>three</t></s>\
46 </root>",
47 )
48 .expect("parse src");
49 let root = src.get_root_element().expect("src root");
50 let mut child = root.get_first_child();
51 let mut subdocs = Vec::new();
52 let mut count = 0;
53 while let Some(n) = child {
54 if n.get_name() == "s" {
55 let sub = Document::dup_node_into_new_doc(&n)
56 .expect("dup_node_into_new_doc must succeed for every sibling");
57 assert_eq!(
58 sub.get_root_element().unwrap().get_name(),
59 "s",
60 "sub-document #{count} should have <s> as root"
61 );
62 subdocs.push(sub);
63 count += 1;
64 }
65 child = n.get_next_sibling();
66 }
67 assert_eq!(count, 3, "all three siblings extracted");
68 // Drop the source while the subdocs are alive; serialization must
69 // still work — proves the subdocs own their C-side memory.
70 drop(src);
71 for (i, s) in subdocs.iter().enumerate() {
72 let xml = s.to_string();
73 assert!(xml.contains("<s"), "subdoc {i} has <s>");
74 assert!(xml.contains("<t"), "subdoc {i} has <t>");
75 }
76 }
77
78 #[test]
79 /// Drop-order independence: dropping the source document before the
80 /// sub-document must not corrupt the sub-document. Specifically tests
81 /// that ns / dict pointers are owned by the sub-document, not still
82 /// referenced from the (now freed) source.
83 fn dup_node_into_new_doc_source_dropped_first() {
84 let sub = {
85 let parser = Parser::default();
86 let src = parser
87 .parse_string(
88 "<root xmlns=\"http://example.com/ns\" xmlns:x=\"http://example.com/x\">\
89 <a x:tag=\"hi\"><b>text</b></a></root>",
90 )
91 .expect("parse src");
92 let root = src.get_root_element().unwrap();
93 let a = root.get_first_child().unwrap();
94 Document::dup_node_into_new_doc(&a).expect("dup")
95 };
96 // src goes out of scope here — its xmlFreeDoc has fired.
97 let s = sub.to_string();
98 assert!(s.contains("<a"));
99 assert!(s.contains("<b"));
100 assert!(s.contains("text"));
101 }
102
103 #[test]
104 /// Repeated extraction in the same source document, with explicit
105 /// unlink first — the failure mode that motivated this API. A plain
106 /// `xmlDocCopyNode(src, dst, 1)` returns NULL on the second sibling
107 /// in this pattern; `dup_node_into_new_doc` must succeed for every
108 /// detached subtree.
109 fn dup_node_into_new_doc_after_unlink_chain() {
110 let parser = Parser::default();
111 let src = parser
112 .parse_string(
113 "<root xmlns=\"http://example.com/ns\">\
114 <s id=\"s1\"><t>one</t></s>\
115 <s id=\"s2\"><t>two</t></s>\
116 <s id=\"s3\"><t>three</t></s>\
117 </root>",
118 )
119 .expect("parse src");
120 let root = src.get_root_element().expect("src root");
121
122 // Phase 1: collect sibling pages then unlink them from the parent
123 // (mirrors the get_last_child / unlink_node loop in Split::process_pages).
124 let mut pages: Vec<Node> = Vec::new();
125 let mut cur = root.get_first_child();
126 while let Some(n) = cur {
127 let next = n.get_next_sibling();
128 if n.get_name() == "s" {
129 pages.push(n);
130 }
131 cur = next;
132 }
133 for p in pages.iter_mut() {
134 p.unlink_node();
135 }
136
137 // Phase 2: dup each unlinked page into its own sub-document. Every
138 // call must succeed — failure on the second sibling is the regression
139 // we are guarding against.
140 let mut subdocs = Vec::new();
141 for (i, p) in pages.iter().enumerate() {
142 let sub = Document::dup_node_into_new_doc(p)
143 .unwrap_or_else(|_| panic!("dup #{i} failed for unlinked sibling"));
144 let sub_root = sub.get_root_element().expect("sub root");
145 assert_eq!(sub_root.get_name(), "s");
146 subdocs.push(sub);
147 }
148 assert_eq!(subdocs.len(), 3);
149
150 // Phase 3: drop source, then exercise each subdoc.
151 drop(src);
152 for s in &subdocs {
153 let xml = s.to_string();
154 // After namespace reconciliation, the default-ns prefix may be
155 // synthesised as "default:"; check for the local-name with either
156 // a "<" or "<prefix:" lead.
157 assert!(
158 xml.contains("<s ") || xml.contains("<s>") || xml.contains(":s "),
159 "subdoc must contain element s: {xml}"
160 );
161 assert!(
162 xml.contains("<t>") || xml.contains(":t>"),
163 "subdoc must contain element t: {xml}"
164 );
165 }
166 }
167
168 #[test]
169 /// Repeated extraction with realistic between-dup work: mutate an
170 /// attribute on the page about to be duped and run XPath against the
171 /// detached subtree. Exercises every state-mutation knob a downstream
172 /// document-splitter is likely to touch between dups.
173 fn dup_node_into_new_doc_after_xpath_and_attr_mutation() {
174 let parser = Parser::default();
175 let src = parser
176 .parse_string(
177 "<root xmlns=\"http://example.com/ns\">\
178 <s xml:id=\"s1\"><t>one</t></s>\
179 <s xml:id=\"s2\"><t>two</t></s>\
180 <s xml:id=\"s3\"><t>three</t></s>\
181 </root>",
182 )
183 .expect("parse src");
184 let root = src.get_root_element().unwrap();
185
186 let mut pages: Vec<Node> = Vec::new();
187 let mut cur = root.get_first_child();
188 while let Some(n) = cur {
189 let next = n.get_next_sibling();
190 if n.get_name() == "s" {
191 pages.push(n);
192 }
193 cur = next;
194 }
195 for p in pages.iter_mut() {
196 p.unlink_node();
197 }
198
199 let mut subdocs = Vec::new();
200 for (i, p) in pages.iter().enumerate() {
201 eprintln!("[iter {i}] start");
202 let mut p_mut = p.clone();
203 p_mut.set_attribute("inlist", "toc").ok();
204 eprintln!("[iter {i}] post set_attribute");
205 let xpath_hits = p.findnodes("descendant-or-self::*[@*]").unwrap_or_default();
206 eprintln!("[iter {i}] post findnodes (hits={})", xpath_hits.len());
207
208 let sub = Document::dup_node_into_new_doc(p)
209 .unwrap_or_else(|_| panic!("dup #{i} failed after xpath/attr mutation"));
210 eprintln!("[iter {i}] post dup");
211 subdocs.push(sub);
212 }
213 assert_eq!(subdocs.len(), 3);
214 // Drop the page wrappers (still flagged unlinked by `unlink_node`)
215 // BEFORE the source doc — otherwise `_Node::drop`'s xmlFreeNode
216 // touches `node->doc` after `xmlFreeDoc(src)` has already freed it.
217 // That's a pre-existing libxml-rs issue with unlinked-node-outliving
218 // -its-doc, not specific to `dup_node_into_new_doc`.
219 drop(pages);
220 drop(src);
221 for s in &subdocs {
222 let _ = s.to_string();
223 }
224 }
225
226 #[test]
227 /// Stress: many namespaces declared on the root, deep subtrees, and
228 /// repeated dup. Designed to surface dict / ns issues that low-content
229 /// tests miss.
230 fn dup_node_into_new_doc_many_ns_repeated() {
231 let parser = Parser::default();
232 let src_xml = "<root xmlns=\"http://example.com/ns\" \
233 xmlns:a=\"http://example.com/a\" \
234 xmlns:b=\"http://example.com/b\" \
235 xmlns:c=\"http://example.com/c\">\
236 <s id=\"s1\"><t a:k=\"v\"><u b:k=\"v\"/></t></s>\
237 <s id=\"s2\"><t a:k=\"v\"><u c:k=\"v\"/></t></s>\
238 <s id=\"s3\"><t b:k=\"v\"><u a:k=\"v\"/></t></s>\
239 <s id=\"s4\"><t c:k=\"v\"><u b:k=\"v\"/></t></s>\
240 <s id=\"s5\"><t a:k=\"v\"><u c:k=\"v\"/></t></s>\
241 </root>";
242 let src = parser.parse_string(src_xml).expect("parse src");
243 let root = src.get_root_element().unwrap();
244
245 let mut pages: Vec<Node> = Vec::new();
246 let mut cur = root.get_first_child();
247 while let Some(n) = cur {
248 let next = n.get_next_sibling();
249 if n.get_name() == "s" {
250 pages.push(n);
251 }
252 cur = next;
253 }
254 for p in pages.iter_mut() {
255 p.unlink_node();
256 }
257
258 let mut subdocs = Vec::new();
259 for (i, p) in pages.iter().enumerate() {
260 let sub = Document::dup_node_into_new_doc(p)
261 .unwrap_or_else(|_| panic!("ns-stress dup #{i} failed"));
262 subdocs.push(sub);
263 }
264 assert_eq!(subdocs.len(), 5);
265 drop(src);
266 for s in &subdocs {
267 let _ = s.to_string();
268 }
269 }
270
271 #[test]
272 /// Repro: large real-world doc, extract every section sibling. The
273 /// failure mode this guards against is xmlDocCopyNode returning NULL
274 /// on the second sibling specifically when the source document is a
275 /// large, deeply-nested tree (small synthetic XML does not reproduce).
276 fn dup_node_into_new_doc_large_doc_siblings() {
277 let parser = Parser::default();
278 let path = "tests/resources/large_doc.xml";
279 if std::fs::metadata(path).is_err() {
280 eprintln!("skipping: {path} not present");
281 return;
282 }
283 let src = parser.parse_file(path).expect("parse large doc");
284 let root = src.get_root_element().expect("root");
285 // Find the chapter and pick its <section> children — mirrors the
286 // pattern Split applies on a large LaTeXML chapter.
287 let mut pages: Vec<Node> = root
288 .findnodes("descendant::*[local-name()='section']")
289 .unwrap_or_default()
290 // direct children of chapter only
291 .into_iter()
292 .filter(|n| {
293 n.get_parent()
294 .map(|p| p.get_name() == "chapter")
295 .unwrap_or(false)
296 })
297 .collect();
298 assert!(pages.len() >= 2, "need at least 2 section siblings to repro");
299 // Detach each page from its parent before duping (mirrors a
300 // document-splitter that pops siblings from the parent first).
301 for p in pages.iter_mut() {
302 p.unlink_node();
303 }
304 let mut subdocs = Vec::new();
305 for (i, p) in pages.iter().enumerate() {
306 eprintln!("[large_doc] dup #{i} of {}", p.get_name());
307 let sub = Document::dup_node_into_new_doc(p)
308 .unwrap_or_else(|_| panic!("dup #{i} of section returned NULL"));
309 subdocs.push(sub);
310 }
311 eprintln!("[large_doc] all dups OK, count={}", subdocs.len());
312 drop(pages);
313 drop(src);
314 for s in &subdocs {
315 let _ = s.to_string();
316 }
317 }
318
319 #[test]
320 /// Repro at scale: each detached page contains hundreds of xml:id-bearing
321 /// descendants, and we run XPath against the detached subtree before
322 /// each dup (mirrors the cleanup pattern a document-splitter uses to
323 /// drop ID-cache entries for the moved subtree). Small synthetic XMLs
324 /// don't trigger the second-dup-NULL; this test does.
325 fn dup_node_into_new_doc_xpath_then_dup_at_scale() {
326 // Build a doc with 5 sibling sections, each carrying ~200 xml:id'd
327 // descendants. Total: ~1000 ids on the source.
328 let mut xml = String::from(
329 "<root xmlns=\"http://example.com/ns\">",
330 );
331 for i in 0..5 {
332 xml.push_str(&format!("<s xml:id=\"s{i}\">"));
333 for j in 0..200 {
334 xml.push_str(&format!(
335 "<p xml:id=\"s{i}.p{j}\"><e xml:id=\"s{i}.p{j}.e\"/></p>"
336 ));
337 }
338 xml.push_str("</s>");
339 }
340 xml.push_str("</root>");
341 let parser = Parser::default();
342 let src = parser.parse_string(&xml).expect("parse");
343 let root = src.get_root_element().unwrap();
344
345 let mut pages: Vec<Node> = Vec::new();
346 let mut cur = root.get_first_child();
347 while let Some(n) = cur {
348 let next = n.get_next_sibling();
349 if n.get_name() == "s" {
350 pages.push(n);
351 }
352 cur = next;
353 }
354 for p in pages.iter_mut() {
355 p.unlink_node();
356 }
357
358 let mut subdocs = Vec::new();
359 for (i, p) in pages.iter().enumerate() {
360 // Mirror the document-splitter pattern: walk the detached subtree
361 // for xml:id-bearing descendants, then dup.
362 let hits = p
363 .findnodes("descendant-or-self::*[@*[local-name()='id']]")
364 .unwrap_or_default();
365 assert!(hits.len() > 100, "expected many xml:id hits, got {}", hits.len());
366 let sub = Document::dup_node_into_new_doc(p)
367 .unwrap_or_else(|_| panic!("dup #{i} returned NULL after XPath descent"));
368 subdocs.push(sub);
369 }
370 drop(pages);
371 drop(src);
372 for s in &subdocs {
373 let _ = s.to_string();
374 }
375 }
376
377 #[test]
378 /// Faithfully reproduce a document-splitter that, for each detached
379 /// page, also runs XPath on the SOURCE (still-live) document and
380 /// scans the detached subtree for xml:id descendants. This is the
381 /// pattern oxide hits — XPath fanout on the source between sub-doc
382 /// builds is what corrupts state for the next xmlDocCopyNode.
383 fn dup_node_into_new_doc_mixed_xpath_at_scale() {
384 let mut xml = String::from("<root xmlns=\"http://example.com/ns\">");
385 // Sprinkle "resource" elements at the top so the source XPath has
386 // something to enumerate.
387 for r in 0..5 {
388 xml.push_str(&format!("<resource src=\"r{r}.css\"/>"));
389 }
390 for i in 0..7 {
391 xml.push_str(&format!("<s xml:id=\"s{i}\">"));
392 for j in 0..400 {
393 xml.push_str(&format!(
394 "<p xml:id=\"s{i}.p{j}\"><e xml:id=\"s{i}.p{j}.e\"/></p>"
395 ));
396 }
397 xml.push_str("</s>");
398 }
399 xml.push_str("</root>");
400
401 let parser = Parser::default();
402 let src = parser.parse_string(&xml).expect("parse");
403 let root = src.get_root_element().unwrap();
404
405 let mut pages: Vec<Node> = Vec::new();
406 let mut cur = root.get_first_child();
407 while let Some(n) = cur {
408 let next = n.get_next_sibling();
409 if n.get_name() == "s" {
410 pages.push(n);
411 }
412 cur = next;
413 }
414 for p in pages.iter_mut() {
415 p.unlink_node();
416 }
417
418 let mut subdocs = Vec::new();
419 for (i, p) in pages.iter().enumerate() {
420 // (a) descendant scan on detached page (id-cache cleanup pattern)
421 let id_hits = p
422 .findnodes("descendant-or-self::*[@*[local-name()='id']]")
423 .unwrap_or_default();
424 assert!(id_hits.len() > 100, "iter {i}: too few id hits");
425 // (b) XPath on the live source doc (resource enumeration pattern)
426 let res_hits = root
427 .findnodes("descendant::*[local-name()='resource']")
428 .unwrap_or_default();
429 assert_eq!(res_hits.len(), 5, "iter {i}: expected 5 resource hits");
430 // (c) dup
431 let sub = Document::dup_node_into_new_doc(p)
432 .unwrap_or_else(|_| panic!("dup #{i} returned NULL after mixed XPath"));
433 subdocs.push(sub);
434 }
435 drop(pages);
436 drop(src);
437 for s in &subdocs {
438 let _ = s.to_string();
439 }
440 }