<lambda>null1 package leakcanary
2 
3 import shark.HeapAnalysisFailure
4 import shark.HeapAnalysisSuccess
5 import shark.SharkLog
6 
7 /**
8  * Thrown when using the [NoLeakAssertionFailedError.throwOnApplicationLeaks] HeapAnalysisReporter
9  */
10 class NoLeakAssertionFailedError(
11   val heapAnalysis: HeapAnalysisSuccess
12 ) : AssertionError(
13   "Application memory leaks were detected:\n$heapAnalysis"
14 ) {
15   companion object {
16     /**
17      * A [HeapAnalysisReporter] that throws a [NoLeakAssertionFailedError] when the heap analysis
18      * has application leaks.
19      */
20     fun throwOnApplicationLeaks(): HeapAnalysisReporter = HeapAnalysisReporter { heapAnalysis ->
21       when (heapAnalysis) {
22         is HeapAnalysisSuccess -> {
23           when {
24             heapAnalysis.applicationLeaks.isNotEmpty() -> {
25               throw NoLeakAssertionFailedError(heapAnalysis)
26             }
27             heapAnalysis.libraryLeaks.isNotEmpty() -> {
28               SharkLog.d {
29                 "Test can keep going: heap analysis found 0 application leaks and ${heapAnalysis.libraryLeaks.size} library leaks:\n$heapAnalysis"
30               }
31             }
32             heapAnalysis.unreachableObjects.isNotEmpty() -> {
33               SharkLog.d {
34                 "Test can keep going: heap analysis found 0 leaks and ${heapAnalysis.unreachableObjects.size} watched weakly reachable objects:\n" +
35                   heapAnalysis
36               }
37             }
38             else -> {
39               SharkLog.d { "Test can keep going: heap analysis found 0 leaks." }
40             }
41           }
42         }
43         is HeapAnalysisFailure -> {
44           throw heapAnalysis.exception
45         }
46       }
47     }
48   }
49 }
50