diff options
Diffstat (limited to 'tests')
57 files changed, 1536 insertions, 169 deletions
diff --git a/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java b/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java index ceb3993e1705..0f4960887a33 100644 --- a/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java +++ b/tests/ActivityTests/src/com/google/android/test/activity/ActivityTestMain.java @@ -117,46 +117,6 @@ public class ActivityTestMain extends Activity { } } - private void addThumbnail(LinearLayout container, Bitmap bm, - final ActivityManager.RecentTaskInfo task, - final ActivityManager.TaskThumbnail thumbs) { - ImageView iv = new ImageView(this); - if (bm != null) { - iv.setImageBitmap(bm); - } - iv.setBackgroundResource(android.R.drawable.gallery_thumb); - int w = getResources().getDimensionPixelSize(android.R.dimen.thumbnail_width); - int h = getResources().getDimensionPixelSize(android.R.dimen.thumbnail_height); - container.addView(iv, new LinearLayout.LayoutParams(w, h)); - - iv.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (task.id >= 0 && thumbs != null) { - mAm.moveTaskToFront(task.id, ActivityManager.MOVE_TASK_WITH_HOME); - } else { - try { - startActivity(task.baseIntent); - } catch (ActivityNotFoundException e) { - Log.w("foo", "Unable to start task: " + e); - } - } - buildUi(); - } - }); - iv.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - if (task.id >= 0 && thumbs != null) { - mAm.removeTask(task.id); - buildUi(); - return true; - } - return false; - } - }); - } - @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -600,7 +560,6 @@ public class ActivityTestMain extends Activity { if (recents != null) { for (int i=0; i<recents.size(); i++) { ActivityManager.RecentTaskInfo r = recents.get(i); - ActivityManager.TaskThumbnail tt = mAm.getTaskThumbnail(r.persistentId); TextView tv = new TextView(this); tv.setText(r.baseIntent.getComponent().flattenToShortString()); top.addView(tv, new LinearLayout.LayoutParams( @@ -608,7 +567,6 @@ public class ActivityTestMain extends Activity { LinearLayout.LayoutParams.WRAP_CONTENT)); LinearLayout item = new LinearLayout(this); item.setOrientation(LinearLayout.HORIZONTAL); - addThumbnail(item, tt != null ? tt.mainThumbnail : null, r, tt); top.addView(item, new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); diff --git a/tests/AppLaunch/Android.mk b/tests/AppLaunch/Android.mk index d01b1f96ee05..09739e5e074a 100644 --- a/tests/AppLaunch/Android.mk +++ b/tests/AppLaunch/Android.mk @@ -9,7 +9,7 @@ LOCAL_SRC_FILES := $(call all-java-files-under, src) LOCAL_PACKAGE_NAME := AppLaunch LOCAL_CERTIFICATE := platform -LOCAL_JAVA_LIBRARIES := legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.base android.test.runner LOCAL_STATIC_JAVA_LIBRARIES := android-support-test diff --git a/tests/BackgroundDexOptServiceIntegrationTests/Android.mk b/tests/BackgroundDexOptServiceIntegrationTests/Android.mk new file mode 100644 index 000000000000..da1a08b79a8f --- /dev/null +++ b/tests/BackgroundDexOptServiceIntegrationTests/Android.mk @@ -0,0 +1,34 @@ +# +# Copyright (C) 2017 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. +# + +LOCAL_PATH:= $(call my-dir) +include $(CLEAR_VARS) + +# We only want this apk build for tests. +LOCAL_MODULE_TAGS := tests + +# Include all test java files. +LOCAL_SRC_FILES := $(call all-java-files-under, src) + +LOCAL_STATIC_JAVA_LIBRARIES := \ + android-support-test \ + +LOCAL_PACKAGE_NAME := BackgroundDexOptServiceIntegrationTests +LOCAL_COMPATIBILITY_SUITE := device-tests + +LOCAL_CERTIFICATE := platform + +include $(BUILD_PACKAGE) diff --git a/tests/BackgroundDexOptServiceIntegrationTests/AndroidManifest.xml b/tests/BackgroundDexOptServiceIntegrationTests/AndroidManifest.xml new file mode 100644 index 000000000000..afae155f88fe --- /dev/null +++ b/tests/BackgroundDexOptServiceIntegrationTests/AndroidManifest.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2017 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.frameworks.bgdexopttest"> + + + <!-- Uses API introduced in O (26) --> + <uses-sdk + android:minSdkVersion="1" + android:targetSdkVersion="26" /> + + <uses-permission android:name="android.permission.DUMP" /> + <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" /> + <uses-permission android:name="android.permission.SET_TIME" /> + <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" /> + <uses-permission android:name="android.permission.WAKE_LOCK" /> + + <application> + <uses-library android:name="android.test.runner" /> + </application> + + <instrumentation + android:name="android.support.test.runner.AndroidJUnitRunner" + android:targetPackage="com.android.frameworks.bgdexopttest" + android:label="Integration test for BackgroundDexOptService" /> +</manifest> diff --git a/tests/BackgroundDexOptServiceIntegrationTests/AndroidTest.xml b/tests/BackgroundDexOptServiceIntegrationTests/AndroidTest.xml new file mode 100644 index 000000000000..9bb1e280b861 --- /dev/null +++ b/tests/BackgroundDexOptServiceIntegrationTests/AndroidTest.xml @@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2017 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 BackgroundDexOptService Integration Tests"> + <!--DeviceSetup should go before TimeSetter because it stops automatic update of time--> + <target_preparer + class="com.android.tradefed.targetprep.DeviceSetup"> + <option name="auto-update-time" value="OFF"/> + <option name="auto-update-timezone" value="OFF"/> + <option name="set-property" key="pm.dexopt.downgrade_after_inactive_days" value="2"/> + <option name="set-property" key="pm.dexopt.disable_bg_dexopt" value="true"/> + <option name="set-property" key="pm.dexopt.inactive" value="verify"/> + <option name="set-property" key="pm.dexopt.bg-dexopt" value="speed"/> + <option name="restore-settings" value="true"/> + <option name="restore-properties" value="true"/> + </target_preparer> + + <!--Test app needs to be installed when we change its settings below--> + <target_preparer class="com.android.tradefed.targetprep.TestAppInstallSetup"> + <option name="test-file-name" value="BackgroundDexOptServiceIntegrationTests.apk"/> + <option name="cleanup-apks" value="true"/> + </target_preparer> + + <target_preparer class="com.android.tradefed.targetprep.SetPackagesRecentlyUsed"> + <option name="package-recently-used-time" value="0d"/> + <option name="package-recently-used-name" value="com.android.frameworks.bgdexopttest"/> + </target_preparer> + + <target_preparer class="com.android.tradefed.targetprep.RestartSystemServerTargetPreparer"/> + + <target_preparer class="com.android.tradefed.targetprep.DeviceStorageFiller"> + <!--32GB--> + <!--necessary because a package cannot create a file larger than 100GB--> + <option name="free-bytes" value="34359738368"/> + </target_preparer> + + <option name="test-suite-tag" value="apct"/> + <option name="test-tag" value="BackgroundDexOptServiceIntegrationTests"/> + <test class="com.android.tradefed.testtype.AndroidJUnitTest"> + <option name="package" value="com.android.frameworks.bgdexopttest"/> + <option name="runner" value="android.support.test.runner.AndroidJUnitRunner"/> + </test> +</configuration> diff --git a/tests/BackgroundDexOptServiceIntegrationTests/src/com/android/server/pm/BackgroundDexOptServiceIntegrationTests.java b/tests/BackgroundDexOptServiceIntegrationTests/src/com/android/server/pm/BackgroundDexOptServiceIntegrationTests.java new file mode 100644 index 000000000000..3734412981d8 --- /dev/null +++ b/tests/BackgroundDexOptServiceIntegrationTests/src/com/android/server/pm/BackgroundDexOptServiceIntegrationTests.java @@ -0,0 +1,313 @@ +/* + * Copyright (C) 2017 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.pm; + +import android.app.AlarmManager; +import android.content.Context; +import android.os.Environment; +import android.os.SystemProperties; +import android.os.storage.StorageManager; +import android.support.test.InstrumentationRegistry; +import android.util.Log; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.concurrent.TimeUnit; + +/** + * Integration tests for {@link BackgroundDexOptService}. + * + * Tests various scenarios around BackgroundDexOptService. + * 1. Under normal conditions, check that dexopt upgrades test app to + * $(getprop pm.dexopt.bg-dexopt). + * 2. Under low storage conditions and package is unused, check + * that dexopt downgrades test app to $(getprop pm.dexopt.inactive). + * 3. Under low storage conditions and package is recently used, check + * that dexopt upgrades test app to $(getprop pm.dexopt.bg-dexopt). + * + * Each test case runs "cmd package bg-dexopt-job com.android.frameworks.bgdexopttest". + * + * The setup for these tests make sure this package has been configured to have been recently used + * plus installed far enough in the past. If a test case requires that this package has not been + * recently used, it sets the time forward more than + * `getprop pm.dexopt.downgrade_after_inactive_days` days. + * + * For tests that require low storage, the phone is filled up. + * + * Run with "atest BackgroundDexOptServiceIntegrationTests". + */ +@RunWith(JUnit4.class) +public final class BackgroundDexOptServiceIntegrationTests { + + private static final String TAG = BackgroundDexOptServiceIntegrationTests.class.getSimpleName(); + + // Name of package to test on. + private static final String PACKAGE_NAME = "com.android.frameworks.bgdexopttest"; + // Name of file used to fill up storage. + private static final String BIG_FILE = "bigfile"; + private static final String BG_DEXOPT_COMPILER_FILTER = SystemProperties.get( + "pm.dexopt.bg-dexopt"); + private static final String DOWNGRADE_COMPILER_FILTER = SystemProperties.get( + "pm.dexopt.inactive"); + private static final long DOWNGRADE_AFTER_DAYS = SystemProperties.getLong( + "pm.dexopt.downgrade_after_inactive_days", 0); + // Needs to be between 1.0 and 2.0. + private static final double LOW_STORAGE_MULTIPLIER = 1.5; + + // The file used to fill up storage. + private File mBigFile; + + // Remember start time. + @BeforeClass + public static void setUpAll() { + if (!SystemProperties.getBoolean("pm.dexopt.disable_bg_dexopt", false)) { + throw new RuntimeException( + "bg-dexopt is not disabled (set pm.dexopt.disable_bg_dexopt to true)"); + } + if (DOWNGRADE_AFTER_DAYS < 1) { + throw new RuntimeException( + "pm.dexopt.downgrade_after_inactive_days must be at least 1"); + } + if ("quicken".equals(BG_DEXOPT_COMPILER_FILTER)) { + throw new RuntimeException("pm.dexopt.bg-dexopt should not be \"quicken\""); + } + if ("quicken".equals(DOWNGRADE_COMPILER_FILTER)) { + throw new RuntimeException("pm.dexopt.inactive should not be \"quicken\""); + } + } + + + private static Context getContext() { + return InstrumentationRegistry.getTargetContext(); + } + + @Before + public void setUp() throws IOException { + File dataDir = getContext().getDataDir(); + mBigFile = new File(dataDir, BIG_FILE); + } + + @After + public void tearDown() { + if (mBigFile.exists()) { + boolean result = mBigFile.delete(); + if (!result) { + throw new RuntimeException("Couldn't delete big file"); + } + } + } + + // Return the content of the InputStream as a String. + private static String inputStreamToString(InputStream is) throws IOException { + char[] buffer = new char[1024]; + StringBuilder builder = new StringBuilder(); + try (InputStreamReader reader = new InputStreamReader(is)) { + for (; ; ) { + int count = reader.read(buffer, 0, buffer.length); + if (count < 0) { + break; + } + builder.append(buffer, 0, count); + } + } + return builder.toString(); + } + + // Run the command and return the stdout. + private static String runShellCommand(String cmd) throws IOException { + Log.i(TAG, String.format("running command: '%s'", cmd)); + long startTime = System.nanoTime(); + Process p = Runtime.getRuntime().exec(cmd); + int res; + try { + res = p.waitFor(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + String stdout = inputStreamToString(p.getInputStream()); + String stderr = inputStreamToString(p.getErrorStream()); + long elapsedTime = System.nanoTime() - startTime; + Log.i(TAG, String.format("ran command: '%s' in %d ms with return code %d", cmd, + TimeUnit.NANOSECONDS.toMillis(elapsedTime), res)); + Log.i(TAG, "stdout"); + Log.i(TAG, stdout); + Log.i(TAG, "stderr"); + Log.i(TAG, stderr); + if (res != 0) { + throw new RuntimeException(String.format("failed command: '%s'", cmd)); + } + return stdout; + } + + // Run the command and return the stdout split by lines. + private static String[] runShellCommandSplitLines(String cmd) throws IOException { + return runShellCommand(cmd).split("\n"); + } + + // Return the compiler filter of a package. + private static String getCompilerFilter(String pkg) throws IOException { + String cmd = String.format("dumpsys package %s", pkg); + String[] lines = runShellCommandSplitLines(cmd); + final String substr = "compilation_filter="; + for (String line : lines) { + int startIndex = line.indexOf(substr); + if (startIndex < 0) { + continue; + } + startIndex += substr.length(); + int endIndex = line.indexOf(']', startIndex); + return line.substring(startIndex, endIndex); + } + throw new RuntimeException("Couldn't find compiler filter in dumpsys package"); + } + + // Return the number of bytes available in the data partition. + private static long getDataDirUsableSpace() { + return Environment.getDataDirectory().getUsableSpace(); + } + + // Fill up the storage until there are bytesRemaining number of bytes available in the data + // partition. Writes to the current package's data directory. + private void fillUpStorage(long bytesRemaining) throws IOException { + Log.i(TAG, String.format("Filling up storage with %d bytes remaining", bytesRemaining)); + logSpaceRemaining(); + long numBytesToAdd = getDataDirUsableSpace() - bytesRemaining; + String cmd = String.format("fallocate -l %d %s", numBytesToAdd, mBigFile.getAbsolutePath()); + runShellCommand(cmd); + logSpaceRemaining(); + } + + // Fill up storage so that device is in low storage condition. + private void fillUpToLowStorage() throws IOException { + fillUpStorage((long) (getStorageLowBytes() * LOW_STORAGE_MULTIPLIER)); + } + + // TODO(aeubanks): figure out how to get scheduled bg-dexopt to run + private static void runBackgroundDexOpt() throws IOException { + runShellCommand("cmd package bg-dexopt-job " + PACKAGE_NAME); + } + + // Set the time ahead of the last use time of the test app in days. + private static void setTimeFutureDays(long futureDays) { + setTimeFutureMillis(TimeUnit.DAYS.toMillis(futureDays)); + } + + // Set the time ahead of the last use time of the test app in milliseconds. + private static void setTimeFutureMillis(long futureMillis) { + long currentTime = System.currentTimeMillis(); + setTime(currentTime + futureMillis); + } + + private static void setTime(long time) { + AlarmManager am = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE); + am.setTime(time); + } + + // Return the number of free bytes when the data partition is considered low on storage. + private static long getStorageLowBytes() { + StorageManager storageManager = (StorageManager) getContext().getSystemService( + Context.STORAGE_SERVICE); + return storageManager.getStorageLowBytes(Environment.getDataDirectory()); + } + + // Log the amount of space remaining in the data directory. + private static void logSpaceRemaining() throws IOException { + runShellCommand("df -h /data"); + } + + // Compile the given package with the given compiler filter. + private static void compilePackageWithFilter(String pkg, String filter) throws IOException { + runShellCommand(String.format("cmd package compile -f -m %s %s", filter, pkg)); + } + + // Test that background dexopt under normal conditions succeeds. + @Test + public void testBackgroundDexOpt() throws IOException { + // Set filter to quicken. + compilePackageWithFilter(PACKAGE_NAME, "verify"); + Assert.assertEquals("verify", getCompilerFilter(PACKAGE_NAME)); + + runBackgroundDexOpt(); + + // Verify that bg-dexopt is successful. + Assert.assertEquals(BG_DEXOPT_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME)); + } + + // Test that background dexopt under low storage conditions upgrades used packages. + @Test + public void testBackgroundDexOptDowngradeSkipRecentlyUsedPackage() throws IOException { + // Should be less than DOWNGRADE_AFTER_DAYS. + long deltaDays = DOWNGRADE_AFTER_DAYS - 1; + try { + // Set time to future. + setTimeFutureDays(deltaDays); + + // Set filter to quicken. + compilePackageWithFilter(PACKAGE_NAME, "quicken"); + Assert.assertEquals("quicken", getCompilerFilter(PACKAGE_NAME)); + + // Fill up storage to trigger low storage threshold. + fillUpToLowStorage(); + + runBackgroundDexOpt(); + + // Verify that downgrade did not happen. + Assert.assertEquals(BG_DEXOPT_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME)); + } finally { + // Reset time. + setTimeFutureDays(-deltaDays); + } + } + + // Test that background dexopt under low storage conditions downgrades unused packages. + @Test + public void testBackgroundDexOptDowngradeSuccessful() throws IOException { + // Should be more than DOWNGRADE_AFTER_DAYS. + long deltaDays = DOWNGRADE_AFTER_DAYS + 1; + try { + // Set time to future. + setTimeFutureDays(deltaDays); + + // Set filter to quicken. + compilePackageWithFilter(PACKAGE_NAME, "quicken"); + Assert.assertEquals("quicken", getCompilerFilter(PACKAGE_NAME)); + + // Fill up storage to trigger low storage threshold. + fillUpToLowStorage(); + + runBackgroundDexOpt(); + + // Verify that downgrade is successful. + Assert.assertEquals(DOWNGRADE_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME)); + } finally { + // Reset time. + setTimeFutureDays(-deltaDays); + } + } + +} diff --git a/tests/BrowserPowerTest/Android.mk b/tests/BrowserPowerTest/Android.mk index 59bc729a6280..57655751cfd8 100644 --- a/tests/BrowserPowerTest/Android.mk +++ b/tests/BrowserPowerTest/Android.mk @@ -18,8 +18,8 @@ include $(CLEAR_VARS) # We only want this apk build for tests. LOCAL_MODULE_TAGS := tests -LOCAL_JAVA_LIBRARIES := android.test.runner -LOCAL_STATIC_JAVA_LIBRARIES := junit legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base +LOCAL_STATIC_JAVA_LIBRARIES := junit # Include all test java files. LOCAL_SRC_FILES := $(call all-java-files-under, src) diff --git a/tests/Camera2Tests/SmartCamera/SimpleCamera/tests/Android.mk b/tests/Camera2Tests/SmartCamera/SimpleCamera/tests/Android.mk index 527d1bbfd886..9e7f61892f93 100644 --- a/tests/Camera2Tests/SmartCamera/SimpleCamera/tests/Android.mk +++ b/tests/Camera2Tests/SmartCamera/SimpleCamera/tests/Android.mk @@ -24,7 +24,7 @@ LOCAL_PACKAGE_NAME := SmartCamera-tests LOCAL_SRC_FILES += $(call all-java-files-under, src) -LOCAL_JAVA_LIBRARIES := legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.base LOCAL_STATIC_JAVA_LIBRARIES := guava junit LOCAL_PROGUARD_ENABLED := disabled diff --git a/tests/CanvasCompare/Android.mk b/tests/CanvasCompare/Android.mk index 90de503ebd81..b071ec4c494b 100644 --- a/tests/CanvasCompare/Android.mk +++ b/tests/CanvasCompare/Android.mk @@ -23,7 +23,7 @@ LOCAL_PACKAGE_NAME := CanvasCompare LOCAL_MODULE_TAGS := tests -LOCAL_JAVA_LIBRARIES := android.test.runner -LOCAL_STATIC_JAVA_LIBRARIES := junit legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base +LOCAL_STATIC_JAVA_LIBRARIES := junit include $(BUILD_PACKAGE) diff --git a/tests/CoreTests/android/Android.mk b/tests/CoreTests/android/Android.mk index c9f11615381f..56d7918aa01e 100644 --- a/tests/CoreTests/android/Android.mk +++ b/tests/CoreTests/android/Android.mk @@ -6,8 +6,14 @@ LOCAL_MODULE_TAGS := tests LOCAL_SRC_FILES := \ $(call all-subdir-java-files) -LOCAL_JAVA_LIBRARIES := android.test.runner bouncycastle conscrypt org.apache.http.legacy -LOCAL_STATIC_JAVA_LIBRARIES := junit legacy-android-test +LOCAL_JAVA_LIBRARIES := \ + android.test.runner \ + bouncycastle \ + conscrypt \ + org.apache.http.legacy \ + android.test.base \ + +LOCAL_STATIC_JAVA_LIBRARIES := junit LOCAL_PACKAGE_NAME := CoreTests diff --git a/tests/DataIdleTest/Android.mk b/tests/DataIdleTest/Android.mk index 4e15729221a9..85f7edf7438d 100644 --- a/tests/DataIdleTest/Android.mk +++ b/tests/DataIdleTest/Android.mk @@ -20,8 +20,8 @@ include $(CLEAR_VARS) LOCAL_MODULE_TAGS := tests LOCAL_PACKAGE_NAME := DataIdleTest -LOCAL_JAVA_LIBRARIES := android.test.runner -LOCAL_STATIC_JAVA_LIBRARIES := junit legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base +LOCAL_STATIC_JAVA_LIBRARIES := junit LOCAL_SRC_FILES := $(call all-java-files-under, src) # We need to sign it to get access to the network usage history. diff --git a/tests/FrameworkPerf/Android.mk b/tests/FrameworkPerf/Android.mk index d2ec75347531..1873cc1de8a9 100644 --- a/tests/FrameworkPerf/Android.mk +++ b/tests/FrameworkPerf/Android.mk @@ -7,8 +7,8 @@ LOCAL_SRC_FILES := $(call all-subdir-java-files) LOCAL_PACKAGE_NAME := FrameworkPerf -LOCAL_JAVA_LIBRARIES := android.test.runner -LOCAL_STATIC_JAVA_LIBRARIES := junit legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base +LOCAL_STATIC_JAVA_LIBRARIES := junit LOCAL_AAPT_FLAGS = -c 120dpi,240dpi,160dpi,161dpi,320dpi,nodpi diff --git a/tests/HierarchyViewerTest/Android.mk b/tests/HierarchyViewerTest/Android.mk index f8c865631f93..8550d703678c 100644 --- a/tests/HierarchyViewerTest/Android.mk +++ b/tests/HierarchyViewerTest/Android.mk @@ -7,7 +7,7 @@ LOCAL_SRC_FILES := $(call all-subdir-java-files) LOCAL_PACKAGE_NAME := HierarchyViewerTest -LOCAL_JAVA_LIBRARIES := android.test.runner -LOCAL_STATIC_JAVA_LIBRARIES := junit legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base +LOCAL_STATIC_JAVA_LIBRARIES := junit include $(BUILD_PACKAGE) diff --git a/tests/HwAccelerationTest/AndroidManifest.xml b/tests/HwAccelerationTest/AndroidManifest.xml index 9caf9d0f6e26..ebf5f6854c6f 100644 --- a/tests/HwAccelerationTest/AndroidManifest.xml +++ b/tests/HwAccelerationTest/AndroidManifest.xml @@ -282,6 +282,15 @@ <category android:name="com.android.test.hwui.TEST" /> </intent-filter> </activity> + + <activity + android:name="ColoredShadowsActivity" + android:label="View/ColoredShadows"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="com.android.test.hwui.TEST" /> + </intent-filter> + </activity> <activity android:name="OpaqueActivity" diff --git a/tests/HwAccelerationTest/res/layout/colored_shadows_activity.xml b/tests/HwAccelerationTest/res/layout/colored_shadows_activity.xml new file mode 100644 index 000000000000..18633250cfcb --- /dev/null +++ b/tests/HwAccelerationTest/res/layout/colored_shadows_activity.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +** +** Copyright 2017, 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. +*/ +--> + +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="vertical" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:id="@+id/colored_grid"> + <include layout="@layout/colored_shadows_row" /> + <include layout="@layout/colored_shadows_row" /> + <include layout="@layout/colored_shadows_row" /> + <include layout="@layout/colored_shadows_row" /> + <include layout="@layout/colored_shadows_row" /> + <include layout="@layout/colored_shadows_row" /> + <include layout="@layout/colored_shadows_row" /> +</LinearLayout> diff --git a/tests/HwAccelerationTest/res/layout/colored_shadows_row.xml b/tests/HwAccelerationTest/res/layout/colored_shadows_row.xml new file mode 100644 index 000000000000..61b075974926 --- /dev/null +++ b/tests/HwAccelerationTest/res/layout/colored_shadows_row.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +** +** Copyright 2017, 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. +*/ +--> + +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="horizontal" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:paddingTop="25dp" + android:paddingBottom="25dp" + android:clipToPadding="false" > + <View android:id="@+id/grey" + android:layout_width="50dp" + android:layout_height="50dp" + android:elevation="16dp" + android:background="#3C4043" + android:layout_marginLeft="20dp" /> + <View android:id="@+id/blue" + android:layout_width="50dp" + android:layout_height="50dp" + android:elevation="16dp" + android:background="#185ABC" + android:layout_marginLeft="20dp"/> + <View android:id="@+id/red" + android:layout_width="50dp" + android:layout_height="50dp" + android:elevation="16dp" + android:background="#B31412" + android:layout_marginLeft="20dp"/> + <View android:id="@+id/yellow" + android:layout_width="50dp" + android:layout_height="50dp" + android:elevation="16dp" + android:background="#EA8600" + android:layout_marginLeft="20dp"/> + <View android:id="@+id/green" + android:layout_width="50dp" + android:layout_height="50dp" + android:elevation="16dp" + android:background="#137333" + android:layout_marginLeft="20dp"/> +</LinearLayout> diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ColoredShadowsActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ColoredShadowsActivity.java new file mode 100644 index 000000000000..135c93c97af2 --- /dev/null +++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ColoredShadowsActivity.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2017 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.test.hwui; + +import android.app.Activity; +import android.os.Bundle; +import android.view.View; +import android.view.ViewGroup; + +public class ColoredShadowsActivity extends Activity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.colored_shadows_activity); + ViewGroup grid = findViewById(R.id.colored_grid); + for (int i = 0; i < grid.getChildCount(); i++) { + setShadowColors((ViewGroup) grid.getChildAt(i), i); + } + } + + private void setShadowColors(ViewGroup row, int rowIndex) { + for (int i = 0; i < row.getChildCount(); i++) { + View view = row.getChildAt(i); + view.setShadowColor(shadowColorFor(view)); + view.setElevation(6.0f * (rowIndex + 1)); + } + } + + private int shadowColorFor(View view) { + switch (view.getId()) { + case R.id.grey: return 0xFF3C4043; + case R.id.blue: return 0xFF185ABC; + case R.id.red: return 0xFFB31412; + case R.id.yellow: return 0xFFEA8600; + case R.id.green: return 0xFF137333; + default: return 0xFF000000; + } + } + +} diff --git a/tests/ImfTest/tests/Android.mk b/tests/ImfTest/tests/Android.mk index 60424712d02c..a0df959cf185 100644 --- a/tests/ImfTest/tests/Android.mk +++ b/tests/ImfTest/tests/Android.mk @@ -7,8 +7,8 @@ LOCAL_MODULE_TAGS := tests # Include all test java files. LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_JAVA_LIBRARIES := android.test.runner -LOCAL_STATIC_JAVA_LIBRARIES := junit legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base +LOCAL_STATIC_JAVA_LIBRARIES := junit LOCAL_PACKAGE_NAME := ImfTestTests diff --git a/tests/Internal/Android.mk b/tests/Internal/Android.mk index fc001e928e80..73181ec36e17 100644 --- a/tests/Internal/Android.mk +++ b/tests/Internal/Android.mk @@ -11,7 +11,6 @@ LOCAL_SRC_FILES := $(call all-java-files-under, src) LOCAL_JAVA_LIBRARIES := android.test.runner LOCAL_STATIC_JAVA_LIBRARIES := junit \ - legacy-android-test \ android-support-test \ mockito-target-minus-junit4 diff --git a/tests/MemoryUsage/Android.mk b/tests/MemoryUsage/Android.mk index 578e628987f1..e186e9fb03c9 100644 --- a/tests/MemoryUsage/Android.mk +++ b/tests/MemoryUsage/Android.mk @@ -9,8 +9,8 @@ LOCAL_SRC_FILES := $(call all-java-files-under, src) LOCAL_PACKAGE_NAME := MemoryUsage LOCAL_CERTIFICATE := platform -LOCAL_JAVA_LIBRARIES := android.test.runner -LOCAL_STATIC_JAVA_LIBRARIES := junit legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base +LOCAL_STATIC_JAVA_LIBRARIES := junit include $(BUILD_PACKAGE) diff --git a/tests/NetworkSecurityConfigTest/Android.mk b/tests/NetworkSecurityConfigTest/Android.mk index dd9ff11971eb..6fb60259a2fc 100644 --- a/tests/NetworkSecurityConfigTest/Android.mk +++ b/tests/NetworkSecurityConfigTest/Android.mk @@ -5,8 +5,13 @@ include $(CLEAR_VARS) LOCAL_MODULE_TAGS := tests LOCAL_CERTIFICATE := platform -LOCAL_JAVA_LIBRARIES := android.test.runner bouncycastle conscrypt -LOCAL_STATIC_JAVA_LIBRARIES := junit legacy-android-test +LOCAL_JAVA_LIBRARIES := \ + android.test.runner \ + bouncycastle \ + conscrypt \ + android.test.base \ + +LOCAL_STATIC_JAVA_LIBRARIES := junit # Include all test java files. LOCAL_SRC_FILES := $(call all-java-files-under, src) diff --git a/tests/NetworkSecurityConfigTest/src/android/security/net/config/NetworkSecurityConfigTests.java b/tests/NetworkSecurityConfigTest/src/android/security/net/config/NetworkSecurityConfigTests.java index 25bfa53b0cf2..047be162e642 100644 --- a/tests/NetworkSecurityConfigTest/src/android/security/net/config/NetworkSecurityConfigTests.java +++ b/tests/NetworkSecurityConfigTest/src/android/security/net/config/NetworkSecurityConfigTests.java @@ -17,6 +17,7 @@ package android.security.net.config; import android.app.Activity; +import android.content.pm.ApplicationInfo; import android.os.Build; import android.test.ActivityUnitTestCase; import android.util.ArraySet; @@ -227,7 +228,8 @@ public class NetworkSecurityConfigTests extends ActivityUnitTestCase<Activity> { public void testConfigBuilderUsesParents() throws Exception { // Check that a builder with a parent uses the parent's values when non is set. NetworkSecurityConfig config = new NetworkSecurityConfig.Builder() - .setParent(NetworkSecurityConfig.getDefaultBuilder(Build.VERSION_CODES.N, 1)) + .setParent(NetworkSecurityConfig + .getDefaultBuilder(TestUtils.makeApplicationInfo())) .build(); assert(!config.getTrustAnchors().isEmpty()); } @@ -268,11 +270,22 @@ public class NetworkSecurityConfigTests extends ActivityUnitTestCase<Activity> { // Install the test CA. store.installCertificate(TEST_CA_CERT); NetworkSecurityConfig preNConfig = - NetworkSecurityConfig.getDefaultBuilder(Build.VERSION_CODES.M, 1).build(); + NetworkSecurityConfig + .getDefaultBuilder(TestUtils.makeApplicationInfo(Build.VERSION_CODES.M)) + .build(); NetworkSecurityConfig nConfig = - NetworkSecurityConfig.getDefaultBuilder(Build.VERSION_CODES.N, 1).build(); + NetworkSecurityConfig + .getDefaultBuilder(TestUtils.makeApplicationInfo(Build.VERSION_CODES.N)) + .build(); + ApplicationInfo privInfo = TestUtils.makeApplicationInfo(Build.VERSION_CODES.M); + privInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; + NetworkSecurityConfig privConfig = + NetworkSecurityConfig + .getDefaultBuilder(privInfo) + .build(); Set<TrustAnchor> preNAnchors = preNConfig.getTrustAnchors(); Set<TrustAnchor> nAnchors = nConfig.getTrustAnchors(); + Set<TrustAnchor> privAnchors = privConfig.getTrustAnchors(); Set<X509Certificate> preNCerts = new HashSet<X509Certificate>(); for (TrustAnchor anchor : preNAnchors) { preNCerts.add(anchor.certificate); @@ -281,8 +294,13 @@ public class NetworkSecurityConfigTests extends ActivityUnitTestCase<Activity> { for (TrustAnchor anchor : nAnchors) { nCerts.add(anchor.certificate); } + Set<X509Certificate> privCerts = new HashSet<X509Certificate>(); + for (TrustAnchor anchor : privAnchors) { + privCerts.add(anchor.certificate); + } assertTrue(preNCerts.contains(TEST_CA_CERT)); assertFalse(nCerts.contains(TEST_CA_CERT)); + assertFalse(privCerts.contains(TEST_CA_CERT)); } finally { // Delete the user added CA. We don't know the alias so just delete them all. for (String alias : store.aliases()) { diff --git a/tests/NetworkSecurityConfigTest/src/android/security/net/config/TestUtils.java b/tests/NetworkSecurityConfigTest/src/android/security/net/config/TestUtils.java index f7590fd6ff12..9dec21be7f37 100644 --- a/tests/NetworkSecurityConfigTest/src/android/security/net/config/TestUtils.java +++ b/tests/NetworkSecurityConfigTest/src/android/security/net/config/TestUtils.java @@ -16,6 +16,8 @@ package android.security.net.config; +import android.content.pm.ApplicationInfo; +import android.os.Build; import java.net.Socket; import java.net.URL; import javax.net.ssl.HttpsURLConnection; @@ -77,4 +79,17 @@ public final class TestUtils extends Assert { context.init(null, tmf.getTrustManagers(), null); return context; } + + public static ApplicationInfo makeApplicationInfo() { + ApplicationInfo info = new ApplicationInfo(); + info.targetSdkVersion = Build.VERSION_CODES.CUR_DEVELOPMENT; + info.targetSandboxVersion = 1; + return info; + } + + public static ApplicationInfo makeApplicationInfo(int targetSdkVersion) { + ApplicationInfo info = makeApplicationInfo(); + info.targetSdkVersion = targetSdkVersion; + return info; + } } diff --git a/tests/NetworkSecurityConfigTest/src/android/security/net/config/XmlConfigTests.java b/tests/NetworkSecurityConfigTest/src/android/security/net/config/XmlConfigTests.java index f7066a6f45f6..4b7a014f25dc 100644 --- a/tests/NetworkSecurityConfigTest/src/android/security/net/config/XmlConfigTests.java +++ b/tests/NetworkSecurityConfigTest/src/android/security/net/config/XmlConfigTests.java @@ -17,6 +17,7 @@ package android.security.net.config; import android.content.Context; +import android.content.pm.ApplicationInfo; import android.test.AndroidTestCase; import android.test.MoreAsserts; import android.util.ArraySet; @@ -44,7 +45,8 @@ public class XmlConfigTests extends AndroidTestCase { private final static String DEBUG_CA_SUBJ = "O=AOSP, CN=Test debug CA"; public void testEmptyConfigFile() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.empty_config); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.empty_config, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertFalse(appConfig.hasPerDomainConfigs()); NetworkSecurityConfig config = appConfig.getConfigForHostname(""); @@ -63,7 +65,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testEmptyAnchors() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.empty_trust); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.empty_trust, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertFalse(appConfig.hasPerDomainConfigs()); NetworkSecurityConfig config = appConfig.getConfigForHostname(""); @@ -81,7 +84,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testBasicDomainConfig() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.domain1); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.domain1, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); NetworkSecurityConfig config = appConfig.getConfigForHostname(""); @@ -117,7 +121,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testBasicPinning() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.pins1); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.pins1, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); // Check android.com. @@ -132,7 +137,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testExpiredPin() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.expired_pin); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.expired_pin, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); // Check android.com. @@ -146,7 +152,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testOverridesPins() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.override_pins); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.override_pins, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); // Check android.com. @@ -160,7 +167,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testBadPin() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.bad_pin); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.bad_pin, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); // Check android.com. @@ -175,7 +183,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testMultipleDomains() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.multiple_domains); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.multiple_domains, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com"); @@ -196,7 +205,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testMultipleDomainConfigs() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.multiple_configs); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.multiple_configs, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); // Should be two different config objects @@ -211,7 +221,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testIncludeSubdomains() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.subdomains); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.subdomains, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); // Try connections. @@ -224,7 +235,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testAttributes() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.attributes); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.attributes, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertFalse(appConfig.hasPerDomainConfigs()); NetworkSecurityConfig config = appConfig.getConfigForHostname(""); @@ -233,7 +245,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testResourcePemCertificateSource() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.resource_anchors_pem); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.resource_anchors_pem, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); // Check android.com. NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com"); @@ -249,7 +262,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testResourceDerCertificateSource() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.resource_anchors_der); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.resource_anchors_der, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); // Check android.com. NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com"); @@ -265,7 +279,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testNestedDomainConfigs() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.nested_domains); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.nested_domains, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); NetworkSecurityConfig parent = appConfig.getConfigForHostname("android.com"); @@ -283,7 +298,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testNestedDomainConfigsOverride() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.nested_domains_override); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.nested_domains_override, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); NetworkSecurityConfig parent = appConfig.getConfigForHostname("android.com"); @@ -294,7 +310,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testDebugOverridesDisabled() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_basic, false); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_basic, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); NetworkSecurityConfig config = appConfig.getConfigForHostname(""); Set<TrustAnchor> anchors = config.getTrustAnchors(); @@ -305,7 +322,9 @@ public class XmlConfigTests extends AndroidTestCase { } public void testBasicDebugOverrides() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_basic, true); + ApplicationInfo info = TestUtils.makeApplicationInfo(); + info.flags |= ApplicationInfo.FLAG_DEBUGGABLE; + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_basic, info); ApplicationConfig appConfig = new ApplicationConfig(source); NetworkSecurityConfig config = appConfig.getConfigForHostname(""); Set<TrustAnchor> anchors = config.getTrustAnchors(); @@ -319,7 +338,9 @@ public class XmlConfigTests extends AndroidTestCase { } public void testDebugOverridesWithDomain() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_domain, true); + ApplicationInfo info = TestUtils.makeApplicationInfo(); + info.flags |= ApplicationInfo.FLAG_DEBUGGABLE; + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_domain, info); ApplicationConfig appConfig = new ApplicationConfig(source); NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com"); Set<TrustAnchor> anchors = config.getTrustAnchors(); @@ -337,7 +358,9 @@ public class XmlConfigTests extends AndroidTestCase { } public void testDebugInherit() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_domain, true); + ApplicationInfo info = TestUtils.makeApplicationInfo(); + info.flags |= ApplicationInfo.FLAG_DEBUGGABLE; + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.debug_domain, info); ApplicationConfig appConfig = new ApplicationConfig(source); NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com"); Set<TrustAnchor> anchors = config.getTrustAnchors(); @@ -357,7 +380,8 @@ public class XmlConfigTests extends AndroidTestCase { private void testBadConfig(int configId) throws Exception { try { - XmlConfigSource source = new XmlConfigSource(getContext(), configId); + XmlConfigSource source = new XmlConfigSource(getContext(), configId, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); appConfig.getConfigForHostname("android.com"); fail("Bad config " + getContext().getResources().getResourceName(configId) @@ -393,7 +417,8 @@ public class XmlConfigTests extends AndroidTestCase { } public void testTrustManagerKeystore() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.bad_pin, true); + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.bad_pin, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); Provider provider = new NetworkSecurityConfigProvider(); TrustManagerFactory tmf = @@ -415,7 +440,9 @@ public class XmlConfigTests extends AndroidTestCase { } public void testDebugDedup() throws Exception { - XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.override_dedup, true); + ApplicationInfo info = TestUtils.makeApplicationInfo(); + info.flags |= ApplicationInfo.FLAG_DEBUGGABLE; + XmlConfigSource source = new XmlConfigSource(getContext(), R.xml.override_dedup, info); ApplicationConfig appConfig = new ApplicationConfig(source); assertTrue(appConfig.hasPerDomainConfigs()); // Check android.com. @@ -433,15 +460,18 @@ public class XmlConfigTests extends AndroidTestCase { } public void testExtraDebugResource() throws Exception { + ApplicationInfo info = TestUtils.makeApplicationInfo(); + info.flags |= ApplicationInfo.FLAG_DEBUGGABLE; XmlConfigSource source = - new XmlConfigSource(getContext(), R.xml.extra_debug_resource, true); + new XmlConfigSource(getContext(), R.xml.extra_debug_resource, info); ApplicationConfig appConfig = new ApplicationConfig(source); assertFalse(appConfig.hasPerDomainConfigs()); NetworkSecurityConfig config = appConfig.getConfigForHostname(""); MoreAsserts.assertNotEmpty(config.getTrustAnchors()); // Check that the _debug file is ignored if debug is false. - source = new XmlConfigSource(getContext(), R.xml.extra_debug_resource, false); + source = new XmlConfigSource(getContext(), R.xml.extra_debug_resource, + TestUtils.makeApplicationInfo()); appConfig = new ApplicationConfig(source); assertFalse(appConfig.hasPerDomainConfigs()); config = appConfig.getConfigForHostname(""); @@ -451,12 +481,15 @@ public class XmlConfigTests extends AndroidTestCase { public void testExtraDebugResourceIgnored() throws Exception { // Verify that parsing the extra debug config resource fails only when debugging is true. XmlConfigSource source = - new XmlConfigSource(getContext(), R.xml.bad_extra_debug_resource, false); + new XmlConfigSource(getContext(), R.xml.bad_extra_debug_resource, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); // Force parsing the config file. appConfig.getConfigForHostname(""); - source = new XmlConfigSource(getContext(), R.xml.bad_extra_debug_resource, true); + ApplicationInfo info = TestUtils.makeApplicationInfo(); + info.flags |= ApplicationInfo.FLAG_DEBUGGABLE; + source = new XmlConfigSource(getContext(), R.xml.bad_extra_debug_resource, info); appConfig = new ApplicationConfig(source); try { appConfig.getConfigForHostname(""); @@ -467,7 +500,8 @@ public class XmlConfigTests extends AndroidTestCase { public void testDomainWhitespaceTrimming() throws Exception { XmlConfigSource source = - new XmlConfigSource(getContext(), R.xml.domain_whitespace, false); + new XmlConfigSource(getContext(), R.xml.domain_whitespace, + TestUtils.makeApplicationInfo()); ApplicationConfig appConfig = new ApplicationConfig(source); NetworkSecurityConfig defaultConfig = appConfig.getConfigForHostname(""); MoreAsserts.assertNotEqual(defaultConfig, appConfig.getConfigForHostname("developer.android.com")); diff --git a/tests/ServiceCrashTest/Android.mk b/tests/ServiceCrashTest/Android.mk index d1f845623be8..f7b34523c086 100644 --- a/tests/ServiceCrashTest/Android.mk +++ b/tests/ServiceCrashTest/Android.mk @@ -9,7 +9,7 @@ LOCAL_SRC_FILES := $(call all-java-files-under, src) LOCAL_PACKAGE_NAME := ServiceCrashTest LOCAL_CERTIFICATE := platform -LOCAL_JAVA_LIBRARIES := legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.base LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util android-support-test diff --git a/tests/SoundTriggerTests/Android.mk b/tests/SoundTriggerTests/Android.mk index 359484ee63d7..030d5f4738dc 100644 --- a/tests/SoundTriggerTests/Android.mk +++ b/tests/SoundTriggerTests/Android.mk @@ -27,8 +27,8 @@ else LOCAL_SRC_FILES := src/android/hardware/soundtrigger/SoundTriggerTest.java endif -LOCAL_STATIC_JAVA_LIBRARIES := mockito-target legacy-android-test -LOCAL_JAVA_LIBRARIES := android.test.runner +LOCAL_STATIC_JAVA_LIBRARIES := mockito-target +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base LOCAL_PACKAGE_NAME := SoundTriggerTests diff --git a/tests/SurfaceComposition/Android.mk b/tests/SurfaceComposition/Android.mk index d97c3f4cd66f..1962791c8392 100644 --- a/tests/SurfaceComposition/Android.mk +++ b/tests/SurfaceComposition/Android.mk @@ -27,7 +27,9 @@ LOCAL_PROGUARD_ENABLED := disabled LOCAL_SRC_FILES := $(call all-java-files-under, src) -LOCAL_STATIC_JAVA_LIBRARIES := legacy-android-test junit +LOCAL_STATIC_JAVA_LIBRARIES := junit + +LOCAL_JAVA_LIBRARIES := android.test.runner.stubs LOCAL_PACKAGE_NAME := SurfaceComposition diff --git a/tests/TtsTests/Android.mk b/tests/TtsTests/Android.mk index 3c3cd77813f7..2fa19508c32c 100644 --- a/tests/TtsTests/Android.mk +++ b/tests/TtsTests/Android.mk @@ -20,8 +20,8 @@ LOCAL_MODULE_TAGS := tests LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_STATIC_JAVA_LIBRARIES := mockito-target legacy-android-test -LOCAL_JAVA_LIBRARIES := android.test.runner +LOCAL_STATIC_JAVA_LIBRARIES := mockito-target +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base LOCAL_PACKAGE_NAME := TtsTests diff --git a/tests/UiBench/Android.mk b/tests/UiBench/Android.mk index e6af4b024700..60327e5cb2a4 100644 --- a/tests/UiBench/Android.mk +++ b/tests/UiBench/Android.mk @@ -10,23 +10,11 @@ LOCAL_SRC_FILES := $(call all-java-files-under,src) # use appcompat/support lib from the tree, so improvements/ # regressions are reflected in test data -LOCAL_RESOURCE_DIR := \ - $(LOCAL_PATH)/res \ - frameworks/support/design/res \ - frameworks/support/v7/appcompat/res \ - frameworks/support/v7/cardview/res \ - frameworks/support/v7/recyclerview/res \ - frameworks/support/v17/leanback/res - -LOCAL_AAPT_FLAGS := \ - --auto-add-overlay \ - --extra-packages android.support.design \ - --extra-packages android.support.v7.appcompat \ - --extra-packages android.support.v7.cardview \ - --extra-packages android.support.v7.recyclerview \ - --extra-packages android.support.v17.leanback - -LOCAL_STATIC_JAVA_LIBRARIES := \ +LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res + +LOCAL_USE_AAPT2 := true + +LOCAL_STATIC_ANDROID_LIBRARIES := \ android-support-design \ android-support-v4 \ android-support-v7-appcompat \ diff --git a/tests/UiBench/AndroidManifest.xml b/tests/UiBench/AndroidManifest.xml index 2521dc9f82ae..c6b4a54f3b0b 100644 --- a/tests/UiBench/AndroidManifest.xml +++ b/tests/UiBench/AndroidManifest.xml @@ -92,6 +92,15 @@ </intent-filter> </activity> <activity + android:name=".TrivialAnimationActivityWideGamut" + android:label="General/Trivial Animation (Wide Gamut)" + android:colorMode="wideColorGamut"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="com.android.test.uibench.TEST" /> + </intent-filter> + </activity> + <activity android:name=".TrivialListActivity" android:label="General/Trivial ListView" > <intent-filter> @@ -201,6 +210,36 @@ </intent-filter> </activity> + <activity-alias + android:name=".InflatingEmojiListActivity" + android:label="Inflation/Inflating ListView with Emoji" + android:targetActivity=".InflatingListActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="com.android.test.uibench.TEST" /> + </intent-filter> + </activity-alias> + + <activity-alias + android:name=".InflatingHanListActivity" + android:label="Inflation/Inflating ListView with Han Characters" + android:targetActivity=".InflatingListActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="com.android.test.uibench.TEST" /> + </intent-filter> + </activity-alias> + + <activity-alias + android:name=".InflatingLongStringListActivity" + android:label="Inflation/Inflating ListView with long string" + android:targetActivity=".InflatingListActivity"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="com.android.test.uibench.TEST" /> + </intent-filter> + </activity-alias> + <!-- Text --> <activity android:name=".EditTextTypeActivity" diff --git a/tests/UiBench/src/com/android/test/uibench/InflatingListActivity.java b/tests/UiBench/src/com/android/test/uibench/InflatingListActivity.java index 603244eb2a43..2b84f2c49e67 100644 --- a/tests/UiBench/src/com/android/test/uibench/InflatingListActivity.java +++ b/tests/UiBench/src/com/android/test/uibench/InflatingListActivity.java @@ -15,6 +15,7 @@ */ package com.android.test.uibench; +import android.content.ComponentName; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; @@ -23,10 +24,33 @@ import android.widget.ListAdapter; import com.android.test.uibench.listview.CompatListActivity; public class InflatingListActivity extends CompatListActivity { + private static final String PACKAGE_NAME = "com.android.test.uibench"; + private static final ComponentName LATIN_WORDS = + ComponentName.createRelative(PACKAGE_NAME, ".InflatingListActivity"); + private static final ComponentName EMOJI = + ComponentName.createRelative(PACKAGE_NAME, ".InflatingEmojiListActivity"); + private static final ComponentName HAN = + ComponentName.createRelative(PACKAGE_NAME, ".InflatingHanListActivity"); + private static final ComponentName LONG_STRING = + ComponentName.createRelative(PACKAGE_NAME, ".InflatingLongStringListActivity"); @Override protected ListAdapter createListAdapter() { - return new ArrayAdapter<String>(this, - android.R.layout.simple_list_item_1, TextUtils.buildSimpleStringList()) { + final ComponentName targetComponent = getIntent().getComponent(); + + final String[] testStrings; + if (targetComponent.equals(LATIN_WORDS)) { + testStrings = TextUtils.buildSimpleStringList(); + } else if (targetComponent.equals(EMOJI)) { + testStrings = TextUtils.buildEmojiStringList(); + } else if (targetComponent.equals(HAN)) { + testStrings = TextUtils.buildHanStringList(); + } else if (targetComponent.equals(LONG_STRING)) { + testStrings = TextUtils.buildLongStringList(); + } else { + throw new RuntimeException("Unknown Component: " + targetComponent); + } + + return new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, testStrings) { @Override public View getView(int position, View convertView, ViewGroup parent) { // pathological getView behavior: drop convertView on the floor to force inflation diff --git a/tests/UiBench/src/com/android/test/uibench/TextUtils.java b/tests/UiBench/src/com/android/test/uibench/TextUtils.java index 32a59868e6c0..2df91047cdf8 100644 --- a/tests/UiBench/src/com/android/test/uibench/TextUtils.java +++ b/tests/UiBench/src/com/android/test/uibench/TextUtils.java @@ -15,11 +15,24 @@ */ package com.android.test.uibench; +import android.icu.text.UnicodeSet; +import android.icu.text.UnicodeSetIterator; + +import java.util.ArrayList; import java.util.Random; public class TextUtils { private static final int STRING_COUNT = 200; - private static final int SIMPLE_STRING_LENGTH = 10; + private static final int SIMPLE_STRING_LENGTH = 10; // in code points + + private static String[] UnicodeSetToArray(UnicodeSet set) { + final UnicodeSetIterator iterator = new UnicodeSetIterator(set); + final ArrayList<String> out = new ArrayList<>(set.size()); + while (iterator.next()) { + out.add(iterator.getString()); + } + return out.toArray(new String[out.size()]); + } /** * Create word of random assortment of lower/upper case letters @@ -34,10 +47,34 @@ public class TextUtils { return result; } + /** + * Create word from a random assortment of a given set of codepoints, given as strings. + */ + private static String randomWordFromStringSet(Random random, int length, String[] stringSet) { + final StringBuilder sb = new StringBuilder(length); + final int setLength = stringSet.length; + for (int j = 0; j < length; j++) { + sb.append(stringSet[random.nextInt(setLength)]); + } + return sb.toString(); + } + public static String[] buildSimpleStringList() { return buildSimpleStringList(SIMPLE_STRING_LENGTH); } + public static String[] buildEmojiStringList() { + return buildEmojiStringList(SIMPLE_STRING_LENGTH); + } + + public static String[] buildHanStringList() { + return buildHanStringList(SIMPLE_STRING_LENGTH); + } + + public static String[] buildLongStringList() { + return buildLongStringList(SIMPLE_STRING_LENGTH); + } + public static String[] buildSimpleStringList(int stringLength) { String[] strings = new String[STRING_COUNT]; Random random = new Random(0); @@ -47,6 +84,41 @@ public class TextUtils { return strings; } + private static String[] buildStringListFromUnicodeSet(int stringLength, UnicodeSet set) { + final String[] strings = new String[STRING_COUNT]; + final Random random = new Random(0); + final String[] stringSet = UnicodeSetToArray(set); + for (int i = 0; i < strings.length; i++) { + strings[i] = randomWordFromStringSet(random, stringLength, stringSet); + } + return strings; + } + + public static String[] buildEmojiStringList(int stringLength) { + return buildStringListFromUnicodeSet(stringLength, new UnicodeSet("[:emoji:]")); + } + + public static String[] buildHanStringList(int stringLength) { + return buildStringListFromUnicodeSet(stringLength, new UnicodeSet("[\\u4E00-\\u9FA0]")); + } + + public static String[] buildLongStringList(int stringLength) { + final int WORD_COUNT = 100; + final String[] strings = new String[STRING_COUNT]; + final Random random = new Random(0); + for (int i = 0; i < strings.length; i++) { + final StringBuilder sb = new StringBuilder((stringLength + 1) * WORD_COUNT); + for (int j = 0; j < WORD_COUNT; ++j) { + if (j != 0) { + sb.append(' '); + } + sb.append(randomWord(random, stringLength)); + } + strings[i] = sb.toString(); + } + return strings; + } + // a small number of strings reused frequently, expected to hit // in the word-granularity text layout cache static final String[] CACHE_HIT_STRINGS = new String[] { diff --git a/tests/UiBench/src/com/android/test/uibench/TrivialAnimationActivityWideGamut.java b/tests/UiBench/src/com/android/test/uibench/TrivialAnimationActivityWideGamut.java new file mode 100644 index 000000000000..c492753d8b7a --- /dev/null +++ b/tests/UiBench/src/com/android/test/uibench/TrivialAnimationActivityWideGamut.java @@ -0,0 +1,18 @@ +/* + * Copyright (C) 2017 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.test.uibench; + +public class TrivialAnimationActivityWideGamut extends TrivialAnimationActivity { } diff --git a/tests/WindowAnimationJank/Android.mk b/tests/WindowAnimationJank/Android.mk index f356afb799a2..8aac8a15c705 100644 --- a/tests/WindowAnimationJank/Android.mk +++ b/tests/WindowAnimationJank/Android.mk @@ -27,7 +27,6 @@ LOCAL_PACKAGE_NAME := WindowAnimationJank LOCAL_STATIC_JAVA_LIBRARIES := \ ub-uiautomator \ ub-janktesthelper \ - legacy-android-test \ junit LOCAL_SDK_VERSION := current diff --git a/tests/WindowManagerStressTest/src/test/windowmanagerstresstest/MainActivity.java b/tests/WindowManagerStressTest/src/test/windowmanagerstresstest/MainActivity.java index 6b9bb31a75c7..9174014dedf4 100644 --- a/tests/WindowManagerStressTest/src/test/windowmanagerstresstest/MainActivity.java +++ b/tests/WindowManagerStressTest/src/test/windowmanagerstresstest/MainActivity.java @@ -24,6 +24,7 @@ import android.os.SystemClock; import android.util.Log; import android.util.MergedConfiguration; import android.view.Display; +import android.view.DisplayCutout; import android.view.IWindowSession; import android.view.Surface; import android.view.View; @@ -103,7 +104,8 @@ public class MainActivity extends Activity { WindowManagerGlobal.getWindowSession().relayout(window, window.mSeq, mLayoutParams, -1, -1, View.VISIBLE, 0, mTmpRect, mTmpRect, mTmpRect, mTmpRect, mTmpRect, mTmpRect, mTmpRect, - new MergedConfiguration(), new Surface()); + new DisplayCutout.ParcelableWrapper(), new MergedConfiguration(), + new Surface()); } catch (RemoteException e) { e.printStackTrace(); } diff --git a/tests/net/Android.mk b/tests/net/Android.mk index 677585cc0c0f..1bd1af5e3c22 100644 --- a/tests/net/Android.mk +++ b/tests/net/Android.mk @@ -21,7 +21,9 @@ LOCAL_STATIC_JAVA_LIBRARIES := \ services.net LOCAL_JAVA_LIBRARIES := \ - android.test.runner + android.test.runner \ + android.test.base \ + android.test.mock LOCAL_PACKAGE_NAME := FrameworksNetTests LOCAL_COMPATIBILITY_SUITE := device-tests diff --git a/tests/net/java/android/net/NetworkCapabilitiesTest.java b/tests/net/java/android/net/NetworkCapabilitiesTest.java index e6170cb42cbb..cd2d0985c793 100644 --- a/tests/net/java/android/net/NetworkCapabilitiesTest.java +++ b/tests/net/java/android/net/NetworkCapabilitiesTest.java @@ -18,7 +18,6 @@ package android.net; import static android.net.NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED; import static android.net.NetworkCapabilities.NET_CAPABILITY_CBS; -import static android.net.NetworkCapabilities.NET_CAPABILITY_DUN; import static android.net.NetworkCapabilities.NET_CAPABILITY_EIMS; import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET; import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED; @@ -144,14 +143,6 @@ public class NetworkCapabilitiesTest { assertEquals("", nc1.describeImmutableDifferences(nc2)); assertEquals("", nc1.describeImmutableDifferences(nc1)); - // DUN changing (http://b/65257223) - nc1 = new NetworkCapabilities() - .addCapability(NET_CAPABILITY_DUN) - .addCapability(NET_CAPABILITY_INTERNET); - nc2 = new NetworkCapabilities().addCapability(NET_CAPABILITY_INTERNET); - assertEquals("", nc1.describeImmutableDifferences(nc2)); - assertEquals("", nc1.describeImmutableDifferences(nc1)); - // Immutable capability changing nc1 = new NetworkCapabilities() .addCapability(NET_CAPABILITY_INTERNET) diff --git a/tests/net/java/android/net/NetworkStatsHistoryTest.java b/tests/net/java/android/net/NetworkStatsHistoryTest.java index 1c0c14eac08b..301d04d5cf6f 100644 --- a/tests/net/java/android/net/NetworkStatsHistoryTest.java +++ b/tests/net/java/android/net/NetworkStatsHistoryTest.java @@ -32,9 +32,14 @@ import static android.text.format.DateUtils.MINUTE_IN_MILLIS; import static android.text.format.DateUtils.SECOND_IN_MILLIS; import static android.text.format.DateUtils.WEEK_IN_MILLIS; import static android.text.format.DateUtils.YEAR_IN_MILLIS; - -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.filters.SmallTest; +import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; @@ -46,25 +51,31 @@ import java.io.DataInputStream; import java.io.DataOutputStream; import java.util.Random; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) @SmallTest -public class NetworkStatsHistoryTest extends AndroidTestCase { +public class NetworkStatsHistoryTest { private static final String TAG = "NetworkStatsHistoryTest"; private static final long TEST_START = 1194220800000L; private NetworkStatsHistory stats; - @Override - protected void tearDown() throws Exception { - super.tearDown(); + @After + public void tearDown() throws Exception { if (stats != null) { assertConsistent(stats); } } + @Test public void testReadOriginalVersion() throws Exception { - final DataInputStream in = new DataInputStream( - getContext().getResources().openRawResource(R.raw.history_v1)); + final Context context = InstrumentationRegistry.getContext(); + final DataInputStream in = + new DataInputStream(context.getResources().openRawResource(R.raw.history_v1)); NetworkStatsHistory.Entry entry = null; try { @@ -88,6 +99,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { } } + @Test public void testRecordSingleBucket() throws Exception { final long BUCKET_SIZE = HOUR_IN_MILLIS; stats = new NetworkStatsHistory(BUCKET_SIZE); @@ -100,6 +112,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertValues(stats, 0, SECOND_IN_MILLIS, 1024L, 10L, 2048L, 20L, 2L); } + @Test public void testRecordEqualBuckets() throws Exception { final long bucketDuration = HOUR_IN_MILLIS; stats = new NetworkStatsHistory(bucketDuration); @@ -114,6 +127,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertValues(stats, 1, HOUR_IN_MILLIS / 2, 512L, 5L, 64L, 1L, 1L); } + @Test public void testRecordTouchingBuckets() throws Exception { final long BUCKET_SIZE = 15 * MINUTE_IN_MILLIS; stats = new NetworkStatsHistory(BUCKET_SIZE); @@ -134,6 +148,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertValues(stats, 2, 4 * MINUTE_IN_MILLIS, 200L, 400L, 1000L, 2000L, 20L); } + @Test public void testRecordGapBuckets() throws Exception { final long BUCKET_SIZE = HOUR_IN_MILLIS; stats = new NetworkStatsHistory(BUCKET_SIZE); @@ -165,6 +180,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertValues(stats, 3, SECOND_IN_MILLIS, 64L, 1L, 512L, 8L, 2L); } + @Test public void testRecordOverlapBuckets() throws Exception { final long BUCKET_SIZE = HOUR_IN_MILLIS; stats = new NetworkStatsHistory(BUCKET_SIZE); @@ -182,6 +198,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertValues(stats, 1, (HOUR_IN_MILLIS / 2), 512L, 5L, 512L, 5L, 5L); } + @Test public void testRecordEntireGapIdentical() throws Exception { // first, create two separate histories far apart final NetworkStatsHistory stats1 = new NetworkStatsHistory(HOUR_IN_MILLIS); @@ -206,6 +223,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertValues(stats, 3, 500L, 250L); } + @Test public void testRecordEntireOverlapVaryingBuckets() throws Exception { // create history just over hour bucket boundary final NetworkStatsHistory stats1 = new NetworkStatsHistory(HOUR_IN_MILLIS); @@ -247,6 +265,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertValues(stats, 3, 150L, 150L); } + @Test public void testRemove() throws Exception { stats = new NetworkStatsHistory(HOUR_IN_MILLIS); @@ -280,6 +299,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertEquals(0, stats.size()); } + @Test public void testTotalData() throws Exception { final long BUCKET_SIZE = HOUR_IN_MILLIS; stats = new NetworkStatsHistory(BUCKET_SIZE); @@ -304,7 +324,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { } - @Suppress + @Test public void testFuzzing() throws Exception { try { // fuzzing with random events, looking for crashes @@ -341,6 +361,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { return value < 0 ? -value : value; } + @Test public void testIgnoreFields() throws Exception { final NetworkStatsHistory history = new NetworkStatsHistory( MINUTE_IN_MILLIS, 0, FIELD_RX_BYTES | FIELD_TX_BYTES); @@ -353,6 +374,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertFullValues(history, UNKNOWN, 1026L, UNKNOWN, 2050L, UNKNOWN, UNKNOWN); } + @Test public void testIgnoreFieldsRecordIn() throws Exception { final NetworkStatsHistory full = new NetworkStatsHistory(MINUTE_IN_MILLIS, 0, FIELD_ALL); final NetworkStatsHistory partial = new NetworkStatsHistory( @@ -365,6 +387,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertFullValues(partial, UNKNOWN, UNKNOWN, 10L, UNKNOWN, UNKNOWN, 4L); } + @Test public void testIgnoreFieldsRecordOut() throws Exception { final NetworkStatsHistory full = new NetworkStatsHistory(MINUTE_IN_MILLIS, 0, FIELD_ALL); final NetworkStatsHistory partial = new NetworkStatsHistory( @@ -377,6 +400,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertFullValues(full, MINUTE_IN_MILLIS, 0L, 10L, 0L, 0L, 4L); } + @Test public void testSerialize() throws Exception { final NetworkStatsHistory before = new NetworkStatsHistory(MINUTE_IN_MILLIS, 40, FIELD_ALL); before.recordData(0, 4 * MINUTE_IN_MILLIS, @@ -396,6 +420,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertFullValues(after, 5 * MINUTE_IN_MILLIS, 1034L, 30L, 2078L, 60L, 54L); } + @Test public void testVarLong() throws Exception { assertEquals(0L, performVarLong(0L)); assertEquals(-1L, performVarLong(-1L)); @@ -409,6 +434,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertEquals(Long.MAX_VALUE - 40, performVarLong(Long.MAX_VALUE - 40)); } + @Test public void testIndexBeforeAfter() throws Exception { final long BUCKET_SIZE = HOUR_IN_MILLIS; stats = new NetworkStatsHistory(BUCKET_SIZE); @@ -451,6 +477,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertIndexBeforeAfter(stats, 4, 4, Long.MAX_VALUE); } + @Test public void testIntersects() throws Exception { final long BUCKET_SIZE = HOUR_IN_MILLIS; stats = new NetworkStatsHistory(BUCKET_SIZE); @@ -485,6 +512,7 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { assertTrue(stats.intersects(Long.MIN_VALUE, TEST_START + 1)); } + @Test public void testSetValues() throws Exception { stats = new NetworkStatsHistory(HOUR_IN_MILLIS); stats.recordData(TEST_START, TEST_START + 1, diff --git a/tests/net/java/com/android/internal/util/RingBufferTest.java b/tests/net/java/com/android/internal/util/RingBufferTest.java index 7a2344317223..90a373a9c11e 100644 --- a/tests/net/java/com/android/internal/util/RingBufferTest.java +++ b/tests/net/java/com/android/internal/util/RingBufferTest.java @@ -17,6 +17,7 @@ package com.android.internal.util; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import android.support.test.filters.SmallTest; @@ -129,6 +130,55 @@ public class RingBufferTest { assertArraysEqual(expected2, buffer.toArray()); } + @Test + public void testGetNextSlot() { + int capacity = 100; + RingBuffer<DummyClass1> buffer = new RingBuffer<>(DummyClass1.class, capacity); + + final DummyClass1[] actual = new DummyClass1[capacity]; + final DummyClass1[] expected = new DummyClass1[capacity]; + for (int i = 0; i < capacity; ++i) { + final DummyClass1 obj = buffer.getNextSlot(); + obj.x = capacity * i; + actual[i] = obj; + expected[i] = new DummyClass1(); + expected[i].x = capacity * i; + } + assertArraysEqual(expected, buffer.toArray()); + + for (int i = 0; i < capacity; ++i) { + if (actual[i] != buffer.getNextSlot()) { + fail("getNextSlot() should re-use objects if available"); + } + } + + RingBuffer<DummyClass2> buffer2 = new RingBuffer<>(DummyClass2.class, capacity); + assertNull("getNextSlot() should return null if the object can't be initiated " + + "(No nullary constructor)", buffer2.getNextSlot()); + + RingBuffer<DummyClass3> buffer3 = new RingBuffer<>(DummyClass3.class, capacity); + assertNull("getNextSlot() should return null if the object can't be initiated " + + "(Inaccessible class)", buffer3.getNextSlot()); + } + + public static final class DummyClass1 { + int x; + + public boolean equals(Object o) { + if (o instanceof DummyClass1) { + final DummyClass1 other = (DummyClass1) o; + return other.x == this.x; + } + return false; + } + } + + public static final class DummyClass2 { + public DummyClass2(int x) {} + } + + private static final class DummyClass3 {} + static <T> void assertArraysEqual(T[] expected, T[] got) { if (expected.length != got.length) { fail(Arrays.toString(expected) + " and " + Arrays.toString(got) diff --git a/tests/net/java/com/android/server/connectivity/TetheringTest.java b/tests/net/java/com/android/server/connectivity/TetheringTest.java index a115146486a4..099cfd457160 100644 --- a/tests/net/java/com/android/server/connectivity/TetheringTest.java +++ b/tests/net/java/com/android/server/connectivity/TetheringTest.java @@ -40,6 +40,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.mock; import android.content.BroadcastReceiver; import android.content.ContentResolver; @@ -59,12 +60,14 @@ import android.net.NetworkRequest; import android.net.util.SharedLog; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; +import android.os.Bundle; import android.os.Handler; import android.os.INetworkManagementService; import android.os.PersistableBundle; import android.os.RemoteException; import android.os.test.TestLooper; import android.os.UserHandle; +import android.os.UserManager; import android.provider.Settings; import android.support.test.filters.SmallTest; import android.support.test.runner.AndroidJUnit4; @@ -558,6 +561,90 @@ public class TetheringTest { verifyNoMoreInteractions(mNMService); } + private void userRestrictionsListenerBehaviour( + boolean currentDisallow, boolean nextDisallow, String[] activeTetheringIfacesList, + int expectedInteractionsWithShowNotification) throws Exception { + final int userId = 0; + final Bundle currRestrictions = new Bundle(); + final Bundle newRestrictions = new Bundle(); + Tethering tethering = mock(Tethering.class); + Tethering.TetheringUserRestrictionListener turl = + new Tethering.TetheringUserRestrictionListener(tethering); + + currRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_TETHERING, currentDisallow); + newRestrictions.putBoolean(UserManager.DISALLOW_CONFIG_TETHERING, nextDisallow); + when(tethering.getTetheredIfaces()).thenReturn(activeTetheringIfacesList); + + turl.onUserRestrictionsChanged(userId, newRestrictions, currRestrictions); + + verify(tethering, times(expectedInteractionsWithShowNotification)) + .showTetheredNotification(anyInt(), eq(false)); + + verify(tethering, times(expectedInteractionsWithShowNotification)).untetherAll(); + } + + @Test + public void testDisallowTetheringWhenNoTetheringInterfaceIsActive() throws Exception { + final String[] emptyActiveIfacesList = new String[]{}; + final boolean currDisallow = false; + final boolean nextDisallow = true; + final int expectedInteractionsWithShowNotification = 0; + + userRestrictionsListenerBehaviour(currDisallow, nextDisallow, emptyActiveIfacesList, + expectedInteractionsWithShowNotification); + } + + @Test + public void testDisallowTetheringWhenAtLeastOneTetheringInterfaceIsActive() throws Exception { + final String[] nonEmptyActiveIfacesList = new String[]{mTestIfname}; + final boolean currDisallow = false; + final boolean nextDisallow = true; + final int expectedInteractionsWithShowNotification = 1; + + userRestrictionsListenerBehaviour(currDisallow, nextDisallow, nonEmptyActiveIfacesList, + expectedInteractionsWithShowNotification); + } + + @Test + public void testAllowTetheringWhenNoTetheringInterfaceIsActive() throws Exception { + final String[] nonEmptyActiveIfacesList = new String[]{}; + final boolean currDisallow = true; + final boolean nextDisallow = false; + final int expectedInteractionsWithShowNotification = 0; + + userRestrictionsListenerBehaviour(currDisallow, nextDisallow, nonEmptyActiveIfacesList, + expectedInteractionsWithShowNotification); + } + + @Test + public void testAllowTetheringWhenAtLeastOneTetheringInterfaceIsActive() throws Exception { + final String[] nonEmptyActiveIfacesList = new String[]{mTestIfname}; + final boolean currDisallow = true; + final boolean nextDisallow = false; + final int expectedInteractionsWithShowNotification = 0; + + userRestrictionsListenerBehaviour(currDisallow, nextDisallow, nonEmptyActiveIfacesList, + expectedInteractionsWithShowNotification); + } + + @Test + public void testDisallowTetheringUnchanged() throws Exception { + final String[] nonEmptyActiveIfacesList = new String[]{mTestIfname}; + final int expectedInteractionsWithShowNotification = 0; + boolean currDisallow = true; + boolean nextDisallow = true; + + userRestrictionsListenerBehaviour(currDisallow, nextDisallow, nonEmptyActiveIfacesList, + expectedInteractionsWithShowNotification); + + currDisallow = false; + nextDisallow = false; + + userRestrictionsListenerBehaviour(currDisallow, nextDisallow, nonEmptyActiveIfacesList, + expectedInteractionsWithShowNotification); + } + + // TODO: Test that a request for hotspot mode doesn't interfere with an // already operating tethering mode interface. } diff --git a/tests/net/java/com/android/server/net/NetworkStatsCollectionTest.java b/tests/net/java/com/android/server/net/NetworkStatsCollectionTest.java index 9c1026465612..dbaf8e690e07 100644 --- a/tests/net/java/com/android/server/net/NetworkStatsCollectionTest.java +++ b/tests/net/java/com/android/server/net/NetworkStatsCollectionTest.java @@ -26,6 +26,9 @@ import static android.net.NetworkTemplate.buildTemplateMobileAll; import static android.os.Process.myUid; import static android.text.format.DateUtils.HOUR_IN_MILLIS; import static android.text.format.DateUtils.MINUTE_IN_MILLIS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; import static com.android.server.net.NetworkStatsCollection.multiplySafe; @@ -37,11 +40,12 @@ import android.net.NetworkStatsHistory; import android.net.NetworkTemplate; import android.os.Process; import android.os.UserHandle; +import android.support.test.InstrumentationRegistry; +import android.support.test.filters.SmallTest; +import android.support.test.runner.AndroidJUnit4; import android.telephony.SubscriptionPlan; import android.telephony.TelephonyManager; -import android.test.AndroidTestCase; import android.test.MoreAsserts; -import android.test.suitebuilder.annotation.SmallTest; import android.text.format.DateUtils; import android.util.RecurrenceRule; @@ -64,11 +68,17 @@ import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + /** * Tests for {@link NetworkStatsCollection}. */ +@RunWith(AndroidJUnit4.class) @SmallTest -public class NetworkStatsCollectionTest extends AndroidTestCase { +public class NetworkStatsCollectionTest { private static final String TEST_FILE = "test.bin"; private static final String TEST_IMSI = "310260000000000"; @@ -79,18 +89,15 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { private static Clock sOriginalClock; - @Override + @Before public void setUp() throws Exception { - super.setUp(); sOriginalClock = RecurrenceRule.sClock; - // ignore any device overlay while testing NetworkTemplate.forceAllNetworkTypes(); } - @Override - protected void tearDown() throws Exception { - super.tearDown(); + @After + public void tearDown() throws Exception { RecurrenceRule.sClock = sOriginalClock; } @@ -98,8 +105,10 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { RecurrenceRule.sClock = Clock.fixed(instant, ZoneId.systemDefault()); } + @Test public void testReadLegacyNetwork() throws Exception { - final File testFile = new File(getContext().getFilesDir(), TEST_FILE); + final File testFile = + new File(InstrumentationRegistry.getContext().getFilesDir(), TEST_FILE); stageFile(R.raw.netstats_v1, testFile); final NetworkStatsCollection collection = new NetworkStatsCollection(30 * MINUTE_IN_MILLIS); @@ -124,8 +133,10 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { 636016770L, 709306L, 88038768L, 518836L, NetworkStatsAccess.Level.DEVICE); } + @Test public void testReadLegacyUid() throws Exception { - final File testFile = new File(getContext().getFilesDir(), TEST_FILE); + final File testFile = + new File(InstrumentationRegistry.getContext().getFilesDir(), TEST_FILE); stageFile(R.raw.netstats_uid_v4, testFile); final NetworkStatsCollection collection = new NetworkStatsCollection(30 * MINUTE_IN_MILLIS); @@ -150,8 +161,10 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { 637076152L, 711413L, 88343717L, 521022L, NetworkStatsAccess.Level.DEVICE); } + @Test public void testReadLegacyUidTags() throws Exception { - final File testFile = new File(getContext().getFilesDir(), TEST_FILE); + final File testFile = + new File(InstrumentationRegistry.getContext().getFilesDir(), TEST_FILE); stageFile(R.raw.netstats_uid_v4, testFile); final NetworkStatsCollection collection = new NetworkStatsCollection(30 * MINUTE_IN_MILLIS); @@ -176,6 +189,7 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { 77017831L, 100995L, 35436758L, 92344L); } + @Test public void testStartEndAtomicBuckets() throws Exception { final NetworkStatsCollection collection = new NetworkStatsCollection(HOUR_IN_MILLIS); @@ -190,6 +204,7 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { assertEquals(2 * HOUR_IN_MILLIS, collection.getEndMillis()); } + @Test public void testAccessLevels() throws Exception { final NetworkStatsCollection collection = new NetworkStatsCollection(HOUR_IN_MILLIS); final NetworkStats.Entry entry = new NetworkStats.Entry(); @@ -250,8 +265,10 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { 0, NetworkStatsAccess.Level.DEVICE); } + @Test public void testAugmentPlan() throws Exception { - final File testFile = new File(getContext().getFilesDir(), TEST_FILE); + final File testFile = + new File(InstrumentationRegistry.getContext().getFilesDir(), TEST_FILE); stageFile(R.raw.netstats_v1, testFile); final NetworkStatsCollection emptyCollection = new NetworkStatsCollection(30 * MINUTE_IN_MILLIS); @@ -439,6 +456,7 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { } } + @Test public void testAugmentPlanGigantic() throws Exception { // We're in the future, but not that far off setClock(Instant.parse("2012-06-01T00:00:00.00Z")); @@ -461,6 +479,7 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { assertEquals(4_939_212_386L, getHistory(large, plan, TIME_A, TIME_C).getTotalBytes()); } + @Test public void testRounding() throws Exception { final NetworkStatsCollection coll = new NetworkStatsCollection(HOUR_IN_MILLIS); @@ -482,6 +501,7 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { assertEquals(TIME_A - HOUR_IN_MILLIS, coll.roundDown(TIME_A - 1)); } + @Test public void testMultiplySafe() { assertEquals(25, multiplySafe(50, 1, 2)); assertEquals(100, multiplySafe(50, 2, 1)); @@ -510,7 +530,7 @@ public class NetworkStatsCollectionTest extends AndroidTestCase { InputStream in = null; OutputStream out = null; try { - in = getContext().getResources().openRawResource(rawId); + in = InstrumentationRegistry.getContext().getResources().openRawResource(rawId); out = new FileOutputStream(file); Streams.copy(in, out); } finally { diff --git a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java index ecc99323d7d7..65be5ffb32a2 100644 --- a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java +++ b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java @@ -85,8 +85,8 @@ import android.os.Messenger; import android.os.PowerManager; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; +import android.support.test.filters.SmallTest; import android.telephony.TelephonyManager; -import android.test.suitebuilder.annotation.SmallTest; import android.util.Log; import android.util.TrustedTime; @@ -201,7 +201,6 @@ public class NetworkStatsServiceTest { ArgumentCaptor.forClass(INetworkManagementEventObserver.class); verify(mNetManager).registerObserver(networkObserver.capture()); mNetworkObserver = networkObserver.getValue(); - } @After diff --git a/tests/permission/Android.mk b/tests/permission/Android.mk index 54688c891046..7f81d9a3a894 100644 --- a/tests/permission/Android.mk +++ b/tests/permission/Android.mk @@ -7,8 +7,8 @@ LOCAL_MODULE_TAGS := tests # Include all test java files. LOCAL_SRC_FILES := $(call all-java-files-under, src) -LOCAL_JAVA_LIBRARIES := android.test.runner telephony-common -LOCAL_STATIC_JAVA_LIBRARIES := junit legacy-android-test +LOCAL_JAVA_LIBRARIES := android.test.runner telephony-common android.test.base +LOCAL_STATIC_JAVA_LIBRARIES := junit LOCAL_PACKAGE_NAME := FrameworkPermissionTests include $(BUILD_PACKAGE) diff --git a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java index 4aeae70ec979..9c4da1f72e38 100644 --- a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java +++ b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java @@ -24,7 +24,6 @@ import android.test.suitebuilder.annotation.SmallTest; import android.view.IWindowManager; import junit.framework.TestCase; -import static android.app.ActivityManager.StackId.INVALID_STACK_ID; import static android.view.Display.DEFAULT_DISPLAY; /** diff --git a/tests/privapp-permissions/Android.mk b/tests/privapp-permissions/Android.mk new file mode 100644 index 000000000000..b001c8c466a9 --- /dev/null +++ b/tests/privapp-permissions/Android.mk @@ -0,0 +1,31 @@ +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_PACKAGE_NAME := PrivAppPermissionTest +LOCAL_PRIVILEGED_MODULE := true +LOCAL_MANIFEST_FILE := system/AndroidManifest.xml +LOCAL_REQUIRED_MODULES := privapp-permissions-test.xml +include $(BUILD_PACKAGE) + +include $(CLEAR_VARS) +LOCAL_MODULE := privapp-permissions-test.xml +LOCAL_MODULE_CLASS := ETC +LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)/permissions +LOCAL_SRC_FILES:= system/privapp-permissions-test.xml +include $(BUILD_PREBUILT) + +include $(CLEAR_VARS) +LOCAL_PACKAGE_NAME := VendorPrivAppPermissionTest +LOCAL_PRIVILEGED_MODULE := true +LOCAL_MANIFEST_FILE := vendor/AndroidManifest.xml +LOCAL_VENDOR_MODULE := true +LOCAL_REQUIRED_MODULES := vendorprivapp-permissions-test.xml +include $(BUILD_PACKAGE) + +include $(CLEAR_VARS) +LOCAL_MODULE := vendorprivapp-permissions-test.xml +LOCAL_MODULE_CLASS := ETC +LOCAL_MODULE_PATH := $(TARGET_OUT_VENDOR_ETC)/permissions +LOCAL_SRC_FILES:= vendor/privapp-permissions-test.xml +include $(BUILD_PREBUILT) + diff --git a/tests/privapp-permissions/system/AndroidManifest.xml b/tests/privapp-permissions/system/AndroidManifest.xml new file mode 100644 index 000000000000..2099e31bd2c1 --- /dev/null +++ b/tests/privapp-permissions/system/AndroidManifest.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2017 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.framework.permission.privapp.tests.system"> + + <!-- MANAGE_USB is signature|privileged --> + <uses-permission android:name="android.permission.MANAGE_USB"/> +</manifest> diff --git a/tests/privapp-permissions/system/privapp-permissions-test.xml b/tests/privapp-permissions/system/privapp-permissions-test.xml new file mode 100644 index 000000000000..a0cb6bc74195 --- /dev/null +++ b/tests/privapp-permissions/system/privapp-permissions-test.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<permissions> + <privapp-permissions package="com.android.framework.permission.privapp.tests.system"> + <permission name="android.permission.MANAGE_USB"/> + </privapp-permissions> +</permissions> diff --git a/tests/privapp-permissions/vendor/AndroidManifest.xml b/tests/privapp-permissions/vendor/AndroidManifest.xml new file mode 100644 index 000000000000..78dedc5f199b --- /dev/null +++ b/tests/privapp-permissions/vendor/AndroidManifest.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + * Copyright (C) 2017 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.framework.permission.privapp.tests.vendor"> + + <!-- BIND_IMS_SERVICE is signature|privileged|vendorPrivileged --> + <uses-permission android:name="android.permission.BIND_IMS_SERVICE"/> + <!-- MANAGE_USB is signature|privileged and thus cannot be granted to this app --> + <uses-permission android:name="android.permission.MANAGE_USB"/> +</manifest> diff --git a/tests/privapp-permissions/vendor/privapp-permissions-test.xml b/tests/privapp-permissions/vendor/privapp-permissions-test.xml new file mode 100644 index 000000000000..51c588f0dea7 --- /dev/null +++ b/tests/privapp-permissions/vendor/privapp-permissions-test.xml @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="utf-8"?> +<permissions> + <privapp-permissions package="com.android.framework.permission.privapp.tests.vendor"> + <permission name="android.permission.BIND_IMS_SERVICE"/> + <permission name="android.permission.MANAGE_USB"/> + </privapp-permissions> +</permissions> diff --git a/tests/testables/Android.mk b/tests/testables/Android.mk index 0e36981e3716..7fcfc6eb82d3 100644 --- a/tests/testables/Android.mk +++ b/tests/testables/Android.mk @@ -25,10 +25,9 @@ LOCAL_SRC_FILES := $(call all-java-files-under,src) LOCAL_STATIC_JAVA_LIBRARIES := \ android-support-test \ - mockito-target-minus-junit4 \ - legacy-android-test + mockito-target-minus-junit4 -LOCAL_JAVA_LIBRARIES := android.test.runner +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.mock include $(BUILD_STATIC_JAVA_LIBRARY) diff --git a/tests/testables/src/android/testing/TestableContext.java b/tests/testables/src/android/testing/TestableContext.java index 498d517c104b..ffe721993a37 100644 --- a/tests/testables/src/android/testing/TestableContext.java +++ b/tests/testables/src/android/testing/TestableContext.java @@ -25,6 +25,7 @@ import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.content.res.Resources; +import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.os.UserHandle; @@ -69,6 +70,7 @@ public class TestableContext extends ContextWrapper implements TestRule { private LeakCheck.Tracker mService; private LeakCheck.Tracker mComponent; private TestableResources mTestableResources; + private TestablePermissions mTestablePermissions; public TestableContext(Context base) { this(base, null); @@ -302,6 +304,159 @@ public class TestableContext extends ContextWrapper implements TestRule { super.unregisterComponentCallbacks(callback); } + public TestablePermissions getTestablePermissions() { + if (mTestablePermissions == null) { + mTestablePermissions = new TestablePermissions(); + } + return mTestablePermissions; + } + + @Override + public int checkCallingOrSelfPermission(String permission) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(permission)) { + return mTestablePermissions.check(permission); + } + return super.checkCallingOrSelfPermission(permission); + } + + @Override + public int checkCallingPermission(String permission) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(permission)) { + return mTestablePermissions.check(permission); + } + return super.checkCallingPermission(permission); + } + + @Override + public int checkPermission(String permission, int pid, int uid) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(permission)) { + return mTestablePermissions.check(permission); + } + return super.checkPermission(permission, pid, uid); + } + + @Override + public int checkPermission(String permission, int pid, int uid, IBinder callerToken) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(permission)) { + return mTestablePermissions.check(permission); + } + return super.checkPermission(permission, pid, uid, callerToken); + } + + @Override + public int checkSelfPermission(String permission) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(permission)) { + return mTestablePermissions.check(permission); + } + return super.checkSelfPermission(permission); + } + + @Override + public void enforceCallingOrSelfPermission(String permission, String message) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(permission)) { + mTestablePermissions.enforce(permission); + } else { + super.enforceCallingOrSelfPermission(permission, message); + } + } + + @Override + public void enforceCallingPermission(String permission, String message) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(permission)) { + mTestablePermissions.enforce(permission); + } else { + super.enforceCallingPermission(permission, message); + } + } + + @Override + public void enforcePermission(String permission, int pid, int uid, String message) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(permission)) { + mTestablePermissions.enforce(permission); + } else { + super.enforcePermission(permission, pid, uid, message); + } + } + + @Override + public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(uri)) { + return mTestablePermissions.check(uri, modeFlags); + } + return super.checkCallingOrSelfUriPermission(uri, modeFlags); + } + + @Override + public int checkCallingUriPermission(Uri uri, int modeFlags) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(uri)) { + return mTestablePermissions.check(uri, modeFlags); + } + return super.checkCallingUriPermission(uri, modeFlags); + } + + @Override + public void enforceCallingOrSelfUriPermission(Uri uri, int modeFlags, String message) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(uri)) { + mTestablePermissions.enforce(uri, modeFlags); + } else { + super.enforceCallingOrSelfUriPermission(uri, modeFlags, message); + } + } + + @Override + public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(uri)) { + return mTestablePermissions.check(uri, modeFlags); + } + return super.checkUriPermission(uri, pid, uid, modeFlags); + } + + @Override + public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(uri)) { + return mTestablePermissions.check(uri, modeFlags); + } + return super.checkUriPermission(uri, pid, uid, modeFlags, callerToken); + } + + @Override + public int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, + int uid, int modeFlags) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(uri)) { + return mTestablePermissions.check(uri, modeFlags); + } + return super.checkUriPermission(uri, readPermission, writePermission, pid, uid, modeFlags); + } + + @Override + public void enforceCallingUriPermission(Uri uri, int modeFlags, String message) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(uri)) { + mTestablePermissions.enforce(uri, modeFlags); + } else { + super.enforceCallingUriPermission(uri, modeFlags, message); + } + } + + @Override + public void enforceUriPermission(Uri uri, int pid, int uid, int modeFlags, String message) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(uri)) { + mTestablePermissions.enforce(uri, modeFlags); + } else { + super.enforceUriPermission(uri, pid, uid, modeFlags, message); + } + } + + @Override + public void enforceUriPermission(Uri uri, String readPermission, String writePermission, + int pid, int uid, int modeFlags, String message) { + if (mTestablePermissions != null && mTestablePermissions.wantsCall(uri)) { + mTestablePermissions.enforce(uri, modeFlags); + } else { + super.enforceUriPermission(uri, readPermission, writePermission, pid, uid, modeFlags, + message); + } + } + @Override public Statement apply(Statement base, Description description) { return new TestWatcher() { diff --git a/tests/testables/src/android/testing/TestablePermissions.java b/tests/testables/src/android/testing/TestablePermissions.java new file mode 100644 index 000000000000..4f009e406ca7 --- /dev/null +++ b/tests/testables/src/android/testing/TestablePermissions.java @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2017 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 android.testing; + +import android.content.pm.PackageManager; +import android.net.Uri; +import android.util.ArrayMap; + +/** + * Simple class for simulating basic permission states for tests. + * + * All enforce* and check* calls on TestableContext are considered the same + * and routed through the same check here. If more fine-grained control is + * required, then either a sub-class or spy on TestableContext is recommended. + */ +public class TestablePermissions { + + private final ArrayMap<String, Integer> mPermissions = new ArrayMap<>(); + private final ArrayMap<Uri, Integer> mUris = new ArrayMap<>(); + + /** + * Sets the return value for checkPermission* calls on TestableContext + * for a specific permission value. For all enforcePermission* calls + * they will throw a security exception if value != PERMISSION_GRANTED. + */ + public void setPermission(String permission, int value) { + mPermissions.put(permission, value); + } + + /** + * Sets the return value for checkUriPermission* calls on TestableContext + * for a specific permission value. For all enforceUriPermission* calls + * they will throw a security exception if value != PERMISSION_GRANTED. + */ + public void setPermission(Uri uri, int value) { + // TODO: Support modeFlags + mUris.put(uri, value); + } + + boolean wantsCall(String permission) { + return mPermissions.containsKey(permission); + } + + boolean wantsCall(Uri uri) { + return mUris.containsKey(uri); + } + + int check(String permission) { + return mPermissions.get(permission); + } + + int check(Uri uri, int modeFlags) { + // TODO: Support modeFlags + return mUris.get(uri); + } + + public void enforce(String permission) { + if (check(permission) != PackageManager.PERMISSION_GRANTED) { + throw new SecurityException(); + } + } + + public void enforce(Uri uri, int modeFlags) { + if (check(uri, modeFlags) != PackageManager.PERMISSION_GRANTED) { + throw new SecurityException(); + } + } +} diff --git a/tests/testables/src/android/testing/TestableResources.java b/tests/testables/src/android/testing/TestableResources.java index a2fa95deaa60..c60f07d56d92 100644 --- a/tests/testables/src/android/testing/TestableResources.java +++ b/tests/testables/src/android/testing/TestableResources.java @@ -39,7 +39,8 @@ public class TestableResources { private final Resources mResources; private final SparseArray<Object> mOverrides = new SparseArray<>(); - TestableResources(Resources realResources) { + /** Creates a TestableResources instance that calls through to the given real Resources. */ + public TestableResources(Resources realResources) { mResources = mock(Resources.class, withSettings() .spiedInstance(realResources) .defaultAnswer(this::answer)); diff --git a/tests/testables/tests/Android.mk b/tests/testables/tests/Android.mk index 16fe5351c161..6e20d797fb5d 100644 --- a/tests/testables/tests/Android.mk +++ b/tests/testables/tests/Android.mk @@ -28,10 +28,9 @@ LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res LOCAL_STATIC_JAVA_LIBRARIES := \ android-support-test \ mockito-target-minus-junit4 \ - legacy-android-test \ testables -LOCAL_JAVA_LIBRARIES := android.test.runner +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base android.test.mock LOCAL_CERTIFICATE := platform diff --git a/tests/testables/tests/AndroidManifest.xml b/tests/testables/tests/AndroidManifest.xml index f6006b0a7fa9..6435ad971476 100644 --- a/tests/testables/tests/AndroidManifest.xml +++ b/tests/testables/tests/AndroidManifest.xml @@ -15,9 +15,11 @@ --> <manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.android.testables"> + package="com.android.testables" android:sharedUserId="android.uid.system"> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> + <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" /> + <uses-permission android:name="android.permission.MANAGE_USERS" /> <application> <uses-library android:name="android.test.runner" /> diff --git a/tests/testables/tests/src/android/testing/TestablePermissionsTest.java b/tests/testables/tests/src/android/testing/TestablePermissionsTest.java new file mode 100644 index 000000000000..c56146e19a40 --- /dev/null +++ b/tests/testables/tests/src/android/testing/TestablePermissionsTest.java @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2017 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 android.testing; + +import static android.content.pm.PackageManager.PERMISSION_DENIED; +import static android.content.pm.PackageManager.PERMISSION_GRANTED; + +import static org.junit.Assert.assertEquals; + +import android.Manifest.permission; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.support.test.InstrumentationRegistry; +import android.support.test.filters.SmallTest; +import android.testing.TestableLooper.RunWithLooper; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +@SmallTest +@RunWith(AndroidTestingRunner.class) +public class TestablePermissionsTest { + + private static final Uri URI_1 = Uri.parse("content://my.authority/path1"); + private static final Uri URI_2 = Uri.parse("content://my.authority/path2"); + + @Rule + public TestableContext mContext = new TestableContext(InstrumentationRegistry.getContext()); + + @Test + public void testCheck() { + mContext.getTestablePermissions().setPermission(permission.INTERACT_ACROSS_USERS, + PERMISSION_GRANTED); + mContext.getTestablePermissions().setPermission(permission.INTERACT_ACROSS_USERS_FULL, + PERMISSION_DENIED); + assertEquals(PERMISSION_GRANTED, + mContext.checkPermission(permission.INTERACT_ACROSS_USERS, 0, 0)); + assertEquals(PERMISSION_DENIED, + mContext.checkPermission(permission.INTERACT_ACROSS_USERS_FULL, 0, 0)); + } + + @Test + public void testCheckUri() { + mContext.getTestablePermissions().setPermission(URI_1, PERMISSION_GRANTED); + mContext.getTestablePermissions().setPermission(URI_2, PERMISSION_DENIED); + + assertEquals(PERMISSION_GRANTED, mContext.checkUriPermission(URI_1, 0, 0, 0)); + assertEquals(PERMISSION_DENIED, mContext.checkUriPermission(URI_2, 0, 0, 0)); + } + + @Test + public void testEnforceNoException() { + mContext.getTestablePermissions().setPermission(permission.INTERACT_ACROSS_USERS, + PERMISSION_GRANTED); + mContext.enforceCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS, ""); + } + + @Test(expected = SecurityException.class) + public void testEnforceWithException() { + mContext.getTestablePermissions().setPermission(permission.INTERACT_ACROSS_USERS, + PERMISSION_DENIED); + mContext.enforceCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS, ""); + } + + @Test + public void testEnforceUriNoException() { + mContext.getTestablePermissions().setPermission(URI_1, PERMISSION_GRANTED); + mContext.enforceUriPermission(URI_1, 0, 0, 0, ""); + } + + @Test(expected = SecurityException.class) + public void testEnforceUriWithException() { + mContext.getTestablePermissions().setPermission(URI_1, PERMISSION_DENIED); + mContext.enforceUriPermission(URI_1, 0, 0, 0, ""); + } + +}
\ No newline at end of file diff --git a/tests/utils/testutils/Android.mk b/tests/utils/testutils/Android.mk index 43d1e37cafa3..543c652dc24a 100644 --- a/tests/utils/testutils/Android.mk +++ b/tests/utils/testutils/Android.mk @@ -25,9 +25,8 @@ LOCAL_SRC_FILES := $(call all-java-files-under,java) LOCAL_STATIC_JAVA_LIBRARIES := \ android-support-test \ - legacy-android-test \ mockito-target-minus-junit4 -LOCAL_JAVA_LIBRARIES := android.test.runner +LOCAL_JAVA_LIBRARIES := android.test.runner android.test.base android.test.mock include $(BUILD_STATIC_JAVA_LIBRARY) |