1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 17 package com.android.compatibility.common.util; 18 19 /** 20 * Helper methods for dealing with stack traces 21 */ 22 public class Stacktrace { 23 24 private static final int SAFETY_DEPTH = 4; 25 private static final String TEST_POSTFIX = "Test"; 26 Stacktrace()27 private Stacktrace() {} 28 29 /** 30 * @return classname#methodname from call stack of the current thread 31 */ getTestCallerClassMethodName()32 public static String getTestCallerClassMethodName() { 33 return getTestCallerClassMethodName(false /*includeLineNumber*/); 34 } 35 36 /** 37 * @return classname#methodname from call stack of the current thread 38 */ getTestCallerClassMethodNameLineNumber()39 public static String getTestCallerClassMethodNameLineNumber() { 40 return getTestCallerClassMethodName(true /*includeLineNumber*/); 41 } 42 43 /** 44 * @return classname#methodname from call stack of the current thread 45 */ getTestCallerClassMethodName(boolean includeLineNumber)46 private static String getTestCallerClassMethodName(boolean includeLineNumber) { 47 StackTraceElement[] elements = Thread.currentThread().getStackTrace(); 48 // Look for the first class name in the elements array that ends with Test 49 for (int i = 0; i < elements.length; i++) { 50 if (elements[i].getClassName().endsWith(TEST_POSTFIX)) { 51 return buildClassMethodName(elements, i, includeLineNumber); 52 } 53 } 54 55 // Use a reasonable default if the test name isn't found 56 return buildClassMethodName(elements, SAFETY_DEPTH, includeLineNumber); 57 } 58 buildClassMethodName( StackTraceElement[] elements, int depth, boolean includeLineNumber)59 private static String buildClassMethodName( 60 StackTraceElement[] elements, int depth, boolean includeLineNumber) { 61 depth = Math.min(depth, elements.length - 1); 62 StringBuilder builder = new StringBuilder(); 63 builder.append(elements[depth].getClassName()).append("#") 64 .append(elements[depth].getMethodName()); 65 if (includeLineNumber) { 66 builder.append(":").append(elements[depth].getLineNumber()); 67 } 68 return builder.toString(); 69 } 70 } 71