xref: /aosp_15_r20/external/leakcanary2/shark-log/src/test/java/shark/SharkLogTest.kt (revision d9e8da70d8c9df9a41d7848ae506fb3115cae6e6)
1 package shark
2 
3 import org.assertj.core.api.Assertions.assertThat
4 import org.junit.Test
5 import shark.SharkLog.Logger
6 import java.io.ByteArrayOutputStream
7 import java.io.PrintStream
8 
9 class SharkLogTest {
10 
11   private class StreamLogger(private val stream: PrintStream) : Logger {
dnull12     override fun d(message: String) = stream.print(message)
13     override fun d(
14       throwable: Throwable,
15       message: String
16     ) = stream.print("$message ${throwable.message}")
17   }
18 
19   @Test fun `logging works when logger is set`() {
20     val outputStream = ByteArrayOutputStream()
21 
22     SharkLog.logger = StreamLogger(PrintStream(outputStream))
23 
24     // Test debug logging
25     SharkLog.d { "Test debug" }
26     assertThat(outputStream.toString()).isEqualTo("Test debug")
27   }
28 
logging with exception works when logger is setnull29   @Test fun `logging with exception works when logger is set`() {
30     val outputStream = ByteArrayOutputStream()
31 
32     SharkLog.logger = StreamLogger(PrintStream(outputStream))
33 
34     // Test error logging
35     SharkLog.d(Exception("Test exception")) { "Test error" }
36     assertThat(outputStream.toString()).isEqualTo("Test error Test exception")
37   }
38 
logging is no-op without logger and string is ignorednull39   @Test fun `logging is no-op without logger and string is ignored`() {
40     SharkLog.logger = null
41 
42     // Logging message will throw an exception when attempting to use it
43     // But since it's in lambda string will not be accessed
44     SharkLog.d { "".substring(1) }
45 
46     SharkLog.d(Exception("Test exception")) { "".substring(1) }
47   }
48 }