Skip to content

Commit

Permalink
Don't crash when logging null parameter (#1081)
Browse files Browse the repository at this point in the history
  • Loading branch information
rfc2822 authored Oct 18, 2024
1 parent d4e9e2a commit 450a418
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,15 @@ class PlainTextFormatter(
}

r.parameters?.let {
for ((idx, param) in it.withIndex())
builder.append("\n\tPARAMETER #").append(idx).append(" = ").append(truncate(param.toString()))
for ((idx, param) in it.withIndex()) {
builder.append("\n\tPARAMETER #").append(idx + 1).append(" = ")

val valStr = if (param == null)
"(null)"
else
truncate(param.toString())
builder.append(valStr)
}
}

if (lineSeparator != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,43 @@

package at.bitfire.davdroid.log

import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.logging.Level
import java.util.logging.LogRecord

class PlainTextFormatterTest {

private val minimum = PlainTextFormatter(
withTime = false,
withSource = false,
withException = false,
lineSeparator = null
)

@Test
fun test_format_param_null() {
val result = minimum.format(LogRecord(Level.INFO, "Message").apply {
parameters = arrayOf(null)
})
assertEquals("Message\n\tPARAMETER #1 = (null)", result)
}

@Test
fun test_format_param_object() {
val result = minimum.format(LogRecord(Level.INFO, "Message").apply {
parameters = arrayOf(object {
override fun toString() = "SomeObject[]"
})
})
assertEquals("Message\n\tPARAMETER #1 = SomeObject[]", result)
}

@Test
fun test_format_TruncatesMessage() {
val formatter = PlainTextFormatter.DEFAULT
val result = formatter.format(LogRecord(Level.INFO, "a".repeat(50000)))
// PlainTextFormatter.MAX_LENGTH is 10,000, so the message should be truncated to 10,000 + something
assert(result.length <= 10100)
fun test_format_truncatesMessage() {
val result = minimum.format(LogRecord(Level.INFO, "a".repeat(50000)))
// PlainTextFormatter.MAX_LENGTH is 10,000
assertEquals(10000, result.length)
}

}

0 comments on commit 450a418

Please sign in to comment.