OSDN Git Service

Extract test utility class.
authorDaichi Hirono <hirono@google.com>
Wed, 2 Dec 2015 03:20:25 +0000 (12:20 +0900)
committerDaichi Hirono <hirono@google.com>
Wed, 2 Dec 2015 03:38:49 +0000 (12:38 +0900)
Change-Id: I8505ab13ceccf32e7a9b6817f84a66766098b09e

packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpManagerTest.java
packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestResultInstrumentation.java
packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestUtil.java [new file with mode: 0644]

index ed6ee7e..a045d06 100644 (file)
 
 package com.android.mtp;
 
-import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
 import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
 import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbDeviceConnection;
 import android.hardware.usb.UsbManager;
 import android.os.CancellationSignal;
 import android.os.OperationCanceledException;
 import android.test.InstrumentationTestCase;
 
 import java.io.IOException;
-import java.util.HashMap;
-import java.util.concurrent.CountDownLatch;
 
 @RealDeviceTest
 public class MtpManagerTest extends InstrumentationTestCase {
-    private static final String ACTION_USB_PERMISSION =
-            "com.android.mtp.USB_PERMISSION";
+
     private static final int TIMEOUT_MS = 1000;
     UsbManager mUsbManager;
     MtpManager mManager;
@@ -45,20 +37,8 @@ public class MtpManagerTest extends InstrumentationTestCase {
     @Override
     public void setUp() throws Exception {
         mUsbManager = getContext().getSystemService(UsbManager.class);
-        for (int i = 0; i < 2; i++) {
-            mUsbDevice = findDevice();
-            mManager = new MtpManager(getContext());
-            mManager.openDevice(mUsbDevice.getDeviceId());
-            try {
-                waitForStorages(mManager, mUsbDevice.getDeviceId());
-                return;
-            } catch (IOException exp) {
-                // When the MTP device is Android, and it changes the USB device type from
-                // "Charging" to "MTP", the device ID will be updated. We need to find a device
-                // again.
-                continue;
-            }
-        }
+        mManager = new MtpManager(getContext());
+        mUsbDevice = TestUtil.setupMtpDevice(getInstrumentation(), mUsbManager, mManager);
     }
 
     @Override
@@ -66,6 +46,11 @@ public class MtpManagerTest extends InstrumentationTestCase {
         mManager.closeDevice(mUsbDevice.getDeviceId());
     }
 
+    @Override
+    public TestResultInstrumentation getInstrumentation() {
+        return (TestResultInstrumentation) super.getInstrumentation();
+    }
+
     public void testCancelEvent() throws Exception {
         final CancellationSignal signal = new CancellationSignal();
         final Thread thread = new Thread() {
@@ -74,7 +59,7 @@ public class MtpManagerTest extends InstrumentationTestCase {
                 try {
                     mManager.readEvent(mUsbDevice.getDeviceId(), signal);
                 } catch (OperationCanceledException | IOException e) {
-                    show(e.getMessage());
+                    getInstrumentation().show(e.getMessage());
                 }
             }
         };
@@ -84,72 +69,6 @@ public class MtpManagerTest extends InstrumentationTestCase {
         thread.join(TIMEOUT_MS);
     }
 
-    private void requestPermission(UsbDevice device) throws InterruptedException {
-        if (mUsbManager.hasPermission(device)) {
-            return;
-        }
-        final CountDownLatch latch = new CountDownLatch(1);
-        final BroadcastReceiver receiver = new BroadcastReceiver() {
-            @Override
-            public void onReceive(Context context, Intent intent) {
-                latch.countDown();
-                getInstrumentation().getTargetContext().unregisterReceiver(this);
-            }
-        };
-        getInstrumentation().getTargetContext().registerReceiver(
-                receiver, new IntentFilter(ACTION_USB_PERMISSION));
-        mUsbManager.requestPermission(device, PendingIntent.getBroadcast(
-                getInstrumentation().getTargetContext(),
-                0 /* requstCode */,
-                new Intent(ACTION_USB_PERMISSION),
-                0 /* flags */));
-        latch.await();
-        assertTrue(mUsbManager.hasPermission(device));
-    }
-
-    private UsbDevice findDevice() throws InterruptedException {
-        while (true) {
-            final HashMap<String,UsbDevice> devices = mUsbManager.getDeviceList();
-            if (devices.size() == 0) {
-                show("Wait for devices.");
-                Thread.sleep(1000);
-                continue;
-            }
-            final UsbDevice device = devices.values().iterator().next();
-            requestPermission(device);
-            final UsbDeviceConnection connection = mUsbManager.openDevice(device);
-            if (connection == null) {
-                fail("Cannot open USB connection.");
-            }
-            for (int i = 0; i < device.getInterfaceCount(); i++) {
-                // Since the test runs real environment, we need to call claim interface with
-                // force = true to rob interfaces from other applications.
-                connection.claimInterface(device.getInterface(i), true);
-                connection.releaseInterface(device.getInterface(i));
-            }
-            connection.close();
-            return device;
-        }
-    }
-
-    private void waitForStorages(MtpManager manager, int deviceId) throws Exception {
-        while (true) {
-            if (manager.getRoots(deviceId).length == 0) {
-                show("Wait for storages.");
-                Thread.sleep(1000);
-                continue;
-            }
-            return;
-        }
-    }
-
-    private void show(String message) {
-        if (!(getInstrumentation() instanceof TestResultInstrumentation)) {
-            return;
-        }
-        ((TestResultInstrumentation) getInstrumentation()).show(message);
-    }
-
     private Context getContext() {
         return getInstrumentation().getContext();
     }
index 0fb0f34..3e64f9a 100644 (file)
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2015 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.mtp;
 
 import android.os.Bundle;
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestUtil.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/TestUtil.java
new file mode 100644 (file)
index 0000000..e6c12cb
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2015 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.mtp;
+
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.hardware.usb.UsbDevice;
+import android.hardware.usb.UsbDeviceConnection;
+import android.hardware.usb.UsbManager;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+import junit.framework.Assert;
+
+/**
+ * Static utility methods for testing.
+ */
+class TestUtil {
+    private static final String ACTION_USB_PERMISSION =
+            "com.android.mtp.USB_PERMISSION";
+
+    private TestUtil() {}
+
+    /**
+     * Requests permission for a MTP device and returns the first MTP device that has at least one
+     * storage.
+     * @throws Exception
+     */
+    static UsbDevice setupMtpDevice(
+            TestResultInstrumentation instrumentation,
+            UsbManager usbManager,
+            MtpManager manager) throws Exception {
+        for (int i = 0; i < 2; i++) {
+            final UsbDevice device = findMtpDevice(instrumentation, usbManager);
+            manager.openDevice(device.getDeviceId());
+            try {
+                waitForStorages(instrumentation, manager, device.getDeviceId());
+                return device;
+            } catch (IOException exp) {
+                // When the MTP device is Android, and it changes the USB device type from
+                // "Charging" to "MTP", the device ID will be updated. We need to find a device
+                // again.
+                continue;
+            }
+        }
+        throw new IOException("Failed to obtain MTP devices");
+    }
+
+    private static UsbDevice findMtpDevice(
+            TestResultInstrumentation instrumentation,
+            UsbManager usbManager) throws InterruptedException {
+        while (true) {
+            final HashMap<String,UsbDevice> devices = usbManager.getDeviceList();
+            if (devices.size() == 0) {
+                instrumentation.show("Wait for devices.");
+                Thread.sleep(1000);
+                continue;
+            }
+            final UsbDevice device = devices.values().iterator().next();
+            requestPermission(instrumentation, usbManager, device);
+            final UsbDeviceConnection connection = usbManager.openDevice(device);
+            if (connection == null) {
+                Assert.fail("Cannot open USB connection.");
+                return null;
+            }
+            for (int i = 0; i < device.getInterfaceCount(); i++) {
+                // Since the test runs real environment, we need to call claim interface with
+                // force = true to rob interfaces from other applications.
+                connection.claimInterface(device.getInterface(i), true);
+                connection.releaseInterface(device.getInterface(i));
+            }
+            connection.close();
+            return device;
+        }
+    }
+
+    private static void requestPermission(
+            final TestResultInstrumentation instrumentation,
+            UsbManager usbManager,
+            UsbDevice device) throws InterruptedException {
+        if (usbManager.hasPermission(device)) {
+            return;
+        }
+        final CountDownLatch latch = new CountDownLatch(1);
+        final BroadcastReceiver receiver = new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                latch.countDown();
+                instrumentation.getTargetContext().unregisterReceiver(this);
+            }
+        };
+        instrumentation.getTargetContext().registerReceiver(
+                receiver, new IntentFilter(ACTION_USB_PERMISSION));
+        usbManager.requestPermission(device, PendingIntent.getBroadcast(
+                instrumentation.getTargetContext(),
+                0 /* requstCode */,
+                new Intent(ACTION_USB_PERMISSION),
+                0 /* flags */));
+        latch.await();
+        Assert.assertTrue(usbManager.hasPermission(device));
+    }
+
+    private static void waitForStorages(
+            TestResultInstrumentation instrumentation,
+            MtpManager manager,
+            int deviceId) throws Exception {
+        while (true) {
+            if (manager.getRoots(deviceId).length == 0) {
+                instrumentation.show("Wait for storages.");
+                Thread.sleep(1000);
+                continue;
+            }
+            return;
+        }
+    }
+}