-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathnode_leaf_test.go
More file actions
1053 lines (899 loc) · 42.7 KB
/
Copy pathnode_leaf_test.go
File metadata and controls
1053 lines (899 loc) · 42.7 KB
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package helium_test
import (
"fmt"
"testing"
"github.com/lestrrat-go/helium"
"github.com/lestrrat-go/helium/enum"
"github.com/stretchr/testify/require"
)
// leafCtor builds a freshly created, unlinked leaf node of a specific concrete
// type for the table-driven AddChild/AddSibling guard tests.
type leafCtor func(t *testing.T, doc *helium.Document) helium.MutableNode
func mustCreatePI(t *testing.T, doc *helium.Document) *helium.ProcessingInstruction {
t.Helper()
return doc.CreatePI("target", "data")
}
func mustCreateEntityRef(t *testing.T, doc *helium.Document) *helium.EntityRef {
t.Helper()
ref, err := doc.CreateReference("amp")
require.NoError(t, err, "CreateReference must succeed")
return ref
}
// leafCase describes one concrete leaf type and the guard behavior it exposes
// through its AddChild override.
type leafCase struct {
name string
// new builds a fresh, unlinked instance of the leaf type.
new leafCtor
// canContainChildren is true when the type's AddChild can legally accept a
// foreign child (EntityRef). For those the ancestor-insertion guard is
// exercised. Types whose AddChild only ever rejects (CDATASection, PI) or
// only content-merges its own kind (Text, Comment) set this false.
canContainChildren bool
// addChildSelfErr is the sentinel AddChild(self) must wrap (errors.Is). For
// Text, Comment and EntityRef the shared cycle guard fires, and
// ProcessingInstruction detects the self-add by identity (ErrCyclicNode);
// CDATASection rejects AddChild before any self-add check
// (ErrInvalidOperation), so self-insertion surfaces that rejection instead.
addChildSelfErr error
}
func leafCases() []leafCase {
return []leafCase{
{
name: "Text",
new: func(t *testing.T, doc *helium.Document) helium.MutableNode {
return mustCreateText(t, doc, []byte("x"))
},
addChildSelfErr: helium.ErrCyclicNode,
},
{
name: "Comment",
new: func(t *testing.T, doc *helium.Document) helium.MutableNode {
return mustCreateComment(t, doc, []byte("x"))
},
addChildSelfErr: helium.ErrCyclicNode,
},
{
name: "CDATASection",
new: func(t *testing.T, doc *helium.Document) helium.MutableNode {
return doc.CreateCDATASection([]byte("x"))
},
addChildSelfErr: helium.ErrInvalidOperation,
},
{
// A PI carries its content as a string, not as element/text
// children, so its AddChild rejects a foreign (non-text) node with
// ErrInvalidOperation. A self-add is detected by identity on the
// reject path (a PI is not a text node, so it reaches that check),
// returning ErrCyclicNode like every other leaf self-add.
name: "ProcessingInstruction",
new: func(t *testing.T, doc *helium.Document) helium.MutableNode { return mustCreatePI(t, doc) },
addChildSelfErr: helium.ErrCyclicNode,
},
{
name: "EntityRef",
new: func(t *testing.T, doc *helium.Document) helium.MutableNode { return mustCreateEntityRef(t, doc) },
canContainChildren: true,
addChildSelfErr: helium.ErrCyclicNode,
},
}
}
const (
errAddChildCycle = "cannot add a node as a child of itself or one of its descendants"
errAddSiblingCycle = "cannot add a node as a sibling of itself or one of its descendants"
)
const errReplaceCycle = "cannot replace a node with one of its own ancestors"
func TestTextNode(t *testing.T) {
t.Parallel()
// Text.AddSibling's non-text fallback
// path (the `return addSibling(n, cur)` branch). Moving an already-linked
// non-text node via text.AddSibling must auto-unlink it from its old parent and
// fix the sibling/parent pointers.
t.Run("AddSibling non-text fallback", func(t *testing.T) {
cases := []struct {
name string
newNode func(t *testing.T, doc *helium.Document) helium.Node
}{
{
name: "comment incoming",
newNode: func(t *testing.T, doc *helium.Document) helium.Node { return mustCreateComment(t, doc, []byte("note")) },
},
{
name: "element incoming",
newNode: func(t *testing.T, doc *helium.Document) helium.Node { return mustCreateElement(t, doc, "incoming") },
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
dst := mustCreateElement(t, doc, "dst")
src := mustCreateElement(t, doc, "src")
txt := mustCreateText(t, doc, []byte("anchor"))
incoming := tc.newNode(t, doc)
require.NoError(t, dst.AddChild(txt), "text anchor starts under dst")
require.NoError(t, src.AddChild(incoming), "incoming starts under src")
// incoming is non-text, so Text.AddSibling falls through to the generic
// addSibling path, which must auto-unlink it from src first.
require.NoError(t, txt.AddSibling(incoming), "non-text sibling move succeeds")
require.Equal(t, helium.Node(dst), incoming.Parent(), "incoming parent is now dst")
require.Equal(t, incoming, txt.NextSibling(), "incoming follows the text node")
require.Equal(t, helium.Node(txt), incoming.PrevSibling(), "text node precedes incoming")
require.Equal(t, incoming, dst.LastChild(), "dst lastChild is incoming")
require.Nil(t, src.FirstChild(), "src no longer holds incoming")
require.Nil(t, src.LastChild(), "src no longer holds incoming")
require.Nil(t, incoming.NextSibling(), "incoming has no stale next")
requireNoCycle(t, dst)
requireNoCycle(t, src)
})
}
})
t.Run("AddSibling self rejected", func(t *testing.T) {
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
txt := mustCreateText(t, doc, []byte("hello"))
require.NoError(t, root.AddChild(txt))
// Self-merge must be rejected by the shared guard, not silently double the
// text content via the text-merge fast path.
err := txt.AddSibling(txt)
require.Error(t, err, "Text.AddSibling(self) must be rejected")
require.ErrorContains(t, err, "cannot add a node as a sibling of itself or one of its descendants")
require.Equal(t, []byte("hello"), txt.Content(), "content must not be doubled")
require.Nil(t, txt.NextSibling(), "text must not gain a sibling")
require.Nil(t, txt.PrevSibling(), "text must not gain a sibling")
requireNoCycle(t, root)
})
t.Run("AddSibling merge unlinks", func(t *testing.T) {
doc := helium.NewDefaultDocument()
dst := mustCreateElement(t, doc, "dst")
src := mustCreateElement(t, doc, "src")
target := mustCreateText(t, doc, []byte("foo"))
incoming := mustCreateText(t, doc, []byte("bar"))
require.NoError(t, dst.AddChild(target), "target starts under dst")
require.NoError(t, src.AddChild(incoming), "incoming starts under src")
// Merging an already-linked text node must auto-unlink it from src before
// merging its content into target, leaving no dangling link under src.
require.NoError(t, target.AddSibling(incoming), "text merge succeeds")
require.Equal(t, []byte("foobar"), target.Content(), "content merged")
require.Nil(t, src.FirstChild(), "incoming detached from src")
require.Nil(t, src.LastChild(), "incoming detached from src")
require.Nil(t, incoming.Parent(), "incoming has no stale parent")
require.Nil(t, incoming.PrevSibling(), "incoming has no stale prev")
require.Nil(t, incoming.NextSibling(), "incoming has no stale next")
requireNoCycle(t, dst)
requireNoCycle(t, src)
})
t.Run("AddChild self rejected", func(t *testing.T) {
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
txt := mustCreateText(t, doc, []byte("hello"))
require.NoError(t, root.AddChild(txt))
// Self-merge must be rejected by the shared guard, not silently double the
// text content via the text-merge fast path.
err := txt.AddChild(txt)
require.Error(t, err, "Text.AddChild(self) must be rejected")
require.ErrorContains(t, err, "cannot add a node as a child of itself or one of its descendants")
require.Equal(t, []byte("hello"), txt.Content(), "content must not be doubled")
require.Nil(t, txt.FirstChild(), "text must not gain a child")
require.Equal(t, txt, root.FirstChild(), "tree must not be corrupted")
requireNoCycle(t, root)
})
t.Run("AddChild merge unlinks", func(t *testing.T) {
doc := helium.NewDefaultDocument()
dst := mustCreateElement(t, doc, "dst")
src := mustCreateElement(t, doc, "src")
target := mustCreateText(t, doc, []byte("foo"))
incoming := mustCreateText(t, doc, []byte("bar"))
require.NoError(t, dst.AddChild(target), "target starts under dst")
require.NoError(t, src.AddChild(incoming), "incoming starts under src")
// Merging an already-linked text node via AddChild must auto-unlink it from
// src before merging its content into target.
require.NoError(t, target.AddChild(incoming), "text merge succeeds")
require.Equal(t, []byte("foobar"), target.Content(), "content merged")
require.Nil(t, src.FirstChild(), "incoming detached from src")
require.Nil(t, src.LastChild(), "incoming detached from src")
require.Nil(t, incoming.Parent(), "incoming has no stale parent")
require.Nil(t, incoming.PrevSibling(), "incoming has no stale prev")
require.Nil(t, incoming.NextSibling(), "incoming has no stale next")
requireNoCycle(t, dst)
requireNoCycle(t, src)
})
}
func TestCommentNode(t *testing.T) {
t.Parallel()
// Comment AddChild merge/rejection branches.
t.Run("node methods", func(t *testing.T) {
doc := helium.NewDocument("1.0", "UTF-8", helium.StandaloneImplicitNo)
c := doc.CreateComment([]byte("hello"))
require.Equal(t, []byte("hello"), c.Content())
// A comment carries the "(comment)" sentinel name, matching the parenthesized
// sentinel convention its sibling leaf types (Text "(text)", CDATA "(CDATA)")
// use for nodes without a real XML name.
require.Equal(t, "(comment)", c.Name(), "comment sentinel name")
require.Equal(t, "(comment)", c.LocalName(), "comment sentinel local name")
// Merging another (unlinked) comment appends its content.
other := doc.CreateComment([]byte(" world"))
require.NoError(t, c.AddChild(other))
require.Equal(t, []byte("hello world"), c.Content())
// AppendText appends.
require.NoError(t, c.AppendText([]byte("!")))
require.Equal(t, []byte("hello world!"), c.Content())
// Adding a non-comment node is rejected.
require.Error(t, c.AddChild(doc.CreateText([]byte("t"))))
// Adding nil is rejected.
require.Error(t, c.AddChild(nil))
})
t.Run("AddChild self rejected", func(t *testing.T) {
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
comment := mustCreateComment(t, doc, []byte("note"))
require.NoError(t, root.AddChild(comment))
// Self-merge must be rejected by the shared guard, not silently double the
// comment content via the comment-merge fast path.
err := comment.AddChild(comment)
require.Error(t, err, "Comment.AddChild(self) must be rejected")
require.ErrorContains(t, err, "cannot add a node as a child of itself or one of its descendants")
require.Equal(t, []byte("note"), comment.Content(), "content must not be doubled")
require.Nil(t, comment.FirstChild(), "comment must not gain a child")
require.Equal(t, comment, root.FirstChild(), "tree must not be corrupted")
requireNoCycle(t, root)
})
t.Run("AddChild merge unlinks", func(t *testing.T) {
doc := helium.NewDefaultDocument()
dst := mustCreateElement(t, doc, "dst")
src := mustCreateElement(t, doc, "src")
target := mustCreateComment(t, doc, []byte("foo"))
incoming := mustCreateComment(t, doc, []byte("bar"))
require.NoError(t, dst.AddChild(target), "target starts under dst")
require.NoError(t, src.AddChild(incoming), "incoming starts under src")
// Merging an already-linked comment node via AddChild must auto-unlink it
// from src before merging its content into target.
require.NoError(t, target.AddChild(incoming), "comment merge succeeds")
require.Equal(t, []byte("foobar"), target.Content(), "content merged")
require.Nil(t, src.FirstChild(), "incoming detached from src")
require.Nil(t, src.LastChild(), "incoming detached from src")
require.Nil(t, incoming.Parent(), "incoming has no stale parent")
require.Nil(t, incoming.PrevSibling(), "incoming has no stale prev")
require.Nil(t, incoming.NextSibling(), "incoming has no stale next")
requireNoCycle(t, dst)
requireNoCycle(t, src)
})
}
func TestCDATANode(t *testing.T) {
t.Parallel()
// the CDATASection node methods.
t.Run("node methods", func(t *testing.T) {
doc := helium.NewDocument("1.0", "UTF-8", helium.StandaloneImplicitNo)
cd := doc.CreateCDATASection([]byte("data"))
// AppendText grows the content.
require.NoError(t, cd.AppendText([]byte("+more")))
require.Equal(t, []byte("data+more"), cd.Content())
// AddChild is rejected on a CDATA node.
require.Error(t, cd.AddChild(doc.CreateText([]byte("x"))))
// SetTreeDoc must not panic.
cd.SetTreeDoc(doc)
// AddSibling and Replace must run without panicking.
root, err := doc.CreateElement("root")
require.NoError(t, err)
require.NoError(t, doc.AddChild(root))
require.NoError(t, root.AddChild(cd))
require.NoError(t, cd.AddSibling(doc.CreateCDATASection([]byte("sib"))))
})
t.Run("AddChild rejected", func(t *testing.T) {
doc := helium.NewDefaultDocument()
cdata := doc.CreateCDATASection([]byte("payload"))
// CDATASection has no content-merge path; AddChild is always rejected and
// must never corrupt the node, including for a self-insertion.
err := cdata.AddChild(cdata)
require.Error(t, err, "CDATASection.AddChild must be rejected")
require.Equal(t, []byte("payload"), cdata.Content(), "content must be untouched")
require.Nil(t, cdata.FirstChild(), "cdata must not gain a child")
requireNoCycle(t, cdata)
})
}
func TestPINode(t *testing.T) {
t.Parallel()
// ProcessingInstruction AddChild/AppendText paths
// including the text-merge and rejection branches.
t.Run("node methods", func(t *testing.T) {
doc := helium.NewDocument("1.0", "UTF-8", helium.StandaloneImplicitNo)
pi := doc.CreatePI("target", "data")
require.Equal(t, "target", pi.Name())
require.Equal(t, []byte("data"), pi.Content())
require.Equal(t, helium.ProcessingInstructionNode, pi.Type())
// Adding a text node merges into the data string.
require.NoError(t, pi.AddChild(doc.CreateText([]byte(" more"))))
require.Equal(t, []byte("data more"), pi.Content())
// Adding a CDATA node also merges.
require.NoError(t, pi.AddChild(doc.CreateCDATASection([]byte("X"))))
require.Contains(t, string(pi.Content()), "X")
// AppendText appends directly.
require.NoError(t, pi.AppendText([]byte("Y")))
require.Contains(t, string(pi.Content()), "Y")
// Adding an element child is rejected with a wrapped ErrInvalidOperation.
e, err := doc.CreateElement("e")
require.NoError(t, err)
require.ErrorIs(t, pi.AddChild(e), helium.ErrInvalidOperation)
// Adding a nil node is rejected with ErrNilNode (not a panic).
require.Error(t, pi.AddChild(nil))
})
// a processing instruction
// carries its content as a string (the "data" portion), not as child nodes.
// AppendText and a Text/CDATA AddChild route into the PI data; any other node
// type is rejected. A PI must never gain element/text children, and must
// serialize as "<?target data?>".
t.Run("content is a string, not children", func(t *testing.T) {
t.Run("AppendText routes into data and creates no children", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
pi := doc.CreatePI("target", "")
require.NoError(t, pi.AppendText([]byte("hello")), "AppendText must succeed")
require.NoError(t, pi.AppendText([]byte(" world")), "second AppendText must succeed")
require.Nil(t, pi.FirstChild(), "PI must not gain child nodes")
require.Nil(t, pi.LastChild(), "PI must not gain child nodes")
require.Equal(t, "hello world", string(pi.Content()), "PI data must hold the appended text")
})
t.Run("AddChild of text/cdata routes into data and creates no children", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
pi := doc.CreatePI("target", "a")
require.NoError(t, pi.AddChild(doc.CreateText([]byte("b"))), "Text AddChild must succeed")
require.NoError(t, pi.AddChild(doc.CreateCDATASection([]byte("c"))), "CDATA AddChild must succeed")
require.Nil(t, pi.FirstChild(), "PI must not gain child nodes")
require.Equal(t, "abc", string(pi.Content()), "PI data must absorb text/cdata content")
})
t.Run("AddChild unlinks an already-linked text/cdata operand", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
oldParent := mustCreateElement(t, doc, "old")
txt := doc.CreateText([]byte("b"))
require.NoError(t, oldParent.AddChild(txt), "text starts under oldParent")
require.Equal(t, helium.Node(oldParent), txt.Parent(), "text parent is oldParent")
pi := doc.CreatePI("target", "a")
require.NoError(t, pi.AddChild(txt), "Text AddChild must succeed")
// Content is merged into the PI data...
require.Equal(t, "ab", string(pi.Content()), "PI data must absorb the text content")
require.Nil(t, pi.FirstChild(), "PI must not gain a child")
// ...and the source node is unlinked from its old parent, honoring the
// AddChild auto-unlink contract instead of leaving it linked twice.
require.Nil(t, txt.Parent(), "merged text must be unlinked from its old parent")
require.Nil(t, oldParent.FirstChild(), "oldParent must no longer reference the text")
})
t.Run("AddChild of a non-text node is rejected", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
pi := doc.CreatePI("target", "data")
err := pi.AddChild(mustCreateElement(t, doc, "child"))
require.Error(t, err, "adding an element child to a PI must be rejected")
require.ErrorIs(t, err, helium.ErrInvalidOperation,
"a non-text PI child rejection must wrap ErrInvalidOperation like every other leaf rejection")
require.Nil(t, pi.FirstChild(), "PI must not gain a child")
require.Equal(t, "data", string(pi.Content()), "PI data must be unchanged")
})
t.Run("AddChild rejects a nil operand", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
pi := doc.CreatePI("target", "data")
require.ErrorIs(t, pi.AddChild(nil), helium.ErrNilNode, "nil operand must be rejected")
})
t.Run("PI serializes as <?target data?>", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root, err := doc.CreateElement("root")
require.NoError(t, err)
require.NoError(t, doc.SetDocumentElement(root))
pi := doc.CreatePI("target", "")
require.NoError(t, pi.AppendText([]byte("data")), "AppendText must succeed")
require.NoError(t, root.AddChild(pi), "PI must attach under root")
str, err := helium.WriteString(doc)
require.NoError(t, err)
require.Contains(t, str, "<?target data?>", "PI must serialize from its data string")
})
})
// AddChild on a typed-nil
// *ProcessingInstruction receiver rejects a non-mergeable operand with the
// shared ErrInvalidOperation shape instead of panicking: the self-add identity
// check compares the operand interface against the receiver pointer directly
// and never dereferences the receiver. The other strict leaves (Text, Comment,
// CDATASection) are not covered here — their rejection message formats
// n.Type() through the value-receiver docnode method, which dereferences a nil
// receiver, and that is out-of-contract caller misuse, outside what this guards.
t.Run("AddChild on a typed-nil receiver", func(t *testing.T) {
doc := helium.NewDefaultDocument()
elem := mustCreateElement(t, doc, "root")
var pi *helium.ProcessingInstruction
var err error
// The closure adapts the call for NotPanics while capturing the error for
// the shape assertions below.
require.NotPanics(t, func() { err = pi.AddChild(elem) },
"nil-receiver AddChild must return an error, not panic")
require.ErrorIs(t, err, helium.ErrInvalidOperation)
require.NotErrorIs(t, err, helium.ErrCyclicNode,
"a nil receiver must not be mistaken for a self-add")
require.ErrorContains(t, err,
fmt.Sprintf("cannot add a %s as a child of a %s node", helium.ElementNode, helium.ProcessingInstructionNode))
})
}
func TestEntityNode(t *testing.T) {
t.Parallel()
// the Entity node-interface methods.
t.Run("entity node methods", func(t *testing.T) {
doc := helium.NewDocument("1.0", "UTF-8", helium.StandaloneImplicitNo)
dtd, err := doc.CreateInternalSubset("doc", "", "")
require.NoError(t, err)
ent, err := dtd.AddEntity("e", enum.InternalGeneralEntity, "", "", "x")
require.NoError(t, err)
ent.SetOrig("&e;")
require.False(t, ent.Checked())
ent.MarkChecked()
require.True(t, ent.Checked())
ent.SetTreeDoc(doc)
require.NoError(t, ent.AppendText([]byte("more")))
})
// the EntityRef node-interface methods.
t.Run("entity reference node methods", func(t *testing.T) {
doc := helium.NewDocument("1.0", "UTF-8", helium.StandaloneImplicitNo)
ref, err := doc.CreateCharRef("amp")
require.NoError(t, err)
ref.SetTreeDoc(doc)
require.NoError(t, ref.AppendText([]byte("x")))
root, err := doc.CreateElement("root")
require.NoError(t, err)
require.NoError(t, doc.AddChild(root))
require.NoError(t, root.AddChild(ref))
require.NoError(t, ref.AddSibling(doc.CreateText([]byte("after"))))
})
}
func TestNotationNode(t *testing.T) {
t.Parallel()
// Notation node-interface methods.
t.Run("node methods", func(t *testing.T) {
doc := helium.NewDocument("1.0", "UTF-8", helium.StandaloneImplicitNo)
dtd, err := doc.CreateInternalSubset("doc", "", "")
require.NoError(t, err)
nota, err := dtd.AddNotation("n", "pub", "sys")
require.NoError(t, err)
nota.SetTreeDoc(doc)
nota.Free()
require.NoError(t, nota.AppendText([]byte("x")))
})
// the remaining Notation node-method
// wrappers (AddSibling, Replace, Free, AddChild).
t.Run("remaining node-interface methods", func(t *testing.T) {
doc := helium.NewDocument("1.0", "UTF-8", helium.StandaloneImplicitNo)
dtd, err := doc.CreateInternalSubset("doc", "", "")
require.NoError(t, err)
nota, err := dtd.AddNotation("n", "", "sys")
require.NoError(t, err)
// These delegate to the shared tree primitives; exercise without asserting
// implementation-defined success on an already-attached node.
x, err := doc.CreateElement("x")
require.NoError(t, err)
_ = nota.AddSibling(x)
_ = nota.Replace()
_ = nota.AddChild(doc.CreateText([]byte("t")))
nota.Free()
})
}
func TestLeafGuards(t *testing.T) {
t.Parallel()
// every leaf-type AddChild override against the
// shared self/ancestor cycle guard and auto-unlink contract.
for _, tc := range leafCases() {
t.Run("AddChild "+tc.name, func(t *testing.T) {
t.Parallel()
t.Run("self insertion is rejected", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
leaf := tc.new(t, doc)
require.NoError(t, root.AddChild(leaf), "leaf starts under root")
err := leaf.AddChild(leaf)
require.Error(t, err, "AddChild(self) must be rejected")
require.ErrorIs(t, err, tc.addChildSelfErr)
require.Nil(t, leaf.FirstChild(), "leaf must not gain a child")
require.Equal(t, helium.Node(leaf), root.FirstChild(), "tree must not be corrupted")
require.Equal(t, helium.Node(root), leaf.Parent(), "leaf parent must stay root")
requireNoCycle(t, root)
})
if tc.canContainChildren {
t.Run("ancestor insertion is rejected", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
leaf := tc.new(t, doc)
require.NoError(t, root.AddChild(leaf), "leaf starts under root")
// Inserting root (an ancestor of leaf) as a child of leaf would
// make an ancestor a descendant of itself.
err := leaf.AddChild(root)
require.Error(t, err, "inserting an ancestor must be rejected")
require.ErrorContains(t, err, errAddChildCycle)
require.Nil(t, leaf.FirstChild(), "leaf must not gain a child")
require.Nil(t, root.Parent(), "root must remain the tree root")
require.Equal(t, helium.Node(root), leaf.Parent(), "tree must stay intact")
requireNoCycle(t, root)
})
t.Run("legal already-linked move unlinks from old parent", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
container := tc.new(t, doc)
oldParent := mustCreateElement(t, doc, "old")
moving := mustCreateElement(t, doc, "moving")
require.NoError(t, oldParent.AddChild(moving), "moving starts under old parent")
// Moving moving from oldParent into the leaf container must detach
// it from oldParent first, leaving no stale links behind.
require.NoError(t, container.AddChild(moving), "reparenting into leaf container succeeds")
require.Equal(t, helium.Node(container), moving.Parent(), "moving parent is now the container")
require.Equal(t, helium.Node(moving), container.FirstChild(), "container firstChild is moving")
require.Equal(t, helium.Node(moving), container.LastChild(), "container lastChild is moving")
require.Nil(t, oldParent.FirstChild(), "old parent no longer holds moving")
require.Nil(t, oldParent.LastChild(), "old parent no longer holds moving")
require.Nil(t, moving.PrevSibling(), "moving has no stale prev")
require.Nil(t, moving.NextSibling(), "moving has no stale next")
requireNoCycle(t, container)
requireNoCycle(t, oldParent)
})
} else {
// The strict leaves (Text, Comment, CDATASection, PI) never hold
// children, so an ancestor operand is not a potential cycle — it
// is just another invalid operand, and must take the shared
// ErrInvalidOperation shape (not ErrCyclicNode, which is reserved
// for the self-add).
t.Run("ancestor operand is rejected as invalid operation", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
mid := mustCreateElement(t, doc, "mid")
require.NoError(t, root.AddChild(mid), "mid starts under root")
leaf := tc.new(t, doc)
require.NoError(t, mid.AddChild(leaf), "leaf starts under mid")
for name, operand := range map[string]helium.Node{
"parent": mid,
"ancestor": root,
} {
err := leaf.AddChild(operand)
require.Error(t, err, "AddChild(%s) must be rejected", name)
require.ErrorIs(t, err, helium.ErrInvalidOperation)
require.NotErrorIs(t, err, helium.ErrCyclicNode)
require.ErrorContains(t, err,
fmt.Sprintf("cannot add a %s as a child of a %s node", helium.ElementNode, leaf.Type()))
}
require.Nil(t, leaf.FirstChild(), "leaf must not gain a child")
require.Equal(t, helium.Node(mid), leaf.Parent(), "tree must stay intact")
require.Nil(t, root.Parent(), "root must remain the tree root")
requireNoCycle(t, root)
})
}
})
}
// every leaf-type AddSibling override against
// the shared self/ancestor cycle guard and auto-unlink contract.
for _, tc := range leafCases() {
t.Run("AddSibling "+tc.name, func(t *testing.T) {
t.Parallel()
t.Run("self insertion is rejected", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
leaf := tc.new(t, doc)
require.NoError(t, root.AddChild(leaf), "leaf starts under root")
err := leaf.AddSibling(leaf)
require.Error(t, err, "AddSibling(self) must be rejected")
require.ErrorContains(t, err, errAddSiblingCycle)
require.Equal(t, helium.Node(leaf), root.FirstChild(), "tree must not be corrupted")
require.Equal(t, helium.Node(leaf), root.LastChild(), "tree must not be corrupted")
require.Nil(t, leaf.NextSibling(), "leaf must not gain a sibling")
require.Nil(t, leaf.PrevSibling(), "leaf must not gain a sibling")
requireNoCycle(t, root)
})
t.Run("ancestor insertion is rejected", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
mid := mustCreateElement(t, doc, "mid")
leaf := tc.new(t, doc)
require.NoError(t, root.AddChild(mid), "mid starts under root")
require.NoError(t, mid.AddChild(leaf), "leaf starts under mid")
// A sibling of leaf lands under mid; installing root (mid's ancestor)
// there would make an ancestor a descendant of itself.
err := leaf.AddSibling(root)
require.Error(t, err, "inserting an ancestor as a sibling must be rejected")
require.ErrorContains(t, err, errAddSiblingCycle)
require.Nil(t, root.Parent(), "root must remain the tree root")
require.Equal(t, helium.Node(leaf), mid.FirstChild(), "tree must stay intact")
require.Equal(t, helium.Node(leaf), mid.LastChild(), "tree must stay intact")
require.Nil(t, leaf.NextSibling(), "leaf must not gain a sibling")
requireNoCycle(t, root)
})
t.Run("legal already-linked move unlinks from old parent", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
dst := mustCreateElement(t, doc, "dst")
src := mustCreateElement(t, doc, "src")
anchor := tc.new(t, doc)
moving := mustCreateElement(t, doc, "moving")
require.NoError(t, dst.AddChild(anchor), "anchor starts under dst")
require.NoError(t, src.AddChild(moving), "moving starts under src")
// anchor.AddSibling(moving) must detach moving from src before
// splicing it after anchor under dst.
require.NoError(t, anchor.AddSibling(moving), "moving anchor's sibling succeeds")
require.Equal(t, helium.Node(dst), moving.Parent(), "moving parent is now dst")
require.Equal(t, helium.Node(moving), anchor.NextSibling(), "moving follows anchor")
require.Equal(t, helium.Node(anchor), moving.PrevSibling(), "anchor precedes moving")
require.Equal(t, helium.Node(moving), dst.LastChild(), "dst lastChild is moving")
require.Nil(t, src.FirstChild(), "src no longer holds moving")
require.Nil(t, src.LastChild(), "src no longer holds moving")
requireNoCycle(t, dst)
requireNoCycle(t, src)
})
})
}
// every leaf-type Replace override (Text,
// Comment, CDATASection, ProcessingInstruction, EntityRef). Each override
// delegates to replaceNode, so this confirms the override exists and is wired to
// the shared ancestor-rejection guard and to the linked / non-MutableNode
// replacement splice.
for _, tc := range leafCases() {
t.Run("Replace "+tc.name, func(t *testing.T) {
t.Parallel()
t.Run("ancestor replacement is rejected", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
mid := mustCreateElement(t, doc, "mid")
leaf := tc.new(t, doc)
require.NoError(t, root.AddChild(mid), "mid starts under root")
require.NoError(t, mid.AddChild(leaf), "leaf starts under mid")
// Replacing leaf with mid (its parent/ancestor) would splice an
// ancestor below itself, creating a cycle.
err := leaf.Replace(mid)
require.Error(t, err, "replacing leaf with an ancestor must be rejected")
require.ErrorContains(t, err, errReplaceCycle)
require.Equal(t, helium.Node(leaf), mid.FirstChild(), "leaf stays under mid")
require.Equal(t, helium.Node(mid), leaf.Parent(), "leaf parent stays mid")
requireNoCycle(t, root)
})
t.Run("legal already-linked replacement splices in", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
leaf := tc.new(t, doc)
incoming := mustCreateElement(t, doc, "incoming")
require.NoError(t, root.AddChild(leaf), "leaf starts under root")
src := mustCreateElement(t, doc, "src")
require.NoError(t, src.AddChild(incoming), "incoming starts under src")
// incoming is already linked under src; replacing leaf with it must
// detach it from src and splice it into leaf's position under root.
require.NoError(t, leaf.Replace(incoming), "linked replacement succeeds")
require.Equal(t, helium.Node(incoming), root.FirstChild(), "incoming took leaf's position")
require.Equal(t, helium.Node(incoming), root.LastChild(), "incoming is the only child")
require.Equal(t, helium.Node(root), incoming.Parent(), "incoming parent is root")
require.Nil(t, src.FirstChild(), "src no longer holds incoming")
require.Nil(t, leaf.Parent(), "replaced leaf is detached")
require.Nil(t, leaf.NextSibling(), "replaced leaf has no stale next")
require.Nil(t, leaf.PrevSibling(), "replaced leaf has no stale prev")
requireNoCycle(t, root)
requireNoCycle(t, src)
})
t.Run("non-mutable replacement splices in", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
leaf := tc.new(t, doc)
require.NoError(t, root.AddChild(leaf), "leaf starts under root")
ns := helium.NewNamespace("p", "urn:example")
nsw := helium.NewNamespaceNodeWrapper(ns, nil)
// A non-MutableNode replacement must not panic on a force-cast and
// must take leaf's position under root.
require.NoError(t, leaf.Replace(nsw), "non-mutable replacement succeeds")
require.Equal(t, helium.Node(nsw), root.FirstChild(), "wrapper took leaf's position")
require.Equal(t, helium.Node(root), nsw.Parent(), "wrapper parent is root")
require.Nil(t, leaf.Parent(), "replaced leaf is detached")
requireNoCycle(t, root)
})
})
}
// the leaf-node AddChild/AddSibling
// overrides which run a content-merge fast path (Text.AddChild, Text.AddSibling,
// Comment.AddChild, ProcessingInstruction.AddChild) reject a nil operand with
// ErrNilNode instead of panicking,
// and leave the linked leaf untouched. Both a literal nil interface and a
// matching typed-nil concrete pointer (Go's interface nil trap) are exercised,
// since the overrides run a type assertion / debug log / preflight before the
// guard would otherwise be reached.
{
cases := []struct {
name string
// op runs the override under test against the supplied operand.
op func(leaf helium.MutableNode, cur helium.Node) error
// typedNil returns a matching typed-nil operand wrapped in a non-nil Node
// interface, to exercise the same fast path's interface-nil trap.
typedNil func() helium.Node
// newLeaf builds the linked leaf that receives the call.
newLeaf leafCtor
}{
{
name: "Text.AddChild",
op: func(leaf helium.MutableNode, cur helium.Node) error { return leaf.AddChild(cur) },
typedNil: func() helium.Node {
var tn *helium.Text
return tn
},
newLeaf: func(t *testing.T, doc *helium.Document) helium.MutableNode {
return mustCreateText(t, doc, []byte("x"))
},
},
{
name: "Text.AddSibling",
op: func(leaf helium.MutableNode, cur helium.Node) error { return leaf.AddSibling(cur) },
typedNil: func() helium.Node {
var tn *helium.Text
return tn
},
newLeaf: func(t *testing.T, doc *helium.Document) helium.MutableNode {
return mustCreateText(t, doc, []byte("x"))
},
},
{
name: "Comment.AddChild",
op: func(leaf helium.MutableNode, cur helium.Node) error { return leaf.AddChild(cur) },
typedNil: func() helium.Node {
var cn *helium.Comment
return cn
},
newLeaf: func(t *testing.T, doc *helium.Document) helium.MutableNode {
return mustCreateComment(t, doc, []byte("x"))
},
},
{
name: "PI.AddChild",
op: func(leaf helium.MutableNode, cur helium.Node) error { return leaf.AddChild(cur) },
typedNil: func() helium.Node {
// A typed-nil *Text would otherwise reach the Text/CDATA
// content-merge fast path and panic on cur.Type().
var tn *helium.Text
return tn
},
newLeaf: func(t *testing.T, doc *helium.Document) helium.MutableNode {
return mustCreatePI(t, doc)
},
},
}
for _, tc := range cases {
t.Run("fast-path nil operand "+tc.name, func(t *testing.T) {
t.Parallel()
t.Run("literal nil", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
leaf := tc.newLeaf(t, doc)
require.NoError(t, root.AddChild(leaf), "leaf starts under root")
err := tc.op(leaf, nil)
require.ErrorIs(t, err, helium.ErrNilNode, "literal nil operand must return ErrNilNode")
require.Nil(t, leaf.FirstChild(), "leaf must not gain a child")
require.Nil(t, leaf.NextSibling(), "leaf must not gain a sibling")
require.Equal(t, helium.Node(leaf), root.FirstChild(), "tree must not be corrupted")
require.Equal(t, helium.Node(root), leaf.Parent(), "leaf parent must stay root")
requireNoCycle(t, root)
})
t.Run("typed nil", func(t *testing.T) {
t.Parallel()
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
leaf := tc.newLeaf(t, doc)
require.NoError(t, root.AddChild(leaf), "leaf starts under root")
err := tc.op(leaf, tc.typedNil())
require.ErrorIs(t, err, helium.ErrNilNode, "typed-nil operand must return ErrNilNode")
require.Nil(t, leaf.FirstChild(), "leaf must not gain a child")
require.Nil(t, leaf.NextSibling(), "leaf must not gain a sibling")
require.Equal(t, helium.Node(leaf), root.FirstChild(), "tree must not be corrupted")
require.Equal(t, helium.Node(root), leaf.Parent(), "leaf parent must stay root")
requireNoCycle(t, root)
})
})
}
}
// inserting an already-linked
// non-MutableNode operand (NamespaceNodeWrapper) detaches it from its old parent,
// skipping no unlink and leaving no stale link.
t.Run("AddChild with a non-mutable operand", func(t *testing.T) {
doc := helium.NewDefaultDocument()
src := mustCreateElement(t, doc, "src")
dst := mustCreateElement(t, doc, "dst")
ns := helium.NewNamespace("p", "urn:example")
nsw := helium.NewNamespaceNodeWrapper(ns, nil)
// Link the wrapper (a non-MutableNode Node) under src first.
require.NoError(t, src.AddChild(nsw), "wrapper links under src")
require.Equal(t, helium.Node(src), nsw.Parent(), "wrapper parent is src")
require.Equal(t, helium.Node(nsw), src.FirstChild(), "src firstChild is wrapper")
// Moving the wrapper into dst must auto-unlink it from src. Previously the
// preflight skipped the unlink for non-MutableNode operands, leaving src
// still pointing at the wrapper.
require.NoError(t, dst.AddChild(nsw), "wrapper move into dst succeeds")
require.Equal(t, helium.Node(dst), nsw.Parent(), "wrapper parent is now dst")
require.Equal(t, helium.Node(nsw), dst.FirstChild(), "dst firstChild is wrapper")
require.Nil(t, src.FirstChild(), "src no longer holds the wrapper")
require.Nil(t, src.LastChild(), "src no longer holds the wrapper")
require.Nil(t, nsw.PrevSibling(), "wrapper has no stale prev")
require.Nil(t, nsw.NextSibling(), "wrapper has no stale next")
requireNoCycle(t, dst)
requireNoCycle(t, src)
})
// AddSibling auto-unlinks an
// already-linked non-MutableNode operand (NamespaceNodeWrapper) from its old
// parent instead of silently skipping the unlink.
t.Run("AddSibling with a non-mutable operand", func(t *testing.T) {
doc := helium.NewDefaultDocument()
src := mustCreateElement(t, doc, "src")
dst := mustCreateElement(t, doc, "dst")
anchor := mustCreateElement(t, doc, "anchor")
ns := helium.NewNamespace("p", "urn:example")
nsw := helium.NewNamespaceNodeWrapper(ns, nil)
require.NoError(t, dst.AddChild(anchor), "anchor starts under dst")
require.NoError(t, src.AddChild(nsw), "wrapper starts under src")
require.NoError(t, anchor.AddSibling(nsw), "moving wrapper as anchor's sibling succeeds")
require.Equal(t, helium.Node(dst), nsw.Parent(), "wrapper parent is now dst")
require.Equal(t, helium.Node(nsw), anchor.NextSibling(), "wrapper follows anchor")
require.Equal(t, helium.Node(anchor), nsw.PrevSibling(), "anchor precedes wrapper")
require.Equal(t, helium.Node(nsw), dst.LastChild(), "dst lastChild is wrapper")
require.Nil(t, src.FirstChild(), "src no longer holds the wrapper")
require.Nil(t, src.LastChild(), "src no longer holds the wrapper")
requireNoCycle(t, dst)
requireNoCycle(t, src)
})
// Replace splices in a non-MutableNode
// operand (NamespaceNodeWrapper) without panicking on a MutableNode force-cast
// and without leaving stale links on either the replaced node or the operand's
// old parent.
t.Run("Replace with a non-mutable operand", func(t *testing.T) {
doc := helium.NewDefaultDocument()
root := mustCreateElement(t, doc, "root")
a := mustCreateElement(t, doc, "a")
b := mustCreateElement(t, doc, "b")
require.NoError(t, root.AddChild(a), "a starts under root")