1 /*
2  * Copyright (C) 2021 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 package android.platform.test.util;
17 
18 import android.os.Bundle;
19 import android.util.Log;
20 
21 import androidx.annotation.VisibleForTesting;
22 
23 import org.junit.runner.Description;
24 
25 /** Contains a method for filtering specific tests to run. Expects the format class#method. */
26 public final class TestFilter {
27 
28     private static final String LOG_TAG = TestFilter.class.getSimpleName();
29     @VisibleForTesting static final String OPTION_NAME = "filter-tests";
30 
TestFilter()31     private TestFilter() {}
32 
isFilteredOrUnspecified(Bundle arguments, Description description)33     public static boolean isFilteredOrUnspecified(Bundle arguments, Description description) {
34         String testFilters = arguments.getString(OPTION_NAME);
35         // If the argument is unspecified, always return true.
36         if (testFilters == null) {
37             return true;
38         }
39 
40         String displayName = description.getDisplayName();
41 
42         // Test the display name against all filter arguments.
43         for (String testFilter : testFilters.split(",")) {
44             String[] filterComponents = testFilter.split("#");
45             if (filterComponents.length != 2) {
46                 Log.e(
47                         LOG_TAG,
48                         String.format(
49                                 "Invalid filter-tests instrumentation argument supplied, %s.",
50                                 testFilter));
51                 continue;
52             }
53 
54             String displayNameFilter =
55                     String.format(
56                             "%s(%s)",
57                             // method
58                             filterComponents[1],
59                             // class
60                             filterComponents[0]);
61             if (displayNameFilter.equals(displayName)) {
62                 return true;
63             }
64         }
65         // If the argument is specified and no matches, return false.
66         return false;
67     }
68 }
69