Skip to content

Commit

Permalink
Disallow replacing elements with themselves
Browse files Browse the repository at this point in the history
And add a test for this edge case

closes jhy#1843
  • Loading branch information
jdngray77 committed Sep 22, 2022
1 parent eabfcdd commit 55f8062
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/main/java/org/jsoup/helper/Validate.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ public final class Validate {

private Validate() {}

/**
* Validates that the two objects are not the same.
* @param a First object
* @param b Second object
* @param message Error message to use if the objects are the same
* @throws IllegalArgumentException if the objects are the same
*/
public static void notStrictlyEqual(Object a, Object b, String message) {
if (a == b)
throw new ValidationException(message);
}

/**
* Validates that the object is not null
* @param obj object to test
Expand Down
1 change: 1 addition & 0 deletions src/main/java/org/jsoup/nodes/Node.java
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,7 @@ void nodelistChanged() {
public void replaceWith(Node in) {
Validate.notNull(in);
Validate.notNull(parentNode);
Validate.notStrictlyEqual(this, in, "Cannot replace a node with itself");
parentNode.replaceChild(this, in);
}

Expand Down
22 changes: 22 additions & 0 deletions src/test/java/org/jsoup/nodes/NodeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.jsoup.Jsoup;
import org.jsoup.TextUtil;
import org.jsoup.helper.ValidationException;
import org.jsoup.parser.Tag;
import org.jsoup.select.NodeVisitor;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -402,4 +403,25 @@ void firstAndLastChild() {
assertNull(firstEl.firstElementChild());
assertNull(firstEl.lastElementChild());
}

@Test
void replaceWithSelf() {
// Issue 1843

Document doc = new Document("");
Element h1 = doc.body().appendElement("h1");
Element div = doc.body().appendElement("div");

assertDoesNotThrow(doc::toString);

assertThrowsExactly(ValidationException.class, () -> h1.replaceWith(h1));

assertTrue(doc.body().children().contains(h1));
assertTrue(doc.body().children().contains(div));
assertNotNull(h1.parent());
assertNotNull(div.parent());
assertDoesNotThrow(doc::toString);


}
}

0 comments on commit 55f8062

Please sign in to comment.