main

square/leakcanary

Last updated at: 29/12/2023 09:39

HprofReaderPrimitiveArrayTest.kt

TLDR

This file is a test class for the HprofReaderPrimitiveArray class. It contains two test methods that verify the behavior of skipping and reading primitive arrays in the HprofReaderPrimitiveArray class.

Methods

skips_primitive_arrays_correctly

This method verifies that all records, including primitive arrays, are skipped correctly by invoking the readRecords method on a StreamingHprofReader instance and asserting that an error is thrown.

reads_primitive_arrays_correctly

This method verifies that primitive arrays are read correctly by invoking the readRecords method on a StreamingHprofReader instance and checking if a specific byte array is present in the heap dump. If the byte array is found, a flag myByteArrayIsInHeapDump is set to true.

package shark

import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import kotlin.text.Charsets.UTF_8
import shark.StreamingRecordReaderAdapter.Companion.asStreamingRecordReader

class HprofReaderPrimitiveArrayTest {

  @get:Rule
  var heapDumpRule = HeapDumpRule()

  @Test
  fun skips_primitive_arrays_correctly() {
    val heapDump = heapDumpRule.dumpHeap()

    StreamingHprofReader.readerFor(heapDump).readRecords(emptySet()) { _, _, _ ->
      error("Should skip all records, including primitive arrays")
    }
  }

  @Test
  fun reads_primitive_arrays_correctly() {
    val byteArray = ("Sharks also have a sensory organ called the \"ampullae of Lorenzini\" " +
      "which they use to \"feel\" the electrical field coming from its prey.")
      .toByteArray(UTF_8)

    val heapDump = heapDumpRule.dumpHeap()

    var myByteArrayIsInHeapDump = false

    val reader = StreamingHprofReader.readerFor(heapDump).asStreamingRecordReader()
    reader.readRecords(setOf(HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord::class)) {  _, record ->
      if (record is HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.ByteArrayDump) {
        if (byteArray.contentEquals(record.array)) {
          myByteArrayIsInHeapDump = true
        }
      }
    }
    assertThat(myByteArrayIsInHeapDump).isTrue()
  }
}