Home | History | Annotate | Download | only in runtime
      1 // Copyright 2017 The Bazel Authors. All rights reserved.
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //    http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 package com.google.devtools.build.android.desugar.runtime;
     15 
     16 import static com.google.common.truth.Truth.assertThat;
     17 
     18 import java.lang.reflect.Method;
     19 
     20 /**
     21  * A utility class for testing ThrowableExtension. It uses reflection to get the strategy name, so
     22  * as to avoid dependency on the runtime library. This is beneficial, because we can test whether
     23  * the runtime library is on the classpath.
     24  */
     25 public class ThrowableExtensionTestUtility {
     26 
     27   private static final String SYSTEM_PROPERTY_EXPECTED_STRATEGY = "expected.strategy";
     28 
     29   public static String getTwrStrategyClassNameSpecifiedInSystemProperty() {
     30     String className = System.getProperty(SYSTEM_PROPERTY_EXPECTED_STRATEGY);
     31     assertThat(className).isNotEmpty();
     32     return className;
     33   }
     34 
     35   private static final String THROWABLE_EXTENSION_CLASS_NAME =
     36       "com.google.devtools.build.android.desugar.runtime.ThrowableExtension";
     37 
     38   private static boolean isStrategyOfClass(String className) {
     39     return getStrategyClassName().equals(className);
     40   }
     41 
     42   public static String getStrategyClassName() {
     43     try {
     44       Class<?> klass = Class.forName(THROWABLE_EXTENSION_CLASS_NAME);
     45       Method method = klass.getMethod("getStrategy");
     46       Object strategy = method.invoke(null);
     47       return strategy.getClass().getName();
     48     } catch (Throwable e) {
     49       throw new AssertionError(e);
     50     }
     51   }
     52 
     53   public static boolean isMimicStrategy() {
     54     return isStrategyOfClass(THROWABLE_EXTENSION_CLASS_NAME + "$MimicDesugaringStrategy");
     55   }
     56 
     57   public static boolean isNullStrategy() {
     58     return isStrategyOfClass(THROWABLE_EXTENSION_CLASS_NAME + "$NullDesugaringStrategy");
     59   }
     60 
     61   public static boolean isReuseStrategy() {
     62     return isStrategyOfClass(THROWABLE_EXTENSION_CLASS_NAME + "$ReuseDesugaringStrategy");
     63   }
     64 }
     65