Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion etree.go
Original file line number Diff line number Diff line change
Expand Up @@ -886,7 +886,7 @@ func (e *Element) RemoveChild(t Token) Token {
// element's list of child tokens. The removed child token is then returned.
// If the index is out of bounds, no child is removed and nil is returned.
func (e *Element) RemoveChildAt(index int) Token {
if index >= len(e.Child) {
if index < 0 || index >= len(e.Child) {
return nil
}

Expand Down
59 changes: 59 additions & 0 deletions etree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1554,6 +1554,65 @@ func TestTokenIndexing(t *testing.T) {
checkIndexes(t, &doc.Element)
}

func TestRemoveChildAtOutOfBounds(t *testing.T) {
for _, name := range []string{"empty", "mixed"} {
t.Run(name, func(t *testing.T) {
doc := NewDocument()
root := doc.CreateElement("root")
if name == "mixed" {
root.CreateElement("child")
root.CreateCharData("text")
root.CreateCData("data")
root.CreateComment("comment")
root.CreateDirective("directive")
root.CreateProcInst("target", "instruction")
}
children := append([]Token(nil), root.Child...)
before, err := doc.WriteToString()
if err != nil {
t.Fatal(err)
}
maxInt := int(^uint(0) >> 1)
cases := []struct {
name string
index int
}{
{"negative one", -1},
{"negative several", -3},
{"minimum int", -maxInt - 1},
{"length", len(children)},
{"above length", len(children) + 1},
{"maximum int", maxInt},
}
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
defer func() {
if p := recover(); p != nil {
t.Errorf("RemoveChildAt(%d) panicked: %v", test.index, p)
}
}()
if removed := root.RemoveChildAt(test.index); removed != nil {
t.Fatalf("RemoveChildAt(%d) returned %v", test.index, removed)
}
if len(root.Child) != len(children) {
t.Fatalf("child count changed from %d to %d", len(children), len(root.Child))
}
for i, child := range children {
if root.Child[i] != child || child.Parent() != root || child.Index() != i {
t.Errorf("child %d changed identity, parent or index", i)
}
}
after, err := doc.WriteToString()
if err != nil {
t.Fatal(err)
}
checkStrEq(t, after, before)
})
}
})
}
}

func TestSetText(t *testing.T) {
doc := NewDocument()
root := doc.CreateElement("root")
Expand Down