main

square/leakcanary

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

MetadataExtractorTest.kt

TLDR

The file MetadataExtractorTest.kt contains a test class for the MetadataExtractor class in the shark package. The test case extracts a static string field from an hprof file, creates a MetadataExtractor object, checks for leaks in the hprof file using the MetadataExtractor, and verifies the extracted metadata.

Class: MetadataExtractorTest

This class contains test cases for the MetadataExtractor class.

Method: setUp()

This method is annotated with @Before and is executed before each test case. It sets up the temporary folder and creates a temporary hprof file.

Method: extractStaticStringField()

This method is annotated with @Test and represents a test case. It extracts a static string field from the hprof file using the hprofFile.dump() function. It then creates a MetadataExtractor object that extracts the "message" field from the "World" class in the hprof file. The extracted metadata is then verified against an expected value using the assertThat assertion.

package shark

import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File

class MetadataExtractorTest {

  @get:Rule
  var testFolder = TemporaryFolder()
  private lateinit var hprofFile: File

  @Before
  fun setUp() {
    hprofFile = testFolder.newFile("temp.hprof")
  }

  @Test fun extractStaticStringField() {
    hprofFile.dump {
      val helloString = string("Hello")
      clazz(
        "World", staticFields = listOf(
        "message" to helloString
      )
      )
    }

    val extractor = MetadataExtractor { graph ->
      val message =
        graph.findClassByName("World")!!["message"]!!.valueAsInstance!!.readAsJavaString()!!
      mapOf("World message" to message)
    }

    val analysis = hprofFile.checkForLeaks<HeapAnalysisSuccess>(metadataExtractor = extractor)

    val metadata = analysis.metadata

    assertThat(metadata).containsAllEntriesOf(mapOf("World message" to "Hello"))
  }
}