Merge "Ensure we close the classloader when done with it"
diff --git a/invocation_interfaces/com/android/tradefed/invoker/ExecutionFiles.java b/invocation_interfaces/com/android/tradefed/invoker/ExecutionFiles.java
index 55e0a33..43b4d16 100644
--- a/invocation_interfaces/com/android/tradefed/invoker/ExecutionFiles.java
+++ b/invocation_interfaces/com/android/tradefed/invoker/ExecutionFiles.java
@@ -121,6 +121,18 @@
         return this;
     }
 
+    /**
+     * Copies all of the mappings from the specified map to this map.
+     *
+     * @param copyFrom original {@link ExecutionFiles} to copy from.
+     * @return The final mapping
+     */
+    public ExecutionFiles putAll(ExecutionFiles copyFrom) {
+        mFiles.putAll(copyFrom.getAll());
+        mShouldNotDelete.addAll(copyFrom.mShouldNotDelete);
+        return this;
+    }
+
     /** Returns whether or not the map of properties is empty. */
     public boolean isEmpty() {
         return mFiles.isEmpty();
diff --git a/invocation_interfaces/com/android/tradefed/invoker/TestInformation.java b/invocation_interfaces/com/android/tradefed/invoker/TestInformation.java
index 5bebbea..a2b1d7f 100644
--- a/invocation_interfaces/com/android/tradefed/invoker/TestInformation.java
+++ b/invocation_interfaces/com/android/tradefed/invoker/TestInformation.java
@@ -60,7 +60,7 @@
         mDependenciesFolder = invocationInfo.mDependenciesFolder;
         if (copyExecFile) {
             mExecutionFiles = new ExecutionFiles();
-            mExecutionFiles.putAll(invocationInfo.executionFiles().getAll());
+            mExecutionFiles.putAll(invocationInfo.executionFiles());
         } else {
             mExecutionFiles = invocationInfo.mExecutionFiles;
         }
diff --git a/test_framework/com/android/tradefed/testtype/binary/ExecutableBaseTest.java b/test_framework/com/android/tradefed/testtype/binary/ExecutableBaseTest.java
index e6b9a16..074a9bb 100644
--- a/test_framework/com/android/tradefed/testtype/binary/ExecutableBaseTest.java
+++ b/test_framework/com/android/tradefed/testtype/binary/ExecutableBaseTest.java
@@ -29,6 +29,7 @@
 import com.android.tradefed.testtype.IRuntimeHintProvider;
 import com.android.tradefed.testtype.IShardableTest;
 import com.android.tradefed.testtype.ITestCollector;
+import com.android.tradefed.testtype.ITestFilterReceiver;
 import com.android.tradefed.util.StreamUtil;
 
 import java.io.File;
@@ -37,21 +38,41 @@
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
 import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 /** Base class for executable style of tests. For example: binaries, shell scripts. */
 public abstract class ExecutableBaseTest
-        implements IRemoteTest, IRuntimeHintProvider, ITestCollector, IShardableTest, IAbiReceiver {
+        implements IRemoteTest,
+                IRuntimeHintProvider,
+                ITestCollector,
+                IShardableTest,
+                IAbiReceiver,
+                ITestFilterReceiver {
 
     public static final String NO_BINARY_ERROR = "Binary %s does not exist.";
 
+    @Option(
+            name = "per-binary-timeout",
+            isTimeVal = true,
+            description = "Timeout applied to each binary for their execution.")
+    private long mTimeoutPerBinaryMs = 5 * 60 * 1000L;
+
     @Option(name = "binary", description = "Path to the binary to be run. Can be repeated.")
     private List<String> mBinaryPaths = new ArrayList<>();
 
     @Option(
-        name = "collect-tests-only",
-        description = "Only dry-run through the tests, do not actually run them."
-    )
+            name = "test-command-line",
+            description = "The test commands of each test names.",
+            requiredForRerun = true)
+    private Map<String, String> mTestCommands = new LinkedHashMap<>();
+
+    @Option(
+            name = "collect-tests-only",
+            description = "Only dry-run through the tests, do not actually run them.")
     private boolean mCollectTestsOnly = false;
 
     @Option(
@@ -63,22 +84,79 @@
 
     private IAbi mAbi;
     private TestInformation mTestInfo;
+    private Set<String> mIncludeFilters = new LinkedHashSet<>();
+    private Set<String> mExcludeFilters = new LinkedHashSet<>();
+
+    /** @return the timeout applied to each binary for their execution. */
+    protected long getTimeoutPerBinaryMs() {
+        return mTimeoutPerBinaryMs;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void addIncludeFilter(String filter) {
+        mIncludeFilters.add(filter);
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void addExcludeFilter(String filter) {
+        mExcludeFilters.add(filter);
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void addAllIncludeFilters(Set<String> filters) {
+        mIncludeFilters.addAll(filters);
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void addAllExcludeFilters(Set<String> filters) {
+        mExcludeFilters.addAll(filters);
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void clearIncludeFilters() {
+        mIncludeFilters.clear();
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void clearExcludeFilters() {
+        mExcludeFilters.clear();
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public Set<String> getIncludeFilters() {
+        return mIncludeFilters;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public Set<String> getExcludeFilters() {
+        return mExcludeFilters;
+    }
 
     @Override
-    public final void run(TestInformation testInfo, ITestInvocationListener listener)
+    public void run(TestInformation testInfo, ITestInvocationListener listener)
             throws DeviceNotAvailableException {
         mTestInfo = testInfo;
-        for (String binary : mBinaryPaths) {
-            String path = findBinary(binary);
+        Map<String, String> testCommands = getAllTestCommands();
+        for (String testName : testCommands.keySet()) {
+            String cmd = testCommands.get(testName);
+            String path = findBinary(cmd);
+            TestDescription description = new TestDescription(testName, testName);
+            if (shouldSkipCurrentTest(description)) continue;
             if (path == null) {
-                listener.testRunStarted(new File(binary).getName(), 0);
-                listener.testRunFailed(String.format(NO_BINARY_ERROR, binary));
+                listener.testRunStarted(testName, 0);
+                listener.testRunFailed(String.format(NO_BINARY_ERROR, cmd));
                 listener.testRunEnded(0L, new HashMap<String, Metric>());
             } else {
-                listener.testRunStarted(new File(path).getName(), 1);
+                listener.testRunStarted(testName, 1);
                 long startTimeMs = System.currentTimeMillis();
-                TestDescription description =
-                        new TestDescription(new File(path).getName(), new File(path).getName());
                 listener.testStarted(description);
                 try {
                     if (!mCollectTestsOnly) {
@@ -99,12 +177,33 @@
     }
 
     /**
+     * Check if current test should be skipped.
+     *
+     * @param description The test in progress.
+     * @return true if the test should be skipped.
+     */
+    private boolean shouldSkipCurrentTest(TestDescription description) {
+        // Force to skip any test not listed in include filters, or listed in exclude filters.
+        // exclude filters have highest priority.
+        String testName = description.getTestName();
+        if (mExcludeFilters.contains(testName)
+                || mExcludeFilters.contains(description.toString())) {
+            return true;
+        }
+        if (!mIncludeFilters.isEmpty()) {
+            return !mIncludeFilters.contains(testName)
+                    && !mExcludeFilters.contains(description.toString());
+        }
+        return false;
+    }
+
+    /**
      * Search for the binary to be able to run it.
      *
      * @param binary the path of the binary or simply the binary name.
      * @return The path to the binary, or null if not found.
      */
-    public abstract String findBinary(String binary);
+    public abstract String findBinary(String binary) throws DeviceNotAvailableException;
 
     /**
      * Actually run the binary at the given path.
@@ -180,4 +279,17 @@
         }
         return shard;
     }
+
+    /**
+     * Convert mBinaryPaths to mTestCommands for consistency.
+     *
+     * @return a Map{@link LinkedHashMap}<String, String> of testCommands.
+     */
+    private Map<String, String> getAllTestCommands() {
+        Map<String, String> testCommands = new LinkedHashMap<>(mTestCommands);
+        for (String binary : mBinaryPaths) {
+            testCommands.put(new File(binary).getName(), binary);
+        }
+        return testCommands;
+    }
 }
diff --git a/test_framework/com/android/tradefed/testtype/binary/ExecutableHostTest.java b/test_framework/com/android/tradefed/testtype/binary/ExecutableHostTest.java
index 7c3c738..3d44499 100644
--- a/test_framework/com/android/tradefed/testtype/binary/ExecutableHostTest.java
+++ b/test_framework/com/android/tradefed/testtype/binary/ExecutableHostTest.java
@@ -56,13 +56,6 @@
     private static final String LOG_STDERR_TAG = "-binary-stderr-";
 
     @Option(
-        name = "per-binary-timeout",
-        isTimeVal = true,
-        description = "Timeout applied to each binary for their execution."
-    )
-    private long mTimeoutPerBinaryMs = 5 * 60 * 1000L;
-
-    @Option(
         name = "relative-path-execution",
         description =
                 "Some scripts assume a relative location to their tests file, this allows to"
@@ -135,7 +128,7 @@
                 FileOutputStream stderrStream = new FileOutputStream(stderr); ) {
             CommandResult res =
                     runUtil.runTimedCmd(
-                            mTimeoutPerBinaryMs,
+                            getTimeoutPerBinaryMs(),
                             stdoutStream,
                             stderrStream,
                             command.toArray(new String[0]));
diff --git a/test_framework/com/android/tradefed/testtype/binary/ExecutableTargetTest.java b/test_framework/com/android/tradefed/testtype/binary/ExecutableTargetTest.java
new file mode 100644
index 0000000..85e7ae8
--- /dev/null
+++ b/test_framework/com/android/tradefed/testtype/binary/ExecutableTargetTest.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.tradefed.testtype.binary;
+
+import com.android.tradefed.config.OptionClass;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.result.TestDescription;
+import com.android.tradefed.testtype.IDeviceTest;
+import com.android.tradefed.util.CommandResult;
+import com.android.tradefed.util.CommandStatus;
+
+import java.io.IOException;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Test runner for executable running on the target. The runner implements {@link IDeviceTest} since
+ * the binary run on a device.
+ */
+@OptionClass(alias = "executable-target-test")
+public class ExecutableTargetTest extends ExecutableBaseTest implements IDeviceTest {
+
+    private ITestDevice mDevice = null;
+
+    /** {@inheritDoc} */
+    @Override
+    public void setDevice(ITestDevice device) {
+        mDevice = device;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public ITestDevice getDevice() {
+        return mDevice;
+    }
+
+    @Override
+    public String findBinary(String binary) throws DeviceNotAvailableException {
+        for (String path : binary.split(" ")) {
+            if (mDevice.isExecutable(path)) return binary;
+        }
+        return null;
+    }
+
+    @Override
+    public void runBinary(
+            String binaryPath, ITestInvocationListener listener, TestDescription description)
+            throws DeviceNotAvailableException, IOException {
+        if (mDevice == null) {
+            throw new IllegalArgumentException("Device has not been set");
+        }
+        CommandResult result =
+                mDevice.executeShellV2Command(
+                        binaryPath, getTimeoutPerBinaryMs(), TimeUnit.MILLISECONDS);
+        checkCommandResult(result, listener, description);
+    }
+
+    /**
+     * Check the result of the test command.
+     *
+     * @param result test result of the command {@link CommandResult}
+     * @param listener the {@link ITestInvocationListener}
+     * @param description The test in progress.
+     */
+    protected void checkCommandResult(
+            CommandResult result, ITestInvocationListener listener, TestDescription description) {
+        if (!CommandStatus.SUCCESS.equals(result.getStatus())) {
+            String error_message;
+            error_message =
+                    String.format(
+                            "binary returned non-zero. Exit code: %d, stderr: %s, stdout: %s",
+                            result.getExitCode(), result.getStderr(), result.getStdout());
+            listener.testFailed(description, error_message);
+        }
+    }
+}
diff --git a/tests/src/com/android/tradefed/UnitTests.java b/tests/src/com/android/tradefed/UnitTests.java
index 3cd8928..ad894a9 100644
--- a/tests/src/com/android/tradefed/UnitTests.java
+++ b/tests/src/com/android/tradefed/UnitTests.java
@@ -280,6 +280,7 @@
 import com.android.tradefed.testtype.PythonUnitTestRunnerTest;
 import com.android.tradefed.testtype.TfTestLauncherTest;
 import com.android.tradefed.testtype.binary.ExecutableHostTestTest;
+import com.android.tradefed.testtype.binary.ExecutableTargetTestTest;
 import com.android.tradefed.testtype.host.CoverageMeasurementForwarderTest;
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4TestTest;
 import com.android.tradefed.testtype.junit4.DeviceParameterizedRunnerTest;
@@ -750,6 +751,7 @@
 
     // testtype/binary
     ExecutableHostTestTest.class,
+    ExecutableTargetTestTest.class,
 
     // testtype/junit4
     BaseHostJUnit4TestTest.class,
diff --git a/tests/src/com/android/tradefed/testtype/binary/ExecutableTargetTestTest.java b/tests/src/com/android/tradefed/testtype/binary/ExecutableTargetTestTest.java
new file mode 100644
index 0000000..69bbd96
--- /dev/null
+++ b/tests/src/com/android/tradefed/testtype/binary/ExecutableTargetTestTest.java
@@ -0,0 +1,306 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.tradefed.testtype.binary;
+
+import static org.mockito.ArgumentMatchers.eq;
+
+import com.android.tradefed.config.ConfigurationException;
+import com.android.tradefed.config.OptionSetter;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.invoker.InvocationContext;
+import com.android.tradefed.invoker.TestInformation;
+import com.android.tradefed.metrics.proto.MetricMeasurement;
+import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.result.TestDescription;
+import com.android.tradefed.util.CommandResult;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.Mockito;
+
+import java.util.HashMap;
+
+/** Unit tests for {@link com.android.tradefed.testtype.binary.ExecutableTargetTest}. */
+@RunWith(JUnit4.class)
+public class ExecutableTargetTestTest {
+    private final String testName1 = "testName1";
+    private final String testCmd1 = "cmd1";
+    private final String testName2 = "testName2";
+    private final String testCmd2 = "cmd2";
+    private final String testName3 = "testName3";
+    private final String testCmd3 = "cmd3";
+    private static final String NO_BINARY_ERROR = "Binary %s does not exist.";
+    private static final String ERROR_MESSAGE = "binary returned non-zero exit code.";
+
+    private ITestInvocationListener mListener = null;
+    private ITestDevice mMockITestDevice = null;
+    private ExecutableTargetTest mExecutableTargetTest;
+
+    private TestInformation mTestInfo;
+
+    /** Helper to initialize the various EasyMocks we'll need. */
+    @Before
+    public void setUp() throws Exception {
+        mListener = Mockito.mock(ITestInvocationListener.class);
+        mMockITestDevice = Mockito.mock(ITestDevice.class);
+        InvocationContext context = new InvocationContext();
+        context.addAllocatedDevice("device", mMockITestDevice);
+        mTestInfo = TestInformation.newBuilder().setInvocationContext(context).build();
+        mTestInfo = TestInformation.newBuilder().build();
+    }
+
+    /** Test the run method for a couple commands and success */
+    @Test
+    public void testRun_cmdSuccess() throws DeviceNotAvailableException, ConfigurationException {
+        mExecutableTargetTest =
+                new ExecutableTargetTest() {
+                    @Override
+                    public String findBinary(String binary) {
+                        return binary;
+                    }
+
+                    @Override
+                    protected void checkCommandResult(
+                            CommandResult result,
+                            ITestInvocationListener listener,
+                            TestDescription description) {}
+                };
+        mExecutableTargetTest.setDevice(mMockITestDevice);
+        // Set test commands
+        OptionSetter setter = new OptionSetter(mExecutableTargetTest);
+        setter.setOptionValue("test-command-line", testName1, testCmd1);
+        setter.setOptionValue("test-command-line", testName2, testCmd2);
+        mExecutableTargetTest.run(mTestInfo, mListener);
+        // run cmd1 test
+        TestDescription testDescription = new TestDescription(testName1, testName1);
+        Mockito.verify(mListener, Mockito.times(1)).testRunStarted(eq(testName1), eq(1));
+        Mockito.verify(mListener, Mockito.times(1)).testStarted(Mockito.eq(testDescription));
+        Mockito.verify(mListener, Mockito.times(1))
+                .testEnded(
+                        Mockito.eq(testDescription),
+                        Mockito.eq(new HashMap<String, MetricMeasurement.Metric>()));
+        // run cmd2 test
+        TestDescription testDescription2 = new TestDescription(testName2, testName2);
+        Mockito.verify(mListener, Mockito.times(1)).testRunStarted(eq(testName2), eq(1));
+        Mockito.verify(mListener, Mockito.times(1)).testStarted(Mockito.eq(testDescription2));
+        Mockito.verify(mListener, Mockito.times(1))
+                .testEnded(
+                        Mockito.eq(testDescription2),
+                        Mockito.eq(new HashMap<String, MetricMeasurement.Metric>()));
+        Mockito.verify(mListener, Mockito.times(2))
+                .testRunEnded(
+                        Mockito.anyLong(),
+                        Mockito.<HashMap<String, MetricMeasurement.Metric>>any());
+    }
+
+    /** Test the run method for a couple commands but binary path not found. */
+    @Test
+    public void testRun_pathNotExist() throws DeviceNotAvailableException, ConfigurationException {
+        mExecutableTargetTest =
+                new ExecutableTargetTest() {
+                    @Override
+                    public String findBinary(String binary) {
+                        return null;
+                    }
+
+                    @Override
+                    protected void checkCommandResult(
+                            CommandResult result,
+                            ITestInvocationListener listener,
+                            TestDescription description) {}
+                };
+        mExecutableTargetTest.setDevice(mMockITestDevice);
+        // Set test commands
+        OptionSetter setter = new OptionSetter(mExecutableTargetTest);
+        setter.setOptionValue("test-command-line", testName1, testCmd1);
+        setter.setOptionValue("test-command-line", testName2, testCmd2);
+        mExecutableTargetTest.run(mTestInfo, mListener);
+        // run cmd1 test
+        Mockito.verify(mListener, Mockito.times(0)).testRunStarted(eq(testName1), eq(1));
+        Mockito.verify(mListener, Mockito.times(1))
+                .testRunFailed(String.format(NO_BINARY_ERROR, testCmd1));
+        // run cmd2 test
+        Mockito.verify(mListener, Mockito.times(0)).testRunStarted(eq(testName2), eq(1));
+        Mockito.verify(mListener, Mockito.times(1))
+                .testRunFailed(String.format(NO_BINARY_ERROR, testCmd2));
+        Mockito.verify(mListener, Mockito.times(2))
+                .testRunEnded(
+                        Mockito.anyLong(),
+                        Mockito.<HashMap<String, MetricMeasurement.Metric>>any());
+    }
+
+    /** Test the run method for a couple commands and commands failed. */
+    @Test
+    public void testRun_cmdFailed() throws DeviceNotAvailableException, ConfigurationException {
+        mExecutableTargetTest =
+                new ExecutableTargetTest() {
+                    @Override
+                    public String findBinary(String binary) {
+                        return binary;
+                    }
+
+                    @Override
+                    protected void checkCommandResult(
+                            CommandResult result,
+                            ITestInvocationListener listener,
+                            TestDescription description) {
+                        listener.testFailed(description, ERROR_MESSAGE);
+                    }
+                };
+        mExecutableTargetTest.setDevice(mMockITestDevice);
+        // Set test commands
+        OptionSetter setter = new OptionSetter(mExecutableTargetTest);
+        setter.setOptionValue("test-command-line", testName1, testCmd1);
+        setter.setOptionValue("test-command-line", testName2, testCmd2);
+        mExecutableTargetTest.run(mTestInfo, mListener);
+        // run cmd1 test
+        TestDescription testDescription = new TestDescription(testName1, testName1);
+        Mockito.verify(mListener, Mockito.times(1)).testRunStarted(eq(testName1), eq(1));
+        Mockito.verify(mListener, Mockito.times(1)).testStarted(Mockito.eq(testDescription));
+        Mockito.verify(mListener, Mockito.times(1)).testFailed(testDescription, ERROR_MESSAGE);
+        Mockito.verify(mListener, Mockito.times(1))
+                .testEnded(
+                        Mockito.eq(testDescription),
+                        Mockito.eq(new HashMap<String, MetricMeasurement.Metric>()));
+        // run cmd2 test
+        TestDescription testDescription2 = new TestDescription(testName2, testName2);
+        Mockito.verify(mListener, Mockito.times(1)).testRunStarted(eq(testName2), eq(1));
+        Mockito.verify(mListener, Mockito.times(1)).testStarted(Mockito.eq(testDescription2));
+        Mockito.verify(mListener, Mockito.times(1)).testFailed(testDescription2, ERROR_MESSAGE);
+        Mockito.verify(mListener, Mockito.times(1))
+                .testEnded(
+                        Mockito.eq(testDescription2),
+                        Mockito.eq(new HashMap<String, MetricMeasurement.Metric>()));
+        Mockito.verify(mListener, Mockito.times(2))
+                .testRunEnded(
+                        Mockito.anyLong(),
+                        Mockito.<HashMap<String, MetricMeasurement.Metric>>any());
+    }
+
+    /** Test the run method for a couple commands with ExcludeFilters */
+    @Test
+    public void testRun_addExcludeFilter()
+            throws DeviceNotAvailableException, ConfigurationException {
+        mExecutableTargetTest =
+                new ExecutableTargetTest() {
+                    @Override
+                    public String findBinary(String binary) {
+                        return binary;
+                    }
+
+                    @Override
+                    protected void checkCommandResult(
+                            CommandResult result,
+                            ITestInvocationListener listener,
+                            TestDescription description) {}
+                };
+        mExecutableTargetTest.setDevice(mMockITestDevice);
+        // Set test commands
+        OptionSetter setter = new OptionSetter(mExecutableTargetTest);
+        setter.setOptionValue("test-command-line", testName1, testCmd1);
+        setter.setOptionValue("test-command-line", testName2, testCmd2);
+        setter.setOptionValue("test-command-line", testName3, testCmd3);
+        TestDescription testDescription = new TestDescription(testName1, testName1);
+        TestDescription testDescription2 = new TestDescription(testName2, testName2);
+        TestDescription testDescription3 = new TestDescription(testName3, testName3);
+        mExecutableTargetTest.addExcludeFilter(testName1);
+        mExecutableTargetTest.addExcludeFilter(testDescription3.toString());
+        mExecutableTargetTest.run(mTestInfo, mListener);
+        // testName1 should NOT run.
+        Mockito.verify(mListener, Mockito.never()).testRunStarted(eq(testName1), eq(1));
+        Mockito.verify(mListener, Mockito.never()).testStarted(Mockito.eq(testDescription));
+        Mockito.verify(mListener, Mockito.never())
+                .testEnded(
+                        Mockito.eq(testDescription),
+                        Mockito.eq(new HashMap<String, MetricMeasurement.Metric>()));
+        // run cmd2 test
+        Mockito.verify(mListener, Mockito.times(1)).testRunStarted(eq(testName2), eq(1));
+        Mockito.verify(mListener, Mockito.times(1)).testStarted(Mockito.eq(testDescription2));
+        Mockito.verify(mListener, Mockito.times(1))
+                .testEnded(
+                        Mockito.eq(testDescription2),
+                        Mockito.eq(new HashMap<String, MetricMeasurement.Metric>()));
+        Mockito.verify(mListener, Mockito.times(1))
+                .testRunEnded(
+                        Mockito.anyLong(),
+                        Mockito.<HashMap<String, MetricMeasurement.Metric>>any());
+        // testName3 should NOT run.
+        Mockito.verify(mListener, Mockito.never()).testRunStarted(eq(testName3), eq(1));
+        Mockito.verify(mListener, Mockito.never()).testStarted(Mockito.eq(testDescription3));
+        Mockito.verify(mListener, Mockito.never())
+                .testEnded(
+                        Mockito.eq(testDescription3),
+                        Mockito.eq(new HashMap<String, MetricMeasurement.Metric>()));
+    }
+
+    /** Test the run method for a couple commands with IncludeFilter */
+    @Test
+    public void testRun_addIncludeFilter()
+            throws DeviceNotAvailableException, ConfigurationException {
+        mExecutableTargetTest =
+                new ExecutableTargetTest() {
+                    @Override
+                    public String findBinary(String binary) {
+                        return binary;
+                    }
+
+                    @Override
+                    protected void checkCommandResult(
+                            CommandResult result,
+                            ITestInvocationListener listener,
+                            TestDescription description) {}
+                };
+        mExecutableTargetTest.setDevice(mMockITestDevice);
+        // Set test commands
+        OptionSetter setter = new OptionSetter(mExecutableTargetTest);
+        setter.setOptionValue("test-command-line", testName1, testCmd1);
+        setter.setOptionValue("test-command-line", testName2, testCmd2);
+        setter.setOptionValue("test-command-line", testName3, testCmd3);
+        TestDescription testDescription = new TestDescription(testName1, testName1);
+        TestDescription testDescription2 = new TestDescription(testName2, testName2);
+        TestDescription testDescription3 = new TestDescription(testName3, testName3);
+        mExecutableTargetTest.addIncludeFilter(testName2);
+        mExecutableTargetTest.run(mTestInfo, mListener);
+        // testName1 should NOT run.
+        Mockito.verify(mListener, Mockito.never()).testRunStarted(eq(testName1), eq(1));
+        Mockito.verify(mListener, Mockito.never()).testStarted(Mockito.eq(testDescription));
+        Mockito.verify(mListener, Mockito.never())
+                .testEnded(
+                        Mockito.eq(testDescription),
+                        Mockito.eq(new HashMap<String, MetricMeasurement.Metric>()));
+        // run cmd2 test
+        Mockito.verify(mListener, Mockito.times(1)).testRunStarted(eq(testName2), eq(1));
+        Mockito.verify(mListener, Mockito.times(1)).testStarted(Mockito.eq(testDescription2));
+        Mockito.verify(mListener, Mockito.times(1))
+                .testEnded(
+                        Mockito.eq(testDescription2),
+                        Mockito.eq(new HashMap<String, MetricMeasurement.Metric>()));
+        Mockito.verify(mListener, Mockito.times(1))
+                .testRunEnded(
+                        Mockito.anyLong(),
+                        Mockito.<HashMap<String, MetricMeasurement.Metric>>any());
+        // testName3 should NOT run.
+        Mockito.verify(mListener, Mockito.never()).testRunStarted(eq(testName3), eq(1));
+        Mockito.verify(mListener, Mockito.never()).testStarted(Mockito.eq(testDescription3));
+        Mockito.verify(mListener, Mockito.never())
+                .testEnded(
+                        Mockito.eq(testDescription3),
+                        Mockito.eq(new HashMap<String, MetricMeasurement.Metric>()));
+    }
+}