1 21 22 package org.dbunit.dataset.csv; 23 24 import junit.framework.TestCase; 25 import org.dbunit.dataset.csv.handlers.PipelineException; 26 27 import java.io.*; 28 import java.util.List ; 29 30 31 public class CsvParserTest extends TestCase { 32 33 CsvParser parser; 34 35 59 60 public void testCanParseNonQuotedStrings() throws PipelineException, IllegalInputCharacterException { 61 String csv = "Hello, world"; 62 List parsed = parser.parse(csv); 63 assertEquals(2, parsed.size()); 64 assertEquals(parsed.get(0), "Hello"); 65 assertEquals(parsed.get(1), "world"); 66 } 67 68 public void testAFieldCanContainANewLine () throws PipelineException, IllegalInputCharacterException { 69 assertEquals("", 3, parser.parse("Hello, World\nIt's today, the day before tomorrow").size()); 70 } 71 72 public void testDontAcceptIncompleteFields () throws PipelineException, IllegalInputCharacterException { 73 String incompleteFields = "AAAAA,\"BB"; 74 75 try { 76 parser.parse(incompleteFields); 77 fail("should have thrown an exception"); 78 } catch (IllegalStateException e) { 79 assertTrue(true); 80 } 81 } 82 83 public void testAFileCanContainFieldWithNewLine () throws IOException, CsvParserException { 84 final String pathname = "src/csv/with-newlines.csv"; 85 List list = parser.parse(new File(pathname)); 86 assertEquals("wrong number of lines parsed from " + pathname, 2, list.size()); 87 List row = (List ) list.get(1); 88 assertEquals("AA\nAAA", row.get(0)); 89 assertEquals("BB\nBBB", row.get(1)); 90 } 91 92 public void testRaiseACSVParserExceptonWhenParsingAnEmptyFile () throws IOException { 93 failParsing(new File("src/csv/empty-file.csv")); 94 } 95 96 public void testRaiseACSVParserExceptonWhenParsingFileWithDifferentNumberOfColumns () throws IllegalInputCharacterException, IOException, PipelineException { 97 failParsing(new File("src/csv/different-column-numbers-last.csv")); 98 failParsing(new File("src/csv/different-column-numbers-first.csv")); 99 } 100 101 private void failParsing(File sample) throws IOException { 102 try { 103 parser.parse(sample); 104 fail("should have thrown a CsvParserException"); 105 } catch (CsvParserException e) { 106 assertTrue(true); 107 } 108 } 109 110 public void testSample() throws Exception { 111 112 File sample = new File("src/csv/sample.csv"); 113 BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(sample))); 114 LineNumberReader lineNumberReader = new LineNumberReader(reader); 115 String line; 116 while ((line = lineNumberReader.readLine()) != null) { 117 if (line.startsWith("#") || line.trim().length() == 0) 118 continue; 119 List actual = parser.parse(line); 121 assertEquals("wrong tokens on line " + lineNumberReader.getLineNumber() + " " + line, 122 3, actual.size()); 123 } 124 } 125 126 protected void setUp() throws Exception { 127 parser = new CsvParserImpl(); 128 } 129 130 } 131 132 | Popular Tags |