function
stringlengths
61
9.1k
testmethod
stringlengths
42
143
location_fixed
stringlengths
43
98
end_buggy
int64
10
12k
location
stringlengths
43
98
function_name
stringlengths
4
73
source_buggy
stringlengths
655
442k
prompt_complete
stringlengths
433
4.3k
end_fixed
int64
10
12k
comment
stringlengths
0
763
bug_id
stringlengths
1
3
start_fixed
int64
7
12k
location_buggy
stringlengths
43
98
source_dir
stringclasses
5 values
prompt_chat
stringlengths
420
3.86k
start_buggy
int64
7
12k
classes_modified
sequence
task_id
stringlengths
64
64
function_signature
stringlengths
22
150
prompt_complete_without_signature
stringlengths
404
4.23k
project
stringclasses
17 values
indent
stringclasses
4 values
source_fixed
stringlengths
655
442k
@Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document(""); Element body = doc.appendElement("body"); body.appendElement("div1"); body.appendElement("div2"); final Element div3 = body.appendElement("div3"); div3.text("Check"); final Element div4 = body.appendElement("div4"); ArrayList<Element> toMove = new ArrayList<Element>(); toMove.add(div3); toMove.add(div4); body.insertChildren(0, toMove); String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); }
org.jsoup.nodes.ElementTest::appendMustCorrectlyMoveChildrenInsideOneParentElement
src/test/java/org/jsoup/nodes/ElementTest.java
879
src/test/java/org/jsoup/nodes/ElementTest.java
appendMustCorrectlyMoveChildrenInsideOneParentElement
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import java.util.*; import static org.junit.Assert.*; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetSiblingsWithDuplicateContent() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("this", p.nextElementSibling().nextElementSibling().text()); assertEquals("is", p.nextElementSibling().nextElementSibling().nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testElementSiblingIndexSameContent() { Document doc = Jsoup.parse("<div><p>One</p>...<p>One</p>...<p>One</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class=' mellow yellow '>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); classes = doc.classNames(); assertEquals(0, classes.size()); assertFalse(doc.hasClass("mellow")); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("class", "second").text("now"); assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><p class=\"second\">now</p></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); List<Attribute> attributes = div.attributes().asList(); assertEquals("There should be one attribute", 1, attributes.size()); assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnAddNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(null); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnPrependNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText(null); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testSetHtmlTitle() { Document doc = Jsoup.parse("<html><head id=2><title id=1></title></head></html>"); Element title = doc.getElementById("1"); title.html("good"); assertEquals("good", title.html()); title.html("<i>bad</i>"); assertEquals("&lt;i&gt;bad&lt;/i&gt;", title.html()); Element head = doc.getElementById("2"); head.html("<title><i>bad</i></title>"); assertEquals("<title>&lt;i&gt;bad&lt;/i&gt;</title>", head.html()); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\">", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\">", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<Node>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4", ""); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testCssPath() { Document doc = Jsoup.parse("<div id=\"id1\">A</div><div>B</div><div class=\"c1 c2\">C</div>"); Element divA = doc.select("div").get(0); Element divB = doc.select("div").get(1); Element divC = doc.select("div").get(2); assertEquals(divA.cssSelector(), "#id1"); assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)"); assertEquals(divC.cssSelector(), "html > body > div.c1.c2"); assertTrue(divA == doc.select(divA.cssSelector()).first()); assertTrue(divB == doc.select(divB.cssSelector()).first()); assertTrue(divC == doc.select(divC.cssSelector()).first()); } @Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length==2); assertEquals("c1", arr1[0]); assertEquals("c2", arr1[1]); // Changes to the set should not be reflected in the Elements getters set1.add("c3"); assertTrue(2==div.classNames().size()); assertEquals("c1 c2", div.className()); // Update the class names to a fresh set final Set<String> newSet = new LinkedHashSet<String>(3); newSet.addAll(set1); newSet.add("c3"); div.classNames(newSet); assertEquals("c1 c2 c3", div.className()); final Set<String> set2 = div.classNames(); final Object[] arr2 = set2.toArray(); assertTrue(arr2.length==3); assertEquals("c1", arr2[0]); assertEquals("c2", arr2[1]); assertEquals("c3", arr2[2]); } @Test public void testHashAndEquals() { String doc1 = "<div id=1><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>" + "<div id=2><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>"; Document doc = Jsoup.parse(doc1); Elements els = doc.select("p"); /* for (Element el : els) { System.out.println(el.hashCode() + " - " + el.outerHtml()); } 0 1534787905 - <p class="one">One</p> 1 1534787905 - <p class="one">One</p> 2 1539683239 - <p class="one">Two</p> 3 1535455211 - <p class="two">One</p> 4 1534787905 - <p class="one">One</p> 5 1534787905 - <p class="one">One</p> 6 1539683239 - <p class="one">Two</p> 7 1535455211 - <p class="two">One</p> */ assertEquals(8, els.size()); Element e0 = els.get(0); Element e1 = els.get(1); Element e2 = els.get(2); Element e3 = els.get(3); Element e4 = els.get(4); Element e5 = els.get(5); Element e6 = els.get(6); Element e7 = els.get(7); assertEquals(e0, e1); assertEquals(e0, e4); assertEquals(e0, e5); assertFalse(e0.equals(e2)); assertFalse(e0.equals(e3)); assertFalse(e0.equals(e6)); assertFalse(e0.equals(e7)); assertEquals(e0.hashCode(), e1.hashCode()); assertEquals(e0.hashCode(), e4.hashCode()); assertEquals(e0.hashCode(), e5.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); assertFalse(e0.hashCode() == (e7).hashCode()); } @Test public void testRelativeUrls() { String html = "<body><a href='./one.html'>One</a> <a href='two.html'>two</a> <a href='../three.html'>Three</a> <a href='//example2.com/four/'>Four</a> <a href='https://example2.com/five/'>Five</a>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("a"); assertEquals("http://example.com/bar/one.html", els.get(0).absUrl("href")); assertEquals("http://example.com/bar/two.html", els.get(1).absUrl("href")); assertEquals("http://example.com/three.html", els.get(2).absUrl("href")); assertEquals("http://example2.com/four/", els.get(3).absUrl("href")); assertEquals("https://example2.com/five/", els.get(4).absUrl("href")); } @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document(""); Element body = doc.appendElement("body"); body.appendElement("div1"); body.appendElement("div2"); final Element div3 = body.appendElement("div3"); div3.text("Check"); final Element div4 = body.appendElement("div4"); ArrayList<Element> toMove = new ArrayList<Element>(); toMove.add(div3); toMove.add(div4); body.insertChildren(0, toMove); String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); } }
// You are a professional Java test case writer, please create a test case named `appendMustCorrectlyMoveChildrenInsideOneParentElement` for the issue `Jsoup-689`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-689 // // ## Issue-Title: // Bug in Element.insertChildren() // // ## Issue-Description: // When using org.jsoup.nodes.Element.insertChildren(int, Collection<? extends Node>) to move (more than one!) child-elements from one parent-element to the same parent, but different index then it produces wrong results. // // // The problem is that the first Element's 'move' leaves the siblingIndex unchanged and then the second 'move' removes a wrong element and produces some crap. Maybe calling reindexChildren() inside the loop in addChildren() fixes this. // // Version 1.8.3. // // Workaround: call remove() on the elements before passing them to insertChildren() // // // Easy Test Case: // // // // ``` // @Test // public void mustCorrectlyMoveChildrenInsideOneParentElement() { // // Document doc = new Document( "" ); // Element body = doc.appendElement( "body" ); // body.appendElement( "div1" ); // body.appendElement( "div2" ); // Element div3 = body.appendElement( "div3" ); // Element div4 = body.appendElement( "div4" ); // // ArrayList<Element> toMove = new ArrayList<Element>() { // { // add( div3 ); // add( div4 ); // } // }; // // body.insertChildren( 0, toMove ); // // String result = doc.toString().replaceAll( "\\s+", "" ); // assertEquals( "<body><div3></div3><div4></div4><div1></div1><div2></div2></body>", result ); // // } // // ``` // // // @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() {
879
49
860
src/test/java/org/jsoup/nodes/ElementTest.java
src/test/java
```markdown ## Issue-ID: Jsoup-689 ## Issue-Title: Bug in Element.insertChildren() ## Issue-Description: When using org.jsoup.nodes.Element.insertChildren(int, Collection<? extends Node>) to move (more than one!) child-elements from one parent-element to the same parent, but different index then it produces wrong results. The problem is that the first Element's 'move' leaves the siblingIndex unchanged and then the second 'move' removes a wrong element and produces some crap. Maybe calling reindexChildren() inside the loop in addChildren() fixes this. Version 1.8.3. Workaround: call remove() on the elements before passing them to insertChildren() Easy Test Case: ``` @Test public void mustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document( "" ); Element body = doc.appendElement( "body" ); body.appendElement( "div1" ); body.appendElement( "div2" ); Element div3 = body.appendElement( "div3" ); Element div4 = body.appendElement( "div4" ); ArrayList<Element> toMove = new ArrayList<Element>() { { add( div3 ); add( div4 ); } }; body.insertChildren( 0, toMove ); String result = doc.toString().replaceAll( "\\s+", "" ); assertEquals( "<body><div3></div3><div4></div4><div1></div1><div2></div2></body>", result ); } ``` ``` You are a professional Java test case writer, please create a test case named `appendMustCorrectlyMoveChildrenInsideOneParentElement` for the issue `Jsoup-689`, utilizing the provided issue report information and the following function signature. ```java @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { ```
860
[ "org.jsoup.nodes.Node" ]
021c78a789592d6afbc95eeb73663d951c5109c229ab25610349c0ffef564ce1
@Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement()
// You are a professional Java test case writer, please create a test case named `appendMustCorrectlyMoveChildrenInsideOneParentElement` for the issue `Jsoup-689`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Jsoup-689 // // ## Issue-Title: // Bug in Element.insertChildren() // // ## Issue-Description: // When using org.jsoup.nodes.Element.insertChildren(int, Collection<? extends Node>) to move (more than one!) child-elements from one parent-element to the same parent, but different index then it produces wrong results. // // // The problem is that the first Element's 'move' leaves the siblingIndex unchanged and then the second 'move' removes a wrong element and produces some crap. Maybe calling reindexChildren() inside the loop in addChildren() fixes this. // // Version 1.8.3. // // Workaround: call remove() on the elements before passing them to insertChildren() // // // Easy Test Case: // // // // ``` // @Test // public void mustCorrectlyMoveChildrenInsideOneParentElement() { // // Document doc = new Document( "" ); // Element body = doc.appendElement( "body" ); // body.appendElement( "div1" ); // body.appendElement( "div2" ); // Element div3 = body.appendElement( "div3" ); // Element div4 = body.appendElement( "div4" ); // // ArrayList<Element> toMove = new ArrayList<Element>() { // { // add( div3 ); // add( div4 ); // } // }; // // body.insertChildren( 0, toMove ); // // String result = doc.toString().replaceAll( "\\s+", "" ); // assertEquals( "<body><div3></div3><div4></div4><div1></div1><div2></div2></body>", result ); // // } // // ``` // // //
Jsoup
package org.jsoup.nodes; import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.junit.Test; import java.util.*; import static org.junit.Assert.*; /** * Tests for Element (DOM stuff mostly). * * @author Jonathan Hedley */ public class ElementTest { private String reference = "<div id=div1><p>Hello</p><p>Another <b>element</b></p><div id=div2><img src=foo.png></div></div>"; @Test public void getElementsByTagName() { Document doc = Jsoup.parse(reference); List<Element> divs = doc.getElementsByTag("div"); assertEquals(2, divs.size()); assertEquals("div1", divs.get(0).id()); assertEquals("div2", divs.get(1).id()); List<Element> ps = doc.getElementsByTag("p"); assertEquals(2, ps.size()); assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); List<Element> ps2 = doc.getElementsByTag("P"); assertEquals(ps, ps2); List<Element> imgs = doc.getElementsByTag("img"); assertEquals("foo.png", imgs.get(0).attr("src")); List<Element> empty = doc.getElementsByTag("wtf"); assertEquals(0, empty.size()); } @Test public void getNamespacedElementsByTag() { Document doc = Jsoup.parse("<div><abc:def id=1>Hello</abc:def></div>"); Elements els = doc.getElementsByTag("abc:def"); assertEquals(1, els.size()); assertEquals("1", els.first().id()); assertEquals("abc:def", els.first().tagName()); } @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); // not the span Element span = div2.child(0).getElementById("2"); // called from <p> context should be span assertEquals("span", span.tagName()); } @Test public void testGetText() { Document doc = Jsoup.parse(reference); assertEquals("Hello Another element", doc.text()); assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); } @Test public void testGetChildText() { Document doc = Jsoup.parse("<p>Hello <b>there</b> now"); Element p = doc.select("p").first(); assertEquals("Hello there now", p.text()); assertEquals("Hello now", p.ownText()); } @Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre> What's \n\n that?</pre>"; Document doc = Jsoup.parse(h); assertEquals("Hello there. What's \n\n that?", doc.text()); } @Test public void testKeepsPreTextInCode() { String h = "<pre><code>code\n\ncode</code></pre>"; Document doc = Jsoup.parse(h); assertEquals("code\n\ncode", doc.text()); assertEquals("<pre><code>code\n\ncode</code></pre>", doc.body().html()); } @Test public void testBrHasSpace() { Document doc = Jsoup.parse("<p>Hello<br>there</p>"); assertEquals("Hello there", doc.text()); assertEquals("Hello there", doc.select("p").first().ownText()); doc = Jsoup.parse("<p>Hello <br> there</p>"); assertEquals("Hello there", doc.text()); } @Test public void testGetSiblings() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetSiblingsWithDuplicateContent() { Document doc = Jsoup.parse("<div><p>Hello<p id=1>there<p>this<p>this<p>is<p>an<p id=last>element</div>"); Element p = doc.getElementById("1"); assertEquals("there", p.text()); assertEquals("Hello", p.previousElementSibling().text()); assertEquals("this", p.nextElementSibling().text()); assertEquals("this", p.nextElementSibling().nextElementSibling().text()); assertEquals("is", p.nextElementSibling().nextElementSibling().nextElementSibling().text()); assertEquals("Hello", p.firstElementSibling().text()); assertEquals("element", p.lastElementSibling().text()); } @Test public void testGetParents() { Document doc = Jsoup.parse("<div><p>Hello <span>there</span></div>"); Element span = doc.select("span").first(); Elements parents = span.parents(); assertEquals(4, parents.size()); assertEquals("p", parents.get(0).tagName()); assertEquals("div", parents.get(1).tagName()); assertEquals("body", parents.get(2).tagName()); assertEquals("html", parents.get(3).tagName()); } @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testElementSiblingIndexSameContent() { Document doc = Jsoup.parse("<div><p>One</p>...<p>One</p>...<p>One</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); } @Test public void testGetElementsWithClass() { Document doc = Jsoup.parse("<div class='mellow yellow'><span class=mellow>Hello <b class='yellow'>Yellow!</b></span><p>Empty</p></div>"); List<Element> els = doc.getElementsByClass("mellow"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("span", els.get(1).tagName()); List<Element> els2 = doc.getElementsByClass("yellow"); assertEquals(2, els2.size()); assertEquals("div", els2.get(0).tagName()); assertEquals("b", els2.get(1).tagName()); List<Element> none = doc.getElementsByClass("solo"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttribute() { Document doc = Jsoup.parse("<div style='bold'><p title=qux><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttribute("style"); assertEquals(2, els.size()); assertEquals("div", els.get(0).tagName()); assertEquals("b", els.get(1).tagName()); List<Element> none = doc.getElementsByAttribute("class"); assertEquals(0, none.size()); } @Test public void testGetElementsWithAttributeDash() { Document doc = Jsoup.parse("<meta http-equiv=content-type value=utf8 id=1> <meta name=foo content=bar id=2> <div http-equiv=content-type value=utf8 id=3>"); Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); assertEquals(1, meta.size()); assertEquals("1", meta.first().id()); } @Test public void testGetElementsWithAttributeValue() { Document doc = Jsoup.parse("<div style='bold'><p><p><b style></b></p></div>"); List<Element> els = doc.getElementsByAttributeValue("style", "bold"); assertEquals(1, els.size()); assertEquals("div", els.get(0).tagName()); List<Element> none = doc.getElementsByAttributeValue("style", "none"); assertEquals(0, none.size()); } @Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class=' mellow yellow '>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); classes = doc.classNames(); assertEquals(0, classes.size()); assertFalse(doc.hasClass("mellow")); } @Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); } @Test public void testOuterHtml() { Document doc = Jsoup.parse("<div title='Tags &amp;c.'><img src=foo.png><p><!-- comment -->Hello<p>there"); assertEquals("<html><head></head><body><div title=\"Tags &amp;c.\"><img src=\"foo.png\"><p><!-- comment -->Hello</p><p>there</p></div></body></html>", TextUtil.stripNewlines(doc.outerHtml())); } @Test public void testInnerHtml() { Document doc = Jsoup.parse("<div>\n <p>Hello</p> </div>"); assertEquals("<p>Hello</p>", doc.getElementsByTag("div").get(0).html()); } @Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testFormatOutline() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); doc.outputSettings().outline(true); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>\n Hello \n <span>\n jsoup \n <span>users</span>\n </span>\n </p>\n <p>Good.</p>\n </div>\n </body>\n</html>", doc.html()); } @Test public void testSetIndent() { Document doc = Jsoup.parse("<div><p>Hello\nthere</p></div>"); doc.outputSettings().indentAmount(0); assertEquals("<html>\n<head></head>\n<body>\n<div>\n<p>Hello there</p>\n</div>\n</body>\n</html>", doc.html()); } @Test public void testNotPretty() { Document doc = Jsoup.parse("<div> \n<p>Hello\n there\n</p></div>"); doc.outputSettings().prettyPrint(false); assertEquals("<html><head></head><body><div> \n<p>Hello\n there\n</p></div></body></html>", doc.html()); Element div = doc.select("div").first(); assertEquals(" \n<p>Hello\n there\n</p>", div.html()); } @Test public void testEmptyElementFormatHtml() { // don't put newlines into empty blocks Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testNoIndentOnScriptAndStyle() { // don't newline+indent closing </script> and </style> tags Document doc = Jsoup.parse("<script>one\ntwo</script>\n<style>three\nfour</style>"); assertEquals("<script>one\ntwo</script> \n<style>three\nfour</style>", doc.head().html()); } @Test public void testContainerOutput() { Document doc = Jsoup.parse("<title>Hello there</title> <div><p>Hello</p><p>there</p></div> <div>Another</div>"); assertEquals("<title>Hello there</title>", doc.select("title").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div>", doc.select("div").first().outerHtml()); assertEquals("<div>\n <p>Hello</p>\n <p>there</p>\n</div> \n<div>\n Another\n</div>", doc.select("body").first().html()); } @Test public void testSetText() { String h = "<div id=1>Hello <p>there <b>now</b></p></div>"; Document doc = Jsoup.parse(h); assertEquals("Hello there now", doc.text()); // need to sort out node whitespace assertEquals("there now", doc.select("p").get(0).text()); Element div = doc.getElementById("1").text("Gone"); assertEquals("Gone", div.text()); assertEquals(0, doc.select("p").size()); } @Test public void testAddNewElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendElement("p").text("there"); div.appendElement("P").attr("class", "second").text("now"); assertEquals("<html><head></head><body><div id=\"1\"><p>Hello</p><p>there</p><p class=\"second\">now</p></div></body></html>", TextUtil.stripNewlines(doc.html())); // check sibling index (with short circuit on reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testAddBooleanAttribute() { Element div = new Element(Tag.valueOf("div"), ""); div.attr("true", true); div.attr("false", "value"); div.attr("false", false); assertTrue(div.hasAttr("true")); assertEquals("", div.attr("true")); List<Attribute> attributes = div.attributes().asList(); assertEquals("There should be one attribute", 1, attributes.size()); assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); assertFalse(div.hasAttr("false")); assertEquals("<div true></div>", div.outerHtml()); } @Test public void testAppendRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.append("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testPrependRowToTable() { Document doc = Jsoup.parse("<table><tr><td>1</td></tr></table>"); Element table = doc.select("tbody").first(); table.prepend("<tr><td>2</td></tr>"); assertEquals("<table><tbody><tr><td>2</td></tr><tr><td>1</td></tr></tbody></table>", TextUtil.stripNewlines(doc.body().html())); // check sibling index (reindexChildren): Elements ps = doc.select("tr"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); } @Test public void testAddNewText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(" there & now >"); assertEquals("<p>Hello</p> there &amp; now &gt;", TextUtil.stripNewlines(div.html())); } @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnAddNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.appendText(null); } @Test(expected = IllegalArgumentException.class) public void testThrowsOnPrependNullText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText(null); } @Test public void testAddNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.append("<p>there</p><p>now</p>"); assertEquals("<p>Hello</p><p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); // check sibling index (no reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testPrependNewHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prepend("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p><p>Hello</p>", TextUtil.stripNewlines(div.html())); // check sibling index (reindexChildren): Elements ps = doc.select("p"); for (int i = 0; i < ps.size(); i++) { assertEquals(i, ps.get(i).siblingIndex); } } @Test public void testSetHtml() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.html("<p>there</p><p>now</p>"); assertEquals("<p>there</p><p>now</p>", TextUtil.stripNewlines(div.html())); } @Test public void testSetHtmlTitle() { Document doc = Jsoup.parse("<html><head id=2><title id=1></title></head></html>"); Element title = doc.getElementById("1"); title.html("good"); assertEquals("good", title.html()); title.html("<i>bad</i>"); assertEquals("&lt;i&gt;bad&lt;/i&gt;", title.html()); Element head = doc.getElementById("2"); head.html("<title><i>bad</i></title>"); assertEquals("<title>&lt;i&gt;bad&lt;/i&gt;</title>", head.html()); } @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); } @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testWrapWithRemainder() { Document doc = Jsoup.parse("<div><p>Hello</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div><p>There!</p>"); assertEquals("<div><div class=\"head\"><p>Hello</p><p>There!</p></div></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); } @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); // size, get, set, add, remove assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); // data- is not a data attribute Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); } @Test public void parentlessToString() { Document doc = Jsoup.parse("<img src='foo'>"); Element img = doc.select("img").first(); assertEquals("<img src=\"foo\">", img.toString()); img.remove(); // lost its parent assertEquals("<img src=\"foo\">", img.toString()); } @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); // should be orphaned assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); // not modified doc.body().appendChild(clone); // adopt assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); } @Test public void testTagNameSet() { Document doc = Jsoup.parse("<div><i>Hello</i>"); doc.select("i").first().tagName("em"); assertEquals(0, doc.select("i").size()); assertEquals(1, doc.select("em").size()); assertEquals("<em>Hello</em>", doc.select("div").first().html()); } @Test public void testHtmlContainsOuter() { Document doc = Jsoup.parse("<title>Check</title> <div>Hello there</div>"); doc.outputSettings().indentAmount(0); assertTrue(doc.html().contains(doc.select("title").outerHtml())); assertTrue(doc.html().contains(doc.select("div").outerHtml())); } @Test public void testGetTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); List<TextNode> textNodes = doc.select("p").first().textNodes(); assertEquals(3, textNodes.size()); assertEquals("One ", textNodes.get(0).text()); assertEquals(" Three ", textNodes.get(1).text()); assertEquals(" Four", textNodes.get(2).text()); assertEquals(0, doc.select("br").first().textNodes().size()); } @Test public void testManipulateTextNodes() { Document doc = Jsoup.parse("<p>One <span>Two</span> Three <br> Four</p>"); Element p = doc.select("p").first(); List<TextNode> textNodes = p.textNodes(); textNodes.get(1).text(" three-more "); textNodes.get(2).splitText(3).text("-ur"); assertEquals("One Two three-more Fo-ur", p.text()); assertEquals("One three-more Fo-ur", p.ownText()); assertEquals(4, p.textNodes().size()); // grew because of split } @Test public void testGetDataNodes() { Document doc = Jsoup.parse("<script>One Two</script> <style>Three Four</style> <p>Fix Six</p>"); Element script = doc.select("script").first(); Element style = doc.select("style").first(); Element p = doc.select("p").first(); List<DataNode> scriptData = script.dataNodes(); assertEquals(1, scriptData.size()); assertEquals("One Two", scriptData.get(0).getWholeData()); List<DataNode> styleData = style.dataNodes(); assertEquals(1, styleData.size()); assertEquals("Three Four", styleData.get(0).getWholeData()); List<DataNode> pData = p.dataNodes(); assertEquals(0, pData.size()); } @Test public void elementIsNotASiblingOfItself() { Document doc = Jsoup.parse("<div><p>One<p>Two<p>Three</div>"); Element p2 = doc.select("p").get(1); assertEquals("Two", p2.text()); Elements els = p2.siblingElements(); assertEquals(2, els.size()); assertEquals("<p>One</p>", els.get(0).outerHtml()); assertEquals("<p>Three</p>", els.get(1).outerHtml()); } @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { Document doc = Jsoup.parse("<div><p>One</p><p>Two</p></div>"); Element div = doc.select("div").first(); assertEquals(2, div.children().size()); assertEquals("One", div.child(0).text()); try { div.child(3); fail("Should throw index out of bounds"); } catch (IndexOutOfBoundsException e) {} } @Test public void moveByAppend() { // test for https://github.com/jhy/jsoup/issues/239 // can empty an element and append its children to another element Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); assertEquals(4, div1.childNodeSize()); List<Node> children = div1.childNodes(); assertEquals(4, children.size()); div2.insertChildren(0, children); assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now assertEquals(0, div1.childNodeSize()); assertEquals(4, div2.childNodeSize()); assertEquals("<div id=\"1\"></div>\n<div id=\"2\">\n Text \n <p>One</p> Text \n <p>Two</p>\n</div>", doc.body().html()); } @Test public void insertChildrenArgumentValidation() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); List<Node> children = div1.childNodes(); try { div2.insertChildren(6, children); fail(); } catch (IllegalArgumentException e) {} try { div2.insertChildren(-5, children); fail(); } catch (IllegalArgumentException e) { } try { div2.insertChildren(0, null); fail(); } catch (IllegalArgumentException e) { } } @Test public void insertChildrenAtPosition() { Document doc = Jsoup.parse("<div id=1>Text1 <p>One</p> Text2 <p>Two</p></div><div id=2>Text3 <p>Three</p></div>"); Element div1 = doc.select("div").get(0); Elements p1s = div1.select("p"); Element div2 = doc.select("div").get(1); assertEquals(2, div2.childNodeSize()); div2.insertChildren(-1, p1s); assertEquals(2, div1.childNodeSize()); // moved two out assertEquals(4, div2.childNodeSize()); assertEquals(3, p1s.get(1).siblingIndex()); // should be last List<Node> els = new ArrayList<Node>(); Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); TextNode tn1 = new TextNode("Text4", ""); els.add(el1); els.add(el2); els.add(tn1); assertNull(el1.parent()); div2.insertChildren(-2, els); assertEquals(div2, el1.parent()); assertEquals(7, div2.childNodeSize()); assertEquals(3, el1.siblingIndex()); assertEquals(4, el2.siblingIndex()); assertEquals(5, tn1.siblingIndex()); } @Test public void insertChildrenAsCopy() { Document doc = Jsoup.parse("<div id=1>Text <p>One</p> Text <p>Two</p></div><div id=2></div>"); Element div1 = doc.select("div").get(0); Element div2 = doc.select("div").get(1); Elements ps = doc.select("p").clone(); ps.first().text("One cloned"); div2.insertChildren(-1, ps); assertEquals(4, div1.childNodeSize()); // not moved -- cloned assertEquals(2, div2.childNodeSize()); assertEquals("<div id=\"1\">Text <p>One</p> Text <p>Two</p></div><div id=\"2\"><p>One cloned</p><p>Two</p></div>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testCssPath() { Document doc = Jsoup.parse("<div id=\"id1\">A</div><div>B</div><div class=\"c1 c2\">C</div>"); Element divA = doc.select("div").get(0); Element divB = doc.select("div").get(1); Element divC = doc.select("div").get(2); assertEquals(divA.cssSelector(), "#id1"); assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)"); assertEquals(divC.cssSelector(), "html > body > div.c1.c2"); assertTrue(divA == doc.select(divA.cssSelector()).first()); assertTrue(divB == doc.select(divB.cssSelector()).first()); assertTrue(divC == doc.select(divC.cssSelector()).first()); } @Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length==2); assertEquals("c1", arr1[0]); assertEquals("c2", arr1[1]); // Changes to the set should not be reflected in the Elements getters set1.add("c3"); assertTrue(2==div.classNames().size()); assertEquals("c1 c2", div.className()); // Update the class names to a fresh set final Set<String> newSet = new LinkedHashSet<String>(3); newSet.addAll(set1); newSet.add("c3"); div.classNames(newSet); assertEquals("c1 c2 c3", div.className()); final Set<String> set2 = div.classNames(); final Object[] arr2 = set2.toArray(); assertTrue(arr2.length==3); assertEquals("c1", arr2[0]); assertEquals("c2", arr2[1]); assertEquals("c3", arr2[2]); } @Test public void testHashAndEquals() { String doc1 = "<div id=1><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>" + "<div id=2><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>"; Document doc = Jsoup.parse(doc1); Elements els = doc.select("p"); /* for (Element el : els) { System.out.println(el.hashCode() + " - " + el.outerHtml()); } 0 1534787905 - <p class="one">One</p> 1 1534787905 - <p class="one">One</p> 2 1539683239 - <p class="one">Two</p> 3 1535455211 - <p class="two">One</p> 4 1534787905 - <p class="one">One</p> 5 1534787905 - <p class="one">One</p> 6 1539683239 - <p class="one">Two</p> 7 1535455211 - <p class="two">One</p> */ assertEquals(8, els.size()); Element e0 = els.get(0); Element e1 = els.get(1); Element e2 = els.get(2); Element e3 = els.get(3); Element e4 = els.get(4); Element e5 = els.get(5); Element e6 = els.get(6); Element e7 = els.get(7); assertEquals(e0, e1); assertEquals(e0, e4); assertEquals(e0, e5); assertFalse(e0.equals(e2)); assertFalse(e0.equals(e3)); assertFalse(e0.equals(e6)); assertFalse(e0.equals(e7)); assertEquals(e0.hashCode(), e1.hashCode()); assertEquals(e0.hashCode(), e4.hashCode()); assertEquals(e0.hashCode(), e5.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); assertFalse(e0.hashCode() == (e7).hashCode()); } @Test public void testRelativeUrls() { String html = "<body><a href='./one.html'>One</a> <a href='two.html'>two</a> <a href='../three.html'>Three</a> <a href='//example2.com/four/'>Four</a> <a href='https://example2.com/five/'>Five</a>"; Document doc = Jsoup.parse(html, "http://example.com/bar/"); Elements els = doc.select("a"); assertEquals("http://example.com/bar/one.html", els.get(0).absUrl("href")); assertEquals("http://example.com/bar/two.html", els.get(1).absUrl("href")); assertEquals("http://example.com/three.html", els.get(2).absUrl("href")); assertEquals("http://example2.com/four/", els.get(3).absUrl("href")); assertEquals("https://example2.com/five/", els.get(4).absUrl("href")); } @Test public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { Document doc = new Document(""); Element body = doc.appendElement("body"); body.appendElement("div1"); body.appendElement("div2"); final Element div3 = body.appendElement("div3"); div3.text("Check"); final Element div4 = body.appendElement("div4"); ArrayList<Element> toMove = new ArrayList<Element>(); toMove.add(div3); toMove.add(div4); body.insertChildren(0, toMove); String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); } }
@Test public void testEscapeNull1() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\"); } assertEquals("\\", sw.toString()); }
org.apache.commons.csv.CSVPrinterTest::testEscapeNull1
src/test/java/org/apache/commons/csv/CSVPrinterTest.java
346
src/test/java/org/apache/commons/csv/CSVPrinterTest.java
testEscapeNull1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; import static org.apache.commons.csv.Constants.CR; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Random; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * * * @version $Id$ */ public class CSVPrinterTest { private static final char DQUOTE_CHAR = '"'; private static final char BACKSLASH_CH = '\\'; private static final char QUOTE_CH = '\''; private static final int ITERATIONS_FOR_RANDOM_TEST = 50000; private static String printable(final String s) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { final char ch = s.charAt(i); if (ch <= ' ' || ch >= 128) { sb.append("(").append((int) ch).append(")"); } else { sb.append(ch); } } return sb.toString(); } private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); private void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = generateLines(nLines, nCol); final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[]) lines[i]); } printer.flush(); } final String result = sw.toString(); // System.out.println("### :" + printable(result)); try (final CSVParser parser = CSVParser.parse(result, format)) { final List<CSVRecord> parseResult = parser.getRecords(); final String[][] expected = lines.clone(); for (int i = 0; i < expected.length; i++) { expected[i] = expectNulls(expected[i], format); } Utils.compare("Printer output :" + printable(result), expected, parseResult); } } private void doRandom(final CSVFormat format, final int iter) throws Exception { for (int i = 0; i < iter; i++) { doOneRandom(format); } } /** * Converts an input CSV array into expected output values WRT NULLs. NULL strings are converted to null values * because the parser will convert these strings to null. */ private <T> T[] expectNulls(final T[] original, final CSVFormat csvFormat) { final T[] fixed = original.clone(); for (int i = 0; i < fixed.length; i++) { if (Objects.equals(csvFormat.getNullString(), fixed[i])) { fixed[i] = null; } } return fixed; } private Connection geH2Connection() throws SQLException, ClassNotFoundException { Class.forName("org.h2.Driver"); return DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); } private String[][] generateLines(final int nLines, final int nCol) { final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } return lines; } private CSVPrinter printWithHeaderComments(final StringWriter sw, final Date now, final CSVFormat baseFormat) throws IOException { CSVFormat format = baseFormat; // Use withHeaderComments first to test CSV-145 format = format.withHeaderComments("Generated by Apache Commons CSV 1.1", now); format = format.withCommentMarker('#'); format = format.withHeader("Col1", "Col2"); final CSVPrinter csvPrinter = format.print(sw); csvPrinter.printRecord("A", "B"); csvPrinter.printRecord("C", "D"); csvPrinter.close(); return csvPrinter; } private String randStr() { final Random r = new Random(); final int sz = r.nextInt(20); // sz = r.nextInt(3); final char[] buf = new char[sz]; for (int i = 0; i < sz; i++) { // stick in special chars with greater frequency char ch; final int what = r.nextInt(20); switch (what) { case 0: ch = '\r'; break; case 1: ch = '\n'; break; case 2: ch = '\t'; break; case 3: ch = '\f'; break; case 4: ch = ' '; break; case 5: ch = ','; break; case 6: ch = DQUOTE_CHAR; break; case 7: ch = '\''; break; case 8: ch = BACKSLASH_CH; break; default: ch = (char) r.nextInt(300); break; // default: ch = 'a'; break; } buf[i] = ch; } return new String(buf); } private void setUpTable(final Connection connection) throws SQLException { try (final Statement statement = connection.createStatement()) { statement.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); statement.execute("insert into TEST values(1, 'r1')"); statement.execute("insert into TEST values(2, 'r2')"); } } @Test public void testDelimeterQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("'a,b,c',xyz", sw.toString()); } } @Test public void testDelimeterQuoteNONE() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuoteMode(QuoteMode.NONE); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a,b,c,xyz", sw.toString()); } } @Test public void testDisabledComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printComment("This is a comment"); assertEquals("", sw.toString()); } } @Test public void testEOLEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a!rb!nc,x\fy\bz", sw.toString()); } } @Test public void testEOLPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a\rb\nc,x\fy\bz", sw.toString()); } } @Test public void testEOLQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a\rb\nc"); printer.print("x\by\fz"); assertEquals("'a\rb\nc',x\by\fz", sw.toString()); } } @Test public void testEscapeBackslash1() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeBackslash2() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\r"); } assertEquals("'\\\r'", sw.toString()); } @Test public void testEscapeBackslash3() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("X\\\r"); } assertEquals("'X\\\r'", sw.toString()); } @Test public void testEscapeBackslash4() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeBackslash5() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull1() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeNull2() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\r"); } assertEquals("\"\\\r\"", sw.toString()); } @Test public void testEscapeNull3() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("X\\\r"); } assertEquals("\"X\\\r\"", sw.toString()); } @Test public void testEscapeNull4() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull5() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testExcelPrintAllArrayOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords((Object[]) new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( (Object[]) new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( Arrays.asList(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testHeader() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3"))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testHeaderCommentExcel() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.EXCEL; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1,Col2\r\nA,B\r\nC,D\r\n", sw.toString()); } } @Test public void testHeaderCommentTdf() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.TDF; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1\tCol2\r\nA\tB\r\nC\tD\r\n", sw.toString()); } } @Test public void testHeaderNotSet() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() throws Exception { final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), invalidFormat)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecords(stmt.executeQuery("select ID, NAME from TEST")); } } assertEquals("1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSet() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection();) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet).print(sw)) { printer.printRecords(resultSet); } } assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSetMetaData() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet.getMetaData()).print(sw)) { printer.printRecords(resultSet); assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } } } @Test @Ignore public void testJira135_part1() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); printer.printRecord(list); } final String expected = "\"\\\"\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part2() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\n"); printer.printRecord(list); } final String expected = "\"\\n\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part3() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135All() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); list.add("\n"); list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\"\",\"\\n\",\"\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test public void testMultiLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment\non multiple lines"); assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString()); } } @Test public void testMySqlNullOutput() throws IOException { Object[] s = new String[] { "NULL", null }; CSVFormat format = CSVFormat.MYSQL.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.NON_NUMERIC); StringWriter writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } String expected = "\"NULL\"\tNULL\n"; assertEquals(expected, writer.toString()); String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(new Object[2], record0); s = new String[] { "\\N", null }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\n", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\n\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL.withNullString("NULL"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\tNULL\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "", "\u000e,\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\t\u000e,\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "NULL", "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "NULL\t\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); } @Test public void testMySqlNullStringDefault() { assertEquals("\\N", CSVFormat.MYSQL.getNullString()); } @Test(expected = IllegalArgumentException.class) public void testNewCsvPrinterAppendableNullFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), null)) { Assert.fail("This test should have thrown an exception."); } } @Test(expected = IllegalArgumentException.class) public void testNewCSVPrinterNullAppendableFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(null, CSVFormat.DEFAULT)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testParseCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.printRecord("a", null, "b"); } final String csvString = sw.toString(); assertEquals("a,NULL,b" + recordSeparator, csvString); try (final CSVParser iterable = format.parse(new StringReader(csvString))) { final Iterator<CSVRecord> iterator = iterable.iterator(); final CSVRecord record = iterator.next(); assertEquals("a", record.get(0)); assertEquals(null, record.get(1)); assertEquals("b", record.get(2)); assertFalse(iterator.hasNext()); } } @Test public void testPlainEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("abc"); assertEquals("abc", sw.toString()); } } @Test public void testPrint() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(sw)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL"))) { printer.printRecord("a", null, "b"); assertEquals("a,NULL,b" + recordSeparator, sw.toString()); } } @Test public void testPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testPrinter3() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a, b", "b "); assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); } } @Test public void testPrinter4() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\"c"); assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter5() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\nc"); assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter6() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\r\nc"); assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter7() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", null, "b"); assertEquals("a,,b" + recordSeparator, sw.toString()); } } @Test public void testPrintOnePositiveInteger() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.MINIMAL))) { printer.print(Integer.MAX_VALUE); assertEquals(String.valueOf(Integer.MAX_VALUE), sw.toString()); } } @Test public void testPrintToFileWithCharsetUtf16Be() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, StandardCharsets.UTF_16BE)) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, StandardCharsets.UTF_16BE)); } @Test public void testPrintToFileWithDefaultCharset() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testPrintToPathWithDefaultCharset() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file.toPath(), Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testQuoteAll() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL))) { printer.printRecord("a", "b\nc", "d"); assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); } } @Test public void testQuoteNonNumeric() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC))) { printer.printRecord("a", "b\nc", Integer.valueOf(1)); assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); } } @Test public void testRandomDefault() throws Exception { doRandom(CSVFormat.DEFAULT, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomExcel() throws Exception { doRandom(CSVFormat.EXCEL, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomMySql() throws Exception { doRandom(CSVFormat.MYSQL, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomRfc4180() throws Exception { doRandom(CSVFormat.RFC4180, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomTdf() throws Exception { doRandom(CSVFormat.TDF, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testSingleLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment"); assertEquals("# This is a comment" + recordSeparator, sw.toString()); } } @Test public void testSingleQuoteQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a'b'c"); printer.print("xyz"); assertEquals("'a''b''c',xyz", sw.toString()); } } @Test public void testSkipHeaderRecordFalse() throws IOException { // functionally identical to testHeader, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(false))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testSkipHeaderRecordTrue() throws IOException { // functionally identical to testHeaderNotSet, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(true))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testTrailingDelimiterOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrailingDelimiter())) { printer.printRecord("A", "B"); assertEquals("A,B,\r\n", sw.toString()); } } @Test public void testTrimOffOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim(false))) { printer.print(" A "); assertEquals("\" A \"", sw.toString()); } } @Test public void testTrimOnOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); assertEquals("A", sw.toString()); } } @Test public void testTrimOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); printer.print(" B "); assertEquals("A,B", sw.toString()); } } private String[] toFirstRecordValues(final String expected, final CSVFormat format) throws IOException { return CSVParser.parse(expected, format).getRecords().get(0).values(); } }
// You are a professional Java test case writer, please create a test case named `testEscapeNull1` for the issue `Csv-CSV-171`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-171 // // ## Issue-Title: // Negative numeric values in the first column are always quoted in minimal mode // // ## Issue-Description: // // Negative Numeric values are always quoted in minimal mode if (and only if) they are in the first column. // // // i.e. // // long,lat,data // // "-92.222",43.333,3 // // // Looking at the code, this is by design but seem to be for an unknown reason. // // // From v1.2 CSVPrinter line 230: // // // // TODO where did this rule come from? // // if (newRecord && (c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { // // quote = true; // // } else ... // // // I propose this rule to either be remove or at a minimum be changed to: // // // TODO where did this rule come from? // // if (newRecord && (c !='-' && c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { // // quote = true; // // } else ... // // // // // @Test public void testEscapeNull1() throws IOException {
346
14
339
src/test/java/org/apache/commons/csv/CSVPrinterTest.java
src/test/java
```markdown ## Issue-ID: Csv-CSV-171 ## Issue-Title: Negative numeric values in the first column are always quoted in minimal mode ## Issue-Description: Negative Numeric values are always quoted in minimal mode if (and only if) they are in the first column. i.e. long,lat,data "-92.222",43.333,3 Looking at the code, this is by design but seem to be for an unknown reason. From v1.2 CSVPrinter line 230: // TODO where did this rule come from? if (newRecord && (c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { quote = true; } else ... I propose this rule to either be remove or at a minimum be changed to: // TODO where did this rule come from? if (newRecord && (c !='-' && c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { quote = true; } else ... ``` You are a professional Java test case writer, please create a test case named `testEscapeNull1` for the issue `Csv-CSV-171`, utilizing the provided issue report information and the following function signature. ```java @Test public void testEscapeNull1() throws IOException { ```
339
[ "org.apache.commons.csv.CSVFormat" ]
02fe4403d96ec0bdd25c23d282e89bcdffb04daeb609bf922ed558bc1139023e
@Test public void testEscapeNull1() throws IOException
// You are a professional Java test case writer, please create a test case named `testEscapeNull1` for the issue `Csv-CSV-171`, utilizing the provided issue report information and the following function signature. // ## Issue-ID: Csv-CSV-171 // // ## Issue-Title: // Negative numeric values in the first column are always quoted in minimal mode // // ## Issue-Description: // // Negative Numeric values are always quoted in minimal mode if (and only if) they are in the first column. // // // i.e. // // long,lat,data // // "-92.222",43.333,3 // // // Looking at the code, this is by design but seem to be for an unknown reason. // // // From v1.2 CSVPrinter line 230: // // // // TODO where did this rule come from? // // if (newRecord && (c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { // // quote = true; // // } else ... // // // I propose this rule to either be remove or at a minimum be changed to: // // // TODO where did this rule come from? // // if (newRecord && (c !='-' && c < '0' || (c > '9' && c < 'A') || (c > 'Z' && c < 'a') || (c > 'z'))) { // // quote = true; // // } else ... // // // // //
Csv
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; import static org.apache.commons.csv.Constants.CR; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Random; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * * * @version $Id$ */ public class CSVPrinterTest { private static final char DQUOTE_CHAR = '"'; private static final char BACKSLASH_CH = '\\'; private static final char QUOTE_CH = '\''; private static final int ITERATIONS_FOR_RANDOM_TEST = 50000; private static String printable(final String s) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { final char ch = s.charAt(i); if (ch <= ' ' || ch >= 128) { sb.append("(").append((int) ch).append(")"); } else { sb.append(ch); } } return sb.toString(); } private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); private void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = generateLines(nLines, nCol); final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[]) lines[i]); } printer.flush(); } final String result = sw.toString(); // System.out.println("### :" + printable(result)); try (final CSVParser parser = CSVParser.parse(result, format)) { final List<CSVRecord> parseResult = parser.getRecords(); final String[][] expected = lines.clone(); for (int i = 0; i < expected.length; i++) { expected[i] = expectNulls(expected[i], format); } Utils.compare("Printer output :" + printable(result), expected, parseResult); } } private void doRandom(final CSVFormat format, final int iter) throws Exception { for (int i = 0; i < iter; i++) { doOneRandom(format); } } /** * Converts an input CSV array into expected output values WRT NULLs. NULL strings are converted to null values * because the parser will convert these strings to null. */ private <T> T[] expectNulls(final T[] original, final CSVFormat csvFormat) { final T[] fixed = original.clone(); for (int i = 0; i < fixed.length; i++) { if (Objects.equals(csvFormat.getNullString(), fixed[i])) { fixed[i] = null; } } return fixed; } private Connection geH2Connection() throws SQLException, ClassNotFoundException { Class.forName("org.h2.Driver"); return DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); } private String[][] generateLines(final int nLines, final int nCol) { final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } return lines; } private CSVPrinter printWithHeaderComments(final StringWriter sw, final Date now, final CSVFormat baseFormat) throws IOException { CSVFormat format = baseFormat; // Use withHeaderComments first to test CSV-145 format = format.withHeaderComments("Generated by Apache Commons CSV 1.1", now); format = format.withCommentMarker('#'); format = format.withHeader("Col1", "Col2"); final CSVPrinter csvPrinter = format.print(sw); csvPrinter.printRecord("A", "B"); csvPrinter.printRecord("C", "D"); csvPrinter.close(); return csvPrinter; } private String randStr() { final Random r = new Random(); final int sz = r.nextInt(20); // sz = r.nextInt(3); final char[] buf = new char[sz]; for (int i = 0; i < sz; i++) { // stick in special chars with greater frequency char ch; final int what = r.nextInt(20); switch (what) { case 0: ch = '\r'; break; case 1: ch = '\n'; break; case 2: ch = '\t'; break; case 3: ch = '\f'; break; case 4: ch = ' '; break; case 5: ch = ','; break; case 6: ch = DQUOTE_CHAR; break; case 7: ch = '\''; break; case 8: ch = BACKSLASH_CH; break; default: ch = (char) r.nextInt(300); break; // default: ch = 'a'; break; } buf[i] = ch; } return new String(buf); } private void setUpTable(final Connection connection) throws SQLException { try (final Statement statement = connection.createStatement()) { statement.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); statement.execute("insert into TEST values(1, 'r1')"); statement.execute("insert into TEST values(2, 'r2')"); } } @Test public void testDelimeterQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("'a,b,c',xyz", sw.toString()); } } @Test public void testDelimeterQuoteNONE() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuoteMode(QuoteMode.NONE); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a!,b!,c,xyz", sw.toString()); } } @Test public void testDelimiterPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a,b,c"); printer.print("xyz"); assertEquals("a,b,c,xyz", sw.toString()); } } @Test public void testDisabledComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printComment("This is a comment"); assertEquals("", sw.toString()); } } @Test public void testEOLEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a!rb!nc,x\fy\bz", sw.toString()); } } @Test public void testEOLPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("a\rb\nc"); printer.print("x\fy\bz"); assertEquals("a\rb\nc,x\fy\bz", sw.toString()); } } @Test public void testEOLQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a\rb\nc"); printer.print("x\by\fz"); assertEquals("'a\rb\nc',x\by\fz", sw.toString()); } } @Test public void testEscapeBackslash1() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeBackslash2() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\r"); } assertEquals("'\\\r'", sw.toString()); } @Test public void testEscapeBackslash3() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("X\\\r"); } assertEquals("'X\\\r'", sw.toString()); } @Test public void testEscapeBackslash4() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeBackslash5() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull1() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\"); } assertEquals("\\", sw.toString()); } @Test public void testEscapeNull2() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\r"); } assertEquals("\"\\\r\"", sw.toString()); } @Test public void testEscapeNull3() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("X\\\r"); } assertEquals("\"X\\\r\"", sw.toString()); } @Test public void testEscapeNull4() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testEscapeNull5() throws IOException { StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { printer.print("\\\\"); } assertEquals("\\\\", sw.toString()); } @Test public void testExcelPrintAllArrayOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords((Object[]) new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( (Object[]) new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfArrays() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrintAllIterableOfLists() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecords( Arrays.asList(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testExcelPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testHeader() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3"))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testHeaderCommentExcel() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.EXCEL; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1,Col2\r\nA,B\r\nC,D\r\n", sw.toString()); } } @Test public void testHeaderCommentTdf() throws IOException { final StringWriter sw = new StringWriter(); final Date now = new Date(); final CSVFormat format = CSVFormat.TDF; try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1\tCol2\r\nA\tB\r\nC\tD\r\n", sw.toString()); } } @Test public void testHeaderNotSet() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() throws Exception { final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), invalidFormat)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecords(stmt.executeQuery("select ID, NAME from TEST")); } } assertEquals("1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSet() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection();) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet).print(sw)) { printer.printRecords(resultSet); } } assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } @Test public void testJdbcPrinterWithResultSetMetaData() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet.getMetaData()).print(sw)) { printer.printRecords(resultSet); assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } } } @Test @Ignore public void testJira135_part1() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); printer.printRecord(list); } final String expected = "\"\\\"\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part2() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\n"); printer.printRecord(list); } final String expected = "\"\\n\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135_part3() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test @Ignore public void testJira135All() throws IOException { final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); final StringWriter sw = new StringWriter(); final List<String> list = new LinkedList<>(); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { list.add("\""); list.add("\n"); list.add("\\"); printer.printRecord(list); } final String expected = "\"\\\"\",\"\\n\",\"\\\"" + format.getRecordSeparator(); assertEquals(expected, sw.toString()); final String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(list.toArray(), format), record0); } @Test public void testMultiLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment\non multiple lines"); assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString()); } } @Test public void testMySqlNullOutput() throws IOException { Object[] s = new String[] { "NULL", null }; CSVFormat format = CSVFormat.MYSQL.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.NON_NUMERIC); StringWriter writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } String expected = "\"NULL\"\tNULL\n"; assertEquals(expected, writer.toString()); String[] record0 = toFirstRecordValues(expected, format); assertArrayEquals(new Object[2], record0); s = new String[] { "\\N", null }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\n", "A" }; format = CSVFormat.MYSQL.withNullString("\\N"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\n\tA\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL.withNullString("NULL"); writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\tNULL\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "", null }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\t\\N\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\N", "", "\u000e,\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\N\t\t\u000e,\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "NULL", "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "NULL\t\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); s = new String[] { "\\\r" }; format = CSVFormat.MYSQL; writer = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(writer, format)) { printer.printRecord(s); } expected = "\\\\\\r\n"; assertEquals(expected, writer.toString()); record0 = toFirstRecordValues(expected, format); assertArrayEquals(expectNulls(s, format), record0); } @Test public void testMySqlNullStringDefault() { assertEquals("\\N", CSVFormat.MYSQL.getNullString()); } @Test(expected = IllegalArgumentException.class) public void testNewCsvPrinterAppendableNullFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), null)) { Assert.fail("This test should have thrown an exception."); } } @Test(expected = IllegalArgumentException.class) public void testNewCSVPrinterNullAppendableFormat() throws Exception { try (final CSVPrinter printer = new CSVPrinter(null, CSVFormat.DEFAULT)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testParseCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); try (final CSVPrinter printer = new CSVPrinter(sw, format)) { printer.printRecord("a", null, "b"); } final String csvString = sw.toString(); assertEquals("a,NULL,b" + recordSeparator, csvString); try (final CSVParser iterable = format.parse(new StringReader(csvString))) { final Iterator<CSVRecord> iterator = iterable.iterator(); final CSVRecord record = iterator.next(); assertEquals("a", record.get(0)); assertEquals(null, record.get(1)); assertEquals("b", record.get(2)); assertFalse(iterator.hasNext()); } } @Test public void testPlainEscaped() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainPlain() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { printer.print("abc"); printer.print("xyz"); assertEquals("abc,xyz", sw.toString()); } } @Test public void testPlainQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("abc"); assertEquals("abc", sw.toString()); } } @Test public void testPrint() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(sw)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL"))) { printer.printRecord("a", null, "b"); assertEquals("a,NULL,b" + recordSeparator, sw.toString()); } } @Test public void testPrinter1() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b"); assertEquals("a,b" + recordSeparator, sw.toString()); } } @Test public void testPrinter2() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } } @Test public void testPrinter3() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a, b", "b "); assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); } } @Test public void testPrinter4() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\"c"); assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter5() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\nc"); assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter6() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\r\nc"); assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); } } @Test public void testPrinter7() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } } @Test public void testPrintNullValues() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { printer.printRecord("a", null, "b"); assertEquals("a,,b" + recordSeparator, sw.toString()); } } @Test public void testPrintOnePositiveInteger() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.MINIMAL))) { printer.print(Integer.MAX_VALUE); assertEquals(String.valueOf(Integer.MAX_VALUE), sw.toString()); } } @Test public void testPrintToFileWithCharsetUtf16Be() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, StandardCharsets.UTF_16BE)) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, StandardCharsets.UTF_16BE)); } @Test public void testPrintToFileWithDefaultCharset() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testPrintToPathWithDefaultCharset() throws IOException { File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file.toPath(), Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); } @Test public void testQuoteAll() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL))) { printer.printRecord("a", "b\nc", "d"); assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); } } @Test public void testQuoteNonNumeric() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC))) { printer.printRecord("a", "b\nc", Integer.valueOf(1)); assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); } } @Test public void testRandomDefault() throws Exception { doRandom(CSVFormat.DEFAULT, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomExcel() throws Exception { doRandom(CSVFormat.EXCEL, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomMySql() throws Exception { doRandom(CSVFormat.MYSQL, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomRfc4180() throws Exception { doRandom(CSVFormat.RFC4180, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testRandomTdf() throws Exception { doRandom(CSVFormat.TDF, ITERATIONS_FOR_RANDOM_TEST); } @Test public void testSingleLineComment() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { printer.printComment("This is a comment"); assertEquals("# This is a comment" + recordSeparator, sw.toString()); } } @Test public void testSingleQuoteQuoted() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { printer.print("a'b'c"); printer.print("xyz"); assertEquals("'a''b''c',xyz", sw.toString()); } } @Test public void testSkipHeaderRecordFalse() throws IOException { // functionally identical to testHeader, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(false))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testSkipHeaderRecordTrue() throws IOException { // functionally identical to testHeaderNotSet, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(true))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } } @Test public void testTrailingDelimiterOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrailingDelimiter())) { printer.printRecord("A", "B"); assertEquals("A,B,\r\n", sw.toString()); } } @Test public void testTrimOffOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim(false))) { printer.print(" A "); assertEquals("\" A \"", sw.toString()); } } @Test public void testTrimOnOneColumn() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); assertEquals("A", sw.toString()); } } @Test public void testTrimOnTwoColumns() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { printer.print(" A "); printer.print(" B "); assertEquals("A,B", sw.toString()); } } private String[] toFirstRecordValues(final String expected, final CSVFormat format) throws IOException { return CSVParser.parse(expected, format).getRecords().get(0).values(); } }
" @Test\n public void testChainedRemoveAttributes() {\n String html = \"<a one two thre(...TRUNCATED)
org.jsoup.nodes.ElementTest::testChainedRemoveAttributes
src/test/java/org/jsoup/nodes/ElementTest.java
973
src/test/java/org/jsoup/nodes/ElementTest.java
testChainedRemoveAttributes
"package org.jsoup.nodes;\n\nimport org.jsoup.Jsoup;\nimport org.jsoup.TextUtil;\nimport org.jsoup.p(...TRUNCATED)
"// You are a professional Java test case writer, please create a test case named `testChainedRemove(...TRUNCATED)
973
57
960
src/test/java/org/jsoup/nodes/ElementTest.java
src/test/java
"```markdown\n## Issue-ID: Jsoup-759\n\n## Issue-Title: \nremoveIgnoreCase ConcurrentModificationExc(...TRUNCATED)
960
[ "org.jsoup.nodes.Attributes" ]
03861a74fcf192e0e0543153e3e1885a9c95b0146e24fe30efe83a989d95bccb
@Test public void testChainedRemoveAttributes()
"// You are a professional Java test case writer, please create a test case named `testChainedRemove(...TRUNCATED)
Jsoup
"package org.jsoup.nodes;\n\nimport org.jsoup.Jsoup;\nimport org.jsoup.TextUtil;\nimport org.jsoup.p(...TRUNCATED)
" public void testWithUnwrappedAndCreatorSingleParameterAtBeginning() throws Exception {\n (...TRUNCATED)
"com.fasterxml.jackson.databind.deser.builder.BuilderWithUnwrappedTest::testWithUnwrappedAndCreatorS(...TRUNCATED)
src/test/java/com/fasterxml/jackson/databind/deser/builder/BuilderWithUnwrappedTest.java
179
src/test/java/com/fasterxml/jackson/databind/deser/builder/BuilderWithUnwrappedTest.java
testWithUnwrappedAndCreatorSingleParameterAtBeginning
"package com.fasterxml.jackson.databind.deser.builder;\n\nimport com.fasterxml.jackson.annotation.Js(...TRUNCATED)
"// You are a professional Java test case writer, please create a test case named `testWithUnwrapped(...TRUNCATED)
179
" /*\n *************************************\n * Unit tests\n ***********************(...TRUNCATED)
76
168
src/test/java/com/fasterxml/jackson/databind/deser/builder/BuilderWithUnwrappedTest.java
src/test/java
"```markdown\n## Issue-ID: JacksonDatabind-1573\n\n## Issue-Title: \nMissing properties when deseria(...TRUNCATED)
168
[ "com.fasterxml.jackson.databind.deser.BuilderBasedDeserializer" ]
0401bac6c0aa608166d12da47792008573fda3176ab1774de2b9f86ea7aabd03
public void testWithUnwrappedAndCreatorSingleParameterAtBeginning() throws Exception
"// You are a professional Java test case writer, please create a test case named `testWithUnwrapped(...TRUNCATED)
JacksonDatabind
"package com.fasterxml.jackson.databind.deser.builder;\n\nimport com.fasterxml.jackson.annotation.Js(...TRUNCATED)
" @Test\n public void survivesPaxHeaderWithNameEndingInSlash() throws Exception {\n fin(...TRUNCATED)
"org.apache.commons.compress.archivers.tar.TarArchiveInputStreamTest::survivesPaxHeaderWithNameEndin(...TRUNCATED)
src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
328
src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
survivesPaxHeaderWithNameEndingInSlash
"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license(...TRUNCATED)
"// You are a professional Java test case writer, please create a test case named `survivesPaxHeader(...TRUNCATED)
328
/** * @link "https://issues.apache.org/jira/browse/COMPRESS-356" */
38
318
src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
src/test/java
"```markdown\n## Issue-ID: Compress-COMPRESS-356\n\n## Issue-Title: \nPAX header entry name ending w(...TRUNCATED)
318
[ "org.apache.commons.compress.archivers.tar.TarArchiveEntry" ]
0415194838d24fbbc7c6bba450f676fa746588c1e44179aae34c4601d66b3b6b
@Test public void survivesPaxHeaderWithNameEndingInSlash() throws Exception
"// You are a professional Java test case writer, please create a test case named `survivesPaxHeader(...TRUNCATED)
Compress
"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license(...TRUNCATED)
" @Test\n public void testReadingOfFirstStoredEntry() throws Exception {\n ZipArchiveIn(...TRUNCATED)
org.apache.commons.compress.archivers.zip.ZipArchiveInputStreamTest::testReadingOfFirstStoredEntry
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
170
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
testReadingOfFirstStoredEntry
"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license(...TRUNCATED)
"// You are a professional Java test case writer, please create a test case named `testReadingOfFirs(...TRUNCATED)
170
" /**\n * Test case for \n * <a href=\"https://issues.apache.org/jira/browse/COMPRESS-264(...TRUNCATED)
25
158
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
src/test/java
"```markdown\n## Issue-ID: Compress-COMPRESS-264\n\n## Issue-Title: \nZIP reads correctly with commo(...TRUNCATED)
158
[ "org.apache.commons.compress.archivers.zip.ZipArchiveInputStream" ]
050b4d4132e91fd034ea46a90712ff55907adde1c1012bec705211fb26cb04ce
@Test public void testReadingOfFirstStoredEntry() throws Exception
"// You are a professional Java test case writer, please create a test case named `testReadingOfFirs(...TRUNCATED)
Compress
"/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license(...TRUNCATED)
" public void testBug4944818() {\n test(\n \"var getDomServices_ = function(self) {\\n\" (...TRUNCATED)
com.google.javascript.jscomp.InlineFunctionsTest::testBug4944818
test/com/google/javascript/jscomp/InlineFunctionsTest.java
2,093
test/com/google/javascript/jscomp/InlineFunctionsTest.java
testBug4944818
"/*\n * Copyright 2008 The Closure Compiler Authors.\n *\n * Licensed under the Apache License, Vers(...TRUNCATED)
"// You are a professional Java test case writer, please create a test case named `testBug4944818` f(...TRUNCATED)
2,093
115
2,058
test/com/google/javascript/jscomp/InlineFunctionsTest.java
test
"```markdown\n## Issue-ID: Closure-1101\n\n## Issue-Title: \nErroneous optimization in ADVANCED_OPTI(...TRUNCATED)
2,058
[ "com.google.javascript.jscomp.FunctionInjector" ]
0547be5ae0ee0bb59db0bd6db5e5b39ba3eb97b4572678f7c8ca2d9687baeea0
public void testBug4944818()
"// You are a professional Java test case writer, please create a test case named `testBug4944818` f(...TRUNCATED)
Closure
"/*\n * Copyright 2008 The Closure Compiler Authors.\n *\n * Licensed under the Apache License, Vers(...TRUNCATED)
" public void testPrintWrapped()\n throws Exception\n {\n StringBuffer sb = new String(...TRUNCATED)
org.apache.commons.cli.HelpFormatterTest::testPrintWrapped
src/test/org/apache/commons/cli/HelpFormatterTest.java
114
src/test/org/apache/commons/cli/HelpFormatterTest.java
testPrintWrapped
"/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license (...TRUNCATED)
"// You are a professional Java test case writer, please create a test case named `testPrintWrapped`(...TRUNCATED)
114
8
67
src/test/org/apache/commons/cli/HelpFormatterTest.java
src/test
"```markdown\n## Issue-ID: Cli-CLI-151\n\n## Issue-Title: \nHelpFormatter wraps incorrectly on every(...TRUNCATED)
67
[ "org.apache.commons.cli.HelpFormatter" ]
06a4b1a5880e47010b28e5cb1d3de6798c92c7a0d4113e697e16d87a8f5c04a0
public void testPrintWrapped() throws Exception
"// You are a professional Java test case writer, please create a test case named `testPrintWrapped`(...TRUNCATED)
Cli
"/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license (...TRUNCATED)
" public void testPropertyOptionFlags() throws Exception\n {\n Properties properties = (...TRUNCATED)
org.apache.commons.cli.ValueTest::testPropertyOptionFlags
src/test/org/apache/commons/cli/ValueTest.java
236
src/test/org/apache/commons/cli/ValueTest.java
testPropertyOptionFlags
"/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license (...TRUNCATED)
"// You are a professional Java test case writer, please create a test case named `testPropertyOptio(...TRUNCATED)
236
28
191
src/test/org/apache/commons/cli/ValueTest.java
src/test
"```markdown\n## Issue-ID: Cli-CLI-201\n\n## Issue-Title: \nDefault options may be partially process(...TRUNCATED)
191
[ "org.apache.commons.cli.Parser" ]
07be9f5a2dc338177219f9e05b441b6c77b4d7baec421c9c82e25c28a1683513
public void testPropertyOptionFlags() throws Exception
"// You are a professional Java test case writer, please create a test case named `testPropertyOptio(...TRUNCATED)
Cli
"/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license (...TRUNCATED)
" public void testIssue1047() throws Exception {\n testTypes(\n \"/**\\n\" +\n \" (...TRUNCATED)
com.google.javascript.jscomp.TypeCheckTest::testIssue1047
test/com/google/javascript/jscomp/TypeCheckTest.java
6,870
test/com/google/javascript/jscomp/TypeCheckTest.java
testIssue1047
"/*\n * Copyright 2006 The Closure Compiler Authors.\n *\n * Licensed under the Apache License, Vers(...TRUNCATED)
"// You are a professional Java test case writer, please create a test case named `testIssue1047` fo(...TRUNCATED)
6,870
117
6,850
test/com/google/javascript/jscomp/TypeCheckTest.java
test
"```markdown\n## Issue-ID: Closure-1047\n\n## Issue-Title: \nWrong type name reported on missing pro(...TRUNCATED)
6,850
[ "com.google.javascript.jscomp.TypeValidator" ]
07cf137f8e93b1b3ea8d9d5deb05baafa7244be45fb719b13791f8e28a6b7d8e
public void testIssue1047() throws Exception
"// You are a professional Java test case writer, please create a test case named `testIssue1047` fo(...TRUNCATED)
Closure
"/*\n * Copyright 2006 The Closure Compiler Authors.\n *\n * Licensed under the Apache License, Vers(...TRUNCATED)
README.md exists but content is empty.
Downloads last month
31