USB: Add test for UsbManager APIs

Make sure UsbManager APIs could only be accessed with required permission

Bug: 142372304
Test: atest UsbTests
Test: atest UsbManagerTests
Test: Forrest (L06700000406507070)
Change-Id: Ibe3337aaa965ba670c3ac363299612f367231f05
diff --git a/tests/UsbManagerTests/Android.bp b/tests/UsbManagerTests/Android.bp
new file mode 100644
index 0000000..a03c6e2
--- /dev/null
+++ b/tests/UsbManagerTests/Android.bp
@@ -0,0 +1,32 @@
+//
+// Copyright (C) 2019 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.
+//
+
+android_test {
+    name: "UsbManagerTests",
+    srcs: ["src/**/*.java"],
+    static_libs: [
+        "frameworks-base-testutils",
+        "androidx.test.rules",
+        "mockito-target-inline-minus-junit4",
+        "platform-test-annotations",
+        "truth-prebuilt",
+        "UsbManagerTestLib",
+    ],
+    jni_libs: ["libdexmakerjvmtiagent"],
+    certificate: "platform",
+    platform_apis: true,
+    test_suites: ["device-tests"],
+}
diff --git a/tests/UsbManagerTests/AndroidManifest.xml b/tests/UsbManagerTests/AndroidManifest.xml
new file mode 100644
index 0000000..4e0b790
--- /dev/null
+++ b/tests/UsbManagerTests/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.server.usbtest" >
+
+    <uses-permission android:name="android.permission.MANAGE_USB" />
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="com.android.server.usbtest"
+                     android:label="UsbManagerTests"/>
+</manifest>
diff --git a/tests/UsbManagerTests/AndroidTest.xml b/tests/UsbManagerTests/AndroidTest.xml
new file mode 100644
index 0000000..c6e22cd
--- /dev/null
+++ b/tests/UsbManagerTests/AndroidTest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+<configuration description="Runs Frameworks USB API instrumentation Tests.">
+    <target_preparer class="com.android.tradefed.targetprep.TestFilePushSetup"/>
+    <target_preparer class="com.android.tradefed.targetprep.TestAppInstallSetup">
+        <option name="test-file-name" value="UsbManagerTests.apk" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer"/>
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer"/>
+    <option name="test-suite-tag" value="apct"/>
+    <option name="test-tag" value="UsbManagerTests" />
+
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest">
+        <option name="package" value="com.android.server.usbtest"/>
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner"/>
+        <option name="hidden-api-checks" value="false"/>
+    </test>
+</configuration>
diff --git a/tests/UsbManagerTests/lib/Android.bp b/tests/UsbManagerTests/lib/Android.bp
new file mode 100644
index 0000000..3c5d91b
--- /dev/null
+++ b/tests/UsbManagerTests/lib/Android.bp
@@ -0,0 +1,34 @@
+//
+// Copyright (C) 2019 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.
+//
+
+android_library {
+    name: "UsbManagerTestLib",
+    srcs: ["src/**/*.java"],
+    static_libs: [
+        "frameworks-base-testutils",
+        "androidx.test.rules",
+        "mockito-target-inline-minus-junit4",
+        "platform-test-annotations",
+        "services.core",
+        "services.net",
+        "services.usb",
+        "truth-prebuilt",
+        "androidx.core_core",
+    ],
+    libs: [
+        "android.test.mock",
+    ],
+}
diff --git a/tests/UsbManagerTests/lib/AndroidManifest.xml b/tests/UsbManagerTests/lib/AndroidManifest.xml
new file mode 100644
index 0000000..c8b301c
--- /dev/null
+++ b/tests/UsbManagerTests/lib/AndroidManifest.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.server.usblib">
+
+    <application/>
+
+</manifest>
diff --git a/tests/UsbManagerTests/lib/src/com/android/server/usblib/UsbManagerTestLib.java b/tests/UsbManagerTests/lib/src/com/android/server/usblib/UsbManagerTestLib.java
new file mode 100644
index 0000000..782439f
--- /dev/null
+++ b/tests/UsbManagerTests/lib/src/com/android/server/usblib/UsbManagerTestLib.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2019 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.server.usblib;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.hardware.usb.UsbManager;
+import android.os.RemoteException;
+import android.util.Log;
+
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+/**
+ * Unit tests lib for {@link android.hardware.usb.UsbManager}.
+ */
+public class UsbManagerTestLib {
+    private static final String TAG = UsbManagerTestLib.class.getSimpleName();
+
+    private Context mContext;
+
+    private UsbManager mUsbManagerSys;
+    private UsbManager mUsbManagerMock;
+    @Mock private android.hardware.usb.IUsbManager mMockUsbService;
+
+    public UsbManagerTestLib(Context context) {
+        MockitoAnnotations.initMocks(this);
+        mContext = context;
+
+        assertNotNull(mUsbManagerSys = mContext.getSystemService(UsbManager.class));
+        assertNotNull(mUsbManagerMock = new UsbManager(mContext, mMockUsbService));
+    }
+
+    private long getCurrentFunctions() {
+        return mUsbManagerMock.getCurrentFunctions();
+    }
+
+    private void setCurrentFunctions(long functions) {
+        mUsbManagerMock.setCurrentFunctions(functions);
+    }
+
+    private long getCurrentFunctionsSys() {
+        return mUsbManagerSys.getCurrentFunctions();
+    }
+
+    private void setCurrentFunctionsSys(long functions) {
+        mUsbManagerSys.setCurrentFunctions(functions);
+    }
+
+    private void testSetGetCurrentFunctions_Matched(long functions) {
+        setCurrentFunctions(functions);
+        assertEquals("CurrentFunctions mismatched: ", functions, getCurrentFunctions());
+    }
+
+    private void testGetCurrentFunctionsMock_Matched(long functions) {
+        try {
+            when(mMockUsbService.getCurrentFunctions()).thenReturn(functions);
+
+            assertEquals("CurrentFunctions mismatched: ", functions, getCurrentFunctions());
+        } catch (RemoteException remEx) {
+            Log.w(TAG, "RemoteException");
+        }
+    }
+
+    private void testSetCurrentFunctionsMock_Matched(long functions) {
+        try {
+            setCurrentFunctions(functions);
+
+            verify(mMockUsbService).setCurrentFunctions(eq(functions));
+        } catch (RemoteException remEx) {
+            Log.w(TAG, "RemoteException");
+        }
+    }
+
+    public void testGetCurrentFunctionsSysEx() throws Exception {
+        getCurrentFunctionsSys();
+    }
+
+    public void testSetCurrentFunctionsSysEx(long functions) throws Exception {
+        setCurrentFunctionsSys(functions);
+    }
+
+    public void testGetCurrentFunctionsEx() throws Exception {
+        getCurrentFunctions();
+
+        verify(mMockUsbService).getCurrentFunctions();
+    }
+
+    public void testSetCurrentFunctionsEx(long functions) throws Exception {
+        setCurrentFunctions(functions);
+
+        verify(mMockUsbService).setCurrentFunctions(eq(functions));
+    }
+
+    public void testGetCurrentFunctions_shouldMatched() {
+        testGetCurrentFunctionsMock_Matched(UsbManager.FUNCTION_NONE);
+        testGetCurrentFunctionsMock_Matched(UsbManager.FUNCTION_MTP);
+        testGetCurrentFunctionsMock_Matched(UsbManager.FUNCTION_PTP);
+        testGetCurrentFunctionsMock_Matched(UsbManager.FUNCTION_MIDI);
+        testGetCurrentFunctionsMock_Matched(UsbManager.FUNCTION_RNDIS);
+    }
+
+    public void testSetCurrentFunctions_shouldMatched() {
+        testSetCurrentFunctionsMock_Matched(UsbManager.FUNCTION_NONE);
+        testSetCurrentFunctionsMock_Matched(UsbManager.FUNCTION_MTP);
+        testSetCurrentFunctionsMock_Matched(UsbManager.FUNCTION_PTP);
+        testSetCurrentFunctionsMock_Matched(UsbManager.FUNCTION_MIDI);
+        testSetCurrentFunctionsMock_Matched(UsbManager.FUNCTION_RNDIS);
+    }
+}
diff --git a/tests/UsbManagerTests/src/com/android/server/usbtest/UsbManagerApiTest.java b/tests/UsbManagerTests/src/com/android/server/usbtest/UsbManagerApiTest.java
new file mode 100644
index 0000000..8b21763
--- /dev/null
+++ b/tests/UsbManagerTests/src/com/android/server/usbtest/UsbManagerApiTest.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2019 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.server.usbtest;
+
+import android.content.Context;
+import android.hardware.usb.UsbManager;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import com.android.server.usblib.UsbManagerTestLib;
+
+/**
+ * Unit tests for {@link android.hardware.usb.UsbManager}.
+ * Note: MUST claimed MANAGE_USB permission in Manifest
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class UsbManagerApiTest {
+    private Context mContext;
+
+    private final UsbManagerTestLib mUsbManagerTestLib =
+            new UsbManagerTestLib(mContext = InstrumentationRegistry.getContext());
+
+    /**
+     * Verify NO SecurityException
+     * Go through System Server
+     */
+    @Test
+    public void testUsbApi_GetCurrentFunctionsSys_shouldNoSecurityException() throws Exception {
+        mUsbManagerTestLib.testGetCurrentFunctionsSysEx();
+    }
+
+    /**
+     * Verify NO SecurityException
+     * Go through System Server
+     */
+    @Test
+    public void testUsbApi_SetCurrentFunctionsSys_shouldNoSecurityException() throws Exception {
+        mUsbManagerTestLib.testSetCurrentFunctionsSysEx(UsbManager.FUNCTION_NONE);
+    }
+
+    /**
+     * Verify NO SecurityException
+     * Go through Direct API, will not be denied by @RequiresPermission annotation
+     */
+    @Test
+    public void testUsbApi_GetCurrentFunctions_shouldNoSecurityException() throws Exception {
+        mUsbManagerTestLib.testGetCurrentFunctionsEx();
+    }
+
+    /**
+     * Verify NO SecurityException
+     * Go through Direct API, will not be denied by @RequiresPermission annotation
+     */
+    @Test
+    public void testUsbApi_SetCurrentFunctions_shouldNoSecurityException() throws Exception {
+        mUsbManagerTestLib.testSetCurrentFunctionsEx(UsbManager.FUNCTION_NONE);
+    }
+
+    /**
+     * Verify API path from UsbManager to UsbService
+     */
+    @Test
+    public void testUsbApi_GetCurrentFunctions_shouldMatched() {
+        mUsbManagerTestLib.testGetCurrentFunctions_shouldMatched();
+    }
+
+    /**
+     * Verify API path from UsbManager to UsbService
+     */
+    @Test
+    public void testUsbApi_SetCurrentFunctions_shouldMatched() {
+        mUsbManagerTestLib.testSetCurrentFunctions_shouldMatched();
+    }
+}
diff --git a/tests/UsbTests/Android.bp b/tests/UsbTests/Android.bp
index 1b2cf63..7c2be9b 100644
--- a/tests/UsbTests/Android.bp
+++ b/tests/UsbTests/Android.bp
@@ -26,6 +26,7 @@
         "services.net",
         "services.usb",
         "truth-prebuilt",
+        "UsbManagerTestLib",
     ],
     jni_libs: ["libdexmakerjvmtiagent"],
     certificate: "platform",
diff --git a/tests/UsbTests/src/com/android/server/usb/UsbManagerNoPermTest.java b/tests/UsbTests/src/com/android/server/usb/UsbManagerNoPermTest.java
new file mode 100644
index 0000000..a0fd9d4
--- /dev/null
+++ b/tests/UsbTests/src/com/android/server/usb/UsbManagerNoPermTest.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2019 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.server.usb;
+
+import android.content.Context;
+import android.hardware.usb.UsbManager;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import com.android.server.usblib.UsbManagerTestLib;
+
+/**
+ * Unit tests for {@link android.hardware.usb.UsbManager}.
+ * Note: NOT claimed MANAGE_USB permission in Manifest
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class UsbManagerNoPermTest {
+    private Context mContext;
+
+    private final UsbManagerTestLib mUsbManagerTestLib =
+            new UsbManagerTestLib(mContext = InstrumentationRegistry.getContext());
+
+    /**
+     * Verify SecurityException resulting from required permissions missing
+     * Go through System Server
+     */
+    @Test(expected = SecurityException.class)
+    public void testUsbApi_GetCurrentFunctionsSys_OnSecurityException() throws Exception {
+        mUsbManagerTestLib.testGetCurrentFunctionsSysEx();
+    }
+
+    /**
+     * Verify SecurityException resulting from required permissions missing
+     * Go through System Server
+     */
+    @Test(expected = SecurityException.class)
+    public void testUsbApi_SetCurrentFunctionsSys_OnSecurityException() throws Exception {
+        mUsbManagerTestLib.testSetCurrentFunctionsSysEx(UsbManager.FUNCTION_NONE);
+    }
+
+    /**
+     * Verify SecurityException resulting from required permissions missing
+     * Go through Direct API, will not be denied by @RequiresPermission annotation
+     */
+    @Test(expected = SecurityException.class)
+    @Ignore
+    public void testUsbApi_GetCurrentFunctions_OnSecurityException() throws Exception {
+        mUsbManagerTestLib.testGetCurrentFunctionsEx();
+    }
+
+    /**
+     * Verify SecurityException resulting from required permissions missing
+     * Go through Direct API, will not be denied by @RequiresPermission annotation
+     */
+    @Test(expected = SecurityException.class)
+    @Ignore
+    public void testUsbApi_SetCurrentFunctions_OnSecurityException() throws Exception {
+        mUsbManagerTestLib.testSetCurrentFunctionsEx(UsbManager.FUNCTION_NONE);
+    }
+}