<lambda>null1package leakcanary 2 3 import shark.HeapAnalysis 4 import shark.HeapAnalysisSuccess 5 import shark.LeakTrace 6 7 object TestUtils { 8 9 fun assertLeak(expectedLeakClass: Class<*>) { 10 assertLeak { (heapAnalysis, leakTrace) -> 11 val className = leakTrace.leakingObject.className 12 if (className != expectedLeakClass.name) { 13 throw AssertionError( 14 "Expected a leak of $expectedLeakClass, not $className in $heapAnalysis" 15 ) 16 } 17 } 18 } 19 20 fun assertLeak(inspectLeakTrace: (Pair<HeapAnalysisSuccess, LeakTrace>) -> Unit = {}) { 21 val heapAnalysis = detectLeaks() 22 val applicationLeaks = heapAnalysis.applicationLeaks 23 if (applicationLeaks.size != 1) { 24 throw AssertionError( 25 "Expected exactly one leak in $heapAnalysis" 26 ) 27 } 28 29 val leak = applicationLeaks.first() 30 31 val leakTrace = leak.leakTraces.first() 32 inspectLeakTrace(heapAnalysis to leakTrace) 33 } 34 35 fun detectLeaks(): HeapAnalysisSuccess { 36 var heapAnalysisOrNull: HeapAnalysis? = null 37 AndroidDetectLeaksAssert { heapAnalysis -> 38 heapAnalysisOrNull = heapAnalysis 39 }.assertNoLeaks("") 40 if (heapAnalysisOrNull == null) { 41 throw AssertionError( 42 "Expected analysis to be performed but skipped" 43 ) 44 } 45 val heapAnalysis = heapAnalysisOrNull 46 47 if (heapAnalysis !is HeapAnalysisSuccess) { 48 throw AssertionError( 49 "Expected analysis success not $heapAnalysis" 50 ) 51 } 52 // Save disk space on emulator 53 heapAnalysis.heapDumpFile.delete() 54 return heapAnalysis 55 } 56 } 57