Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2017 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 import android.support.test.InstrumentationRegistry;
     20 import android.util.Log;
     21 
     22 import org.junit.rules.TestRule;
     23 import org.junit.runner.Description;
     24 import org.junit.runners.model.Statement;
     25 
     26 /**
     27  * Custom JUnit4 rule that does not run a test case if the device does not have a given feature.
     28  */
     29 public class RequiredFeatureRule implements TestRule {
     30     private static final String TAG = "RequiredFeatureRule";
     31 
     32     private final String mFeature;
     33     private final boolean mHasFeature;
     34 
     35     public RequiredFeatureRule(String feature) {
     36         mFeature = feature;
     37         mHasFeature = hasFeature(feature);
     38     }
     39 
     40     @Override
     41     public Statement apply(Statement base, Description description) {
     42         return new Statement() {
     43 
     44             @Override
     45             public void evaluate() throws Throwable {
     46                 if (!mHasFeature) {
     47                     Log.d(TAG, "skipping "
     48                             + description.getClassName() + "#" + description.getMethodName()
     49                             + " because device does not have feature '" + mFeature + "'");
     50                     return;
     51                 }
     52                 base.evaluate();
     53             }
     54         };
     55     }
     56 
     57     public static boolean hasFeature(String feature) {
     58         return InstrumentationRegistry.getContext().getPackageManager().hasSystemFeature(feature);
     59     }
     60 }
     61