1 /*
2  * Copyright (C) 2016 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.cts.documentclient;
18 
19 import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
20 
21 import java.io.ByteArrayOutputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 
26 import com.android.cts.documentclient.MyActivity.Result;
27 
28 import android.app.Activity;
29 import android.content.ContentResolver;
30 import android.content.Intent;
31 import android.content.pm.PackageManager;
32 import android.content.pm.ResolveInfo;
33 import android.content.res.AssetFileDescriptor;
34 import android.content.res.AssetFileDescriptor.AutoCloseInputStream;
35 import android.database.Cursor;
36 import android.net.Uri;
37 import android.support.test.uiautomator.Configurator;
38 import android.support.test.uiautomator.UiDevice;
39 import android.test.InstrumentationTestCase;
40 import android.text.format.DateUtils;
41 import android.util.Log;
42 import android.view.MotionEvent;
43 
44 /**
45  * Base class for DocumentsUI test cases.
46  */
47 abstract class DocumentsClientTestCase extends InstrumentationTestCase {
48     protected static final long TIMEOUT = 30 * DateUtils.SECOND_IN_MILLIS;
49     protected static final int REQUEST_CODE = 42;
50 
51     static final String PROVIDER_PACKAGE = "com.android.cts.documentprovider";
52 
53     private static final String TAG = "DocumentsClientTestCase";
54 
55     protected UiDevice mDevice;
56     protected MyActivity mActivity;
57 
58     private String mDocumentsUiPackageId;
59 
60     private static final String COMPONENT_NAME_DUMMY_IME = "com.android.cts.dummyime/.CtsDummyIme";
61 
62     @Override
setUp()63     public void setUp() throws Exception {
64         super.setUp();
65 
66         final PackageManager pm = getInstrumentation().getContext().getPackageManager();
67 
68         final Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
69         intent.addCategory(Intent.CATEGORY_OPENABLE);
70         intent.setType("*/*");
71         final ResolveInfo ri = pm.resolveActivity(intent, 0);
72         mDocumentsUiPackageId = ri.activityInfo.packageName;
73 
74 
75         // Wake up the device and dismiss the keyguard before the test starts.
76         executeShellCommand("input keyevent KEYCODE_WAKEUP");
77         executeShellCommand("wm dismiss-keyguard");
78 
79         Configurator.getInstance().setToolType(MotionEvent.TOOL_TYPE_FINGER);
80 
81         // Disable IME's to avoid virtual keyboards from showing up. Occasionally IME draws some UI
82         // controls out of its boundary for some first time setup that obscures the text edit and/or
83         // save/select button. This will constantly fail some of our tests.
84         enableDummyIme();
85 
86         mDevice = UiDevice.getInstance(getInstrumentation());
87         mActivity = launchActivity(getInstrumentation().getTargetContext().getPackageName(),
88                 MyActivity.class, null);
89         mDevice.waitForIdle();
90     }
91 
92     @Override
tearDown()93     public void tearDown() throws Exception {
94         super.tearDown();
95         mActivity.finish();
96 
97         executeShellCommand("ime reset");
98     }
99 
getDocumentsUiPackageId()100     protected String getDocumentsUiPackageId() {
101         return mDocumentsUiPackageId;
102     }
103 
getColumn(Uri uri, String column)104     protected String getColumn(Uri uri, String column) {
105         final ContentResolver resolver = getInstrumentation().getContext().getContentResolver();
106         final Cursor cursor = resolver.query(uri, new String[] { column }, null, null, null);
107         try {
108             assertTrue(cursor.moveToFirst());
109             return cursor.getString(0);
110         } finally {
111             cursor.close();
112         }
113     }
114 
readFully(Uri uri)115     protected byte[] readFully(Uri uri) throws IOException {
116         final InputStream in = getInstrumentation().getContext().getContentResolver()
117                 .openInputStream(uri);
118         return readFully(in);
119     }
120 
readTypedFully(Uri uri, String mimeType)121     protected byte[] readTypedFully(Uri uri, String mimeType) throws IOException {
122         final AssetFileDescriptor descriptor =
123                 getInstrumentation().getContext().getContentResolver()
124                         .openTypedAssetFileDescriptor(uri, mimeType, null, null);
125         try (AutoCloseInputStream in = new AutoCloseInputStream(descriptor)) {
126             return readFully(in);
127         }
128     }
129 
readFully(InputStream in)130     protected byte[] readFully(InputStream in) throws IOException {
131         try {
132             ByteArrayOutputStream bytes = new ByteArrayOutputStream();
133             byte[] buffer = new byte[1024];
134             int count;
135             while ((count = in.read(buffer)) != -1) {
136                 bytes.write(buffer, 0, count);
137             }
138             return bytes.toByteArray();
139         } finally {
140             in.close();
141         }
142     }
143 
writeFully(Uri uri, byte[] data)144     protected void writeFully(Uri uri, byte[] data) throws IOException {
145         OutputStream out = getInstrumentation().getContext().getContentResolver()
146                 .openOutputStream(uri);
147         try {
148             out.write(data);
149         } finally {
150             out.close();
151         }
152     }
153 
supportedHardware()154     protected boolean supportedHardware() {
155         final PackageManager pm = getInstrumentation().getContext().getPackageManager();
156         if (pm.hasSystemFeature("android.hardware.type.television")
157                 || pm.hasSystemFeature("android.hardware.type.watch")
158                 || pm.hasSystemFeature("android.hardware.type.automotive")) {
159             return false;
160         }
161         return true;
162     }
163 
supportedHardwareForScopedDirectoryAccess()164     protected boolean supportedHardwareForScopedDirectoryAccess() {
165         final PackageManager pm = getInstrumentation().getContext().getPackageManager();
166         if (pm.hasSystemFeature("android.hardware.type.television")
167                 || pm.hasSystemFeature("android.hardware.type.watch")
168                 || pm.hasSystemFeature("android.hardware.type.automotive")) {
169             return false;
170         }
171         return true;
172     }
173 
isTelevision()174     protected boolean isTelevision() {
175         final PackageManager pm = getInstrumentation().getContext().getPackageManager();
176         return pm.hasSystemFeature("android.hardware.type.television");
177     }
178 
assertActivityFailed()179     protected void assertActivityFailed() {
180         final Result result = mActivity.getResult();
181         assertEquals(REQUEST_CODE, result.requestCode);
182         assertEquals(Activity.RESULT_CANCELED, result.resultCode);
183         assertNull(result.data);
184     }
185 
assertActivitySucceeded(String prefix)186     protected Intent assertActivitySucceeded(String prefix) {
187         final Result result = mActivity.getResult();
188         assertEquals(prefix + ": invalid request code", REQUEST_CODE, result.requestCode);
189         assertEquals(prefix + ": invalid result code", Activity.RESULT_OK, result.resultCode);
190         assertNotNull(prefix + ": null data on result", result.data);
191         return result.data;
192     }
193 
executeShellCommand(String command)194     protected String executeShellCommand(String command) throws Exception {
195         final String result = runShellCommand(getInstrumentation(), command).trim();
196         Log.d(TAG, "Command '" + command + "' returned '" + result + "'");
197         return result;
198     }
199 
200     /**
201      * Clears the DocumentsUI package data, unless test name ends on {@code DoNotClear}.
202      */
clearDocumentsUi()203     protected void clearDocumentsUi() throws Exception {
204         final String testName = getName();
205         if (testName.endsWith("DoNotClear")) {
206             Log.d(TAG, "Not clearing DocumentsUI due to test name: " + testName);
207             return;
208         }
209         executeShellCommand("pm clear " + getDocumentsUiPackageId());
210     }
211 
enableDummyIme()212     private void enableDummyIme() throws Exception {
213         String enableDummyCommand = "ime enable " + COMPONENT_NAME_DUMMY_IME;
214         executeShellCommand(enableDummyCommand);
215 
216         String setDummyCommand = "ime set " + COMPONENT_NAME_DUMMY_IME;
217         executeShellCommand(setDummyCommand);
218     }
219 }
220