diff options
Diffstat (limited to 'core/tests')
128 files changed, 5519 insertions, 5739 deletions
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/AccessPointParserHelper.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/AccessPointParserHelper.java index 27363e8..a6057de 100644 --- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/AccessPointParserHelper.java +++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/AccessPointParserHelper.java @@ -215,7 +215,9 @@ public class AccessPointParserHelper { config.phase2.setValue(""); config.ca_cert.setValue(""); config.client_cert.setValue(""); - config.private_key.setValue(""); + config.engine.setValue(""); + config.engine_id.setValue(""); + config.key_id.setValue(""); config.identity.setValue(""); config.anonymous_identity.setValue(""); break; diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java index 3ffa085..3ec9031 100644 --- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java +++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java @@ -42,17 +42,13 @@ public class ConnectivityManagerStressTestRunner extends InstrumentationTestRunn public int mSleepTime = 2 * 60 * 1000; public String mReconnectSsid = "securenetdhcp"; public String mReconnectPassword = "androidwifi"; + public boolean mWifiOnlyFlag = false; @Override public TestSuite getAllTests() { TestSuite suite = new InstrumentationTestSuite(this); - if (!UtilHelper.isWifiOnly()) { - suite.addTestSuite(WifiApStress.class); - suite.addTestSuite(WifiStressTest.class); - } else { - // only the wifi stress tests - suite.addTestSuite(WifiStressTest.class); - } + suite.addTestSuite(WifiApStress.class); + suite.addTestSuite(WifiStressTest.class); return suite; } @@ -64,13 +60,11 @@ public class ConnectivityManagerStressTestRunner extends InstrumentationTestRunn @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); - if (!UtilHelper.isWifiOnly()) { - String valueStr = (String) icicle.get("softap_iterations"); - if (valueStr != null) { - int iteration = Integer.parseInt(valueStr); - if (iteration > 0) { - mSoftapIterations = iteration; - } + String valueStr = (String) icicle.get("softap_iterations"); + if (valueStr != null) { + int iteration = Integer.parseInt(valueStr); + if (iteration > 0) { + mSoftapIterations = iteration; } } @@ -107,5 +101,10 @@ public class ConnectivityManagerStressTestRunner extends InstrumentationTestRunn mSleepTime = 1000 * sleepTime; } } + + String wifiOnlyFlag = (String) icicle.get("wifi-only"); + if (wifiOnlyFlag != null) { + mWifiOnlyFlag = true; + } } } diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java index d375d4c..f01562c 100644 --- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java +++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java @@ -94,6 +94,7 @@ public class ConnectivityManagerTestActivity extends Activity { * Control Wifi States */ public WifiManager mWifiManager; + public WifiManager.Channel mChannel; /* * Verify connectivity state @@ -240,13 +241,17 @@ public class ConnectivityManagerTestActivity extends Activity { mCM = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); // Get an instance of WifiManager mWifiManager =(WifiManager)getSystemService(Context.WIFI_SERVICE); - mWifiManager.asyncConnect(this, new WifiServiceHandler()); + mContext = this; + mChannel = mWifiManager.initialize(mContext, mContext.getMainLooper(), null); - initializeNetworkStates(); + if (mWifiManager.isWifiApEnabled()) { + // if soft AP is enabled, disable it + mWifiManager.setWifiApEnabled(null, false); + log("Disable soft ap"); + } - mWifiManager.setWifiEnabled(true); + initializeNetworkStates(); log("Clear Wifi before we start the test."); - sleep(SHORT_TIMEOUT); removeConfiguredNetworksAndDisableWifi(); mWifiRegexs = mCM.getTetherableWifiRegexs(); } @@ -594,7 +599,14 @@ public class ConnectivityManagerTestActivity extends Activity { log("found " + ssid + " in the scan result list"); log("retry: " + retry); foundApInScanResults = true; - mWifiManager.connectNetwork(config); + mWifiManager.connect(mChannel, config, + new WifiManager.ActionListener() { + public void onSuccess() { + } + public void onFailure(int reason) { + log("connect failure " + reason); + } + }); break; } } @@ -636,12 +648,23 @@ public class ConnectivityManagerTestActivity extends Activity { */ public boolean disconnectAP() { // remove saved networks + if (!mWifiManager.isWifiEnabled()) { + log("Enabled wifi before remove configured networks"); + mWifiManager.setWifiEnabled(true); + sleep(SHORT_TIMEOUT); + } List<WifiConfiguration> wifiConfigList = mWifiManager.getConfiguredNetworks(); log("size of wifiConfigList: " + wifiConfigList.size()); for (WifiConfiguration wifiConfig: wifiConfigList) { log("remove wifi configuration: " + wifiConfig.networkId); int netId = wifiConfig.networkId; - mWifiManager.forgetNetwork(netId); + mWifiManager.forget(mChannel, netId, new WifiManager.ActionListener() { + public void onSuccess() { + } + public void onFailure(int reason) { + log("Failed to forget " + reason); + } + }); } return true; } diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestRunner.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestRunner.java index 20aae47..b94306a 100644 --- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestRunner.java +++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestRunner.java @@ -35,24 +35,13 @@ import junit.framework.TestSuite; */ public class ConnectivityManagerTestRunner extends InstrumentationTestRunner { - public String TEST_SSID = null; + public boolean mWifiOnlyFlag = false; + public String mTestSsid = null; @Override public TestSuite getAllTests() { TestSuite suite = new InstrumentationTestSuite(this); - if (!UtilHelper.isWifiOnly()) { - suite.addTestSuite(ConnectivityManagerMobileTest.class); - } else { - // create a new test suite - suite.setName("ConnectivityManagerWifiOnlyFunctionalTests"); - String[] methodNames = {"testConnectToWifi", "testConnectToWifWithKnownAP", - "testDisconnectWifi", "testDataConnectionOverAMWithWifi", - "testDataConnectionWithWifiToAMToWifi", "testWifiStateChange"}; - Class<ConnectivityManagerMobileTest> testClass = ConnectivityManagerMobileTest.class; - for (String method: methodNames) { - suite.addTest(TestSuite.createTest(testClass, method)); - } - } + suite.addTestSuite(ConnectivityManagerMobileTest.class); suite.addTestSuite(WifiConnectionTest.class); return suite; } @@ -67,7 +56,11 @@ public class ConnectivityManagerTestRunner extends InstrumentationTestRunner { super.onCreate(icicle); String testSSID = (String) icicle.get("ssid"); if (testSSID != null) { - TEST_SSID = testSSID; + mTestSsid = testSSID; + } + String wifiOnlyFlag = (String) icicle.get("wifi-only"); + if (wifiOnlyFlag != null) { + mWifiOnlyFlag = true; } } } diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/UtilHelper.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/UtilHelper.java deleted file mode 100644 index 1b966bf..0000000 --- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/UtilHelper.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2010 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.connectivitymanagertest; - -import android.os.SystemProperties; - -public class UtilHelper { - public static boolean isWifiOnly() { - return "wifi-only".equals(SystemProperties.get("ro.carrier")); - } - - -} diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/ConnectivityManagerMobileTest.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/ConnectivityManagerMobileTest.java index b1f4bf1..bf188d3 100644 --- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/ConnectivityManagerMobileTest.java +++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/ConnectivityManagerMobileTest.java @@ -16,37 +16,30 @@ package com.android.connectivitymanagertest.functional; -import com.android.connectivitymanagertest.ConnectivityManagerTestActivity; -import com.android.connectivitymanagertest.UtilHelper; - -import android.content.Intent; import android.content.Context; -import android.os.PowerManager; -import android.os.PowerManager.WakeLock; -import android.app.Instrumentation; -import android.os.Handler; -import android.os.Message; -import android.provider.Settings; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; -import android.net.NetworkInfo.DetailedState; import android.net.wifi.WifiManager; - -import android.test.suitebuilder.annotation.LargeTest; +import android.os.PowerManager; +import android.os.PowerManager.WakeLock; +import android.provider.Settings; import android.test.ActivityInstrumentationTestCase2; +import android.test.suitebuilder.annotation.LargeTest; +import android.util.Log; + +import com.android.connectivitymanagertest.ConnectivityManagerTestActivity; import com.android.connectivitymanagertest.ConnectivityManagerTestRunner; import com.android.connectivitymanagertest.NetworkState; -import android.util.Log; -public class ConnectivityManagerMobileTest - extends ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> { +public class ConnectivityManagerMobileTest extends + ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> { private static final String LOG_TAG = "ConnectivityManagerMobileTest"; - private static final String PKG_NAME = "com.android.connectivitymanagertest"; - private String TEST_ACCESS_POINT; + private String mTestAccessPoint; private ConnectivityManagerTestActivity cmActivity; private WakeLock wl; + private boolean mWifiOnlyFlag; public ConnectivityManagerMobileTest() { super(ConnectivityManagerTestActivity.class); @@ -58,7 +51,9 @@ public class ConnectivityManagerMobileTest cmActivity = getActivity(); ConnectivityManagerTestRunner mRunner = (ConnectivityManagerTestRunner)getInstrumentation(); - TEST_ACCESS_POINT = mRunner.TEST_SSID; + mTestAccessPoint = mRunner.mTestSsid; + mWifiOnlyFlag = mRunner.mWifiOnlyFlag; + PowerManager pm = (PowerManager)getInstrumentation(). getContext().getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "CMWakeLock"); @@ -69,7 +64,8 @@ public class ConnectivityManagerMobileTest log("airplane is not disabled, disable it."); cmActivity.setAirplaneMode(getInstrumentation().getContext(), false); } - if (!UtilHelper.isWifiOnly()) { + + if (!mWifiOnlyFlag) { if (!cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)) { // Note: When the test fails in setUp(), tearDown is not called. In that case, @@ -118,6 +114,10 @@ public class ConnectivityManagerMobileTest // event should be expected. @LargeTest public void test3GToWifiNotification() { + if (mWifiOnlyFlag) { + Log.v(LOG_TAG, this.getName() + " is excluded for wifi-only test"); + return; + } // Enable Wi-Fi to avoid initial UNKNOWN state cmActivity.enableWifi(); sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT); @@ -164,9 +164,9 @@ public class ConnectivityManagerMobileTest // Test case 2: test connection to a given AP @LargeTest public void testConnectToWifi() { - assertNotNull("SSID is null", TEST_ACCESS_POINT); + assertNotNull("SSID is null", mTestAccessPoint); NetworkInfo networkInfo; - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { //Prepare for connectivity verification networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE, @@ -177,15 +177,15 @@ public class ConnectivityManagerMobileTest NetworkState.TO_CONNECTION, State.CONNECTED); // Enable Wifi and connect to a test access point - assertTrue("failed to connect to " + TEST_ACCESS_POINT, - cmActivity.connectToWifi(TEST_ACCESS_POINT)); + assertTrue("failed to connect to " + mTestAccessPoint, + cmActivity.connectToWifi(mTestAccessPoint)); assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_ENABLED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); log("wifi state is enabled"); assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); } @@ -197,7 +197,7 @@ public class ConnectivityManagerMobileTest cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI)); assertTrue(false); } - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) { log("Mobile state transition validation failed."); log("reason: " + @@ -210,10 +210,10 @@ public class ConnectivityManagerMobileTest // Test case 3: connect to Wifi with known AP @LargeTest public void testConnectToWifWithKnownAP() { - assertNotNull("SSID is null", TEST_ACCESS_POINT); - // Connect to TEST_ACCESS_POINT - assertTrue("failed to connect to " + TEST_ACCESS_POINT, - cmActivity.connectToWifi(TEST_ACCESS_POINT)); + assertNotNull("SSID is null", mTestAccessPoint); + // Connect to mTestAccessPoint + assertTrue("failed to connect to " + mTestAccessPoint, + cmActivity.connectToWifi(mTestAccessPoint)); assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_ENABLED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED, @@ -232,13 +232,13 @@ public class ConnectivityManagerMobileTest ConnectivityManagerTestActivity.LONG_TIMEOUT)); assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); } NetworkInfo networkInfo; - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { //Prepare for connectivity state verification networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE, @@ -258,7 +258,7 @@ public class ConnectivityManagerMobileTest // Wait for Wifi to be connected and mobile to be disconnected assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); } @@ -275,11 +275,11 @@ public class ConnectivityManagerMobileTest // Test case 4: test disconnect Wifi @LargeTest public void testDisconnectWifi() { - assertNotNull("SSID is null", TEST_ACCESS_POINT); + assertNotNull("SSID is null", mTestAccessPoint); // connect to Wifi - assertTrue("failed to connect to " + TEST_ACCESS_POINT, - cmActivity.connectToWifi(TEST_ACCESS_POINT)); + assertTrue("failed to connect to " + mTestAccessPoint, + cmActivity.connectToWifi(mTestAccessPoint)); assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); @@ -288,7 +288,7 @@ public class ConnectivityManagerMobileTest sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT); NetworkInfo networkInfo; - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE, networkInfo.getState(), @@ -304,7 +304,7 @@ public class ConnectivityManagerMobileTest assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); } @@ -316,7 +316,7 @@ public class ConnectivityManagerMobileTest cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI)); assertTrue(false); } - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) { log("Mobile state transition validation failed."); log("reason: " + @@ -329,6 +329,10 @@ public class ConnectivityManagerMobileTest // Test case 5: test connectivity from 3G to airplane mode, then to 3G again @LargeTest public void testDataConnectionWith3GToAmTo3G() { + if (mWifiOnlyFlag) { + Log.v(LOG_TAG, this.getName() + " is excluded for wifi-only test"); + return; + } //Prepare for state verification NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE, @@ -345,7 +349,9 @@ public class ConnectivityManagerMobileTest networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI); assertEquals(State.DISCONNECTED, networkInfo.getState()); - + // wait until mobile is turn off + assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, + State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) { log("Mobile state transition validation failed."); log("reason: " + @@ -387,13 +393,17 @@ public class ConnectivityManagerMobileTest // Test case 6: test connectivity with airplane mode Wifi connected @LargeTest public void testDataConnectionOverAMWithWifi() { - assertNotNull("SSID is null", TEST_ACCESS_POINT); + if (mWifiOnlyFlag) { + Log.v(LOG_TAG, this.getName() + " is excluded for wifi-only test"); + return; + } + assertNotNull("SSID is null", mTestAccessPoint); // Eanble airplane mode log("Enable airplane mode"); cmActivity.setAirplaneMode(getInstrumentation().getContext(), true); NetworkInfo networkInfo; - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); @@ -407,8 +417,8 @@ public class ConnectivityManagerMobileTest NetworkState.TO_CONNECTION, State.CONNECTED); // Connect to Wifi - assertTrue("failed to connect to " + TEST_ACCESS_POINT, - cmActivity.connectToWifi(TEST_ACCESS_POINT)); + assertTrue("failed to connect to " + mTestAccessPoint, + cmActivity.connectToWifi(mTestAccessPoint)); assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); @@ -419,7 +429,7 @@ public class ConnectivityManagerMobileTest cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI)); assertTrue("State validation failed", false); } - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) { log("state validation for Mobile failed"); log("reason: " + @@ -433,11 +443,15 @@ public class ConnectivityManagerMobileTest // Test case 7: test connectivity while transit from Wifi->AM->Wifi @LargeTest public void testDataConnectionWithWifiToAMToWifi () { - // Connect to TEST_ACCESS_POINT - assertNotNull("SSID is null", TEST_ACCESS_POINT); + if (mWifiOnlyFlag) { + Log.v(LOG_TAG, this.getName() + " is excluded for wifi-only test"); + return; + } + // Connect to mTestAccessPoint + assertNotNull("SSID is null", mTestAccessPoint); // Connect to Wifi - assertTrue("failed to connect to " + TEST_ACCESS_POINT, - cmActivity.connectToWifi(TEST_ACCESS_POINT)); + assertTrue("failed to connect to " + mTestAccessPoint, + cmActivity.connectToWifi(mTestAccessPoint)); assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); @@ -471,7 +485,7 @@ public class ConnectivityManagerMobileTest assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.DISCONNECTED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); } @@ -488,10 +502,10 @@ public class ConnectivityManagerMobileTest // Test case 8: test wifi state change while connecting/disconnecting to/from an AP @LargeTest public void testWifiStateChange () { - assertNotNull("SSID is null", TEST_ACCESS_POINT); - //Connect to TEST_ACCESS_POINT - assertTrue("failed to connect to " + TEST_ACCESS_POINT, - cmActivity.connectToWifi(TEST_ACCESS_POINT)); + assertNotNull("SSID is null", mTestAccessPoint); + //Connect to mTestAccessPoint + assertTrue("failed to connect to " + mTestAccessPoint, + cmActivity.connectToWifi(mTestAccessPoint)); assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_ENABLED, ConnectivityManagerTestActivity.LONG_TIMEOUT)); assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED, @@ -508,7 +522,7 @@ public class ConnectivityManagerMobileTest // Disconnect from the current AP log("disconnect from the AP"); if (!cmActivity.disconnectAP()) { - log("failed to disconnect from " + TEST_ACCESS_POINT); + log("failed to disconnect from " + mTestAccessPoint); } // Verify the connectivity state for Wifi is DISCONNECTED diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiConnectionTest.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiConnectionTest.java index d33a445..8d73bc0 100644 --- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiConnectionTest.java +++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiConnectionTest.java @@ -63,6 +63,7 @@ public class WifiConnectionTest private ConnectivityManagerTestActivity mAct; private ConnectivityManagerTestRunner mRunner; private WifiManager mWifiManager = null; + private WifiManager.Channel mChannel; private Set<WifiConfiguration> enabledNetworks = null; public WifiConnectionTest() { @@ -76,7 +77,8 @@ public class WifiConnectionTest mWifiManager = (WifiManager) mRunner.getContext().getSystemService(Context.WIFI_SERVICE); mAct = getActivity(); - mWifiManager.asyncConnect(mAct, new WifiServiceHandler()); + mChannel = mWifiManager.initialize(mAct, mAct.getMainLooper(), null); + networks = mAct.loadNetworkConfigurations(); if (DEBUG) { printNetworkConfigurations(); diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java index 41104fe..60595fb 100644 --- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java +++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java @@ -51,6 +51,7 @@ public class WifiApStress private int iterations; private BufferedWriter mOutputWriter = null; private int mLastIteration = 0; + private boolean mWifiOnlyFlag; public WifiApStress() { super(ConnectivityManagerTestActivity.class); @@ -63,6 +64,7 @@ public class WifiApStress ConnectivityManagerStressTestRunner mRunner = (ConnectivityManagerStressTestRunner)getInstrumentation(); iterations = mRunner.mSoftapIterations; + mWifiOnlyFlag = mRunner.mWifiOnlyFlag; mAct.turnScreenOn(); } @@ -79,6 +81,10 @@ public class WifiApStress @LargeTest public void testWifiHotSpot() { + if (mWifiOnlyFlag) { + Log.v(TAG, this.getName() + " is excluded for wi-fi only test"); + return; + } WifiConfiguration config = new WifiConfiguration(); config.SSID = NETWORK_ID; config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); @@ -97,7 +103,7 @@ public class WifiApStress assertTrue(mAct.mWifiManager.setWifiApEnabled(config, true)); // Wait for wifi ap state to be ENABLED assertTrue(mAct.waitForWifiAPState(WifiManager.WIFI_AP_STATE_ENABLED, - ConnectivityManagerTestActivity.LONG_TIMEOUT)); + 2 * ConnectivityManagerTestActivity.LONG_TIMEOUT)); // Wait for wifi tethering result assertEquals(ConnectivityManagerTestActivity.SUCCESS, mAct.waitForTetherStateChange(2*ConnectivityManagerTestActivity.SHORT_TIMEOUT)); diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java index 2069789..39e2cf2 100644 --- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java +++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java @@ -16,10 +16,6 @@ package com.android.connectivitymanagertest.stress; -import com.android.connectivitymanagertest.ConnectivityManagerStressTestRunner; -import com.android.connectivitymanagertest.ConnectivityManagerTestActivity; -import com.android.connectivitymanagertest.UtilHelper; - import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo.State; @@ -31,15 +27,14 @@ import android.net.wifi.WifiConfiguration.ProxySettings; import android.net.wifi.WifiManager; import android.os.Environment; import android.os.PowerManager; -import android.os.IPowerManager; -import android.os.SystemClock; -import android.os.ServiceManager; import android.provider.Settings; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.LargeTest; - import android.util.Log; +import com.android.connectivitymanagertest.ConnectivityManagerStressTestRunner; +import com.android.connectivitymanagertest.ConnectivityManagerTestActivity; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -79,6 +74,7 @@ public class WifiStressTest private String mPassword; private ConnectivityManagerStressTestRunner mRunner; private BufferedWriter mOutputWriter = null; + private boolean mWifiOnlyFlag; public WifiStressTest() { super(ConnectivityManagerTestActivity.class); @@ -87,6 +83,7 @@ public class WifiStressTest @Override public void setUp() throws Exception { super.setUp(); + mAct = getActivity(); mRunner = (ConnectivityManagerStressTestRunner) getInstrumentation(); mReconnectIterations = mRunner.mReconnectIterations; @@ -94,6 +91,7 @@ public class WifiStressTest mPassword = mRunner.mReconnectPassword; mScanIterations = mRunner.mScanIterations; mWifiSleepTime = mRunner.mSleepTime; + mWifiOnlyFlag = mRunner.mWifiOnlyFlag; log(String.format("mReconnectIterations(%d), mSsid(%s), mPassword(%s)," + "mScanIterations(%d), mWifiSleepTime(%d)", mReconnectIterations, mSsid, mPassword, mScanIterations, mWifiSleepTime)); @@ -271,7 +269,7 @@ public class WifiStressTest assertTrue("Wait for Wi-Fi to idle timeout", mAct.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED, 6 * ConnectivityManagerTestActivity.SHORT_TIMEOUT)); - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { // use long timeout as the pppd startup may take several retries. assertTrue("Wait for cellular connection timeout", mAct.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED, @@ -282,7 +280,7 @@ public class WifiStressTest assertEquals("Wi-Fi is reconnected", State.DISCONNECTED, mAct.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()); - if (!UtilHelper.isWifiOnly()) { + if (!mWifiOnlyFlag) { assertEquals("Cellular connection is down", State.CONNECTED, mAct.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState()); assertTrue("Mobile is connected, but no data connection.", mAct.pingTest(null)); diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/unit/WifiClientTest.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/unit/WifiClientTest.java index e22b018..e44023b 100644 --- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/unit/WifiClientTest.java +++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/unit/WifiClientTest.java @@ -271,4 +271,46 @@ public class WifiClientTest extends AndroidTestCase { } + // Test case 6: test configured network status + @LargeTest + public void testWifiConfiguredNetworkStatus() { + + /* Initialize */ + mWifiManager.setWifiEnabled(false); + sleepAfterWifiEnable(); + + /* Ensure no network is CURRENT */ + List<WifiConfiguration> configList = mWifiManager.getConfiguredNetworks(); + for (WifiConfiguration c : configList) { + assertTrue(c.status != WifiConfiguration.Status.CURRENT); + } + + /* Enable wifi */ + mWifiManager.setWifiEnabled(true); + sleepAfterWifiEnable(); + + /* Ensure connected network is CURRENT */ + String connectedSSID = mWifiManager.getConnectionInfo().getSSID(); + configList = mWifiManager.getConfiguredNetworks(); + for (WifiConfiguration c : configList) { + if (c.SSID.contains(connectedSSID)) { + assertTrue(c.status == WifiConfiguration.Status.CURRENT); + } else { + assertTrue(c.status != WifiConfiguration.Status.CURRENT); + } + } + + /* Disable wifi */ + mWifiManager.setWifiEnabled(false); + sleepAfterWifiEnable(); + + /* Ensure no network is CURRENT */ + configList = mWifiManager.getConfiguredNetworks(); + for (WifiConfiguration c : configList) { + assertTrue(c.status != WifiConfiguration.Status.CURRENT); + } + } + + + } diff --git a/core/tests/bandwidthtests/src/com/android/bandwidthtest/util/ConnectionUtil.java b/core/tests/bandwidthtests/src/com/android/bandwidthtest/util/ConnectionUtil.java index 75d3cce..c3cc7c5 100644 --- a/core/tests/bandwidthtests/src/com/android/bandwidthtest/util/ConnectionUtil.java +++ b/core/tests/bandwidthtests/src/com/android/bandwidthtest/util/ConnectionUtil.java @@ -74,6 +74,7 @@ public class ConnectionUtil { private int mWifiState; private NetworkInfo mWifiNetworkInfo; private WifiManager mWifiManager; + private WifiManager.Channel mChannel; private Context mContext; // Verify connectivity state private static final int NUM_NETWORK_TYPES = ConnectivityManager.MAX_NETWORK_TYPE + 1; @@ -114,7 +115,7 @@ public class ConnectionUtil { // Get an instance of WifiManager mWifiManager =(WifiManager)mContext.getSystemService(Context.WIFI_SERVICE); - mWifiManager.asyncConnect(mContext, new WifiServiceHandler()); + mChannel = mWifiManager.initialize(mContext, mContext.getMainLooper(), null); mDownloadManager = (DownloadManager)mContext.getSystemService(Context.DOWNLOAD_SERVICE); @@ -573,7 +574,14 @@ public class ConnectionUtil { Log.v(LOG_TAG, "Found " + ssid + " in the scan result list."); Log.v(LOG_TAG, "Retry: " + retry); foundApInScanResults = true; - mWifiManager.connectNetwork(config); + mWifiManager.connect(mChannel, config, new WifiManager.ActionListener() { + public void onSuccess() { + } + public void onFailure(int reason) { + Log.e(LOG_TAG, "connect failed " + reason); + } + }); + break; } } @@ -620,7 +628,13 @@ public class ConnectionUtil { for (WifiConfiguration wifiConfig: wifiConfigList) { Log.v(LOG_TAG, "Remove wifi configuration: " + wifiConfig.networkId); int netId = wifiConfig.networkId; - mWifiManager.forgetNetwork(netId); + mWifiManager.forget(mChannel, netId, new WifiManager.ActionListener() { + public void onSuccess() { + } + public void onFailure(int reason) { + Log.e(LOG_TAG, "forget failed " + reason); + } + }); } return true; } @@ -729,4 +743,4 @@ public class ConnectionUtil { } return false; } -}
\ No newline at end of file +} diff --git a/core/tests/benchmarks/README b/core/tests/benchmarks/README new file mode 100644 index 0000000..0a41bcc --- /dev/null +++ b/core/tests/benchmarks/README @@ -0,0 +1,8 @@ + +These benchmarks use the Caliper benchmark framework, and can be +run on a remote device using Vogar: + +http://code.google.com/p/caliper/ +http://code.google.com/p/vogar/ + +$ vogar --benchmark path/to/Benchmark.java diff --git a/core/tests/benchmarks/src/android/os/ParcelArrayBenchmark.java b/core/tests/benchmarks/src/android/os/ParcelArrayBenchmark.java new file mode 100644 index 0000000..21cfb09 --- /dev/null +++ b/core/tests/benchmarks/src/android/os/ParcelArrayBenchmark.java @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2012 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.os; + +import com.google.caliper.Param; +import com.google.caliper.SimpleBenchmark; + +public class ParcelArrayBenchmark extends SimpleBenchmark { + + @Param({ "1", "10", "100", "1000" }) + private int mSize; + + private Parcel mWriteParcel; + + private byte[] mByteArray; + private int[] mIntArray; + private long[] mLongArray; + + private Parcel mByteParcel; + private Parcel mIntParcel; + private Parcel mLongParcel; + + @Override + protected void setUp() { + mWriteParcel = Parcel.obtain(); + + mByteArray = new byte[mSize]; + mIntArray = new int[mSize]; + mLongArray = new long[mSize]; + + mByteParcel = Parcel.obtain(); + mByteParcel.writeByteArray(mByteArray); + mIntParcel = Parcel.obtain(); + mIntParcel.writeIntArray(mIntArray); + mLongParcel = Parcel.obtain(); + mLongParcel.writeLongArray(mLongArray); + } + + @Override + protected void tearDown() { + mWriteParcel.recycle(); + mWriteParcel = null; + } + + public void timeWriteByteArray(int reps) { + for (int i = 0; i < reps; i++) { + mWriteParcel.setDataPosition(0); + mWriteParcel.writeByteArray(mByteArray); + } + } + + public void timeCreateByteArray(int reps) { + for (int i = 0; i < reps; i++) { + mByteParcel.setDataPosition(0); + mByteParcel.createByteArray(); + } + } + + public void timeReadByteArray(int reps) { + for (int i = 0; i < reps; i++) { + mByteParcel.setDataPosition(0); + mByteParcel.readByteArray(mByteArray); + } + } + + public void timeWriteIntArray(int reps) { + for (int i = 0; i < reps; i++) { + mWriteParcel.setDataPosition(0); + mWriteParcel.writeIntArray(mIntArray); + } + } + + public void timeCreateIntArray(int reps) { + for (int i = 0; i < reps; i++) { + mIntParcel.setDataPosition(0); + mIntParcel.createIntArray(); + } + } + + public void timeReadIntArray(int reps) { + for (int i = 0; i < reps; i++) { + mIntParcel.setDataPosition(0); + mIntParcel.readIntArray(mIntArray); + } + } + + public void timeWriteLongArray(int reps) { + for (int i = 0; i < reps; i++) { + mWriteParcel.setDataPosition(0); + mWriteParcel.writeLongArray(mLongArray); + } + } + + public void timeCreateLongArray(int reps) { + for (int i = 0; i < reps; i++) { + mLongParcel.setDataPosition(0); + mLongParcel.createLongArray(); + } + } + + public void timeReadLongArray(int reps) { + for (int i = 0; i < reps; i++) { + mLongParcel.setDataPosition(0); + mLongParcel.readLongArray(mLongArray); + } + } + +} diff --git a/core/tests/benchmarks/src/android/os/ParcelBenchmark.java b/core/tests/benchmarks/src/android/os/ParcelBenchmark.java new file mode 100644 index 0000000..6a7b7c8 --- /dev/null +++ b/core/tests/benchmarks/src/android/os/ParcelBenchmark.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2012 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.os; + +import com.google.caliper.SimpleBenchmark; + +public class ParcelBenchmark extends SimpleBenchmark { + + private Parcel mParcel; + + @Override + protected void setUp() { + mParcel = Parcel.obtain(); + } + + @Override + protected void tearDown() { + mParcel.recycle(); + mParcel = null; + } + + public void timeWriteByte(int reps) { + final byte val = 0xF; + for (int i = 0; i < reps; i++) { + mParcel.writeByte(val); + } + } + + public void timeReadByte(int reps) { + mParcel.setDataCapacity(reps); + for (int i = 0; i < reps; i++) { + mParcel.readByte(); + } + } + + public void timeWriteInt(int reps) { + final int val = 0xF; + for (int i = 0; i < reps; i++) { + mParcel.writeInt(val); + } + } + + public void timeReadInt(int reps) { + mParcel.setDataCapacity(reps << 2); + for (int i = 0; i < reps; i++) { + mParcel.readInt(); + } + } + + public void timeWriteLong(int reps) { + final long val = 0xF; + for (int i = 0; i < reps; i++) { + mParcel.writeLong(val); + } + } + + public void timeReadLong(int reps) { + mParcel.setDataCapacity(reps << 3); + for (int i = 0; i < reps; i++) { + mParcel.readLong(); + } + } +} diff --git a/core/tests/coretests/Android.mk b/core/tests/coretests/Android.mk index b2ebb08..88f3f34 100644 --- a/core/tests/coretests/Android.mk +++ b/core/tests/coretests/Android.mk @@ -1,4 +1,14 @@ -LOCAL_PATH:= $(call my-dir) +ACTUAL_LOCAL_PATH := $(call my-dir) + +# this var will hold all the test apk module names later. +FrameworkCoreTests_all_apks := + +# We have to include the subdir makefiles first +# so that FrameworkCoreTests_all_apks will be populated correctly. +include $(call all-makefiles-under,$(ACTUAL_LOCAL_PATH)) + +LOCAL_PATH := $(ACTUAL_LOCAL_PATH) + include $(CLEAR_VARS) # We only want this apk build for tests. @@ -12,12 +22,27 @@ LOCAL_SRC_FILES := \ $(call all-java-files-under, EnabledTestApp/src) LOCAL_DX_FLAGS := --core-library -LOCAL_STATIC_JAVA_LIBRARIES := core-tests android-common frameworks-core-util-lib mockwebserver guava +LOCAL_STATIC_JAVA_LIBRARIES := core-tests android-common frameworks-core-util-lib mockwebserver guava littlemock LOCAL_JAVA_LIBRARIES := android.test.runner LOCAL_PACKAGE_NAME := FrameworksCoreTests LOCAL_CERTIFICATE := platform +# intermediate dir to include all the test apks as raw resource +FrameworkCoreTests_intermediates := $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME))/test_apks/res +LOCAL_RESOURCE_DIR := $(FrameworkCoreTests_intermediates) $(LOCAL_PATH)/res + include $(BUILD_PACKAGE) +# Rules to copy all the test apks to the intermediate raw resource directory +FrameworkCoreTests_all_apks_res := $(addprefix $(FrameworkCoreTests_intermediates)/raw/, \ + $(foreach a, $(FrameworkCoreTests_all_apks), $(patsubst FrameworkCoreTests_%,%,$(a)))) + +$(FrameworkCoreTests_all_apks_res): $(FrameworkCoreTests_intermediates)/raw/%: $(call intermediates-dir-for,APPS,FrameworkCoreTests_%)/package.apk | $(ACP) + $(call copy-file-to-new-target) + +# Use R_file_stamp as dependency because we want the test apks in place before the R.java is generated. +$(R_file_stamp) : $(FrameworkCoreTests_all_apks_res) -include $(call all-makefiles-under,$(LOCAL_PATH)) +FrameworkCoreTests_all_apks := +FrameworkCoreTests_intermediates := +FrameworkCoreTests_all_apks_res := diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml index cadc895..dcd1bab 100644 --- a/core/tests/coretests/AndroidManifest.xml +++ b/core/tests/coretests/AndroidManifest.xml @@ -1039,7 +1039,8 @@ </intent-filter> </activity> - <service android:name="android.webkit.AccessibilityInjectorTest$MockAccessibilityService"> + <service android:name="android.webkit.AccessibilityInjectorTest$MockAccessibilityService" + android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"> <intent-filter> <action android:name="android.accessibilityservice.AccessibilityService" /> </intent-filter> diff --git a/core/tests/coretests/apks/Android.mk b/core/tests/coretests/apks/Android.mk index 4670e21..98c0c2a 100644 --- a/core/tests/coretests/apks/Android.mk +++ b/core/tests/coretests/apks/Android.mk @@ -1,5 +1,7 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) +FrameworkCoreTests_BUILD_PACKAGE := $(LOCAL_PATH)/FrameworkCoreTests_apk.mk + # build sub packages include $(call all-makefiles-under,$(LOCAL_PATH)) diff --git a/core/tests/coretests/apks/FrameworkCoreTests_apk.mk b/core/tests/coretests/apks/FrameworkCoreTests_apk.mk new file mode 100644 index 0000000..ac545ca --- /dev/null +++ b/core/tests/coretests/apks/FrameworkCoreTests_apk.mk @@ -0,0 +1,12 @@ + +LOCAL_MODULE_TAGS := tests + +# Disable dexpreopt. +LOCAL_DEX_PREOPT := false + +# Make sure every package name gets the FrameworkCoreTests_ prefix. +LOCAL_PACKAGE_NAME := FrameworkCoreTests_$(LOCAL_PACKAGE_NAME) + +FrameworkCoreTests_all_apks += $(LOCAL_PACKAGE_NAME) + +include $(BUILD_PACKAGE) diff --git a/core/tests/coretests/apks/install/Android.mk b/core/tests/coretests/apks/install/Android.mk new file mode 100644 index 0000000..b38dc20 --- /dev/null +++ b/core/tests/coretests/apks/install/Android.mk @@ -0,0 +1,8 @@ +LOCAL_PATH:= $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := $(call all-subdir-java-files) + +LOCAL_PACKAGE_NAME := install + +include $(FrameworkCoreTests_BUILD_PACKAGE) diff --git a/core/tests/coretests/apks/install/AndroidManifest.xml b/core/tests/coretests/apks/install/AndroidManifest.xml new file mode 100644 index 0000000..60f1ba0 --- /dev/null +++ b/core/tests/coretests/apks/install/AndroidManifest.xml @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2010 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.coretests.install_loc"> + + <application android:hasCode="false"> + </application> +</manifest> diff --git a/core/tests/coretests/apks/install/res/values/strings.xml b/core/tests/coretests/apks/install/res/values/strings.xml new file mode 100644 index 0000000..3b8b3b1 --- /dev/null +++ b/core/tests/coretests/apks/install/res/values/strings.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> + +<!-- Just need this dummy file to have something to build. --> +<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> + <string name="dummy">dummy</string> +</resources> diff --git a/core/tests/coretests/apks/install_decl_perm/Android.mk b/core/tests/coretests/apks/install_decl_perm/Android.mk index c38e981..86370c8 100644 --- a/core/tests/coretests/apks/install_decl_perm/Android.mk +++ b/core/tests/coretests/apks/install_decl_perm/Android.mk @@ -1,11 +1,8 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := tests - LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_PACKAGE_NAME := FrameworkCoreTests_install_decl_perm - -include $(BUILD_PACKAGE) +LOCAL_PACKAGE_NAME := install_decl_perm +include $(FrameworkCoreTests_BUILD_PACKAGE) diff --git a/core/tests/coretests/apks/install_loc_auto/Android.mk b/core/tests/coretests/apks/install_loc_auto/Android.mk index 2deb978..6435f36 100644 --- a/core/tests/coretests/apks/install_loc_auto/Android.mk +++ b/core/tests/coretests/apks/install_loc_auto/Android.mk @@ -1,11 +1,8 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := tests - LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_PACKAGE_NAME := FrameworkCoreTests_install_loc_auto - -include $(BUILD_PACKAGE) +LOCAL_PACKAGE_NAME := install_loc_auto +include $(FrameworkCoreTests_BUILD_PACKAGE) diff --git a/core/tests/coretests/apks/install_loc_internal/Android.mk b/core/tests/coretests/apks/install_loc_internal/Android.mk index 784bf0a..8cc8b8e 100644 --- a/core/tests/coretests/apks/install_loc_internal/Android.mk +++ b/core/tests/coretests/apks/install_loc_internal/Android.mk @@ -1,11 +1,8 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := tests - LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_PACKAGE_NAME := FrameworkCoreTests_install_loc_internal - -include $(BUILD_PACKAGE) +LOCAL_PACKAGE_NAME := install_loc_internal +include $(FrameworkCoreTests_BUILD_PACKAGE) diff --git a/core/tests/coretests/apks/install_loc_sdcard/Android.mk b/core/tests/coretests/apks/install_loc_sdcard/Android.mk index 4eea322..e1411c2 100644 --- a/core/tests/coretests/apks/install_loc_sdcard/Android.mk +++ b/core/tests/coretests/apks/install_loc_sdcard/Android.mk @@ -1,11 +1,8 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := tests - LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_PACKAGE_NAME := FrameworkCoreTests_install_loc_sdcard - -include $(BUILD_PACKAGE) +LOCAL_PACKAGE_NAME := install_loc_sdcard +include $(FrameworkCoreTests_BUILD_PACKAGE) diff --git a/core/tests/coretests/apks/install_loc_unspecified/Android.mk b/core/tests/coretests/apks/install_loc_unspecified/Android.mk index 206c99f..0741d04 100644 --- a/core/tests/coretests/apks/install_loc_unspecified/Android.mk +++ b/core/tests/coretests/apks/install_loc_unspecified/Android.mk @@ -1,11 +1,8 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := tests - LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_PACKAGE_NAME := FrameworkCoreTests_install_loc_unspecified - -include $(BUILD_PACKAGE) +LOCAL_PACKAGE_NAME := install_loc_unspecified +include $(FrameworkCoreTests_BUILD_PACKAGE) diff --git a/core/tests/coretests/apks/install_use_perm_good/Android.mk b/core/tests/coretests/apks/install_use_perm_good/Android.mk index 1a07fc8..e2661a1 100644 --- a/core/tests/coretests/apks/install_use_perm_good/Android.mk +++ b/core/tests/coretests/apks/install_use_perm_good/Android.mk @@ -1,11 +1,8 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := tests - LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_PACKAGE_NAME := FrameworkCoreTests_install_use_perm_good - -include $(BUILD_PACKAGE) +LOCAL_PACKAGE_NAME := install_use_perm_good +include $(FrameworkCoreTests_BUILD_PACKAGE) diff --git a/core/tests/coretests/apks/install_uses_feature/Android.mk b/core/tests/coretests/apks/install_uses_feature/Android.mk index c0a5067..b60d734 100644 --- a/core/tests/coretests/apks/install_uses_feature/Android.mk +++ b/core/tests/coretests/apks/install_uses_feature/Android.mk @@ -1,11 +1,8 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := tests - LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_PACKAGE_NAME := FrameworkCoreTests_install_uses_feature - -include $(BUILD_PACKAGE) +LOCAL_PACKAGE_NAME := install_uses_feature +include $(FrameworkCoreTests_BUILD_PACKAGE) diff --git a/core/tests/coretests/apks/install_verifier_bad/Android.mk b/core/tests/coretests/apks/install_verifier_bad/Android.mk index b50cfd0..a6f9d5b 100644 --- a/core/tests/coretests/apks/install_verifier_bad/Android.mk +++ b/core/tests/coretests/apks/install_verifier_bad/Android.mk @@ -1,11 +1,8 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := tests - LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_PACKAGE_NAME := FrameworkCoreTests_install_verifier_bad - -include $(BUILD_PACKAGE) +LOCAL_PACKAGE_NAME := install_verifier_bad +include $(FrameworkCoreTests_BUILD_PACKAGE) diff --git a/core/tests/coretests/apks/install_verifier_good/Android.mk b/core/tests/coretests/apks/install_verifier_good/Android.mk index a48a80e..6f2d44f 100644 --- a/core/tests/coretests/apks/install_verifier_good/Android.mk +++ b/core/tests/coretests/apks/install_verifier_good/Android.mk @@ -1,10 +1,8 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) -LOCAL_MODULE_TAGS := tests - LOCAL_SRC_FILES := $(call all-subdir-java-files) -LOCAL_PACKAGE_NAME := FrameworkCoreTests_install_verifier_good +LOCAL_PACKAGE_NAME := install_verifier_good -include $(BUILD_PACKAGE) +include $(FrameworkCoreTests_BUILD_PACKAGE) diff --git a/core/tests/coretests/res/drawable/abe.jpg b/core/tests/coretests/res/drawable/abe.jpg Binary files differnew file mode 100644 index 0000000..1f978a9 --- /dev/null +++ b/core/tests/coretests/res/drawable/abe.jpg diff --git a/core/tests/coretests/res/drawable/gettysburg.png b/core/tests/coretests/res/drawable/gettysburg.png Binary files differnew file mode 100644 index 0000000..7a2d596 --- /dev/null +++ b/core/tests/coretests/res/drawable/gettysburg.png diff --git a/core/tests/coretests/res/layout/textview_test.xml b/core/tests/coretests/res/drawable/size_adaptive_statelist.xml index f0c7b9e..aaa2de7 100644 --- a/core/tests/coretests/res/layout/textview_test.xml +++ b/core/tests/coretests/res/drawable/size_adaptive_statelist.xml @@ -13,15 +13,9 @@ See the License for the specific language governing permissions and limitations under the License. --> +<selector xmlns:android="http://schemas.android.com/apk/res/android" + android:exitFadeDuration="@android:integer/config_mediumAnimTime"> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/textviewtest_layout" - android:layout_width="fill_parent" - android:layout_height="fill_parent"> - - <TextView android:id="@+id/textviewtest_textview" - android:layout_height="wrap_content" - android:layout_width="wrap_content" - android:text="@string/textview_hebrew_text"/> - -</LinearLayout>
\ No newline at end of file + <item android:state_pressed="true" android:drawable="@drawable/blue" /> + <item android:state_pressed="false" android:drawable="@drawable/red" /> +</selector> diff --git a/core/tests/coretests/res/layout/size_adaptive.xml b/core/tests/coretests/res/layout/size_adaptive.xml new file mode 100644 index 0000000..03d0574 --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<com.android.internal.widget.SizeAdaptiveLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:internal="http://schemas.android.com/apk/prv/res/android" + android:id="@+id/multi1" + android:layout_width="match_parent" + android:layout_height="64dp" > + + <include + android:id="@+id/one_u" + layout="@layout/size_adaptive_one_u" + android:layout_width="fill_parent" + android:layout_height="64dp" + internal:layout_minHeight="64dp" + internal:layout_maxHeight="64dp" + /> + + <include + android:id="@+id/four_u" + layout="@layout/size_adaptive_four_u" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + internal:layout_minHeight="65dp" + internal:layout_maxHeight="unbounded"/> + +</com.android.internal.widget.SizeAdaptiveLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_color.xml b/core/tests/coretests/res/layout/size_adaptive_color.xml new file mode 100644 index 0000000..cdb7a59 --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_color.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<com.android.internal.widget.SizeAdaptiveLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:internal="http://schemas.android.com/apk/prv/res/android" + android:background="#ffffff" + android:id="@+id/multi1" + android:layout_width="match_parent" + android:layout_height="64dp" > + + <include + android:id="@+id/one_u" + layout="@layout/size_adaptive_one_u" + android:layout_width="fill_parent" + android:layout_height="64dp" + internal:layout_minHeight="64dp" + internal:layout_maxHeight="64dp" + /> + + <include + android:id="@+id/four_u" + layout="@layout/size_adaptive_four_u" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + internal:layout_minHeight="65dp" + internal:layout_maxHeight="unbounded"/> + +</com.android.internal.widget.SizeAdaptiveLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_color_statelist.xml b/core/tests/coretests/res/layout/size_adaptive_color_statelist.xml new file mode 100644 index 0000000..d24df5b --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_color_statelist.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<com.android.internal.widget.SizeAdaptiveLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:internal="http://schemas.android.com/apk/prv/res/android" + android:background="@drawable/size_adaptive_statelist" + android:id="@+id/multi1" + android:layout_width="match_parent" + android:layout_height="64dp" > + + <include + android:id="@+id/one_u" + layout="@layout/size_adaptive_one_u" + android:layout_width="fill_parent" + android:layout_height="64dp" + internal:layout_minHeight="64dp" + internal:layout_maxHeight="64dp" + /> + + <include + android:id="@+id/four_u" + layout="@layout/size_adaptive_four_u" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + internal:layout_minHeight="65dp" + internal:layout_maxHeight="unbounded"/> + +</com.android.internal.widget.SizeAdaptiveLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_four_u.xml b/core/tests/coretests/res/layout/size_adaptive_four_u.xml new file mode 100644 index 0000000..232b921 --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_four_u.xml @@ -0,0 +1,68 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<GridLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/gridLayout4" + android:layout_width="match_parent" + android:layout_height="256dp" + android:background="#000000" + android:columnCount="2" + android:padding="1dp" > + + <ImageView + android:id="@+id/actor" + android:layout_width="62dp" + android:layout_height="62dp" + android:layout_row="0" + android:layout_column="0" + android:layout_rowSpan="2" + android:contentDescription="@string/actor" + android:src="@drawable/abe" /> + + <TextView + android:layout_width="0dp" + android:id="@+id/name" + android:layout_row="0" + android:layout_column="1" + android:layout_gravity="fill_horizontal" + android:padding="3dp" + android:text="@string/actor" + android:textColor="#ffffff" + android:textStyle="bold" /> + + <ImageView + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_row="1" + android:layout_column="1" + android:layout_gravity="fill_horizontal" + android:padding="5dp" + android:adjustViewBounds="true" + android:background="#555555" + android:scaleType="centerCrop" + android:src="@drawable/gettysburg" + android:contentDescription="@string/caption" /> + + <TextView + android:layout_width="0dp" + android:id="@+id/note" + android:layout_row="2" + android:layout_column="1" + android:layout_gravity="fill_horizontal" + android:padding="3dp" + android:singleLine="true" + android:text="@string/first" + android:textColor="#ffffff" /> +</GridLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_four_u_text.xml b/core/tests/coretests/res/layout/size_adaptive_four_u_text.xml new file mode 100644 index 0000000..93a10de --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_four_u_text.xml @@ -0,0 +1,59 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<GridLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/gridLayout4" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:background="#000000" + android:columnCount="2" + android:padding="1dp" + android:orientation="horizontal" > + + <ImageView + android:id="@+id/actor" + android:layout_width="62dp" + android:layout_height="62dp" + android:layout_row="0" + android:layout_column="0" + android:layout_rowSpan="2" + android:contentDescription="@string/actor" + android:src="@drawable/abe" /> + + <TextView + android:layout_width="0dp" + android:id="@+id/name" + android:layout_row="0" + android:layout_column="1" + android:layout_gravity="fill_horizontal" + android:padding="3dp" + android:text="@string/actor" + android:textColor="#ffffff" + android:textStyle="bold" /> + + <TextView + android:id="@+id/note" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_column="1" + android:layout_gravity="fill_horizontal" + android:layout_marginTop="5dp" + android:layout_row="1" + android:padding="3dp" + android:singleLine="false" + android:text="@string/first" + android:textColor="#ffffff" /> + + </GridLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_gappy.xml b/core/tests/coretests/res/layout/size_adaptive_gappy.xml new file mode 100644 index 0000000..d5e3b41 --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_gappy.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<com.android.internal.widget.SizeAdaptiveLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:internal="http://schemas.android.com/apk/prv/res/android" + android:id="@+id/multi_with_gap" + android:layout_width="match_parent" + android:layout_height="64dp" > + + <include + android:id="@+id/one_u" + layout="@layout/size_adaptive_one_u" + android:layout_width="fill_parent" + android:layout_height="64dp" + internal:layout_minHeight="64dp" + internal:layout_maxHeight="64dp" + /> + + <include + android:id="@+id/four_u" + layout="@layout/size_adaptive_four_u" + android:layout_width="fill_parent" + android:layout_height="256dp" + internal:layout_minHeight="128dp" + internal:layout_maxHeight="unbounded"/> + +</com.android.internal.widget.SizeAdaptiveLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_large_only.xml b/core/tests/coretests/res/layout/size_adaptive_large_only.xml new file mode 100644 index 0000000..cf58265 --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_large_only.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<com.android.internal.widget.SizeAdaptiveLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:internal="http://schemas.android.com/apk/prv/res/android" + android:id="@+id/large_only_multi" + android:layout_width="match_parent" + android:layout_height="64dp" > + + <include + android:id="@+id/four_u" + layout="@layout/size_adaptive_four_u" + android:layout_width="fill_parent" + android:layout_height="256dp" + internal:layout_minHeight="65dp" + internal:layout_maxHeight="unbounded"/> + +</com.android.internal.widget.SizeAdaptiveLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_lies.xml b/core/tests/coretests/res/layout/size_adaptive_lies.xml new file mode 100644 index 0000000..7de892e --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_lies.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<com.android.internal.widget.SizeAdaptiveLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:internal="http://schemas.android.com/apk/prv/res/android" + android:id="@+id/multi1" + android:layout_width="match_parent" + android:layout_height="64dp" > + + <include + android:id="@+id/one_u" + layout="@layout/size_adaptive_one_u" + android:layout_width="fill_parent" + android:layout_height="64dp" + internal:layout_minHeight="64dp" + internal:layout_maxHeight="64dp" + /> + + <include + android:id="@+id/four_u" + layout="@layout/size_adaptive_one_u" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + internal:layout_minHeight="65dp" + internal:layout_maxHeight="unbounded"/> + +</com.android.internal.widget.SizeAdaptiveLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_one_u.xml b/core/tests/coretests/res/layout/size_adaptive_one_u.xml new file mode 100644 index 0000000..b6fe4a0 --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_one_u.xml @@ -0,0 +1,66 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<GridLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/gridLayout1" + android:layout_width="match_parent" + android:layout_height="64dp" + android:background="#000000" + android:columnCount="3" + android:padding="1dp" + android:rowCount="2" > + + <ImageView + android:id="@+id/actor" + android:layout_width="62dp" + android:layout_height="62dp" + android:layout_column="0" + android:layout_row="0" + android:layout_rowSpan="2" + android:contentDescription="@string/actor" + android:src="@drawable/abe" /> + + <TextView + android:id="@+id/name" + android:layout_gravity="fill" + android:padding="3dp" + android:text="@string/actor" + android:textColor="#ffffff" + android:textStyle="bold" /> + + <ImageView + android:layout_width="62dp" + android:layout_height="62dp" + android:layout_gravity="fill_vertical" + android:layout_rowSpan="2" + android:adjustViewBounds="true" + android:background="#555555" + android:padding="2dp" + android:scaleType="fitXY" + android:src="@drawable/gettysburg" + android:contentDescription="@string/caption" /> + + <TextView + android:id="@+id/note" + android:layout_width="0dp" + android:layout_height="0dp" + android:layout_gravity="fill" + android:layout_marginTop="5dp" + android:padding="3dp" + android:singleLine="true" + android:text="@string/first" + android:textColor="#ffffff" /> + +</GridLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_one_u_text.xml b/core/tests/coretests/res/layout/size_adaptive_one_u_text.xml new file mode 100644 index 0000000..df54eb6 --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_one_u_text.xml @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<GridLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/gridLayout1" + android:layout_width="match_parent" + android:layout_height="64dp" + android:background="#000000" + android:columnCount="2" + android:padding="1dp" + android:rowCount="2" > + + <ImageView + android:id="@+id/actor" + android:layout_width="62dp" + android:layout_height="62dp" + android:layout_column="0" + android:layout_row="0" + android:layout_rowSpan="2" + android:contentDescription="@string/actor" + android:src="@drawable/abe" /> + + <TextView + android:id="@+id/name" + android:layout_gravity="fill" + android:padding="3dp" + android:text="@string/actor" + android:textColor="#ffffff" + android:textStyle="bold" /> + + <TextView + android:id="@+id/note" + android:layout_width="0dp" + android:layout_height="0dp" + android:layout_gravity="fill" + android:layout_marginTop="5dp" + android:padding="3dp" + android:singleLine="true" + android:text="@string/first" + android:textColor="#ffffff" /> + +</GridLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_overlapping.xml b/core/tests/coretests/res/layout/size_adaptive_overlapping.xml new file mode 100644 index 0000000..4abe8b0 --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_overlapping.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<com.android.internal.widget.SizeAdaptiveLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:internal="http://schemas.android.com/apk/prv/res/android" + android:id="@+id/multi_with_overlap" + android:layout_width="match_parent" + android:layout_height="64dp" > + + <include + android:id="@+id/one_u" + layout="@layout/size_adaptive_one_u" + android:layout_width="fill_parent" + android:layout_height="64dp" + internal:layout_minHeight="64dp" + internal:layout_maxHeight="64dp" + /> + + <include + android:id="@+id/four_u" + layout="@layout/size_adaptive_four_u" + android:layout_width="fill_parent" + android:layout_height="256dp" + internal:layout_minHeight="64dp" + internal:layout_maxHeight="256dp"/> + +</com.android.internal.widget.SizeAdaptiveLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_singleton.xml b/core/tests/coretests/res/layout/size_adaptive_singleton.xml new file mode 100644 index 0000000..eba387f --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_singleton.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<com.android.internal.widget.SizeAdaptiveLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:internal="http://schemas.android.com/apk/prv/res/android" + android:layout_width="match_parent" + android:layout_height="64dp" > + + <include + android:id="@+id/one_u" + layout="@layout/size_adaptive_one_u_text" + android:layout_width="fill_parent" + android:layout_height="64dp" + internal:layout_minHeight="64dp" + internal:layout_maxHeight="64dp" + /> + +</com.android.internal.widget.SizeAdaptiveLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_text.xml b/core/tests/coretests/res/layout/size_adaptive_text.xml new file mode 100644 index 0000000..a9f0ba9 --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_text.xml @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<com.android.internal.widget.SizeAdaptiveLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:internal="http://schemas.android.com/apk/prv/res/android" + android:id="@+id/multi1" + android:layout_width="match_parent" + android:layout_height="64dp" > + + <include + android:id="@+id/one_u" + layout="@layout/size_adaptive_one_u_text" + android:layout_width="fill_parent" + android:layout_height="64dp" + internal:layout_minHeight="64dp" + internal:layout_maxHeight="64dp" + /> + + <include + android:id="@+id/four_u" + layout="@layout/size_adaptive_four_u_text" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + internal:layout_minHeight="65dp" + internal:layout_maxHeight="unbounded"/> + +</com.android.internal.widget.SizeAdaptiveLayout> diff --git a/core/tests/coretests/res/layout/size_adaptive_three_way.xml b/core/tests/coretests/res/layout/size_adaptive_three_way.xml new file mode 100644 index 0000000..1eb5396 --- /dev/null +++ b/core/tests/coretests/res/layout/size_adaptive_three_way.xml @@ -0,0 +1,48 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2012 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. +--> +<com.android.internal.widget.SizeAdaptiveLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:internal="http://schemas.android.com/apk/prv/res/android" + android:id="@+id/three_way_multi" + android:layout_width="match_parent" + android:layout_height="64dp" > + + <include + android:id="@+id/one_u" + layout="@layout/size_adaptive_one_u" + android:layout_width="fill_parent" + android:layout_height="64dp" + internal:layout_minHeight="64dp" + internal:layout_maxHeight="64dp" + /> + + <include + android:id="@+id/two_u" + layout="@layout/size_adaptive_four_u" + android:layout_width="fill_parent" + android:layout_height="128dp" + internal:layout_minHeight="65dp" + internal:layout_maxHeight="128dp"/> + + <include + android:id="@+id/four_u" + layout="@layout/size_adaptive_four_u" + android:layout_width="fill_parent" + android:layout_height="256dp" + internal:layout_minHeight="129dp" + internal:layout_maxHeight="unbounded"/> + +</com.android.internal.widget.SizeAdaptiveLayout> diff --git a/core/tests/coretests/res/raw/alt_ip_only.crt b/core/tests/coretests/res/raw/alt_ip_only.crt deleted file mode 100644 index 3ac9f5a..0000000 --- a/core/tests/coretests/res/raw/alt_ip_only.crt +++ /dev/null @@ -1,17 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICsjCCAZqgAwIBAgIJALrC37YAXFIeMA0GCSqGSIb3DQEBBQUAMA0xCzAJBgNV -BAYTAkpQMCAXDTEwMDExMjIxMzk0NloYDzIwNjQxMDE1MjEzOTQ2WjANMQswCQYD -VQQGEwJKUDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALr8s/4Abpby -IYks5YCJE2nbWH7kj6XbwnRzsVP9RVC33bPoQ1M+2ZY24HqkigjQS/HEXR0s0bYh -dewNUnTj1uGyGs6cYzsbu7x114vmVYqjxUo3hKjwfYiPeF6f3IE1vpLI7I2G32gq -Zwm9c1/vXNHIdWQxCpFcuPA8P3YGfoApFX4pQPFplBUNAQqnjdmA68cbxxMC+1F3 -mX42D7iIEVwyVpah5HjyxjIZQlf3X7QBj0bCmkL+ibIHTALrkNNwNM6i4xzYLz/5 -14GkN9ncHY87eSOk6r53ptER6mQMhCe9qPRjSHnpWTTyj6IXTaYe+dDQw657B80w -cSHL7Ed25zUCAwEAAaMTMBEwDwYDVR0RBAgwBocEwKgKATANBgkqhkiG9w0BAQUF -AAOCAQEAgrwrtOWZT3fbi1AafpGaAiOBWSJqYqRhtQy0AfiZBxv1U0XaYqmZmpnq -DVAqr0NkljowD28NBrxIFO5gBNum2ZOPDl2/5vjFn+IirUCJ9u9wS7zYkTCW2lQR -xE7Ic3mfWv7wUbKDfjlWqP1IDHUxwkrBTAl+HnwOPiaKKk1ttwcrgS8AHlqASe03 -mlwnvJ+Stk54IneRaegL0L93sNAy63RZqnPCTxGz7eHcFwX8Jdr4sbxTxQqV6pIc -WPjHQcWfpkFzAF5wyOq0kveVfx0g5xPhOVDd+U+q7WastbXICpCoHp9FxISmZVik -sAyifp8agkYdzaSh55fFmKXlFnRsQw== ------END CERTIFICATE----- diff --git a/core/tests/coretests/res/raw/install b/core/tests/coretests/res/raw/install Binary files differdeleted file mode 100644 index 06981f4..0000000 --- a/core/tests/coretests/res/raw/install +++ /dev/null diff --git a/core/tests/coretests/res/raw/install_decl_perm b/core/tests/coretests/res/raw/install_decl_perm Binary files differdeleted file mode 100644 index af05d81..0000000 --- a/core/tests/coretests/res/raw/install_decl_perm +++ /dev/null diff --git a/core/tests/coretests/res/raw/install_loc_auto b/core/tests/coretests/res/raw/install_loc_auto Binary files differdeleted file mode 100644 index 63bf35c..0000000 --- a/core/tests/coretests/res/raw/install_loc_auto +++ /dev/null diff --git a/core/tests/coretests/res/raw/install_loc_internal b/core/tests/coretests/res/raw/install_loc_internal Binary files differdeleted file mode 100644 index 5178803..0000000 --- a/core/tests/coretests/res/raw/install_loc_internal +++ /dev/null diff --git a/core/tests/coretests/res/raw/install_loc_sdcard b/core/tests/coretests/res/raw/install_loc_sdcard Binary files differdeleted file mode 100644 index 013a414..0000000 --- a/core/tests/coretests/res/raw/install_loc_sdcard +++ /dev/null diff --git a/core/tests/coretests/res/raw/install_loc_unspecified b/core/tests/coretests/res/raw/install_loc_unspecified Binary files differdeleted file mode 100644 index 06981f4..0000000 --- a/core/tests/coretests/res/raw/install_loc_unspecified +++ /dev/null diff --git a/core/tests/coretests/res/raw/install_use_perm_good b/core/tests/coretests/res/raw/install_use_perm_good Binary files differdeleted file mode 100644 index a7eb32f..0000000 --- a/core/tests/coretests/res/raw/install_use_perm_good +++ /dev/null diff --git a/core/tests/coretests/res/raw/install_uses_feature b/core/tests/coretests/res/raw/install_uses_feature Binary files differdeleted file mode 100644 index eeeb309..0000000 --- a/core/tests/coretests/res/raw/install_uses_feature +++ /dev/null diff --git a/core/tests/coretests/res/raw/net_dev_typical b/core/tests/coretests/res/raw/net_dev_typical deleted file mode 100644 index 290bf03..0000000 --- a/core/tests/coretests/res/raw/net_dev_typical +++ /dev/null @@ -1,8 +0,0 @@ -Inter-| Receive | Transmit - face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed - lo: 8308 116 0 0 0 0 0 0 8308 116 0 0 0 0 0 0 -rmnet0: 1507570 2205 0 0 0 0 0 0 489339 2237 0 0 0 0 0 0 - ifb0: 52454 151 0 151 0 0 0 0 0 0 0 0 0 0 0 0 - ifb1: 52454 151 0 151 0 0 0 0 0 0 0 0 0 0 0 0 - sit0: 0 0 0 0 0 0 0 0 0 0 148 0 0 0 0 0 -ip6tnl0: 0 0 0 0 0 0 0 0 0 0 151 151 0 0 0 0 diff --git a/core/tests/coretests/res/raw/subject_alt_only.crt b/core/tests/coretests/res/raw/subject_alt_only.crt deleted file mode 100644 index d5808fb..0000000 --- a/core/tests/coretests/res/raw/subject_alt_only.crt +++ /dev/null @@ -1,17 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICvTCCAaWgAwIBAgIJALbA0TZk2YmNMA0GCSqGSIb3DQEBBQUAMA0xCzAJBgNV -BAYTAkpQMCAXDTEwMDExMjIwNTg1NFoYDzIwNjQxMDE1MjA1ODU0WjANMQswCQYD -VQQGEwJKUDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMEg6acVC9V4 -xNGoLNVLPbqBc8IvMvcsc88dF6MW3d9VagX3aeWU8c79tI/KOV/1AOakH7WYxw/w -yD8aOX7+9BK1Hu0qKKKbSM+ycqaMthXd6xytrNDsIx5WiGUz8zTko0Gk3orIR7p7 -rPcNzB/zwtESkscqPv85aEn7S/yClNkzLfEzm3CtaYOc0tfhBMyzi/ipXzGMxUmx -PvOLr3v/Oz5pZEQw7Kxlm4+tAtn7bJlHziQ1UW4WPIy+T3hySBEpODFiqZi7Ok3X -Zjxdii62fgo5B2Ee7q5Amo0mUIwcQTDjJ2CLAqzYnSh3tpiPJGjEIjmRyCoMQ1bx -7D+y7nSPIq8CAwEAAaMeMBwwGgYDVR0RBBMwEYIPd3d3LmV4YW1wbGUuY29tMA0G -CSqGSIb3DQEBBQUAA4IBAQBsGEh+nHc0l9FJTzWqvG3qs7i6XoJZdtThCDx4HjKJ -8GMrJtreNN4JvIxn7KC+alVbnILjzCRO+c3rsnpxKBi5cp2imjuw5Kf/x2Seimb9 -UvZbaJvBVOzy4Q1IGef9bLy3wZzy2/WfBFyvPTAkgkRaX7LN2jnYOYVhNoNFrwqe -EWxkA6fzrpyseUEFeGFFjGxRSRCDcQ25Eq6d9rkC1x21zNtt4QwZBO0wHrTy155M -JPRynf9244Pn0Sr/wsnmdsTRFIFYynrc51hQ7DkwbUxpcaewkZzilru/SwZ3+pPT -9JSqm5hJ1pg5WDlPkW7c/1VA0/141N52Q8MIU+2ZpuOj ------END CERTIFICATE----- diff --git a/core/tests/coretests/res/raw/subject_only.crt b/core/tests/coretests/res/raw/subject_only.crt deleted file mode 100644 index 11b34e7..0000000 --- a/core/tests/coretests/res/raw/subject_only.crt +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC0TCCAbmgAwIBAgIJANCQbJPPw31SMA0GCSqGSIb3DQEBBQUAMCcxCzAJBgNV -BAYTAkpQMRgwFgYDVQQDEw93d3cuZXhhbXBsZS5jb20wIBcNMTAwMTEyMjA1ODE4 -WhgPMjA2NDEwMTUyMDU4MThaMCcxCzAJBgNVBAYTAkpQMRgwFgYDVQQDEw93d3cu -ZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDsdUJk -4KxADA3vlDHxNbyC27Ozw4yiSVzPTHUct471YmdDRW3orO2P5a5hRnUGV70gjH9X -MU4oeOdWYAgXB9pxfLyr6621k1+uNrmaZtzp0ECH9twcwxNJJFDZsN7o9vt7V6Ej -NN9weeqDr/aeQXo07a12vyVfR6jWO8jHB0e4aemwZNoYjNvM69fivQTse2ZoRVfj -eSHhjRTX6I8ry4a31Hwt+fT1QiWWNN6o7+WOtpJAhX3eg4smhSD1svi2kOT8tdUe -NS4hWlmXmumU9G4tI8PBurcLNTm7PB2lUlbn/IV18WavqKE/Uy/1WgAx+a1EJNdp -i07AG1PsqaONKkf1AgMBAAEwDQYJKoZIhvcNAQEFBQADggEBAJrNsuL7fZZNC8gL -BdePJ7DYW2e7mXANU3bCBe2BZqmXKQxKwibZnEsqA+yMLqcSd8uxISlyHY2tw9wT -4wB9KPIttfNLbwn/rk+MbOTHpvyF60d9WhJJVUkPBl8D4VuPSl+VnlA54kU9dtZN -+ZYdxYbNtSsI/Flz9SCoOV79W9GhN+uYJhv6RwyIMIHeMpZpyX1xSUVx5dZlmerQ -WAUvghDH3fFRt2ZdnA4OXoKkTAaM3Pv7PUMsnah8bux6MQi0AuLMWFWOI1H34koH -rs2oQLwOLnuifH52ey9+tJguabo+brlYYigAuWWFEzJfBzikDkIwnE/L7wlrypIk -taXDWI4= ------END CERTIFICATE----- diff --git a/core/tests/coretests/res/raw/subject_with_alt_names.crt b/core/tests/coretests/res/raw/subject_with_alt_names.crt deleted file mode 100644 index 6963c7e..0000000 --- a/core/tests/coretests/res/raw/subject_with_alt_names.crt +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDBDCCAeygAwIBAgIJALv14qjcuhw9MA0GCSqGSIb3DQEBBQUAMCcxCzAJBgNV -BAYTAkpQMRgwFgYDVQQDEw93d3cuZXhhbXBsZS5jb20wIBcNMTAwMTEyMjA1OTM4 -WhgPMjA2NDEwMTUyMDU5MzhaMCcxCzAJBgNVBAYTAkpQMRgwFgYDVQQDEw93d3cu -ZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCiTVgU -kBO9KNYZZLmiPR0eBrk8u61CLnm35BGKW8EFpDaINLbbIFIQvqOMekURON/N+xFY -D8roo7aFZVuHWAUqFcOJ4e6NmviK5qocLihtzAexsw4f4AzZxM3A8kcLlWLyAt7e -EVLxhcMHogY7GaF6q+33Z8p+zp6x3tj07mwyPrriCLse2PeRsRunZl/fp/VvRlr6 -YbC7CbRrhnIv5nqohs8BsbBiiFpxQftsMQmiXhY2LUzqY2RXUIOw24fHjoQkHTL2 -4z5nUM3b6ueQe+CBnobUS6fzK/36Nct4dRpev9i/ORdRLuIDKJ+QR16G1V/BJYBR -dAK+3iXvg6z8vP1XAgMBAAGjMTAvMC0GA1UdEQQmMCSCEHd3dzIuZXhhbXBsZS5j -b22CEHd3dzMuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQEFBQADggEBAJQNf38uXm3h -0vsF+Yd6/HqM48Su7tWnTDAfTXnQZZkzjzITq3JXzquMXICktAVN2cLnT9zPfRAE -8V8A3BNO5zXiR5W3o/mJP5HQ3/WxpzBGM2N+YmDCJyBoQrIVaAZaXAZUaBBvn5A+ -kEVfGWquwIFuvA67xegbJOCRLD4eUzRdNsn5+NFiakWO1tkFqEzqyQ0PNPviRjgu -z9NxdPvd1JQOhydkucsPKJzlEBbGyL5QL/Jkot3Qy+FOeuNzgQUfAGtQgzRrsZDK -hrTVypLSoRXuTB2aWilu4p6aNh84xTdyqo2avtNr2MiQMZIcdamBq8LdBIAShFXI -h5G2eVGXH/Y= ------END CERTIFICATE----- diff --git a/core/tests/coretests/res/raw/subject_with_wild_alt_name.crt b/core/tests/coretests/res/raw/subject_with_wild_alt_name.crt deleted file mode 100644 index 19b1174..0000000 --- a/core/tests/coretests/res/raw/subject_with_wild_alt_name.crt +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC8DCCAdigAwIBAgIJAL/oWJ64VAdXMA0GCSqGSIb3DQEBBQUAMCcxCzAJBgNV -BAYTAkpQMRgwFgYDVQQDEw93d3cuZXhhbXBsZS5jb20wIBcNMTAwMTEyMjEwMDAx -WhgPMjA2NDEwMTUyMTAwMDFaMCcxCzAJBgNVBAYTAkpQMRgwFgYDVQQDEw93d3cu -ZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCbx1QB -92iea7VybLYICA4MX4LWipYrRsgXUXQrcIQ3YLTQ9rH0VwScrHL4O4JDxgXCQnR+ -4VOzD42q1KXHJAqzqGUYCNPyvZEzkGCnQ4FBIUEmxZd5SNEefJVH3Z6GizYJomTh -p78yDcoqymD9umxRC2cWFu8GscfFGMVyhsqLlOofu7UWOs22mkXPo43jDx+VOAoV -n48YP3P57a2Eo0gcd4zVL00y62VegqBO/1LW38aTS7teiCBFc1TkNYa5I40yN9lP -rB9ICHYQWyzf/7OxU9iauEK2w6DmSsQoLs9JzEhgeNZddkcc77ciSUCo2Hx0VpOJ -BFyf2rbryJeAk+FDAgMBAAGjHTAbMBkGA1UdEQQSMBCCDiouZXhhbXBsZTIuY29t -MA0GCSqGSIb3DQEBBQUAA4IBAQA2a14pRL+4laJ8sscQlucaDB/oSdb0cwhk4IkE -kKl/ZKr6rKwPZ81sJRgzvI4imLbUAKt4AJHdpI9cIQUq1gw9bzil7LKwmFtFSPmC -MYb1iadaYrvp7RE4yXrWCcSbU0hup9JQLHTrHLlqLtRuU48NHMvWYThBcS9Q/hQp -nJ/JxYy3am99MHALWLAfuRxQXhE4C5utDmBwI2KD6A8SA30s+CnuegmkYScuSqBu -Y3R0HZvKzNIU3pwAm69HCJoG+/9MZEIDJb0WJc5UygxDT45XE9zQMQe4dBOTaNXT -+ntgaB62kE10HzrzpqXAgoAWxWK4RzFcUpBWw9qYq9xOCewJ ------END CERTIFICATE----- diff --git a/core/tests/coretests/res/raw/wild_alt_name_only.crt b/core/tests/coretests/res/raw/wild_alt_name_only.crt deleted file mode 100644 index fafdebf..0000000 --- a/core/tests/coretests/res/raw/wild_alt_name_only.crt +++ /dev/null @@ -1,17 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICuzCCAaOgAwIBAgIJAP82tgcvmAGxMA0GCSqGSIb3DQEBBQUAMA0xCzAJBgNV -BAYTAkpQMCAXDTEwMDExMjIxMDAyN1oYDzIwNjQxMDE1MjEwMDI3WjANMQswCQYD -VQQGEwJKUDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALs528EQbcB1 -x4BwxthQBZrgDJzoO7KPV3dhGYoeP8EnRjapZm+T/sj9P/O4HvfxjnB+fsjYSdmE -WWUtnFrP7wtG9DUC748Ea2PMV8WFhOG58dqBNIko5XzkHB7SxkNZD5S/0KQYMGLr -rchDsDlmsEf2Qb6qiqpNEU70aSkExZJcH+B9nWdeBpsVFu7wtezwSWEc2NUa2bhW -gcXQ/aafwHZ4o2PyGwy0sgS/UifqO9tEllC2tPleSNJOmYsVudv5Bz4Q0GG38BSz -Pc0IcOoln0ZWpXbGr03V2vlXWCwzaFAl3I1T3O7YVqDiaSWoP+d0tHZzmw8aJLXd -B+KaUUGxRPsCAwEAAaMcMBowGAYDVR0RBBEwD4INKi5leGFtcGxlLmNvbTANBgkq -hkiG9w0BAQUFAAOCAQEAJbVan4QgJ0cvpJnK9UWIVJNC+UbP87RC5go2fQiTnmGv -prOrIuMqz1+vGcpIheLTLctJRHPoadXq0+UbQEIaU3pQbY6C4nNdfl+hcvmJeqrt -kOCcvmIamO68iNvTSeszuHuu4O38PefrW2Xd0nn7bjFZrzBzHFhTudmnqNliP3ue -KKQpqkUt5lCytnH8V/u/UCWdvVx5LnUa2XFGVLi3ongBIojW5fvF+yxn9ADqxdrI -va++ow5r1VxQXFJc0ZPzsDo+6TlktoDHaRQJGMqQomqHWT4i7F5UZgf6BHGfEUPU -qep+GsF3QRHSBtpObWkVDZNFvky3a1iZ2q25+hFIqQ== ------END CERTIFICATE----- diff --git a/core/tests/coretests/res/raw/xt_qtaguid_iface_fmt_typical b/core/tests/coretests/res/raw/xt_qtaguid_iface_fmt_typical new file mode 100644 index 0000000..656d5bb --- /dev/null +++ b/core/tests/coretests/res/raw/xt_qtaguid_iface_fmt_typical @@ -0,0 +1,4 @@ +ifname total_skb_rx_bytes total_skb_rx_packets total_skb_tx_bytes total_skb_tx_packets +rmnet2 4968 35 3081 39 +rmnet1 11153922 8051 190226 2468 +rmnet0 6824 16 5692 10 diff --git a/core/tests/coretests/res/values/strings.xml b/core/tests/coretests/res/values/strings.xml index 71f3520..ce0d9a2 100644 --- a/core/tests/coretests/res/values/strings.xml +++ b/core/tests/coretests/res/values/strings.xml @@ -131,4 +131,8 @@ <string name="textview_hebrew_text">םמab?!</string> + <!-- SizeAdaptiveLayout --> + <string name="first">Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.</string> + <string name="actor">Abe Lincoln</string> + <string name="caption">Lincoln adressing the crowd at Gettysburgh</string> </resources> diff --git a/core/tests/coretests/src/android/accessibilityservice/InterrogationActivity.java b/core/tests/coretests/src/android/accessibilityservice/InterrogationActivity.java index b4a0581..a9f144b 100644 --- a/core/tests/coretests/src/android/accessibilityservice/InterrogationActivity.java +++ b/core/tests/coretests/src/android/accessibilityservice/InterrogationActivity.java @@ -14,12 +14,12 @@ package android.accessibilityservice; -import com.android.frameworks.coretests.R; - import android.app.Activity; import android.os.Bundle; import android.view.View; +import com.android.frameworks.coretests.R; + /** * Activity for testing the accessibility APIs for "interrogation" of * the screen content. These APIs allow exploring the screen and diff --git a/core/tests/coretests/src/android/accessibilityservice/InterrogationActivityTest.java b/core/tests/coretests/src/android/accessibilityservice/InterrogationActivityTest.java index ec12124..3dc140b 100644 --- a/core/tests/coretests/src/android/accessibilityservice/InterrogationActivityTest.java +++ b/core/tests/coretests/src/android/accessibilityservice/InterrogationActivityTest.java @@ -14,26 +14,21 @@ package android.accessibilityservice; -import static android.view.accessibility.AccessibilityNodeInfo.ACTION_CLEAR_FOCUS; -import static android.view.accessibility.AccessibilityNodeInfo.ACTION_CLEAR_SELECTION; import static android.view.accessibility.AccessibilityNodeInfo.ACTION_FOCUS; +import static android.view.accessibility.AccessibilityNodeInfo.ACTION_CLEAR_FOCUS; import static android.view.accessibility.AccessibilityNodeInfo.ACTION_SELECT; +import static android.view.accessibility.AccessibilityNodeInfo.ACTION_CLEAR_SELECTION; -import android.content.Context; import android.graphics.Rect; -import android.os.ServiceManager; import android.os.SystemClock; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.LargeTest; import android.util.Log; -import android.view.View; import android.view.accessibility.AccessibilityEvent; -import android.view.accessibility.AccessibilityInteractionClient; -import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeInfo; -import android.view.accessibility.IAccessibilityManager; import com.android.frameworks.coretests.R; +import com.android.internal.util.Predicate; import java.util.ArrayList; import java.util.LinkedList; @@ -48,21 +43,21 @@ import java.util.Queue; */ public class InterrogationActivityTest extends ActivityInstrumentationTestCase2<InterrogationActivity> { - private static final boolean DEBUG = true; + private static final boolean DEBUG = false; private static String LOG_TAG = "InterrogationActivityTest"; - // Timeout before give up wait for the system to process an accessibility setting change. - private static final int TIMEOUT_PROPAGATE_ACCESSIBLITY_SETTING = 2000; - // Timeout for the accessibility state of an Activity to be fully initialized. - private static final int TIMEOUT_ACCESSIBLITY_STATE_INITIALIZED_MILLIS = 100; + private static final int TIMEOUT_PROPAGATE_ACCESSIBILITY_EVENT_MILLIS = 5000; - // Handle to a connection to the AccessibilityManagerService - private static int sConnectionId = View.NO_ID; + // Timeout for which non getting accessibility events considers the app idle. + private static final long IDLE_EVENT_TIME_DELTA_MILLIS = 200; - // The last received accessibility event - private volatile AccessibilityEvent mLastAccessibilityEvent; + // Timeout in which to wait for idle device. + private static final long GLOBAL_IDLE_DETECTION_TIMEOUT_MILLIS = 1000; + + // Handle to a connection to the AccessibilityManagerService + private UiTestAutomationBridge mUiTestAutomationBridge; public InterrogationActivityTest() { super(InterrogationActivity.class); @@ -70,16 +65,41 @@ public class InterrogationActivityTest @Override public void setUp() throws Exception { - ensureConnection(); - bringUpActivityWithInitalizedAccessbility(); + super.setUp(); + mUiTestAutomationBridge = new UiTestAutomationBridge(); + mUiTestAutomationBridge.connect(); + mUiTestAutomationBridge.waitForIdle(IDLE_EVENT_TIME_DELTA_MILLIS, + GLOBAL_IDLE_DETECTION_TIMEOUT_MILLIS); + mUiTestAutomationBridge.executeCommandAndWaitForAccessibilityEvent(new Runnable() { + // wait for the first accessibility event + @Override + public void run() { + // bring up the activity + getActivity(); + } + }, + new Predicate<AccessibilityEvent>() { + @Override + public boolean apply(AccessibilityEvent event) { + return (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED + && event.getPackageName().equals(getActivity().getPackageName())); + } + }, + TIMEOUT_PROPAGATE_ACCESSIBILITY_EVENT_MILLIS); + } + + @Override + public void tearDown() throws Exception { + mUiTestAutomationBridge.disconnect(); + super.tearDown(); } @LargeTest public void testFindAccessibilityNodeInfoByViewId() throws Exception { final long startTimeMillis = SystemClock.uptimeMillis(); try { - AccessibilityNodeInfo button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + AccessibilityNodeInfo button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertNotNull(button); assertEquals(0, button.getChildCount()); @@ -125,8 +145,8 @@ public class InterrogationActivityTest final long startTimeMillis = SystemClock.uptimeMillis(); try { // find a view by text - List<AccessibilityNodeInfo> buttons = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfosByViewTextInActiveWindow(sConnectionId, "butto"); + List<AccessibilityNodeInfo> buttons = mUiTestAutomationBridge + .findAccessibilityNodeInfosByTextInActiveWindow("butto"); assertEquals(9, buttons.size()); } finally { if (DEBUG) { @@ -141,12 +161,9 @@ public class InterrogationActivityTest public void testFindAccessibilityNodeInfoByViewTextContentDescription() throws Exception { final long startTimeMillis = SystemClock.uptimeMillis(); try { - bringUpActivityWithInitalizedAccessbility(); - // find a view by text - List<AccessibilityNodeInfo> buttons = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfosByViewTextInActiveWindow(sConnectionId, - "contentDescription"); + List<AccessibilityNodeInfo> buttons = mUiTestAutomationBridge + .findAccessibilityNodeInfosByTextInActiveWindow("contentDescription"); assertEquals(1, buttons.size()); } finally { if (DEBUG) { @@ -177,8 +194,8 @@ public class InterrogationActivityTest classNameAndTextList.add("android.widget.ButtonButton8"); classNameAndTextList.add("android.widget.ButtonButton9"); - AccessibilityNodeInfo root = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.root); + AccessibilityNodeInfo root = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.root); assertNotNull("We must find the existing root.", root); Queue<AccessibilityNodeInfo> fringe = new LinkedList<AccessibilityNodeInfo>(); @@ -216,16 +233,16 @@ public class InterrogationActivityTest final long startTimeMillis = SystemClock.uptimeMillis(); try { // find a view and make sure it is not focused - AccessibilityNodeInfo button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + AccessibilityNodeInfo button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertFalse(button.isFocused()); // focus the view assertTrue(button.performAction(ACTION_FOCUS)); // find the view again and make sure it is focused - button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertTrue(button.isFocused()); } finally { if (DEBUG) { @@ -240,24 +257,24 @@ public class InterrogationActivityTest final long startTimeMillis = SystemClock.uptimeMillis(); try { // find a view and make sure it is not focused - AccessibilityNodeInfo button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + AccessibilityNodeInfo button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertFalse(button.isFocused()); // focus the view assertTrue(button.performAction(ACTION_FOCUS)); // find the view again and make sure it is focused - button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertTrue(button.isFocused()); // unfocus the view assertTrue(button.performAction(ACTION_CLEAR_FOCUS)); // find the view again and make sure it is not focused - button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertFalse(button.isFocused()); } finally { if (DEBUG) { @@ -273,16 +290,16 @@ public class InterrogationActivityTest final long startTimeMillis = SystemClock.uptimeMillis(); try { // find a view and make sure it is not selected - AccessibilityNodeInfo button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + AccessibilityNodeInfo button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertFalse(button.isSelected()); // select the view assertTrue(button.performAction(ACTION_SELECT)); // find the view again and make sure it is selected - button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertTrue(button.isSelected()); } finally { if (DEBUG) { @@ -297,24 +314,24 @@ public class InterrogationActivityTest final long startTimeMillis = SystemClock.uptimeMillis(); try { // find a view and make sure it is not selected - AccessibilityNodeInfo button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + AccessibilityNodeInfo button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertFalse(button.isSelected()); // select the view assertTrue(button.performAction(ACTION_SELECT)); // find the view again and make sure it is selected - button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertTrue(button.isSelected()); // unselect the view assertTrue(button.performAction(ACTION_CLEAR_SELECTION)); // find the view again and make sure it is not selected - button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); assertFalse(button.isSelected()); } finally { if (DEBUG) { @@ -330,23 +347,33 @@ public class InterrogationActivityTest final long startTimeMillis = SystemClock.uptimeMillis(); try { // find a view and make sure it is not focused - AccessibilityNodeInfo button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); - assertFalse(button.isSelected()); - - // focus the view - assertTrue(button.performAction(ACTION_FOCUS)); + final AccessibilityNodeInfo button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); + assertFalse(button.isFocused()); - synchronized (this) { - try { - wait(TIMEOUT_ACCESSIBLITY_STATE_INITIALIZED_MILLIS); - } catch (InterruptedException ie) { - /* ignore */ + AccessibilityEvent event = mUiTestAutomationBridge + .executeCommandAndWaitForAccessibilityEvent(new Runnable() { + @Override + public void run() { + // focus the view + assertTrue(button.performAction(ACTION_FOCUS)); } - } + }, + new Predicate<AccessibilityEvent>() { + @Override + public boolean apply(AccessibilityEvent event) { + return (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED + && event.getPackageName().equals(getActivity().getPackageName()) + && event.getText().get(0).equals(button.getText())); + } + }, + TIMEOUT_PROPAGATE_ACCESSIBILITY_EVENT_MILLIS); + + // check the last event + assertNotNull(event); // check that last event source - AccessibilityNodeInfo source = mLastAccessibilityEvent.getSource(); + AccessibilityNodeInfo source = event.getSource(); assertNotNull(source); // bounds @@ -389,8 +416,9 @@ public class InterrogationActivityTest final long startTimeMillis = SystemClock.uptimeMillis(); try { // find a view and make sure it is not focused - AccessibilityNodeInfo button = AccessibilityInteractionClient.getInstance() - .findAccessibilityNodeInfoByViewIdInActiveWindow(sConnectionId, R.id.button5); + AccessibilityNodeInfo button = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.button5); + assertNotNull(button); AccessibilityNodeInfo parent = button.getParent(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { @@ -411,69 +439,33 @@ public class InterrogationActivityTest } } - private void bringUpActivityWithInitalizedAccessbility() { - mLastAccessibilityEvent = null; - // bring up the activity - getActivity(); - + @LargeTest + public void testGetRootAccessibilityNodeInfoInActiveWindow() throws Exception { final long startTimeMillis = SystemClock.uptimeMillis(); - while (true) { - if (mLastAccessibilityEvent != null) { - final int eventType = mLastAccessibilityEvent.getEventType(); - if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { - return; - } - } - final long remainingTimeMillis = TIMEOUT_ACCESSIBLITY_STATE_INITIALIZED_MILLIS - - (SystemClock.uptimeMillis() - startTimeMillis); - if (remainingTimeMillis <= 0) { - return; - } - synchronized (this) { - try { - wait(remainingTimeMillis); - } catch (InterruptedException e) { - /* ignore */ + try { + // get the root via the designated API + AccessibilityNodeInfo fetched = mUiTestAutomationBridge + .getRootAccessibilityNodeInfoInActiveWindow(); + assertNotNull(fetched); + + // get the root via traversal + AccessibilityNodeInfo expected = mUiTestAutomationBridge + .findAccessibilityNodeInfoByViewIdInActiveWindow(R.id.root); + while (true) { + AccessibilityNodeInfo parent = expected.getParent(); + if (parent == null) { + break; } + expected = parent; } - } - } + assertNotNull(expected); - private void ensureConnection() throws Exception { - if (sConnectionId == View.NO_ID) { - IEventListener listener = new IEventListener.Stub() { - public void setConnection(IAccessibilityServiceConnection connection, - int connectionId) { - sConnectionId = connectionId; - if (connection != null) { - AccessibilityInteractionClient.getInstance().addConnection(connectionId, - connection); - } else { - AccessibilityInteractionClient.getInstance().removeConnection(connectionId); - } - synchronized (this) { - notifyAll(); - } - } - - public void onInterrupt() {} - - public void onAccessibilityEvent(AccessibilityEvent event) { - mLastAccessibilityEvent = AccessibilityEvent.obtain(event); - synchronized (this) { - notifyAll(); - } - } - }; - - AccessibilityManager accessibilityManager = - AccessibilityManager.getInstance(getInstrumentation().getContext()); - - synchronized (this) { - IAccessibilityManager manager = IAccessibilityManager.Stub.asInterface( - ServiceManager.getService(Context.ACCESSIBILITY_SERVICE)); - manager.registerEventListener(listener); - wait(TIMEOUT_PROPAGATE_ACCESSIBLITY_SETTING); + assertEquals("The node with id \"root\" should be the root.", expected, fetched); + } finally { + if (DEBUG) { + final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis; + Log.i(LOG_TAG, "testGetRootAccessibilityNodeInfoInActiveWindow: " + + elapsedTimeMillis + "ms"); } } } diff --git a/core/tests/coretests/src/android/animation/EventsTest.java b/core/tests/coretests/src/android/animation/EventsTest.java index 701a3f0..8df711b 100644 --- a/core/tests/coretests/src/android/animation/EventsTest.java +++ b/core/tests/coretests/src/android/animation/EventsTest.java @@ -173,8 +173,7 @@ public abstract class EventsTest // This should only be called on an animation that has been started and not // yet canceled or ended assertFalse(mCanceled); - assertTrue(mRunning); - assertTrue(mStarted); + assertTrue(mRunning || mStarted); mCanceled = true; } @@ -182,8 +181,7 @@ public abstract class EventsTest public void onAnimationEnd(Animator animation) { // This should only be called on an animation that has been started and not // yet ended - assertTrue(mRunning); - assertTrue(mStarted); + assertTrue(mRunning || mStarted); mRunning = false; mStarted = false; super.onAnimationEnd(animation); @@ -210,11 +208,12 @@ public abstract class EventsTest } /** - * Verify that calling end on an unstarted animator does nothing. + * Verify that calling end on an unstarted animator starts/ends an animator. */ @UiThreadTest @SmallTest public void testEnd() throws Exception { + mRunning = true; // end() implicitly starts an unstarted animator mAnimator.end(); } @@ -496,6 +495,7 @@ public abstract class EventsTest mRunning = true; mAnimator.start(); mAnimator.end(); + mRunning = true; // end() implicitly starts an unstarted animator mAnimator.end(); mFuture.release(); } catch (junit.framework.AssertionFailedError e) { @@ -544,6 +544,7 @@ public abstract class EventsTest mRunning = true; mAnimator.start(); mAnimator.end(); + mRunning = true; // end() implicitly starts an unstarted animator mAnimator.end(); mFuture.release(); } catch (junit.framework.AssertionFailedError e) { diff --git a/core/tests/coretests/src/android/app/DownloadManagerBaseTest.java b/core/tests/coretests/src/android/app/DownloadManagerBaseTest.java index 6a471ad..b2075ae 100644 --- a/core/tests/coretests/src/android/app/DownloadManagerBaseTest.java +++ b/core/tests/coretests/src/android/app/DownloadManagerBaseTest.java @@ -16,12 +16,8 @@ package android.app; -import coretestutils.http.MockResponse; -import coretestutils.http.MockWebServer; - import android.app.DownloadManager.Query; import android.app.DownloadManager.Request; -import android.app.DownloadManagerBaseTest.DataType; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -39,10 +35,14 @@ import android.provider.Settings; import android.test.InstrumentationTestCase; import android.util.Log; +import com.google.mockwebserver.MockResponse; +import com.google.mockwebserver.MockWebServer; + import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; @@ -53,13 +53,15 @@ import java.util.Random; import java.util.Set; import java.util.concurrent.TimeoutException; +import libcore.io.Streams; + /** * Base class for Instrumented tests for the Download Manager. */ public class DownloadManagerBaseTest extends InstrumentationTestCase { private static final String TAG = "DownloadManagerBaseTest"; protected DownloadManager mDownloadManager = null; - protected MockWebServer mServer = null; + private MockWebServer mServer = null; protected String mFileType = "text/plain"; protected Context mContext = null; protected MultipleDownloadsCompletedReceiver mReceiver = null; @@ -237,63 +239,57 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { mContext = getInstrumentation().getContext(); mDownloadManager = (DownloadManager)mContext.getSystemService(Context.DOWNLOAD_SERVICE); mServer = new MockWebServer(); + mServer.play(); mReceiver = registerNewMultipleDownloadsReceiver(); // Note: callers overriding this should call mServer.play() with the desired port # } /** - * Helper to enqueue a response from the MockWebServer with no body. + * Helper to build a response from the MockWebServer with no body. * * @param status The HTTP status code to return for this response * @return Returns the mock web server response that was queued (which can be modified) */ - protected MockResponse enqueueResponse(int status) { - return doEnqueueResponse(status); - + protected MockResponse buildResponse(int status) { + MockResponse response = new MockResponse().setResponseCode(status); + response.setHeader("Content-type", mFileType); + return response; } /** - * Helper to enqueue a response from the MockWebServer. + * Helper to build a response from the MockWebServer. * * @param status The HTTP status code to return for this response * @param body The body to return in this response * @return Returns the mock web server response that was queued (which can be modified) */ - protected MockResponse enqueueResponse(int status, byte[] body) { - return doEnqueueResponse(status).setBody(body); - + protected MockResponse buildResponse(int status, byte[] body) { + return buildResponse(status).setBody(body); } /** - * Helper to enqueue a response from the MockWebServer. + * Helper to build a response from the MockWebServer. * * @param status The HTTP status code to return for this response * @param bodyFile The body to return in this response * @return Returns the mock web server response that was queued (which can be modified) */ - protected MockResponse enqueueResponse(int status, File bodyFile) { - return doEnqueueResponse(status).setBody(bodyFile); + protected MockResponse buildResponse(int status, File bodyFile) + throws FileNotFoundException, IOException { + final byte[] body = Streams.readFully(new FileInputStream(bodyFile)); + return buildResponse(status).setBody(body); } - /** - * Helper for enqueue'ing a response from the MockWebServer. - * - * @param status The HTTP status code to return for this response - * @return Returns the mock web server response that was queued (which can be modified) - */ - protected MockResponse doEnqueueResponse(int status) { - MockResponse response = new MockResponse().setResponseCode(status); - response.addHeader("Content-type", mFileType); - mServer.enqueue(response); - return response; + protected void enqueueResponse(MockResponse resp) { + mServer.enqueue(resp); } /** * Helper to generate a random blob of bytes. * * @param size The size of the data to generate - * @param type The type of data to generate: currently, one of {@link DataType.TEXT} or - * {@link DataType.BINARY}. + * @param type The type of data to generate: currently, one of {@link DataType#TEXT} or + * {@link DataType#BINARY}. * @return The random data that is generated. */ protected byte[] generateData(int size, DataType type) { @@ -304,8 +300,8 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { * Helper to generate a random blob of bytes using a given RNG. * * @param size The size of the data to generate - * @param type The type of data to generate: currently, one of {@link DataType.TEXT} or - * {@link DataType.BINARY}. + * @param type The type of data to generate: currently, one of {@link DataType#TEXT} or + * {@link DataType#BINARY}. * @param rng (optional) The RNG to use; pass null to use * @return The random data that is generated. */ @@ -492,8 +488,6 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); - mServer.checkForExceptions(); - verifyFileSize(pfd, fileSize); verifyFileContents(pfd, fileData); } finally { @@ -928,7 +922,7 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { protected long enqueueDownloadRequest(byte[] body, int location) throws Exception { // Prepare the mock server with a standard response - enqueueResponse(HTTP_OK, body); + mServer.enqueue(buildResponse(HTTP_OK, body)); return doEnqueue(location); } @@ -943,7 +937,7 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { protected long enqueueDownloadRequest(File body, int location) throws Exception { // Prepare the mock server with a standard response - enqueueResponse(HTTP_OK, body); + mServer.enqueue(buildResponse(HTTP_OK, body)); return doEnqueue(location); } @@ -1035,4 +1029,4 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { assertEquals(1, mReceiver.numDownloadsCompleted()); return dlRequest; } -}
\ No newline at end of file +} diff --git a/core/tests/coretests/src/android/app/DownloadManagerFunctionalTest.java b/core/tests/coretests/src/android/app/DownloadManagerFunctionalTest.java index afe7f55..aa9f69d 100644 --- a/core/tests/coretests/src/android/app/DownloadManagerFunctionalTest.java +++ b/core/tests/coretests/src/android/app/DownloadManagerFunctionalTest.java @@ -16,8 +16,6 @@ package android.app; -import coretestutils.http.MockResponse; - import android.app.DownloadManager.Query; import android.app.DownloadManager.Request; import android.database.Cursor; @@ -26,6 +24,8 @@ import android.os.Environment; import android.os.ParcelFileDescriptor; import android.test.suitebuilder.annotation.LargeTest; +import com.google.mockwebserver.MockResponse; + import java.io.File; import java.util.Iterator; import java.util.Set; @@ -47,7 +47,6 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { public void setUp() throws Exception { super.setUp(); setWiFiStateOn(true); - mServer.play(); removeAllCurrentDownloads(); } @@ -132,8 +131,6 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToFirst()); - mServer.checkForExceptions(); - verifyFileSize(pfd, fileSize); verifyFileContents(pfd, fileData); int colIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME); @@ -154,7 +151,7 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { byte[] blobData = generateData(DEFAULT_FILE_SIZE, DataType.TEXT); // Prepare the mock server with a standard response - enqueueResponse(HTTP_OK, blobData); + enqueueResponse(buildResponse(HTTP_OK, blobData)); try { Uri uri = getServerUri(DEFAULT_FILENAME); @@ -193,7 +190,7 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { byte[] blobData = generateData(DEFAULT_FILE_SIZE, DataType.TEXT); // Prepare the mock server with a standard response - enqueueResponse(HTTP_OK, blobData); + enqueueResponse(buildResponse(HTTP_OK, blobData)); Uri uri = getServerUri(DEFAULT_FILENAME); Request request = new Request(uri); @@ -224,7 +221,7 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { byte[] blobData = generateData(DEFAULT_FILE_SIZE, DataType.TEXT); // Prepare the mock server with a standard response - enqueueResponse(HTTP_OK, blobData); + enqueueResponse(buildResponse(HTTP_OK, blobData)); Uri uri = getServerUri(DEFAULT_FILENAME); Request request = new Request(uri); @@ -251,7 +248,7 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { public void testGetDownloadIdOnNotification() throws Exception { byte[] blobData = generateData(3000, DataType.TEXT); // file size = 3000 bytes - MockResponse response = enqueueResponse(HTTP_OK, blobData); + enqueueResponse(buildResponse(HTTP_OK, blobData)); long dlRequest = doCommonStandardEnqueue(); waitForDownloadOrTimeout(dlRequest); @@ -271,8 +268,9 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { // force 6 redirects for (int i = 0; i < 6; ++i) { - MockResponse response = enqueueResponse(HTTP_REDIRECT); - response.addHeader("Location", uri.toString()); + final MockResponse resp = buildResponse(HTTP_REDIRECT); + resp.setHeader("Location", uri.toString()); + enqueueResponse(resp); } doErrorTest(uri, DownloadManager.ERROR_TOO_MANY_REDIRECTS); } @@ -283,7 +281,7 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { @LargeTest public void testErrorUnhandledHttpCode() throws Exception { Uri uri = getServerUri(DEFAULT_FILENAME); - MockResponse response = enqueueResponse(HTTP_PARTIAL_CONTENT); + enqueueResponse(buildResponse(HTTP_PARTIAL_CONTENT)); doErrorTest(uri, DownloadManager.ERROR_UNHANDLED_HTTP_CODE); } @@ -294,8 +292,9 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { @LargeTest public void testErrorHttpDataError_invalidRedirect() throws Exception { Uri uri = getServerUri(DEFAULT_FILENAME); - MockResponse response = enqueueResponse(HTTP_REDIRECT); - response.addHeader("Location", "://blah.blah.blah.com"); + final MockResponse resp = buildResponse(HTTP_REDIRECT); + resp.setHeader("Location", "://blah.blah.blah.com"); + enqueueResponse(resp); doErrorTest(uri, DownloadManager.ERROR_HTTP_DATA_ERROR); } @@ -327,7 +326,7 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { public void testSetTitle() throws Exception { int fileSize = 1024; byte[] blobData = generateData(fileSize, DataType.BINARY); - MockResponse response = enqueueResponse(HTTP_OK, blobData); + enqueueResponse(buildResponse(HTTP_OK, blobData)); // An arbitrary unicode string title final String title = "\u00a5123;\"\u0152\u017d \u054b \u0a07 \ucce0 \u6820\u03a8\u5c34" + @@ -359,7 +358,7 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { byte[] blobData = generateData(fileSize, DataType.TEXT); setWiFiStateOn(false); - enqueueResponse(HTTP_OK, blobData); + enqueueResponse(buildResponse(HTTP_OK, blobData)); try { Uri uri = getServerUri(DEFAULT_FILENAME); @@ -383,32 +382,16 @@ public class DownloadManagerFunctionalTest extends DownloadManagerBaseTest { } /** - * Tests when the server drops the connection after all headers (but before any data send). - */ - @LargeTest - public void testDropConnection_headers() throws Exception { - byte[] blobData = generateData(DEFAULT_FILE_SIZE, DataType.TEXT); - - MockResponse response = enqueueResponse(HTTP_OK, blobData); - response.setCloseConnectionAfterHeader("content-length"); - long dlRequest = doCommonStandardEnqueue(); - - // Download will never complete when header is dropped - boolean success = waitForDownloadOrTimeoutNoThrow(dlRequest, DEFAULT_WAIT_POLL_TIME, - DEFAULT_MAX_WAIT_TIME); - - assertFalse(success); - } - - /** * Tests that we get an error code when the server drops the connection during a download. */ @LargeTest public void testServerDropConnection_body() throws Exception { byte[] blobData = generateData(25000, DataType.TEXT); // file size = 25000 bytes - MockResponse response = enqueueResponse(HTTP_OK, blobData); - response.setCloseConnectionAfterXBytes(15382); + final MockResponse resp = buildResponse(HTTP_OK, blobData); + resp.setHeader("Content-Length", "50000"); + enqueueResponse(resp); + long dlRequest = doCommonStandardEnqueue(); waitForDownloadOrTimeout(dlRequest); diff --git a/core/tests/coretests/src/android/app/DownloadManagerStressTest.java b/core/tests/coretests/src/android/app/DownloadManagerStressTest.java index bdeb554..864b2d6 100644 --- a/core/tests/coretests/src/android/app/DownloadManagerStressTest.java +++ b/core/tests/coretests/src/android/app/DownloadManagerStressTest.java @@ -46,7 +46,6 @@ public class DownloadManagerStressTest extends DownloadManagerBaseTest { public void setUp() throws Exception { super.setUp(); setWiFiStateOn(true); - mServer.play(); removeAllCurrentDownloads(); } @@ -85,7 +84,7 @@ public class DownloadManagerStressTest extends DownloadManagerBaseTest { request.setTitle(String.format("%s--%d", DEFAULT_FILENAME + i, i)); // Prepare the mock server with a standard response - enqueueResponse(HTTP_OK, blobData); + enqueueResponse(buildResponse(HTTP_OK, blobData)); long requestID = mDownloadManager.enqueue(request); } @@ -127,7 +126,7 @@ public class DownloadManagerStressTest extends DownloadManagerBaseTest { try { long dlRequest = doStandardEnqueue(largeFile); - // wait for the download to complete + // wait for the download to complete waitForDownloadOrTimeout(dlRequest); ParcelFileDescriptor pfd = mDownloadManager.openDownloadedFile(dlRequest); diff --git a/core/tests/coretests/src/android/app/activity/BroadcastTest.java b/core/tests/coretests/src/android/app/activity/BroadcastTest.java index 4b1f9fd..d527c0d 100644 --- a/core/tests/coretests/src/android/app/activity/BroadcastTest.java +++ b/core/tests/coretests/src/android/app/activity/BroadcastTest.java @@ -303,7 +303,8 @@ public class BroadcastTest extends ActivityTestsBase { public void testSetSticky() throws Exception { Intent intent = new Intent(LaunchpadActivity.BROADCAST_STICKY1, null); intent.putExtra("test", LaunchpadActivity.DATA_1); - ActivityManagerNative.getDefault().unbroadcastIntent(null, intent); + ActivityManagerNative.getDefault().unbroadcastIntent(null, intent, + Binder.getOrigCallingUser()); ActivityManagerNative.broadcastStickyIntent(intent, null); addIntermediate("finished-broadcast"); @@ -320,7 +321,8 @@ public class BroadcastTest extends ActivityTestsBase { ActivityManagerNative.broadcastStickyIntent(intent, null); ActivityManagerNative.getDefault().unbroadcastIntent( - null, new Intent(LaunchpadActivity.BROADCAST_STICKY1, null)); + null, new Intent(LaunchpadActivity.BROADCAST_STICKY1, null), + Binder.getOrigCallingUser()); addIntermediate("finished-unbroadcast"); IntentFilter filter = new IntentFilter(LaunchpadActivity.BROADCAST_STICKY1); diff --git a/core/tests/coretests/src/android/content/SyncOperationTest.java b/core/tests/coretests/src/android/content/SyncOperationTest.java index 37e948d..910c721 100644 --- a/core/tests/coretests/src/android/content/SyncOperationTest.java +++ b/core/tests/coretests/src/android/content/SyncOperationTest.java @@ -41,7 +41,7 @@ public class SyncOperationTest extends AndroidTestCase { Bundle b2 = new Bundle(); b2.putBoolean("b2", true); - SyncOperation op1 = new SyncOperation(account1, + SyncOperation op1 = new SyncOperation(account1, 0, 1, "authority1", b1, @@ -51,7 +51,7 @@ public class SyncOperationTest extends AndroidTestCase { false); // Same as op1 but different time infos - SyncOperation op2 = new SyncOperation(account1, + SyncOperation op2 = new SyncOperation(account1, 0, 1, "authority1", b1, @@ -61,7 +61,7 @@ public class SyncOperationTest extends AndroidTestCase { false); // Same as op1 but different authority - SyncOperation op3 = new SyncOperation(account1, + SyncOperation op3 = new SyncOperation(account1, 0, 1, "authority2", b1, @@ -71,7 +71,7 @@ public class SyncOperationTest extends AndroidTestCase { false); // Same as op1 but different account - SyncOperation op4 = new SyncOperation(account2, + SyncOperation op4 = new SyncOperation(account2, 0, 1, "authority1", b1, @@ -81,7 +81,7 @@ public class SyncOperationTest extends AndroidTestCase { false); // Same as op1 but different bundle - SyncOperation op5 = new SyncOperation(account1, + SyncOperation op5 = new SyncOperation(account1, 0, 1, "authority1", b2, diff --git a/core/tests/coretests/src/android/content/SyncStorageEngineTest.java b/core/tests/coretests/src/android/content/SyncStorageEngineTest.java index ae41409..2add623 100644 --- a/core/tests/coretests/src/android/content/SyncStorageEngineTest.java +++ b/core/tests/coretests/src/android/content/SyncStorageEngineTest.java @@ -34,6 +34,10 @@ import java.util.List; public class SyncStorageEngineTest extends AndroidTestCase { + private File getSyncDir() { + return new File(new File(getContext().getFilesDir(), "system"), "sync"); + } + /** * Test that we handle the case of a history row being old enough to purge before the * correcponding sync is finished. This can happen if the clock changes while we are syncing. @@ -52,7 +56,8 @@ public class SyncStorageEngineTest extends AndroidTestCase { long time0 = 1000; long historyId = engine.insertStartSyncEvent( - account, authority, time0, SyncStorageEngine.SOURCE_LOCAL); + account, 0, authority, time0, SyncStorageEngine.SOURCE_LOCAL, + false /* initialization */); long time1 = time0 + SyncStorageEngine.MILLIS_IN_4WEEKS * 2; engine.stopSyncEvent(historyId, time1 - time0, "yay", 0, 0); } @@ -82,38 +87,47 @@ public class SyncStorageEngineTest extends AndroidTestCase { SyncStorageEngine engine = SyncStorageEngine.newTestInstance( new TestContext(mockResolver, getContext())); - removePeriodicSyncs(engine, account1, authority); - removePeriodicSyncs(engine, account2, authority); + removePeriodicSyncs(engine, account1, 0, authority); + removePeriodicSyncs(engine, account2, 0, authority); + removePeriodicSyncs(engine, account1, 1, authority); // this should add two distinct periodic syncs for account1 and one for account2 - engine.addPeriodicSync(sync1.account, sync1.authority, sync1.extras, sync1.period); - engine.addPeriodicSync(sync2.account, sync2.authority, sync2.extras, sync2.period); - engine.addPeriodicSync(sync3.account, sync3.authority, sync3.extras, sync3.period); - engine.addPeriodicSync(sync4.account, sync4.authority, sync4.extras, sync4.period); + engine.addPeriodicSync(sync1.account, 0, sync1.authority, sync1.extras, sync1.period); + engine.addPeriodicSync(sync2.account, 0, sync2.authority, sync2.extras, sync2.period); + engine.addPeriodicSync(sync3.account, 0, sync3.authority, sync3.extras, sync3.period); + engine.addPeriodicSync(sync4.account, 0, sync4.authority, sync4.extras, sync4.period); + // add a second user + engine.addPeriodicSync(sync2.account, 1, sync2.authority, sync2.extras, sync2.period); - List<PeriodicSync> syncs = engine.getPeriodicSyncs(account1, authority); + List<PeriodicSync> syncs = engine.getPeriodicSyncs(account1, 0, authority); assertEquals(2, syncs.size()); assertEquals(sync1, syncs.get(0)); assertEquals(sync3, syncs.get(1)); - engine.removePeriodicSync(sync1.account, sync1.authority, sync1.extras); + engine.removePeriodicSync(sync1.account, 0, sync1.authority, sync1.extras); - syncs = engine.getPeriodicSyncs(account1, authority); + syncs = engine.getPeriodicSyncs(account1, 0, authority); assertEquals(1, syncs.size()); assertEquals(sync3, syncs.get(0)); - syncs = engine.getPeriodicSyncs(account2, authority); + syncs = engine.getPeriodicSyncs(account2, 0, authority); assertEquals(1, syncs.size()); assertEquals(sync4, syncs.get(0)); + + syncs = engine.getPeriodicSyncs(sync2.account, 1, sync2.authority); + assertEquals(1, syncs.size()); + assertEquals(sync2, syncs.get(0)); } - private void removePeriodicSyncs(SyncStorageEngine engine, Account account, String authority) { - engine.setIsSyncable(account, authority, engine.getIsSyncable(account, authority)); - List<PeriodicSync> syncs = engine.getPeriodicSyncs(account, authority); + private void removePeriodicSyncs(SyncStorageEngine engine, Account account, int userId, + String authority) { + engine.setIsSyncable(account, userId, authority, + engine.getIsSyncable(account, 0, authority)); + List<PeriodicSync> syncs = engine.getPeriodicSyncs(account, userId, authority); for (PeriodicSync sync : syncs) { - engine.removePeriodicSync(sync.account, sync.authority, sync.extras); + engine.removePeriodicSync(sync.account, userId, sync.authority, sync.extras); } } @@ -147,57 +161,57 @@ public class SyncStorageEngineTest extends AndroidTestCase { SyncStorageEngine engine = SyncStorageEngine.newTestInstance( new TestContext(mockResolver, getContext())); - removePeriodicSyncs(engine, account1, authority1); - removePeriodicSyncs(engine, account2, authority1); - removePeriodicSyncs(engine, account1, authority2); - removePeriodicSyncs(engine, account2, authority2); + removePeriodicSyncs(engine, account1, 0, authority1); + removePeriodicSyncs(engine, account2, 0, authority1); + removePeriodicSyncs(engine, account1, 0, authority2); + removePeriodicSyncs(engine, account2, 0, authority2); - engine.setMasterSyncAutomatically(false); + engine.setMasterSyncAutomatically(false, 0); - engine.setIsSyncable(account1, authority1, 1); - engine.setSyncAutomatically(account1, authority1, true); + engine.setIsSyncable(account1, 0, authority1, 1); + engine.setSyncAutomatically(account1, 0, authority1, true); - engine.setIsSyncable(account2, authority1, 1); - engine.setSyncAutomatically(account2, authority1, true); + engine.setIsSyncable(account2, 0, authority1, 1); + engine.setSyncAutomatically(account2, 0, authority1, true); - engine.setIsSyncable(account1, authority2, 1); - engine.setSyncAutomatically(account1, authority2, false); + engine.setIsSyncable(account1, 0, authority2, 1); + engine.setSyncAutomatically(account1, 0, authority2, false); - engine.setIsSyncable(account2, authority2, 0); - engine.setSyncAutomatically(account2, authority2, true); + engine.setIsSyncable(account2, 0, authority2, 0); + engine.setSyncAutomatically(account2, 0, authority2, true); - engine.addPeriodicSync(sync1.account, sync1.authority, sync1.extras, sync1.period); - engine.addPeriodicSync(sync2.account, sync2.authority, sync2.extras, sync2.period); - engine.addPeriodicSync(sync3.account, sync3.authority, sync3.extras, sync3.period); - engine.addPeriodicSync(sync4.account, sync4.authority, sync4.extras, sync4.period); - engine.addPeriodicSync(sync5.account, sync5.authority, sync5.extras, sync5.period); + engine.addPeriodicSync(sync1.account, 0, sync1.authority, sync1.extras, sync1.period); + engine.addPeriodicSync(sync2.account, 0, sync2.authority, sync2.extras, sync2.period); + engine.addPeriodicSync(sync3.account, 0, sync3.authority, sync3.extras, sync3.period); + engine.addPeriodicSync(sync4.account, 0, sync4.authority, sync4.extras, sync4.period); + engine.addPeriodicSync(sync5.account, 0, sync5.authority, sync5.extras, sync5.period); engine.writeAllState(); engine.clearAndReadState(); - List<PeriodicSync> syncs = engine.getPeriodicSyncs(account1, authority1); + List<PeriodicSync> syncs = engine.getPeriodicSyncs(account1, 0, authority1); assertEquals(2, syncs.size()); assertEquals(sync1, syncs.get(0)); assertEquals(sync2, syncs.get(1)); - syncs = engine.getPeriodicSyncs(account1, authority2); + syncs = engine.getPeriodicSyncs(account1, 0, authority2); assertEquals(2, syncs.size()); assertEquals(sync3, syncs.get(0)); assertEquals(sync4, syncs.get(1)); - syncs = engine.getPeriodicSyncs(account2, authority1); + syncs = engine.getPeriodicSyncs(account2, 0, authority1); assertEquals(1, syncs.size()); assertEquals(sync5, syncs.get(0)); - assertEquals(true, engine.getSyncAutomatically(account1, authority1)); - assertEquals(true, engine.getSyncAutomatically(account2, authority1)); - assertEquals(false, engine.getSyncAutomatically(account1, authority2)); - assertEquals(true, engine.getSyncAutomatically(account2, authority2)); + assertEquals(true, engine.getSyncAutomatically(account1, 0, authority1)); + assertEquals(true, engine.getSyncAutomatically(account2, 0, authority1)); + assertEquals(false, engine.getSyncAutomatically(account1, 0, authority2)); + assertEquals(true, engine.getSyncAutomatically(account2, 0, authority2)); - assertEquals(1, engine.getIsSyncable(account1, authority1)); - assertEquals(1, engine.getIsSyncable(account2, authority1)); - assertEquals(1, engine.getIsSyncable(account1, authority2)); - assertEquals(0, engine.getIsSyncable(account2, authority2)); + assertEquals(1, engine.getIsSyncable(account1, 0, authority1)); + assertEquals(1, engine.getIsSyncable(account2, 0, authority1)); + assertEquals(1, engine.getIsSyncable(account1, 0, authority2)); + assertEquals(0, engine.getIsSyncable(account2, 0, authority2)); } @MediumTest @@ -220,12 +234,13 @@ public class SyncStorageEngineTest extends AndroidTestCase { byte[] accountsFileData = ("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n" + "<accounts>\n" - + "<authority id=\"0\" account=\"account1\" type=\"type1\" authority=\"auth1\" />\n" - + "<authority id=\"1\" account=\"account1\" type=\"type1\" authority=\"auth2\" />\n" - + "<authority id=\"2\" account=\"account1\" type=\"type1\" authority=\"auth3\" />\n" + + "<authority id=\"0\" user=\"0\" account=\"account1\" type=\"type1\" authority=\"auth1\" />\n" + + "<authority id=\"1\" user=\"0\" account=\"account1\" type=\"type1\" authority=\"auth2\" />\n" + + "<authority id=\"2\" account=\"account1\" type=\"type1\" authority=\"auth3\" />\n" + + "<authority id=\"3\" user=\"1\" account=\"account1\" type=\"type1\" authority=\"auth3\" />\n" + "</accounts>\n").getBytes(); - File syncDir = new File(new File(testContext.getFilesDir(), "system"), "sync"); + File syncDir = getSyncDir(); syncDir.mkdirs(); AtomicFile accountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml")); FileOutputStream fos = accountInfoFile.startWrite(); @@ -234,15 +249,19 @@ public class SyncStorageEngineTest extends AndroidTestCase { SyncStorageEngine engine = SyncStorageEngine.newTestInstance(testContext); - List<PeriodicSync> syncs = engine.getPeriodicSyncs(account, authority1); + List<PeriodicSync> syncs = engine.getPeriodicSyncs(account, 0, authority1); assertEquals(1, syncs.size()); assertEquals(sync1, syncs.get(0)); - syncs = engine.getPeriodicSyncs(account, authority2); + syncs = engine.getPeriodicSyncs(account, 0, authority2); assertEquals(1, syncs.size()); assertEquals(sync2, syncs.get(0)); - syncs = engine.getPeriodicSyncs(account, authority3); + syncs = engine.getPeriodicSyncs(account, 0, authority3); + assertEquals(1, syncs.size()); + assertEquals(sync3, syncs.get(0)); + + syncs = engine.getPeriodicSyncs(account, 1, authority3); assertEquals(1, syncs.size()); assertEquals(sync3, syncs.get(0)); @@ -260,13 +279,13 @@ public class SyncStorageEngineTest extends AndroidTestCase { engine.clearAndReadState(); - syncs = engine.getPeriodicSyncs(account, authority1); + syncs = engine.getPeriodicSyncs(account, 0, authority1); assertEquals(0, syncs.size()); - syncs = engine.getPeriodicSyncs(account, authority2); + syncs = engine.getPeriodicSyncs(account, 0, authority2); assertEquals(0, syncs.size()); - syncs = engine.getPeriodicSyncs(account, authority3); + syncs = engine.getPeriodicSyncs(account, 0, authority3); assertEquals(0, syncs.size()); accountsFileData = ("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n" @@ -289,20 +308,48 @@ public class SyncStorageEngineTest extends AndroidTestCase { engine.clearAndReadState(); - syncs = engine.getPeriodicSyncs(account, authority1); + syncs = engine.getPeriodicSyncs(account, 0, authority1); assertEquals(1, syncs.size()); assertEquals(sync1s, syncs.get(0)); - syncs = engine.getPeriodicSyncs(account, authority2); + syncs = engine.getPeriodicSyncs(account, 0, authority2); assertEquals(1, syncs.size()); assertEquals(sync2s, syncs.get(0)); - syncs = engine.getPeriodicSyncs(account, authority3); + syncs = engine.getPeriodicSyncs(account, 0, authority3); assertEquals(1, syncs.size()); assertEquals(sync3s, syncs.get(0)); } @MediumTest + public void testListenForTicklesParsing() throws Exception { + byte[] accountsFileData = ("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n" + + "<accounts>\n" + + "<listenForTickles user=\"0\" enabled=\"false\" />" + + "<listenForTickles user=\"1\" enabled=\"true\" />" + + "<authority id=\"0\" user=\"0\" account=\"account1\" type=\"type1\" authority=\"auth1\" />\n" + + "<authority id=\"1\" user=\"1\" account=\"account1\" type=\"type1\" authority=\"auth1\" />\n" + + "</accounts>\n").getBytes(); + + MockContentResolver mockResolver = new MockContentResolver(); + final TestContext testContext = new TestContext(mockResolver, getContext()); + + File syncDir = getSyncDir(); + syncDir.mkdirs(); + AtomicFile accountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml")); + FileOutputStream fos = accountInfoFile.startWrite(); + fos.write(accountsFileData); + accountInfoFile.finishWrite(fos); + + SyncStorageEngine engine = SyncStorageEngine.newTestInstance(testContext); + + assertEquals(false, engine.getMasterSyncAutomatically(0)); + assertEquals(true, engine.getMasterSyncAutomatically(1)); + assertEquals(true, engine.getMasterSyncAutomatically(2)); + + } + + @MediumTest public void testAuthorityRenaming() throws Exception { final Account account1 = new Account("acc1", "type1"); final Account account2 = new Account("acc2", "type2"); @@ -339,17 +386,17 @@ public class SyncStorageEngineTest extends AndroidTestCase { SyncStorageEngine engine = SyncStorageEngine.newTestInstance(testContext); - assertEquals(false, engine.getSyncAutomatically(account1, authorityContacts)); - assertEquals(false, engine.getSyncAutomatically(account1, authorityCalendar)); - assertEquals(true, engine.getSyncAutomatically(account1, authorityOther)); - assertEquals(true, engine.getSyncAutomatically(account1, authorityContactsNew)); - assertEquals(true, engine.getSyncAutomatically(account1, authorityCalendarNew)); - - assertEquals(false, engine.getSyncAutomatically(account2, authorityContacts)); - assertEquals(false, engine.getSyncAutomatically(account2, authorityCalendar)); - assertEquals(true, engine.getSyncAutomatically(account2, authorityOther)); - assertEquals(false, engine.getSyncAutomatically(account2, authorityContactsNew)); - assertEquals(false, engine.getSyncAutomatically(account2, authorityCalendarNew)); + assertEquals(false, engine.getSyncAutomatically(account1, 0, authorityContacts)); + assertEquals(false, engine.getSyncAutomatically(account1, 0, authorityCalendar)); + assertEquals(true, engine.getSyncAutomatically(account1, 0, authorityOther)); + assertEquals(true, engine.getSyncAutomatically(account1, 0, authorityContactsNew)); + assertEquals(true, engine.getSyncAutomatically(account1, 0, authorityCalendarNew)); + + assertEquals(false, engine.getSyncAutomatically(account2, 0, authorityContacts)); + assertEquals(false, engine.getSyncAutomatically(account2, 0, authorityCalendar)); + assertEquals(true, engine.getSyncAutomatically(account2, 0, authorityOther)); + assertEquals(false, engine.getSyncAutomatically(account2, 0, authorityContactsNew)); + assertEquals(false, engine.getSyncAutomatically(account2, 0, authorityCalendarNew)); } @SmallTest @@ -379,10 +426,10 @@ public class SyncStorageEngineTest extends AndroidTestCase { SyncStorageEngine engine = SyncStorageEngine.newTestInstance(testContext); - assertEquals(-1, engine.getIsSyncable(account, "other1")); - assertEquals(1, engine.getIsSyncable(account, "other2")); - assertEquals(0, engine.getIsSyncable(account, "other3")); - assertEquals(1, engine.getIsSyncable(account, "other4")); + assertEquals(-1, engine.getIsSyncable(account, 0, "other1")); + assertEquals(1, engine.getIsSyncable(account, 0, "other2")); + assertEquals(0, engine.getIsSyncable(account, 0, "other3")); + assertEquals(1, engine.getIsSyncable(account, 0, "other4")); } } diff --git a/core/tests/coretests/src/android/content/pm/AppCacheTest.java b/core/tests/coretests/src/android/content/pm/AppCacheTest.java index 2982816..0c31e2d 100755 --- a/core/tests/coretests/src/android/content/pm/AppCacheTest.java +++ b/core/tests/coretests/src/android/content/pm/AppCacheTest.java @@ -24,6 +24,7 @@ import android.content.IntentFilter; import android.os.RemoteException; import android.os.ServiceManager; import android.os.StatFs; +import android.os.UserId; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; @@ -674,7 +675,7 @@ public class AppCacheTest extends AndroidTestCase { PackageDataObserver observer = new PackageDataObserver(); //wait on observer synchronized(observer) { - getPm().clearApplicationUserData(packageName, observer); + getPm().clearApplicationUserData(packageName, observer, 0 /* TODO: Other users */); long waitTime = 0; while(!observer.isDone() || (waitTime > MAX_WAIT_TIME)) { observer.wait(WAIT_TIME_INCR); @@ -717,7 +718,8 @@ public class AppCacheTest extends AndroidTestCase { File getDataDir() { try { - ApplicationInfo appInfo = getPm().getApplicationInfo(mContext.getPackageName(), 0); + ApplicationInfo appInfo = getPm().getApplicationInfo(mContext.getPackageName(), 0, + UserId.myUserId()); return new File(appInfo.dataDir); } catch (RemoteException e) { throw new RuntimeException("Pacakge manager dead", e); @@ -746,7 +748,7 @@ public class AppCacheTest extends AndroidTestCase { @LargeTest public void testClearApplicationUserDataNoObserver() throws Exception { - getPm().clearApplicationUserData(mContext.getPackageName(), null); + getPm().clearApplicationUserData(mContext.getPackageName(), null, UserId.myUserId()); //sleep for 1 minute Thread.sleep(60*1000); //confirm files dont exist diff --git a/core/tests/coretests/src/android/content/pm/ContainerEncryptionParamsTest.java b/core/tests/coretests/src/android/content/pm/ContainerEncryptionParamsTest.java new file mode 100644 index 0000000..7deaa9a --- /dev/null +++ b/core/tests/coretests/src/android/content/pm/ContainerEncryptionParamsTest.java @@ -0,0 +1,370 @@ +/* + * Copyright (C) 2012 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.content.pm; + +import android.os.Parcel; +import android.test.AndroidTestCase; + +import java.util.Arrays; + +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +public class ContainerEncryptionParamsTest extends AndroidTestCase { + private static final String ENC_ALGORITHM = "AES/CBC/PKCS7Padding"; + + private static final byte[] IV_BYTES = "FOOBAR".getBytes(); + + private static final IvParameterSpec ENC_PARAMS = new IvParameterSpec(IV_BYTES); + + private static final byte[] ENC_KEY_BYTES = "abcd1234wxyz7890".getBytes(); + + private static final SecretKey ENC_KEY = new SecretKeySpec(ENC_KEY_BYTES, "RAW"); + + private static final String MAC_ALGORITHM = "HMAC-SHA1"; + + private static final byte[] MAC_KEY_BYTES = "4wxyzabcd1237890".getBytes(); + + private static final SecretKey MAC_KEY = new SecretKeySpec(MAC_KEY_BYTES, "RAW"); + + private static final byte[] MAC_TAG = "faketag".getBytes(); + + private static final int AUTHENTICATED_START = 5; + + private static final int ENCRYPTED_START = 11; + + private static final int DATA_END = 19; + + public void testParcel() throws Exception { + ContainerEncryptionParams expected = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + Parcel parcel = Parcel.obtain(); + expected.writeToParcel(parcel, 0); + parcel.setDataPosition(0); + + ContainerEncryptionParams actual = ContainerEncryptionParams.CREATOR + .createFromParcel(parcel); + + assertEquals(ENC_ALGORITHM, actual.getEncryptionAlgorithm()); + + if (!(actual.getEncryptionSpec() instanceof IvParameterSpec)) { + fail("encryption parameters should be IvParameterSpec"); + } else { + IvParameterSpec actualParams = (IvParameterSpec) actual.getEncryptionSpec(); + assertTrue(Arrays.equals(IV_BYTES, actualParams.getIV())); + } + + assertEquals(ENC_KEY, actual.getEncryptionKey()); + + assertEquals(MAC_ALGORITHM, actual.getMacAlgorithm()); + + assertNull(actual.getMacSpec()); + + assertEquals(MAC_KEY, actual.getMacKey()); + + assertTrue(Arrays.equals(MAC_TAG, actual.getMacTag())); + + assertEquals(AUTHENTICATED_START, actual.getAuthenticatedDataStart()); + + assertEquals(ENCRYPTED_START, actual.getEncryptedDataStart()); + + assertEquals(DATA_END, actual.getDataEnd()); + } + + public void testEquals_Success() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertEquals(params1, params2); + } + + public void testEquals_EncAlgo_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams(new String( + "AES-256/CBC/PKCS7Padding"), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.equals(params2)); + } + + public void testEquals_EncParams_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec("BLAHBLAH".getBytes()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.equals(params2)); + } + + public void testEquals_EncKey_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec("BLAHBLAH".getBytes(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.equals(params2)); + } + + public void testEquals_MacAlgo_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), "BLAHBLAH", null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.equals(params2)); + } + + public void testEquals_MacKey_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec("FAKE_MAC_KEY".getBytes(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.equals(params2)); + } + + public void testEquals_MacTag_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), "broken".getBytes(), + AUTHENTICATED_START, ENCRYPTED_START, DATA_END); + + assertFalse(params1.equals(params2)); + } + + public void testEquals_AuthenticatedStart_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START - 1, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.equals(params2)); + } + + public void testEquals_EncryptedStart_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START - 1, DATA_END); + + assertFalse(params1.equals(params2)); + } + + public void testEquals_DataEnd_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END + 1); + + assertFalse(params1.equals(params2)); + } + + public void testHashCode_Success() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertEquals(params1.hashCode(), params2.hashCode()); + } + + public void testHashCode_EncAlgo_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams(new String( + "AES-256/CBC/PKCS7Padding"), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.hashCode() == params2.hashCode()); + } + + public void testHashCode_EncParams_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec("BLAHBLAH".getBytes()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.hashCode() == params2.hashCode()); + } + + public void testHashCode_EncKey_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec("BLAHBLAH".getBytes(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.hashCode() == params2.hashCode()); + } + + public void testHashCode_MacAlgo_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), "BLAHBLAH", null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.hashCode() == params2.hashCode()); + } + + public void testHashCode_MacKey_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec("FAKE_MAC_KEY".getBytes(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.hashCode() == params2.hashCode()); + } + + public void testHashCode_MacTag_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), "broken".getBytes(), + AUTHENTICATED_START, ENCRYPTED_START, DATA_END); + + assertFalse(params1.hashCode() == params2.hashCode()); + } + + public void testHashCode_AuthenticatedStart_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START - 1, + ENCRYPTED_START, DATA_END); + + assertFalse(params1.hashCode() == params2.hashCode()); + } + + public void testHashCode_EncryptedStart_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START - 1, DATA_END); + + assertFalse(params1.hashCode() == params2.hashCode()); + } + + public void testHashCode_DataEnd_Failure() throws Exception { + ContainerEncryptionParams params1 = new ContainerEncryptionParams(ENC_ALGORITHM, + ENC_PARAMS, ENC_KEY, MAC_ALGORITHM, null, MAC_KEY, MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END); + + ContainerEncryptionParams params2 = new ContainerEncryptionParams( + new String(ENC_ALGORITHM), new IvParameterSpec(IV_BYTES.clone()), + new SecretKeySpec(ENC_KEY_BYTES.clone(), "RAW"), new String(MAC_ALGORITHM), null, + new SecretKeySpec(MAC_KEY_BYTES.clone(), "RAW"), MAC_TAG, AUTHENTICATED_START, + ENCRYPTED_START, DATA_END + 1); + + assertFalse(params1.hashCode() == params2.hashCode()); + } +} diff --git a/core/tests/coretests/src/android/content/pm/LimitedLengthInputStreamTest.java b/core/tests/coretests/src/android/content/pm/LimitedLengthInputStreamTest.java new file mode 100644 index 0000000..1f762fd --- /dev/null +++ b/core/tests/coretests/src/android/content/pm/LimitedLengthInputStreamTest.java @@ -0,0 +1,196 @@ +/* + * Copyright (C) 2012 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.content.pm; + +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.MediumTest; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +public class LimitedLengthInputStreamTest extends AndroidTestCase { + private final byte[] TEST_STRING1 = "This is a test".getBytes(); + + private InputStream mTestStream1; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + mTestStream1 = new ByteArrayInputStream(TEST_STRING1); + } + + @MediumTest + public void testConstructor_NegativeOffset_Failure() throws Exception { + try { + InputStream is = new LimitedLengthInputStream(mTestStream1, -1, TEST_STRING1.length); + fail("Should throw IOException on negative index"); + } catch (IOException e) { + // success + } + } + + @MediumTest + public void testConstructor_NegativeLength_Failure() throws Exception { + try { + InputStream is = new LimitedLengthInputStream(mTestStream1, 0, -1); + fail("Should throw IOException on negative length"); + } catch (IOException e) { + // success + } + } + + @MediumTest + public void testConstructor_NullInputStream_Failure() throws Exception { + try { + InputStream is = new LimitedLengthInputStream(null, 0, 1); + fail("Should throw IOException on null input stream"); + } catch (IOException e) { + // success + } + } + + @MediumTest + public void testConstructor_OffsetLengthOverflow_Fail() throws Exception { + try { + InputStream is = new LimitedLengthInputStream(mTestStream1, Long.MAX_VALUE - 1, + Long.MAX_VALUE - 1); + fail("Should fail when offset + length is > Long.MAX_VALUE"); + } catch (IOException e) { + // success + } + } + + private void checkReadBytesWithOffsetAndLength_WithString1(int offset, int length) + throws Exception { + byte[] temp = new byte[TEST_STRING1.length]; + byte[] expected = new byte[length]; + byte[] actual = new byte[length]; + + System.arraycopy(TEST_STRING1, offset, expected, 0, length); + + InputStream is = new LimitedLengthInputStream(mTestStream1, offset, length); + assertEquals(length, is.read(temp, 0, temp.length)); + + System.arraycopy(temp, 0, actual, 0, length); + assertTrue(Arrays.equals(expected, actual)); + + assertEquals(-1, is.read(temp, 0, temp.length)); + } + + @MediumTest + public void testReadBytesWithOffsetAndLength_ZeroOffset_PartialLength_Success() + throws Exception { + checkReadBytesWithOffsetAndLength_WithString1(0, 2); + } + + @MediumTest + public void testReadBytesWithOffsetAndLength_NonZeroOffset_PartialLength_Success() + throws Exception { + checkReadBytesWithOffsetAndLength_WithString1(3, 2); + } + + @MediumTest + public void testReadBytesWithOffsetAndLength_ZeroOffset_FullLength_Success() throws Exception { + checkReadBytesWithOffsetAndLength_WithString1(0, TEST_STRING1.length); + } + + @MediumTest + public void testReadBytesWithOffsetAndLength_NonZeroOffset_FullLength_Success() + throws Exception { + checkReadBytesWithOffsetAndLength_WithString1(3, TEST_STRING1.length - 3); + } + + @MediumTest + public void testReadBytesWithOffsetAndLength_ZeroOffset_PastEnd_Success() throws Exception { + byte[] temp = new byte[TEST_STRING1.length + 10]; + InputStream is = new LimitedLengthInputStream(mTestStream1, 0, TEST_STRING1.length + 10); + assertEquals(TEST_STRING1.length, is.read(temp, 0, TEST_STRING1.length + 10)); + + byte[] actual = new byte[TEST_STRING1.length]; + System.arraycopy(temp, 0, actual, 0, actual.length); + assertTrue(Arrays.equals(TEST_STRING1, actual)); + } + + private void checkReadBytes_WithString1(int offset, int length) throws Exception { + byte[] temp = new byte[TEST_STRING1.length]; + byte[] expected = new byte[length]; + byte[] actual = new byte[length]; + + System.arraycopy(TEST_STRING1, offset, expected, 0, length); + + InputStream is = new LimitedLengthInputStream(mTestStream1, offset, length); + assertEquals(length, is.read(temp)); + + System.arraycopy(temp, 0, actual, 0, length); + assertTrue(Arrays.equals(expected, actual)); + + assertEquals(-1, is.read(temp)); + } + + @MediumTest + public void testReadBytes_ZeroOffset_PartialLength_Success() throws Exception { + checkReadBytesWithOffsetAndLength_WithString1(0, 2); + } + + @MediumTest + public void testReadBytes_NonZeroOffset_PartialLength_Success() throws Exception { + checkReadBytesWithOffsetAndLength_WithString1(3, 2); + } + + @MediumTest + public void testReadBytes_ZeroOffset_FullLength_Success() throws Exception { + checkReadBytesWithOffsetAndLength_WithString1(0, TEST_STRING1.length); + } + + @MediumTest + public void testReadBytes_NonZeroOffset_FullLength_Success() throws Exception { + checkReadBytesWithOffsetAndLength_WithString1(3, TEST_STRING1.length - 3); + } + + private void checkSingleByteRead_WithString1(int offset, int length) throws Exception { + InputStream is = new LimitedLengthInputStream(mTestStream1, offset, length); + + for (int i = 0; i < length; i++) { + assertEquals(TEST_STRING1[offset + i], is.read()); + } + + assertEquals(-1, is.read()); + } + + @MediumTest + public void testSingleByteRead_ZeroOffset_PartialLength_Success() throws Exception { + checkSingleByteRead_WithString1(0, 2); + } + + @MediumTest + public void testSingleByteRead_NonZeroOffset_PartialLength_Success() throws Exception { + checkSingleByteRead_WithString1(3, 2); + } + + @MediumTest + public void testSingleByteRead_ZeroOffset_FullLength_Success() throws Exception { + checkSingleByteRead_WithString1(0, TEST_STRING1.length); + } + + @MediumTest + public void testSingleByteRead_NonZeroOffset_FullLength_Success() throws Exception { + checkSingleByteRead_WithString1(3, TEST_STRING1.length - 3); + } +} diff --git a/core/tests/coretests/src/android/content/pm/MacAuthenticatedInputStreamTest.java b/core/tests/coretests/src/android/content/pm/MacAuthenticatedInputStreamTest.java new file mode 100644 index 0000000..948e722 --- /dev/null +++ b/core/tests/coretests/src/android/content/pm/MacAuthenticatedInputStreamTest.java @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2012 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.content.pm; + +import android.test.AndroidTestCase; + +import java.io.ByteArrayInputStream; +import java.util.Arrays; + +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import libcore.io.Streams; + +public class MacAuthenticatedInputStreamTest extends AndroidTestCase { + + private static final SecretKey HMAC_KEY_1 = new SecretKeySpec("test_key_1".getBytes(), "HMAC"); + + private static final byte[] TEST_STRING_1 = "Hello, World!".getBytes(); + + /** + * Generated with: + * + * echo -n 'Hello, World!' | openssl dgst -hmac 'test_key_1' -binary -sha1 | recode ..//x1 | + * sed 's/0x/(byte) 0x/g' + */ + private static final byte[] TEST_STRING_1_MAC = { + (byte) 0x29, (byte) 0xB1, (byte) 0x87, (byte) 0x6B, (byte) 0xFE, (byte) 0x83, + (byte) 0x96, (byte) 0x51, (byte) 0x61, (byte) 0x02, (byte) 0xAF, (byte) 0x7B, + (byte) 0xBA, (byte) 0x05, (byte) 0xE6, (byte) 0xA4, (byte) 0xAB, (byte) 0x36, + (byte) 0x18, (byte) 0x02 + }; + + /** + * Same as TEST_STRING_1_MAC but with the first byte as 0x28 instead of + * 0x29. + */ + private static final byte[] TEST_STRING_1_MAC_BROKEN = { + (byte) 0x28, (byte) 0xB1, (byte) 0x87, (byte) 0x6B, (byte) 0xFE, (byte) 0x83, + (byte) 0x96, (byte) 0x51, (byte) 0x61, (byte) 0x02, (byte) 0xAF, (byte) 0x7B, + (byte) 0xBA, (byte) 0x05, (byte) 0xE6, (byte) 0xA4, (byte) 0xAB, (byte) 0x36, + (byte) 0x18, (byte) 0x02 + }; + + private ByteArrayInputStream mTestStream1; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + mTestStream1 = new ByteArrayInputStream(TEST_STRING_1); + } + + public void testString1Authenticate_Success() throws Exception { + Mac mac = Mac.getInstance("HMAC-SHA1"); + mac.init(HMAC_KEY_1); + + MacAuthenticatedInputStream is = new MacAuthenticatedInputStream(mTestStream1, mac); + + assertTrue(Arrays.equals(TEST_STRING_1, Streams.readFully(is))); + + assertTrue(is.isTagEqual(TEST_STRING_1_MAC)); + } + + public void testString1Authenticate_WrongTag_Failure() throws Exception { + Mac mac = Mac.getInstance("HMAC-SHA1"); + mac.init(HMAC_KEY_1); + + MacAuthenticatedInputStream is = new MacAuthenticatedInputStream(mTestStream1, mac); + + assertTrue(Arrays.equals(TEST_STRING_1, Streams.readFully(is))); + + assertFalse(is.isTagEqual(TEST_STRING_1_MAC_BROKEN)); + } + + public void testString1Authenticate_NullTag_Failure() throws Exception { + Mac mac = Mac.getInstance("HMAC-SHA1"); + mac.init(HMAC_KEY_1); + + MacAuthenticatedInputStream is = new MacAuthenticatedInputStream(mTestStream1, mac); + + assertTrue(Arrays.equals(TEST_STRING_1, Streams.readFully(is))); + + assertFalse(is.isTagEqual(null)); + } + + public void testString1Authenticate_ReadSingleByte_Success() throws Exception { + Mac mac = Mac.getInstance("HMAC-SHA1"); + mac.init(HMAC_KEY_1); + + MacAuthenticatedInputStream is = new MacAuthenticatedInputStream(mTestStream1, mac); + + int numRead = 0; + while (is.read() != -1) { + numRead++; + + if (numRead > TEST_STRING_1.length) { + fail("read too many bytes"); + } + } + assertEquals(TEST_STRING_1.length, numRead); + + assertTrue(is.isTagEqual(TEST_STRING_1_MAC)); + } +} diff --git a/core/tests/coretests/src/android/content/pm/PackageHelperTests.java b/core/tests/coretests/src/android/content/pm/PackageHelperTests.java index 27112a6..7ad35d0 100644 --- a/core/tests/coretests/src/android/content/pm/PackageHelperTests.java +++ b/core/tests/coretests/src/android/content/pm/PackageHelperTests.java @@ -81,7 +81,8 @@ public class PackageHelperTests extends AndroidTestCase { public void testMountAndPullSdCard() { try { fullId = PREFIX; - fullId2 = PackageHelper.createSdDir(1024, fullId, "none", android.os.Process.myUid()); + fullId2 = PackageHelper.createSdDir(1024, fullId, "none", android.os.Process.myUid(), + true); Log.d(TAG,PackageHelper.getSdDir(fullId)); PackageHelper.unMountSdDir(fullId); diff --git a/core/tests/coretests/src/android/content/pm/PackageManagerTests.java b/core/tests/coretests/src/android/content/pm/PackageManagerTests.java index 9575ced..77e4986 100755 --- a/core/tests/coretests/src/android/content/pm/PackageManagerTests.java +++ b/core/tests/coretests/src/android/content/pm/PackageManagerTests.java @@ -170,11 +170,10 @@ public class PackageManagerTests extends AndroidTestCase { return ipm; } - public boolean invokeInstallPackage(Uri packageURI, int flags, GenericReceiver receiver) { + public void invokeInstallPackage(Uri packageURI, int flags, GenericReceiver receiver, + boolean shouldSucceed) { PackageInstallObserver observer = new PackageInstallObserver(); - final boolean received = false; mContext.registerReceiver(receiver, receiver.filter); - final boolean DEBUG = true; try { // Wait on observer synchronized(observer) { @@ -192,10 +191,24 @@ public class PackageManagerTests extends AndroidTestCase { if(!observer.isDone()) { fail("Timed out waiting for packageInstalled callback"); } - if (observer.returnCode != PackageManager.INSTALL_SUCCEEDED) { - Log.i(TAG, "Failed to install with error code = " + observer.returnCode); - return false; + + if (shouldSucceed) { + if (observer.returnCode != PackageManager.INSTALL_SUCCEEDED) { + fail("Package installation should have succeeded, but got code " + + observer.returnCode); + } + } else { + if (observer.returnCode == PackageManager.INSTALL_SUCCEEDED) { + fail("Package installation should fail"); + } + + /* + * We'll never expect get a notification since we + * shouldn't succeed. + */ + return; } + // Verify we received the broadcast waitTime = 0; while((!receiver.isDone()) && (waitTime < MAX_WAIT_TIME) ) { @@ -209,7 +222,6 @@ public class PackageManagerTests extends AndroidTestCase { if(!receiver.isDone()) { fail("Timed out waiting for PACKAGE_ADDED notification"); } - return receiver.received; } } } finally { @@ -297,9 +309,7 @@ public class PackageManagerTests extends AndroidTestCase { private static final int INSTALL_LOC_ERR = -1; private int getInstallLoc(int flags, int expInstallLocation, long pkgLen) { // Flags explicitly over ride everything else. - if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0 ) { - return INSTALL_LOC_INT; - } else if ((flags & PackageManager.INSTALL_EXTERNAL) != 0 ) { + if ((flags & PackageManager.INSTALL_EXTERNAL) != 0 ) { return INSTALL_LOC_SD; } else if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { return INSTALL_LOC_INT; @@ -368,61 +378,76 @@ public class PackageManagerTests extends AndroidTestCase { String publicSrcPath = publicSrcDir.getParent(); long pkgLen = new File(info.sourceDir).length(); - if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) { - assertTrue((info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0); - assertEquals(srcPath, drmInstallPath); - assertEquals(publicSrcPath, appInstallPath); - assertTrue(info.nativeLibraryDir.startsWith(dataDir.getPath())); - } else { - assertFalse((info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0); - int rLoc = getInstallLoc(flags, expInstallLocation, pkgLen); - if (rLoc == INSTALL_LOC_INT) { - assertEquals(srcPath, appInstallPath); - assertEquals(publicSrcPath, appInstallPath); - assertFalse((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0); - assertTrue(info.nativeLibraryDir.startsWith(dataDir.getPath())); - - // Make sure the native library dir is not a symlink - final File nativeLibDir = new File(info.nativeLibraryDir); - assertTrue("Native library dir should exist at " + info.nativeLibraryDir, - nativeLibDir.exists()); - try { - assertEquals("Native library dir should not be a symlink", - info.nativeLibraryDir, - nativeLibDir.getCanonicalPath()); - } catch (IOException e) { - fail("Can't read " + nativeLibDir.getPath()); - } - } else if (rLoc == INSTALL_LOC_SD){ - assertTrue("Application flags (" + info.flags - + ") should contain FLAG_EXTERNAL_STORAGE", - (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0); + int rLoc = getInstallLoc(flags, expInstallLocation, pkgLen); + if (rLoc == INSTALL_LOC_INT) { + if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) { + assertTrue("The application should be installed forward locked", + (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0); assertTrue("The APK path (" + srcPath + ") should start with " - + SECURE_CONTAINERS_PREFIX, srcPath - .startsWith(SECURE_CONTAINERS_PREFIX)); + + SECURE_CONTAINERS_PREFIX, + srcPath.startsWith(SECURE_CONTAINERS_PREFIX)); assertTrue("The public APK path (" + publicSrcPath + ") should start with " - + SECURE_CONTAINERS_PREFIX, publicSrcPath - .startsWith(SECURE_CONTAINERS_PREFIX)); + + SECURE_CONTAINERS_PREFIX, + publicSrcPath.startsWith(SECURE_CONTAINERS_PREFIX)); assertTrue("The native library path (" + info.nativeLibraryDir + ") should start with " + SECURE_CONTAINERS_PREFIX, info.nativeLibraryDir.startsWith(SECURE_CONTAINERS_PREFIX)); + } else { + assertFalse((info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0); + assertEquals(srcPath, appInstallPath); + assertEquals(publicSrcPath, appInstallPath); + assertTrue(info.nativeLibraryDir.startsWith(dataDir.getPath())); + } + assertFalse((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0); - // Make sure the native library in /data/data/<app>/lib is a - // symlink to the ASEC - final File nativeLibSymLink = new File(info.dataDir, "lib"); - assertTrue("Native library symlink should exist at " + nativeLibSymLink.getPath(), - nativeLibSymLink.exists()); - try { - assertEquals(nativeLibSymLink.getPath() + " should be a symlink to " - + info.nativeLibraryDir, info.nativeLibraryDir, nativeLibSymLink - .getCanonicalPath()); - } catch (IOException e) { - fail("Can't read " + nativeLibSymLink.getPath()); - } + // Make sure the native library dir is not a symlink + final File nativeLibDir = new File(info.nativeLibraryDir); + assertTrue("Native library dir should exist at " + info.nativeLibraryDir, + nativeLibDir.exists()); + try { + assertEquals("Native library dir should not be a symlink", + info.nativeLibraryDir, + nativeLibDir.getCanonicalPath()); + } catch (IOException e) { + fail("Can't read " + nativeLibDir.getPath()); + } + } else if (rLoc == INSTALL_LOC_SD){ + if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) { + assertTrue("The application should be installed forward locked", + (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0); } else { - // TODO handle error. Install should have failed. - fail("Install should have failed"); + assertFalse("The application should not be installed forward locked", + (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0); } + assertTrue("Application flags (" + info.flags + + ") should contain FLAG_EXTERNAL_STORAGE", + (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0); + // Might need to check: + // ((info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) + assertTrue("The APK path (" + srcPath + ") should start with " + + SECURE_CONTAINERS_PREFIX, srcPath.startsWith(SECURE_CONTAINERS_PREFIX)); + assertTrue("The public APK path (" + publicSrcPath + ") should start with " + + SECURE_CONTAINERS_PREFIX, + publicSrcPath.startsWith(SECURE_CONTAINERS_PREFIX)); + assertTrue("The native library path (" + info.nativeLibraryDir + + ") should start with " + SECURE_CONTAINERS_PREFIX, + info.nativeLibraryDir.startsWith(SECURE_CONTAINERS_PREFIX)); + + // Make sure the native library in /data/data/<app>/lib is a + // symlink to the ASEC + final File nativeLibSymLink = new File(info.dataDir, "lib"); + assertTrue("Native library symlink should exist at " + nativeLibSymLink.getPath(), + nativeLibSymLink.exists()); + try { + assertEquals(nativeLibSymLink.getPath() + " should be a symlink to " + + info.nativeLibraryDir, info.nativeLibraryDir, nativeLibSymLink + .getCanonicalPath()); + } catch (IOException e) { + fail("Can't read " + nativeLibSymLink.getPath()); + } + } else { + // TODO handle error. Install should have failed. + fail("Install should have failed"); } } catch (NameNotFoundException e) { failStr("failed with exception : " + e); @@ -588,7 +613,7 @@ public class PackageManagerTests extends AndroidTestCase { } } else { InstallReceiver receiver = new InstallReceiver(pkg.packageName); - assertTrue(invokeInstallPackage(packageURI, flags, receiver)); + invokeInstallPackage(packageURI, flags, receiver, true); // Verify installed information assertInstall(pkg, flags, expInstallLocation); } @@ -705,13 +730,9 @@ public class PackageManagerTests extends AndroidTestCase { receiver = new InstallReceiver(ip.pkg.packageName); } try { - try { - assertEquals(invokeInstallPackage(ip.packageURI, flags, receiver), replace); - if (replace) { - assertInstall(ip.pkg, flags, ip.pkg.installLocation); - } - } catch (Exception e) { - failStr("Failed with exception : " + e); + invokeInstallPackage(ip.packageURI, flags, receiver, replace); + if (replace) { + assertInstall(ip.pkg, flags, ip.pkg.installLocation); } } finally { cleanUpInstall(ip); @@ -1208,9 +1229,8 @@ public class PackageManagerTests extends AndroidTestCase { installFromRawResource("install.apk", R.raw.install_loc_unspecified, PackageManager.INSTALL_FORWARD_LOCK | - PackageManager.INSTALL_EXTERNAL, true, true, - PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION, - PackageInfo.INSTALL_LOCATION_UNSPECIFIED); + PackageManager.INSTALL_EXTERNAL, true, false, -1, + PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL); } @LargeTest @@ -1244,7 +1264,7 @@ public class PackageManagerTests extends AndroidTestCase { GenericReceiver receiver = new ReplaceReceiver(ip.pkg.packageName); int replaceFlags = rFlags | PackageManager.INSTALL_REPLACE_EXISTING; try { - assertEquals(invokeInstallPackage(ip.packageURI, replaceFlags, receiver), true); + invokeInstallPackage(ip.packageURI, replaceFlags, receiver, true); assertInstall(ip.pkg, rFlags, ip.pkg.installLocation); } catch (Exception e) { failStr("Failed with exception : " + e); @@ -1271,7 +1291,7 @@ public class PackageManagerTests extends AndroidTestCase { GenericReceiver receiver = new ReplaceReceiver(ip.pkg.packageName); int replaceFlags = rFlags | PackageManager.INSTALL_REPLACE_EXISTING; try { - assertEquals(invokeInstallPackage(ip.packageURI, replaceFlags, receiver), true); + invokeInstallPackage(ip.packageURI, replaceFlags, receiver, true); assertInstall(ip.pkg, iFlags, ip.pkg.installLocation); } catch (Exception e) { failStr("Failed with exception : " + e); @@ -1605,8 +1625,8 @@ public class PackageManagerTests extends AndroidTestCase { int installFlags = PackageManager.INSTALL_FORWARD_LOCK; int moveFlags = PackageManager.MOVE_EXTERNAL_MEDIA; - boolean fail = true; - int result = PackageManager.MOVE_FAILED_FORWARD_LOCKED; + boolean fail = false; + int result = PackageManager.MOVE_SUCCEEDED; sampleMoveFromRawResource(installFlags, moveFlags, fail, result); } @@ -1766,15 +1786,17 @@ public class PackageManagerTests extends AndroidTestCase { } /* - * Install an app with both external and forward-lock flags set. should fail + * Install an app with both external and forward-lock flags set. */ @LargeTest public void testFlagEF() { - installFromRawResource("install.apk", R.raw.install, - PackageManager.INSTALL_FORWARD_LOCK | PackageManager.INSTALL_EXTERNAL, - false, - true, PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION, - PackageInfo.INSTALL_LOCATION_AUTO); + // Do not run on devices with emulated external storage. + if (Environment.isExternalStorageEmulated()) { + return; + } + + sampleInstallFromRawResource(PackageManager.INSTALL_FORWARD_LOCK + | PackageManager.INSTALL_EXTERNAL, true); } /* @@ -1891,15 +1913,20 @@ public class PackageManagerTests extends AndroidTestCase { PackageManager.INSTALL_FORWARD_LOCK, true, false, -1, - PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL); + PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY); } /* * Install an app with fwd locked flag set and install location set to - * preferExternal. should install internally. + * preferExternal. Should install externally. */ @LargeTest public void testFlagFManifestE() { + // Do not run on devices with emulated external storage. + if (Environment.isExternalStorageEmulated()) { + return; + } + installFromRawResource("install.apk", R.raw.install_loc_sdcard, PackageManager.INSTALL_FORWARD_LOCK, true, @@ -1908,16 +1935,21 @@ public class PackageManagerTests extends AndroidTestCase { } /* - * Install an app with fwd locked flag set and install location set to - * auto. should install internally. + * Install an app with fwd locked flag set and install location set to auto. + * should install externally. */ @LargeTest public void testFlagFManifestA() { + // Do not run on devices with emulated external storage. + if (Environment.isExternalStorageEmulated()) { + return; + } + installFromRawResource("install.apk", R.raw.install_loc_auto, PackageManager.INSTALL_FORWARD_LOCK, true, false, -1, - PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL); + PackageInfo.INSTALL_LOCATION_AUTO); } /* The following test functions verify install location for existing apps. diff --git a/core/tests/coretests/src/android/database/CursorWindowTest.java b/core/tests/coretests/src/android/database/CursorWindowTest.java index 8c8081c..075f5b7 100644 --- a/core/tests/coretests/src/android/database/CursorWindowTest.java +++ b/core/tests/coretests/src/android/database/CursorWindowTest.java @@ -35,15 +35,45 @@ public class CursorWindowTest extends TestCase implements PerformanceTestCase { } @SmallTest - public void testValuesLocalWindow() { - doTestValues(new CursorWindow(true)); + public void testConstructor_WithName() { + CursorWindow window = new CursorWindow("MyWindow"); + assertEquals("MyWindow", window.getName()); + assertEquals(0, window.getStartPosition()); + window.close(); } - + + @SmallTest + public void testConstructorWithEmptyName() { + CursorWindow window = new CursorWindow(""); + assertEquals("<unnamed>", window.getName()); + assertEquals(0, window.getStartPosition()); + window.close(); + } + @SmallTest - public void testValuesRemoteWindow() { - doTestValues(new CursorWindow(false)); + public void testConstructorWithNullName() { + CursorWindow window = new CursorWindow(null); + assertEquals("<unnamed>", window.getName()); + assertEquals(0, window.getStartPosition()); + window.close(); } - + + @SmallTest + public void testDeprecatedConstructor() { + @SuppressWarnings("deprecation") + CursorWindow window = new CursorWindow(true /*this argument is ignored*/); + assertEquals("<unnamed>", window.getName()); + assertEquals(0, window.getStartPosition()); + window.close(); + } + + @SmallTest + public void testValues() { + CursorWindow window = new CursorWindow("MyWindow"); + doTestValues(window); + window.close(); + } + private void doTestValues(CursorWindow window) { assertTrue(window.setNumColumns(7)); assertTrue(window.allocRow()); diff --git a/core/tests/coretests/src/android/database/DatabaseCursorTest.java b/core/tests/coretests/src/android/database/DatabaseCursorTest.java index 179338d..36f0f4b 100644 --- a/core/tests/coretests/src/android/database/DatabaseCursorTest.java +++ b/core/tests/coretests/src/android/database/DatabaseCursorTest.java @@ -16,7 +16,6 @@ package android.database; -import dalvik.annotation.BrokenTest; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; @@ -27,13 +26,11 @@ import android.database.sqlite.SQLiteCursor; import android.database.sqlite.SQLiteCursorDriver; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQuery; -import android.database.sqlite.SQLiteStatement; import android.os.Looper; import android.test.AndroidTestCase; import android.test.PerformanceTestCase; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; -import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import java.io.File; diff --git a/core/tests/coretests/src/android/database/DatabaseErrorHandlerTest.java b/core/tests/coretests/src/android/database/DatabaseErrorHandlerTest.java index 1cfd960..91c7687 100644 --- a/core/tests/coretests/src/android/database/DatabaseErrorHandlerTest.java +++ b/core/tests/coretests/src/android/database/DatabaseErrorHandlerTest.java @@ -21,7 +21,6 @@ import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDiskIOException; import android.database.sqlite.SQLiteException; import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import java.io.BufferedWriter; diff --git a/core/tests/coretests/src/android/database/DatabaseGeneralTest.java b/core/tests/coretests/src/android/database/DatabaseGeneralTest.java index 6786700..c7cb43d 100644 --- a/core/tests/coretests/src/android/database/DatabaseGeneralTest.java +++ b/core/tests/coretests/src/android/database/DatabaseGeneralTest.java @@ -410,40 +410,6 @@ public class DatabaseGeneralTest extends AndroidTestCase implements PerformanceT } } - private class ChangeObserver extends ContentObserver { - private int mCursorNotificationCount = 0; - private int mNotificationCount = 0; - - public int getCursorNotificationCount() { - return mCursorNotificationCount; - } - - public int getNotificationCount() { - return mNotificationCount; - } - - public ChangeObserver(boolean cursor) { - super(new Handler()); - mCursor = cursor; - } - - @Override - public boolean deliverSelfNotifications() { - return true; - } - - @Override - public void onChange(boolean selfChange) { - if (mCursor) { - mCursorNotificationCount++; - } else { - mNotificationCount++; - } - } - - boolean mCursor; - } - @MediumTest public void testSelectionArgs() throws Exception { mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);"); diff --git a/core/tests/coretests/src/android/database/DatabaseLockTest.java b/core/tests/coretests/src/android/database/DatabaseLockTest.java index f7a9f8a..8d3cf5a 100644 --- a/core/tests/coretests/src/android/database/DatabaseLockTest.java +++ b/core/tests/coretests/src/android/database/DatabaseLockTest.java @@ -16,18 +16,13 @@ package android.database; -import android.app.Activity; -import android.content.Context; import android.database.sqlite.SQLiteDatabase; -import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import java.io.File; import java.util.concurrent.atomic.AtomicInteger; import android.test.AndroidTestCase; -import junit.framework.TestCase; - /* * This is a series of unit tests for database locks. * @@ -104,9 +99,9 @@ public class DatabaseLockTest extends AndroidTestCase { public void run() { for (int i = 0; i < NUM_ITERATIONS; i++) { mDatabase.beginTransaction(); - int val = mCounter.incrementAndGet(); + mCounter.incrementAndGet(); try { - Thread.currentThread().sleep(SLEEP_TIME); + Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { // ignore } @@ -124,7 +119,6 @@ public class DatabaseLockTest extends AndroidTestCase { @Suppress public void testLockLatency() { startDatabaseLatencyThread(); - int previous = 0; long sumTime = 0; long maxTime = 0; for (int i = 0; i < NUM_ITERATIONS; i++) { @@ -137,7 +131,7 @@ public class DatabaseLockTest extends AndroidTestCase { } sumTime += elapsedTime; try { - Thread.currentThread().sleep(SLEEP_TIME); + Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { // ignore } @@ -164,7 +158,7 @@ public class DatabaseLockTest extends AndroidTestCase { { mDatabase.beginTransaction(); try { - Thread.currentThread().sleep(SLEEP_TIME); + Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { // ignore } diff --git a/core/tests/coretests/src/android/database/DatabasePerformanceTests.java b/core/tests/coretests/src/android/database/DatabasePerformanceTests.java index b8ebcc4..d0e739b 100644 --- a/core/tests/coretests/src/android/database/DatabasePerformanceTests.java +++ b/core/tests/coretests/src/android/database/DatabasePerformanceTests.java @@ -35,6 +35,7 @@ import java.util.Random; * */ +@SuppressWarnings("deprecation") public class DatabasePerformanceTests { public static String[] children() { diff --git a/core/tests/coretests/src/android/database/DatabaseStatementTest.java b/core/tests/coretests/src/android/database/DatabaseStatementTest.java index 71dc3ae..512d5cd 100644 --- a/core/tests/coretests/src/android/database/DatabaseStatementTest.java +++ b/core/tests/coretests/src/android/database/DatabaseStatementTest.java @@ -25,8 +25,6 @@ import android.database.sqlite.SQLiteStatement; import android.test.AndroidTestCase; import android.test.PerformanceTestCase; import android.test.suitebuilder.annotation.MediumTest; -import android.test.suitebuilder.annotation.SmallTest; -import junit.framework.TestCase; import java.io.File; diff --git a/core/tests/coretests/src/android/database/NewDatabasePerformanceTests.java b/core/tests/coretests/src/android/database/NewDatabasePerformanceTests.java index 0dca90b..adf88d2 100644 --- a/core/tests/coretests/src/android/database/NewDatabasePerformanceTests.java +++ b/core/tests/coretests/src/android/database/NewDatabasePerformanceTests.java @@ -20,7 +20,6 @@ import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.test.PerformanceTestCase; -import junit.framework.Assert; import junit.framework.TestCase; import java.io.File; @@ -33,1202 +32,1196 @@ import java.util.Random; public class NewDatabasePerformanceTests { - // Edit this to change the test run times. The original is 100. - final static int kMultiplier = 1; - - public static class PerformanceBase extends TestCase - implements PerformanceTestCase { - protected static final int CURRENT_DATABASE_VERSION = 42; - protected SQLiteDatabase mDatabase; - protected File mDatabaseFile; - - public void setUp() { - mDatabaseFile = new File("/sdcard", "perf_database_test.db"); - if (mDatabaseFile.exists()) { - mDatabaseFile.delete(); - } - mDatabase = - SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), - null); - assertTrue(mDatabase != null); - mDatabase.setVersion(CURRENT_DATABASE_VERSION); + // Edit this to change the test run times. The original is 100. + final static int kMultiplier = 1; + + public static class PerformanceBase extends TestCase + implements PerformanceTestCase { + protected static final int CURRENT_DATABASE_VERSION = 42; + protected SQLiteDatabase mDatabase; + protected File mDatabaseFile; + + public void setUp() { + mDatabaseFile = new File("/sdcard", "perf_database_test.db"); + if (mDatabaseFile.exists()) { + mDatabaseFile.delete(); + } + mDatabase = + SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), + null); + assertTrue(mDatabase != null); + mDatabase.setVersion(CURRENT_DATABASE_VERSION); + } + + public void tearDown() { + mDatabase.close(); + mDatabaseFile.delete(); + } + + public boolean isPerformanceOnly() { + return true; + } + + // These tests can only be run once. + public int startPerformance(Intermediates intermediates) { + return 0; + } + + public String numberName(int number) { + String result = ""; + + if (number >= 1000) { + result += numberName((number / 1000)) + " thousand"; + number = (number % 1000); + + if (number > 0) result += " "; + } + + if (number >= 100) { + result += ONES[(number / 100)] + " hundred"; + number = (number % 100); + + if (number > 0) result += " "; + } + + if (number >= 20) { + result += TENS[(number / 10)]; + number = (number % 10); + + if (number > 0) result += " "; + } + + if (number > 0) { + result += ONES[number]; + } + + return result; + } } - public void tearDown() { - mDatabase.close(); - mDatabaseFile.delete(); - } - - public boolean isPerformanceOnly() { - return true; - } - - // These tests can only be run once. - public int startPerformance(Intermediates intermediates) { - return 0; - } + /** + * Test 1000 inserts. + */ - public String numberName(int number) { - String result = ""; + public static class Insert1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; - if (number >= 1000) { - result += numberName((number / 1000)) + " thousand"; - number = (number % 1000); + private String[] statements = new String[SIZE]; - if (number > 0) result += " "; - } + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - if (number >= 100) { - result += ONES[(number / 100)] + " hundred"; - number = (number % 100); + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + statements[i] = + "INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"; + } - if (number > 0) result += " "; - } + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + } - if (number >= 20) { - result += TENS[(number / 10)]; - number = (number % 10); - - if (number > 0) result += " "; - } - - if (number > 0) { - result += ONES[number]; - } - - return result; + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.execSQL(statements[i]); + } + } } - } - - /** - * Test 1000 inserts. - */ - public static class Insert1000 extends PerformanceBase { - private static final int SIZE = 10 * kMultiplier; - - private String[] statements = new String[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - statements[i] = - "INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"; - } - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + /** + * Test 1000 inserts into an indexed table. + */ + + public static class InsertIndexed1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + + private String[] statements = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + statements[i] = + "INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"; + } + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1c ON t1(c)"); + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.execSQL(statements[i]); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.execSQL(statements[i]); - } + /** + * 100 SELECTs without an index + */ + + public static class Select100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"count(*)", "avg(b)"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } } - } - - /** - * Test 1000 inserts into an indexed table. - */ - - public static class InsertIndexed1000 extends PerformanceBase { - private static final int SIZE = 10 * kMultiplier; - - private String[] statements = new String[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - statements[i] = - "INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"; - } - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i1c ON t1(c)"); + /** + * 100 SELECTs on a string comparison + */ + + public static class SelectStringComparison100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"count(*)", "avg(b)"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + where[i] = "c LIKE '" + numberName(i) + "'"; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.execSQL(statements[i]); - } + /** + * 100 SELECTs with an index + */ + + public static class SelectIndex100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"count(*)", "avg(b)"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } } - } - /** - * 100 SELECTs without an index - */ - - public static class Select100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"count(*)", "avg(b)"}; - - private String[] where = new String[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - int lower = i * 100; - int upper = (i + 10) * 100; - where[i] = "b >= " + lower + " AND b < " + upper; - } + /** + * INNER JOIN without an index + */ + + public static class InnerJoin100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"t1.a"}; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase + .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + } + + public void testRun() { + mDatabase.query("t1 INNER JOIN t2 ON t1.b = t2.b", COLUMNS, null, + null, null, null, null); + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase - .query("t1", COLUMNS, where[i], null, null, null, null); - } + /** + * INNER JOIN without an index on one side + */ + + public static class InnerJoinOneSide100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"t1.a"}; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase + .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); + + mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + } + + public void testRun() { + mDatabase.query("t1 INNER JOIN t2 ON t1.b = t2.b", COLUMNS, null, + null, null, null, null); + } } - } - - /** - * 100 SELECTs on a string comparison - */ - - public static class SelectStringComparison100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"count(*)", "avg(b)"}; - - private String[] where = new String[SIZE]; - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - where[i] = "c LIKE '" + numberName(i) + "'"; - } + /** + * INNER JOIN without an index on one side + */ + + public static class InnerJoinNoIndex100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"t1.a"}; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase + .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); + + mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + } + + public void testRun() { + mDatabase.query("t1 INNER JOIN t2 ON t1.c = t2.c", COLUMNS, null, + null, null, null, null); + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase - .query("t1", COLUMNS, where[i], null, null, null, null); - } - } - } - - /** - * 100 SELECTs with an index - */ - - public static class SelectIndex100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"count(*)", "avg(b)"}; - - private String[] where = new String[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - int lower = i * 100; - int upper = (i + 10) * 100; - where[i] = "b >= " + lower + " AND b < " + upper; - } + /** + * 100 SELECTs with subqueries. Subquery is using an index + */ + + public static class SelectSubQIndex100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"t1.a"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase + .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); + + mDatabase.execSQL("CREATE INDEX i2b ON t2(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = + "t1.b IN (SELECT t2.b FROM t2 WHERE t2.b >= " + lower + + " AND t2.b < " + upper + ")"; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase - .query("t1", COLUMNS, where[i], null, null, null, null); - } - } - } - - /** - * INNER JOIN without an index - */ - - public static class InnerJoin100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"t1.a"}; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase - .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } + /** + * 100 SELECTs on string comparison with Index + */ + + public static class SelectIndexStringComparison100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"count(*)", "avg(b)"}; + + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i3c ON t1(c)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + where[i] = "c LIKE '" + numberName(i) + "'"; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } } - public void testRun() { - mDatabase.query("t1 INNER JOIN t2 ON t1.b = t2.b", COLUMNS, null, - null, null, null, null); - } - } - - /** - * INNER JOIN without an index on one side - */ - - public static class InnerJoinOneSide100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"t1.a"}; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase - .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); - - mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - } + /** + * 100 SELECTs on integer + */ - public void testRun() { - mDatabase.query("t1 INNER JOIN t2 ON t1.b = t2.b", COLUMNS, null, - null, null, null, null); - } - } - - /** - * INNER JOIN without an index on one side - */ - - public static class InnerJoinNoIndex100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"t1.a"}; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase - .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); - - mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - } + public static class SelectInteger100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"b"}; - public void testRun() { - mDatabase.query("t1 INNER JOIN t2 ON t1.c = t2.c", COLUMNS, null, - null, null, null, null); - } - } - - /** - * 100 SELECTs with subqueries. Subquery is using an index - */ - - public static class SelectSubQIndex100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"t1.a"}; - - private String[] where = new String[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase - .execSQL("CREATE TABLE t2(a INTEGER, b INTEGER, c VARCHAR(100))"); - - mDatabase.execSQL("CREATE INDEX i2b ON t2(b)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t2 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - int lower = i * 100; - int upper = (i + 10) * 100; - where[i] = - "t1.b IN (SELECT t2.b FROM t2 WHERE t2.b >= " + lower - + " AND t2.b < " + upper + ")"; - } - } - - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase - .query("t1", COLUMNS, where[i], null, null, null, null); - } - } - } + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - /** - * 100 SELECTs on string comparison with Index - */ + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - public static class SelectIndexStringComparison100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"count(*)", "avg(b)"}; + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } - private String[] where = new String[SIZE]; + } - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i3c ON t1(c)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - where[i] = "c LIKE '" + numberName(i) + "'"; - } + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t1", COLUMNS, null, null, null, null, null); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase - .query("t1", COLUMNS, where[i], null, null, null, null); - } - } - } + /** + * 100 SELECTs on String + */ - /** - * 100 SELECTs on integer - */ + public static class SelectString100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"c"}; - public static class SelectInteger100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"b"}; + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - private String[] where = new String[SIZE]; + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + } - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - } - - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.query("t1", COLUMNS, null, null, null, null, null); - } + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t1", COLUMNS, null, null, null, null, null); + } + } } - } - /** - * 100 SELECTs on String - */ + /** + * 100 SELECTs on integer with index + */ - public static class SelectString100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"c"}; + public static class SelectIntegerIndex100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"b"}; - private String[] where = new String[SIZE]; + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1b on t1(b)"); - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } + } + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t1", COLUMNS, null, null, null, null, null); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.query("t1", COLUMNS, null, null, null, null, null); - } - } - } + /** + * 100 SELECTs on String with index + */ - /** - * 100 SELECTs on integer with index - */ + public static class SelectIndexString100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"c"}; - public static class SelectIntegerIndex100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"b"}; + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1c ON t1(c)"); - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i1b on t1(b)"); + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } + } + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t1", COLUMNS, null, null, null, null, null); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.query("t1", COLUMNS, null, null, null, null, null); - } - } - } + /** + * 100 SELECTs on String with starts with + */ - /** - * 100 SELECTs on String with index - */ + public static class SelectStringStartsWith100 extends PerformanceBase { + private static final int SIZE = 1 * kMultiplier; + private static final String[] COLUMNS = {"c"}; + private String[] where = new String[SIZE]; - public static class SelectIndexString100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"c"}; + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1c ON t1(c)"); - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i1c ON t1(c)"); + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + where[i] = "c LIKE '" + numberName(r).substring(0, 1) + "*'"; - } + } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.query("t1", COLUMNS, null, null, null, null, null); - } - } - } + } - /** - * 100 SELECTs on String with starts with - */ + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase + .query("t1", COLUMNS, where[i], null, null, null, null); + } + } + } - public static class SelectStringStartsWith100 extends PerformanceBase { - private static final int SIZE = 1 * kMultiplier; - private static final String[] COLUMNS = {"c"}; - private String[] where = new String[SIZE]; + /** + * 1000 Deletes on an indexed table + */ - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); + public static class DeleteIndexed1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i1c ON t1(c)"); + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i3c ON t1(c)"); - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - where[i] = "c LIKE '" + numberName(r).substring(0, 1) + "*'"; + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } - } + } + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.delete("t1", null, null); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase - .query("t1", COLUMNS, where[i], null, null, null, null); - } - } - } + /** + * 1000 Deletes + */ - /** - * 1000 Deletes on an indexed table - */ + public static class Delete1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; - public static class DeleteIndexed1000 extends PerformanceBase { - private static final int SIZE = 10 * kMultiplier; - private static final String[] COLUMNS = {"c"}; + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i3c ON t1(c)"); + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } + } + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.delete("t1", null, null); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.delete("t1", null, null); - } + /** + * 1000 DELETE's without an index with where clause + */ + + public static class DeleteWhere1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.delete("t1", where[i], null); + } + } } - } - - /** - * 1000 Deletes - */ - - public static class Delete1000 extends PerformanceBase { - private static final int SIZE = 10 * kMultiplier; - private static final String[] COLUMNS = {"c"}; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } + /** + * 1000 DELETE's with an index with where clause + */ + + public static class DeleteIndexWhere1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.delete("t1", where[i], null); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.delete("t1", null, null); - } - } - } - - /** - * 1000 DELETE's without an index with where clause - */ - - public static class DeleteWhere1000 extends PerformanceBase { - private static final int SIZE = 10 * kMultiplier; - private String[] where = new String[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - int lower = i * 100; - int upper = (i + 10) * 100; - where[i] = "b >= " + lower + " AND b < " + upper; - } + /** + * 1000 update's with an index with where clause + */ + + public static class UpdateIndexWhere1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + private String[] where = new String[SIZE]; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + ContentValues b = new ContentValues(1); + b.put("b", upper); + mValues[i] = b; + + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.update("t1", mValues[i], where[i], null); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.delete("t1", where[i], null); - } - } - } - - /** - * 1000 DELETE's with an index with where clause - */ - - public static class DeleteIndexWhere1000 extends PerformanceBase { - private static final int SIZE = 10 * kMultiplier; - private String[] where = new String[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - int lower = i * 100; - int upper = (i + 10) * 100; - where[i] = "b >= " + lower + " AND b < " + upper; - } + /** + * 1000 update's without an index with where clause + */ + + public static class UpdateWhere1000 extends PerformanceBase { + private static final int SIZE = 10 * kMultiplier; + private String[] where = new String[SIZE]; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "b >= " + lower + " AND b < " + upper; + ContentValues b = new ContentValues(1); + b.put("b", upper); + mValues[i] = b; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.update("t1", mValues[i], where[i], null); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.delete("t1", where[i], null); - } - } - } - - /** - * 1000 update's with an index with where clause - */ - - public static class UpdateIndexWhere1000 extends PerformanceBase { - private static final int SIZE = 10 * kMultiplier; - private String[] where = new String[SIZE]; - ContentValues[] mValues = new ContentValues[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i1b ON t1(b)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - - int lower = i * 100; - int upper = (i + 10) * 100; - where[i] = "b >= " + lower + " AND b < " + upper; - ContentValues b = new ContentValues(1); - b.put("b", upper); - mValues[i] = b; - - } + /** + * 10000 inserts for an integer + */ + + public static class InsertInteger10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + ContentValues b = new ContentValues(1); + b.put("a", r); + mValues[i] = b; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.insert("t1", null, mValues[i]); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.update("t1", mValues[i], where[i], null); - } - } - } - - /** - * 1000 update's without an index with where clause - */ - - public static class UpdateWhere1000 extends PerformanceBase { - private static final int SIZE = 10 * kMultiplier; - private String[] where = new String[SIZE]; - ContentValues[] mValues = new ContentValues[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER, b INTEGER, c VARCHAR(100))"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t1 VALUES(" + i + "," + r + ",'" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - - int lower = i * 100; - int upper = (i + 10) * 100; - where[i] = "b >= " + lower + " AND b < " + upper; - ContentValues b = new ContentValues(1); - b.put("b", upper); - mValues[i] = b; - } + /** + * 10000 inserts for an integer -indexed table + */ + + public static class InsertIntegerIndex10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a INTEGER)"); + mDatabase.execSQL("CREATE INDEX i1a ON t1(a)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + ContentValues b = new ContentValues(1); + b.put("a", r); + mValues[i] = b; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.insert("t1", null, mValues[i]); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.update("t1", mValues[i], where[i], null); - } - } - } - - /** - * 10000 inserts for an integer - */ - - public static class InsertInteger10000 extends PerformanceBase { - private static final int SIZE = 100 * kMultiplier; - ContentValues[] mValues = new ContentValues[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - ContentValues b = new ContentValues(1); - b.put("a", r); - mValues[i] = b; - } - } - - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.insert("t1", null, mValues[i]); - } - } - } - - /** - * 10000 inserts for an integer -indexed table - */ - - public static class InsertIntegerIndex10000 extends PerformanceBase { - private static final int SIZE = 100 * kMultiplier; - ContentValues[] mValues = new ContentValues[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a INTEGER)"); - mDatabase.execSQL("CREATE INDEX i1a ON t1(a)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - ContentValues b = new ContentValues(1); - b.put("a", r); - mValues[i] = b; - } - } - - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.insert("t1", null, mValues[i]); - } - } - } - - /** - * 10000 inserts for a String - */ - - public static class InsertString10000 extends PerformanceBase { - private static final int SIZE = 100 * kMultiplier; - ContentValues[] mValues = new ContentValues[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a VARCHAR(100))"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - ContentValues b = new ContentValues(1); - b.put("a", numberName(r)); - mValues[i] = b; - } - } - - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.insert("t1", null, mValues[i]); - } - } - } - - /** - * 10000 inserts for a String - indexed table - */ - - public static class InsertStringIndexed10000 extends PerformanceBase { - private static final int SIZE = 100 * kMultiplier; - ContentValues[] mValues = new ContentValues[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t1(a VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i1a ON t1(a)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - ContentValues b = new ContentValues(1); - b.put("a", numberName(r)); - mValues[i] = b; - } + /** + * 10000 inserts for a String + */ + + public static class InsertString10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a VARCHAR(100))"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + ContentValues b = new ContentValues(1); + b.put("a", numberName(r)); + mValues[i] = b; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.insert("t1", null, mValues[i]); + } + } } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.insert("t1", null, mValues[i]); - } + /** + * 10000 inserts for a String - indexed table + */ + + public static class InsertStringIndexed10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + ContentValues[] mValues = new ContentValues[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t1(a VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i1a ON t1(a)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + ContentValues b = new ContentValues(1); + b.put("a", numberName(r)); + mValues[i] = b; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.insert("t1", null, mValues[i]); + } + } } - } - /** - * 10000 selects for a String -starts with - */ + /** + * 10000 selects for a String -starts with + */ - public static class SelectStringStartsWith10000 extends PerformanceBase { - private static final int SIZE = 100 * kMultiplier; - private static final String[] COLUMNS = {"t3.a"}; - private String[] where = new String[SIZE]; + public static class SelectStringStartsWith10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t3.a"}; + private String[] where = new String[SIZE]; - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - mDatabase - .execSQL("CREATE TABLE t3(a VARCHAR(100))"); + mDatabase + .execSQL("CREATE TABLE t3(a VARCHAR(100))"); - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t3 VALUES('" - + numberName(r) + "')"); - } + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t3 VALUES('" + + numberName(r) + "')"); + } - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - where[i] = "a LIKE '" + numberName(r).substring(0, 1) + "*'"; + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + where[i] = "a LIKE '" + numberName(r).substring(0, 1) + "*'"; - } - } + } + } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); - } + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); + } + } } - } - - /** - * 10000 selects for a String - indexed table -starts with - */ - - public static class SelectStringIndexedStartsWith10000 extends - PerformanceBase { - private static final int SIZE = 100 * kMultiplier; - private static final String[] COLUMNS = {"t3.a"}; - private String[] where = new String[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t3(a VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i3a ON t3(a)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t3 VALUES('" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - where[i] = "a LIKE '" + numberName(r).substring(0, 1) + "*'"; - - } - } - - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); - } + + /** + * 10000 selects for a String - indexed table -starts with + */ + + public static class SelectStringIndexedStartsWith10000 extends + PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t3.a"}; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t3(a VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i3a ON t3(a)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t3 VALUES('" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + where[i] = "a LIKE '" + numberName(r).substring(0, 1) + "*'"; + + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); + } + } } - } - - /** - * 10000 selects for an integer - - */ - - public static class SelectInteger10000 extends PerformanceBase { - private static final int SIZE = 100 * kMultiplier; - private static final String[] COLUMNS = {"t4.a"}; - private String[] where = new String[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t4(a INTEGER)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t4 VALUES(" + r + ")"); - int lower = i * 100; - int upper = (i + 10) * 100; - where[i] = "a >= " + lower + " AND a < " + upper; - } - } - - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.query("t4", COLUMNS, where[i], null, null, null, null); - } + + /** + * 10000 selects for an integer - + */ + + public static class SelectInteger10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t4.a"}; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t4(a INTEGER)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t4 VALUES(" + r + ")"); + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "a >= " + lower + " AND a < " + upper; + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t4", COLUMNS, where[i], null, null, null, null); + } + } } - } - /** - * 10000 selects for an integer -indexed table - */ + /** + * 10000 selects for an integer -indexed table + */ - public static class SelectIntegerIndexed10000 extends PerformanceBase { - private static final int SIZE = 100 * kMultiplier; - private static final String[] COLUMNS = {"t4.a"}; - private String[] where = new String[SIZE]; + public static class SelectIntegerIndexed10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t4.a"}; + private String[] where = new String[SIZE]; - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - mDatabase - .execSQL("CREATE TABLE t4(a INTEGER)"); - mDatabase.execSQL("CREATE INDEX i4a ON t4(a)"); + mDatabase + .execSQL("CREATE TABLE t4(a INTEGER)"); + mDatabase.execSQL("CREATE INDEX i4a ON t4(a)"); - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t4 VALUES(" + r + ")"); + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t4 VALUES(" + r + ")"); - int lower = i * 100; - int upper = (i + 10) * 100; - where[i] = "a >= " + lower + " AND a < " + upper; - } + int lower = i * 100; + int upper = (i + 10) * 100; + where[i] = "a >= " + lower + " AND a < " + upper; + } - } + } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.query("t4", COLUMNS, where[i], null, null, null, null); - } + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t4", COLUMNS, where[i], null, null, null, null); + } + } } - } - /** - * 10000 selects for a String - contains 'e' - */ + /** + * 10000 selects for a String - contains 'e' + */ - public static class SelectStringContains10000 extends PerformanceBase { - private static final int SIZE = 100 * kMultiplier; - private static final String[] COLUMNS = {"t3.a"}; - private String[] where = new String[SIZE]; + public static class SelectStringContains10000 extends PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t3.a"}; + private String[] where = new String[SIZE]; - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); - mDatabase - .execSQL("CREATE TABLE t3(a VARCHAR(100))"); + mDatabase + .execSQL("CREATE TABLE t3(a VARCHAR(100))"); - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t3 VALUES('" - + numberName(r) + "')"); - } + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t3 VALUES('" + + numberName(r) + "')"); + } - for (int i = 0; i < SIZE; i++) { - where[i] = "a LIKE '*e*'"; + for (int i = 0; i < SIZE; i++) { + where[i] = "a LIKE '*e*'"; - } - } + } + } - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); - } + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); + } + } } - } - - /** - * 10000 selects for a String - contains 'e'-indexed table - */ - - public static class SelectStringIndexedContains10000 extends - PerformanceBase { - private static final int SIZE = 100 * kMultiplier; - private static final String[] COLUMNS = {"t3.a"}; - private String[] where = new String[SIZE]; - - @Override - public void setUp() { - super.setUp(); - Random random = new Random(42); - - mDatabase - .execSQL("CREATE TABLE t3(a VARCHAR(100))"); - mDatabase.execSQL("CREATE INDEX i3a ON t3(a)"); - - for (int i = 0; i < SIZE; i++) { - int r = random.nextInt(100000); - mDatabase.execSQL("INSERT INTO t3 VALUES('" - + numberName(r) + "')"); - } - - for (int i = 0; i < SIZE; i++) { - where[i] = "a LIKE '*e*'"; - - } - } - - public void testRun() { - for (int i = 0; i < SIZE; i++) { - mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); - } + + /** + * 10000 selects for a String - contains 'e'-indexed table + */ + + public static class SelectStringIndexedContains10000 extends + PerformanceBase { + private static final int SIZE = 100 * kMultiplier; + private static final String[] COLUMNS = {"t3.a"}; + private String[] where = new String[SIZE]; + + @Override + public void setUp() { + super.setUp(); + Random random = new Random(42); + + mDatabase + .execSQL("CREATE TABLE t3(a VARCHAR(100))"); + mDatabase.execSQL("CREATE INDEX i3a ON t3(a)"); + + for (int i = 0; i < SIZE; i++) { + int r = random.nextInt(100000); + mDatabase.execSQL("INSERT INTO t3 VALUES('" + + numberName(r) + "')"); + } + + for (int i = 0; i < SIZE; i++) { + where[i] = "a LIKE '*e*'"; + + } + } + + public void testRun() { + for (int i = 0; i < SIZE; i++) { + mDatabase.query("t3", COLUMNS, where[i], null, null, null, null); + } + } } - } - public static final String[] ONES = - {"zero", "one", "two", "three", "four", "five", "six", "seven", - "eight", "nine", "ten", "eleven", "twelve", "thirteen", - "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", - "nineteen"}; + public static final String[] ONES = + {"zero", "one", "two", "three", "four", "five", "six", "seven", + "eight", "nine", "ten", "eleven", "twelve", "thirteen", + "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", + "nineteen"}; - public static final String[] TENS = - {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", - "seventy", "eighty", "ninety"}; + public static final String[] TENS = + {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", + "seventy", "eighty", "ninety"}; } diff --git a/core/tests/coretests/src/android/database/sqlite/DatabaseConnectionPoolTest.java b/core/tests/coretests/src/android/database/sqlite/DatabaseConnectionPoolTest.java deleted file mode 100644 index 525dd2d..0000000 --- a/core/tests/coretests/src/android/database/sqlite/DatabaseConnectionPoolTest.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (C) 2006 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.database.sqlite; - -import android.content.Context; -import android.database.sqlite.SQLiteDatabaseTest.ClassToTestSqlCompilationAndCaching; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; -import android.util.Log; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; - -public class DatabaseConnectionPoolTest extends AndroidTestCase { - private static final String TAG = "DatabaseConnectionPoolTest"; - - private static final int MAX_CONN = 5; - private static final String TEST_SQL = "select * from test where i = ? AND j = 1"; - private static final String[] TEST_SQLS = new String[] { - TEST_SQL, TEST_SQL + 1, TEST_SQL + 2, TEST_SQL + 3, TEST_SQL + 4 - }; - - private SQLiteDatabase mDatabase; - private File mDatabaseFile; - private DatabaseConnectionPool mTestPool; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - File dbDir = getContext().getDir(this.getClass().getName(), Context.MODE_PRIVATE); - mDatabaseFile = new File(dbDir, "database_test.db"); - if (mDatabaseFile.exists()) { - mDatabaseFile.delete(); - } - mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null); - assertNotNull(mDatabase); - mDatabase.execSQL("create table test (i int, j int);"); - mTestPool = new DatabaseConnectionPool(mDatabase); - assertNotNull(mTestPool); - } - - @Override - protected void tearDown() throws Exception { - mTestPool.close(); - mDatabase.close(); - mDatabaseFile.delete(); - super.tearDown(); - } - - @SmallTest - public void testGetAndRelease() { - mTestPool.setMaxPoolSize(MAX_CONN); - // connections should be lazily created. - assertEquals(0, mTestPool.getSize()); - // MAX pool size should be set to MAX_CONN - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // get a connection - SQLiteDatabase db = mTestPool.get(TEST_SQL); - // pool size should be one - since only one should be allocated for the above get() - assertEquals(1, mTestPool.getSize()); - assertEquals(mDatabase, db.mParentConnObj); - // no free connections should be available - assertEquals(0, mTestPool.getFreePoolSize()); - assertFalse(mTestPool.isDatabaseObjFree(db)); - // release the connection - mTestPool.release(db); - assertEquals(1, mTestPool.getFreePoolSize()); - assertEquals(1, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - assertTrue(mTestPool.isDatabaseObjFree(db)); - // release the same object again and expect IllegalStateException - try { - mTestPool.release(db); - fail("illegalStateException expected"); - } catch (IllegalStateException e ) { - // expected. - } - } - - /** - * get all connections from the pool and ask for one more. - * should get one of the connections already got so far. - */ - @SmallTest - public void testGetAllConnAndOneMore() { - mTestPool.setMaxPoolSize(MAX_CONN); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - ArrayList<SQLiteDatabase> dbObjs = new ArrayList<SQLiteDatabase>(); - for (int i = 0; i < MAX_CONN; i++) { - SQLiteDatabase db = mTestPool.get(TEST_SQL); - assertFalse(dbObjs.contains(db)); - dbObjs.add(db); - assertEquals(mDatabase, db.mParentConnObj); - } - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // pool is maxed out and no free connections. ask for one more connection - SQLiteDatabase db1 = mTestPool.get(TEST_SQL); - // make sure db1 is one of the existing ones - assertTrue(dbObjs.contains(db1)); - // pool size should remain at MAX_CONN - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // release db1 but since it is allocated 2 times, it should still remain 'busy' - mTestPool.release(db1); - assertFalse(mTestPool.isDatabaseObjFree(db1)); - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // release all connections - for (int i = 0; i < MAX_CONN; i++) { - mTestPool.release(dbObjs.get(i)); - } - // all objects in the pool should be freed now - assertEquals(MAX_CONN, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - } - - /** - * same as above except that each connection has different SQL statement associated with it. - */ - @SmallTest - public void testConnRetrievalForPreviouslySeenSql() { - mTestPool.setMaxPoolSize(MAX_CONN); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - - HashMap<String, SQLiteDatabase> dbObjs = new HashMap<String, SQLiteDatabase>(); - for (int i = 0; i < MAX_CONN; i++) { - SQLiteDatabase db = mTestPool.get(TEST_SQLS[i]); - executeSqlOnDatabaseConn(db, TEST_SQLS[i]); - assertFalse(dbObjs.values().contains(db)); - dbObjs.put(TEST_SQLS[i], db); - } - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // pool is maxed out and no free connections. ask for one more connection - // use a previously seen SQL statement - String testSql = TEST_SQLS[MAX_CONN - 1]; - SQLiteDatabase db1 = mTestPool.get(testSql); - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // make sure db1 is one of the existing ones - assertTrue(dbObjs.values().contains(db1)); - assertEquals(db1, dbObjs.get(testSql)); - // do the same again - SQLiteDatabase db2 = mTestPool.get(testSql); - // make sure db1 is one of the existing ones - assertEquals(db2, dbObjs.get(testSql)); - - // pool size should remain at MAX_CONN - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - - // release db1 but since the same connection is allocated 3 times, - // it should still remain 'busy' - mTestPool.release(db1); - assertFalse(mTestPool.isDatabaseObjFree(dbObjs.get(testSql))); - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - - // release db2 but since the same connection is allocated 2 times, - // it should still remain 'busy' - mTestPool.release(db2); - assertFalse(mTestPool.isDatabaseObjFree(dbObjs.get(testSql))); - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - - // release all connections - for (int i = 0; i < MAX_CONN; i++) { - mTestPool.release(dbObjs.get(TEST_SQLS[i])); - } - // all objects in the pool should be freed now - assertEquals(MAX_CONN, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - } - - private void executeSqlOnDatabaseConn(SQLiteDatabase db, String sql) { - // get the given sql be compiled on the given database connection. - // this will help DatabaseConenctionPool figure out if a given SQL statement - // is already cached by a database connection. - ClassToTestSqlCompilationAndCaching c = - ClassToTestSqlCompilationAndCaching.create(db, sql); - c.close(); - } - - /** - * get a connection for a SQL statement 'blah'. (connection_s) - * make sure the pool has at least one free connection even after this get(). - * and get a connection for the same SQL again. - * this connection should be different from connection_s. - * even though there is a connection with the given SQL pre-compiled, since is it not free - * AND since the pool has free connections available, should get a new connection. - */ - @SmallTest - public void testGetConnForTheSameSql() { - mTestPool.setMaxPoolSize(MAX_CONN); - - SQLiteDatabase db = mTestPool.get(TEST_SQL); - executeSqlOnDatabaseConn(db, TEST_SQL); - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(1, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - - assertFalse(mTestPool.isDatabaseObjFree(db)); - - SQLiteDatabase db1 = mTestPool.get(TEST_SQL); - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(2, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - - assertFalse(mTestPool.isDatabaseObjFree(db1)); - assertFalse(db1.equals(db)); - - mTestPool.release(db); - assertEquals(1, mTestPool.getFreePoolSize()); - assertEquals(2, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - - mTestPool.release(db1); - assertEquals(2, mTestPool.getFreePoolSize()); - assertEquals(2, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - } - - /** - * get the same connection N times and release it N times. - * this tests DatabaseConnectionPool.PoolObj.mNumHolders - */ - @SmallTest - public void testGetSameConnNtimesAndReleaseItNtimes() { - mTestPool.setMaxPoolSize(MAX_CONN); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - - HashMap<String, SQLiteDatabase> dbObjs = new HashMap<String, SQLiteDatabase>(); - for (int i = 0; i < MAX_CONN; i++) { - SQLiteDatabase db = mTestPool.get(TEST_SQLS[i]); - executeSqlOnDatabaseConn(db, TEST_SQLS[i]); - assertFalse(dbObjs.values().contains(db)); - dbObjs.put(TEST_SQLS[i], db); - } - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // every connection in the pool should have numHolders = 1 - for (int i = 0; i < MAX_CONN; i ++) { - assertEquals(1, mTestPool.getPool().get(i).getNumHolders()); - } - // pool is maxed out and no free connections. ask for one more connection - // use a previously seen SQL statement - String testSql = TEST_SQLS[MAX_CONN - 1]; - SQLiteDatabase db1 = mTestPool.get(testSql); - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // make sure db1 is one of the existing ones - assertTrue(dbObjs.values().contains(db1)); - assertEquals(db1, dbObjs.get(testSql)); - assertFalse(mTestPool.isDatabaseObjFree(db1)); - DatabaseConnectionPool.PoolObj poolObj = mTestPool.getPool().get(db1.mConnectionNum - 1); - int numHolders = poolObj.getNumHolders(); - assertEquals(2, numHolders); - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // get the same connection N times more - int N = 100; - for (int i = 0; i < N; i++) { - SQLiteDatabase db2 = mTestPool.get(testSql); - assertEquals(db1, db2); - assertFalse(mTestPool.isDatabaseObjFree(db2)); - // numHolders for this object should be now up by 1 - int prev = numHolders; - numHolders = poolObj.getNumHolders(); - assertEquals(prev + 1, numHolders); - } - // release it N times - for (int i = 0; i < N; i++) { - mTestPool.release(db1); - int prev = numHolders; - numHolders = poolObj.getNumHolders(); - assertEquals(prev - 1, numHolders); - assertFalse(mTestPool.isDatabaseObjFree(db1)); - } - // the connection should still have 2 more holders - assertFalse(mTestPool.isDatabaseObjFree(db1)); - assertEquals(2, poolObj.getNumHolders()); - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // release 2 more times - mTestPool.release(db1); - mTestPool.release(db1); - assertEquals(0, poolObj.getNumHolders()); - assertEquals(1, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - assertTrue(mTestPool.isDatabaseObjFree(db1)); - } - - @SmallTest - public void testStressTest() { - mTestPool.setMaxPoolSize(MAX_CONN); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - - HashMap<SQLiteDatabase, Integer> dbMap = new HashMap<SQLiteDatabase, Integer>(); - for (int i = 0; i < MAX_CONN; i++) { - SQLiteDatabase db = mTestPool.get(TEST_SQLS[i]); - assertFalse(dbMap.containsKey(db)); - dbMap.put(db, 1); - executeSqlOnDatabaseConn(db, TEST_SQLS[i]); - } - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // ask for lot more connections but since the pool is maxed out, we should start receiving - // connections that we already got so far - for (int i = MAX_CONN; i < 1000; i++) { - SQLiteDatabase db = mTestPool.get(TEST_SQL + i); - assertTrue(dbMap.containsKey(db)); - int k = dbMap.get(db); - dbMap.put(db, ++k); - } - assertEquals(0, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - // print the distribution of the database connection handles received, should be uniform. - for (SQLiteDatabase d : dbMap.keySet()) { - Log.i(TAG, "connection # " + d.mConnectionNum + ", numHolders: " + dbMap.get(d)); - } - // print the pool info - Log.i(TAG, mTestPool.toString()); - // release all - for (SQLiteDatabase d : dbMap.keySet()) { - int num = dbMap.get(d); - for (int i = 0; i < num; i++) { - mTestPool.release(d); - } - } - assertEquals(MAX_CONN, mTestPool.getFreePoolSize()); - assertEquals(MAX_CONN, mTestPool.getSize()); - assertEquals(MAX_CONN, mTestPool.getMaxPoolSize()); - } -} diff --git a/core/tests/coretests/src/android/database/sqlite/SQLiteCursorTest.java b/core/tests/coretests/src/android/database/sqlite/SQLiteCursorTest.java index f6b1d04..9ccc6e8 100644 --- a/core/tests/coretests/src/android/database/sqlite/SQLiteCursorTest.java +++ b/core/tests/coretests/src/android/database/sqlite/SQLiteCursorTest.java @@ -21,8 +21,6 @@ import android.content.Context; import android.database.Cursor; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.LargeTest; -import android.test.suitebuilder.annotation.SmallTest; -import android.util.Log; import java.io.File; import java.util.HashSet; @@ -54,52 +52,8 @@ public class SQLiteCursorTest extends AndroidTestCase { super.tearDown(); } - @SmallTest - public void testQueryObjReassignment() { - mDatabase.enableWriteAheadLogging(); - // have a few connections in the database connection pool - DatabaseConnectionPool pool = mDatabase.mConnectionPool; - pool.setMaxPoolSize(5); - SQLiteCursor cursor = - (SQLiteCursor) mDatabase.rawQuery("select * from " + TABLE_NAME, null); - assertNotNull(cursor); - // it should use a pooled database connection - SQLiteDatabase db = cursor.getDatabase(); - assertTrue(db.mConnectionNum > 0); - assertFalse(mDatabase.equals(db)); - assertEquals(mDatabase, db.mParentConnObj); - assertTrue(pool.getConnectionList().contains(db)); - assertTrue(db.isOpen()); - // do a requery. cursor should continue to use the above pooled connection - cursor.requery(); - SQLiteDatabase dbAgain = cursor.getDatabase(); - assertEquals(db, dbAgain); - // disable WAL so that the pooled connection held by the above cursor is closed - mDatabase.disableWriteAheadLogging(); - assertFalse(db.isOpen()); - assertNull(mDatabase.mConnectionPool); - // requery - which should make the cursor use mDatabase connection since the pooled - // connection is no longer available - cursor.requery(); - SQLiteDatabase db1 = cursor.getDatabase(); - assertTrue(db1.mConnectionNum == 0); - assertEquals(mDatabase, db1); - assertNull(mDatabase.mConnectionPool); - assertTrue(db1.isOpen()); - assertFalse(mDatabase.equals(db)); - // enable WAL and requery - this time a pooled connection should be used - mDatabase.enableWriteAheadLogging(); - cursor.requery(); - db = cursor.getDatabase(); - assertTrue(db.mConnectionNum > 0); - assertFalse(mDatabase.equals(db)); - assertEquals(mDatabase, db.mParentConnObj); - assertTrue(mDatabase.mConnectionPool.getConnectionList().contains(db)); - assertTrue(db.isOpen()); - } - /** - * this test could take a while to execute. so, designate it as LargetTest + * this test could take a while to execute. so, designate it as LargeTest */ @LargeTest public void testFillWindow() { diff --git a/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java b/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java deleted file mode 100644 index 5ef8d11..0000000 --- a/core/tests/coretests/src/android/database/sqlite/SQLiteDatabaseTest.java +++ /dev/null @@ -1,971 +0,0 @@ -/* - * Copyright (C) 2006 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.database.sqlite; - -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.database.DatabaseErrorHandler; -import android.database.DatabaseUtils; -import android.database.DefaultDatabaseErrorHandler; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteDatabase.CursorFactory; -import android.database.sqlite.SQLiteStatement; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.LargeTest; -import android.test.suitebuilder.annotation.MediumTest; -import android.test.suitebuilder.annotation.SmallTest; -import android.test.suitebuilder.annotation.Suppress; -import android.util.Log; -import android.util.Pair; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -public class SQLiteDatabaseTest extends AndroidTestCase { - private static final String TAG = "DatabaseGeneralTest"; - private static final String TEST_TABLE = "test"; - private static final int CURRENT_DATABASE_VERSION = 42; - private SQLiteDatabase mDatabase; - private File mDatabaseFile; - private static final int INSERT = 1; - private static final int UPDATE = 2; - private static final int DELETE = 3; - private static final String DB_NAME = "database_test.db"; - - @Override - protected void setUp() throws Exception { - super.setUp(); - dbSetUp(); - } - - @Override - protected void tearDown() throws Exception { - dbTeardown(); - super.tearDown(); - } - - private void dbTeardown() throws Exception { - mDatabase.close(); - mDatabaseFile.delete(); - } - - private void dbSetUp() throws Exception { - File dbDir = getContext().getDir(this.getClass().getName(), Context.MODE_PRIVATE); - mDatabaseFile = new File(dbDir, DB_NAME); - if (mDatabaseFile.exists()) { - mDatabaseFile.delete(); - } - mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null, null); - assertNotNull(mDatabase); - mDatabase.setVersion(CURRENT_DATABASE_VERSION); - } - - @SmallTest - public void testEnableWriteAheadLogging() { - mDatabase.disableWriteAheadLogging(); - assertNull(mDatabase.mConnectionPool); - mDatabase.enableWriteAheadLogging(); - DatabaseConnectionPool pool = mDatabase.mConnectionPool; - assertNotNull(pool); - // make the same call again and make sure the pool already setup is not re-created - mDatabase.enableWriteAheadLogging(); - assertEquals(pool, mDatabase.mConnectionPool); - } - - @SmallTest - public void testDisableWriteAheadLogging() { - mDatabase.execSQL("create table test (i int);"); - mDatabase.enableWriteAheadLogging(); - assertNotNull(mDatabase.mConnectionPool); - // get a pooled database connection - SQLiteDatabase db = mDatabase.getDbConnection("select * from test"); - assertNotNull(db); - assertFalse(mDatabase.equals(db)); - assertTrue(db.isOpen()); - // disable WAL - which should close connection pool and all pooled connections - mDatabase.disableWriteAheadLogging(); - assertNull(mDatabase.mConnectionPool); - assertFalse(db.isOpen()); - } - - @SmallTest - public void testCursorsWithClosedDbConnAfterDisableWriteAheadLogging() { - mDatabase.disableWriteAheadLogging(); - mDatabase.beginTransactionNonExclusive(); - mDatabase.execSQL("create table test (i int);"); - mDatabase.execSQL("insert into test values(1);"); - mDatabase.setTransactionSuccessful(); - mDatabase.endTransaction(); - mDatabase.enableWriteAheadLogging(); - assertNotNull(mDatabase.mConnectionPool); - assertEquals(0, mDatabase.mConnectionPool.getSize()); - assertEquals(0, mDatabase.mConnectionPool.getFreePoolSize()); - // get a cursor which should use pooled database connection - Cursor c = mDatabase.rawQuery("select * from test", null); - assertEquals(1, c.getCount()); - assertEquals(1, mDatabase.mConnectionPool.getSize()); - assertEquals(1, mDatabase.mConnectionPool.getFreePoolSize()); - SQLiteDatabase db = mDatabase.mConnectionPool.getConnectionList().get(0); - assertTrue(mDatabase.mConnectionPool.isDatabaseObjFree(db)); - // disable WAL - which should close connection pool and all pooled connections - mDatabase.disableWriteAheadLogging(); - assertNull(mDatabase.mConnectionPool); - assertFalse(db.isOpen()); - // cursor data should still be accessible because it is fetching data from CursorWindow - c.moveToNext(); - assertEquals(1, c.getInt(0)); - c.requery(); - assertEquals(1, c.getCount()); - c.moveToNext(); - assertEquals(1, c.getInt(0)); - c.close(); - } - - /** - * a transaction should be started before a standalone-update/insert/delete statement - */ - @SmallTest - public void testStartXactBeforeUpdateSql() throws InterruptedException { - runTestForStartXactBeforeUpdateSql(INSERT); - runTestForStartXactBeforeUpdateSql(UPDATE); - runTestForStartXactBeforeUpdateSql(DELETE); - } - private void runTestForStartXactBeforeUpdateSql(int stmtType) throws InterruptedException { - createTableAndClearCache(); - - ContentValues values = new ContentValues(); - // make some changes to data in TEST_TABLE - for (int i = 0; i < 5; i++) { - values.put("i", i); - values.put("j", "i" + System.currentTimeMillis()); - mDatabase.insert(TEST_TABLE, null, values); - switch (stmtType) { - case UPDATE: - values.put("j", "u" + System.currentTimeMillis()); - mDatabase.update(TEST_TABLE, values, "i = " + i, null); - break; - case DELETE: - mDatabase.delete(TEST_TABLE, "i = 1", null); - break; - } - } - // do a query. even though query uses a different database connection, - // it should still see the above changes to data because the above standalone - // insert/update/deletes are done in transactions automatically. - String sql = "select count(*) from " + TEST_TABLE; - SQLiteStatement stmt = mDatabase.compileStatement(sql); - final int expectedValue = (stmtType == DELETE) ? 4 : 5; - assertEquals(expectedValue, stmt.simpleQueryForLong()); - stmt.close(); - Cursor c = mDatabase.rawQuery(sql, null); - assertEquals(1, c.getCount()); - c.moveToFirst(); - assertEquals(expectedValue, c.getLong(0)); - c.close(); - - // do 5 more changes in a transaction but do a query before and after the commit - mDatabase.beginTransaction(); - for (int i = 10; i < 15; i++) { - values.put("i", i); - values.put("j", "i" + System.currentTimeMillis()); - mDatabase.insert(TEST_TABLE, null, values); - switch (stmtType) { - case UPDATE: - values.put("j", "u" + System.currentTimeMillis()); - mDatabase.update(TEST_TABLE, values, "i = " + i, null); - break; - case DELETE: - mDatabase.delete(TEST_TABLE, "i = 1", null); - break; - } - } - mDatabase.setTransactionSuccessful(); - // do a query before commit - should still have 5 rows - // this query should run in a different thread to force it to use a different database - // connection - Thread t = new Thread() { - @Override public void run() { - String sql = "select count(*) from " + TEST_TABLE; - SQLiteStatement stmt = getDb().compileStatement(sql); - assertEquals(expectedValue, stmt.simpleQueryForLong()); - stmt.close(); - Cursor c = getDb().rawQuery(sql, null); - assertEquals(1, c.getCount()); - c.moveToFirst(); - assertEquals(expectedValue, c.getLong(0)); - c.close(); - } - }; - t.start(); - // wait until the above thread is done - t.join(); - // commit and then query. should see changes from the transaction - mDatabase.endTransaction(); - stmt = mDatabase.compileStatement(sql); - final int expectedValue2 = (stmtType == DELETE) ? 9 : 10; - assertEquals(expectedValue2, stmt.simpleQueryForLong()); - stmt.close(); - c = mDatabase.rawQuery(sql, null); - assertEquals(1, c.getCount()); - c.moveToFirst(); - assertEquals(expectedValue2, c.getLong(0)); - c.close(); - } - private synchronized SQLiteDatabase getDb() { - return mDatabase; - } - - /** - * Test to ensure that readers are able to read the database data (old versions) - * EVEN WHEN the writer is in a transaction on the same database. - *<p> - * This test starts 1 Writer and 2 Readers and sets up connection pool for readers - * by calling the method {@link SQLiteDatabase#enableWriteAheadLogging()}. - * <p> - * Writer does the following in a tight loop - * <pre> - * begin transaction - * insert into table_1 - * insert into table_2 - * commit - * </pre> - * <p> - * As long a the writer is alive, Readers do the following in a tight loop at the same time - * <pre> - * Reader_K does "select count(*) from table_K" where K = 1 or 2 - * </pre> - * <p> - * The test is run for TIME_TO_RUN_WAL_TEST_FOR sec. - * <p> - * The test is repeated for different connection-pool-sizes (1..3) - * <p> - * And at the end of of each test, the following statistics are printed - * <ul> - * <li>connection-pool-size</li> - * <li>number-of-transactions by writer</li> - * <li>number of reads by reader_K while the writer is IN or NOT-IN xaction</li> - * </ul> - */ - @LargeTest - @Suppress // run this test only if you need to collect the numbers from this test - public void testConcurrencyEffectsOfConnPool() throws Exception { - // run the test with sqlite WAL enable - runConnectionPoolTest(true); - - // run the same test WITHOUT sqlite WAL enabled - runConnectionPoolTest(false); - } - - private void runConnectionPoolTest(boolean useWal) throws Exception { - int M = 3; - StringBuilder[] buff = new StringBuilder[M]; - for (int i = 0; i < M; i++) { - if (useWal) { - // set up connection pool - mDatabase.enableWriteAheadLogging(); - mDatabase.mConnectionPool.setMaxPoolSize(i + 1); - } else { - mDatabase.disableWriteAheadLogging(); - } - mDatabase.execSQL("CREATE TABLE t1 (i int, j int);"); - mDatabase.execSQL("CREATE TABLE t2 (i int, j int);"); - mDatabase.beginTransaction(); - for (int k = 0; k < 5; k++) { - mDatabase.execSQL("insert into t1 values(?,?);", new String[] {k+"", k+""}); - mDatabase.execSQL("insert into t2 values(?,?);", new String[] {k+"", k+""}); - } - mDatabase.setTransactionSuccessful(); - mDatabase.endTransaction(); - - // start a writer - Writer w = new Writer(mDatabase); - - // initialize an array of counters to be passed to the readers - Reader r1 = new Reader(mDatabase, "t1", w, 0); - Reader r2 = new Reader(mDatabase, "t2", w, 1); - w.start(); - r1.start(); - r2.start(); - - // wait for all threads to die - w.join(); - r1.join(); - r2.join(); - - // print the stats - int[][] counts = getCounts(); - buff[i] = new StringBuilder(); - buff[i].append("connpool-size = "); - buff[i].append(i + 1); - buff[i].append(", num xacts by writer = "); - buff[i].append(getNumXacts()); - buff[i].append(", num-reads-in-xact/NOT-in-xact by reader1 = "); - buff[i].append(counts[0][1] + "/" + counts[0][0]); - buff[i].append(", by reader2 = "); - buff[i].append(counts[1][1] + "/" + counts[1][0]); - - Log.i(TAG, "done testing for conn-pool-size of " + (i+1)); - - dbTeardown(); - dbSetUp(); - } - Log.i(TAG, "duration of test " + TIME_TO_RUN_WAL_TEST_FOR + " sec"); - for (int i = 0; i < M; i++) { - Log.i(TAG, buff[i].toString()); - } - } - - private boolean inXact = false; - private int numXacts; - private static final int TIME_TO_RUN_WAL_TEST_FOR = 15; // num sec this test should run - private int[][] counts = new int[2][2]; - - private synchronized boolean inXact() { - return inXact; - } - - private synchronized void setInXactFlag(boolean flag) { - inXact = flag; - } - - private synchronized void setCounts(int readerNum, int[] numReads) { - counts[readerNum][0] = numReads[0]; - counts[readerNum][1] = numReads[1]; - } - - private synchronized int[][] getCounts() { - return counts; - } - - private synchronized void setNumXacts(int num) { - numXacts = num; - } - - private synchronized int getNumXacts() { - return numXacts; - } - - private class Writer extends Thread { - private SQLiteDatabase db = null; - public Writer(SQLiteDatabase db) { - this.db = db; - } - @Override public void run() { - // in a loop, for N sec, do the following - // BEGIN transaction - // insert into table t1, t2 - // Commit - long now = System.currentTimeMillis(); - int k; - for (k = 0;(System.currentTimeMillis() - now) / 1000 < TIME_TO_RUN_WAL_TEST_FOR; k++) { - db.beginTransactionNonExclusive(); - setInXactFlag(true); - for (int i = 0; i < 10; i++) { - db.execSQL("insert into t1 values(?,?);", new String[] {i+"", i+""}); - db.execSQL("insert into t2 values(?,?);", new String[] {i+"", i+""}); - } - db.setTransactionSuccessful(); - setInXactFlag(false); - db.endTransaction(); - } - setNumXacts(k); - } - } - - private class Reader extends Thread { - private SQLiteDatabase db = null; - private String table = null; - private Writer w = null; - private int readerNum; - private int[] numReads = new int[2]; - public Reader(SQLiteDatabase db, String table, Writer w, int readerNum) { - this.db = db; - this.table = table; - this.w = w; - this.readerNum = readerNum; - } - @Override public void run() { - // while the write is alive, in a loop do the query on a table - while (w.isAlive()) { - for (int i = 0; i < 10; i++) { - DatabaseUtils.longForQuery(db, "select count(*) from " + this.table, null); - // update count of reads - numReads[inXact() ? 1 : 0] += 1; - } - } - setCounts(readerNum, numReads); - } - } - - public static class ClassToTestSqlCompilationAndCaching extends SQLiteProgram { - private ClassToTestSqlCompilationAndCaching(SQLiteDatabase db, String sql) { - super(db, sql); - } - public static ClassToTestSqlCompilationAndCaching create(SQLiteDatabase db, String sql) { - db.lock(); - try { - return new ClassToTestSqlCompilationAndCaching(db, sql); - } finally { - db.unlock(); - } - } - } - - @SmallTest - public void testLruCachingOfSqliteCompiledSqlObjs() { - createTableAndClearCache(); - // set cache size - int N = SQLiteDatabase.MAX_SQL_CACHE_SIZE; - mDatabase.setMaxSqlCacheSize(N); - - // do N+1 queries - and when the 0th entry is removed from LRU cache due to the - // insertion of (N+1)th entry, make sure 0th entry is closed - ArrayList<Integer> stmtObjs = new ArrayList<Integer>(); - ArrayList<String> sqlStrings = new ArrayList<String>(); - int stmt0 = 0; - for (int i = 0; i < N+1; i++) { - String s = "insert into test values(" + i + ",?);"; - sqlStrings.add(s); - ClassToTestSqlCompilationAndCaching c = - ClassToTestSqlCompilationAndCaching.create(mDatabase, s); - int n = c.getSqlStatementId(); - stmtObjs.add(i, n); - if (i == 0) { - // save the statementId of this obj. we want to make sure it is thrown out of - // the cache at the end of this test. - stmt0 = n; - } - c.close(); - } - // is 0'th entry out of the cache? it should be in the list of statementIds - // corresponding to the pre-compiled sql statements to be finalized. - assertTrue(mDatabase.getQueuedUpStmtList().contains(stmt0)); - for (int i = 1; i < N+1; i++) { - SQLiteCompiledSql compSql = mDatabase.getCompiledStatementForSql(sqlStrings.get(i)); - assertNotNull(compSql); - assertTrue(stmtObjs.contains(compSql.nStatement)); - } - } - - @MediumTest - public void testDbCloseReleasingAllCachedSql() { - mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, text1 TEXT, text2 TEXT, " + - "num1 INTEGER, num2 INTEGER, image BLOB);"); - final String statement = "DELETE FROM test WHERE _id=?;"; - SQLiteStatement statementDoNotClose = mDatabase.compileStatement(statement); - statementDoNotClose.bindLong(1, 1); - /* do not close statementDoNotClose object. - * That should leave it in SQLiteDatabase.mPrograms. - * mDatabase.close() in tearDown() should release it. - */ - } - - private void createTableAndClearCache() { - mDatabase.disableWriteAheadLogging(); - mDatabase.execSQL("DROP TABLE IF EXISTS " + TEST_TABLE); - mDatabase.execSQL("CREATE TABLE " + TEST_TABLE + " (i int, j int);"); - mDatabase.enableWriteAheadLogging(); - mDatabase.lock(); - // flush the above statement from cache and close all the pending statements to be released - mDatabase.deallocCachedSqlStatements(); - mDatabase.closePendingStatements(); - mDatabase.unlock(); - assertEquals(0, mDatabase.getQueuedUpStmtList().size()); - } - - /** - * test to make sure the statement finalizations are not done right away but - * piggy-backed onto the next sql statement execution on the same database. - */ - @SmallTest - public void testStatementClose() { - createTableAndClearCache(); - // fill up statement cache in mDatabase - int N = SQLiteDatabase.MAX_SQL_CACHE_SIZE; - mDatabase.setMaxSqlCacheSize(N); - SQLiteStatement stmt; - int stmt0Id = 0; - for (int i = 0; i < N; i ++) { - ClassToTestSqlCompilationAndCaching c = - ClassToTestSqlCompilationAndCaching.create(mDatabase, - "insert into test values(" + i + ", ?);"); - // keep track of 0th entry - if (i == 0) { - stmt0Id = c.getSqlStatementId(); - } - c.close(); - } - - // add one more to the cache - and the above 'stmt0Id' should fall out of cache - ClassToTestSqlCompilationAndCaching stmt1 = - ClassToTestSqlCompilationAndCaching.create(mDatabase, - "insert into test values(100, ?);"); - stmt1.close(); - - // the above close() should have queuedUp the statement for finalization - ArrayList<Integer> statementIds = mDatabase.getQueuedUpStmtList(); - assertTrue(statementIds.contains(stmt0Id)); - - // execute something to see if this statement gets finalized - mDatabase.execSQL("delete from test where i = 10;"); - statementIds = mDatabase.getQueuedUpStmtList(); - assertFalse(statementIds.contains(stmt0Id)); - } - - /** - * same as above - except that the statement to be finalized is from Thread # 1. - * and it is eventually finalized in Thread # 2 when it executes a SQL statement. - * @throws InterruptedException - */ - @LargeTest - public void testStatementCloseDiffThread() throws InterruptedException { - createTableAndClearCache(); - final int N = SQLiteDatabase.MAX_SQL_CACHE_SIZE; - mDatabase.setMaxSqlCacheSize(N); - // fill up statement cache in mDatabase in a thread - Thread t1 = new Thread() { - @Override public void run() { - SQLiteStatement stmt; - for (int i = 0; i < N; i++) { - ClassToTestSqlCompilationAndCaching c = - ClassToTestSqlCompilationAndCaching.create(getDb(), - "insert into test values(" + i + ", ?);"); - // keep track of 0th entry - if (i == 0) { - stmt0Id = c.getSqlStatementId(); - } - c.close(); - } - } - }; - t1.start(); - // wait for the thread to finish - t1.join(); - // mDatabase shouldn't have any statements to be released - assertEquals(0, mDatabase.getQueuedUpStmtList().size()); - - // add one more to the cache - and the above 'stmt0Id' should fall out of cache - // just for the heck of it, do it in a separate thread - Thread t2 = new Thread() { - @Override public void run() { - ClassToTestSqlCompilationAndCaching stmt1 = - ClassToTestSqlCompilationAndCaching.create(getDb(), - "insert into test values(100, ?);"); - stmt1.bindLong(1, 1); - stmt1.close(); - } - }; - t2.start(); - t2.join(); - - // close() in the above thread should have queuedUp the stmt0Id for finalization - ArrayList<Integer> statementIds = getDb().getQueuedUpStmtList(); - assertTrue(statementIds.contains(getStmt0Id())); - assertEquals(1, statementIds.size()); - - // execute something to see if this statement gets finalized - // again do it in a separate thread - Thread t3 = new Thread() { - @Override public void run() { - getDb().execSQL("delete from test where i = 10;"); - } - }; - t3.start(); - t3.join(); - - // is the statement finalized? - statementIds = getDb().getQueuedUpStmtList(); - assertFalse(statementIds.contains(getStmt0Id())); - } - - private volatile int stmt0Id = 0; - private synchronized int getStmt0Id() { - return this.stmt0Id; - } - - /** - * same as above - except that the queue of statements to be finalized are finalized - * by database close() operation. - */ - @LargeTest - public void testStatementCloseByDbClose() throws InterruptedException { - createTableAndClearCache(); - // fill up statement cache in mDatabase in a thread - Thread t1 = new Thread() { - @Override public void run() { - int N = SQLiteDatabase.MAX_SQL_CACHE_SIZE; - getDb().setMaxSqlCacheSize(N); - SQLiteStatement stmt; - for (int i = 0; i < N; i ++) { - ClassToTestSqlCompilationAndCaching c = - ClassToTestSqlCompilationAndCaching.create(getDb(), - "insert into test values(" + i + ", ?);"); - // keep track of 0th entry - if (i == 0) { - stmt0Id = c.getSqlStatementId(); - } - c.close(); - } - } - }; - t1.start(); - // wait for the thread to finish - t1.join(); - - // add one more to the cache - and the above 'stmt0Id' should fall out of cache - // just for the heck of it, do it in a separate thread - Thread t2 = new Thread() { - @Override public void run() { - ClassToTestSqlCompilationAndCaching stmt1 = - ClassToTestSqlCompilationAndCaching.create(getDb(), - "insert into test values(100, ?);"); - stmt1.bindLong(1, 1); - stmt1.close(); - } - }; - t2.start(); - t2.join(); - - // close() in the above thread should have queuedUp the statement for finalization - ArrayList<Integer> statementIds = getDb().getQueuedUpStmtList(); - assertTrue(getStmt0Id() > 0); - assertTrue(statementIds.contains(stmt0Id)); - assertEquals(1, statementIds.size()); - - // close the database. everything from mClosedStatementIds in mDatabase - // should be finalized and cleared from the list - // again do it in a separate thread - Thread t3 = new Thread() { - @Override public void run() { - getDb().close(); - } - }; - t3.start(); - t3.join(); - - // check mClosedStatementIds in mDatabase. it should be empty - statementIds = getDb().getQueuedUpStmtList(); - assertEquals(0, statementIds.size()); - } - - /** - * This test tests usage execSQL() to begin transaction works in the following way - * Thread #1 does - * execSQL("begin transaction"); - * insert() - * Thread # 2 - * query() - * Thread#1 ("end transaction") - * Thread # 2 query will execute - because java layer will not have locked the SQLiteDatabase - * object and sqlite will consider this query to be part of the transaction. - * - * but if thread # 1 uses beginTransaction() instead of execSQL() to start transaction, - * then Thread # 2's query will have been blocked by java layer - * until Thread#1 ends transaction. - * - * @throws InterruptedException - */ - @SmallTest - public void testExecSqlToStartAndEndTransaction() throws InterruptedException { - runExecSqlToStartAndEndTransaction("END"); - // same as above, instead now do "COMMIT" or "ROLLBACK" instead of "END" transaction - runExecSqlToStartAndEndTransaction("COMMIT"); - runExecSqlToStartAndEndTransaction("ROLLBACK"); - } - private void runExecSqlToStartAndEndTransaction(String str) throws InterruptedException { - createTableAndClearCache(); - // disable WAL just so queries and updates use the same database connection - mDatabase.disableWriteAheadLogging(); - mDatabase.execSQL("BEGIN transaction"); - // even though mDatabase.beginTransaction() is not called to start transaction, - // mDatabase connection should now be in transaction as a result of - // mDatabase.execSQL("BEGIN transaction") - // but mDatabase.mLock should not be held by any thread - assertTrue(mDatabase.inTransaction()); - assertFalse(mDatabase.isDbLockedByCurrentThread()); - assertFalse(mDatabase.isDbLockedByOtherThreads()); - assertTrue(mDatabase.amIInTransaction()); - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(10, 999);"); - assertTrue(mDatabase.inTransaction()); - assertFalse(mDatabase.isDbLockedByCurrentThread()); - assertFalse(mDatabase.isDbLockedByOtherThreads()); - assertTrue(mDatabase.amIInTransaction()); - Thread t = new Thread() { - @Override public void run() { - assertTrue(mDatabase.amIInTransaction()); - assertEquals(999, DatabaseUtils.longForQuery(getDb(), - "select j from " + TEST_TABLE + " WHERE i = 10", null)); - assertTrue(getDb().inTransaction()); - assertFalse(getDb().isDbLockedByCurrentThread()); - assertFalse(getDb().isDbLockedByOtherThreads()); - assertTrue(mDatabase.amIInTransaction()); - } - }; - t.start(); - t.join(); - assertTrue(mDatabase.amIInTransaction()); - assertTrue(mDatabase.inTransaction()); - assertFalse(mDatabase.isDbLockedByCurrentThread()); - assertFalse(mDatabase.isDbLockedByOtherThreads()); - mDatabase.execSQL(str); - assertFalse(mDatabase.amIInTransaction()); - assertFalse(mDatabase.inTransaction()); - assertFalse(mDatabase.isDbLockedByCurrentThread()); - assertFalse(mDatabase.isDbLockedByOtherThreads()); - } - - /** - * test the following - * http://b/issue?id=2871037 - * Cursor cursor = db.query(...); - * // with WAL enabled, the above uses a pooled database connection - * db.beginTransaction() - * try { - * db.insert(......); - * cursor.requery(); - * // since the cursor uses pooled database connection, the above requery - * // will not return the results that were inserted above since the insert is - * // done using main database connection AND the transaction is not committed yet. - * // fix is to make the above cursor use the main database connection - and NOT - * // the pooled database connection - * db.setTransactionSuccessful() - * } finally { - * db.endTransaction() - * } - * - * @throws InterruptedException - */ - @SmallTest - public void testTransactionAndWalInterplay1() throws InterruptedException { - createTableAndClearCache(); - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(10, 999);"); - String sql = "select * from " + TEST_TABLE; - Cursor c = mDatabase.rawQuery(sql, null); - // should have 1 row in the table - assertEquals(1, c.getCount()); - mDatabase.beginTransactionNonExclusive(); - try { - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(100, 9909);"); - assertEquals(2, DatabaseUtils.longForQuery(mDatabase, - "select count(*) from " + TEST_TABLE, null)); - // requery on the previously opened cursor - // cursor should now use the main database connection and see 2 rows - c.requery(); - assertEquals(2, c.getCount()); - mDatabase.setTransactionSuccessful(); - } finally { - mDatabase.endTransaction(); - } - c.close(); - - // do the same test but now do the requery in a separate thread. - createTableAndClearCache(); - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(10, 999);"); - final Cursor c1 = mDatabase.rawQuery("select count(*) from " + TEST_TABLE, null); - // should have 1 row in the table - assertEquals(1, c1.getCount()); - mDatabase.beginTransactionNonExclusive(); - try { - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(100, 9909);"); - assertEquals(2, DatabaseUtils.longForQuery(mDatabase, - "select count(*) from " + TEST_TABLE, null)); - // query in a different thread. that causes the cursor to use a pooled connection - // and since this thread hasn't committed its changes, the cursor should still see only - // 1 row - Thread t = new Thread() { - @Override public void run() { - c1.requery(); - assertEquals(1, c1.getCount()); - } - }; - t.start(); - t.join(); - // should be 2 rows now - including the the row inserted above - mDatabase.setTransactionSuccessful(); - } finally { - mDatabase.endTransaction(); - } - c1.close(); - } - - /** - * This test is same as {@link #testTransactionAndWalInterplay1()} except the following: - * instead of mDatabase.beginTransactionNonExclusive(), use execSQL("BEGIN transaction") - * and instead of mDatabase.endTransaction(), use execSQL("END"); - */ - @SmallTest - public void testTransactionAndWalInterplay2() throws InterruptedException { - createTableAndClearCache(); - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(10, 999);"); - String sql = "select * from " + TEST_TABLE; - Cursor c = mDatabase.rawQuery(sql, null); - // should have 1 row in the table - assertEquals(1, c.getCount()); - mDatabase.execSQL("BEGIN transaction"); - try { - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(100, 9909);"); - assertEquals(2, DatabaseUtils.longForQuery(mDatabase, - "select count(*) from " + TEST_TABLE, null)); - // requery on the previously opened cursor - // cursor should now use the main database connection and see 2 rows - c.requery(); - assertEquals(2, c.getCount()); - } finally { - mDatabase.execSQL("commit;"); - } - c.close(); - - // do the same test but now do the requery in a separate thread. - createTableAndClearCache(); - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(10, 999);"); - final Cursor c1 = mDatabase.rawQuery("select count(*) from " + TEST_TABLE, null); - // should have 1 row in the table - assertEquals(1, c1.getCount()); - mDatabase.execSQL("BEGIN transaction"); - try { - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(100, 9909);"); - assertEquals(2, DatabaseUtils.longForQuery(mDatabase, - "select count(*) from " + TEST_TABLE, null)); - // query in a different thread. but since the transaction is started using - // execSQ() instead of beginTransaction(), cursor's query is considered part of - // the same transaction - and hence it should see the above inserted row - Thread t = new Thread() { - @Override public void run() { - c1.requery(); - assertEquals(1, c1.getCount()); - } - }; - t.start(); - t.join(); - // should be 2 rows now - including the the row inserted above - } finally { - mDatabase.execSQL("commit"); - } - c1.close(); - } - - /** - * This test is same as {@link #testTransactionAndWalInterplay2()} except the following: - * instead of committing the data, do rollback and make sure the data seen by the query - * within the transaction is now gone. - */ - @SmallTest - public void testTransactionAndWalInterplay3() { - createTableAndClearCache(); - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(10, 999);"); - String sql = "select * from " + TEST_TABLE; - Cursor c = mDatabase.rawQuery(sql, null); - // should have 1 row in the table - assertEquals(1, c.getCount()); - mDatabase.execSQL("BEGIN transaction"); - try { - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(100, 9909);"); - assertEquals(2, DatabaseUtils.longForQuery(mDatabase, - "select count(*) from " + TEST_TABLE, null)); - // requery on the previously opened cursor - // cursor should now use the main database connection and see 2 rows - c.requery(); - assertEquals(2, c.getCount()); - } finally { - // rollback the change - mDatabase.execSQL("rollback;"); - } - // since the change is rolled back, do the same query again and should now find only 1 row - c.requery(); - assertEquals(1, c.getCount()); - assertEquals(1, DatabaseUtils.longForQuery(mDatabase, - "select count(*) from " + TEST_TABLE, null)); - c.close(); - } - - @SmallTest - public void testAttachDb() { - String newDb = "/sdcard/mydata.db"; - File f = new File(newDb); - if (f.exists()) { - f.delete(); - } - assertFalse(f.exists()); - SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(newDb, null); - db.execSQL("create table test1 (i int);"); - db.execSQL("insert into test1 values(1);"); - db.execSQL("insert into test1 values(11);"); - Cursor c = null; - try { - c = db.rawQuery("select * from test1", null); - int count = c.getCount(); - Log.i(TAG, "count: " + count); - assertEquals(2, count); - } finally { - c.close(); - db.close(); - c = null; - } - - mDatabase.execSQL("attach database ? as newDb" , new String[]{newDb}); - Cursor c1 = null; - try { - c1 = mDatabase.rawQuery("select * from newDb.test1", null); - assertEquals(2, c1.getCount()); - } catch (Exception e) { - fail("unexpected exception: " + e.getMessage()); - } finally { - if (c1 != null) { - c1.close(); - } - } - List<Pair<String, String>> dbs = mDatabase.getAttachedDbs(); - for (Pair<String, String> p: dbs) { - Log.i(TAG, "attached dbs: " + p.first + " : " + p.second); - } - assertEquals(2, dbs.size()); - } - - /** - * http://b/issue?id=2943028 - * SQLiteOpenHelper maintains a Singleton even if it is in bad state. - */ - @SmallTest - public void testCloseAndReopen() { - mDatabase.close(); - TestOpenHelper helper = new TestOpenHelper(getContext(), DB_NAME, null, - CURRENT_DATABASE_VERSION, new DefaultDatabaseErrorHandler()); - mDatabase = helper.getWritableDatabase(); - createTableAndClearCache(); - mDatabase.execSQL("INSERT into " + TEST_TABLE + " values(10, 999);"); - Cursor c = mDatabase.query(TEST_TABLE, new String[]{"i", "j"}, null, null, null, null, null); - assertEquals(1, c.getCount()); - c.close(); - mDatabase.close(); - assertFalse(mDatabase.isOpen()); - mDatabase = helper.getReadableDatabase(); - assertTrue(mDatabase.isOpen()); - c = mDatabase.query(TEST_TABLE, new String[]{"i", "j"}, null, null, null, null, null); - assertEquals(1, c.getCount()); - c.close(); - } - private class TestOpenHelper extends SQLiteOpenHelper { - public TestOpenHelper(Context context, String name, CursorFactory factory, int version, - DatabaseErrorHandler errorHandler) { - super(context, name, factory, version, errorHandler); - } - @Override public void onCreate(SQLiteDatabase db) {} - @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {} - } -} diff --git a/core/tests/coretests/src/android/database/sqlite/SQLiteStatementTest.java b/core/tests/coretests/src/android/database/sqlite/SQLiteStatementTest.java deleted file mode 100644 index 955336a..0000000 --- a/core/tests/coretests/src/android/database/sqlite/SQLiteStatementTest.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (C) 2006 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.database.sqlite; - -import android.content.Context; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.LargeTest; -import android.test.suitebuilder.annotation.SmallTest; - -import java.io.File; -import java.util.Random; -import java.util.concurrent.locks.ReentrantLock; - -public class SQLiteStatementTest extends AndroidTestCase { - private SQLiteDatabase mDatabase; - private File mDatabaseFile; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - File dbDir = getContext().getDir(this.getClass().getName(), Context.MODE_PRIVATE); - mDatabaseFile = new File(dbDir, "database_test.db"); - if (mDatabaseFile.exists()) { - mDatabaseFile.delete(); - } - mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null); - assertNotNull(mDatabase); - } - - @Override - protected void tearDown() throws Exception { - mDatabase.close(); - mDatabaseFile.delete(); - super.tearDown(); - } - - /** - * Start 2 threads to repeatedly execute the above SQL statement. - * Even though 2 threads are executing the same SQL, they each should get their own copy of - * prepared SQL statement id and there SHOULD NOT be an error from sqlite or android. - * @throws InterruptedException thrown if the test threads started by this test are interrupted - */ - @LargeTest - public void testUseOfSameSqlStatementBy2Threads() throws InterruptedException { - mDatabase.execSQL("CREATE TABLE test_pstmt (i INTEGER PRIMARY KEY, j text);"); - final String stmt = "SELECT * FROM test_pstmt WHERE i = ?"; - class RunStmtThread extends Thread { - @Override public void run() { - // do it enough times to make sure there are no corner cases going untested - for (int i = 0; i < 1000; i++) { - SQLiteStatement s1 = mDatabase.compileStatement(stmt); - s1.bindLong(1, i); - s1.execute(); - s1.close(); - } - } - } - RunStmtThread t1 = new RunStmtThread(); - t1.start(); - RunStmtThread t2 = new RunStmtThread(); - t2.start(); - while (t1.isAlive() || t2.isAlive()) { - Thread.sleep(10); - } - } - - /** - * A simple test: start 2 threads to repeatedly execute the same {@link SQLiteStatement}. - * The 2 threads take turns to use the {@link SQLiteStatement}; i.e., it is NOT in use - * by both the threads at the same time. - * - * @throws InterruptedException thrown if the test threads started by this test are interrupted - */ - @LargeTest - public void testUseOfSameSqliteStatementBy2Threads() throws InterruptedException { - mDatabase.execSQL("CREATE TABLE test_pstmt (i INTEGER PRIMARY KEY, j text);"); - final String stmt = "SELECT * FROM test_pstmt WHERE i = ?"; - final SQLiteStatement s1 = mDatabase.compileStatement(stmt); - class RunStmtThread extends Thread { - @Override public void run() { - // do it enough times to make sure there are no corner cases going untested - for (int i = 0; i < 1000; i++) { - lock(); - try { - s1.bindLong(1, i); - s1.execute(); - } finally { - unlock(); - } - Thread.yield(); - } - } - } - RunStmtThread t1 = new RunStmtThread(); - t1.start(); - RunStmtThread t2 = new RunStmtThread(); - t2.start(); - while (t1.isAlive() || t2.isAlive()) { - Thread.sleep(10); - } - } - /** Synchronize on this when accessing the SqliteStatemet in the above */ - private final ReentrantLock mLock = new ReentrantLock(true); - private void lock() { - mLock.lock(); - } - private void unlock() { - mLock.unlock(); - } - - /** - * Tests the following: a {@link SQLiteStatement} object should not refer to a - * pre-compiled SQL statement id except in during the period of binding the arguments - * and executing the SQL statement. - */ - @LargeTest - public void testReferenceToPrecompiledStatementId() { - mDatabase.execSQL("create table t (i int, j text);"); - verifyReferenceToPrecompiledStatementId(false); - verifyReferenceToPrecompiledStatementId(true); - - // a small stress test to make sure there are no side effects of - // the acquire & release of pre-compiled statement id by SQLiteStatement object. - for (int i = 0; i < 100; i++) { - verifyReferenceToPrecompiledStatementId(false); - verifyReferenceToPrecompiledStatementId(true); - } - } - - @SuppressWarnings("deprecation") - private void verifyReferenceToPrecompiledStatementId(boolean wal) { - if (wal) { - mDatabase.enableWriteAheadLogging(); - } else { - mDatabase.disableWriteAheadLogging(); - } - // test with INSERT statement - doesn't use connection pool, if WAL is set - SQLiteStatement stmt = mDatabase.compileStatement("insert into t values(?,?);"); - assertEquals(mDatabase.mNativeHandle, stmt.nHandle); - assertEquals(mDatabase, stmt.mDatabase); - // sql statement should not be compiled yet - assertEquals(0, stmt.nStatement); - assertEquals(0, stmt.getSqlStatementId()); - int colValue = new Random().nextInt(); - stmt.bindLong(1, colValue); - // verify that the sql statement is still not compiled - assertEquals(0, stmt.getSqlStatementId()); - // should still be using the mDatabase connection - verify - assertEquals(mDatabase.mNativeHandle, stmt.nHandle); - assertEquals(mDatabase, stmt.mDatabase); - stmt.bindString(2, "blah" + colValue); - // verify that the sql statement is still not compiled - assertEquals(0, stmt.getSqlStatementId()); - assertEquals(mDatabase.mNativeHandle, stmt.nHandle); - assertEquals(mDatabase, stmt.mDatabase); - stmt.executeInsert(); - // now that the statement is executed, pre-compiled statement should be released - assertEquals(0, stmt.nStatement); - assertEquals(0, stmt.getSqlStatementId()); - assertEquals(mDatabase.mNativeHandle, stmt.nHandle); - assertEquals(mDatabase, stmt.mDatabase); - stmt.close(); - // pre-compiled SQL statement should still remain released from this object - assertEquals(0, stmt.nStatement); - assertEquals(0, stmt.getSqlStatementId()); - // but the database handle should still be the same - assertEquals(mDatabase, stmt.mDatabase); - - // test with a SELECT statement - uses connection pool if WAL is set - stmt = mDatabase.compileStatement("select i from t where j=?;"); - // sql statement should not be compiled yet - assertEquals(0, stmt.nStatement); - assertEquals(0, stmt.getSqlStatementId()); - assertEquals(mDatabase.mNativeHandle, stmt.nHandle); - assertEquals(mDatabase, stmt.mDatabase); - stmt.bindString(1, "blah" + colValue); - // verify that the sql statement is still not compiled - assertEquals(0, stmt.nStatement); - assertEquals(0, stmt.getSqlStatementId()); - assertEquals(mDatabase.mNativeHandle, stmt.nHandle); - assertEquals(mDatabase, stmt.mDatabase); - // execute the statement - Long l = stmt.simpleQueryForLong(); - assertEquals(colValue, l.intValue()); - // now that the statement is executed, pre-compiled statement should be released - assertEquals(0, stmt.nStatement); - assertEquals(0, stmt.getSqlStatementId()); - assertEquals(mDatabase.mNativeHandle, stmt.nHandle); - assertEquals(mDatabase, stmt.mDatabase); - stmt.close(); - // pre-compiled SQL statement should still remain released from this object - assertEquals(0, stmt.nStatement); - assertEquals(0, stmt.getSqlStatementId()); - // but the database handle should still remain attached to the statement - assertEquals(mDatabase.mNativeHandle, stmt.nHandle); - assertEquals(mDatabase, stmt.mDatabase); - } -} diff --git a/core/tests/coretests/src/android/database/sqlite/SQLiteUnfinalizedExceptionTest.java b/core/tests/coretests/src/android/database/sqlite/SQLiteUnfinalizedExceptionTest.java deleted file mode 100644 index cd2005d..0000000 --- a/core/tests/coretests/src/android/database/sqlite/SQLiteUnfinalizedExceptionTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2010 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.database.sqlite; - -import android.content.Context; -import android.database.sqlite.SQLiteDatabaseTest.ClassToTestSqlCompilationAndCaching; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import java.io.File; - -public class SQLiteUnfinalizedExceptionTest extends AndroidTestCase { - private SQLiteDatabase mDatabase; - private File mDatabaseFile; - private static final String TABLE_NAME = "testCursor"; - @Override - protected void setUp() throws Exception { - super.setUp(); - - File dbDir = getContext().getDir(this.getClass().getName(), Context.MODE_PRIVATE); - mDatabaseFile = new File(dbDir, "UnfinalizedExceptionTest.db"); - if (mDatabaseFile.exists()) { - mDatabaseFile.delete(); - } - mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null); - assertNotNull(mDatabase); - } - - @Override - protected void tearDown() throws Exception { - mDatabase.close(); - mDatabaseFile.delete(); - super.tearDown(); - } - - @SmallTest - public void testUnfinalizedExceptionNotExcpected() { - mDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " (i int, j int);"); - // the above statement should be in SQLiteDatabase.mPrograms - // and should automatically be finalized when database is closed - mDatabase.lock(); - try { - mDatabase.closeDatabase(); - } finally { - mDatabase.unlock(); - } - } - - @SmallTest - public void testUnfinalizedException() { - mDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " (i int, j int);"); - mDatabase.lock(); - mDatabase.closePendingStatements(); // clears the above from finalizer queue in mdatabase - mDatabase.unlock(); - ClassToTestSqlCompilationAndCaching.create(mDatabase, "select * from " + TABLE_NAME); - // since the above is NOT closed, closing database should fail - mDatabase.lock(); - try { - mDatabase.closeDatabase(); - fail("exception expected"); - } catch (SQLiteUnfinalizedObjectsException e) { - // expected - } finally { - mDatabase.unlock(); - } - } -} diff --git a/core/tests/coretests/src/android/net/NetworkStatsHistoryTest.java b/core/tests/coretests/src/android/net/NetworkStatsHistoryTest.java index 1df763a..b181122 100644 --- a/core/tests/coretests/src/android/net/NetworkStatsHistoryTest.java +++ b/core/tests/coretests/src/android/net/NetworkStatsHistoryTest.java @@ -24,6 +24,8 @@ import static android.net.NetworkStatsHistory.FIELD_TX_BYTES; import static android.net.NetworkStatsHistory.DataStreamUtils.readVarLong; import static android.net.NetworkStatsHistory.DataStreamUtils.writeVarLong; import static android.net.NetworkStatsHistory.Entry.UNKNOWN; +import static android.net.TrafficStats.GB_IN_BYTES; +import static android.net.TrafficStats.MB_IN_BYTES; import static android.text.format.DateUtils.DAY_IN_MILLIS; import static android.text.format.DateUtils.HOUR_IN_MILLIS; import static android.text.format.DateUtils.MINUTE_IN_MILLIS; @@ -50,10 +52,6 @@ public class NetworkStatsHistoryTest extends AndroidTestCase { private static final long TEST_START = 1194220800000L; - private static final long KB_IN_BYTES = 1024; - private static final long MB_IN_BYTES = KB_IN_BYTES * 1024; - private static final long GB_IN_BYTES = MB_IN_BYTES * 1024; - private NetworkStatsHistory stats; @Override diff --git a/core/tests/coretests/src/android/net/SSLTest.java b/core/tests/coretests/src/android/net/SSLTest.java index 810ed0d..27b699d 100644 --- a/core/tests/coretests/src/android/net/SSLTest.java +++ b/core/tests/coretests/src/android/net/SSLTest.java @@ -16,17 +16,16 @@ package android.net; -import android.net.SSLCertificateSocketFactory; import android.test.suitebuilder.annotation.Suppress; -import junit.framework.TestCase; - import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; +import java.util.Arrays; +import junit.framework.TestCase; -//This test relies on network resources. -@Suppress public class SSLTest extends TestCase { + //This test relies on network resources. + @Suppress public void testCertificate() throws Exception { // test www.fortify.net/sslcheck.html Socket ssl = SSLCertificateSocketFactory.getDefault().createSocket("www.fortify.net",443); @@ -49,4 +48,38 @@ public class SSLTest extends TestCase { // System.out.println(new String(b)); } + + public void testStringsToNpnBytes() { + byte[] expected = { + 6, 's', 'p', 'd', 'y', '/', '2', + 8, 'h', 't', 't', 'p', '/', '1', '.', '1', + }; + assertTrue(Arrays.equals(expected, SSLCertificateSocketFactory.toNpnProtocolsList( + new byte[] { 's', 'p', 'd', 'y', '/', '2' }, + new byte[] { 'h', 't', 't', 'p', '/', '1', '.', '1' }))); + } + + public void testStringsToNpnBytesEmptyArray() { + try { + SSLCertificateSocketFactory.toNpnProtocolsList(); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + public void testStringsToNpnBytesEmptyByteArray() { + try { + SSLCertificateSocketFactory.toNpnProtocolsList(new byte[0]); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + public void testStringsToNpnBytesOversizedInput() { + try { + SSLCertificateSocketFactory.toNpnProtocolsList(new byte[256]); + fail(); + } catch (IllegalArgumentException expected) { + } + } } diff --git a/core/tests/coretests/src/android/net/UriTest.java b/core/tests/coretests/src/android/net/UriTest.java index b878aa5..6fb8946 100644 --- a/core/tests/coretests/src/android/net/UriTest.java +++ b/core/tests/coretests/src/android/net/UriTest.java @@ -16,17 +16,15 @@ package android.net; -import android.net.Uri; import android.content.ContentUris; import android.os.Parcel; import android.test.suitebuilder.annotation.SmallTest; -import junit.framework.TestCase; - import java.io.File; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; +import junit.framework.TestCase; public class UriTest extends TestCase { @@ -195,7 +193,7 @@ public class UriTest extends TestCase { Uri b = a.buildUpon().fragment("new").build(); assertEquals("new", b.getFragment()); assertEquals("bar", b.getSchemeSpecificPart()); - assertEquals("foo", b.getScheme()); + assertEquals("foo", b.getScheme()); } @SmallTest @@ -724,7 +722,7 @@ public class UriTest extends TestCase { String value = uri.getQueryParameter("a b"); assertEquals("foo", value); } - + public void testClearQueryParameters() { Uri uri = Uri.parse("http://www.google.com/?a=x&b=y&c=z").buildUpon() .clearQuery().appendQueryParameter("foo", "bar").build(); @@ -748,4 +746,10 @@ public class UriTest extends TestCase { assertEquals(Arrays.asList("a", "", ""), Uri.parse("http://foo/path?abc=a&abc=&abc=").getQueryParameters("abc")); } + + // http://code.google.com/p/android/issues/detail?id=21064 + public void testPlusCharacterInQuery() { + assertEquals("d e", Uri.parse("http://a/b?c=d%20e").getQueryParameter("c")); + assertEquals("d e", Uri.parse("http://a/b?c=d+e").getQueryParameter("c")); + } } diff --git a/core/tests/coretests/src/android/net/http/HttpResponseCacheTest.java b/core/tests/coretests/src/android/net/http/HttpResponseCacheTest.java index 4d65588..9015a6f 100644 --- a/core/tests/coretests/src/android/net/http/HttpResponseCacheTest.java +++ b/core/tests/coretests/src/android/net/http/HttpResponseCacheTest.java @@ -16,6 +16,8 @@ package android.net.http; +import com.google.mockwebserver.MockResponse; +import com.google.mockwebserver.MockWebServer; import java.io.File; import java.net.CacheRequest; import java.net.CacheResponse; @@ -30,6 +32,7 @@ import junit.framework.TestCase; public final class HttpResponseCacheTest extends TestCase { private File cacheDir; + private MockWebServer server = new MockWebServer(); @Override public void setUp() throws Exception { super.setUp(); @@ -39,6 +42,7 @@ public final class HttpResponseCacheTest extends TestCase { @Override protected void tearDown() throws Exception { ResponseCache.setDefault(null); + server.shutdown(); super.tearDown(); } @@ -100,4 +104,32 @@ public final class HttpResponseCacheTest extends TestCase { cache.delete(); assertNull(ResponseCache.getDefault()); } + + /** + * Make sure that statistics tracking are wired all the way through the + * wrapper class. http://code.google.com/p/android/issues/detail?id=25418 + */ + public void testStatisticsTracking() throws Exception { + HttpResponseCache cache = HttpResponseCache.install(cacheDir, 10 * 1024 * 1024); + + server.enqueue(new MockResponse() + .addHeader("Cache-Control: max-age=60") + .setBody("A")); + server.play(); + + URLConnection c1 = server.getUrl("/").openConnection(); + assertEquals('A', c1.getInputStream().read()); + assertEquals(1, cache.getRequestCount()); + assertEquals(1, cache.getNetworkCount()); + assertEquals(0, cache.getHitCount()); + + URLConnection c2 = server.getUrl("/").openConnection(); + assertEquals('A', c2.getInputStream().read()); + + URLConnection c3 = server.getUrl("/").openConnection(); + assertEquals('A', c3.getInputStream().read()); + assertEquals(3, cache.getRequestCount()); + assertEquals(1, cache.getNetworkCount()); + assertEquals(2, cache.getHitCount()); + } } diff --git a/core/tests/coretests/src/android/os/storage/AsecTests.java b/core/tests/coretests/src/android/os/storage/AsecTests.java index 5efbd88..abb8eae 100755 --- a/core/tests/coretests/src/android/os/storage/AsecTests.java +++ b/core/tests/coretests/src/android/os/storage/AsecTests.java @@ -27,20 +27,13 @@ import android.util.Log; import java.io.File; import java.io.FileOutputStream; -import junit.framework.Assert; - public class AsecTests extends AndroidTestCase { + private static final String SECURE_CONTAINER_PREFIX = "com.android.unittests.AsecTests."; private static final boolean localLOGV = true; public static final String TAG="AsecTests"; - void failStr(String errMsg) { - Log.w(TAG, "errMsg="+errMsg); - } - - void failStr(Exception e) { - Log.w(TAG, "e.getMessage="+e.getMessage()); - Log.w(TAG, "e="+e); - } + private static final String FS_FAT = "fat"; + private static final String FS_EXT4 = "ext4"; @Override protected void setUp() throws Exception { @@ -61,7 +54,9 @@ public class AsecTests extends AndroidTestCase { String[] containers = ms.getSecureContainerList(); for (int i = 0; i < containers.length; i++) { - if (containers[i].startsWith("com.android.unittests.AsecTests.")) { + if (containers[i].startsWith(SECURE_CONTAINER_PREFIX)) { + if (localLOGV) + Log.i(TAG, "Cleaning: " + containers[i]); ms.destroySecureContainer(containers[i], true); } } @@ -70,7 +65,7 @@ public class AsecTests extends AndroidTestCase { private boolean containerExists(String localId) throws RemoteException { IMountService ms = getMs(); String[] containers = ms.getSecureContainerList(); - String fullId = "com.android.unittests.AsecTests." + localId; + String fullId = SECURE_CONTAINER_PREFIX + localId; for (int i = 0; i < containers.length; i++) { if (containers[i].equals(fullId)) { @@ -80,50 +75,52 @@ public class AsecTests extends AndroidTestCase { return false; } - private int createContainer(String localId, int size, String key) throws RemoteException { - Assert.assertTrue(isMediaMounted()); - String fullId = "com.android.unittests.AsecTests." + localId; + private int createContainer(String localId, int size, String key, String filesystem, + boolean isExternal) throws Exception { + assertTrue("Media should be mounted", isMediaMounted()); + String fullId = SECURE_CONTAINER_PREFIX + localId; IMountService ms = getMs(); - return ms.createSecureContainer(fullId, size, "fat", key, android.os.Process.myUid()); + return ms.createSecureContainer(fullId, size, filesystem, key, android.os.Process.myUid(), + isExternal); } - private int mountContainer(String localId, String key) throws RemoteException { - Assert.assertTrue(isMediaMounted()); - String fullId = "com.android.unittests.AsecTests." + localId; + private int mountContainer(String localId, String key) throws Exception { + assertTrue("Media should be mounted", isMediaMounted()); + String fullId = SECURE_CONTAINER_PREFIX + localId; IMountService ms = getMs(); return ms.mountSecureContainer(fullId, key, android.os.Process.myUid()); } - private int renameContainer(String localId1, String localId2) throws RemoteException { - Assert.assertTrue(isMediaMounted()); - String fullId1 = "com.android.unittests.AsecTests." + localId1; - String fullId2 = "com.android.unittests.AsecTests." + localId2; + private int renameContainer(String localId1, String localId2) throws Exception { + assertTrue("Media should be mounted", isMediaMounted()); + String fullId1 = SECURE_CONTAINER_PREFIX + localId1; + String fullId2 = SECURE_CONTAINER_PREFIX + localId2; IMountService ms = getMs(); return ms.renameSecureContainer(fullId1, fullId2); } - private int unmountContainer(String localId, boolean force) throws RemoteException { - Assert.assertTrue(isMediaMounted()); - String fullId = "com.android.unittests.AsecTests." + localId; + private int unmountContainer(String localId, boolean force) throws Exception { + assertTrue("Media should be mounted", isMediaMounted()); + String fullId = SECURE_CONTAINER_PREFIX + localId; IMountService ms = getMs(); return ms.unmountSecureContainer(fullId, force); } - private int destroyContainer(String localId, boolean force) throws RemoteException { - Assert.assertTrue(isMediaMounted()); - String fullId = "com.android.unittests.AsecTests." + localId; + private int destroyContainer(String localId, boolean force) throws Exception { + assertTrue("Media should be mounted", isMediaMounted()); + String fullId = SECURE_CONTAINER_PREFIX + localId; IMountService ms = getMs(); return ms.destroySecureContainer(fullId, force); } - private boolean isContainerMounted(String localId) throws RemoteException { - Assert.assertTrue(isMediaMounted()); - String fullId = "com.android.unittests.AsecTests." + localId; + private boolean isContainerMounted(String localId) throws Exception { + assertTrue("Media should be mounted", isMediaMounted()); + String fullId = SECURE_CONTAINER_PREFIX + localId; IMountService ms = getMs(); return ms.isSecureContainerMounted(fullId); @@ -139,248 +136,392 @@ public class AsecTests extends AndroidTestCase { return null; } - private boolean isMediaMounted() { - try { + private boolean isMediaMounted() throws Exception { String mPath = Environment.getExternalStorageDirectory().toString(); String state = getMs().getVolumeState(mPath); return Environment.MEDIA_MOUNTED.equals(state); - } catch (RemoteException e) { - failStr(e); - return false; - } } - public void testCreateContainer() { - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testCreateContainer", 4, "none")); - Assert.assertEquals(true, containerExists("testCreateContainer")); - } catch (Exception e) { - failStr(e); + + /* + * CREATE + */ + + public void test_Fat_External_Create_Success() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateContainer", 4, "none", FS_FAT, true)); + assertTrue(containerExists("testCreateContainer")); } - public void testCreateMinSizeContainer() { - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testCreateContainer", 1, "none")); - Assert.assertEquals(true, containerExists("testCreateContainer")); - } catch (Exception e) { - failStr(e); + public void test_Ext4_External_Create_Success() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateContainer", 4, "none", FS_EXT4, true)); + assertTrue(containerExists("testCreateContainer")); } - public void testCreateZeroSizeContainer() { - try { - Assert.assertEquals(StorageResultCode.OperationFailedInternalError, - createContainer("testCreateZeroContainer", 0, "none")); - } catch (Exception e) { - failStr(e); - } + public void test_Fat_Internal_Create_Success() throws Exception { + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateContainer", 4, "none", FS_FAT, false)); + assertTrue(containerExists("testCreateContainer")); } - public void testCreateDuplicateContainer() { - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testCreateDupContainer", 4, "none")); + public void test_Ext4_Internal_Create_Success() throws Exception { + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateContainer", 4, "none", FS_EXT4, false)); + assertTrue(containerExists("testCreateContainer")); + } - Assert.assertEquals(StorageResultCode.OperationFailedInternalError, - createContainer("testCreateDupContainer", 4, "none")); - } catch (Exception e) { - failStr(e); + + /* + * CREATE MIN SIZE + */ + + public void test_Fat_External_CreateMinSize_Success() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateContainer", 1, "none", FS_FAT, true)); + assertTrue(containerExists("testCreateContainer")); } - public void testDestroyContainer() { - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testDestroyContainer", 4, "none")); - Assert.assertEquals(StorageResultCode.OperationSucceeded, - destroyContainer("testDestroyContainer", false)); - } catch (Exception e) { - failStr(e); + public void test_Ext4_External_CreateMinSize_Success() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateContainer", 1, "none", FS_EXT4, true)); + assertTrue(containerExists("testCreateContainer")); } - public void testMountContainer() { - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testMountContainer", 4, "none")); + public void test_Fat_Internal_CreateMinSize_Success() throws Exception { + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateContainer", 1, "none", FS_FAT, false)); + assertTrue(containerExists("testCreateContainer")); + } - Assert.assertEquals(StorageResultCode.OperationSucceeded, - unmountContainer("testMountContainer", false)); + public void test_Ext4_Internal_CreateMinSize_Success() throws Exception { + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateContainer", 1, "none", FS_EXT4, false)); + assertTrue(containerExists("testCreateContainer")); + } + + + /* + * CREATE ZERO SIZE - FAIL CASE + */ - Assert.assertEquals(StorageResultCode.OperationSucceeded, - mountContainer("testMountContainer", "none")); - } catch (Exception e) { - failStr(e); + public void test_Fat_External_CreateZeroSize_Failure() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationFailedInternalError, + createContainer("testCreateZeroContainer", 0, "none", FS_FAT, true)); } - public void testMountBadKey() { - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testMountBadKey", 4, "00000000000000000000000000000000")); + public void test_Ext4_External_CreateZeroSize_Failure() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; + } + + assertEquals(StorageResultCode.OperationFailedInternalError, + createContainer("testCreateZeroContainer", 0, "none", FS_EXT4, true)); + } - Assert.assertEquals(StorageResultCode.OperationSucceeded, - unmountContainer("testMountBadKey", false)); + public void test_Fat_Internal_CreateZeroSize_Failure() throws Exception { + assertEquals(StorageResultCode.OperationFailedInternalError, + createContainer("testCreateZeroContainer", 0, "none", FS_FAT, false)); + } - Assert.assertEquals(StorageResultCode.OperationFailedInternalError, - mountContainer("testMountContainer", "000000000000000000000000000000001")); + public void test_Ext4_Internal_CreateZeroSize_Failure() throws Exception { + assertEquals(StorageResultCode.OperationFailedInternalError, + createContainer("testCreateZeroContainer", 0, "none", FS_EXT4, false)); + } - Assert.assertEquals(StorageResultCode.OperationFailedInternalError, - mountContainer("testMountContainer", "none")); - } catch (Exception e) { - failStr(e); + + /* + * CREATE DUPLICATE - FAIL CASE + */ + + public void test_Fat_External_CreateDuplicate_Failure() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateDupContainer", 4, "none", FS_FAT, true)); + + assertEquals(StorageResultCode.OperationFailedInternalError, + createContainer("testCreateDupContainer", 4, "none", FS_FAT, true)); } - public void testNonExistPath() { - IMountService ms = getMs(); - try { - String path = ms.getSecureContainerPath("jparks.broke.it"); - failStr(path); - } catch (IllegalArgumentException e) { - } catch (Exception e) { - failStr(e); + public void test_Ext4_External_CreateDuplicate_Failure() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateDupContainer", 4, "none", FS_EXT4, true)); + + assertEquals(StorageResultCode.OperationFailedInternalError, + createContainer("testCreateDupContainer", 4, "none", FS_EXT4, true)); } - public void testUnmountBusyContainer() { - IMountService ms = getMs(); - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testUnmountBusyContainer", 4, "none")); + public void test_Fat_Internal_CreateDuplicate_Failure() throws Exception { + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateDupContainer", 4, "none", FS_FAT, false)); + + assertEquals(StorageResultCode.OperationFailedInternalError, + createContainer("testCreateDupContainer", 4, "none", FS_FAT, false)); + } + + public void test_Ext4_Internal_CreateDuplicate_Failure() throws Exception { + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testCreateDupContainer", 4, "none", FS_EXT4, false)); - String path = ms.getSecureContainerPath("com.android.unittests.AsecTests.testUnmountBusyContainer"); + assertEquals(StorageResultCode.OperationFailedInternalError, + createContainer("testCreateDupContainer", 4, "none", FS_EXT4, false)); + } - File f = new File(path, "reference"); - FileOutputStream fos = new FileOutputStream(f); - Assert.assertEquals(StorageResultCode.OperationFailedStorageBusy, - unmountContainer("testUnmountBusyContainer", false)); + /* + * DESTROY + */ - fos.close(); - Assert.assertEquals(StorageResultCode.OperationSucceeded, - unmountContainer("testUnmountBusyContainer", false)); - } catch (Exception e) { - failStr(e); + public void test_Fat_External_Destroy_Success() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testDestroyContainer", 4, "none", FS_FAT, true)); + assertEquals(StorageResultCode.OperationSucceeded, + destroyContainer("testDestroyContainer", false)); } - public void testDestroyBusyContainer() { - IMountService ms = getMs(); - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testDestroyBusyContainer", 4, "none")); + public void test_Ext4_External_Destroy_Success() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; + } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testDestroyContainer", 4, "none", FS_EXT4, true)); + assertEquals(StorageResultCode.OperationSucceeded, + destroyContainer("testDestroyContainer", false)); + } - String path = ms.getSecureContainerPath("com.android.unittests.AsecTests.testDestroyBusyContainer"); + public void test_Fat_Internal_Destroy_Success() throws Exception { + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testDestroyContainer", 4, "none", FS_FAT, false)); + assertEquals(StorageResultCode.OperationSucceeded, + destroyContainer("testDestroyContainer", false)); + } + + public void test_Ext4_Internal_Destroy_Success() throws Exception { + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testDestroyContainer", 4, "none", FS_EXT4, false)); + assertEquals(StorageResultCode.OperationSucceeded, + destroyContainer("testDestroyContainer", false)); + } - File f = new File(path, "reference"); - FileOutputStream fos = new FileOutputStream(f); - Assert.assertEquals(StorageResultCode.OperationFailedStorageBusy, - destroyContainer("testDestroyBusyContainer", false)); + /* + * MOUNT + */ - fos.close(); - Assert.assertEquals(StorageResultCode.OperationSucceeded, - destroyContainer("testDestroyBusyContainer", false)); - } catch (Exception e) { - failStr(e); + public void test_Fat_External_Mount() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testMountContainer", 4, "none", FS_FAT, true)); + + assertEquals(StorageResultCode.OperationSucceeded, + unmountContainer("testMountContainer", false)); + + assertEquals(StorageResultCode.OperationSucceeded, + mountContainer("testMountContainer", "none")); } - public void testRenameContainer() { - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testRenameContainer.1", 4, "none")); - Assert.assertEquals(StorageResultCode.OperationSucceeded, - unmountContainer("testRenameContainer.1", false)); + /* + * MOUNT BAD KEY - FAIL CASE + */ + + public void test_Fat_External_MountBadKey_Failure() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; + } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testMountBadKey", 4, "00000000000000000000000000000000", FS_FAT, + true)); + + assertEquals(StorageResultCode.OperationSucceeded, + unmountContainer("testMountBadKey", false)); + + assertEquals(StorageResultCode.OperationFailedInternalError, + mountContainer("testMountContainer", "000000000000000000000000000000001")); + + assertEquals(StorageResultCode.OperationFailedInternalError, + mountContainer("testMountContainer", "none")); + } - Assert.assertEquals(StorageResultCode.OperationSucceeded, - renameContainer("testRenameContainer.1", "testRenameContainer.2")); - Assert.assertEquals(false, containerExists("testRenameContainer.1")); - Assert.assertEquals(true, containerExists("testRenameContainer.2")); - } catch (Exception e) { - failStr(e); + public void test_Fat_External_UnmountBusy_Success() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + IMountService ms = getMs(); + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testUnmountBusyContainer", 4, "none", FS_FAT, true)); + + String path = ms.getSecureContainerPath(SECURE_CONTAINER_PREFIX + + "testUnmountBusyContainer"); + + File f = new File(path, "reference"); + FileOutputStream fos = new FileOutputStream(f); + + assertEquals(StorageResultCode.OperationFailedStorageBusy, + unmountContainer("testUnmountBusyContainer", false)); + + fos.close(); + assertEquals(StorageResultCode.OperationSucceeded, + unmountContainer("testUnmountBusyContainer", false)); } - public void testRenameSrcMountedContainer() { - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testRenameContainer.1", 4, "none")); + public void test_Fat_External_DestroyBusy() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; + } + + IMountService ms = getMs(); + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testDestroyBusyContainer", 4, "none", FS_FAT, true)); + + String path = ms.getSecureContainerPath(SECURE_CONTAINER_PREFIX + + "testDestroyBusyContainer"); + + File f = new File(path, "reference"); + FileOutputStream fos = new FileOutputStream(f); + + assertEquals(StorageResultCode.OperationFailedStorageBusy, + destroyContainer("testDestroyBusyContainer", false)); - Assert.assertEquals(StorageResultCode.OperationFailedStorageMounted, - renameContainer("testRenameContainer.1", "testRenameContainer.2")); - } catch (Exception e) { - failStr(e); + fos.close(); + assertEquals(StorageResultCode.OperationSucceeded, + destroyContainer("testDestroyBusyContainer", false)); + } + + public void test_Fat_External_Rename_Success() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testRenameContainer.1", 4, "none", FS_FAT, true)); + + assertEquals(StorageResultCode.OperationSucceeded, + unmountContainer("testRenameContainer.1", false)); + + assertEquals(StorageResultCode.OperationSucceeded, + renameContainer("testRenameContainer.1", "testRenameContainer.2")); + + assertFalse(containerExists("testRenameContainer.1")); + assertTrue(containerExists("testRenameContainer.2")); } - public void testRenameDstMountedContainer() { - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testRenameContainer.1", 4, "none")); + public void test_Fat_External_RenameSrcMounted_Failure() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; + } - Assert.assertEquals(StorageResultCode.OperationSucceeded, - unmountContainer("testRenameContainer.1", false)); + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testRenameContainer.1", 4, "none", FS_FAT, true)); - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testRenameContainer.2", 4, "none")); + assertEquals(StorageResultCode.OperationFailedStorageMounted, + renameContainer("testRenameContainer.1", "testRenameContainer.2")); + } - Assert.assertEquals(StorageResultCode.OperationFailedStorageMounted, - renameContainer("testRenameContainer.1", "testRenameContainer.2")); - } catch (Exception e) { - failStr(e); + public void test_Fat_External_RenameDstMounted_Failure() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; } + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testRenameContainer.1", 4, "none", FS_FAT, true)); + + assertEquals(StorageResultCode.OperationSucceeded, + unmountContainer("testRenameContainer.1", false)); + + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testRenameContainer.2", 4, "none", FS_FAT, true)); + + assertEquals(StorageResultCode.OperationFailedStorageMounted, + renameContainer("testRenameContainer.1", "testRenameContainer.2")); } - public void testContainerSize() { + public void test_Fat_External_Size_Success() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; + } + IMountService ms = getMs(); - try { - Assert.assertEquals(StorageResultCode.OperationSucceeded, - createContainer("testContainerSize", 1, "none")); - String path = ms.getSecureContainerPath("com.android.unittests.AsecTests.testUnmountBusyContainer"); - - byte[] buf = new byte[4096]; - File f = new File(path, "reference"); - FileOutputStream fos = new FileOutputStream(f); - for (int i = 0; i < (1024 * 1024); i+= buf.length) { - fos.write(buf); - } - fos.close(); - } catch (Exception e) { - failStr(e); + assertEquals(StorageResultCode.OperationSucceeded, + createContainer("testContainerSize", 1, "none", FS_FAT, true)); + String path = ms.getSecureContainerPath(SECURE_CONTAINER_PREFIX + "testContainerSize"); + + byte[] buf = new byte[4096]; + File f = new File(path, "reference"); + FileOutputStream fos = new FileOutputStream(f); + for (int i = 0; i < (1024 * 1024); i += buf.length) { + fos.write(buf); } + fos.close(); + } + + public void testGetSecureContainerPath_NonExistPath_Failure() throws Exception { + IMountService ms = getMs(); + assertNull("Getting the path for an invalid container should return null", + ms.getSecureContainerPath("jparks.broke.it")); } /*------------ Tests for unmounting volume ---*/ public final long MAX_WAIT_TIME=120*1000; public final long WAIT_TIME_INCR=20*1000; - boolean getMediaState() { - try { + + boolean getMediaState() throws Exception { String mPath = Environment.getExternalStorageDirectory().toString(); String state = getMs().getVolumeState(mPath); return Environment.MEDIA_MOUNTED.equals(state); - } catch (RemoteException e) { - return false; - } } - boolean mountMedia() { + boolean mountMedia() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return true; + } + if (getMediaState()) { return true; } - try { + String mPath = Environment.getExternalStorageDirectory().toString(); int ret = getMs().mountVolume(mPath); return ret == StorageResultCode.OperationSucceeded; - } catch (RemoteException e) { - return false; - } } class StorageListener extends StorageEventListener { @@ -410,10 +551,15 @@ public class AsecTests extends AndroidTestCase { } } - private boolean unmountMedia() { + private void unmountMedia() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; + } + if (!getMediaState()) { - return true; + return; } + String path = Environment.getExternalStorageDirectory().toString(); StorageListener observer = new StorageListener(); StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE); @@ -428,17 +574,15 @@ public class AsecTests extends AndroidTestCase { waitTime += WAIT_TIME_INCR; } if(!observer.isDone()) { - throw new Exception("Timed out waiting for packageInstalled callback"); + fail("Timed out waiting for packageInstalled callback"); } - return true; } - } catch (Exception e) { - return false; } finally { sm.unregisterListener(observer); } } - public void testUnmount() { + + public void testUnmount() throws Exception { boolean oldStatus = getMediaState(); Log.i(TAG, "oldStatus="+oldStatus); try { @@ -446,7 +590,7 @@ public class AsecTests extends AndroidTestCase { if (!getMediaState()) { mountMedia(); } - assertTrue(unmountMedia()); + unmountMedia(); } finally { // Restore old status boolean currStatus = getMediaState(); @@ -472,7 +616,11 @@ public class AsecTests extends AndroidTestCase { * This test invokes unmount multiple time and expects the call back * to be invoked just once. */ - public void testUnmountMultiple() { + public void testUnmountMultiple() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; + } + boolean oldStatus = getMediaState(); StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE); MultipleStorageLis observer = new MultipleStorageLis(); @@ -494,12 +642,10 @@ public class AsecTests extends AndroidTestCase { waitTime += WAIT_TIME_INCR; } if(!observer.isDone()) { - failStr("Timed out waiting for packageInstalled callback"); + fail("Timed out waiting for packageInstalled callback"); } } assertEquals(observer.count, 1); - } catch (Exception e) { - failStr(e); } finally { sm.unregisterListener(observer); // Restore old status @@ -514,7 +660,7 @@ public class AsecTests extends AndroidTestCase { } } } - + class ShutdownObserver extends IMountShutdownObserver.Stub{ private boolean doneFlag = false; int statusCode; @@ -536,28 +682,26 @@ public class AsecTests extends AndroidTestCase { } - boolean invokeShutdown() { + void invokeShutdown() throws Exception { IMountService ms = getMs(); ShutdownObserver observer = new ShutdownObserver(); synchronized (observer) { - try { - ms.shutdown(observer); - return true; - } catch (RemoteException e) { - failStr(e); - } + ms.shutdown(observer); } - return false; } - public void testShutdown() { + public void testShutdown() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; + } + boolean oldStatus = getMediaState(); try { // Mount media firsts if (!getMediaState()) { mountMedia(); } - assertTrue(invokeShutdown()); + invokeShutdown(); } finally { // Restore old status boolean currStatus = getMediaState(); @@ -576,7 +720,11 @@ public class AsecTests extends AndroidTestCase { * This test invokes unmount multiple time and expects the call back * to be invoked just once. */ - public void testShutdownMultiple() { + public void testShutdownMultiple() throws Exception { + if (Environment.isExternalStorageEmulated()) { + return; + } + boolean oldStatus = getMediaState(); try { // Mount media firsts @@ -586,13 +734,9 @@ public class AsecTests extends AndroidTestCase { IMountService ms = getMs(); ShutdownObserver observer = new ShutdownObserver(); synchronized (observer) { - try { - ms.shutdown(observer); - for (int i = 0; i < 4; i++) { - ms.shutdown(null); - } - } catch (RemoteException e) { - failStr(e); + ms.shutdown(observer); + for (int i = 0; i < 4; i++) { + ms.shutdown(null); } } } finally { diff --git a/core/tests/coretests/src/android/text/DynamicLayoutBlocksTest.java b/core/tests/coretests/src/android/text/DynamicLayoutBlocksTest.java new file mode 100644 index 0000000..2e42e5a --- /dev/null +++ b/core/tests/coretests/src/android/text/DynamicLayoutBlocksTest.java @@ -0,0 +1,327 @@ +/* + * Copyright (C) 2012 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.text; + +import static android.text.Layout.Alignment.*; + +import android.text.DynamicLayout; + +import junit.framework.TestCase; + +/** + * Tests DynamciLayout updateBlocks method. + * + * Requires disabling access checks in the vm since this calls package-private APIs. + * + * @Suppress + */ +public class DynamicLayoutBlocksTest extends TestCase { + private DynamicLayout dl = new DynamicLayout("", new TextPaint(), 0, ALIGN_NORMAL, 0, 0, false); + private static final int ___ = DynamicLayout.INVALID_BLOCK_INDEX; + + private int[] initialBlockEnds; + private int[] initialBlockIndices; + + private void defineInitialState(int[] ends, int[] indices) { + initialBlockEnds = ends; + initialBlockIndices = indices; + assertEquals(initialBlockEnds.length, initialBlockIndices.length); + } + + public void printBlocks(String message) { + System.out.print(message); + for (int i = 0; i < dl.getNumberOfBlocks(); i++) { + System.out.print(" " + Integer.toString(dl.getBlockEndLines()[i])); + } + System.out.println(); + } + + public void checkInvariants() { + assertTrue(dl.getNumberOfBlocks() > 0); + assertTrue(dl.getNumberOfBlocks() <= dl.getBlockEndLines().length); + assertEquals(dl.getBlockEndLines().length, dl.getBlockIndices().length); + + for (int i = 1; i < dl.getNumberOfBlocks(); i++) { + assertTrue(dl.getBlockEndLines()[i] > dl.getBlockEndLines()[i-1]); + } + } + + private void update(int startLine, int endLine, int newLineCount) { + dl.setBlocksDataForTest(initialBlockEnds, initialBlockIndices, initialBlockEnds.length); + checkInvariants(); + dl.updateBlocks(startLine, endLine, newLineCount); + } + + private void assertState(int[] sizes, int[] indices) { + checkInvariants(); + + assertEquals(sizes.length, dl.getNumberOfBlocks()); + assertEquals(indices.length, dl.getNumberOfBlocks()); + + int[] ends = new int[sizes.length]; + for (int i = 0; i < ends.length; i++) { + ends[i] = i == 0 ? (sizes[0] == 0 ? 0 : sizes[0] - 1) : ends[i - 1] + sizes[i]; + } + + for (int i = 0; i < dl.getNumberOfBlocks(); i++) { + assertEquals(ends[i], dl.getBlockEndLines()[i]); + assertEquals(indices[i], dl.getBlockIndices()[i]); + } + } + + private void assertState(int[] sizes) { + int[] ids = new int[sizes.length]; + for (int i = 0; i < sizes.length; i++) { + ids[i] = DynamicLayout.INVALID_BLOCK_INDEX; + } + assertState(sizes, ids); + } + + public void testFrom0() { + defineInitialState( new int[] { 0 }, new int[] { 123 }); + + update(0, 0, 0); + assertState( new int[] { 0 } ); + + update(0, 0, 1); + assertState( new int[] { 0 } ); + + update(0, 0, 10); + assertState( new int[] { 10 } ); + } + + public void testFrom1ReplaceByEmpty() { + defineInitialState( new int[] { 100 }, new int[] { 123 }); + + update(0, 0, 0); + assertState( new int[] { 100 } ); + + update(0, 10, 0); + assertState( new int[] { 90 } ); + + update(0, 100, 0); + assertState( new int[] { 0 } ); + + update(20, 30, 0); + assertState( new int[] { 20, 70 } ); + + update(20, 20, 0); + assertState( new int[] { 20, 80 } ); + + update(40, 100, 0); + assertState( new int[] { 40 } ); + + update(100, 100, 0); + assertState( new int[] { 100 } ); + } + + public void testFrom1ReplaceFromFirstLine() { + defineInitialState( new int[] { 100 }, new int[] { 123 }); + + update(0, 0, 1); + assertState( new int[] { 0, 100 } ); + + update(0, 0, 10); + assertState( new int[] { 10, 100 } ); + + update(0, 30, 31); + assertState( new int[] { 31, 70 } ); + + update(0, 100, 20); + assertState( new int[] { 20 } ); + } + + public void testFrom1ReplaceFromCenter() { + defineInitialState( new int[] { 100 }, new int[] { 123 }); + + update(20, 20, 1); + assertState( new int[] { 20, 1, 80 } ); + + update(20, 20, 10); + assertState( new int[] { 20, 10, 80 } ); + + update(20, 30, 50); + assertState( new int[] { 20, 50, 70 } ); + + update(20, 100, 50); + assertState( new int[] { 20, 50 } ); + } + + public void testFrom1ReplaceFromEnd() { + defineInitialState( new int[] { 100 }, new int[] { 123 }); + + update(100, 100, 0); + assertState( new int[] { 100 } ); + + update(100, 100, 1); + assertState( new int[] { 100, 1 } ); + + update(100, 100, 10); + assertState( new int[] { 100, 10 } ); + } + + public void testFrom2ReplaceFromFirstLine() { + defineInitialState( new int[] { 10, 20 }, new int[] { 123, 456 }); + + update(0, 4, 50); + assertState( new int[] { 50, 10-4, 20-10 }, new int[] { ___, ___, 456 } ); + + update(0, 10, 50); + assertState( new int[] { 50, 20-10 }, new int[] { ___, 456 } ); + + update(0, 15, 50); + assertState( new int[] { 50, 20-15 }, new int[] { ___, ___ } ); + + update(0, 20, 50); + assertState( new int[] { 50 }, new int[] { ___ } ); + } + + public void testFrom2ReplaceFromFirstBlock() { + defineInitialState( new int[] { 10, 20 }, new int[] { 123, 456 }); + + update(3, 7, 50); + assertState( new int[] { 3, 50, 10-7, 20-10 }, new int[] { ___, ___, ___, 456 } ); + + update(3, 10, 50); + assertState( new int[] { 3, 50, 20-10 }, new int[] { ___, ___, 456 } ); + + update(3, 14, 50); + assertState( new int[] { 3, 50, 20-14 }, new int[] { ___, ___, ___ } ); + + update(3, 20, 50); + assertState( new int[] { 3, 50 }, new int[] { ___, ___ } ); + } + + public void testFrom2ReplaceFromBottomBoundary() { + defineInitialState( new int[] { 10, 20 }, new int[] { 123, 456 }); + + update(10, 10, 50); + assertState( new int[] { 10, 50, 20-10 }, new int[] { ___, ___, 456 } ); + + update(10, 14, 50); + assertState( new int[] { 10, 50, 20-14 }, new int[] { ___, ___, ___ } ); + + update(10, 20, 50); + assertState( new int[] { 10, 50 }, new int[] { ___, ___ } ); + } + + public void testFrom2ReplaceFromTopBoundary() { + defineInitialState( new int[] { 10, 20 }, new int[] { 123, 456 }); + + update(11, 11, 50); + assertState( new int[] { 11, 50, 20-11 }, new int[] { 123, ___, ___ } ); + + update(11, 14, 50); + assertState( new int[] { 11, 50, 20-14 }, new int[] { 123, ___, ___ } ); + + update(11, 20, 50); + assertState( new int[] { 11, 50 }, new int[] { 123, ___ } ); + } + + public void testFrom2ReplaceFromSecondBlock() { + defineInitialState( new int[] { 10, 20 }, new int[] { 123, 456 }); + + update(14, 14, 50); + assertState( new int[] { 11, 14-11, 50, 20-14 }, new int[] { 123, ___, ___, ___ } ); + + update(14, 17, 50); + assertState( new int[] { 11, 14-11, 50, 20-17 }, new int[] { 123, ___, ___, ___ } ); + + update(14, 20, 50); + assertState( new int[] { 11, 14-11, 50 }, new int[] { 123, ___, ___ } ); + } + + public void testFrom2RemoveFromFirst() { + defineInitialState( new int[] { 10, 20 }, new int[] { 123, 456 }); + + update(0, 4, 0); + assertState( new int[] { 10-4, 20-10 }, new int[] { ___, 456 } ); + + update(0, 10, 0); + assertState( new int[] { 20-10 }, new int[] { 456 } ); + + update(0, 14, 0); + assertState( new int[] { 20-14 }, new int[] { ___ } ); + + update(0, 20, 0); + assertState( new int[] { 0 }, new int[] { ___ } ); + } + + public void testFrom2RemoveFromFirstBlock() { + defineInitialState( new int[] { 10, 20 }, new int[] { 123, 456 }); + + update(4, 7, 0); + assertState( new int[] { 4, 10-7, 20-10 }, new int[] { ___, ___, 456 } ); + + update(4, 10, 0); + assertState( new int[] { 4, 20-10 }, new int[] { ___, 456 } ); + + update(4, 14, 0); + assertState( new int[] { 4, 20-14 }, new int[] { ___, ___ } ); + + update(4, 20, 0); + assertState( new int[] { 4 }, new int[] { ___ } ); + } + + public void testFrom2RemoveFromSecondBlock() { + defineInitialState( new int[] { 10, 20 }, new int[] { 123, 456 }); + + update(14, 17, 0); + assertState( new int[] { 11, 14-11, 20-17 }, new int[] { 123, ___, ___ } ); + + update(14, 20, 0); + assertState( new int[] { 11, 14-11 }, new int[] { 123, ___ } ); + } + + public void testFrom3ReplaceFromFirstBlock() { + defineInitialState( new int[] { 10, 30, 60 }, new int[] { 123, 456, 789 }); + + update(3, 7, 50); + assertState( new int[] { 3, 50, 10-7, 30-10, 60-30 }, new int[] { ___, ___, ___, 456, 789 } ); + + update(3, 10, 50); + assertState( new int[] { 3, 50, 30-10, 60-30 }, new int[] { ___, ___, 456, 789 } ); + + update(3, 17, 50); + assertState( new int[] { 3, 50, 30-17, 60-30 }, new int[] { ___, ___, ___, 789 } ); + + update(3, 30, 50); + assertState( new int[] { 3, 50, 60-30 }, new int[] { ___, ___, 789 } ); + + update(3, 40, 50); + assertState( new int[] { 3, 50, 60-40 }, new int[] { ___, ___, ___ } ); + + update(3, 60, 50); + assertState( new int[] { 3, 50 }, new int[] { ___, ___ } ); + } + + public void testFrom3ReplaceFromSecondBlock() { + defineInitialState( new int[] { 10, 30, 60 }, new int[] { 123, 456, 789 }); + + update(13, 17, 50); + assertState( new int[] { 11, 2, 50, 30-17, 60-30 }, new int[] { 123, ___, ___, ___, 789 } ); + + update(13, 30, 50); + assertState( new int[] { 11, 2, 50, 60-30 }, new int[] { 123, ___, ___, 789 } ); + + update(13, 40, 50); + assertState( new int[] { 11, 2, 50, 60-40 }, new int[] { 123, ___, ___, ___ } ); + + update(13, 60, 50); + assertState( new int[] { 11, 2, 50 }, new int[] { 123, ___, ___ } ); + } +} diff --git a/core/tests/coretests/src/android/util/InternalSelectionView.java b/core/tests/coretests/src/android/util/InternalSelectionView.java index babf38d..a0fb0f1 100644 --- a/core/tests/coretests/src/android/util/InternalSelectionView.java +++ b/core/tests/coretests/src/android/util/InternalSelectionView.java @@ -36,6 +36,11 @@ import android.util.AttributeSet; * entire width of the view. The height of the view is divided evenly among * the rows. * + * Note: If the height of the view does not divide exactly to the number of rows, + * the last row's height is inflated with the remainder. For example, if the + * view height is 22 and there are two rows, the height of the first row is + * 10 and the second 22. + * * Notice what this view does to be a good citizen w.r.t its internal selection: * 1) calls {@link View#requestRectangleOnScreen} each time the selection changes due to * internal navigation. @@ -138,9 +143,6 @@ public class InternalSelectionView extends View { @Override protected void onDraw(Canvas canvas) { - - int rowHeight = getRowHeight(); - int rectTop = mPaddingTop; int rectLeft = mPaddingLeft; int rectRight = getWidth() - mPaddingRight; @@ -149,6 +151,8 @@ public class InternalSelectionView extends View { mPainter.setColor(Color.BLACK); mPainter.setAlpha(0x20); + int rowHeight = getRowHeight(i); + // draw background rect mTempRect.set(rectLeft, rectTop, rectRight, rectTop + rowHeight); canvas.drawRect(mTempRect, mPainter); @@ -178,12 +182,19 @@ public class InternalSelectionView extends View { } } - private int getRowHeight() { - return (getHeight() - mPaddingTop - mPaddingBottom) / mNumRows; + private int getRowHeight(int row) { + final int availableHeight = getHeight() - mPaddingTop - mPaddingBottom; + final int desiredRowHeight = availableHeight / mNumRows; + if (row < mNumRows - 1) { + return desiredRowHeight; + } else { + final int residualHeight = availableHeight % mNumRows; + return desiredRowHeight + residualHeight; + } } public void getRectForRow(Rect rect, int row) { - final int rowHeight = getRowHeight(); + final int rowHeight = getRowHeight(row); final int top = mPaddingTop + row * rowHeight; rect.set(mPaddingLeft, top, @@ -197,10 +208,7 @@ public class InternalSelectionView extends View { requestRectangleOnScreen(mTempRect); } - - /* (non-Javadoc) - * @see android.view.KeyEvent.Callback#onKeyDown(int, android.view.KeyEvent) - */ + @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch(event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_UP: diff --git a/core/tests/coretests/src/android/util/ListScenario.java b/core/tests/coretests/src/android/util/ListScenario.java index 22be4e7..fa088a3 100644 --- a/core/tests/coretests/src/android/util/ListScenario.java +++ b/core/tests/coretests/src/android/util/ListScenario.java @@ -590,7 +590,7 @@ public abstract class ListScenario extends Activity { } /** - * Return an the number of types created by the adapter. Override if your + * Return the number of types created by the adapter. Override if your * adapter creates more than one type. */ public int getViewTypeCount() { diff --git a/core/tests/coretests/src/android/util/LocaleUtilTest.java b/core/tests/coretests/src/android/util/LocaleUtilTest.java deleted file mode 100644 index ff3d539..0000000 --- a/core/tests/coretests/src/android/util/LocaleUtilTest.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright (C) 2007 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.util; - -import java.util.Locale; - -import android.test.AndroidTestCase; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - -import static android.util.LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE; - -public class LocaleUtilTest extends AndroidTestCase { - - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "getLayoutDirectionFromLocale", - args = {Locale.class} - ) - public void testGetLayoutDirectionFromLocale() { - assertEquals(TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(null)); - - assertEquals(TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.ENGLISH)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.CANADA)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.CANADA_FRENCH)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.FRANCE)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.FRENCH)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.GERMAN)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.GERMANY)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.ITALIAN)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.ITALY)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.UK)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.US)); - - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.ROOT)); - - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.CHINA)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.CHINESE)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.JAPAN)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.JAPANESE)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.KOREA)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.KOREAN)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.PRC)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.SIMPLIFIED_CHINESE)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.TAIWAN)); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(Locale.TRADITIONAL_CHINESE)); - - Locale locale = new Locale("ar"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "AE"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "BH"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "DZ"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "EG"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "IQ"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "JO"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "KW"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "LB"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "LY"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "MA"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "OM"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "QA"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "SA"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "SD"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "SY"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "TN"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ar", "YE"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - - locale = new Locale("fa"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("fa", "AF"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("fa", "IR"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - - locale = new Locale("iw"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("iw", "IL"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("he"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("he", "IL"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - - locale = new Locale("pa_Arab"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("pa_Arab", "PK"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - - locale = new Locale("ps"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ps", "AF"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - - locale = new Locale("ur"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ur", "IN"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("ur", "PK"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - - locale = new Locale("uz_Arab"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - locale = new Locale("uz_Arab", "AF"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - - // Locale without a real language - locale = new Locale("zz"); - assertEquals(LocaleUtil.TEXT_LAYOUT_DIRECTION_LTR_DO_NOT_USE, - LocaleUtil.getLayoutDirectionFromLocale(locale)); - } -} diff --git a/core/tests/coretests/src/android/view/GravityTest.java b/core/tests/coretests/src/android/view/GravityTest.java deleted file mode 100644 index d8ef650..0000000 --- a/core/tests/coretests/src/android/view/GravityTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2011 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.view; - -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -public class GravityTest extends AndroidTestCase { - - @SmallTest - public void testGetAbsoluteGravity() throws Exception { - assertOneGravity(Gravity.LEFT, Gravity.LEFT, false); - assertOneGravity(Gravity.LEFT, Gravity.LEFT, true); - - assertOneGravity(Gravity.RIGHT, Gravity.RIGHT, false); - assertOneGravity(Gravity.RIGHT, Gravity.RIGHT, true); - - assertOneGravity(Gravity.TOP, Gravity.TOP, false); - assertOneGravity(Gravity.TOP, Gravity.TOP, true); - - assertOneGravity(Gravity.BOTTOM, Gravity.BOTTOM, false); - assertOneGravity(Gravity.BOTTOM, Gravity.BOTTOM, true); - - assertOneGravity(Gravity.CENTER_VERTICAL, Gravity.CENTER_VERTICAL, false); - assertOneGravity(Gravity.CENTER_VERTICAL, Gravity.CENTER_VERTICAL, true); - - assertOneGravity(Gravity.CENTER_HORIZONTAL, Gravity.CENTER_HORIZONTAL, false); - assertOneGravity(Gravity.CENTER_HORIZONTAL, Gravity.CENTER_HORIZONTAL, true); - - assertOneGravity(Gravity.CENTER, Gravity.CENTER, false); - assertOneGravity(Gravity.CENTER, Gravity.CENTER, true); - - assertOneGravity(Gravity.FILL_VERTICAL, Gravity.FILL_VERTICAL, false); - assertOneGravity(Gravity.FILL_VERTICAL, Gravity.FILL_VERTICAL, true); - - assertOneGravity(Gravity.FILL_HORIZONTAL, Gravity.FILL_HORIZONTAL, false); - assertOneGravity(Gravity.FILL_HORIZONTAL, Gravity.FILL_HORIZONTAL, true); - - assertOneGravity(Gravity.FILL, Gravity.FILL, false); - assertOneGravity(Gravity.FILL, Gravity.FILL, true); - - assertOneGravity(Gravity.CLIP_HORIZONTAL, Gravity.CLIP_HORIZONTAL, false); - assertOneGravity(Gravity.CLIP_HORIZONTAL, Gravity.CLIP_HORIZONTAL, true); - - assertOneGravity(Gravity.CLIP_VERTICAL, Gravity.CLIP_VERTICAL, false); - assertOneGravity(Gravity.CLIP_VERTICAL, Gravity.CLIP_VERTICAL, true); - - assertOneGravity(Gravity.LEFT, Gravity.START, false); - assertOneGravity(Gravity.RIGHT, Gravity.START, true); - - assertOneGravity(Gravity.RIGHT, Gravity.END, false); - assertOneGravity(Gravity.LEFT, Gravity.END, true); - } - - private void assertOneGravity(int expected, int initial, boolean isRtl) { - final int layoutDirection = isRtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR; - - assertEquals(expected, Gravity.getAbsoluteGravity(initial, layoutDirection)); - } -} diff --git a/core/tests/coretests/src/android/view/ViewAttachTest.java b/core/tests/coretests/src/android/view/ViewAttachTest.java index cff66e4..a73f5a6 100644 --- a/core/tests/coretests/src/android/view/ViewAttachTest.java +++ b/core/tests/coretests/src/android/view/ViewAttachTest.java @@ -29,12 +29,12 @@ public class ViewAttachTest extends /** * Make sure that onAttachedToWindow and onDetachedToWindow is called in the - * correct order The ViewAttachTestActivity contains a view that will throw - * an RuntimeException if onDetachedToWindow and onAttachedToWindow is + * correct order. The ViewAttachTestActivity contains a view that will throw + * a RuntimeException if onDetachedToWindow and onAttachedToWindow are * called in the wrong order. * * 1. Initiate the activity 2. Perform a series of orientation changes to - * the activity (this will force the View hierarchy to be rebuild, + * the activity (this will force the View hierarchy to be rebuilt, * generating onAttachedToWindow and onDetachedToWindow) * * Expected result: No RuntimeException is thrown from the TestView in diff --git a/core/tests/coretests/src/android/webkit/ZoomManagerTest.java b/core/tests/coretests/src/android/webkit/ZoomManagerTest.java index 1c9defe..7e0e0b2 100644 --- a/core/tests/coretests/src/android/webkit/ZoomManagerTest.java +++ b/core/tests/coretests/src/android/webkit/ZoomManagerTest.java @@ -24,8 +24,9 @@ public class ZoomManagerTest extends AndroidTestCase { @Override public void setUp() { WebView webView = new WebView(this.getContext()); - CallbackProxy callbackProxy = new CallbackProxy(this.getContext(), webView); - zoomManager = new ZoomManager(webView, callbackProxy); + WebViewClassic webViewClassic = WebViewClassic.fromWebView(webView); + CallbackProxy callbackProxy = new CallbackProxy(this.getContext(), webViewClassic); + zoomManager = new ZoomManager(webViewClassic, callbackProxy); zoomManager.init(1.00f); } diff --git a/core/tests/coretests/src/android/widget/TextViewTest.java b/core/tests/coretests/src/android/widget/TextViewTest.java index 5f65faf..af6df1a 100644 --- a/core/tests/coretests/src/android/widget/TextViewTest.java +++ b/core/tests/coretests/src/android/widget/TextViewTest.java @@ -16,25 +16,18 @@ package android.widget; -import android.test.ActivityInstrumentationTestCase2; +import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; import android.text.GetChars; -import android.view.View; - -import com.android.frameworks.coretests.R; /** * TextViewTest tests {@link TextView}. */ -public class TextViewTest extends ActivityInstrumentationTestCase2<TextViewTestActivity> { - - public TextViewTest() { - super(TextViewTestActivity.class); - } +public class TextViewTest extends AndroidTestCase { @SmallTest public void testArray() throws Exception { - TextView tv = new TextView(getActivity()); + TextView tv = new TextView(mContext); char[] c = new char[] { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!' }; @@ -61,158 +54,4 @@ public class TextViewTest extends ActivityInstrumentationTestCase2<TextViewTestA assertEquals('o', c2[4]); assertEquals('\0', c2[5]); } - - @SmallTest - public void testTextDirectionDefault() { - TextView tv = new TextView(getActivity()); - assertEquals(View.TEXT_DIRECTION_INHERIT, tv.getTextDirection()); - } - - @SmallTest - public void testSetGetTextDirection() { - TextView tv = new TextView(getActivity()); - - tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG); - assertEquals(View.TEXT_DIRECTION_FIRST_STRONG, tv.getTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_ANY_RTL); - assertEquals(View.TEXT_DIRECTION_ANY_RTL, tv.getTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_INHERIT); - assertEquals(View.TEXT_DIRECTION_INHERIT, tv.getTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_LTR); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_RTL); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getTextDirection()); - } - - @SmallTest - public void testGetResolvedTextDirectionLtr() { - TextView tv = new TextView(getActivity()); - tv.setText("this is a test"); - - tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_ANY_RTL); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_INHERIT); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_LTR); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_RTL); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - } - - @SmallTest - public void testGetResolvedTextDirectionLtrWithInheritance() { - LinearLayout ll = new LinearLayout(getActivity()); - ll.setTextDirection(View.TEXT_DIRECTION_RTL); - - TextView tv = new TextView(getActivity()); - tv.setText("this is a test"); - ll.addView(tv); - - tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_ANY_RTL); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_INHERIT); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_LTR); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_RTL); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - } - - @SmallTest - public void testGetResolvedTextDirectionRtl() { - TextView tv = new TextView(getActivity()); - tv.setText("\u05DD\u05DE"); // hebrew - - tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_ANY_RTL); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_INHERIT); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_LTR); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_RTL); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - } - - @SmallTest - public void testGetResolvedTextDirectionRtlWithInheritance() { - LinearLayout ll = new LinearLayout(getActivity()); - - TextView tv = new TextView(getActivity()); - tv.setText("\u05DD\u05DE"); // hebrew - ll.addView(tv); - - tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_ANY_RTL); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_INHERIT); - assertEquals(View.TEXT_DIRECTION_FIRST_STRONG, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_LTR); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_RTL); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - - // Force to RTL text direction on the layout - ll.setTextDirection(View.TEXT_DIRECTION_RTL); - - tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_ANY_RTL); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_INHERIT); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_LTR); - assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection()); - - tv.setTextDirection(View.TEXT_DIRECTION_RTL); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - } - - @SmallTest - public void testResetTextDirection() { - final TextViewTestActivity activity = getActivity(); - - final LinearLayout ll = (LinearLayout) activity.findViewById(R.id.textviewtest_layout); - final TextView tv = (TextView) activity.findViewById(R.id.textviewtest_textview); - - getActivity().runOnUiThread(new Runnable() { - public void run() { - ll.setTextDirection(View.TEXT_DIRECTION_RTL); - tv.setTextDirection(View.TEXT_DIRECTION_INHERIT); - assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection()); - - ll.removeView(tv); - assertEquals(View.TEXT_DIRECTION_FIRST_STRONG, tv.getResolvedTextDirection()); - } - }); - } } diff --git a/core/tests/coretests/src/android/widget/TextViewTestActivity.java b/core/tests/coretests/src/android/widget/TextViewTestActivity.java deleted file mode 100644 index 1bb4d24..0000000 --- a/core/tests/coretests/src/android/widget/TextViewTestActivity.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2011 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.widget; - -import android.app.Activity; -import android.os.Bundle; - -import com.android.frameworks.coretests.R; - -public class TextViewTestActivity extends Activity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.textview_test); - } -} diff --git a/core/tests/coretests/src/android/widget/focus/ListOfButtonsTest.java b/core/tests/coretests/src/android/widget/focus/ListOfButtonsTest.java index 3dba4e5..1968a32 100644 --- a/core/tests/coretests/src/android/widget/focus/ListOfButtonsTest.java +++ b/core/tests/coretests/src/android/widget/focus/ListOfButtonsTest.java @@ -19,7 +19,7 @@ package android.widget.focus; import android.widget.focus.ListOfButtons; import com.android.frameworks.coretests.R; -import android.test.ActivityInstrumentationTestCase; +import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.MediumTest; import android.widget.ListAdapter; import android.widget.Button; @@ -31,7 +31,7 @@ import android.view.View; * Tests that focus works as expected when navigating into and out of * a {@link ListView} that has buttons in it. */ -public class ListOfButtonsTest extends ActivityInstrumentationTestCase<ListOfButtons> { +public class ListOfButtonsTest extends ActivityInstrumentationTestCase2<ListOfButtons> { private ListAdapter mListAdapter; private Button mButtonAtTop; @@ -39,7 +39,7 @@ public class ListOfButtonsTest extends ActivityInstrumentationTestCase<ListOfBut private ListView mListView; public ListOfButtonsTest() { - super("com.android.frameworks.coretests", ListOfButtons.class); + super(ListOfButtons.class); } @Override @@ -47,6 +47,7 @@ public class ListOfButtonsTest extends ActivityInstrumentationTestCase<ListOfBut super.setUp(); ListOfButtons a = getActivity(); + getInstrumentation().waitForIdleSync(); mListAdapter = a.getListAdapter(); mButtonAtTop = (Button) a.findViewById(R.id.button); mListView = a.getListView(); diff --git a/core/tests/coretests/src/android/widget/focus/ListOfInternalSelectionViews.java b/core/tests/coretests/src/android/widget/focus/ListOfInternalSelectionViews.java index 6518341..53b866c 100644 --- a/core/tests/coretests/src/android/widget/focus/ListOfInternalSelectionViews.java +++ b/core/tests/coretests/src/android/widget/focus/ListOfInternalSelectionViews.java @@ -17,6 +17,7 @@ package android.widget.focus; import android.app.Activity; +import android.graphics.Point; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; @@ -110,7 +111,10 @@ public class ListOfInternalSelectionViews extends Activity { @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); - mScreenHeight = getWindowManager().getDefaultDisplay().getHeight(); + + Point size = new Point(); + getWindowManager().getDefaultDisplay().getSize(size); + mScreenHeight = size.y; Bundle extras = getIntent().getExtras(); if (extras != null) { diff --git a/core/tests/coretests/src/android/widget/focus/RequestFocus.java b/core/tests/coretests/src/android/widget/focus/RequestFocus.java index af9ee17..21d762a 100644 --- a/core/tests/coretests/src/android/widget/focus/RequestFocus.java +++ b/core/tests/coretests/src/android/widget/focus/RequestFocus.java @@ -21,9 +21,7 @@ import com.android.frameworks.coretests.R; import android.app.Activity; import android.os.Bundle; import android.os.Handler; -import android.widget.LinearLayout; import android.widget.Button; -import android.view.View; /** * Exercises cases where elements of the UI are requestFocus()ed. diff --git a/core/tests/coretests/src/android/widget/focus/RequestFocusTest.java b/core/tests/coretests/src/android/widget/focus/RequestFocusTest.java index 909a8c9..f2eba23 100644 --- a/core/tests/coretests/src/android/widget/focus/RequestFocusTest.java +++ b/core/tests/coretests/src/android/widget/focus/RequestFocusTest.java @@ -16,21 +16,28 @@ package android.widget.focus; -import android.widget.focus.RequestFocus; -import com.android.frameworks.coretests.R; +import static com.google.testing.littlemock.LittleMock.inOrder; +import static com.google.testing.littlemock.LittleMock.mock; import android.os.Handler; -import android.test.ActivityInstrumentationTestCase; +import android.test.ActivityInstrumentationTestCase2; +import android.test.UiThreadTest; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; -import android.widget.Button; import android.util.AndroidRuntimeException; +import android.view.View; +import android.view.View.OnFocusChangeListener; +import android.view.ViewTreeObserver.OnGlobalFocusChangeListener; +import android.widget.Button; + +import com.android.frameworks.coretests.R; +import com.google.testing.littlemock.LittleMock.InOrder; /** * {@link RequestFocusTest} is set up to exercise cases where the views that * have focus become invisible or GONE. */ -public class RequestFocusTest extends ActivityInstrumentationTestCase<RequestFocus> { +public class RequestFocusTest extends ActivityInstrumentationTestCase2<RequestFocus> { private Button mTopLeftButton; private Button mBottomLeftButton; @@ -39,7 +46,7 @@ public class RequestFocusTest extends ActivityInstrumentationTestCase<RequestFoc private Handler mHandler; public RequestFocusTest() { - super("com.android.frameworks.coretests", RequestFocus.class); + super(RequestFocus.class); } @Override @@ -90,8 +97,94 @@ public class RequestFocusTest extends ActivityInstrumentationTestCase<RequestFoc fail("requestFocus from wrong thread should raise exception."); } catch (AndroidRuntimeException e) { // Expected. The actual exception is not public, so we can't catch it. - assertEquals("android.view.ViewAncestor$CalledFromWrongThreadException", + assertEquals("android.view.ViewRootImpl$CalledFromWrongThreadException", e.getClass().getName()); } } + + /** + * This tests checks the case in which the first focusable View clears focus. + * In such a case the framework tries to give the focus to another View starting + * from the top. Hence, the framework will try to give focus to the view that + * wants to clear its focus. + * + * @throws Exception If an error occurs. + */ + @UiThreadTest + public void testOnFocusChangeCallbackOrderWhenClearingFocusOfFirstFocusable() + throws Exception { + // Get the first focusable. + Button clearingFocusButton = mTopLeftButton; + Button gainingFocusButton = mTopLeftButton; + + // Make sure that the clearing focus View is the first focusable. + View focusCandidate = clearingFocusButton.getRootView().getParent().focusSearch(null, + View.FOCUS_FORWARD); + assertSame("The clearing focus button is the first focusable.", + clearingFocusButton, focusCandidate); + assertSame("The gaining focus button is the first focusable.", + gainingFocusButton, focusCandidate); + + // Focus the clearing focus button. + clearingFocusButton.requestFocus(); + assertTrue(clearingFocusButton.hasFocus()); + + // Register the invocation order checker. + CombinedListeners mock = mock(CombinedListeners.class); + clearingFocusButton.setOnFocusChangeListener(mock); + gainingFocusButton.setOnFocusChangeListener(mock); + clearingFocusButton.getViewTreeObserver().addOnGlobalFocusChangeListener(mock); + + // Try to clear focus. + clearingFocusButton.clearFocus(); + + // Check that no callback was invoked since focus did not move. + InOrder inOrder = inOrder(mock); + inOrder.verify(mock).onFocusChange(clearingFocusButton, false); + inOrder.verify(mock).onGlobalFocusChanged(clearingFocusButton, gainingFocusButton); + inOrder.verify(mock).onFocusChange(gainingFocusButton, true); + } + + public interface CombinedListeners extends OnFocusChangeListener, OnGlobalFocusChangeListener {} + + /** + * This tests check whether the on focus change callbacks are invoked in + * the proper order when a View loses focus and the framework gives it to + * the fist focusable one. + * + * @throws Exception + */ + @UiThreadTest + public void testOnFocusChangeCallbackOrderWhenClearingFocusOfNotFirstFocusable() + throws Exception { + Button clearingFocusButton = mTopRightButton; + Button gainingFocusButton = mTopLeftButton; + + // Make sure that the clearing focus View is not the first focusable. + View focusCandidate = clearingFocusButton.getRootView().getParent().focusSearch(null, + View.FOCUS_FORWARD); + assertNotSame("The clearing focus button is not the first focusable.", + clearingFocusButton, focusCandidate); + assertSame("The gaining focus button is the first focusable.", + gainingFocusButton, focusCandidate); + + // Focus the clearing focus button. + clearingFocusButton.requestFocus(); + assertTrue(clearingFocusButton.hasFocus()); + + // Register the invocation order checker. + CombinedListeners mock = mock(CombinedListeners.class); + clearingFocusButton.setOnFocusChangeListener(mock); + gainingFocusButton.setOnFocusChangeListener(mock); + clearingFocusButton.getViewTreeObserver().addOnGlobalFocusChangeListener(mock); + + // Try to clear focus. + clearingFocusButton.clearFocus(); + + // Check that no callback was invoked since focus did not move. + InOrder inOrder = inOrder(mock); + inOrder.verify(mock).onFocusChange(clearingFocusButton, false); + inOrder.verify(mock).onGlobalFocusChanged(clearingFocusButton, gainingFocusButton); + inOrder.verify(mock).onFocusChange(gainingFocusButton, true); + } } diff --git a/core/tests/coretests/src/android/widget/focus/ScrollingThroughListOfFocusablesTest.java b/core/tests/coretests/src/android/widget/focus/ScrollingThroughListOfFocusablesTest.java index eb9192a..795e09c 100644 --- a/core/tests/coretests/src/android/widget/focus/ScrollingThroughListOfFocusablesTest.java +++ b/core/tests/coretests/src/android/widget/focus/ScrollingThroughListOfFocusablesTest.java @@ -20,10 +20,9 @@ import android.graphics.Rect; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; +import android.util.InternalSelectionView; import android.view.KeyEvent; import android.widget.ListView; -import android.widget.focus.ListOfInternalSelectionViews; -import android.util.InternalSelectionView; /** @@ -51,6 +50,10 @@ public class ScrollingThroughListOfFocusablesTest extends InstrumentationTestCas mNumRowsPerItem, // 5 internally selectable rows per item mScreenHeightFactor)); // each item is 5 / 4 screen height tall mListView = mActivity.getListView(); + // Make sure we have some fading edge regardless of ListView style. + mListView.setVerticalFadingEdgeEnabled(true); + mListView.setFadingEdgeLength(10); + ensureNotInTouchMode(); } @Override @@ -67,12 +70,12 @@ public class ScrollingThroughListOfFocusablesTest extends InstrumentationTestCas assertEquals(mNumRowsPerItem, mActivity.getNumRowsPerItem()); } - // TODO: needs to be adjusted to pass on non-HVGA displays - // @MediumTest + @MediumTest public void testScrollingDownInFirstItem() throws Exception { for (int i = 0; i < mNumRowsPerItem; i++) { assertEquals(0, mListView.getSelectedItemPosition()); + InternalSelectionView view = mActivity.getSelectedView(); assertInternallySelectedRowOnScreen(view, i); @@ -90,13 +93,12 @@ public class ScrollingThroughListOfFocusablesTest extends InstrumentationTestCas mListView.getSelectedView(); // 1 pixel tolerance in case height / 4 is not an even number - final int fadingEdge = mListView.getBottom() - mListView.getVerticalFadingEdgeLength(); + final int bottomFadingEdgeTop = + mListView.getBottom() - mListView.getVerticalFadingEdgeLength(); assertTrue("bottom of view should be just above fading edge", - view.getBottom() >= fadingEdge - 1 && - view.getBottom() <= fadingEdge); + view.getBottom() == bottomFadingEdgeTop); } - // make sure fading edge is the expected view { assertEquals("should be a second view visible due to the fading edge", @@ -109,7 +111,6 @@ public class ScrollingThroughListOfFocusablesTest extends InstrumentationTestCas } } - @MediumTest public void testScrollingToSecondItem() throws Exception { @@ -223,4 +224,12 @@ public class ScrollingThroughListOfFocusablesTest extends InstrumentationTestCas assertTrue("bottom of row " + row + " should be on sreen", mTempRect.bottom < mActivity.getScreenHeight()); } + + private void ensureNotInTouchMode() { + // If in touch mode inject a DPAD down event to exit that mode. + if (mListView.isInTouchMode()) { + sendKeys(KeyEvent.KEYCODE_DPAD_DOWN); + getInstrumentation().waitForIdleSync(); + } + } } diff --git a/core/tests/coretests/src/com/android/internal/net/DNParserTest.java b/core/tests/coretests/src/com/android/internal/net/DNParserTest.java deleted file mode 100644 index 9b490a3..0000000 --- a/core/tests/coretests/src/com/android/internal/net/DNParserTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2010 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.internal.net; - -import com.android.internal.net.DNParser; - -import javax.security.auth.x500.X500Principal; - -import junit.framework.TestCase; - -public class DNParserTest extends TestCase { - public void testFind() { - checkFind("", "cn", null); - checkFind("ou=xxx", "cn", null); - checkFind("ou=xxx,cn=xxx", "cn", "xxx"); - checkFind("ou=xxx+cn=yyy,cn=zzz+cn=abc", "cn", "yyy"); - checkFind("2.5.4.3=a,ou=xxx", "cn", "a"); // OID - checkFind("cn=a,cn=b", "cn", "a"); - checkFind("ou=Cc,ou=Bb,ou=Aa", "ou", "Cc"); - checkFind("cn=imap.gmail.com", "cn", "imap.gmail.com"); - - // Quoted string (see http://www.ietf.org/rfc/rfc2253.txt) - checkFind("o=\"\\\" a ,=<>#;\"", "o", "\" a ,=<>#;"); - checkFind("o=abc\\,def", "o", "abc,def"); - - // UTF-8 (example in rfc 2253) - checkFind("cn=Lu\\C4\\8Di\\C4\\87", "cn", "\u004c\u0075\u010d\u0069\u0107"); - - // whitespaces - checkFind("ou=a, o= a b ,cn=x", "o", "a b"); - checkFind("o=\" a b \" ,cn=x", "o", " a b "); - } - - private void checkFind(String dn, String attrType, String expected) { - String actual = new DNParser(new X500Principal(dn)).find(attrType); - assertEquals("dn:" + dn + " attr:" + attrType, expected, actual); - } -} diff --git a/core/tests/coretests/src/com/android/internal/net/DomainNameValidatorTest.java b/core/tests/coretests/src/com/android/internal/net/DomainNameValidatorTest.java deleted file mode 100644 index f0d581e..0000000 --- a/core/tests/coretests/src/com/android/internal/net/DomainNameValidatorTest.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Copyright (C) 2010 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.internal.net; - -import com.android.internal.net.DomainNameValidator; -import com.android.frameworks.coretests.R; -import com.android.frameworks.coretests.R.raw; - -import android.test.AndroidTestCase; - -import java.io.InputStream; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.PublicKey; -import java.security.SignatureException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateFactory; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import javax.security.auth.x500.X500Principal; - -public class DomainNameValidatorTest extends AndroidTestCase { - private static final int ALT_UNKNOWN = 0; - private static final int ALT_DNS_NAME = 2; - private static final int ALT_IPA_NAME = 7; - - /** - * Tests {@link DomainNameValidator#match}, using a simple {@link X509Certificate} - * implementation. - */ - public void testMatch() { - checkMatch("11", new StubX509Certificate("cn=imap.g.com"), "imap.g.com", true); - checkMatch("12", new StubX509Certificate("cn=imap2.g.com"), "imap.g.com", false); - checkMatch("13", new StubX509Certificate("cn=sub.imap.g.com"), "imap.g.com", false); - - // If a subjectAltName extension of type dNSName is present, that MUST - // be used as the identity - checkMatch("21", new StubX509Certificate("") - .addSubjectAlternativeName(ALT_DNS_NAME, "a.y.com") - , "imap.g.com", false); - checkMatch("22", new StubX509Certificate("cn=imap.g.com") // This cn should be ignored - .addSubjectAlternativeName(ALT_DNS_NAME, "a.y.com") - , "imap.g.com", false); - checkMatch("23", new StubX509Certificate("") - .addSubjectAlternativeName(ALT_DNS_NAME, "imap.g.com") - , "imap.g.com", true); - - // With wildcards - checkMatch("24", new StubX509Certificate("") - .addSubjectAlternativeName(ALT_DNS_NAME, "*.g.com") - , "imap.g.com", true); - - // host name is ip address - checkMatch("31", new StubX509Certificate("") - .addSubjectAlternativeName(ALT_IPA_NAME, "1.2.3.4") - , "1.2.3.4", true); - checkMatch("32", new StubX509Certificate("") - .addSubjectAlternativeName(ALT_IPA_NAME, "1.2.3.4") - , "1.2.3.5", false); - checkMatch("32", new StubX509Certificate("") - .addSubjectAlternativeName(ALT_IPA_NAME, "1.2.3.4") - .addSubjectAlternativeName(ALT_IPA_NAME, "192.168.100.1") - , "192.168.100.1", true); - - // Has unknown subject alternative names - checkMatch("41", new StubX509Certificate("") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 1") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 2") - .addSubjectAlternativeName(ALT_DNS_NAME, "a.b.c.d") - .addSubjectAlternativeName(ALT_DNS_NAME, "*.google.com") - .addSubjectAlternativeName(ALT_DNS_NAME, "imap.g.com") - .addSubjectAlternativeName(ALT_IPA_NAME, "2.33.44.55") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 3") - , "imap.g.com", true); - - checkMatch("42", new StubX509Certificate("") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 1") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 2") - .addSubjectAlternativeName(ALT_DNS_NAME, "a.b.c.d") - .addSubjectAlternativeName(ALT_DNS_NAME, "*.google.com") - .addSubjectAlternativeName(ALT_DNS_NAME, "imap.g.com") - .addSubjectAlternativeName(ALT_IPA_NAME, "2.33.44.55") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 3") - , "2.33.44.55", true); - - checkMatch("43", new StubX509Certificate("") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 1") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 2") - .addSubjectAlternativeName(ALT_DNS_NAME, "a.b.c.d") - .addSubjectAlternativeName(ALT_DNS_NAME, "*.google.com") - .addSubjectAlternativeName(ALT_DNS_NAME, "imap.g.com") - .addSubjectAlternativeName(ALT_IPA_NAME, "2.33.44.55") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 3") - , "g.com", false); - - checkMatch("44", new StubX509Certificate("") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 1") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 2") - .addSubjectAlternativeName(ALT_DNS_NAME, "a.b.c.d") - .addSubjectAlternativeName(ALT_DNS_NAME, "*.google.com") - .addSubjectAlternativeName(ALT_DNS_NAME, "imap.g.com") - .addSubjectAlternativeName(ALT_IPA_NAME, "2.33.44.55") - .addSubjectAlternativeName(ALT_UNKNOWN, "random string 3") - , "2.33.44.1", false); - } - - private void checkMatch(String message, X509Certificate certificate, String thisDomain, - boolean expected) { - Boolean actual = DomainNameValidator.match(certificate, thisDomain); - assertEquals(message, (Object) expected, (Object) actual); - } - - /** - * Tests {@link DomainNameValidator#matchDns} - */ - public void testMatchDns() { - checkMatchDns("11", "a.b.c.d", "a.b.c.d", true); - checkMatchDns("12", "a.b.c.d", "*.b.c.d", true); - checkMatchDns("13", "b.c.d", "*.b.c.d", true); - checkMatchDns("14", "b.c.d", "b*.c.d", true); - - checkMatchDns("15", "a.b.c.d", "*.*.c.d", false); - checkMatchDns("16", "a.b.c.d", "*.c.d", false); - - checkMatchDns("21", "imap.google.com", "imap.google.com", true); - checkMatchDns("22", "imap2.google.com", "imap.google.com", false); - checkMatchDns("23", "imap.google.com", "*.google.com", true); - checkMatchDns("24", "imap2.google.com", "*.google.com", true); - checkMatchDns("25", "imap.google.com", "*.googl.com", false); - checkMatchDns("26", "imap2.google2.com", "*.google3.com", false); - checkMatchDns("27", "imap.google.com", "ima*.google.com", true); - checkMatchDns("28", "imap.google.com", "imap*.google.com", true); - checkMatchDns("29", "imap.google.com", "*.imap.google.com", true); - - checkMatchDns("41", "imap.google.com", "a*.google.com", false); - checkMatchDns("42", "imap.google.com", "ix*.google.com", false); - - checkMatchDns("51", "imap.google.com", "iMap.Google.Com", true); - } - - private void checkMatchDns(String message, String thisDomain, String thatDomain, - boolean expected) { - boolean actual = DomainNameValidator.matchDns(thisDomain, thatDomain); - assertEquals(message, expected, actual); - } - - /** - * Test {@link DomainNameValidator#match} with actual certificates. - */ - public void testWithActualCert() throws Exception { - // subject_only - // - // subject: C=JP, CN=www.example.com - // subject alt names: n/a - checkWithActualCert("11", R.raw.subject_only, "www.example.com", true); - checkWithActualCert("12", R.raw.subject_only, "www2.example.com", false); - - // subject_alt_only - // - // subject: C=JP (no CN) - // subject alt names: DNS:www.example.com - checkWithActualCert("21", R.raw.subject_alt_only, "www.example.com", true); - checkWithActualCert("22", R.raw.subject_alt_only, "www2.example.com", false); - - // subject_with_alt_names - // - // subject: C=JP, CN=www.example.com - // subject alt names: DNS:www2.example.com, DNS:www3.example.com - // * Subject should be ignored, because it has subject alt names. - checkWithActualCert("31", R.raw.subject_with_alt_names, "www.example.com", false); - checkWithActualCert("32", R.raw.subject_with_alt_names, "www2.example.com", true); - checkWithActualCert("33", R.raw.subject_with_alt_names, "www3.example.com", true); - checkWithActualCert("34", R.raw.subject_with_alt_names, "www4.example.com", false); - - // subject_with_wild_alt_name - // - // subject: C=JP, CN=www.example.com - // subject alt names: DNS:*.example2.com - // * Subject should be ignored, because it has subject alt names. - checkWithActualCert("41", R.raw.subject_with_wild_alt_name, "www.example.com", false); - checkWithActualCert("42", R.raw.subject_with_wild_alt_name, "www2.example.com", false); - checkWithActualCert("43", R.raw.subject_with_wild_alt_name, "www.example2.com", true); - checkWithActualCert("44", R.raw.subject_with_wild_alt_name, "abc.example2.com", true); - checkWithActualCert("45", R.raw.subject_with_wild_alt_name, "www.example3.com", false); - - // wild_alt_name_only - // - // subject: C=JP - // subject alt names: DNS:*.example.com - checkWithActualCert("51", R.raw.wild_alt_name_only, "www.example.com", true); - checkWithActualCert("52", R.raw.wild_alt_name_only, "www2.example.com", true); - checkWithActualCert("53", R.raw.wild_alt_name_only, "www.example2.com", false); - - // wild_alt_name_only - // - // subject: C=JP - // subject alt names: IP Address:192.168.10.1 - checkWithActualCert("61", R.raw.alt_ip_only, "192.168.10.1", true); - checkWithActualCert("61", R.raw.alt_ip_only, "192.168.10.2", false); - } - - private void checkWithActualCert(String message, int resId, String domain, - boolean expected) throws Exception { - CertificateFactory factory = CertificateFactory.getInstance("X509"); - InputStream certStream = getContext().getResources().openRawResource(resId); - X509Certificate certificate = (X509Certificate) factory.generateCertificate(certStream); - - checkMatch(message, certificate, domain, expected); - } - - /** - * Minimal {@link X509Certificate} implementation for {@link DomainNameValidator}. - */ - private static class StubX509Certificate extends X509Certificate { - private final X500Principal subjectX500Principal; - private Collection<List<?>> subjectAlternativeNames; - - public StubX509Certificate(String subjectDn) { - subjectX500Principal = new X500Principal(subjectDn); - subjectAlternativeNames = null; - } - - public StubX509Certificate addSubjectAlternativeName(int type, String name) { - if (subjectAlternativeNames == null) { - subjectAlternativeNames = new ArrayList<List<?>>(); - } - LinkedList<Object> entry = new LinkedList<Object>(); - entry.add(type); - entry.add(name); - subjectAlternativeNames.add(entry); - return this; - } - - @Override - public Collection<List<?>> getSubjectAlternativeNames() throws CertificateParsingException { - return subjectAlternativeNames; - } - - @Override - public X500Principal getSubjectX500Principal() { - return subjectX500Principal; - } - - @Override - public void checkValidity() throws CertificateExpiredException, - CertificateNotYetValidException { - throw new RuntimeException("Method not implemented"); - } - - @Override - public void checkValidity(Date date) throws CertificateExpiredException, - CertificateNotYetValidException { - throw new RuntimeException("Method not implemented"); - } - - @Override - public int getBasicConstraints() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public Principal getIssuerDN() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public boolean[] getIssuerUniqueID() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public boolean[] getKeyUsage() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public Date getNotAfter() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public Date getNotBefore() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public BigInteger getSerialNumber() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public String getSigAlgName() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public String getSigAlgOID() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public byte[] getSigAlgParams() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public byte[] getSignature() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public Principal getSubjectDN() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public boolean[] getSubjectUniqueID() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public byte[] getTBSCertificate() throws CertificateEncodingException { - throw new RuntimeException("Method not implemented"); - } - - @Override - public int getVersion() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public byte[] getEncoded() throws CertificateEncodingException { - throw new RuntimeException("Method not implemented"); - } - - @Override - public PublicKey getPublicKey() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public String toString() { - throw new RuntimeException("Method not implemented"); - } - - @Override - public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException { - throw new RuntimeException("Method not implemented"); - } - - @Override - public void verify(PublicKey key, String sigProvider) throws CertificateException, - NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, - SignatureException { - throw new RuntimeException("Method not implemented"); - } - - public Set<String> getCriticalExtensionOIDs() { - throw new RuntimeException("Method not implemented"); - } - - public byte[] getExtensionValue(String oid) { - throw new RuntimeException("Method not implemented"); - } - - public Set<String> getNonCriticalExtensionOIDs() { - throw new RuntimeException("Method not implemented"); - } - - public boolean hasUnsupportedCriticalExtension() { - throw new RuntimeException("Method not implemented"); - } - } -} diff --git a/core/tests/coretests/src/com/android/internal/net/NetworkStatsFactoryTest.java b/core/tests/coretests/src/com/android/internal/net/NetworkStatsFactoryTest.java index ea94fa9..d3dd01a 100644 --- a/core/tests/coretests/src/com/android/internal/net/NetworkStatsFactoryTest.java +++ b/core/tests/coretests/src/com/android/internal/net/NetworkStatsFactoryTest.java @@ -16,6 +16,7 @@ package com.android.internal.net; +import static android.net.NetworkStats.SET_ALL; import static android.net.NetworkStats.SET_DEFAULT; import static android.net.NetworkStats.SET_FOREGROUND; import static android.net.NetworkStats.TAG_NONE; @@ -24,6 +25,7 @@ import static com.android.server.NetworkManagementSocketTagger.kernelToTag; import android.content.res.Resources; import android.net.NetworkStats; +import android.net.TrafficStats; import android.test.AndroidTestCase; import com.android.frameworks.coretests.R; @@ -79,64 +81,18 @@ public class NetworkStatsFactoryTest extends AndroidTestCase { assertStatsEntry(stats, "rmnet2", 10001, SET_DEFAULT, 0x0, 1125899906842624L, 984L); } - public void testNetworkStatsSummary() throws Exception { - stageFile(R.raw.net_dev_typical, new File(mTestProc, "net/dev")); - - final NetworkStats stats = mFactory.readNetworkStatsSummary(); - assertEquals(6, stats.size()); - assertStatsEntry(stats, "lo", UID_ALL, SET_DEFAULT, TAG_NONE, 8308L, 8308L); - assertStatsEntry(stats, "rmnet0", UID_ALL, SET_DEFAULT, TAG_NONE, 1507570L, 489339L); - assertStatsEntry(stats, "ifb0", UID_ALL, SET_DEFAULT, TAG_NONE, 52454L, 0L); - assertStatsEntry(stats, "ifb1", UID_ALL, SET_DEFAULT, TAG_NONE, 52454L, 0L); - assertStatsEntry(stats, "sit0", UID_ALL, SET_DEFAULT, TAG_NONE, 0L, 0L); - assertStatsEntry(stats, "ip6tnl0", UID_ALL, SET_DEFAULT, TAG_NONE, 0L, 0L); - } - - public void testNetworkStatsSummaryDown() throws Exception { - stageFile(R.raw.net_dev_typical, new File(mTestProc, "net/dev")); - stageLong(1L, new File(mTestProc, "net/xt_qtaguid/iface_stat/wlan0/active")); - stageLong(1024L, new File(mTestProc, "net/xt_qtaguid/iface_stat/wlan0/rx_bytes")); - stageLong(128L, new File(mTestProc, "net/xt_qtaguid/iface_stat/wlan0/rx_packets")); - stageLong(2048L, new File(mTestProc, "net/xt_qtaguid/iface_stat/wlan0/tx_bytes")); - stageLong(256L, new File(mTestProc, "net/xt_qtaguid/iface_stat/wlan0/tx_packets")); - - final NetworkStats stats = mFactory.readNetworkStatsSummary(); - assertEquals(7, stats.size()); - assertStatsEntry(stats, "rmnet0", UID_ALL, SET_DEFAULT, TAG_NONE, 1507570L, 489339L); - assertStatsEntry(stats, "wlan0", UID_ALL, SET_DEFAULT, TAG_NONE, 1024L, 2048L); - } - - public void testNetworkStatsCombined() throws Exception { - stageFile(R.raw.net_dev_typical, new File(mTestProc, "net/dev")); - stageLong(1L, new File(mTestProc, "net/xt_qtaguid/iface_stat/rmnet0/active")); - stageLong(10L, new File(mTestProc, "net/xt_qtaguid/iface_stat/rmnet0/rx_bytes")); - stageLong(20L, new File(mTestProc, "net/xt_qtaguid/iface_stat/rmnet0/rx_packets")); - stageLong(30L, new File(mTestProc, "net/xt_qtaguid/iface_stat/rmnet0/tx_bytes")); - stageLong(40L, new File(mTestProc, "net/xt_qtaguid/iface_stat/rmnet0/tx_packets")); - - final NetworkStats stats = mFactory.readNetworkStatsSummary(); - assertStatsEntry(stats, "rmnet0", UID_ALL, SET_DEFAULT, TAG_NONE, 1507570L + 10L, - 2205L + 20L, 489339L + 30L, 2237L + 40L); - } - - public void testNetworkStatsCombinedInactive() throws Exception { - stageFile(R.raw.net_dev_typical, new File(mTestProc, "net/dev")); - stageLong(0L, new File(mTestProc, "net/xt_qtaguid/iface_stat/rmnet0/active")); - stageLong(10L, new File(mTestProc, "net/xt_qtaguid/iface_stat/rmnet0/rx_bytes")); - stageLong(20L, new File(mTestProc, "net/xt_qtaguid/iface_stat/rmnet0/rx_packets")); - stageLong(30L, new File(mTestProc, "net/xt_qtaguid/iface_stat/rmnet0/tx_bytes")); - stageLong(40L, new File(mTestProc, "net/xt_qtaguid/iface_stat/rmnet0/tx_packets")); - - final NetworkStats stats = mFactory.readNetworkStatsSummary(); - assertStatsEntry(stats, "rmnet0", UID_ALL, SET_DEFAULT, TAG_NONE, 10L, 20L, 30L, 40L); - } - public void testKernelTags() throws Exception { assertEquals(0, kernelToTag("0x0000000000000000")); assertEquals(0x32, kernelToTag("0x0000003200000000")); assertEquals(2147483647, kernelToTag("0x7fffffff00000000")); assertEquals(0, kernelToTag("0x0000000000000000")); assertEquals(2147483136, kernelToTag("0x7FFFFE0000000000")); + + assertEquals(0, kernelToTag("0x0")); + assertEquals(0, kernelToTag("0xf00d")); + assertEquals(1, kernelToTag("0x100000000")); + assertEquals(14438007, kernelToTag("0xdc4e7700000000")); + assertEquals(TrafficStats.TAG_SYSTEM_DOWNLOAD, kernelToTag("0xffffff0100000000")); } public void testNetworkStatsWithSet() throws Exception { @@ -151,11 +107,22 @@ public class NetworkStatsFactoryTest extends AndroidTestCase { public void testNetworkStatsSingle() throws Exception { stageFile(R.raw.xt_qtaguid_iface_typical, new File(mTestProc, "net/xt_qtaguid/iface_stat_all")); - final NetworkStats stats = mFactory.readNetworkStatsSummary(); + final NetworkStats stats = mFactory.readNetworkStatsSummaryDev(); assertEquals(6, stats.size()); - assertStatsEntry(stats, "rmnet0", UID_ALL, SET_DEFAULT, TAG_NONE, 2112L, 24L, 700L, 10L); - assertStatsEntry(stats, "test1", UID_ALL, SET_DEFAULT, TAG_NONE, 6L, 8L, 10L, 12L); - assertStatsEntry(stats, "test2", UID_ALL, SET_DEFAULT, TAG_NONE, 1L, 2L, 3L, 4L); + assertStatsEntry(stats, "rmnet0", UID_ALL, SET_ALL, TAG_NONE, 2112L, 24L, 700L, 10L); + assertStatsEntry(stats, "test1", UID_ALL, SET_ALL, TAG_NONE, 6L, 8L, 10L, 12L); + assertStatsEntry(stats, "test2", UID_ALL, SET_ALL, TAG_NONE, 1L, 2L, 3L, 4L); + } + + public void testNetworkStatsXt() throws Exception { + stageFile(R.raw.xt_qtaguid_iface_fmt_typical, + new File(mTestProc, "net/xt_qtaguid/iface_stat_fmt")); + + final NetworkStats stats = mFactory.readNetworkStatsSummaryXt(); + assertEquals(3, stats.size()); + assertStatsEntry(stats, "rmnet0", UID_ALL, SET_ALL, TAG_NONE, 6824L, 16L, 5692L, 10L); + assertStatsEntry(stats, "rmnet1", UID_ALL, SET_ALL, TAG_NONE, 11153922L, 8051L, 190226L, 2468L); + assertStatsEntry(stats, "rmnet2", UID_ALL, SET_ALL, TAG_NONE, 4968L, 35L, 3081L, 39L); } /** diff --git a/core/tests/coretests/src/com/android/internal/os/DebugTest.java b/core/tests/coretests/src/com/android/internal/os/DebugTest.java new file mode 100644 index 0000000..88c7d1b --- /dev/null +++ b/core/tests/coretests/src/com/android/internal/os/DebugTest.java @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2012 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.internal.os; + +import android.os.Debug; + +import android.test.suitebuilder.annotation.SmallTest; +import junit.framework.TestCase; + +@SmallTest +public class DebugTest extends TestCase { + + private final static String EXPECTED_GET_CALLER = + "com\\.android\\.internal\\.os\\.DebugTest\\.testGetCaller:\\d\\d"; + private final static String EXPECTED_GET_CALLERS = + "com\\.android\\.internal\\.os\\.DebugTest.callDepth3:\\d\\d " + + "com\\.android\\.internal\\.os\\.DebugTest.callDepth2:\\d\\d " + + "com\\.android\\.internal\\.os\\.DebugTest.callDepth1:\\d\\d "; + + /** + * @return String consisting of the caller to this method. + */ + private String callDepth0() { + return Debug.getCaller(); + } + + public void testGetCaller() { + assertTrue(callDepth0().matches(EXPECTED_GET_CALLER)); + } + + /** + * @return String consisting of the callers to this method. + */ + private String callDepth4() { + return Debug.getCallers(3); + } + + private String callDepth3() { + return callDepth4(); + } + + private String callDepth2() { + return callDepth3(); + } + + private String callDepth1() { + return callDepth2(); + } + + public void testGetCallers() { + assertTrue(callDepth1().matches(EXPECTED_GET_CALLERS)); + } +} diff --git a/core/tests/coretests/src/com/android/internal/util/BitwiseStreamsTest.java b/core/tests/coretests/src/com/android/internal/util/BitwiseStreamsTest.java index a304b68..306f58f 100644 --- a/core/tests/coretests/src/com/android/internal/util/BitwiseStreamsTest.java +++ b/core/tests/coretests/src/com/android/internal/util/BitwiseStreamsTest.java @@ -133,4 +133,25 @@ public class BitwiseStreamsTest extends AndroidTestCase { long end = android.os.SystemClock.elapsedRealtime(); Log.d(LOG_TAG, "repeated encode-decode took " + (end - start) + " ms"); } + + @SmallTest + public void testExpandArray() throws Exception { + Random random = new Random(); + int iterations = 10000; + int[] sizeArr = new int[iterations]; + int[] valueArr = new int[iterations]; + BitwiseOutputStream outStream = new BitwiseOutputStream(8); + for (int i = 0; i < iterations; i++) { + int x = random.nextInt(); + int size = (x & 0x07) + 1; + int value = x & (-1 >>> (32 - size)); + sizeArr[i] = size; + valueArr[i] = value; + outStream.write(size, value); + } + BitwiseInputStream inStream = new BitwiseInputStream(outStream.toByteArray()); + for (int i = 0; i < iterations; i++) { + assertEquals(valueArr[i], inStream.read(sizeArr[i])); + } + } } diff --git a/core/tests/coretests/src/com/android/internal/util/FileRotatorTest.java b/core/tests/coretests/src/com/android/internal/util/FileRotatorTest.java new file mode 100644 index 0000000..95f0e67 --- /dev/null +++ b/core/tests/coretests/src/com/android/internal/util/FileRotatorTest.java @@ -0,0 +1,428 @@ +/* + * Copyright (C) 2012 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.internal.util; + +import static android.text.format.DateUtils.DAY_IN_MILLIS; +import static android.text.format.DateUtils.HOUR_IN_MILLIS; +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.Suppress; +import android.util.Log; + +import com.android.internal.util.FileRotator.Reader; +import com.android.internal.util.FileRotator.Writer; +import com.google.android.collect.Lists; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ProtocolException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Random; + +import libcore.io.IoUtils; + +/** + * Tests for {@link FileRotator}. + */ +public class FileRotatorTest extends AndroidTestCase { + private static final String TAG = "FileRotatorTest"; + + private File mBasePath; + + private static final String PREFIX = "rotator"; + private static final String ANOTHER_PREFIX = "another_rotator"; + + private static final long TEST_TIME = 1300000000000L; + + // TODO: test throwing rolls back correctly + + @Override + protected void setUp() throws Exception { + super.setUp(); + + mBasePath = getContext().getFilesDir(); + IoUtils.deleteContents(mBasePath); + } + + public void testEmpty() throws Exception { + final FileRotator rotate1 = new FileRotator( + mBasePath, PREFIX, DAY_IN_MILLIS, WEEK_IN_MILLIS); + final FileRotator rotate2 = new FileRotator( + mBasePath, ANOTHER_PREFIX, DAY_IN_MILLIS, WEEK_IN_MILLIS); + + final RecordingReader reader = new RecordingReader(); + long currentTime = TEST_TIME; + + // write single new value + rotate1.combineActive(reader, writer("foo"), currentTime); + reader.assertRead(); + + // assert that one rotator doesn't leak into another + assertReadAll(rotate1, "foo"); + assertReadAll(rotate2); + } + + public void testCombine() throws Exception { + final FileRotator rotate = new FileRotator( + mBasePath, PREFIX, DAY_IN_MILLIS, WEEK_IN_MILLIS); + + final RecordingReader reader = new RecordingReader(); + long currentTime = TEST_TIME; + + // first combine should have empty read, but still write data. + rotate.combineActive(reader, writer("foo"), currentTime); + reader.assertRead(); + assertReadAll(rotate, "foo"); + + // second combine should replace contents; should read existing data, + // and write final data to disk. + currentTime += SECOND_IN_MILLIS; + reader.reset(); + rotate.combineActive(reader, writer("bar"), currentTime); + reader.assertRead("foo"); + assertReadAll(rotate, "bar"); + } + + public void testRotate() throws Exception { + final FileRotator rotate = new FileRotator( + mBasePath, PREFIX, DAY_IN_MILLIS, WEEK_IN_MILLIS); + + final RecordingReader reader = new RecordingReader(); + long currentTime = TEST_TIME; + + // combine first record into file + rotate.combineActive(reader, writer("foo"), currentTime); + reader.assertRead(); + assertReadAll(rotate, "foo"); + + // push time a few minutes forward; shouldn't rotate file + reader.reset(); + currentTime += MINUTE_IN_MILLIS; + rotate.combineActive(reader, writer("bar"), currentTime); + reader.assertRead("foo"); + assertReadAll(rotate, "bar"); + + // push time forward enough to rotate file; should still have same data + currentTime += DAY_IN_MILLIS + SECOND_IN_MILLIS; + rotate.maybeRotate(currentTime); + assertReadAll(rotate, "bar"); + + // combine a second time, should leave rotated value untouched, and + // active file should be empty. + reader.reset(); + rotate.combineActive(reader, writer("baz"), currentTime); + reader.assertRead(); + assertReadAll(rotate, "bar", "baz"); + } + + public void testDelete() throws Exception { + final FileRotator rotate = new FileRotator( + mBasePath, PREFIX, MINUTE_IN_MILLIS, DAY_IN_MILLIS); + + final RecordingReader reader = new RecordingReader(); + long currentTime = TEST_TIME; + + // create first record and trigger rotating it + rotate.combineActive(reader, writer("foo"), currentTime); + reader.assertRead(); + currentTime += MINUTE_IN_MILLIS + SECOND_IN_MILLIS; + rotate.maybeRotate(currentTime); + + // create second record + reader.reset(); + rotate.combineActive(reader, writer("bar"), currentTime); + reader.assertRead(); + assertReadAll(rotate, "foo", "bar"); + + // push time far enough to expire first record + currentTime = TEST_TIME + DAY_IN_MILLIS + (2 * MINUTE_IN_MILLIS); + rotate.maybeRotate(currentTime); + assertReadAll(rotate, "bar"); + + // push further to delete second record + currentTime += WEEK_IN_MILLIS; + rotate.maybeRotate(currentTime); + assertReadAll(rotate); + } + + public void testThrowRestoresBackup() throws Exception { + final FileRotator rotate = new FileRotator( + mBasePath, PREFIX, MINUTE_IN_MILLIS, DAY_IN_MILLIS); + + final RecordingReader reader = new RecordingReader(); + long currentTime = TEST_TIME; + + // first, write some valid data + rotate.combineActive(reader, writer("foo"), currentTime); + reader.assertRead(); + assertReadAll(rotate, "foo"); + + try { + // now, try writing which will throw + reader.reset(); + rotate.combineActive(reader, new Writer() { + public void write(OutputStream out) throws IOException { + new DataOutputStream(out).writeUTF("bar"); + throw new NullPointerException("yikes"); + } + }, currentTime); + + fail("woah, somehow able to write exception"); + } catch (IOException e) { + // expected from above + } + + // assert that we read original data, and that it's still intact after + // the failed write above. + reader.assertRead("foo"); + assertReadAll(rotate, "foo"); + } + + public void testOtherFilesAndMalformed() throws Exception { + final FileRotator rotate = new FileRotator( + mBasePath, PREFIX, SECOND_IN_MILLIS, SECOND_IN_MILLIS); + + // should ignore another prefix + touch("another_rotator.1024"); + touch("another_rotator.1024-2048"); + assertReadAll(rotate); + + // verify that broken filenames don't crash + touch("rotator"); + touch("rotator..."); + touch("rotator.-"); + touch("rotator.---"); + touch("rotator.a-b"); + touch("rotator_but_not_actually"); + assertReadAll(rotate); + + // and make sure that we can read something from a legit file + write("rotator.100-200", "meow"); + assertReadAll(rotate, "meow"); + } + + private static final String RED = "red"; + private static final String GREEN = "green"; + private static final String BLUE = "blue"; + private static final String YELLOW = "yellow"; + + public void testQueryMatch() throws Exception { + final FileRotator rotate = new FileRotator( + mBasePath, PREFIX, HOUR_IN_MILLIS, YEAR_IN_MILLIS); + + final RecordingReader reader = new RecordingReader(); + long currentTime = TEST_TIME; + + // rotate a bunch of historical data + rotate.maybeRotate(currentTime); + rotate.combineActive(reader, writer(RED), currentTime); + + currentTime += DAY_IN_MILLIS; + rotate.maybeRotate(currentTime); + rotate.combineActive(reader, writer(GREEN), currentTime); + + currentTime += DAY_IN_MILLIS; + rotate.maybeRotate(currentTime); + rotate.combineActive(reader, writer(BLUE), currentTime); + + currentTime += DAY_IN_MILLIS; + rotate.maybeRotate(currentTime); + rotate.combineActive(reader, writer(YELLOW), currentTime); + + final String[] FULL_SET = { RED, GREEN, BLUE, YELLOW }; + + assertReadAll(rotate, FULL_SET); + assertReadMatching(rotate, Long.MIN_VALUE, Long.MAX_VALUE, FULL_SET); + assertReadMatching(rotate, Long.MIN_VALUE, currentTime, FULL_SET); + assertReadMatching(rotate, TEST_TIME + SECOND_IN_MILLIS, currentTime, FULL_SET); + + // should omit last value, since it only touches at currentTime + assertReadMatching(rotate, TEST_TIME + SECOND_IN_MILLIS, currentTime - SECOND_IN_MILLIS, + RED, GREEN, BLUE); + + // check boundary condition + assertReadMatching(rotate, TEST_TIME + DAY_IN_MILLIS, Long.MAX_VALUE, FULL_SET); + assertReadMatching(rotate, TEST_TIME + DAY_IN_MILLIS + SECOND_IN_MILLIS, Long.MAX_VALUE, + GREEN, BLUE, YELLOW); + + // test range smaller than file + final long blueStart = TEST_TIME + (DAY_IN_MILLIS * 2); + final long blueEnd = TEST_TIME + (DAY_IN_MILLIS * 3); + assertReadMatching(rotate, blueStart + SECOND_IN_MILLIS, blueEnd - SECOND_IN_MILLIS, BLUE); + + // outside range should return nothing + assertReadMatching(rotate, Long.MIN_VALUE, TEST_TIME - DAY_IN_MILLIS); + } + + public void testClockRollingBackwards() throws Exception { + final FileRotator rotate = new FileRotator( + mBasePath, PREFIX, DAY_IN_MILLIS, YEAR_IN_MILLIS); + + final RecordingReader reader = new RecordingReader(); + long currentTime = TEST_TIME; + + // create record at current time + // --> foo + rotate.combineActive(reader, writer("foo"), currentTime); + reader.assertRead(); + assertReadAll(rotate, "foo"); + + // record a day in past; should create a new active file + // --> bar + currentTime -= DAY_IN_MILLIS; + reader.reset(); + rotate.combineActive(reader, writer("bar"), currentTime); + reader.assertRead(); + assertReadAll(rotate, "bar", "foo"); + + // verify that we rewrite current active file + // bar --> baz + currentTime += SECOND_IN_MILLIS; + reader.reset(); + rotate.combineActive(reader, writer("baz"), currentTime); + reader.assertRead("bar"); + assertReadAll(rotate, "baz", "foo"); + + // return to present and verify we write oldest active file + // baz --> meow + currentTime = TEST_TIME + SECOND_IN_MILLIS; + reader.reset(); + rotate.combineActive(reader, writer("meow"), currentTime); + reader.assertRead("baz"); + assertReadAll(rotate, "meow", "foo"); + + // current time should trigger rotate of older active file + rotate.maybeRotate(currentTime); + + // write active file, verify this time we touch original + // foo --> yay + reader.reset(); + rotate.combineActive(reader, writer("yay"), currentTime); + reader.assertRead("foo"); + assertReadAll(rotate, "meow", "yay"); + } + + @Suppress + public void testFuzz() throws Exception { + final FileRotator rotate = new FileRotator( + mBasePath, PREFIX, HOUR_IN_MILLIS, DAY_IN_MILLIS); + + final RecordingReader reader = new RecordingReader(); + long currentTime = TEST_TIME; + + // walk forward through time, ensuring that files are cleaned properly + final Random random = new Random(); + for (int i = 0; i < 1024; i++) { + currentTime += Math.abs(random.nextLong()) % DAY_IN_MILLIS; + + reader.reset(); + rotate.combineActive(reader, writer("meow"), currentTime); + + if (random.nextBoolean()) { + rotate.maybeRotate(currentTime); + } + } + + rotate.maybeRotate(currentTime); + + Log.d(TAG, "currentTime=" + currentTime); + Log.d(TAG, Arrays.toString(mBasePath.list())); + } + + public void testRecoverAtomic() throws Exception { + write("rotator.1024-2048", "foo"); + write("rotator.1024-2048.backup", "bar"); + write("rotator.2048-4096", "baz"); + write("rotator.2048-4096.no_backup", ""); + + final FileRotator rotate = new FileRotator( + mBasePath, PREFIX, SECOND_IN_MILLIS, SECOND_IN_MILLIS); + + // verify backup value was recovered; no_backup indicates that + // corresponding file had no backup and should be discarded. + assertReadAll(rotate, "bar"); + } + + private void touch(String... names) throws IOException { + for (String name : names) { + final OutputStream out = new FileOutputStream(new File(mBasePath, name)); + out.close(); + } + } + + private void write(String name, String value) throws IOException { + final DataOutputStream out = new DataOutputStream( + new FileOutputStream(new File(mBasePath, name))); + out.writeUTF(value); + out.close(); + } + + private static Writer writer(final String value) { + return new Writer() { + public void write(OutputStream out) throws IOException { + new DataOutputStream(out).writeUTF(value); + } + }; + } + + private static void assertReadAll(FileRotator rotate, String... expected) throws IOException { + assertReadMatching(rotate, Long.MIN_VALUE, Long.MAX_VALUE, expected); + } + + private static void assertReadMatching( + FileRotator rotate, long matchStartMillis, long matchEndMillis, String... expected) + throws IOException { + final RecordingReader reader = new RecordingReader(); + rotate.readMatching(reader, matchStartMillis, matchEndMillis); + reader.assertRead(expected); + } + + private static class RecordingReader implements Reader { + private ArrayList<String> mActual = Lists.newArrayList(); + + public void read(InputStream in) throws IOException { + mActual.add(new DataInputStream(in).readUTF()); + } + + public void reset() { + mActual.clear(); + } + + public void assertRead(String... expected) { + assertEquals(expected.length, mActual.size()); + + final ArrayList<String> actualCopy = new ArrayList<String>(mActual); + for (String value : expected) { + if (!actualCopy.remove(value)) { + final String expectedString = Arrays.toString(expected); + final String actualString = Arrays.toString(mActual.toArray()); + fail("expected: " + expectedString + " but was: " + actualString); + } + } + } + } +} diff --git a/core/tests/coretests/src/com/android/internal/widget/SizeAdaptiveLayoutTest.java b/core/tests/coretests/src/com/android/internal/widget/SizeAdaptiveLayoutTest.java new file mode 100644 index 0000000..efd06bf --- /dev/null +++ b/core/tests/coretests/src/com/android/internal/widget/SizeAdaptiveLayoutTest.java @@ -0,0 +1,490 @@ +/* + * Copyright (C) 2012 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.internal.widget; + +import com.android.frameworks.coretests.R; + +import android.content.Context; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.test.AndroidTestCase; +import android.test.suitebuilder.annotation.SmallTest; +import android.view.LayoutInflater; +import android.view.View; + +import com.android.internal.widget.SizeAdaptiveLayout; + + +public class SizeAdaptiveLayoutTest extends AndroidTestCase { + + private LayoutInflater mInflater; + private int mOneU; + private int mFourU; + private SizeAdaptiveLayout mSizeAdaptiveLayout; + private View mSmallView; + private View mMediumView; + private View mLargeView; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + // inflate the layout + final Context context = getContext(); + mInflater = LayoutInflater.from(context); + mOneU = 64; + mFourU = 4 * mOneU; + } + + private void inflate(int resource){ + mSizeAdaptiveLayout = (SizeAdaptiveLayout) mInflater.inflate(resource, null); + mSizeAdaptiveLayout.onAttachedToWindow(); + + mSmallView = mSizeAdaptiveLayout.findViewById(R.id.one_u); + mMediumView = mSizeAdaptiveLayout.findViewById(R.id.two_u); + mLargeView = mSizeAdaptiveLayout.findViewById(R.id.four_u); + } + + /** + * The name 'test preconditions' is a convention to signal that if this + * test doesn't pass, the test case was not set up properly and it might + * explain any and all failures in other tests. This is not guaranteed + * to run before other tests, as junit uses reflection to find the tests. + */ + @SmallTest + public void testPreconditions() { + assertNotNull(mInflater); + + inflate(R.layout.size_adaptive); + assertNotNull(mSizeAdaptiveLayout); + assertNotNull(mSmallView); + assertNotNull(mLargeView); + } + + @SmallTest + public void testOpenLarge() { + inflate(R.layout.size_adaptive); + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + int height = (int) lp.minHeight + 10; + + measureAndLayout(height); + + assertEquals("4U should be visible", + View.VISIBLE, + mLargeView.getVisibility()); + assertEquals("1U should be gone", + View.GONE, + mSmallView.getVisibility()); + } + + @SmallTest + public void testOpenSmall() { + inflate(R.layout.size_adaptive); + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mSmallView.getLayoutParams(); + int height = (int) lp.minHeight; + + measureAndLayout(height); + + assertEquals("1U should be visible", + View.VISIBLE, + mSmallView.getVisibility()); + assertEquals("4U should be gone", + View.GONE, + mLargeView.getVisibility()); + } + + @SmallTest + public void testOpenTooSmall() { + inflate(R.layout.size_adaptive); + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mSmallView.getLayoutParams(); + int height = (int) lp.minHeight - 10; + + measureAndLayout(height); + + assertEquals("1U should be visible", + View.VISIBLE, + mSmallView.getVisibility()); + assertEquals("4U should be gone", + View.GONE, + mLargeView.getVisibility()); + } + + @SmallTest + public void testOpenTooBig() { + inflate(R.layout.size_adaptive); + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + lp.maxHeight = 500; + mLargeView.setLayoutParams(lp); + int height = (int) (lp.minHeight + 10); + + measureAndLayout(height); + + assertEquals("4U should be visible", + View.VISIBLE, + mLargeView.getVisibility()); + assertEquals("1U should be gone", + View.GONE, + mSmallView.getVisibility()); + } + + @SmallTest + public void testOpenWrapContent() { + inflate(R.layout.size_adaptive_text); + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + int height = (int) lp.minHeight + 10; + + // manually measure it, and lay it out + int measureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST); + mSizeAdaptiveLayout.measure(500, measureSpec); + assertTrue("should not be forced to 4U", + mSizeAdaptiveLayout.getMeasuredHeight() < mFourU); + } + + @SmallTest + public void testOpenOneUOnlySmall() { + inflate(R.layout.size_adaptive_singleton); + assertNull("largeView should be NULL in the singleton layout", mLargeView); + + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mSmallView.getLayoutParams(); + int height = (int) lp.minHeight - 10; + + measureAndLayout(height); + + assertEquals("1U should be visible", + View.VISIBLE, + mSmallView.getVisibility()); + } + + @SmallTest + public void testOpenOneUOnlyLarge() { + inflate(R.layout.size_adaptive_singleton); + assertNull("largeView should be NULL in the singleton layout", mLargeView); + + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mSmallView.getLayoutParams(); + int height = (int) lp.maxHeight + 10; + + measureAndLayout(height); + + assertEquals("1U should be visible", + View.VISIBLE, + mSmallView.getVisibility()); + } + + @SmallTest + public void testOpenOneUOnlyJustRight() { + inflate(R.layout.size_adaptive_singleton); + assertNull("largeView should be NULL in the singleton layout", mLargeView); + + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mSmallView.getLayoutParams(); + int height = (int) lp.minHeight; + + measureAndLayout(height); + + assertEquals("1U should be visible", + View.VISIBLE, + mSmallView.getVisibility()); + } + + @SmallTest + public void testOpenFourUOnlySmall() { + inflate(R.layout.size_adaptive_large_only); + assertNull("smallView should be NULL in the singleton layout", mSmallView); + + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + int height = (int) lp.minHeight - 10; + + measureAndLayout(height); + + assertEquals("4U should be visible", + View.VISIBLE, + mLargeView.getVisibility()); + } + + @SmallTest + public void testOpenFourUOnlyLarge() { + inflate(R.layout.size_adaptive_large_only); + assertNull("smallView should be NULL in the singleton layout", mSmallView); + + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + int height = (int) lp.maxHeight + 10; + + measureAndLayout(height); + + assertEquals("4U should be visible", + View.VISIBLE, + mLargeView.getVisibility()); + } + + @SmallTest + public void testOpenFourUOnlyJustRight() { + inflate(R.layout.size_adaptive_large_only); + assertNull("smallView should be NULL in the singleton layout", mSmallView); + + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + int height = (int) lp.minHeight; + + measureAndLayout(height); + + assertEquals("4U should be visible", + View.VISIBLE, + mLargeView.getVisibility()); + } + + @SmallTest + public void testOpenIntoAGap() { + inflate(R.layout.size_adaptive_gappy); + + SizeAdaptiveLayout.LayoutParams smallParams = + (SizeAdaptiveLayout.LayoutParams) mSmallView.getLayoutParams(); + SizeAdaptiveLayout.LayoutParams largeParams = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + assertTrue("gappy layout should have a gap", + smallParams.maxHeight + 10 < largeParams.minHeight); + int height = (int) smallParams.maxHeight + 10; + + measureAndLayout(height); + + assertTrue("one and only one view should be visible", + mLargeView.getVisibility() != mSmallView.getVisibility()); + // behavior is undefined in this case. + } + + @SmallTest + public void testOpenIntoAnOverlap() { + inflate(R.layout.size_adaptive_overlapping); + + SizeAdaptiveLayout.LayoutParams smallParams = + (SizeAdaptiveLayout.LayoutParams) mSmallView.getLayoutParams(); + SizeAdaptiveLayout.LayoutParams largeParams = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + assertEquals("overlapping layout should overlap", + smallParams.minHeight, + largeParams.minHeight); + int height = (int) smallParams.maxHeight; + + measureAndLayout(height); + + assertTrue("one and only one view should be visible", + mLargeView.getVisibility() != mSmallView.getVisibility()); + assertEquals("1U should get priority in an overlap because it is first", + View.VISIBLE, + mSmallView.getVisibility()); + } + + @SmallTest + public void testOpenThreeWayViewSmall() { + inflate(R.layout.size_adaptive_three_way); + assertNotNull("mMediumView should not be NULL in the three view layout", mMediumView); + + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mSmallView.getLayoutParams(); + int height = (int) lp.minHeight; + + measureAndLayout(height); + + assertEquals("1U should be visible", + View.VISIBLE, + mSmallView.getVisibility()); + assertEquals("2U should be gone", + View.GONE, + mMediumView.getVisibility()); + assertEquals("4U should be gone", + View.GONE, + mLargeView.getVisibility()); + } + + @SmallTest + public void testOpenThreeWayViewMedium() { + inflate(R.layout.size_adaptive_three_way); + assertNotNull("mMediumView should not be NULL in the three view layout", mMediumView); + + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mMediumView.getLayoutParams(); + int height = (int) lp.minHeight; + + measureAndLayout(height); + + assertEquals("1U should be gone", + View.GONE, + mSmallView.getVisibility()); + assertEquals("2U should be visible", + View.VISIBLE, + mMediumView.getVisibility()); + assertEquals("4U should be gone", + View.GONE, + mLargeView.getVisibility()); + } + + @SmallTest + public void testOpenThreeWayViewLarge() { + inflate(R.layout.size_adaptive_three_way); + assertNotNull("mMediumView should not be NULL in the three view layout", mMediumView); + + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + int height = (int) lp.minHeight; + + measureAndLayout(height); + + assertEquals("1U should be gone", + View.GONE, + mSmallView.getVisibility()); + assertEquals("2U should be gone", + View.GONE, + mMediumView.getVisibility()); + assertEquals("4U should be visible", + View.VISIBLE, + mLargeView.getVisibility()); + } + + @SmallTest + public void testResizeWithoutAnimation() { + inflate(R.layout.size_adaptive); + + SizeAdaptiveLayout.LayoutParams largeParams = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + int startHeight = (int) largeParams.minHeight + 10; + int endHeight = (int) largeParams.minHeight + 10; + + measureAndLayout(startHeight); + + assertEquals("4U should be visible", + View.VISIBLE, + mLargeView.getVisibility()); + assertFalse("There should be no animation on initial rendering.", + mSizeAdaptiveLayout.getTransitionAnimation().isRunning()); + + measureAndLayout(endHeight); + + assertEquals("4U should still be visible", + View.VISIBLE, + mLargeView.getVisibility()); + assertFalse("There should be no animation on scale within a view.", + mSizeAdaptiveLayout.getTransitionAnimation().isRunning()); + } + + @SmallTest + public void testResizeWithAnimation() { + inflate(R.layout.size_adaptive); + + SizeAdaptiveLayout.LayoutParams smallParams = + (SizeAdaptiveLayout.LayoutParams) mSmallView.getLayoutParams(); + SizeAdaptiveLayout.LayoutParams largeParams = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + int startHeight = (int) largeParams.minHeight + 10; + int endHeight = (int) smallParams.maxHeight; + + measureAndLayout(startHeight); + + assertEquals("4U should be visible", + View.VISIBLE, + mLargeView.getVisibility()); + assertFalse("There should be no animation on initial rendering.", + mSizeAdaptiveLayout.getTransitionAnimation().isRunning()); + + measureAndLayout(endHeight); + + assertEquals("1U should now be visible", + View.VISIBLE, + mSmallView.getVisibility()); + assertTrue("There should be an animation on scale between views.", + mSizeAdaptiveLayout.getTransitionAnimation().isRunning()); + } + + @SmallTest + public void testModestyPanelChangesColorWhite() { + inflate(R.layout.size_adaptive_color); + View panel = mSizeAdaptiveLayout.getModestyPanel(); + assertTrue("ModestyPanel should have a ColorDrawable background", + panel.getBackground() instanceof ColorDrawable); + ColorDrawable panelColor = (ColorDrawable) panel.getBackground(); + ColorDrawable salColor = (ColorDrawable) mSizeAdaptiveLayout.getBackground(); + assertEquals("ModestyPanel color should match the SizeAdaptiveLayout", + panelColor.getColor(), salColor.getColor()); + } + + @SmallTest + public void testModestyPanelTracksStateListColor() { + inflate(R.layout.size_adaptive_color_statelist); + View panel = mSizeAdaptiveLayout.getModestyPanel(); + assertEquals("ModestyPanel should have a ColorDrawable background" , + panel.getBackground().getClass(), ColorDrawable.class); + ColorDrawable panelColor = (ColorDrawable) panel.getBackground(); + assertEquals("ModestyPanel color should match the SizeAdaptiveLayout", + panelColor.getColor(), Color.RED); + } + + @SmallTest + public void testModestyPanelHasDefault() { + inflate(R.layout.size_adaptive); + View panel = mSizeAdaptiveLayout.getModestyPanel(); + assertNull("SizeAdaptiveLayout should have no background for this test", + mSizeAdaptiveLayout.getBackground()); + assertTrue("ModestyPanel should have a ColorDrawable background", + panel.getBackground() instanceof ColorDrawable); + } + + @SmallTest + public void testOpenSmallEvenWhenLargeIsActuallySmall() { + inflate(R.layout.size_adaptive_lies); + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mSmallView.getLayoutParams(); + int height = (int) lp.minHeight; + + measureAndLayout(height); + + assertEquals("1U should be visible", + View.VISIBLE, + mSmallView.getVisibility()); + assertTrue("1U should also have been measured", + mSmallView.getMeasuredHeight() > 0); + } + + @SmallTest + public void testOpenLargeEvenWhenLargeIsActuallySmall() { + inflate(R.layout.size_adaptive_lies); + SizeAdaptiveLayout.LayoutParams lp = + (SizeAdaptiveLayout.LayoutParams) mLargeView.getLayoutParams(); + int height = (int) lp.minHeight; + + measureAndLayout(height); + + assertEquals("4U should be visible", + View.VISIBLE, + mLargeView.getVisibility()); + assertTrue("4U should also have been measured", + mLargeView.getMeasuredHeight() > 0); + } + + private void measureAndLayout(int height) { + // manually measure it, and lay it out + int measureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST); + mSizeAdaptiveLayout.measure(500, measureSpec); + mSizeAdaptiveLayout.layout(0, 0, 500, mSizeAdaptiveLayout.getMeasuredHeight()); + } +} diff --git a/core/tests/hosttests/test-apps/DownloadManagerTestApp/Android.mk b/core/tests/hosttests/test-apps/DownloadManagerTestApp/Android.mk index a419068..09dcac5 100644 --- a/core/tests/hosttests/test-apps/DownloadManagerTestApp/Android.mk +++ b/core/tests/hosttests/test-apps/DownloadManagerTestApp/Android.mk @@ -20,7 +20,7 @@ LOCAL_MODULE_TAGS := tests LOCAL_SRC_FILES := $(call all-java-files-under, src) -LOCAL_STATIC_JAVA_LIBRARIES := android-common frameworks-core-util-lib +LOCAL_STATIC_JAVA_LIBRARIES := android-common mockwebserver LOCAL_SDK_VERSION := current LOCAL_PACKAGE_NAME := DownloadManagerTestApp diff --git a/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/DownloadManagerBaseTest.java b/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/downloadmanagertests/DownloadManagerBaseTest.java index 334661d..8e935f8 100644 --- a/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/DownloadManagerBaseTest.java +++ b/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/downloadmanagertests/DownloadManagerBaseTest.java @@ -18,7 +18,6 @@ package com.android.frameworks.downloadmanagertests; import android.app.DownloadManager; import android.app.DownloadManager.Query; -import android.app.DownloadManager.Request; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -26,37 +25,19 @@ import android.content.IntentFilter; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; -import android.net.Uri; import android.net.wifi.WifiManager; -import android.os.Bundle; import android.os.Environment; import android.os.ParcelFileDescriptor; import android.os.SystemClock; -import android.os.ParcelFileDescriptor.AutoCloseInputStream; import android.provider.Settings; import android.test.InstrumentationTestCase; import android.util.Log; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.URL; -import java.util.concurrent.TimeoutException; import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Random; import java.util.Set; -import java.util.Vector; - -import junit.framework.AssertionFailedError; - -import coretestutils.http.MockResponse; -import coretestutils.http.MockWebServer; +import java.util.concurrent.TimeoutException; /** * Base class for Instrumented tests for the Download Manager. @@ -64,7 +45,6 @@ import coretestutils.http.MockWebServer; public class DownloadManagerBaseTest extends InstrumentationTestCase { protected DownloadManager mDownloadManager = null; - protected MockWebServer mServer = null; protected String mFileType = "text/plain"; protected Context mContext = null; protected MultipleDownloadsCompletedReceiver mReceiver = null; @@ -77,7 +57,6 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { protected static final int HTTP_PARTIAL_CONTENT = 206; protected static final int HTTP_NOT_FOUND = 404; protected static final int HTTP_SERVICE_UNAVAILABLE = 503; - protected String DEFAULT_FILENAME = "somefile.txt"; protected static final int DEFAULT_MAX_WAIT_TIME = 2 * 60 * 1000; // 2 minutes protected static final int DEFAULT_WAIT_POLL_TIME = 5 * 1000; // 5 seconds @@ -86,48 +65,6 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { protected static final int MAX_WAIT_FOR_DOWNLOAD_TIME = 5 * 60 * 1000; // 5 minutes protected static final int MAX_WAIT_FOR_LARGE_DOWNLOAD_TIME = 15 * 60 * 1000; // 15 minutes - protected static final int DOWNLOAD_TO_SYSTEM_CACHE = 1; - protected static final int DOWNLOAD_TO_DOWNLOAD_CACHE_DIR = 2; - - // Just a few popular file types used to return from a download - protected enum DownloadFileType { - PLAINTEXT, - APK, - GIF, - GARBAGE, - UNRECOGNIZED, - ZIP - } - - protected enum DataType { - TEXT, - BINARY - } - - public static class LoggingRng extends Random { - - /** - * Constructor - * - * Creates RNG with self-generated seed value. - */ - public LoggingRng() { - this(SystemClock.uptimeMillis()); - } - - /** - * Constructor - * - * Creats RNG with given initial seed value - - * @param seed The initial seed value - */ - public LoggingRng(long seed) { - super(seed); - Log.i(LOG_TAG, "Seeding RNG with value: " + seed); - } - } - public static class MultipleDownloadsCompletedReceiver extends BroadcastReceiver { private volatile int mNumDownloadsCompleted = 0; private Set<Long> downloadIds = Collections.synchronizedSet(new HashSet<Long>()); @@ -171,7 +108,7 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { /** * Gets the number of times the {@link #onReceive} callback has been called for the - * {@link DownloadManager.ACTION_DOWNLOAD_COMPLETED} action, indicating the number of + * {@link DownloadManager#ACTION_DOWNLOAD_COMPLETE} action, indicating the number of * downloads completed thus far. * * @return the number of downloads completed so far. @@ -241,76 +178,7 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { public void setUp() throws Exception { mContext = getInstrumentation().getContext(); mDownloadManager = (DownloadManager)mContext.getSystemService(Context.DOWNLOAD_SERVICE); - mServer = new MockWebServer(); mReceiver = registerNewMultipleDownloadsReceiver(); - // Note: callers overriding this should call mServer.play() with the desired port # - } - - /** - * Helper to enqueue a response from the MockWebServer. - * - * @param status The HTTP status code to return for this response - * @param body The body to return in this response - * @return Returns the mock web server response that was queued (which can be modified) - */ - private MockResponse enqueueResponse(int status, byte[] body) { - return doEnqueueResponse(status).setBody(body); - - } - - /** - * Helper to enqueue a response from the MockWebServer. - * - * @param status The HTTP status code to return for this response - * @param bodyFile The body to return in this response - * @return Returns the mock web server response that was queued (which can be modified) - */ - private MockResponse enqueueResponse(int status, File bodyFile) { - return doEnqueueResponse(status).setBody(bodyFile); - } - - /** - * Helper for enqueue'ing a response from the MockWebServer. - * - * @param status The HTTP status code to return for this response - * @return Returns the mock web server response that was queued (which can be modified) - */ - private MockResponse doEnqueueResponse(int status) { - MockResponse response = new MockResponse().setResponseCode(status); - response.addHeader("Content-type", mFileType); - mServer.enqueue(response); - return response; - } - - /** - * Helper to generate a random blob of bytes using a given RNG. - * - * @param size The size of the data to generate - * @param type The type of data to generate: currently, one of {@link DataType.TEXT} or - * {@link DataType.BINARY}. - * @param rng (optional) The RNG to use; pass null to use - * @return The random data that is generated. - */ - private byte[] generateData(int size, DataType type, Random rng) { - int min = Byte.MIN_VALUE; - int max = Byte.MAX_VALUE; - - // Only use chars in the HTTP ASCII printable character range for Text - if (type == DataType.TEXT) { - min = 32; - max = 126; - } - byte[] result = new byte[size]; - Log.i(LOG_TAG, "Generating data of size: " + size); - - if (rng == null) { - rng = new LoggingRng(); - } - - for (int i = 0; i < size; ++i) { - result[i] = (byte) (min + rng.nextInt(max - min + 1)); - } - return result; } /** @@ -324,76 +192,6 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { } /** - * Helper to verify the contents of a downloaded file versus a byte[]. - * - * @param actual The file of whose contents to verify - * @param expected The data we expect to find in the aforementioned file - * @throws IOException if there was a problem reading from the file - */ - private void verifyFileContents(ParcelFileDescriptor actual, byte[] expected) - throws IOException { - AutoCloseInputStream input = new ParcelFileDescriptor.AutoCloseInputStream(actual); - long fileSize = actual.getStatSize(); - - assertTrue(fileSize <= Integer.MAX_VALUE); - assertEquals(expected.length, fileSize); - - byte[] actualData = new byte[expected.length]; - assertEquals(input.read(actualData), fileSize); - compareByteArrays(actualData, expected); - } - - /** - * Helper to compare 2 byte arrays. - * - * @param actual The array whose data we want to verify - * @param expected The array of data we expect to see - */ - private void compareByteArrays(byte[] actual, byte[] expected) { - assertEquals(actual.length, expected.length); - int length = actual.length; - for (int i = 0; i < length; ++i) { - // assert has a bit of overhead, so only do the assert when the values are not the same - if (actual[i] != expected[i]) { - fail("Byte arrays are not equal."); - } - } - } - - /** - * Gets the MIME content string for a given type - * - * @param type The MIME type to return - * @return the String representation of that MIME content type - */ - protected String getMimeMapping(DownloadFileType type) { - switch (type) { - case APK: - return "application/vnd.android.package-archive"; - case GIF: - return "image/gif"; - case ZIP: - return "application/x-zip-compressed"; - case GARBAGE: - return "zip\\pidy/doo/da"; - case UNRECOGNIZED: - return "application/new.undefined.type.of.app"; - } - return "text/plain"; - } - - /** - * Gets the Uri that should be used to access the mock server - * - * @param filename The name of the file to try to retrieve from the mock server - * @return the Uri to use for access the file on the mock server - */ - private Uri getServerUri(String filename) throws Exception { - URL url = mServer.getUrl("/" + filename); - return Uri.parse(url.toString()); - } - - /** * Helper to create and register a new MultipleDownloadCompletedReciever * * This is used to track many simultaneous downloads by keeping count of all the downloads @@ -738,39 +536,6 @@ public class DownloadManagerBaseTest extends InstrumentationTestCase { } /** - * Helper to perform a standard enqueue of data to the mock server. - * download is performed to the downloads cache dir (NOT systemcache dir) - * - * @param body The body to return in the response from the server - */ - private long doStandardEnqueue(byte[] body) throws Exception { - // Prepare the mock server with a standard response - enqueueResponse(HTTP_OK, body); - return doCommonStandardEnqueue(); - } - - /** - * Helper to perform a standard enqueue of data to the mock server. - * - * @param body The body to return in the response from the server, contained in the file - */ - private long doStandardEnqueue(File body) throws Exception { - // Prepare the mock server with a standard response - enqueueResponse(HTTP_OK, body); - return doCommonStandardEnqueue(); - } - - /** - * Helper to do the additional steps (setting title and Uri of default filename) when - * doing a standard enqueue request to the server. - */ - private long doCommonStandardEnqueue() throws Exception { - Uri uri = getServerUri(DEFAULT_FILENAME); - Request request = new Request(uri).setTitle(DEFAULT_FILENAME); - return mDownloadManager.enqueue(request); - } - - /** * Helper to verify an int value in a Cursor * * @param cursor The cursor containing the query results diff --git a/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/DownloadManagerTestApp.java b/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/downloadmanagertests/DownloadManagerTestApp.java index 654f747..9c44d61 100644 --- a/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/DownloadManagerTestApp.java +++ b/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/downloadmanagertests/DownloadManagerTestApp.java @@ -16,16 +16,11 @@ package com.android.frameworks.downloadmanagertests; import android.app.DownloadManager; -import android.app.DownloadManager.Query; import android.app.DownloadManager.Request; -import android.content.Context; -import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import android.os.ParcelFileDescriptor; -import android.provider.Settings; -import android.test.suitebuilder.annotation.LargeTest; import android.util.Log; import java.io.DataInputStream; @@ -33,13 +28,8 @@ import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.FileWriter; import java.util.HashSet; -import coretestutils.http.MockResponse; -import coretestutils.http.MockWebServer; -import coretestutils.http.RecordedRequest; - /** * Class to test downloading files from a real (not mock) external server. */ @@ -243,7 +233,7 @@ public class DownloadManagerTestApp extends DownloadManagerBaseTest { Uri remoteUri = getExternalFileUri(filename); Request request = new Request(remoteUri); - request.setMimeType(getMimeMapping(DownloadFileType.APK)); + request.setMimeType("application/vnd.android.package-archive"); dlRequest = mDownloadManager.enqueue(request); diff --git a/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/DownloadManagerTestRunner.java b/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/downloadmanagertests/DownloadManagerTestRunner.java index 27bf7e1..27bf7e1 100644 --- a/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/DownloadManagerTestRunner.java +++ b/core/tests/hosttests/test-apps/DownloadManagerTestApp/src/com/android/frameworks/downloadmanagertests/DownloadManagerTestRunner.java diff --git a/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java b/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java index 85b49ce..6211c1c 100644 --- a/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java +++ b/core/tests/overlaytests/OverlayTest/src/com/android/overlaytest/OverlayBaseTest.java @@ -64,8 +64,8 @@ public abstract class OverlayBaseTest extends AndroidTestCase { } public void testBoolean() throws Throwable { - // config_bypass_keyguard_if_slider_open has no overlay - final int resId = com.android.internal.R.bool.config_bypass_keyguard_if_slider_open; + // config_annoy_dianne has no overlay + final int resId = com.android.internal.R.bool.config_annoy_dianne; assertResource(resId, true, true); } diff --git a/core/tests/utillib/src/android/test/BandwidthTest.java b/core/tests/utillib/src/android/test/BandwidthTest.java new file mode 100644 index 0000000..6cff0ff --- /dev/null +++ b/core/tests/utillib/src/android/test/BandwidthTest.java @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2012 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.test; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * This annotation can be used on an {@link junit.framework.TestCase}'s test methods. When the + * annotation is present, the test method is profiled for bandwidth metrics and the results + * written through instrumentation output. It can also be used on the class itself, + * which is equivalent to tagging all test methods with this annotation. + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface BandwidthTest { +} diff --git a/core/tests/utillib/src/android/test/BandwidthTestCase.java b/core/tests/utillib/src/android/test/BandwidthTestCase.java new file mode 100644 index 0000000..c03d9b3 --- /dev/null +++ b/core/tests/utillib/src/android/test/BandwidthTestCase.java @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2012 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.test; + +import android.net.NetworkStats; +import android.net.TrafficStats; +import android.os.Bundle; +import android.util.Log; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +/** + * A bandwidth test case that collects bandwidth statistics for tests that are + * annotated with {@link BandwidthTest} otherwise the test is executed + * as an {@link InstrumentationTestCase} + */ +public class BandwidthTestCase extends InstrumentationTestCase { + private static final String TAG = "BandwidthTestCase"; + private static final String REPORT_KEY_PACKETS_SENT = "txPackets"; + private static final String REPORT_KEY_PACKETS_RECEIVED = "rxPackets"; + private static final String REPORT_KEY_BYTES_SENT = "txBytes"; + private static final String REPORT_KEY_BYTES_RECEIVED = "rxBytes"; + private static final String REPORT_KEY_OPERATIONS = "operations"; + + @Override + protected void runTest() throws Throwable { + //This is a copy of {@link InstrumentationTestCase#runTest} with + //added logic to handle bandwidth measurements + String fName = getName(); + assertNotNull(fName); + Method method = null; + Class testClass = null; + try { + // use getMethod to get all public inherited + // methods. getDeclaredMethods returns all + // methods of this class but excludes the + // inherited ones. + testClass = getClass(); + method = testClass.getMethod(fName, (Class[]) null); + } catch (NoSuchMethodException e) { + fail("Method \""+fName+"\" not found"); + } + + if (!Modifier.isPublic(method.getModifiers())) { + fail("Method \""+fName+"\" should be public"); + } + + int runCount = 1; + boolean isRepetitive = false; + if (method.isAnnotationPresent(FlakyTest.class)) { + runCount = method.getAnnotation(FlakyTest.class).tolerance(); + } else if (method.isAnnotationPresent(RepetitiveTest.class)) { + runCount = method.getAnnotation(RepetitiveTest.class).numIterations(); + isRepetitive = true; + } + + if (method.isAnnotationPresent(UiThreadTest.class)) { + final int tolerance = runCount; + final boolean repetitive = isRepetitive; + final Method testMethod = method; + final Throwable[] exceptions = new Throwable[1]; + getInstrumentation().runOnMainSync(new Runnable() { + public void run() { + try { + runMethod(testMethod, tolerance, repetitive); + } catch (Throwable throwable) { + exceptions[0] = throwable; + } + } + }); + if (exceptions[0] != null) { + throw exceptions[0]; + } + } else if (method.isAnnotationPresent(BandwidthTest.class) || + testClass.isAnnotationPresent(BandwidthTest.class)) { + /** + * If bandwidth profiling fails for whatever reason the test + * should be allow to execute to its completion. + * Typically bandwidth profiling would fail when a lower level + * component is missing, such as the kernel module, for a newly + * introduced hardware. + */ + try{ + TrafficStats.startDataProfiling(null); + } catch(IllegalStateException isx){ + Log.w(TAG, "Failed to start bandwidth profiling"); + } + runMethod(method, 1, false); + try{ + NetworkStats stats = TrafficStats.stopDataProfiling(null); + NetworkStats.Entry entry = stats.getTotal(null); + getInstrumentation().sendStatus(2, getBandwidthStats(entry)); + } catch (IllegalStateException isx){ + Log.w(TAG, "Failed to collect bandwidth stats"); + } + } else { + runMethod(method, runCount, isRepetitive); + } + } + + private void runMethod(Method runMethod, int tolerance, boolean isRepetitive) throws Throwable { + //This is a copy of {@link InstrumentationTestCase#runMethod} + Throwable exception = null; + + int runCount = 0; + do { + try { + runMethod.invoke(this, (Object[]) null); + exception = null; + } catch (InvocationTargetException e) { + e.fillInStackTrace(); + exception = e.getTargetException(); + } catch (IllegalAccessException e) { + e.fillInStackTrace(); + exception = e; + } finally { + runCount++; + // Report current iteration number, if test is repetitive + if (isRepetitive) { + Bundle iterations = new Bundle(); + iterations.putInt("currentiterations", runCount); + getInstrumentation().sendStatus(2, iterations); + } + } + } while ((runCount < tolerance) && (isRepetitive || exception != null)); + + if (exception != null) { + throw exception; + } + } + + private Bundle getBandwidthStats(NetworkStats.Entry entry){ + Bundle bundle = new Bundle(); + bundle.putLong(REPORT_KEY_BYTES_RECEIVED, entry.rxBytes); + bundle.putLong(REPORT_KEY_BYTES_SENT, entry.txBytes); + bundle.putLong(REPORT_KEY_PACKETS_RECEIVED, entry.rxPackets); + bundle.putLong(REPORT_KEY_PACKETS_SENT, entry.txPackets); + bundle.putLong(REPORT_KEY_OPERATIONS, entry.operations); + return bundle; + } +} + diff --git a/core/tests/utillib/src/coretestutils/http/MockResponse.java b/core/tests/utillib/src/coretestutils/http/MockResponse.java deleted file mode 100644 index 5b03e5f..0000000 --- a/core/tests/utillib/src/coretestutils/http/MockResponse.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (C) 2010 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 coretestutils.http; - -import static coretestutils.http.MockWebServer.ASCII; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import android.util.Log; - -/** - * A scripted response to be replayed by the mock web server. - */ -public class MockResponse { - private static final byte[] EMPTY_BODY = new byte[0]; - static final String LOG_TAG = "coretestutils.http.MockResponse"; - - private String status = "HTTP/1.1 200 OK"; - private Map<String, String> headers = new HashMap<String, String>(); - private byte[] body = EMPTY_BODY; - private boolean closeConnectionAfter = false; - private String closeConnectionAfterHeader = null; - private int closeConnectionAfterXBytes = -1; - private int pauseConnectionAfterXBytes = -1; - private File bodyExternalFile = null; - - public MockResponse() { - addHeader("Content-Length", 0); - } - - /** - * Returns the HTTP response line, such as "HTTP/1.1 200 OK". - */ - public String getStatus() { - return status; - } - - public MockResponse setResponseCode(int code) { - this.status = "HTTP/1.1 " + code + " OK"; - return this; - } - - /** - * Returns the HTTP headers, such as "Content-Length: 0". - */ - public List<String> getHeaders() { - List<String> headerStrings = new ArrayList<String>(); - for (String header : headers.keySet()) { - headerStrings.add(header + ": " + headers.get(header)); - } - return headerStrings; - } - - public MockResponse addHeader(String header, String value) { - headers.put(header.toLowerCase(), value); - return this; - } - - public MockResponse addHeader(String header, long value) { - return addHeader(header, Long.toString(value)); - } - - public MockResponse removeHeader(String header) { - headers.remove(header.toLowerCase()); - return this; - } - - /** - * Returns true if the body should come from an external file, false otherwise. - */ - private boolean bodyIsExternal() { - return bodyExternalFile != null; - } - - /** - * Returns an input stream containing the raw HTTP payload. - */ - public InputStream getBody() { - if (bodyIsExternal()) { - try { - return new FileInputStream(bodyExternalFile); - } catch (FileNotFoundException e) { - Log.e(LOG_TAG, "File not found: " + bodyExternalFile.getAbsolutePath()); - } - } - return new ByteArrayInputStream(this.body); - } - - public MockResponse setBody(File body) { - addHeader("Content-Length", body.length()); - this.bodyExternalFile = body; - return this; - } - - public MockResponse setBody(byte[] body) { - addHeader("Content-Length", body.length); - this.body = body; - return this; - } - - public MockResponse setBody(String body) { - try { - return setBody(body.getBytes(ASCII)); - } catch (UnsupportedEncodingException e) { - throw new AssertionError(); - } - } - - /** - * Sets the body as chunked. - * - * Currently chunked body is not supported for external files as bodies. - */ - public MockResponse setChunkedBody(byte[] body, int maxChunkSize) throws IOException { - addHeader("Transfer-encoding", "chunked"); - - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - int pos = 0; - while (pos < body.length) { - int chunkSize = Math.min(body.length - pos, maxChunkSize); - bytesOut.write(Integer.toHexString(chunkSize).getBytes(ASCII)); - bytesOut.write("\r\n".getBytes(ASCII)); - bytesOut.write(body, pos, chunkSize); - bytesOut.write("\r\n".getBytes(ASCII)); - pos += chunkSize; - } - bytesOut.write("0\r\n".getBytes(ASCII)); - this.body = bytesOut.toByteArray(); - return this; - } - - public MockResponse setChunkedBody(String body, int maxChunkSize) throws IOException { - return setChunkedBody(body.getBytes(ASCII), maxChunkSize); - } - - @Override public String toString() { - return status; - } - - public boolean shouldCloseConnectionAfter() { - return closeConnectionAfter; - } - - public MockResponse setCloseConnectionAfter(boolean closeConnectionAfter) { - this.closeConnectionAfter = closeConnectionAfter; - return this; - } - - /** - * Sets the header after which sending the server should close the connection. - */ - public MockResponse setCloseConnectionAfterHeader(String header) { - closeConnectionAfterHeader = header; - setCloseConnectionAfter(true); - return this; - } - - /** - * Returns the header after which sending the server should close the connection. - */ - public String getCloseConnectionAfterHeader() { - return closeConnectionAfterHeader; - } - - /** - * Sets the number of bytes in the body to send before which the server should close the - * connection. Set to -1 to unset and send the entire body (default). - */ - public MockResponse setCloseConnectionAfterXBytes(int position) { - closeConnectionAfterXBytes = position; - setCloseConnectionAfter(true); - return this; - } - - /** - * Returns the number of bytes in the body to send before which the server should close the - * connection. Returns -1 if the entire body should be sent (default). - */ - public int getCloseConnectionAfterXBytes() { - return closeConnectionAfterXBytes; - } - - /** - * Sets the number of bytes in the body to send before which the server should pause the - * connection (stalls in sending data). Only one pause per response is supported. - * Set to -1 to unset pausing (default). - */ - public MockResponse setPauseConnectionAfterXBytes(int position) { - pauseConnectionAfterXBytes = position; - return this; - } - - /** - * Returns the number of bytes in the body to send before which the server should pause the - * connection (stalls in sending data). (Returns -1 if it should not pause). - */ - public int getPauseConnectionAfterXBytes() { - return pauseConnectionAfterXBytes; - } - - /** - * Returns true if this response is flagged to pause the connection mid-stream, false otherwise - */ - public boolean getShouldPause() { - return (pauseConnectionAfterXBytes != -1); - } - - /** - * Returns true if this response is flagged to close the connection mid-stream, false otherwise - */ - public boolean getShouldClose() { - return (closeConnectionAfterXBytes != -1); - } -} diff --git a/core/tests/utillib/src/coretestutils/http/MockWebServer.java b/core/tests/utillib/src/coretestutils/http/MockWebServer.java deleted file mode 100644 index c329ffa..0000000 --- a/core/tests/utillib/src/coretestutils/http/MockWebServer.java +++ /dev/null @@ -1,426 +0,0 @@ -/* - * Copyright (C) 2010 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 coretestutils.http; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.URL; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import android.util.Log; - -/** - * A scriptable web server. Callers supply canned responses and the server - * replays them upon request in sequence. - * - * TODO: merge with the version from libcore/support/src/tests/java once it's in. - */ -public final class MockWebServer { - static final String ASCII = "US-ASCII"; - static final String LOG_TAG = "coretestutils.http.MockWebServer"; - - private final BlockingQueue<RecordedRequest> requestQueue - = new LinkedBlockingQueue<RecordedRequest>(); - private final BlockingQueue<MockResponse> responseQueue - = new LinkedBlockingQueue<MockResponse>(); - private int bodyLimit = Integer.MAX_VALUE; - private final ExecutorService executor = Executors.newCachedThreadPool(); - // keep Futures around so we can rethrow any exceptions thrown by Callables - private final Queue<Future<?>> futures = new LinkedList<Future<?>>(); - private final Object downloadPauseLock = new Object(); - // global flag to signal when downloads should resume on the server - private volatile boolean downloadResume = false; - - private int port = -1; - - public int getPort() { - if (port == -1) { - throw new IllegalStateException("Cannot retrieve port before calling play()"); - } - return port; - } - - /** - * Returns a URL for connecting to this server. - * - * @param path the request path, such as "/". - */ - public URL getUrl(String path) throws MalformedURLException { - return new URL("http://localhost:" + getPort() + path); - } - - /** - * Sets the number of bytes of the POST body to keep in memory to the given - * limit. - */ - public void setBodyLimit(int maxBodyLength) { - this.bodyLimit = maxBodyLength; - } - - public void enqueue(MockResponse response) { - responseQueue.add(response); - } - - /** - * Awaits the next HTTP request, removes it, and returns it. Callers should - * use this to verify the request sent was as intended. - */ - public RecordedRequest takeRequest() throws InterruptedException { - return requestQueue.take(); - } - - public RecordedRequest takeRequestWithTimeout(long timeoutMillis) throws InterruptedException { - return requestQueue.poll(timeoutMillis, TimeUnit.MILLISECONDS); - } - - public List<RecordedRequest> drainRequests() { - List<RecordedRequest> requests = new ArrayList<RecordedRequest>(); - requestQueue.drainTo(requests); - return requests; - } - - /** - * Starts the server, serves all enqueued requests, and shuts the server - * down using the default (server-assigned) port. - */ - public void play() throws IOException { - play(0); - } - - /** - * Starts the server, serves all enqueued requests, and shuts the server - * down. - * - * @param port The port number to use to listen to connections on; pass in 0 to have the - * server automatically assign a free port - */ - public void play(int portNumber) throws IOException { - final ServerSocket ss = new ServerSocket(portNumber); - ss.setReuseAddress(true); - port = ss.getLocalPort(); - submitCallable(new Callable<Void>() { - public Void call() throws Exception { - int count = 0; - while (true) { - if (count > 0 && responseQueue.isEmpty()) { - ss.close(); - executor.shutdown(); - return null; - } - - serveConnection(ss.accept()); - count++; - } - } - }); - } - - private void serveConnection(final Socket s) { - submitCallable(new Callable<Void>() { - public Void call() throws Exception { - InputStream in = new BufferedInputStream(s.getInputStream()); - OutputStream out = new BufferedOutputStream(s.getOutputStream()); - - int sequenceNumber = 0; - while (true) { - RecordedRequest request = readRequest(in, sequenceNumber); - if (request == null) { - if (sequenceNumber == 0) { - throw new IllegalStateException("Connection without any request!"); - } else { - break; - } - } - requestQueue.add(request); - MockResponse response = computeResponse(request); - writeResponse(out, response); - if (response.shouldCloseConnectionAfter()) { - break; - } - sequenceNumber++; - } - - in.close(); - out.close(); - return null; - } - }); - } - - private void submitCallable(Callable<?> callable) { - Future<?> future = executor.submit(callable); - futures.add(future); - } - - /** - * Check for and raise any exceptions that have been thrown by child threads. Will not block on - * children still running. - * @throws ExecutionException for the first child thread that threw an exception - */ - public void checkForExceptions() throws ExecutionException, InterruptedException { - final int originalSize = futures.size(); - for (int i = 0; i < originalSize; i++) { - Future<?> future = futures.remove(); - try { - future.get(0, TimeUnit.SECONDS); - } catch (TimeoutException e) { - futures.add(future); // still running - } - } - } - - /** - * @param sequenceNumber the index of this request on this connection. - */ - private RecordedRequest readRequest(InputStream in, int sequenceNumber) throws IOException { - String request = readAsciiUntilCrlf(in); - if (request.equals("")) { - return null; // end of data; no more requests - } - - List<String> headers = new ArrayList<String>(); - int contentLength = -1; - boolean chunked = false; - String header; - while (!(header = readAsciiUntilCrlf(in)).equals("")) { - headers.add(header); - String lowercaseHeader = header.toLowerCase(); - if (contentLength == -1 && lowercaseHeader.startsWith("content-length:")) { - contentLength = Integer.parseInt(header.substring(15).trim()); - } - if (lowercaseHeader.startsWith("transfer-encoding:") && - lowercaseHeader.substring(18).trim().equals("chunked")) { - chunked = true; - } - } - - boolean hasBody = false; - TruncatingOutputStream requestBody = new TruncatingOutputStream(); - List<Integer> chunkSizes = new ArrayList<Integer>(); - if (contentLength != -1) { - hasBody = true; - transfer(contentLength, in, requestBody); - } else if (chunked) { - hasBody = true; - while (true) { - int chunkSize = Integer.parseInt(readAsciiUntilCrlf(in).trim(), 16); - if (chunkSize == 0) { - readEmptyLine(in); - break; - } - chunkSizes.add(chunkSize); - transfer(chunkSize, in, requestBody); - readEmptyLine(in); - } - } - - if (request.startsWith("GET ")) { - if (hasBody) { - throw new IllegalArgumentException("GET requests should not have a body!"); - } - } else if (request.startsWith("POST ")) { - if (!hasBody) { - throw new IllegalArgumentException("POST requests must have a body!"); - } - } else { - throw new UnsupportedOperationException("Unexpected method: " + request); - } - - return new RecordedRequest(request, headers, chunkSizes, - requestBody.numBytesReceived, requestBody.toByteArray(), sequenceNumber); - } - - /** - * Returns a response to satisfy {@code request}. - */ - private MockResponse computeResponse(RecordedRequest request) throws InterruptedException { - if (responseQueue.isEmpty()) { - throw new IllegalStateException("Unexpected request: " + request); - } - return responseQueue.take(); - } - - private void writeResponse(OutputStream out, MockResponse response) throws IOException { - out.write((response.getStatus() + "\r\n").getBytes(ASCII)); - boolean doCloseConnectionAfterHeader = (response.getCloseConnectionAfterHeader() != null); - - // Send headers - String closeConnectionAfterHeader = response.getCloseConnectionAfterHeader(); - for (String header : response.getHeaders()) { - out.write((header + "\r\n").getBytes(ASCII)); - - if (doCloseConnectionAfterHeader && header.startsWith(closeConnectionAfterHeader)) { - Log.i(LOG_TAG, "Closing connection after header" + header); - break; - } - } - - // Send actual body data - if (!doCloseConnectionAfterHeader) { - out.write(("\r\n").getBytes(ASCII)); - - InputStream body = response.getBody(); - final int READ_BLOCK_SIZE = 10000; // process blocks this size - byte[] currentBlock = new byte[READ_BLOCK_SIZE]; - int currentBlockSize = 0; - int writtenSoFar = 0; - - boolean shouldPause = response.getShouldPause(); - boolean shouldClose = response.getShouldClose(); - int pause = response.getPauseConnectionAfterXBytes(); - int close = response.getCloseConnectionAfterXBytes(); - - // Don't bother pausing if it's set to pause -after- the connection should be dropped - if (shouldPause && shouldClose && (pause > close)) { - shouldPause = false; - } - - // Process each block we read in... - while ((currentBlockSize = body.read(currentBlock)) != -1) { - int startIndex = 0; - int writeLength = currentBlockSize; - - // handle the case of pausing - if (shouldPause && (writtenSoFar + currentBlockSize >= pause)) { - writeLength = pause - writtenSoFar; - out.write(currentBlock, 0, writeLength); - out.flush(); - writtenSoFar += writeLength; - - // now pause... - try { - Log.i(LOG_TAG, "Pausing connection after " + pause + " bytes"); - // Wait until someone tells us to resume sending... - synchronized(downloadPauseLock) { - while (!downloadResume) { - downloadPauseLock.wait(); - } - // reset resume back to false - downloadResume = false; - } - } catch (InterruptedException e) { - Log.e(LOG_TAG, "Server was interrupted during pause in download."); - } - - startIndex = writeLength; - writeLength = currentBlockSize - writeLength; - } - - // handle the case of closing the connection - if (shouldClose && (writtenSoFar + writeLength > close)) { - writeLength = close - writtenSoFar; - out.write(currentBlock, startIndex, writeLength); - writtenSoFar += writeLength; - Log.i(LOG_TAG, "Closing connection after " + close + " bytes"); - break; - } - out.write(currentBlock, startIndex, writeLength); - writtenSoFar += writeLength; - } - } - out.flush(); - } - - /** - * Transfer bytes from {@code in} to {@code out} until either {@code length} - * bytes have been transferred or {@code in} is exhausted. - */ - private void transfer(int length, InputStream in, OutputStream out) throws IOException { - byte[] buffer = new byte[1024]; - while (length > 0) { - int count = in.read(buffer, 0, Math.min(buffer.length, length)); - if (count == -1) { - return; - } - out.write(buffer, 0, count); - length -= count; - } - } - - /** - * Returns the text from {@code in} until the next "\r\n", or null if - * {@code in} is exhausted. - */ - private String readAsciiUntilCrlf(InputStream in) throws IOException { - StringBuilder builder = new StringBuilder(); - while (true) { - int c = in.read(); - if (c == '\n' && builder.length() > 0 && builder.charAt(builder.length() - 1) == '\r') { - builder.deleteCharAt(builder.length() - 1); - return builder.toString(); - } else if (c == -1) { - return builder.toString(); - } else { - builder.append((char) c); - } - } - } - - private void readEmptyLine(InputStream in) throws IOException { - String line = readAsciiUntilCrlf(in); - if (!line.equals("")) { - throw new IllegalStateException("Expected empty but was: " + line); - } - } - - /** - * An output stream that drops data after bodyLimit bytes. - */ - private class TruncatingOutputStream extends ByteArrayOutputStream { - private int numBytesReceived = 0; - @Override public void write(byte[] buffer, int offset, int len) { - numBytesReceived += len; - super.write(buffer, offset, Math.min(len, bodyLimit - count)); - } - @Override public void write(int oneByte) { - numBytesReceived++; - if (count < bodyLimit) { - super.write(oneByte); - } - } - } - - /** - * Trigger the server to resume sending the download - */ - public void doResumeDownload() { - synchronized (downloadPauseLock) { - downloadResume = true; - downloadPauseLock.notifyAll(); - } - } -} diff --git a/core/tests/utillib/src/coretestutils/http/RecordedRequest.java b/core/tests/utillib/src/coretestutils/http/RecordedRequest.java deleted file mode 100644 index 293ff80..0000000 --- a/core/tests/utillib/src/coretestutils/http/RecordedRequest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2010 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 coretestutils.http; - -import java.util.List; - -/** - * An HTTP request that came into the mock web server. - */ -public final class RecordedRequest { - private final String requestLine; - private final List<String> headers; - private final List<Integer> chunkSizes; - private final int bodySize; - private final byte[] body; - private final int sequenceNumber; - - RecordedRequest(String requestLine, List<String> headers, List<Integer> chunkSizes, - int bodySize, byte[] body, int sequenceNumber) { - this.requestLine = requestLine; - this.headers = headers; - this.chunkSizes = chunkSizes; - this.bodySize = bodySize; - this.body = body; - this.sequenceNumber = sequenceNumber; - } - - public String getRequestLine() { - return requestLine; - } - - public List<String> getHeaders() { - return headers; - } - - /** - * Returns the sizes of the chunks of this request's body, or an empty list - * if the request's body was empty or unchunked. - */ - public List<Integer> getChunkSizes() { - return chunkSizes; - } - - /** - * Returns the total size of the body of this POST request (before - * truncation). - */ - public int getBodySize() { - return bodySize; - } - - /** - * Returns the body of this POST request. This may be truncated. - */ - public byte[] getBody() { - return body; - } - - /** - * Returns the index of this request on its HTTP connection. Since a single - * HTTP connection may serve multiple requests, each request is assigned its - * own sequence number. - */ - public int getSequenceNumber() { - return sequenceNumber; - } - - @Override public String toString() { - return requestLine; - } - - public String getMethod() { - return getRequestLine().split(" ")[0]; - } - - public String getPath() { - return getRequestLine().split(" ")[1]; - } -} |