Skip to content

Commit

Permalink
fix: Update parser readField method to read up to last line index (#15)
Browse files Browse the repository at this point in the history
* Update readField function to read up to last index of line

* Fix unit test name
  • Loading branch information
marianptelus authored Mar 31, 2022
1 parent ae68a5f commit 9837e67
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package digital.capsa.core.fileparser

import java.io.BufferedReader
import kotlin.math.min

@DslMarker
annotation class ParserMarker
Expand Down Expand Up @@ -112,7 +113,7 @@ class RecordParser(
from: Int,
toExclusive: Int
): String {
return if (line.length >= toExclusive) line.substring(from, toExclusive).trimEnd() else ""
return if (line.length > from) line.substring(from, min(toExclusive, line.length)).trimEnd() else ""
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,57 @@ class FileParserBasicDslTest {
Assertions.assertEquals("Line length should be 22 but was 20", parser.getRecords()[1].issues[0].message)
Assertions.assertEquals("Line length should be 22 but was 20", parser.getRecords()[2].issues[0].message)
}

@Test
fun `line length ends before last fields toExclusive`() {
data class CustomItem(val string1: String?, val string2: String, val int1: Int?, val date1: String?)

val parser = parser(
BufferedReader(
StringReader(
"""
aaa 23 2021-03-09
bbb c 23 2021-04-19
d e f1 34 2021-05-2
""".trimIndent()
)
)
) {
header(17) {
Header(
string1 = optionalField(0, 4, "field1"),
int1 = mandatoryField(4, 7, "field2"),
date1 = optionalField(7, 17, "field3")
)
}
line {
CustomItem(
string1 = optionalField(0, 4, "field1"),
string2 = mandatoryField(4, 7, "field2"),
int1 = optionalField(7, 10, "field3"),
date1 = optionalField(10, 20, "field4")
)
}
}
Assertions.assertEquals(0, parser.getRecords()[0].issues.count())
Assertions.assertEquals(0, parser.getRecords()[1].issues.count())
Assertions.assertEquals(0, parser.getRecords()[2].issues.count())

val header = parser.getRecords()[0].value as Header
Assertions.assertEquals("aaa", header.string1)
Assertions.assertEquals(23, header.int1)
Assertions.assertEquals(LocalDate.parse("2021-03-09"), header.date1)

var item = parser.getRecords()[1].value as CustomItem
Assertions.assertEquals("bbb", item.string1)
Assertions.assertEquals(" c", item.string2)
Assertions.assertEquals(23, item.int1)
Assertions.assertEquals("2021-04-19", item.date1)

item = parser.getRecords()[2].value as CustomItem
Assertions.assertEquals("d e", item.string1)
Assertions.assertEquals("f1", item.string2)
Assertions.assertEquals(34, item.int1)
Assertions.assertEquals("2021-05-2", item.date1)
}
}

0 comments on commit 9837e67

Please sign in to comment.