1 // Copyright 2023 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.base.test.util; 6 7 import org.junit.rules.TestWatcher; 8 import org.junit.runner.Description; 9 10 import org.chromium.base.Log; 11 12 import java.util.Map; 13 14 /** 15 * A simple rule that dumps all threads if the test fails. Used for debugging tests where an 16 * unknown long running task might be causing problems. 17 */ 18 public class DumpThreadsOnFailureRule extends TestWatcher { 19 private static final String TAG = " DTOFR"; 20 21 @Override failed(Throwable e, Description description)22 protected void failed(Throwable e, Description description) { 23 super.failed(e, description); 24 logThreadDumps(); 25 } 26 logThreadDumps()27 private void logThreadDumps() { 28 Map<Thread, StackTraceElement[]> threadDumps = Thread.getAllStackTraces(); 29 for (Map.Entry<Thread, StackTraceElement[]> entry : threadDumps.entrySet()) { 30 Thread thread = entry.getKey(); 31 Log.e(TAG, thread.getName() + ": " + thread.getState()); 32 for (StackTraceElement stackTraceElement : entry.getValue()) { 33 Log.e(TAG, "\t" + stackTraceElement); 34 } 35 } 36 } 37 } 38