Merge "Add more instruction on app UI." into lmp-dev
diff --git a/CtsTestCaseList.mk b/CtsTestCaseList.mk
index c052a71..a3ca867 100644
--- a/CtsTestCaseList.mk
+++ b/CtsTestCaseList.mk
@@ -39,6 +39,7 @@
CtsDeviceUi \
CtsMonkeyApp \
CtsMonkeyApp2 \
+ CtsProfileOwnerApp \
CtsSomeAccessibilityServices \
CtsTestStubs \
CtsThemeDeviceApp \
@@ -113,7 +114,6 @@
CtsSaxTestCases \
CtsSecurityTestCases \
CtsSpeechTestCases \
- CtsTelecomTestCases \
CtsTelephonyTestCases \
CtsTextTestCases \
CtsTextureViewTestCases \
@@ -136,6 +136,7 @@
cts_host_libraries := \
CtsAdbTests \
CtsAppSecurityTests \
+ CtsDevicePolicyManagerTestCases \
CtsHostJank \
CtsHostUi \
CtsMonkeyTestCases \
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index e151325..d4676d9 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -47,7 +47,6 @@
<uses-feature android:name="android.hardware.usb.accessory" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
- <uses-feature android:name="android.software.connectionservice" android:required="false" />
<!-- Needed by the Audio Quality Verifier to store the sound samples that will be mailed. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
@@ -633,14 +632,28 @@
<meta-data android:name="android.nfc.cardemulation.off_host_apdu_service" android:resource="@xml/offhost_aid_list"/>
</service>
- <activity android:name=".sensors.AccelerometerTestActivity" android:label="@string/snsr_accel_test"
+ <!--
+ A DeviceAdmin receiver for sensor tests, it allows sensor tests to turn off the screen.
+ -->
+ <receiver android:name=".sensors.helpers.SensorDeviceAdminReceiver"
+ android:label="@string/snsr_device_admin_receiver">
+ <meta-data android:name="android.app.device_admin"
+ android:resource="@xml/sensor_device_admin" />
+ <intent-filter>
+ <action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
+ </intent-filter>
+ </receiver>
+
+ <activity android:name=".sensors.AccelerometerTestActivity"
+ android:label="@string/snsr_accel_test"
android:screenOrientation="nosensor">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.cts.intent.category.MANUAL_TEST" />
</intent-filter>
<meta-data android:name="test_category" android:value="@string/test_category_sensors" />
- <meta-data android:name="test_required_features" android:value="android.hardware.sensor.accelerometer" />
+ <meta-data android:name="test_required_features"
+ android:value="android.hardware.sensor.accelerometer" />
</activity>
<activity android:name=".sensors.AccelerometerMeasurementTestActivity"
@@ -662,7 +675,8 @@
<category android:name="android.cts.intent.category.MANUAL_TEST" />
</intent-filter>
<meta-data android:name="test_category" android:value="@string/test_category_sensors" />
- <meta-data android:name="test_required_features" android:value="android.hardware.sensor.gyroscope" />
+ <meta-data android:name="test_required_features"
+ android:value="android.hardware.sensor.gyroscope" />
</activity>
<activity android:name=".sensors.GyroscopeMeasurementTestActivity"
@@ -1149,67 +1163,6 @@
android:label="@string/projection_service_name"
android:process=":projectionservice" />
- <activity android:name=".telecom.TelecomTestActivity"
- android:label="@string/telecom_test_title">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.cts.intent.category.MANUAL_TEST" />
- </intent-filter>
- <meta-data android:name="test_category" android:value="@string/test_category_telecom" />
- <meta-data android:name="test_required_features" android:value="android.software.connectionservice"/>
- </activity>
-
- <activity android:name=".telecom.CancelCallTestActivity"
- android:label="@string/telecom_cancel_call_title">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.cts.intent.category.MANUAL_TEST" />
- </intent-filter>
- <meta-data android:name="test_category" android:value="@string/test_category_telecom" />
- <meta-data android:name="test_parent" android:value="com.android.cts.verifier.telecom.TelecomTestActivity" />
- </activity>
-
- <service android:name=".telecom.CancelCallTestActivity$ConnectionService"
- android:permission="android.permission.BIND_CONNECTION_SERVICE">
- <intent-filter>
- <action android:name="android.telecom.ConnectionService" />
- </intent-filter>
- </service>
-
- <activity android:name=".telecom.FailedCallTestActivity"
- android:label="@string/telecom_failed_call_title">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.cts.intent.category.MANUAL_TEST" />
- </intent-filter>
- <meta-data android:name="test_category" android:value="@string/test_category_telecom" />
- <meta-data android:name="test_parent" android:value="com.android.cts.verifier.telecom.TelecomTestActivity" />
- </activity>
-
- <service android:name=".telecom.FailedCallTestActivity$ConnectionService"
- android:permission="android.permission.BIND_CONNECTION_SERVICE">
- <intent-filter>
- <action android:name="android.telecom.ConnectionService" />
- </intent-filter>
- </service>
-
- <activity android:name=".telecom.BasicCallTestActivity"
- android:label="@string/telecom_basic_call_title">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.cts.intent.category.MANUAL_TEST" />
- </intent-filter>
- <meta-data android:name="test_category" android:value="@string/test_category_telecom" />
- <meta-data android:name="test_parent" android:value="com.android.cts.verifier.telecom.TelecomTestActivity" />
- </activity>
-
- <service android:name=".telecom.BasicCallTestActivity$ConnectionService"
- android:permission="android.permission.BIND_CONNECTION_SERVICE">
- <intent-filter>
- <action android:name="android.telecom.ConnectionService" />
- </intent-filter>
- </service>
-
</application>
</manifest>
diff --git a/apps/CtsVerifier/assets/scripts/execute_power_tests.py b/apps/CtsVerifier/assets/scripts/execute_power_tests.py
index 68e13db..e1b11c2 100755
--- a/apps/CtsVerifier/assets/scripts/execute_power_tests.py
+++ b/apps/CtsVerifier/assets/scripts/execute_power_tests.py
@@ -30,10 +30,10 @@
signal_exit_q = Queue.Queue()
signal_abort = Queue.Queue()
-# let this script know about the power monitor impementations
+# let this script know about the power monitor implementations
sys.path = [os.path.basename(__file__)] + sys.path
-available_monitors = [name for _, name, _ in pkgutil.iter_modules([os.path.join(os.path.dirname(__file__),'power_monitors')])
- if not name.startswith('_')]
+available_monitors = [name for _, name, _ in pkgutil.iter_modules(
+ [os.path.join(os.path.dirname(__file__),'power_monitors')]) if not name.startswith('_')]
APK = os.path.join( os.path.dirname(__file__), '..', "CtsVerifier.apk")
@@ -77,18 +77,28 @@
SAMPLE_COUNT_NOMINAL = 1000
RATE_NOMINAL = 100
- QUERY_EXTERNAL_STORAGE = "EXTERNAL STORAGE?"
-
+ REQUEST_EXTERNAL_STORAGE = "EXTERNAL STORAGE?"
+ REQUEST_EXIT = "EXIT"
+ REQUEST_RAISE = "RAISE %s %s"
+ REQUEST_USER_RESPONSE = "USER RESPONSE %s"
+ REQUEST_SET_TEST_RESULT = "SET TEST RESULT %s %s %s"
+ REQUEST_SENSOR_SWITCH = "SENSOR %s %s"
+ REQUEST_SENSOR_AVAILABILITY = "SENSOR? %s"
+ REQUEST_SCREEN_OFF = "SCREEN OFF"
+ REQUEST_SHOW_MESSAGE = "MESSAGE %s"
+
+
def __init__(self):
power_monitors = do_import("power_monitors.%s" % FLAGS.power_monitor)
testid = time.strftime("%d_%m_%Y__%H__%M_%S")
self._power_monitor = power_monitors.Power_Monitor(log_file_id = testid)
print ("Establishing connection to device...")
- self.setUSBEnabled(True)
+ self.setUsbEnabled(True)
status = self._power_monitor.GetStatus()
self._native_hz = status["sampleRate"] * 1000
self._current_test = "None"
- self._external_storage = self.executeOnDevice(PowerTest.QUERY_EXTERNAL_STORAGE, reportErrors=True )
+ self._external_storage = self.executeOnDevice(PowerTest.REQUEST_EXTERNAL_STORAGE,
+ reportErrors=True)
def __del__(self):
self.finalize()
@@ -97,7 +107,7 @@
"""To be called upon termination of host connection to device"""
if PowerTest.PORT > 0:
# tell device side to exit connection loop, and remove the forwarding connection
- self.executeOnDevice("EXIT", reportErrors=False)
+ self.executeOnDevice(PowerTest.REQUEST_EXIT, reportErrors=False)
self.executeLocal("adb forward --remove tcp:%d" % PowerTest.PORT)
PowerTest.PORT = 0
if self._power_monitor:
@@ -105,18 +115,19 @@
self._power_monitor = None
def _send(self, msg, report_errors=True):
- """Connect to the device, send the given commmand, and then disconnect"""
+ """Connect to the device, send the given command, and then disconnect"""
if PowerTest.PORT == 0:
# on first attempt to send a command, connect to device via any open port number,
# forwarding that port to a local socket on the device via adb
logging.debug("Seeking port for communication...")
- # discover an open port
+ # discover an open port
dummysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dummysocket.bind(("localhost", 0))
(_, PowerTest.PORT) = dummysocket.getsockname()
dummysocket.close()
assert(PowerTest.PORT > 0)
- status = self.executeLocal("adb forward tcp:%d localabstract:%s" % (PowerTest.PORT, PowerTest.DOMAIN_NAME))
+ status = self.executeLocal("adb forward tcp:%d localabstract:%s" %
+ (PowerTest.PORT, PowerTest.DOMAIN_NAME))
if report_errors:
self.reportErrorIf(status != 0, msg="Unable to forward requests to client over adb")
logging.info("Forwarding requests over local port %d" % PowerTest.PORT)
@@ -139,11 +150,11 @@
return response
def queryDevice(self, query):
- """Post a yes/no query to the device, return True upon successful query,
- False otherwise"""
+ """Post a yes/no query to the device, return True upon successful query, False otherwise"""
logging.info("Querying device with '%s'" % query)
return self._send(query) == "OK"
+ # TODO: abstract device communication (and string commands) into its own class
def executeOnDevice(self, cmd , reportErrors=True):
"""Execute a (string) command on the remote device"""
return self._send(cmd , reportErrors)
@@ -164,7 +175,7 @@
if condition:
try:
logging.error("Exiting on error: %s" % msg)
- self.executeOnDevice("RAISE " + self._current_test + " " + msg , False)
+ self.executeOnDevice(PowerTest.REQUEST_RAISE % (self._current_test, msg), False)
except:
logging.error("Unable to communicate with device to report error: %s" % msg)
@@ -172,7 +183,7 @@
sys.exit(msg)
raise Exception(msg)
- def setUSBEnabled(self, enabled, verbose=True):
+ def setUsbEnabled(self, enabled, verbose=True):
if enabled:
val = 1
else:
@@ -180,7 +191,7 @@
self._power_monitor.SetUsbPassthrough(val)
tries = 0
- # Sometimes command won't go through first time, paricularly if immediately after a data
+ # Sometimes command won't go through first time, particularly if immediately after a data
# collection, so allow for retries
status = self._power_monitor.GetStatus()
while status is None and tries < 5:
@@ -199,7 +210,8 @@
if verbose: logging.info("...USB disabled")
# re-establish port forwarding
if enabled and PowerTest.PORT > 0:
- status = self.executeLocal("adb forward tcp:%d localabstract:%s" % (PowerTest.PORT, PowerTest.DOMAIN_NAME))
+ status = self.executeLocal("adb forward tcp:%d localabstract:%s" %
+ (PowerTest.PORT, PowerTest.DOMAIN_NAME))
self.reportErrorIf(status != 0, msg="Unable to forward requests to client over adb")
def waitForScreenOff(self):
@@ -211,13 +223,13 @@
# need at least 100 sequential clean low-power measurements to know screen is off
THRESHOLD_COUNT_LOW_POWER = 100
- CURRENT_LOW_POWER_THRESHOLD = 0.060 # mAmps
- TIMEOUT_SCREEN_OFF = 30 #this many tries at most
+ CURRENT_LOW_POWER_THRESHOLD = 0.060 # Amps
+ TIMEOUT_SCREEN_OFF = 30 # this many tries at most
count_good = 0
tries = 0
print("Waiting for screen off and application processor in suspend mode...")
while count_good < THRESHOLD_COUNT_LOW_POWER:
- measurements = self.collectMeasurements( THRESHOLD_COUNT_LOW_POWER,
+ measurements = self.collectMeasurements(THRESHOLD_COUNT_LOW_POWER,
PowerTest.RATE_NOMINAL,
ensure_screen_off=False,
verbose=False)
@@ -225,20 +237,19 @@
if m < CURRENT_LOW_POWER_THRESHOLD])
tries += 1
if count_good < THRESHOLD_COUNT_LOW_POWER and measurements:
- print("This current high: %.2f mAmps. Device is probably not in suspend mode. Waiting..."%\
+ print("Current usage: %.2f mAmps. Device is probably not in suspend mode. Waiting..." %
(1000.0*(sum(measurements)/len(measurements))))
if tries >= TIMEOUT_SCREEN_OFF:
# TODO: dump the state of sensor service to identify if there are features using sensors
- self.reportErrorIf(tries>=TIMEOUT_SCREEN_OFF, msg="Unable to determine application processor suspend mode status.")
+ self.reportErrorIf(tries>=TIMEOUT_SCREEN_OFF,
+ msg="Unable to determine application processor suspend mode status.")
break
if DELAY_SCREEN_OFF:
# add additional delay time if necessary
time.sleep(DELAY_SCREEN_OFF)
print("...Screen off and device in suspend mode.")
-
- def collectMeasurements(self, measurementCount, rate ,
- ensure_screen_off=True,
- verbose=True,
+
+ def collectMeasurements(self, measurementCount, rate , ensure_screen_off=True, verbose=True,
plot_data = False):
assert(measurementCount > 0)
decimate_by = self._native_hz / rate or 1
@@ -253,11 +264,10 @@
try:
while len(measurements) < measurementCount and tries < 5:
if tries:
- #logging.error("Failed attempt %d" % tries)
self._power_monitor.StopDataCollection()
self._power_monitor.StartDataCollection()
time.sleep(1.0)
- tries += 1
+ tries += 1
additional = self._power_monitor.CollectData()
if additional is not None:
tries = 0
@@ -278,7 +288,7 @@
def request_user_acknowledgment(self, msg):
"""Post message to user on screen and wait for acknowledgment"""
- response = self.executeOnDevice("REQUEST USER RESPONSE " + msg)
+ response = self.executeOnDevice(PowerTest.REQUEST_USER_RESPONSE % msg)
self.reportErrorIf(response != "OK", "Unable to request user acknowledgment")
def setTestResult (self, testname, condition, msg):
@@ -289,19 +299,21 @@
else:
val = condition
print ("Test %s : %s" % (testname, val))
- response = self.executeOnDevice("SET TEST RESULT %s %s %s" % (testname, val, msg))
+ response = self.executeOnDevice(PowerTest.REQUEST_SET_TEST_RESULT % (testname, val, msg))
self.reportErrorIf(response != "OK", "Unable to send test status to Verifier")
def setPowerOn(self, sensor, powered_on):
- response = self.executeOnDevice("SENSOR %s %s" % ({True:"ON", False:"OFF"}[powered_on], sensor))
- self.reportErrorIf(response == "ERR", "Unable to set sensor %s state"%sensor)
+ response = self.executeOnDevice(PowerTest.REQUEST_SENSOR_SWITCH %
+ ({True:"ON", False:"OFF"}[powered_on], sensor))
+ self.reportErrorIf(response == "ERR", "Unable to set sensor %s state" % sensor)
logging.info("Set %s %s" % (sensor, {True:"ON", False:"OFF"}[powered_on]))
return response
def runPowerTest(self, sensor, max_power_allowed, user_request = None):
if not signal_abort.empty():
sys.exit( signal_abort.get() )
- self._current_test = "%s_Power_Test_While_%s" % (sensor, {True:"Under_Motion", False:"Still"}[user_request is not None])
+ self._current_test = "%s_Power_Test_While_%s" % (sensor,
+ {True:"Under_Motion", False:"Still"}[user_request is not None])
try:
print ("\n\n---------------------------------")
if user_request is not None:
@@ -309,9 +321,10 @@
else:
print ("Running power test on %s while device is still." % sensor)
print ("---------------------------------")
- response = self.executeOnDevice("SENSOR? %s"%sensor)
+ response = self.executeOnDevice(PowerTest.REQUEST_SENSOR_AVAILABILITY % sensor)
if response == "UNAVAILABLE":
- self.setTestResult(self._current_test, condition="SKIPPED", msg="Sensor %s not available on this platform"%sensor)
+ self.setTestResult(self._current_test, condition="SKIPPED",
+ msg="Sensor %s not available on this platform"%sensor)
self.setPowerOn("ALL", False)
if response == "UNAVAILABLE":
self.setTestResult(self._current_test, condition="SKIPPED",
@@ -321,8 +334,8 @@
self.reportErrorIf(response != "OK", "Unable to set all sensor off")
if not signal_abort.empty():
sys.exit( signal_abort.get() )
- self.executeOnDevice("MESSAGE: \nPlease turn screen off or wait for screen to turn off. Do not interact with the device until screen is turned on again.")
- self.setUSBEnabled(False)
+ self.executeOnDevice(PowerTest.REQUEST_SCREEN_OFF)
+ self.setUsbEnabled(False)
print("Collecting background measurements...")
measurements = self.collectMeasurements( PowerTest.SAMPLE_COUNT_NOMINAL,
PowerTest.RATE_NOMINAL,
@@ -334,17 +347,16 @@
f.write( "%.4f\n"%m)
self.reportErrorIf(not measurements, "No background measurements could be taken")
backgnd = sum(measurements) / len(measurements)
- self.setUSBEnabled( True )
- self.setPowerOn( sensor, True )
+ self.setUsbEnabled(True)
+ self.setPowerOn(sensor, True)
if user_request is not None:
print("===========================================\n" +
"==> Please follow the instructions presented on the device\n" +
"==========================================="
)
self.request_user_acknowledgment(user_request)
- else:
- self.executeOnDevice("MESSAGE: Turn screen off or wait for screen to turn off and do not interact with the device until screen is turned on again.")
- self.setUSBEnabled(False)
+ self.executeOnDevice(PowerTest.REQUEST_SCREEN_OFF)
+ self.setUsbEnabled(False)
self.reportErrorIf(response != "OK", "Unable to set sensor %s ON" % sensor)
print ("Collecting sensor %s measurements" % sensor)
measurements = self.collectMeasurements(PowerTest.SAMPLE_COUNT_NOMINAL,
@@ -355,11 +367,13 @@
{True:"Under_Motion", False:"Still"}[user_request is not None] ),'w') as f:
for m in measurements:
f.write( "%.4f\n"%m)
- self.setUSBEnabled(True, verbose = False)
+ self.setUsbEnabled(True, verbose = False)
print("Saving raw data files to device...")
- self.executeLocal("adb shell mkdir -p %s/ctsVerifierData/sensor_power_test_data"%self._external_storage, False)
- self.executeLocal("adb push %s %s/ctsVerifierData/sensor_power_test_data/."%(f.name, self._external_storage))
- self.setUSBEnabled(False, verbose = False)
+ self.executeLocal("adb shell mkdir -p %s/ctsVerifierData/sensor_power_test_data"
+ % self._external_storage, False)
+ self.executeLocal("adb push %s %s/ctsVerifierData/sensor_power_test_data/." %
+ (f.name, self._external_storage))
+ self.setUsbEnabled(False, verbose = False)
self.reportErrorIf(not measurements, "No measurements could be taken for %s" % sensor)
avg = sum(measurements) / len(measurements)
squared = [(m-avg)*(m-avg) for m in measurements]
@@ -367,7 +381,7 @@
import math
stddev = math.sqrt(sum(squared)/len(squared))
current_diff = avg - backgnd
- self.setUSBEnabled(True)
+ self.setUsbEnabled(True)
max_power = max(measurements) - avg
if current_diff <= max_power_allowed:
# TODO: fail the test of background > current
@@ -383,27 +397,24 @@
except:
import traceback
traceback.print_exc()
- self.setTestResult(self._current_test, condition="FAIL", msg="Exception occurred during run of test.")
+ self.setTestResult(self._current_test, condition="FAIL",
+ msg="Exception occurred during run of test.")
@staticmethod
def run_tests():
testrunner = None
try:
- GENERIC_MOTION_REQUEST = "\n===> Please press Next and when the screen is off, keep the device under motion with only tiny, slow movements" + \
- " until the screen turns on again.\n" + \
- "Please refrain from interacting with the screen or pressing any side buttons " + \
- "while measurements are taken."
- USER_STEPS_REQUEST = "\n===> Please press Next and when the screen is off, then move the device to simulate step motion" + \
- " until the screen turns on again.\n" + \
- "Please refrain from interacting with the screen or pressing any side buttons " + \
- "while measurements are taken."
+ GENERIC_MOTION_REQUEST = "\n===> Please press Next and when the screen is off, keep " + \
+ "the device under motion with only tiny, slow movements until the screen turns " + \
+ "on again.\nPlease refrain from interacting with the screen or pressing any side " + \
+ "buttons while measurements are taken."
+ USER_STEPS_REQUEST = "\n===> Please press Next and when the screen is off, then move " + \
+ "the device to simulate step motion until the screen turns on again.\nPlease " + \
+ "refrain from interacting with the screen or pressing any side buttons while " + \
+ "measurements are taken."
testrunner = PowerTest()
- testrunner.reportErrorIf(not testrunner.queryDevice("AIRPLANE MODE ON?"),
- "Airplane mode not off as expected")
- #testrunner.reportErrorIf(int(testrunner.executeOnDevice("SCREEN OFF TIMEOUT?")) > 15000,
- # "Screen sleep time not set to 15 seconds")
- testrunner.executeOnDevice("MESSAGE: Connected. Running tests...")
+ testrunner.executeOnDevice(PowerTest.REQUEST_SHOW_MESSAGE % "Connected. Running tests...")
testrunner.runPowerTest("SIGNIFICANT_MOTION", PowerTest.MAX_SIGMO_POWER, user_request = GENERIC_MOTION_REQUEST)
testrunner.runPowerTest("STEP_DETECTOR", PowerTest.MAX_STEP_DETECTOR_POWER, user_request = USER_STEPS_REQUEST)
testrunner.runPowerTest("STEP_COUNTER", PowerTest.MAX_STEP_COUNTER_POWER, user_request = USER_STEPS_REQUEST)
@@ -426,9 +437,10 @@
try:
testrunner.finalize()
except socket.error:
- sys.exit("============================\nUnable to connect to device under test. Make sure the device is connected via the usb passthrough,"+\
- " the CtsVerifier app is running the SensorPowerTest on the device, and USB passthrough is enabled."
- "\n===========================")
+ sys.exit("============================\nUnable to connect to device under " + \
+ "test. Make sure the device is connected via the usb pass-through, " + \
+ "the CtsVerifier app is running the SensorPowerTest on the device, " + \
+ "and USB pass-through is enabled.\n===========================")
def main(argv):
@@ -455,9 +467,8 @@
sys.exit("Aborting.")
if not FLAGS.power_monitor:
- sys.exit("You must specify a '--power_monitor' option to specify which power monitor type you are using.\n"+
- "One of:\n " +
- "\n ".join(available_monitors))
+ sys.exit("You must specify a '--power_monitor' option to specify which power monitor type " + \
+ "you are using.\nOne of:\n \n ".join(available_monitors))
power_monitors = do_import('power_monitors.%s' % FLAGS.power_monitor)
try:
mon = power_monitors.Power_Monitor(device=FLAGS.device)
@@ -489,7 +500,7 @@
mon.SetUsbPassthrough(2)
else:
mon.Close()
- sys.exit('bad passthrough flag: %s' % FLAGS.usbpassthrough)
+ sys.exit('bad pass-through flag: %s' % FLAGS.usbpassthrough)
if FLAGS.samples:
# Make sure state is normal
diff --git a/apps/CtsVerifier/res/layout/telecom_test_activity.xml b/apps/CtsVerifier/res/layout/telecom_test_activity.xml
deleted file mode 100644
index 9ca7cde..0000000
--- a/apps/CtsVerifier/res/layout/telecom_test_activity.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:padding="10dip" >
- <Button android:id="@+id/open_settings"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/telecom_open_settings" />
- <EditText android:id="@+id/phone_number"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/telecom_default_phone_number"
- android:hint="@string/telecom_phone_number_hint" />
- <Button android:id="@+id/simulate_call"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/telecom_simulate_call" />
- <include layout="@layout/pass_fail_buttons" />
-</LinearLayout>
\ No newline at end of file
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 33f6af1..df0db72 100644
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -431,6 +431,7 @@
<string name="offhostService">OffhostService</string>
<!-- Strings for Sensor Test Activities -->
+ <string name="snsr_device_admin_receiver">Sensor Tests Device Admin Receiver</string>
<string name="snsr_test_summary">Tests passed: %1$d, Tests skipped: %2$d, Tests failed: %3$d</string>
<string name="snsr_test_complete">Test completed.</string>
<string name="snsr_test_pass">PASS</string>
@@ -507,7 +508,8 @@
<string name="snsr_mag_verify_std_dev">Verifying the Standard Deviation...</string>
<string name="snsr_mag_calibration_description">Please calibrate the Magnetometer by moving
it in 8 shapes in different orientations.</string>
- <string name="snsr_mag_calibration_complete">When done, leave the device in a flat surface.</string>
+ <string name="snsr_mag_calibration_complete">When done, leave the device in a flat surface, far
+ from all metallic objects (if the test does not pass, try re-running it outdoors).</string>
<!-- Sensor Value Accuracy -->
<string name="snsr_val_acc_test">Sensor Value Accuracy Tests</string>
@@ -552,7 +554,7 @@
<string name="snsr_significant_motion_test_in_hand">Once you begin the test, hold the device in your hand while you perform natural hand movements.</string>
<string name="snsr_significant_motion_test_sitting">Once you begin the test, keep the device in your pocket and move naturally while sitting in a chair.</string>
<string name="snsr_significant_motion_test_deactivation">Once you begin the test, you will need to walk to ensure Significant Motion triggers only once.</string>
- <string name="snsr_significant_motion_registration">Expected to be able to register for TriggerSensor. Found=%b.</string>
+ <string name="snsr_significant_motion_registration">Expected to be able to register for TriggerSensor. Found=%1$b.</string>
<string name="snsr_significant_motion_cancelation">Expected to be able to cancel TriggerSensor. Found=%b.</string>
<!-- Strings for Sensor CTS tests inside CtsVerifier -->
@@ -1126,29 +1128,4 @@
<string name="snsr_rotation_vector_set_final">Place the device back to the reference position.</string>
<string name="snsr_rotation_vector_verification">Angular deviation [%1$4.1f %2$4.1f %3$4.1f]. Current: %4$f deg. Max tolerated: %5$f.</string>
- <string name="test_category_telecom">Telecom</string>
- <string name="telecom_test_title">Telecom Tests</string>
- <string name="telecom_test_summary">These tests cover aspects of Telecom call routing.
- These tests may be run in any order, but each one will require user input before it can be run.
- </string>
- <string name="telecom_open_settings">Open settings</string>
- <string name="telecom_simulate_call">Place call</string>
- <string name="telecom_default_phone_number">555-263-7643</string>
- <string name="telecom_phone_number_hint">Phone number to call</string>
- <string name="telecom_cancel_call_title">Canceled Call Test</string>
- <string name="telecom_cancel_call_info">This tests to make sure that canceled calls are handled correctly.
- Press the \"Open settings\" button and make sure that \"Call Cancel Manager\" is the default Wi-Fi calling account.
- Then press the \"Place call\" button; the test will pass (or fail) automatically.
- </string>
- <string name="telecom_failed_call_title">Failed Call Test</string>
- <string name="telecom_failed_call_info">This tests to make sure that failed calls are handled correctly.
- Press the \"Open settings\" button and make sure that \"Call Failed Manager\" is the default Wi-Fi calling account.
- Then press the \"Place call\" button; the test will pass (or fail) automatically.
- </string>
- <string name="telecom_basic_call_title">Basic Call Test</string>
- <string name="telecom_basic_call_info">This tests to make sure that basic calls are handled correctly.
- Press the \"Open settings\" button and make sure that \"Basic Call Manager\" is the default Wi-Fi calling account.
- Then press the \"Place call\" button; the test will pass (or fail) automatically.
- </string>
-
</resources>
diff --git a/apps/CtsVerifier/res/xml/sensor_device_admin.xml b/apps/CtsVerifier/res/xml/sensor_device_admin.xml
new file mode 100644
index 0000000..2a3437d
--- /dev/null
+++ b/apps/CtsVerifier/res/xml/sensor_device_admin.xml
@@ -0,0 +1,20 @@
+<!-- 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.
+-->
+
+<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-policies>
+ <force-lock />
+ </uses-policies>
+</device-admin>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/formats/CameraFormatsActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/formats/CameraFormatsActivity.java
index 3e52ed8..8d6ef2c 100755
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/formats/CameraFormatsActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/formats/CameraFormatsActivity.java
@@ -51,6 +51,7 @@
import java.lang.Math;
import java.lang.Thread;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
@@ -344,9 +345,10 @@
new ArrayAdapter<String>(
this, R.layout.cf_format_list_item, availableSizeNames));
- // Get preview formats
+ // Get preview formats, removing duplicates
- mPreviewFormats = p.getSupportedPreviewFormats();
+ HashSet<Integer> formatSet = new HashSet<>(p.getSupportedPreviewFormats());
+ mPreviewFormats = new ArrayList<Integer>(formatSet);
String[] availableFormatNames = new String[mPreviewFormats.size()];
for (int i = 0; i < mPreviewFormats.size(); i++) {
@@ -600,9 +602,11 @@
mCamera = Camera.open(i);
Camera.Parameters p = mCamera.getParameters();
+ HashSet<Integer> formatSet = new HashSet<>(p.getSupportedPreviewFormats());
+
allCombinationsSize +=
p.getSupportedPreviewSizes().size() * // resolutions
- p.getSupportedPreviewFormats().size(); // formats
+ formatSet.size(); // unique formats
}
return allCombinationsSize;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nls/NotificationListenerVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nls/NotificationListenerVerifierActivity.java
index 842c024..5e9db53 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nls/NotificationListenerVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nls/NotificationListenerVerifierActivity.java
@@ -425,7 +425,7 @@
new MockListener.StringListResultCatcher() {
@Override
public void accept(List<String> result) {
- if (result.size() > 0 && result.contains(mTag1)) {
+ if (result != null && result.size() > 0 && result.contains(mTag1)) {
mStatus[i] = PASS;
} else {
logWithStack("failed testNotificationRecieved");
@@ -444,7 +444,7 @@
public void accept(List<String> result) {
boolean pass = false;
Set<String> found = new HashSet<String>();
- if (result.size() > 0) {
+ if (result != null && result.size() > 0) {
pass = true;
for(String payloadData : result) {
try {
@@ -513,7 +513,7 @@
new MockListener.StringListResultCatcher() {
@Override
public void accept(List<String> result) {
- if (result.size() > 0 && result.contains(mTag1)) {
+ if (result != null && result.size() > 0 && result.contains(mTag1)) {
mStatus[i] = PASS;
next();
} else {
@@ -546,7 +546,8 @@
new MockListener.StringListResultCatcher() {
@Override
public void accept(List<String> result) {
- if (result.size() == 2 && result.contains(mTag2) && result.contains(mTag3)) {
+ if (result != null && result.size() == 2
+ && result.contains(mTag2) && result.contains(mTag3)) {
mStatus[i] = PASS;
next();
} else {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/projection/offscreen/ProjectionOffscreenActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/projection/offscreen/ProjectionOffscreenActivity.java
index 5f32cfd..f992618 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/projection/offscreen/ProjectionOffscreenActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/projection/offscreen/ProjectionOffscreenActivity.java
@@ -185,6 +185,13 @@
}
Image image = reader.acquireLatestImage();
+
+ // No new images available
+ if (image == null) {
+ Log.w(TAG, "onImageAvailable called but no image!");
+ return;
+ }
+
if (mTestStatus == TestStatus.RUNNING) {
int ret = scanImage(image);
if (ret == -1) {
@@ -244,9 +251,7 @@
offset += rowPadding;
}
- // Return a color if it represents more than one quarter of the pixels.
- // We use this threshold in case the display is being letterboxed when
- // mirroring so there might be large black bars on the sides, which is normal.
+ // Return a color if it represents all of the pixels.
Log.d(TAG, "- Pixels: " + blackPixels + " black, "
+ bluePixels + " blue, "
+ otherPixels + " other");
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/AccelerometerMeasurementTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/AccelerometerMeasurementTestActivity.java
index 265f086..945e9ab 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/AccelerometerMeasurementTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/AccelerometerMeasurementTestActivity.java
@@ -21,6 +21,7 @@
import android.hardware.Sensor;
import android.hardware.SensorManager;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
import android.hardware.cts.helpers.sensorverification.MeanVerification;
@@ -91,12 +92,12 @@
*/
private String verifyMeasurements(float ... expectations) throws Throwable {
Thread.sleep(500 /*ms*/);
- TestSensorOperation verifyMeasurements = new TestSensorOperation(
+ TestSensorEnvironment environment = new TestSensorEnvironment(
getApplicationContext(),
Sensor.TYPE_ACCELEROMETER,
- SensorManager.SENSOR_DELAY_FASTEST,
- 0 /*reportLatencyInUs*/,
- 100 /* event count */);
+ SensorManager.SENSOR_DELAY_FASTEST);
+ TestSensorOperation verifyMeasurements =
+ new TestSensorOperation(environment, 100 /* event count */);
verifyMeasurements.addVerification(new MeanVerification(
expectations,
new float[]{1.95f, 1.95f, 1.95f} /* m / s^2 */));
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/BatchingTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/BatchingTestActivity.java
index 42bd6ad..4ba38a9 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/BatchingTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/BatchingTestActivity.java
@@ -22,6 +22,7 @@
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.sensoroperations.TestSensorFlushOperation;
import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
import android.hardware.cts.helpers.sensoroperations.VerifiableSensorOperation;
@@ -61,15 +62,12 @@
protected void activitySetUp() throws InterruptedException {
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "BatchingTests");
-
- deactivateSensorFeatures();
mWakeLock.acquire();
}
@Override
protected void activityCleanUp() throws InterruptedException {
mWakeLock.release();
- restoreSensorFeatures();
}
// TODO: refactor to discover all available sensors of each type and dynamically generate test
@@ -135,17 +133,16 @@
getTestLogger().logInstructions(instructionsResId);
waitForUserToBegin();
- Context context = getApplicationContext();
int maxBatchReportLatencyUs = (int) TimeUnit.SECONDS.toMicros(maxBatchReportLatencySec);
- int testDurationSec = maxBatchReportLatencySec + BATCHING_PADDING_TIME_S;
- TestSensorOperation operation = new TestSensorOperation(
- context,
+ TestSensorEnvironment environment = new TestSensorEnvironment(
+ getApplicationContext(),
sensorType,
SENSOR_BATCHING_RATE_US,
- maxBatchReportLatencyUs,
- testDurationSec,
- TimeUnit.SECONDS);
+ maxBatchReportLatencyUs);
+ int testDurationSec = maxBatchReportLatencySec + BATCHING_PADDING_TIME_S;
+ TestSensorOperation operation =
+ new TestSensorOperation(environment, testDurationSec,TimeUnit.SECONDS);
return executeTest(operation);
}
@@ -154,17 +151,16 @@
getTestLogger().logInstructions(instructionsResId);
waitForUserToBegin();
- Context context = getApplicationContext();
int maxBatchReportLatencyUs = (int) TimeUnit.SECONDS.toMicros(maxBatchReportLatencySec);
- int flushDurationSec = maxBatchReportLatencySec / 2;
- TestSensorFlushOperation operation = new TestSensorFlushOperation(
- context,
+ TestSensorEnvironment environment = new TestSensorEnvironment(
+ getApplicationContext(),
sensorType,
SENSOR_BATCHING_RATE_US,
- maxBatchReportLatencyUs,
- flushDurationSec,
- TimeUnit.SECONDS);
+ maxBatchReportLatencyUs);
+ int flushDurationSec = maxBatchReportLatencySec / 2;
+ TestSensorFlushOperation operation =
+ new TestSensorFlushOperation(environment, flushDurationSec, TimeUnit.SECONDS);
return executeTest(operation);
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeMeasurementTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeMeasurementTestActivity.java
index c4927e9..11a741b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeMeasurementTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/GyroscopeMeasurementTestActivity.java
@@ -21,6 +21,7 @@
import android.hardware.Sensor;
import android.hardware.SensorManager;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
import android.hardware.cts.helpers.sensorverification.SigNumVerification;
@@ -119,12 +120,13 @@
waitForUser();
Thread.sleep(500 /*ms*/);
- TestSensorOperation verifySignum = new TestSensorOperation(
+
+ TestSensorEnvironment environment = new TestSensorEnvironment(
getApplicationContext(),
Sensor.TYPE_GYROSCOPE,
- SensorManager.SENSOR_DELAY_FASTEST,
- 0 /*reportLatencyInUs*/,
- 100 /* event count */);
+ SensorManager.SENSOR_DELAY_FASTEST);
+ TestSensorOperation verifySignum =
+ new TestSensorOperation(environment, 100 /* event count */);
verifySignum.addVerification(new SigNumVerification(
expectations,
new float[]{0.2f, 0.2f, 0.2f} /*noiseThreshold*/));
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MagneticFieldMeasurementTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MagneticFieldMeasurementTestActivity.java
index 0e83a3e..c2a9207 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MagneticFieldMeasurementTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/MagneticFieldMeasurementTestActivity.java
@@ -24,6 +24,7 @@
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener2;
import android.hardware.SensorManager;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEventListener;
import android.hardware.cts.helpers.TestSensorManager;
import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
@@ -77,9 +78,11 @@
public void onFlushCompleted(Sensor sensor) {}
};
- TestSensorManager magnetometer = new TestSensorManager(
- this.getApplicationContext(), Sensor.TYPE_MAGNETIC_FIELD,
- SensorManager.SENSOR_DELAY_NORMAL, 0);
+ TestSensorEnvironment environment = new TestSensorEnvironment(
+ getApplicationContext(),
+ Sensor.TYPE_MAGNETIC_FIELD,
+ SensorManager.SENSOR_DELAY_NORMAL);
+ TestSensorManager magnetometer = new TestSensorManager(environment);
try {
magnetometer.registerListener(new TestSensorEventListener(listener));
waitForUser();
@@ -109,16 +112,17 @@
* - the values sampled from the sensor
*/
private String verifyNorm() throws Throwable {
+ TestSensorEnvironment environment = new TestSensorEnvironment(
+ getApplicationContext(),
+ Sensor.TYPE_MAGNETIC_FIELD,
+ SensorManager.SENSOR_DELAY_FASTEST);
+ TestSensorOperation verifyNorm =
+ new TestSensorOperation(environment, 100 /* event count */);
+
float expectedMagneticFieldEarth =
(SensorManager.MAGNETIC_FIELD_EARTH_MAX + SensorManager.MAGNETIC_FIELD_EARTH_MIN) / 2;
float magneticFieldEarthThreshold =
expectedMagneticFieldEarth - SensorManager.MAGNETIC_FIELD_EARTH_MIN;
- TestSensorOperation verifyNorm = new TestSensorOperation(
- this.getApplicationContext(),
- Sensor.TYPE_MAGNETIC_FIELD,
- SensorManager.SENSOR_DELAY_FASTEST,
- 0 /*reportLatencyInUs*/,
- 100 /* event count */);
verifyNorm.addVerification(new MagnitudeVerification(
expectedMagneticFieldEarth,
magneticFieldEarthThreshold));
@@ -150,12 +154,12 @@
* the failure to help track down the issue.
*/
private String verifyStandardDeviation() throws Throwable {
- TestSensorOperation verifyStdDev = new TestSensorOperation(
- this.getApplicationContext(),
+ TestSensorEnvironment environment = new TestSensorEnvironment(
+ getApplicationContext(),
Sensor.TYPE_MAGNETIC_FIELD,
- SensorManager.SENSOR_DELAY_FASTEST,
- 0 /*reportLatencyInUs*/,
- 100 /* event count */);
+ SensorManager.SENSOR_DELAY_FASTEST);
+ TestSensorOperation verifyStdDev =
+ new TestSensorOperation(environment, 100 /* event count */);
verifyStdDev.addVerification(new StandardDeviationVerification(
new float[]{2f, 2f, 2f} /* uT */));
verifyStdDev.execute();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorPowerTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorPowerTestActivity.java
index 85ab6c5..cfc4db0 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorPowerTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorPowerTestActivity.java
@@ -18,51 +18,54 @@
import com.android.cts.verifier.sensors.base.SensorCtsVerifierTestActivity;
import com.android.cts.verifier.sensors.helpers.PowerTestHostLink;
+import com.android.cts.verifier.sensors.helpers.SensorTestScreenManipulator;
import com.android.cts.verifier.sensors.reporting.SensorTestDetails;
import junit.framework.Assert;
-import java.util.concurrent.TimeUnit;
-
public class SensorPowerTestActivity
extends SensorCtsVerifierTestActivity
implements PowerTestHostLink.HostToDeviceInterface {
- public class TestExecutionException extends Exception {
- public TestExecutionException(final String message) {
- super(message);
- }
- }
+
+ private PowerTestHostLink mHostLink;
+ private SensorTestScreenManipulator mScreenManipulator;
public SensorPowerTestActivity() {
super(SensorPowerTestActivity.class);
}
- private PowerTestHostLink mHostLink;
- /** HostToDeviceInterface implementation **/
+ @Override
public void waitForUserAcknowledgement(final String message) {
appendText(message);
waitForUser();
}
- /* channel for host to raise an exception on the device if needed */
+ @Override
public void raiseError(String testName, String message) throws Exception {
getTestLogger().logTestFail(testName, message);
- throw new TestExecutionException(message);
+ throw new RuntimeException(message);
}
+ @Override
public void logText(String text) {
appendText(text);
}
+ @Override
public void logTestResult(SensorTestDetails testDetails) {
getTestLogger().logTestDetails(testDetails);
}
@Override
- protected void activitySetUp() throws InterruptedException {
- setScreenOffTimeout(15, TimeUnit.SECONDS);
- deactivateSensorFeatures();
+ public void turnScreenOff() {
+ mScreenManipulator.turnScreenOffOnNextPowerDisconnect();
+ }
+
+ @Override
+ protected void activitySetUp() {
+ mScreenManipulator = new SensorTestScreenManipulator(getApplicationContext());
+ mScreenManipulator.initialize(this);
}
@Override
@@ -70,9 +73,7 @@
if (mHostLink != null) {
mHostLink.close();
}
-
- restoreSensorFeatures();
- resetScreenOffTimeout();
+ mScreenManipulator.close();
}
public String testSensorsPower() throws Throwable {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorValueAccuracyActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorValueAccuracyActivity.java
index d8075f0..4f20a1f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorValueAccuracyActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SensorValueAccuracyActivity.java
@@ -27,6 +27,7 @@
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.cts.helpers.SensorNotSupportedException;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEvent;
import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
import android.hardware.cts.helpers.sensorverification.ISensorVerification;
@@ -51,14 +52,12 @@
private static final int EVENTS_TO_COLLECT = 100;
private static final int SENSOR_RATE = SensorManager.SENSOR_DELAY_FASTEST;
- private static final float MAGNETIC_FIELD_CALIBRATED_UNCALIBRATED_THRESHOLD_UT = 1f;
+ private static final float MAGNETIC_FIELD_CALIBRATED_UNCALIBRATED_THRESHOLD_UT = 3f;
private static final float GYROSCOPE_CALIBRATED_UNCALIBRATED_THRESHOLD_RAD_SEC = 0.01f;
private static final float RANGE_ATMOSPHERIC_PRESSURE = 35f;
private static final float AMBIENT_TEMPERATURE_AVERAGE = 22.5f;
private static final float AMBIENT_TEMPERATURE_THRESHOLD = 7.5f;
- private static final float PROXIMITY_AVERAGE = 50f;
- private static final float PROXIMITY_THRESHOLD = 50f;
private static final double ONE_HUNDRED_EIGHTY_DEGREES = 180.0f;
private static final double GYROSCOPE_INTEGRATION_THRESHOLD_DEGREES = 10.0f;
@@ -174,12 +173,10 @@
appendText(instructionsResId);
waitForUser();
- TestSensorOperation verifyNormOperation = new TestSensorOperation(
- getApplicationContext(),
- sensorType,
- SENSOR_RATE,
- 0 /* reportLatencyInUs */,
- EVENTS_TO_COLLECT);
+ TestSensorEnvironment environment =
+ new TestSensorEnvironment(getApplicationContext(), sensorType, SENSOR_RATE);
+ TestSensorOperation verifyNormOperation =
+ new TestSensorOperation(environment, EVENTS_TO_COLLECT);
// TODO: add event ordering and timestamp > 0 verifications
ISensorVerification magnitudeVerification =
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java
index 73608f1..fbc56c2 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/SignificantMotionTestActivity.java
@@ -26,7 +26,8 @@
import android.hardware.SensorManager;
import android.hardware.TriggerEvent;
import android.hardware.TriggerEventListener;
-import android.os.Bundle;
+import android.hardware.cts.helpers.SensorNotSupportedException;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.os.SystemClock;
import java.util.concurrent.CountDownLatch;
@@ -144,9 +145,10 @@
}
TriggerVerifier verifier = new TriggerVerifier();
+ boolean success = mSensorManager.requestTriggerSensor(verifier, mSensorSignificantMotion);
Assert.assertTrue(
- getString(R.string.snsr_significant_motion_registration),
- mSensorManager.requestTriggerSensor(verifier, mSensorSignificantMotion));
+ getString(R.string.snsr_significant_motion_registration, success),
+ success);
if (cancelEventNotification) {
Assert.assertTrue(
getString(R.string.snsr_significant_motion_cancelation),
@@ -168,14 +170,13 @@
}
@Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
+ protected void activitySetUp() {
mSensorManager = (SensorManager) getApplicationContext()
.getSystemService(Context.SENSOR_SERVICE);
- mSensorSignificantMotion = mSensorManager
- .getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION);
-
+ mSensorSignificantMotion = mSensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION);
+ if (mSensorSignificantMotion == null) {
+ throw new SensorNotSupportedException(Sensor.TYPE_SIGNIFICANT_MOTION);
+ }
}
/**
@@ -236,10 +237,12 @@
sensorName);
Assert.assertEquals(valuesMessage, EXPECTED_EVENT_VALUE, value);
+ long deltaThreshold = MAX_ACCEPTABLE_EVENT_TIME_DELAY_NANOS
+ + TestSensorEnvironment.getSensorMaxDetectionLatencyNs(event.sensor);
return assertTimestampSynchronization(
event.timestamp,
registry.realtimeTimestampNanos,
- MAX_ACCEPTABLE_EVENT_TIME_DELAY_NANOS,
+ deltaThreshold,
sensorName);
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/StepCounterTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/StepCounterTestActivity.java
index 221c92a..f66d754 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/StepCounterTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/StepCounterTestActivity.java
@@ -27,6 +27,8 @@
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.cts.helpers.MovementDetectorHelper;
+import android.hardware.cts.helpers.SensorTestStateNotSupportedException;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEvent;
import android.os.SystemClock;
import android.view.MotionEvent;
@@ -79,6 +81,11 @@
mSensorStepCounter = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mSensorStepDetector = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
+ if (mSensorStepCounter == null && mSensorStepDetector == null) {
+ throw new SensorTestStateNotSupportedException(
+ "Sensors Step Counter/Detector are not supported.");
+ }
+
ScrollView scrollView = (ScrollView) findViewById(R.id.log_scroll_view);
scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
@@ -131,7 +138,7 @@
mMoveDetected = false;
mCheckForMotion = false;
- getTestLogger().logMessage(instructionsResId);
+ getTestLogger().logInstructions(instructionsResId);
waitForUserToBegin();
mCheckForMotion = (expectedSteps > 0);
@@ -148,7 +155,7 @@
return verifyMeasurements(expectedSteps);
}
- private void startMeasurements() throws Throwable {
+ private void startMeasurements() {
if (mSensorStepCounter != null) {
mSensorManager.registerListener(this, mSensorStepCounter,
SensorManager.SENSOR_DELAY_NORMAL);
@@ -168,7 +175,7 @@
mMovementDetectorHelper.start();
}
- private String verifyMeasurements(int stepsExpected) throws Throwable {
+ private String verifyMeasurements(int stepsExpected) {
mSensorManager.unregisterListener(this);
mMovementDetectorHelper.stop();
@@ -192,8 +199,12 @@
}
private void verifyStepCounterMeasurements() {
- final int userReportedSteps = mTimestampsUserReported.size();
+ if (mSensorStepCounter == null) {
+ // sensor not supported, so no-op
+ return;
+ }
+ final int userReportedSteps = mTimestampsUserReported.size();
int totalStepsCounted = 0;
int initialStepCount = -1;
for (TestSensorEvent counterEvent : mStepCounterEvents) {
@@ -222,19 +233,15 @@
counterEvent.timestamp);
Assert.assertTrue(eventTriggered, countDelta > 0);
- long systemTimestamp = counterEvent.receivedTimestamp;
- long timestamp = counterEvent.timestamp;
- long timestampDelta = Math.abs(timestamp - systemTimestamp);
- String eventTimestampMessage = getString(
- R.string.snsr_event_time,
- systemTimestamp,
- timestamp,
- timestampDelta,
- TIMESTAMP_SYNCHRONIZATION_THRESHOLD_NANOS,
- sensorName);
- Assert.assertTrue(
- eventTimestampMessage,
- timestampDelta < TIMESTAMP_SYNCHRONIZATION_THRESHOLD_NANOS);
+ // TODO: abstract this into an ISensorVerification
+
+ long deltaThreshold = TIMESTAMP_SYNCHRONIZATION_THRESHOLD_NANOS
+ + TestSensorEnvironment.getSensorMaxDetectionLatencyNs(counterEvent.sensor);
+ assertTimestampSynchronization(
+ counterEvent.timestamp,
+ counterEvent.receivedTimestamp,
+ deltaThreshold,
+ counterEvent.sensor.getName());
totalStepsCounted = stepsCounted;
}
@@ -263,8 +270,12 @@
}
private void verifyStepDetectorMeasurements() {
- final int userReportedSteps = mTimestampsUserReported.size();
+ if (mSensorStepDetector == null) {
+ // sensor not supported, so no-op
+ return;
+ }
+ final int userReportedSteps = mTimestampsUserReported.size();
int stepsDetected = mStepDetectorEvents.size();
int stepsDetectedDelta = Math.abs(stepsDetected - userReportedSteps);
String stepsDetectedMessage = getString(
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorSemiAutomatedTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorSemiAutomatedTestActivity.java
index 7f32a07..9f2f5c4 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorSemiAutomatedTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorSemiAutomatedTestActivity.java
@@ -18,7 +18,7 @@
import com.android.cts.verifier.sensors.reporting.SensorTestDetails;
-import android.hardware.cts.helpers.SensorNotSupportedException;
+import android.hardware.cts.helpers.SensorTestStateNotSupportedException;
/**
* Base class to author a single Sensor semi-automated test case.
@@ -37,8 +37,8 @@
SensorTestDetails.ResultCode resultCode = SensorTestDetails.ResultCode.PASS;
try {
onRun();
- } catch(SensorNotSupportedException e) {
- // the sensor is not supported/available in the device, log a warning and skip the test
+ } catch(SensorTestStateNotSupportedException e) {
+ // the sensor state is not supported in the device, log a warning and skip the test
resultCode = SensorTestDetails.ResultCode.SKIPPED;
summary = e.getMessage();
} catch(Throwable e) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java
index 04603cb..c044894 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/BaseSensorTestActivity.java
@@ -25,9 +25,10 @@
import junit.framework.Assert;
import android.app.Activity;
-import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
+import android.hardware.cts.helpers.ActivityResultMultiplexedLatch;
+import android.hardware.cts.helpers.SensorTestStateNotSupportedException;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
@@ -40,9 +41,7 @@
import android.widget.TextView;
import java.security.InvalidParameterException;
-import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
/**
* A base Activity that is used to build different methods to execute tests inside CtsVerifier.
@@ -66,18 +65,19 @@
*/
public abstract class BaseSensorTestActivity
extends Activity
- implements View.OnClickListener, Runnable {
+ implements View.OnClickListener, Runnable, ISensorTestStateContainer {
@Deprecated
protected static final String LOG_TAG = "SensorTest";
protected final Class mTestClass;
private final int mLayoutId;
- private final DeactivatorActivityHandler mDeactivatorActivityHandler;
private final SensorFeaturesDeactivator mSensorFeaturesDeactivator;
private final Semaphore mSemaphore = new Semaphore(0);
private final SensorTestLogger mTestLogger = new SensorTestLogger();
+ private final ActivityResultMultiplexedLatch mActivityResultMultiplexedLatch =
+ new ActivityResultMultiplexedLatch();
private ScrollView mLogScrollView;
private LinearLayout mLogLayout;
@@ -104,8 +104,7 @@
protected BaseSensorTestActivity(Class testClass, int layoutId) {
mTestClass = testClass;
mLayoutId = layoutId;
- mDeactivatorActivityHandler = new DeactivatorActivityHandler();
- mSensorFeaturesDeactivator = new SensorFeaturesDeactivator(mDeactivatorActivityHandler);
+ mSensorFeaturesDeactivator = new SensorFeaturesDeactivator(this);
}
@Override
@@ -129,7 +128,7 @@
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- mDeactivatorActivityHandler.onActivityResult();
+ mActivityResultMultiplexedLatch.onActivityResult(requestCode, resultCode);
}
/**
@@ -143,12 +142,18 @@
@Override
public void run() {
SensorTestDetails testDetails = null;
+ mSensorFeaturesDeactivator.requestDeactivationOfFeatures();
try {
activitySetUp();
- } catch (Throwable e) {
+ } catch (SensorTestStateNotSupportedException e) {
testDetails = new SensorTestDetails(
getTestClassName(),
SensorTestDetails.ResultCode.SKIPPED,
+ e.getMessage());
+ } catch (Throwable e) {
+ testDetails = new SensorTestDetails(
+ getTestClassName(),
+ SensorTestDetails.ResultCode.FAIL,
"[ActivitySetUp] " + e.getMessage());
}
@@ -167,6 +172,7 @@
SensorTestDetails.ResultCode.FAIL,
"[ActivityCleanUp] " + e.getMessage());
}
+ mSensorFeaturesDeactivator.requestToRestoreFeatures();
mTestLogger.logInstructions(R.string.snsr_test_complete);
// log to screen and save the overall test summary (activity level)
@@ -199,51 +205,8 @@
*/
protected abstract SensorTestDetails executeTests();
- /**
- * Guides the operator throughout the process of deactivating features that are known to use
- * Sensor data.
- *
- * @throws InterruptedException
- */
- protected void deactivateSensorFeatures() throws InterruptedException {
- mSensorFeaturesDeactivator.requestDeactivationOfFeatures();
- }
-
- /**
- * Guides the operator throughout the process of restoring the state of features that are known
- * to use Sensor data, to their original state.
- *
- * @throws InterruptedException
- */
- protected void restoreSensorFeatures() throws InterruptedException {
- mSensorFeaturesDeactivator.requestToRestoreFeatures();
- }
-
- /**
- * Guides the operator throughout the process of setting the Screen Off timeout to a required
- * value.
- *
- * @param timeout The expected timeout.
- * @param timeUnit The unit of the provided timeout.
- *
- * @throws InterruptedException
- */
- protected void setScreenOffTimeout(long timeout, TimeUnit timeUnit)
- throws InterruptedException {
- mSensorFeaturesDeactivator.requestToSetScreenOffTimeout(timeout, timeUnit);
- }
-
- /**
- * Guides the operator throughout the process of restoring the state of the Screen Off timeout
- * to its original state.
- *
- * @throws InterruptedException
- */
- protected void resetScreenOffTimeout() throws InterruptedException {
- mSensorFeaturesDeactivator.requestToResetScreenOffTimeout();
- }
-
- protected SensorTestLogger getTestLogger() {
+ @Override
+ public SensorTestLogger getTestLogger() {
return mTestLogger;
}
@@ -302,9 +265,35 @@
waitForUser(R.string.snsr_wait_to_begin);
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void waitForUserToContinue() {
+ waitForUser(R.string.snsr_wait_for_user);
+ }
+
@Deprecated
protected void waitForUser() {
- waitForUser(R.string.snsr_wait_for_user);
+ waitForUserToContinue();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int executeActivity(String action) {
+ return executeActivity(new Intent(action));
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int executeActivity(Intent intent) {
+ ActivityResultMultiplexedLatch.Latch latch = mActivityResultMultiplexedLatch.bindThread();
+ startActivityForResult(intent, latch.getRequestCode());
+ return latch.await();
}
protected void playSound() {
@@ -382,12 +371,12 @@
}
// a logger available until sensor reporting is in place
- protected class SensorTestLogger {
+ public class SensorTestLogger {
private static final String SUMMARY_SEPARATOR = " | ";
private final StringBuilder mOverallSummaryBuilder = new StringBuilder();
- public void logTestStart(String testName) {
+ void logTestStart(String testName) {
// TODO: log the sensor information and expected execution time of each test
TextAppender textAppender = new TextAppender(R.layout.snsr_test_title);
textAppender.setText(testName);
@@ -427,7 +416,7 @@
}
}
- public void logTestPass(String testName, String testSummary) {
+ void logTestPass(String testName, String testSummary) {
testSummary = getValidTestSummary(testSummary, R.string.snsr_test_pass);
logTestEnd(R.layout.snsr_success, testSummary);
Log.d(LOG_TAG, testSummary);
@@ -441,14 +430,14 @@
saveResult(testName, SensorTestDetails.ResultCode.FAIL, testSummary);
}
- public void logTestSkip(String testName, String testSummary) {
+ void logTestSkip(String testName, String testSummary) {
testSummary = getValidTestSummary(testSummary, R.string.snsr_test_skipped);
logTestEnd(R.layout.snsr_warning, testSummary);
Log.i(LOG_TAG, testSummary);
saveResult(testName, SensorTestDetails.ResultCode.SKIPPED, testSummary);
}
- public String getOverallSummary() {
+ String getOverallSummary() {
return mOverallSummaryBuilder.toString();
}
@@ -523,42 +512,4 @@
mButtonView.setEnabled(mButtonEnabled);
}
}
-
- private class DeactivatorActivityHandler implements SensorFeaturesDeactivator.ActivityHandler {
- private static final int SENSOR_FEATURES_DEACTIVATOR_RESULT = 0;
-
- private CountDownLatch mCountDownLatch;
-
- @Override
- public ContentResolver getContentResolver() {
- return BaseSensorTestActivity.this.getContentResolver();
- }
-
- @Override
- public void logInstructions(int instructionsResId, Object ... params) {
- mTestLogger.logInstructions(instructionsResId, params);
- }
-
- @Override
- public void waitForUser() {
- BaseSensorTestActivity.this.waitForUser(R.string.snsr_wait_for_user);
- }
-
- @Override
- public void launchAndWaitForSubactivity(String action) throws InterruptedException {
- mCountDownLatch = new CountDownLatch(1);
- Intent intent = new Intent(action);
- startActivityForResult(intent, SENSOR_FEATURES_DEACTIVATOR_RESULT);
- mCountDownLatch.await();
- }
-
- public void onActivityResult() {
- mCountDownLatch.countDown();
- }
-
- @Override
- public String getString(int resId, Object ... params) {
- return BaseSensorTestActivity.this.getString(resId, params);
- }
- }
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/ISensorTestStateContainer.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/ISensorTestStateContainer.java
new file mode 100644
index 0000000..3ef7e21
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/ISensorTestStateContainer.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2014 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.cts.verifier.sensors.base;
+
+import android.content.ContentResolver;
+import android.content.Intent;
+
+/**
+ * An interface that defines a facade for {@link BaseSensorTestActivity}, so it can be consumed by
+ * other CtsVerifier Sensor Test Framework helper components.
+ */
+public interface ISensorTestStateContainer {
+
+ /**
+ * @return The current logger.
+ */
+ BaseSensorTestActivity.SensorTestLogger getTestLogger();
+
+ /**
+ * Waits for the operator to acknowledge to continue execution.
+ */
+ void waitForUserToContinue();
+
+ /**
+ * @param resId The resource Id to extract.
+ * @return The extracted string.
+ */
+ String getString(int resId);
+
+ /**
+ * @param resId The resource Id to extract.
+ * @param params The parameters to format the string represented by the resource contents.
+ * @return The formatted extracted string.
+ */
+ String getString(int resId, Object ... params);
+
+ /**
+ * Starts an Activity and blocks until it completes, then it returns its result back to the
+ * client.
+ *
+ * @param action The action to start the Activity.
+ * @return The Activity's result code.
+ */
+ int executeActivity(String action);
+
+ /**
+ * Starts an Activity and blocks until it completes, then it returns its result back to the
+ * client.
+ *
+ * @param intent The intent to start the Activity.
+ * @return The Activity's result code.
+ */
+ int executeActivity(Intent intent);
+
+ /**
+ * @return The {@link ContentResolver} associated with the test.
+ */
+ ContentResolver getContentResolver();
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestActivity.java
index 1479248..4d2813c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestActivity.java
@@ -20,10 +20,11 @@
import com.android.cts.verifier.R;
import com.android.cts.verifier.sensors.reporting.SensorTestDetails;
-import junit.framework.TestResult;
+import junit.framework.Test;
import junit.framework.TestSuite;
import org.junit.internal.runners.JUnit38ClassRunner;
+import org.junit.internal.runners.SuiteMethod;
import org.junit.runner.Computer;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
@@ -61,8 +62,6 @@
protected void activitySetUp() {
getTestLogger().logInstructions(R.string.snsr_no_interaction);
waitForUserToBegin();
-
- // TODO: deactivate Sensor features?
}
/**
@@ -93,27 +92,35 @@
}
/**
- * A {@link RunnerBuilder} that is used to inject during execution a {@link SensorTestSuite}.
+ * A {@link RunnerBuilder} that is used to inject during execution a {@link SensorCtsTestSuite}.
*/
private class SensorRunnerBuilder extends RunnerBuilder {
@Override
public Runner runnerForClass(Class<?> testClass) throws Throwable {
- TestSuite testSuite = new SensorTestSuite(testClass);
- return new JUnit38ClassRunner(testSuite);
- }
- }
-
- /**
- * A {@link TestSuite} that is used to inject during execution a {@link SensorCtsTestResult}.
- */
- private class SensorTestSuite extends TestSuite {
- public SensorTestSuite(Class<?> testClass) {
- super(testClass);
+ TestSuite testSuite;
+ if (hasSuiteMethod(testClass)) {
+ Test test = SuiteMethod.testFromSuiteMethod(testClass);
+ if (test instanceof TestSuite) {
+ testSuite = (TestSuite) test;
+ } else {
+ throw new IllegalArgumentException(
+ testClass.getName() + "#suite() did not return a TestSuite.");
+ }
+ } else {
+ testSuite = new TestSuite(testClass);
+ }
+ SensorCtsTestSuite sensorTestSuite =
+ new SensorCtsTestSuite(getApplicationContext(), testSuite);
+ return new JUnit38ClassRunner(sensorTestSuite);
}
- @Override
- public void run(TestResult testResult) {
- super.run(new SensorCtsTestResult(getApplicationContext(), testResult));
+ private boolean hasSuiteMethod(Class testClass) {
+ try {
+ testClass.getMethod("suite");
+ return true;
+ } catch (NoSuchMethodException e) {
+ return false;
+ }
}
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestResult.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestResult.java
index d07b4c4..851d405 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestResult.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestResult.java
@@ -124,6 +124,7 @@
if (testCase instanceof SensorTestCase) {
SensorTestCase sensorTestCase = (SensorTestCase) testCase;
sensorTestCase.setContext(mContext);
+ sensorTestCase.setEmulateSensorUnderLoad(false);
// TODO: set delayed assertion provider
} else {
throw new IllegalStateException("TestCase must be an instance of SensorTestCase.");
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestSuite.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestSuite.java
new file mode 100644
index 0000000..bbf76a7
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsTestSuite.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2014 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.cts.verifier.sensors.base;
+
+import junit.framework.Test;
+import junit.framework.TestResult;
+import junit.framework.TestSuite;
+
+import android.content.Context;
+
+import java.util.Enumeration;
+
+/**
+ * A wrapper class for a {@link TestSuite}.
+ *
+ * It provides a way to inject a {@link SensorCtsTestResult} during execution.
+ */
+class SensorCtsTestSuite extends TestSuite {
+ private final Context mContext;
+ private final TestSuite mWrappedTestSuite;
+
+ public SensorCtsTestSuite(Context context, TestSuite testSuite) {
+ mContext = context;
+ mWrappedTestSuite = testSuite;
+ }
+
+ @Override
+ public void run(TestResult testResult) {
+ mWrappedTestSuite.run(new SensorCtsTestResult(mContext, testResult));
+ }
+
+ @Override
+ public void addTest(Test test) {
+ mWrappedTestSuite.addTest(test);
+ }
+
+ @Override
+ public int countTestCases() {
+ return mWrappedTestSuite.countTestCases();
+ }
+
+ @Override
+ public String getName() {
+ return mWrappedTestSuite.getName();
+ }
+
+ @Override
+ public void runTest(Test test, TestResult testResult) {
+ mWrappedTestSuite.runTest(test, testResult);
+ }
+
+ @Override
+ public void setName(String name) {
+ mWrappedTestSuite.setName(name);
+ }
+
+ @Override
+ public Test testAt(int index) {
+ return mWrappedTestSuite.testAt(index);
+ }
+
+ @Override
+ public int testCount() {
+ return mWrappedTestSuite.testCount();
+ }
+
+ @Override
+ public Enumeration<Test> tests() {
+ return mWrappedTestSuite.tests();
+ }
+
+ @Override
+ public String toString() {
+ return mWrappedTestSuite.toString();
+ }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsVerifierTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsVerifierTestActivity.java
index 5987036..148e457 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsVerifierTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/base/SensorCtsVerifierTestActivity.java
@@ -19,7 +19,7 @@
import com.android.cts.verifier.sensors.reporting.SensorTestDetails;
-import android.hardware.cts.helpers.SensorNotSupportedException;
+import android.hardware.cts.helpers.SensorTestStateNotSupportedException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@@ -114,7 +114,7 @@
// get the inner exception, because we use reflection APIs to execute the test
Throwable cause = e.getCause();
testSummary = cause.getMessage();
- if (cause instanceof SensorNotSupportedException) {
+ if (cause instanceof SensorTestStateNotSupportedException) {
testResultCode = SensorTestDetails.ResultCode.SKIPPED;
++mTestSkippedCounter;
} else {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/PowerTestHostLink.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/PowerTestHostLink.java
index 645bdb2..59caadf 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/PowerTestHostLink.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/PowerTestHostLink.java
@@ -25,8 +25,6 @@
import android.hardware.SensorManager;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
-import android.os.PowerManager;
-import android.provider.Settings;
import android.util.Log;
import java.io.IOException;
@@ -38,13 +36,14 @@
/**
* This class handles communication with the host to respond to commands.
* The command/response link is through a TCP socket on the host side, forwarded via adb to a local
- * socket on the device. The system uses a standard "accept-read_command-send_response-close" to
- * execute commands sent from the host.
- *
+ * socket on the device. The system uses a standard "accept-read_command-send_response-close" to
+ * execute commands sent from the host.
+ *
* CAUTION: The local socket name (SOCKET_NAME below) must match that used by the host to set up
* the adb-forwarding.
*/
public class PowerTestHostLink {
+ private static final String TAG = "PowerTestHostLink";
/**
* Host-to-device bridge will use a Listener instance to drive the test via the CtsVerifier
@@ -55,17 +54,15 @@
void raiseError(String testName, String message) throws Exception;
void waitForUserAcknowledgement(String message);
void logText(String text);
- };
+ void turnScreenOff();
+ }
/** This is a data-only message to communicate result of a power test */
public class PowerTestResult{
public int passedCount = 0;
public int skippedCount = 0;
public int failedCount = 0;
- };
-
-
- public final String TAG = "PowerTestHostLink";
+ }
/**
* Standard response types back to host. Host-side code must match these definitions.
@@ -79,35 +76,15 @@
*/
public final static String SOCKET_NAME = "/android/cts/powertest";
- private LocalServerSocket mServerSocket;
private volatile boolean mStopThread;
private final SensorManager mSensorManager;
- private final PowerManager mPowerManager;
- private final Context mContext;
private final HostToDeviceInterface mHostToDeviceExecutor;
- private PowerTestResult mTestResult;
+ private final PowerTestResult mTestResult = new PowerTestResult();
- public PowerTestHostLink(Context context, final HostToDeviceInterface listener) {
+ public PowerTestHostLink(Context context, HostToDeviceInterface listener) {
Log.d(TAG, " +++ Begin of localSocketServer() +++ ");
mHostToDeviceExecutor = listener;
- mContext = context;
- try {
- mServerSocket = new LocalServerSocket(SOCKET_NAME);
- Log.i(TAG, "OKAY");
-
- } catch (IOException e) {
- Log.e(TAG, "The local Socket Server create failed");
- e.printStackTrace();
- }
- if (mServerSocket != null) {
- Log.d(TAG, "Bound to local server socket");
- } else {
- Log.e(TAG, "Unable to bind to local socket ");
- }
- mStopThread = false;
-
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
- mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
}
/**
@@ -124,15 +101,15 @@
* @throws Exception
*/
public PowerTestResult run() throws Exception {
- mTestResult = new PowerTestResult();
// define buffer to receive data from host
final int BUFFER_SIZE = 4096;
byte[] buffer = new byte[BUFFER_SIZE];
- if (null == mServerSocket) {
- Log.d(TAG, "The localSocketServer is NULL !!!");
+ LocalServerSocket serverSocket = createSocket();
+ if (null == serverSocket) {
mStopThread = true;
}
+
InputStream streamIn;
OutputStream streamOut;
LocalSocket receiverSocket;
@@ -140,7 +117,7 @@
try {
Log.d(TAG, "localSocketServer accept...");
- receiverSocket = mServerSocket.accept();
+ receiverSocket = serverSocket.accept();
Log.d(TAG, "Got new connection");
} catch (IOException e) {
Log.d(TAG, "localSocketServer accept() failed !!!", e);
@@ -188,7 +165,7 @@
Log.d(TAG, "Sending response " + response);
streamOut.write(response.getBytes(), 0, response.length());
}
- // null response means response is defered awaiting user response
+ // null response means response is deferred awaiting user response
} catch (Exception e) {
Log.e(TAG, "Error executing " + clientRequest, e);
streamOut.write(RESPONSE_ERR.getBytes(), 0, RESPONSE_ERR.length());
@@ -196,75 +173,80 @@
}
receiverSocket.close();
} catch (IOException e) {
- Log.e(TAG, "There is an exception when reading from or writing tosocket", e);
+ Log.e(TAG, "There is an exception when reading from or writing to socket", e);
break;
}
}
Log.d(TAG, "The LocalSocketServer thread is going to stop !!!");
- if (mServerSocket != null) {
+ if (serverSocket != null) {
try {
- mServerSocket.close();
+ serverSocket.close();
} catch (IOException e) {
Log.d(TAG, "Exception on close of server socket", e);
}
}
mHostToDeviceExecutor.logText("Device disconnected.");
- Log.d(TAG, "Returning " + mTestResult.passedCount + "passed " + mTestResult.skippedCount + "skipped " +
- mTestResult.failedCount + "failed.");
+ Log.d(TAG, "Returning " + mTestResult.passedCount + "passed " + mTestResult.skippedCount +
+ "skipped " + mTestResult.failedCount + "failed.");
return mTestResult;
}
- protected String processClientRequest(String request) throws Exception {
- final String USER_REQUEST = "REQUEST USER RESPONSE";
+ private String processClientRequest(String request) throws Exception {
+ // the following constants need to match the definitions in execute_power_tests.py
+ final String REQUEST_EXTERNAL_STORAGE = "EXTERNAL STORAGE?";
+ final String REQUEST_EXIT = "EXIT";
+ final String REQUEST_RAISE = "RAISE ";
+ final String REQUEST_USER_RESPONSE = "USER RESPONSE ";
+ final String REQUEST_SET_TEST_RESULT = "SET TEST RESULT ";
+ final String REQUEST_SENSOR_ON = "SENSOR ON ";
+ final String REQUEST_SENSOR_OFF = "SENSOR OFF";
+ final String REQUEST_SENSOR_AVAILABILITY = "SENSOR? ";
+ final String REQUEST_SCREEN_OFF = "SCREEN OFF";
+ final String REQUEST_SHOW_MESSAGE = "MESSAGE ";
+
String response = RESPONSE_ERR;
// Queries must appear first and then commands to direct actions after in these statements
- if (request.startsWith("SCREEN OFF TIMEOUT?")) {
- int timeout = Settings.System.getInt(mContext.getContentResolver(),
- Settings.System.SCREEN_OFF_TIMEOUT);
- response = "" + timeout;
- } else if (request.startsWith("AIRPLANE MODE ON?")) {
- boolean airplaneModeOn = Settings.Global.getInt
- (mContext.getContentResolver(),
- Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
- response = airplaneModeOn ? RESPONSE_OK : RESPONSE_ERR;
- } else if (request.startsWith("SENSOR?")) {
- final String sensor = request.substring(9);
+ if (request.startsWith(REQUEST_SENSOR_AVAILABILITY)) {
+ final String sensor = request.substring(REQUEST_SENSOR_AVAILABILITY.length());
final int sensorId = getSensorId(sensor);
if (mSensorManager.getDefaultSensor(sensorId) == null) {
response = RESPONSE_UNAVAILABLE;
} else {
response = RESPONSE_OK;
}
- } else if (request.startsWith("EXTERNAL STORAGE?")){
+ } else if (request.startsWith(REQUEST_EXTERNAL_STORAGE)){
response = System.getenv("EXTERNAL_STORAGE");
Log.d(TAG,"External storage is " + response);
- } else if (request.startsWith("SCREEN OFF?")) {
- boolean screenOn = mPowerManager.isScreenOn();
- response = screenOn ? RESPONSE_ERR : RESPONSE_OK;
- } else if (request.startsWith("SCREEN ON?")) {
- boolean screenOn = mPowerManager.isScreenOn();
- response = screenOn ? RESPONSE_OK : RESPONSE_ERR;
- } else if (request.startsWith("SENSOR ON ")) {
- String sensorList = request.substring(10).trim();
- response = handleSensorSensorSwitchCmd(sensorList, true);
- } else if (request.startsWith("SENSOR OFF")) {
- String sensorList = request.substring(10).trim();
- response = handleSensorSensorSwitchCmd(sensorList, false);
- } else if (request.startsWith("MESSAGE")) {
- final String message = request.substring(8);
+ } else if (request.startsWith(REQUEST_SCREEN_OFF)) {
+ try {
+ mHostToDeviceExecutor.turnScreenOff();
+ response = RESPONSE_OK;
+ } catch (SecurityException e) {
+ Log.e(TAG, "Error Turning screen off", e);
+ response = RESPONSE_ERR;
+ }
+ } else if (request.startsWith(REQUEST_SENSOR_ON)) {
+ String sensorList = request.substring(REQUEST_SENSOR_ON.length()).trim();
+ response = handleSensorSwitchCommand(sensorList, true);
+ } else if (request.startsWith(REQUEST_SENSOR_OFF)) {
+ String sensorList = request.substring(REQUEST_SENSOR_ON.length()).trim();
+ response = handleSensorSwitchCommand(sensorList, false);
+ } else if (request.startsWith(REQUEST_SHOW_MESSAGE)) {
+ final String message = request.substring(REQUEST_SHOW_MESSAGE.length());
mHostToDeviceExecutor.logText(message);
response = RESPONSE_OK;
- } else if (request.startsWith(USER_REQUEST)) {
- final String message = request.substring(USER_REQUEST.length() + 1);
+ } else if (request.startsWith(REQUEST_USER_RESPONSE)) {
+ String message = request.substring(REQUEST_USER_RESPONSE.length());
mHostToDeviceExecutor.waitForUserAcknowledgement(message);
response = RESPONSE_OK;
- } else if (request.startsWith("SET TEST RESULT")) {
- response = handleSetTestResultCmd(request);
- } else if (request.startsWith("RAISE")) {
- StringTokenizer tokenizer = new StringTokenizer(request);
+ } else if (request.startsWith(REQUEST_SET_TEST_RESULT)) {
+ String testResult = request.substring(REQUEST_SET_TEST_RESULT.length());
+ response = handleSetTestResultCmd(testResult);
+ } else if (request.startsWith(REQUEST_RAISE)) {
+ String command = request.substring(REQUEST_RAISE.length());
+ StringTokenizer tokenizer = new StringTokenizer(command);
try {
- tokenizer.nextToken();/* RAISE */
final String testName = tokenizer.nextToken();
final String message = request.substring(7 + testName.length());
mHostToDeviceExecutor.raiseError(testName, message);
@@ -273,7 +255,7 @@
Log.e(TAG, "Invalid RAISE command received (bad arguments): " + request);
response = RESPONSE_ERR;
}
- } else if (request.startsWith("EXIT")) {
+ } else if (request.startsWith(REQUEST_EXIT)) {
mStopThread = true;
response = RESPONSE_OK;
} else {
@@ -282,7 +264,7 @@
return response;
}
- protected String handleSetTestResultCmd(final String request) {
+ private String handleSetTestResultCmd(final String request) {
String response;
StringTokenizer tokenizer = new StringTokenizer(request, " ");
String testName = "";
@@ -290,9 +272,6 @@
String message = "";
try {
- tokenizer.nextToken();/* SET */
- tokenizer.nextToken();/* TEST */
- tokenizer.nextToken();/* RESULT */
testName = tokenizer.nextToken();
final String resultToken = tokenizer.nextToken();
@@ -328,7 +307,7 @@
return response;
}
- protected String handleSensorSensorSwitchCmd(String sensorList, boolean switchOn) {
+ private String handleSensorSwitchCommand(String sensorList, boolean switchOn) {
String response;
try {
StringTokenizer tokenizer = new StringTokenizer(sensorList, " ");
@@ -360,7 +339,7 @@
return response;
}
- protected int getSensorId(String sensorName) {
+ private static int getSensorId(String sensorName) {
int sensorId = -1;
if (sensorName.compareToIgnoreCase("ACCELEROMETER") == 0) {
@@ -398,11 +377,11 @@
return sensorId;
}
- protected String switchSensor(int sensorId, boolean switchOn) {
+ private String switchSensor(int sensorId, boolean switchOn) {
return switchSensor(sensorId, switchOn, "SENSOR_DELAY_NORMAL");
}
- protected String switchSensor(int sensorId, boolean switchOn, String requestFrequency) {
+ private String switchSensor(int sensorId, boolean switchOn, String requestFrequency) {
String response;
int rateUs = SensorManager.SENSOR_DELAY_NORMAL;
@@ -429,7 +408,7 @@
return response;
}
- protected String switchAllSensors(boolean on) {
+ private String switchAllSensors(boolean on) {
List<Sensor> allSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
String response = RESPONSE_OK;
for (Sensor sensor : allSensors) {
@@ -441,13 +420,20 @@
return response;
}
+ private LocalServerSocket createSocket() {
+ try {
+ return new LocalServerSocket(SOCKET_NAME);
+ } catch (IOException e) {
+ Log.e(TAG, "LocalSocketServer creation failure.", e);
+ return null;
+ }
+ }
+
private SensorEventListener mSensorEventListener = new SensorEventListener() {
@Override
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- }
+ public void onAccuracyChanged(Sensor sensor, int accuracy) {}
@Override
- public void onSensorChanged(SensorEvent event) {
- }
+ public void onSensorChanged(SensorEvent event) {}
};
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorDeviceAdminReceiver.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorDeviceAdminReceiver.java
new file mode 100644
index 0000000..9d75a98
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorDeviceAdminReceiver.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2014 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.cts.verifier.sensors.helpers;
+
+import android.app.admin.DeviceAdminReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+
+/**
+ * Receiver to be used with {@link SensorTestScreenManipulator}.
+ */
+public class SensorDeviceAdminReceiver extends DeviceAdminReceiver {
+
+ /**
+ * Gets the associated {@link ComponentName} of the current receiver.
+ */
+ public static ComponentName getComponentName(Context context) {
+ return new ComponentName(context, SensorDeviceAdminReceiver.class);
+ }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorFeaturesDeactivator.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorFeaturesDeactivator.java
index 48b069d..75c0ec0 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorFeaturesDeactivator.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorFeaturesDeactivator.java
@@ -17,119 +17,63 @@
package com.android.cts.verifier.sensors.helpers;
import com.android.cts.verifier.R;
+import com.android.cts.verifier.sensors.base.ISensorTestStateContainer;
import android.content.ContentResolver;
import android.os.Build;
import android.provider.Settings;
-import android.util.Log;
-
-import java.util.concurrent.TimeUnit;
/**
- * A helper class that provides a mechanism to prompt users to deactivate features that are known
- * to register for sensor data.
- *
- * It also keeps stored the initial state for each feature modified.
+ * A helper class that provides a mechanism to:
+ * - prompt users to activate/deactivate features that are known to register for sensor data.
+ * - turn on/off certain components of the device on behalf of the test (described as 'runtime
+ * features')
+ * - keep track of the initial state for each sensor feature, so it can be restored at will
*/
public class SensorFeaturesDeactivator {
- private static final String TAG = "SensorFeaturesDeactivator";
-
- private final ActivityHandler mActivityHandler;
private boolean mInitialStateCaptured;
- private long mScreenOffTimeoutInMs;
- private final SensorSettingContainer mAirplaneMode;
- private final SensorSettingContainer mScreenBrightnessMode;
- private final SensorSettingContainer mAutoRotateScreenMode;
- private final SensorSettingContainer mKeepScreenOnMode;
- private final SensorSettingContainer mLocationMode;
+ private final ISensorTestStateContainer mStateContainer;
- /**
- * The handler is a facade for the Activity making use of the {@link SensorFeaturesDeactivator}.
- */
- public interface ActivityHandler {
- ContentResolver getContentResolver();
- void logInstructions(int instructionsResId, Object ... params);
- void waitForUser();
- void launchAndWaitForSubactivity(String action) throws InterruptedException;
- String getString(int resId, Object ... params);
+ private final SensorSettingContainer mAirplaneMode = new AirplaneModeSettingContainer();
+ private final SensorSettingContainer mScreenBrightnessMode =
+ new ScreenBrightnessModeSettingContainer();
+ private final SensorSettingContainer mAutoRotateScreenMode =
+ new AutoRotateScreenModeSettingContainer();
+ private final SensorSettingContainer mKeepScreenOnMode = new KeepScreenOnModeSettingContainer();
+ private final SensorSettingContainer mLocationMode = new LocationModeSettingContainer();
+
+ public SensorFeaturesDeactivator(ISensorTestStateContainer stateContainer) {
+ mStateContainer = stateContainer;
}
- public SensorFeaturesDeactivator(ActivityHandler activityHandler) {
- mActivityHandler = activityHandler;
- mAirplaneMode = new AirplaneModeSettingContainer();
- mScreenBrightnessMode = new ScreenBrightnessModeSettingContainer();
- mAutoRotateScreenMode = new AutoRotateScreenModeSettingContainer();
- mKeepScreenOnMode = new KeepScreenOnModeSettingContainer();
- mLocationMode = new LocationModeSettingContainer();
- }
-
- public synchronized void requestDeactivationOfFeatures() throws InterruptedException {
+ public synchronized void requestDeactivationOfFeatures() {
captureInitialState();
- mAirplaneMode.requestToSetMode(true);
- mScreenBrightnessMode.requestToSetMode(false);
- mAutoRotateScreenMode.requestToSetMode(false);
- mKeepScreenOnMode.requestToSetMode(false);
- mLocationMode.requestToSetMode(false);
+ mAirplaneMode.requestToSetMode(mStateContainer, true);
+ mScreenBrightnessMode.requestToSetMode(mStateContainer, false);
+ mAutoRotateScreenMode.requestToSetMode(mStateContainer, false);
+ mKeepScreenOnMode.requestToSetMode(mStateContainer, false);
+ mLocationMode.requestToSetMode(mStateContainer, false);
// TODO: try to use adb shell dumpsys sensorservice to find out if there are clients still
// registered at this time
- mActivityHandler.logInstructions(R.string.snsr_sensor_feature_deactivation);
- mActivityHandler.waitForUser();
+ mStateContainer.getTestLogger()
+ .logInstructions(R.string.snsr_sensor_feature_deactivation);
+ mStateContainer.waitForUserToContinue();
}
- public synchronized void requestToRestoreFeatures() throws InterruptedException {
+ public synchronized void requestToRestoreFeatures() {
if (!isInitialStateCaptured()) {
return;
}
- mAirplaneMode.requestToResetMode();
- mScreenBrightnessMode.requestToResetMode();
- mAutoRotateScreenMode.requestToResetMode();
- mKeepScreenOnMode.requestToResetMode();
- mLocationMode.requestToResetMode();
- }
- public synchronized void requestToResetScreenOffTimeout() throws InterruptedException {
- if (!isInitialStateCaptured()) {
- return;
- }
- try {
- requestToSetScreenOffTimeout(mScreenOffTimeoutInMs, TimeUnit.MILLISECONDS);
- } catch (IllegalStateException e) {
- Log.e(TAG, "Error resetting screen off timeout.", e);
- }
- }
-
- public synchronized void requestToSetScreenOffTimeout(long timeout, TimeUnit timeUnit)
- throws InterruptedException {
- captureInitialState();
-
- String settingName = mActivityHandler.getString(R.string.snsr_setting_auto_screen_off_mode);
- long timeoutInMs = TimeUnit.MILLISECONDS.convert(timeout, timeUnit);
- long timeoutInSec = TimeUnit.SECONDS.convert(timeout, timeUnit);
- if (isScreenOffTimeout(timeoutInMs)) {
- mActivityHandler.logInstructions(
- R.string.snsr_setting_mode_set,
- settingName,
- timeoutInSec + "s");
- return;
- }
-
- mActivityHandler.logInstructions(
- R.string.snsr_setting_mode_request,
- settingName,
- timeoutInSec + "s");
- mActivityHandler.logInstructions(R.string.snsr_on_complete_return);
- mActivityHandler.waitForUser();
- mActivityHandler.launchAndWaitForSubactivity(Settings.ACTION_DISPLAY_SETTINGS);
-
- if (!isScreenOffTimeout(timeoutInMs)) {
- String message = mActivityHandler
- .getString(R.string.snsr_setting_mode_not_set, settingName, timeoutInSec + "s");
- throw new IllegalStateException(message);
- }
+ mAirplaneMode.requestToResetMode(mStateContainer);
+ mScreenBrightnessMode.requestToResetMode(mStateContainer);
+ mAutoRotateScreenMode.requestToResetMode(mStateContainer);
+ mKeepScreenOnMode.requestToResetMode(mStateContainer);
+ mLocationMode.requestToResetMode(mStateContainer);
}
private void captureInitialState() {
@@ -142,7 +86,6 @@
mAutoRotateScreenMode.captureInitialState();
mLocationMode.captureInitialState();
mKeepScreenOnMode.captureInitialState();
- mScreenOffTimeoutInMs = getScreenOffTimeoutInMs();
mInitialStateCaptured = true;
}
@@ -151,27 +94,14 @@
return mInitialStateCaptured;
}
- private boolean isScreenOffTimeout(long expectedTimeoutInMs) {
- return getScreenOffTimeoutInMs() == expectedTimeoutInMs;
- }
-
- private long getScreenOffTimeoutInMs() {
- return Settings.System.getLong(
- mActivityHandler.getContentResolver(),
- Settings.System.SCREEN_OFF_TIMEOUT,
- Integer.MAX_VALUE);
- }
-
private class AirplaneModeSettingContainer extends SensorSettingContainer {
public AirplaneModeSettingContainer() {
- super(mActivityHandler,
- Settings.ACTION_WIRELESS_SETTINGS,
- R.string.snsr_setting_airplane_mode);
+ super(Settings.ACTION_WIRELESS_SETTINGS, R.string.snsr_setting_airplane_mode);
}
@Override
protected int getSettingMode() {
- ContentResolver contentResolver = mActivityHandler.getContentResolver();
+ ContentResolver contentResolver = mStateContainer.getContentResolver();
// Settings.System.AIRPLANE_MODE_ON is deprecated in API 17
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.System.getInt(contentResolver, Settings.System.AIRPLANE_MODE_ON, 0);
@@ -183,15 +113,13 @@
private class ScreenBrightnessModeSettingContainer extends SensorSettingContainer {
public ScreenBrightnessModeSettingContainer() {
- super(mActivityHandler,
- Settings.ACTION_DISPLAY_SETTINGS,
- R.string.snsr_setting_screen_brightness_mode);
+ super(Settings.ACTION_DISPLAY_SETTINGS, R.string.snsr_setting_screen_brightness_mode);
}
@Override
public int getSettingMode() {
return Settings.System.getInt(
- mActivityHandler.getContentResolver(),
+ mStateContainer.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
@@ -199,15 +127,14 @@
private class AutoRotateScreenModeSettingContainer extends SensorSettingContainer {
public AutoRotateScreenModeSettingContainer() {
- super(mActivityHandler,
- Settings.ACTION_ACCESSIBILITY_SETTINGS,
+ super(Settings.ACTION_ACCESSIBILITY_SETTINGS,
R.string.snsr_setting_auto_rotate_screen_mode);
}
@Override
protected int getSettingMode() {
return Settings.System.getInt(
- mActivityHandler.getContentResolver(),
+ mStateContainer.getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION,
0 /* default */);
}
@@ -215,15 +142,14 @@
private class KeepScreenOnModeSettingContainer extends SensorSettingContainer {
public KeepScreenOnModeSettingContainer() {
- super(mActivityHandler,
- Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS,
+ super(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS,
R.string.snsr_setting_keep_screen_on);
}
@Override
protected int getSettingMode() {
return Settings.Global.getInt(
- mActivityHandler.getContentResolver(),
+ mStateContainer.getContentResolver(),
Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
0);
}
@@ -231,15 +157,13 @@
private class LocationModeSettingContainer extends SensorSettingContainer {
public LocationModeSettingContainer() {
- super(mActivityHandler,
- Settings.ACTION_LOCATION_SOURCE_SETTINGS,
- R.string.snsr_setting_location_mode);
+ super(Settings.ACTION_LOCATION_SOURCE_SETTINGS, R.string.snsr_setting_location_mode);
}
@Override
protected int getSettingMode() {
return Settings.Secure.getInt(
- mActivityHandler.getContentResolver(),
+ mStateContainer.getContentResolver(),
Settings.Secure.LOCATION_MODE,
Settings.Secure.LOCATION_MODE_OFF);
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorSettingContainer.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorSettingContainer.java
index aa73d6c..27fa699 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorSettingContainer.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorSettingContainer.java
@@ -17,6 +17,8 @@
package com.android.cts.verifier.sensors.helpers;
import com.android.cts.verifier.R;
+import com.android.cts.verifier.sensors.base.BaseSensorTestActivity;
+import com.android.cts.verifier.sensors.base.ISensorTestStateContainer;
import android.util.Log;
@@ -28,17 +30,12 @@
*/
abstract class SensorSettingContainer {
private static final String TAG = "SensorSettingContainer";
- private final SensorFeaturesDeactivator.ActivityHandler mActivityHandler;
private final String mAction;
private final int mSettingNameResId;
private boolean mCapturedModeOn;
- public SensorSettingContainer(
- SensorFeaturesDeactivator.ActivityHandler activityHandler,
- String action,
- int settingNameResId) {
- mActivityHandler = activityHandler;
+ public SensorSettingContainer(String action, int settingNameResId) {
mAction = action;
mSettingNameResId = settingNameResId;
}
@@ -47,28 +44,31 @@
mCapturedModeOn = getCurrentSettingMode();
}
- public synchronized void requestToSetMode(boolean modeOn) throws InterruptedException {
- String settingName = mActivityHandler.getString(mSettingNameResId);
+ public synchronized void requestToSetMode(
+ ISensorTestStateContainer stateContainer,
+ boolean modeOn) {
+ BaseSensorTestActivity.SensorTestLogger logger = stateContainer.getTestLogger();
+ String settingName = stateContainer.getString(mSettingNameResId);
if (getCurrentSettingMode() == modeOn) {
- mActivityHandler.logInstructions(R.string.snsr_setting_mode_set, settingName, modeOn);
+ logger.logInstructions(R.string.snsr_setting_mode_set, settingName, modeOn);
return;
}
- mActivityHandler.logInstructions(R.string.snsr_setting_mode_request, settingName, modeOn);
- mActivityHandler.logInstructions(R.string.snsr_on_complete_return);
- mActivityHandler.waitForUser();
+ logger.logInstructions(R.string.snsr_setting_mode_request, settingName, modeOn);
+ logger.logInstructions(R.string.snsr_on_complete_return);
+ stateContainer.waitForUserToContinue();
- mActivityHandler.launchAndWaitForSubactivity(mAction);
+ stateContainer.executeActivity(mAction);
if (getCurrentSettingMode() != modeOn) {
- String message = mActivityHandler
+ String message = stateContainer
.getString(R.string.snsr_setting_mode_not_set, settingName, modeOn);
throw new IllegalStateException(message);
}
}
- public synchronized void requestToResetMode() throws InterruptedException {
+ public synchronized void requestToResetMode(ISensorTestStateContainer stateContainer) {
try {
- requestToSetMode(mCapturedModeOn);
+ requestToSetMode(stateContainer, mCapturedModeOn);
} catch (IllegalStateException e) {
Log.e(TAG, "Error restoring state of action: " + mAction, e);
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorTestScreenManipulator.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorTestScreenManipulator.java
new file mode 100644
index 0000000..8986cd9
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorTestScreenManipulator.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2014 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.cts.verifier.sensors.helpers;
+
+import com.android.cts.verifier.sensors.base.BaseSensorTestActivity;
+import com.android.cts.verifier.sensors.base.ISensorTestStateContainer;
+
+import android.app.Activity;
+import android.app.admin.DeviceAdminInfo;
+import android.app.admin.DevicePolicyManager;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.text.TextUtils;
+
+/**
+ * A class that provides functionality to manipulate the state of the device's screen.
+ */
+public class SensorTestScreenManipulator {
+
+ private final Context mContext;
+ private final DevicePolicyManager mDevicePolicyManager;
+ private final ComponentName mComponentName;
+
+ private volatile InternalBroadcastReceiver mBroadcastReceiver;
+ private volatile boolean mTurnOffScreenOnPowerDisconnected;
+
+ public SensorTestScreenManipulator(Context context) {
+ mContext = context;
+ mComponentName = SensorDeviceAdminReceiver.getComponentName(context);
+ mDevicePolicyManager =
+ (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
+ }
+
+ /**
+ * Initializes the current instance.
+ * Initialization should usually happen inside {@link BaseSensorTestActivity#activitySetUp}.
+ *
+ * NOTE: Initialization will bring up an Activity to let the user activate the Device Admin,
+ * this method will block until the user completes the operation.
+ */
+ public synchronized void initialize(ISensorTestStateContainer stateContainer) {
+ if (!isDeviceAdminInitialized()) {
+ Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
+ intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
+ int resultCode = stateContainer.executeActivity(intent);
+ if (resultCode != Activity.RESULT_OK) {
+ throw new IllegalStateException(
+ "Test cannot execute without Activating the Device Administrator.");
+ }
+ }
+
+ if (mBroadcastReceiver == null) {
+ mBroadcastReceiver = new InternalBroadcastReceiver();
+ IntentFilter intentFilter = new IntentFilter();
+ intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
+ mContext.registerReceiver(mBroadcastReceiver, intentFilter);
+ }
+ }
+
+ /**
+ * Closes the current instance.
+ * This operation should usually happen inside {@link BaseSensorTestActivity#activityCleanUp}.
+ */
+ public synchronized void close() {
+ if (mBroadcastReceiver != null) {
+ mContext.unregisterReceiver(mBroadcastReceiver);
+ mBroadcastReceiver = null;
+ }
+ }
+
+ /**
+ * Instruct the device to turn off the screen immediately.
+ */
+ public synchronized void turnScreenOff() {
+ ensureDeviceAdminInitialized();
+ mDevicePolicyManager.lockNow();
+ }
+
+ /**
+ * Queues a request to turn off the screen off when the device has been disconnected from a
+ * power source (usually upon USB disconnected).
+ *
+ * (It is useful for Sensor Power Tests, as the Power Monitor usually detaches itself from the
+ * device before beginning to sample data).
+ */
+ public synchronized void turnScreenOffOnNextPowerDisconnect() {
+ ensureDeviceAdminInitialized();
+ mTurnOffScreenOnPowerDisconnected = true;
+ }
+
+ private void ensureDeviceAdminInitialized() throws IllegalStateException {
+ if (!isDeviceAdminInitialized()) {
+ throw new IllegalStateException("Component must be initialized before it can be used.");
+ }
+ }
+
+ private boolean isDeviceAdminInitialized() {
+ if (!mDevicePolicyManager.isAdminActive(mComponentName)) {
+ return false;
+ }
+ return mDevicePolicyManager
+ .hasGrantedPolicy(mComponentName, DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
+ }
+
+ private class InternalBroadcastReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+
+ if (mTurnOffScreenOnPowerDisconnected &&
+ TextUtils.equals(action, Intent.ACTION_POWER_DISCONNECTED)) {
+ turnScreenOff();
+
+ // reset the flag after it has triggered once, we try to avoid cases when the test
+ // might leave the receiver enabled after itself,
+ // this approach still provides a way to multiplex one time requests
+ mTurnOffScreenOnPowerDisconnected = false;
+ }
+ }
+ }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/BasicCallTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/telecom/BasicCallTestActivity.java
deleted file mode 100644
index 70d141c..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/BasicCallTestActivity.java
+++ /dev/null
@@ -1,151 +0,0 @@
-package com.android.cts.verifier.telecom;
-
-import com.android.cts.verifier.R;
-
-import android.net.Uri;
-import android.os.SystemClock;
-import android.telecom.Connection;
-import android.telecom.ConnectionRequest;
-import android.telecom.DisconnectCause;
-import android.telecom.PhoneAccountHandle;
-import android.telecom.RemoteConnection;
-import android.telecom.StatusHints;
-
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Tests that a basic call with RemoteConnections will go through. When this ConnectionService is
- * notified of an outgoing call, it will create a Connection which wraps a RemoteConnection. Then,
- * once the RemoteConnection starts dialing, it will disconnect the call and the test will pass.
- */
-public class BasicCallTestActivity extends TelecomBaseTestActivity {
- private static final Semaphore sLock = new Semaphore(0);
-
- @Override
- protected int getTestTitleResource() {
- return R.string.telecom_basic_call_title;
- }
-
- @Override
- protected int getTestInfoResource() {
- return R.string.telecom_basic_call_info;
- }
-
- @Override
- protected Class<? extends android.telecom.ConnectionService> getConnectionService() {
- return ConnectionService.class;
- }
-
- @Override
- protected String getConnectionServiceLabel() {
- return "Basic Call Manager";
- }
-
- @Override
- protected boolean onCallPlacedBackgroundThread() {
- try {
- if (!sLock.tryAcquire(5000, TimeUnit.MILLISECONDS)) {
- return false;
- }
-
- // Wait for the listeners to be fired so the call is cleaned up.
- SystemClock.sleep(1000);
-
- return !getTelecomManager().isInCall();
- } catch (Exception e) {
- return false;
- }
- }
-
- public static class ConnectionService extends android.telecom.ConnectionService {
- @Override
- public Connection onCreateOutgoingConnection(
- PhoneAccountHandle connectionManagerPhoneAccount,
- ConnectionRequest request) {
- RemoteConnection remoteConnection =
- createRemoteOutgoingConnection(connectionManagerPhoneAccount, request);
- return new ProxyConnection(remoteConnection);
- }
- }
-
- private static class ProxyConnection extends Connection {
- private final RemoteConnection mRemoteConnection;
-
- private final RemoteConnection.Callback mCallback = new RemoteConnection.Callback() {
- @Override
- public void onStateChanged(RemoteConnection connection, int state) {
- switch (state) {
- case Connection.STATE_ACTIVE:
- setActive();
- break;
- case Connection.STATE_DIALING:
- setDialing();
- break;
- case Connection.STATE_DISCONNECTED:
- sLock.release();
- break;
- case Connection.STATE_HOLDING:
- setOnHold();
- break;
- case Connection.STATE_INITIALIZING:
- setInitializing();
- break;
- case Connection.STATE_NEW:
- setInitialized();
- break;
- case Connection.STATE_RINGING:
- setRinging();
- break;
- }
- }
-
- @Override
- public void onDisconnected(
- RemoteConnection connection, DisconnectCause disconnectCause) {
- setDisconnected(disconnectCause);
- }
-
- @Override
- public void onStatusHintsChanged(RemoteConnection connection, StatusHints statusHints) {
- setStatusHints(statusHints);
- }
-
- @Override
- public void onAddressChanged(
- RemoteConnection connection, Uri address, int presentation) {
- setAddress(address, presentation);
- }
-
- @Override
- public void onCallerDisplayNameChanged(RemoteConnection connection,
- String callerDisplayName,
- int presentation) {
- setCallerDisplayName(callerDisplayName, presentation);
- }
-
- @Override
- public void onDestroyed(RemoteConnection connection) {
- destroy();
- }
- };
-
- public ProxyConnection(RemoteConnection connection) {
- mRemoteConnection = connection;
- if (connection.getState() == Connection.STATE_DISCONNECTED) {
- sLock.release();
- } else {
- mRemoteConnection.registerCallback(mCallback);
- }
- }
-
- @Override
- public void onStateChanged(int state) {
- if (state == Connection.STATE_DIALING) {
- // Good enough; let's disconnect this call.
- mRemoteConnection.disconnect();
- sLock.release();
- }
- }
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/CancelCallTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/telecom/CancelCallTestActivity.java
deleted file mode 100644
index 58d71ce..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/CancelCallTestActivity.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2014 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.cts.verifier.telecom;
-
-import android.os.SystemClock;
-import android.telecom.Connection;
-import android.telecom.ConnectionRequest;
-import android.telecom.PhoneAccountHandle;
-
-import com.android.cts.verifier.R;
-
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Tests that a call can be canceled by a ConnectionService (and that the cancelation is respected).
- * Once the ConnectionService returns a canceled connection, the test verifies that Telecomm does
- * not have any active calls. If this is the case, the test will pass.
- */
-public class CancelCallTestActivity extends TelecomBaseTestActivity {
- private static final Semaphore sLock = new Semaphore(0);
-
- @Override
- protected int getTestTitleResource() {
- return R.string.telecom_cancel_call_title;
- }
-
- @Override
- protected int getTestInfoResource() {
- return R.string.telecom_cancel_call_info;
- }
-
- @Override
- protected Class<? extends android.telecom.ConnectionService> getConnectionService() {
- return ConnectionService.class;
- }
-
- @Override
- protected String getConnectionServiceLabel() {
- return "Call Cancel Manager";
- }
-
- @Override
- protected boolean onCallPlacedBackgroundThread() {
- try {
- if (!sLock.tryAcquire(1000, TimeUnit.MILLISECONDS)) {
- return false;
- }
-
- // Wait for the listeners to be fired so the call is cleaned up.
- SystemClock.sleep(1000);
-
- // Make sure that there aren't any ongoing calls.
- return !getTelecomManager().isInCall();
- } catch (Exception e) {
- return false;
- }
- }
-
- public static class ConnectionService extends android.telecom.ConnectionService {
- @Override
- public Connection onCreateOutgoingConnection(
- PhoneAccountHandle connectionManagerPhoneAccount,
- ConnectionRequest request) {
- sLock.release();
- return Connection.createCanceledConnection();
- }
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/FailedCallTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/telecom/FailedCallTestActivity.java
deleted file mode 100644
index 74a8637..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/FailedCallTestActivity.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2014 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.cts.verifier.telecom;
-
-import android.os.SystemClock;
-import android.telecom.Connection;
-import android.telecom.ConnectionRequest;
-import android.telecom.DisconnectCause;
-import android.telecom.PhoneAccountHandle;
-
-import com.android.cts.verifier.R;
-
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Tests that a connection manager can fail calls and they're handled appropriately. That is, when
- * a call is failed, it will not go through. The flow here is that the ConnectionService will say
- * that the call failed because it's busy, and then make sure that there are no active calls. If
- * this is the case, the test will pass.
- */
-public class FailedCallTestActivity extends TelecomBaseTestActivity {
- private static final Semaphore sLock = new Semaphore(0);
-
- @Override
- protected int getTestTitleResource() {
- return R.string.telecom_failed_call_title;
- }
-
- @Override
- protected int getTestInfoResource() {
- return R.string.telecom_failed_call_info;
- }
-
- @Override
- protected Class<? extends android.telecom.ConnectionService> getConnectionService() {
- return ConnectionService.class;
- }
-
- @Override
- protected String getConnectionServiceLabel() {
- return "Call Failed Manager";
- }
-
- @Override
- protected boolean onCallPlacedBackgroundThread() {
- try {
- if (!sLock.tryAcquire(1000, TimeUnit.MILLISECONDS)) {
- return false;
- }
-
- // Wait for the listeners to be fired so the call is cleaned up.
- SystemClock.sleep(1000);
-
- // Make sure that there aren't any ongoing calls.
- return !getTelecomManager().isInCall();
- } catch (Exception e) {
- return false;
- }
- }
-
- public static class ConnectionService extends android.telecom.ConnectionService {
- @Override
- public Connection onCreateOutgoingConnection(
- PhoneAccountHandle connectionManagerPhoneAccount,
- ConnectionRequest request) {
- sLock.release();
- return Connection.createFailedConnection(
- new DisconnectCause(DisconnectCause.BUSY, "Test; no need to continue"));
- }
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/TelecomBaseTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/telecom/TelecomBaseTestActivity.java
deleted file mode 100644
index 03a986b..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/TelecomBaseTestActivity.java
+++ /dev/null
@@ -1,120 +0,0 @@
-package com.android.cts.verifier.telecom;
-
-import android.content.ComponentName;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Bundle;
-import android.telecom.ConnectionService;
-import android.telecom.PhoneAccount;
-import android.telecom.PhoneAccountHandle;
-import android.telecom.TelecomManager;
-import android.view.View;
-import android.widget.Button;
-import android.widget.EditText;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import java.util.Objects;
-
-public abstract class TelecomBaseTestActivity extends PassFailButtons.Activity {
- protected PhoneAccountHandle mPhoneAccountHandle;
-
- private Button mOpenSettingsBtn;
- private Button mPlaceCallBtn;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- setResult(RESULT_CANCELED);
- setContentView(R.layout.telecom_test_activity);
- setPassFailButtonClickListeners();
- setInfoResources(getTestTitleResource(), getTestInfoResource(), 0);
-
- mOpenSettingsBtn = (Button) findViewById(R.id.open_settings);
- mOpenSettingsBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- mPhoneAccountHandle = new PhoneAccountHandle(
- new ComponentName(getApplicationContext(), getConnectionService()),
- getClass().getSimpleName()
- );
- PhoneAccount account = new PhoneAccount.Builder(mPhoneAccountHandle,
- getConnectionServiceLabel())
- .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER)
- .build();
-
- getTelecomManager().registerPhoneAccount(account);
-
- Intent i = new Intent(TelecomManager.ACTION_CHANGE_PHONE_ACCOUNTS);
- startActivity(i);
- }
- });
-
- mPlaceCallBtn = (Button) findViewById(R.id.simulate_call);
- mPlaceCallBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- runTest();
- }
- });
- }
-
- @Override
- protected void onResume() {
- super.onResume();
-
- PhoneAccountHandle defaultConnectionManager = getTelecomManager().getConnectionManager();
- boolean isDefaultConnectionManager = mPhoneAccountHandle != null &&
- Objects.equals(mPhoneAccountHandle, defaultConnectionManager);
- mOpenSettingsBtn.setEnabled(!isDefaultConnectionManager);
- mPlaceCallBtn.setEnabled(isDefaultConnectionManager);
- }
-
- abstract protected int getTestTitleResource();
-
- abstract protected int getTestInfoResource();
-
- abstract protected Class<? extends ConnectionService> getConnectionService();
-
- abstract protected String getConnectionServiceLabel();
-
- /**
- * Perform any tests once the call has been placed. This is called from a background thread, so
- * it is safe to block until the result is known.
- *
- * @return True if the test passed.
- */
- abstract protected boolean onCallPlacedBackgroundThread();
-
- protected void runTest() {
- new Thread() {
- @Override
- public void run() {
- EditText phoneNumberEdit = (EditText) findViewById(R.id.phone_number);
- String numberText = phoneNumberEdit.getText().toString();
- Uri number = Uri.fromParts("tel", numberText, null);
-
- Intent call = new Intent(Intent.ACTION_CALL);
- call.setData(number);
- startActivity(call);
-
- boolean passed = onCallPlacedBackgroundThread();
- setTestResultAndFinish(passed);
- }
- }.start();
- }
-
- protected TelecomManager getTelecomManager() {
- return (TelecomManager) getSystemService(TELECOM_SERVICE);
- }
-
- @Override
- public void setTestResultAndFinish(boolean passed) {
- super.setTestResultAndFinish(passed);
- if (mPhoneAccountHandle != null) {
- getTelecomManager().unregisterPhoneAccount(mPhoneAccountHandle);
- }
- }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/TelecomTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/telecom/TelecomTestActivity.java
deleted file mode 100644
index 3f7596a..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/TelecomTestActivity.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2014 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.cts.verifier.telecom;
-
-import com.android.cts.verifier.ManifestTestListAdapter;
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import android.os.Bundle;
-
-public class TelecomTestActivity extends PassFailButtons.TestListActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.pass_fail_list);
- setPassFailButtonClickListeners();
- setInfoResources(R.string.telecom_test_title, R.string.telecom_test_summary, -1);
-
- setTestListAdapter(new ManifestTestListAdapter(this, getClass().getName()));
- }
-}
diff --git a/build/test_executable.mk b/build/test_executable.mk
index 1439663..5cccd1c 100644
--- a/build/test_executable.mk
+++ b/build/test_executable.mk
@@ -41,5 +41,4 @@
-p $(PRIVATE_TEST_PACKAGE) \
-e $(CTS_EXPECTATIONS) \
-b $(CTS_UNSUPPORTED_ABIS) \
- -a $(TARGET_ARCH) \
-o $@
diff --git a/build/test_gtest_package.mk b/build/test_gtest_package.mk
index eeb8bbe..c3471ed 100644
--- a/build/test_gtest_package.mk
+++ b/build/test_gtest_package.mk
@@ -50,5 +50,4 @@
-p $(PRIVATE_TEST_PACKAGE) \
-e $(CTS_EXPECTATIONS) \
-b $(CTS_UNSUPPORTED_ABIS) \
- -a $(TARGET_ARCH) \
-o $@
diff --git a/build/test_host_java_library.mk b/build/test_host_java_library.mk
index c502b83..cb44010 100644
--- a/build/test_host_java_library.mk
+++ b/build/test_host_java_library.mk
@@ -36,5 +36,4 @@
-p $(PRIVATE_TEST_PACKAGE) \
-e $(CTS_EXPECTATIONS) \
-b $(CTS_UNSUPPORTED_ABIS) \
- -a $(TARGET_ARCH) \
-o $@
diff --git a/build/test_package.mk b/build/test_package.mk
index 97f9c43..7f61e60 100644
--- a/build/test_package.mk
+++ b/build/test_package.mk
@@ -58,5 +58,4 @@
-p $(PRIVATE_TEST_PACKAGE) \
-e $(CTS_EXPECTATIONS) \
-b $(CTS_UNSUPPORTED_ABIS) \
- -a $(TARGET_ARCH) \
-o $@
diff --git a/build/test_target_java_library.mk b/build/test_target_java_library.mk
index 204bddc..d526805 100644
--- a/build/test_target_java_library.mk
+++ b/build/test_target_java_library.mk
@@ -41,6 +41,5 @@
-p $(PRIVATE_TEST_PACKAGE) \
-e $(CTS_EXPECTATIONS) \
-b $(CTS_UNSUPPORTED_ABIS) \
- -a $(TARGET_ARCH) \
-x "runtimeArgs->$(PRIVATE_RUNTIME_ARGS)" \
-o $@
diff --git a/build/test_uiautomator.mk b/build/test_uiautomator.mk
index be78f6c..7757027 100644
--- a/build/test_uiautomator.mk
+++ b/build/test_uiautomator.mk
@@ -49,5 +49,4 @@
-r $(PRIVATE_TEST_APP_PACKAGE) \
-e $(CTS_EXPECTATIONS) \
-b $(CTS_UNSUPPORTED_ABIS) \
- -a $(TARGET_ARCH) \
-o $@
diff --git a/development/ide/eclipse/.classpath b/development/ide/eclipse/.classpath
index b95d52a..fafcc32 100644
--- a/development/ide/eclipse/.classpath
+++ b/development/ide/eclipse/.classpath
@@ -1,25 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="lib" path="prebuilt/common/ddmlib/ddmlib-prebuilt.jar"/>
- <classpathentry kind="lib" path="prebuilt/common/tradefed/tradefed-prebuilt.jar"/>
+ <classpathentry kind="lib" path="prebuilts/misc/common/ddmlib/ddmlib-prebuilt.jar"/>
+ <classpathentry kind="lib" path="prebuilts/misc/common/tradefed/tradefed-prebuilt.jar"/>
<classpathentry kind="src" path="cts/apps/CtsVerifier/src"/>
- <classpathentry kind="src" path="cts/apps/CtsVerifier/tests/src"/>
<classpathentry kind="src" path="cts/hostsidetests/appsecurity/src"/>
<classpathentry kind="src" path="cts/hostsidetests/appsecurity/test-apps/AppWithData/src"/>
<classpathentry kind="src" path="cts/hostsidetests/monkey/src"/>
<classpathentry kind="src" path="cts/hostsidetests/monkey/test-apps/CtsMonkeyApp/src"/>
<classpathentry kind="src" path="cts/hostsidetests/monkey/test-apps/CtsMonkeyApp2/src"/>
+ <classpathentry kind="src" path="cts/hostsidetests/sample/src"/>
+ <classpathentry kind="src" path="cts/hostsidetests/sample/app/src"/>
+ <classpathentry kind="src" path="cts/hostsidetests/theme/src"/>
+ <classpathentry kind="src" path="cts/hostsidetests/theme/app/src"/>
+ <classpathentry kind="src" path="cts/hostsidetests/usb/src"/>
<classpathentry kind="src" path="cts/libs/vogar-expect/src"/>
- <classpathentry kind="src" path="cts/tests/ApiDemosReferenceTest/src"/>
+ <classpathentry kind="src" path="cts/libs/commonutil/src"/>
+ <classpathentry kind="src" path="cts/libs/deviceutil/src"/>
+ <classpathentry kind="src" path="cts/libs/json/src"/>
+ <classpathentry kind="src" path="cts/libs/testserver/src"/>
+ <classpathentry kind="src" path="cts/libs/wrappedgtest/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/deviceTests/browserbench/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/deviceTests/dram/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/deviceTests/filesystemperf/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/deviceTests/opengl/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/deviceTests/simplecpu/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/deviceTests/ui/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/deviceTests/videoperf/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/hostTests/jank/app/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/hostTests/jank/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/hostTests/uihost/appA/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/hostTests/uihost/appB/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/hostTests/uihost/control/src"/>
+ <classpathentry kind="src" path="cts/suite/cts/hostTests/uihost/src"/>
<classpathentry kind="src" path="cts/tests/ProcessTest/src"/>
<classpathentry kind="src" path="cts/tests/ProcessTest/NoShareUidApp/src"/>
<classpathentry kind="src" path="cts/tests/ProcessTest/ShareUidApp/src"/>
<classpathentry kind="src" path="cts/tests/SignatureTest/src"/>
<classpathentry kind="src" path="cts/tests/SignatureTest/tests/src"/>
<classpathentry kind="src" path="cts/tests/acceleration/src"/>
- <classpathentry kind="src" path="cts/tests/accessibilityservice/src"/>
<classpathentry kind="src" path="cts/tests/core/runner/src"/>
<classpathentry kind="src" path="cts/tests/deviceadmin/src"/>
+ <classpathentry kind="src" path="cts/tests/sample/src"/>
<classpathentry kind="src" path="cts/tests/src"/>
<classpathentry kind="src" path="cts/tests/tests/acceleration/src"/>
<classpathentry kind="src" path="cts/tests/tests/accessibility/src"/>
@@ -34,12 +55,10 @@
<classpathentry kind="src" path="cts/tests/tests/dpi/src"/>
<classpathentry kind="src" path="cts/tests/tests/dpi2/src"/>
<classpathentry kind="src" path="cts/tests/tests/drm/src"/>
- <classpathentry kind="src" path="cts/tests/tests/example/src"/>
<classpathentry kind="src" path="cts/tests/tests/gesture/src"/>
<classpathentry kind="src" path="cts/tests/tests/graphics/src"/>
<classpathentry kind="src" path="cts/tests/tests/graphics2/src"/>
<classpathentry kind="src" path="cts/tests/tests/hardware/src"/>
- <classpathentry kind="src" path="cts/tests/tests/holo/src"/>
<classpathentry kind="src" path="cts/tests/tests/jni/src"/>
<classpathentry kind="src" path="cts/tests/tests/location/src"/>
<classpathentry kind="src" path="cts/tests/tests/media/src"/>
@@ -48,11 +67,6 @@
<classpathentry kind="src" path="cts/tests/tests/opengl/src"/>
<classpathentry kind="src" path="cts/tests/tests/openglperf/src"/>
<classpathentry kind="src" path="cts/tests/tests/os/src"/>
- <classpathentry kind="src" path="cts/tests/tests/performance/src"/>
- <classpathentry kind="src" path="cts/tests/tests/performance2/src"/>
- <classpathentry kind="src" path="cts/tests/tests/performance3/src"/>
- <classpathentry kind="src" path="cts/tests/tests/performance4/src"/>
- <classpathentry kind="src" path="cts/tests/tests/performance5/src"/>
<classpathentry kind="src" path="cts/tests/tests/permission/src"/>
<classpathentry kind="src" path="cts/tests/tests/permission2/src"/>
<classpathentry kind="src" path="cts/tests/tests/preference/src"/>
@@ -64,7 +78,6 @@
<classpathentry kind="src" path="cts/tests/tests/telephony/src"/>
<classpathentry kind="src" path="cts/tests/tests/text/src"/>
<classpathentry kind="src" path="cts/tests/tests/textureview/src"/>
- <classpathentry kind="src" path="cts/tests/tests/theme/src"/>
<classpathentry kind="src" path="cts/tests/tests/util/src"/>
<classpathentry kind="src" path="cts/tests/tests/view/src"/>
<classpathentry kind="src" path="cts/tests/tests/webkit/src"/>
@@ -78,19 +91,11 @@
<classpathentry kind="src" path="cts/tools/dasm/src"/>
<classpathentry kind="src" path="cts/tools/device-setup/TestDeviceSetup/src"/>
<classpathentry kind="src" path="cts/tools/dex-tools/src"/>
- <classpathentry kind="src" path="cts/tools/dx-tests/src"/>
- <classpathentry kind="src" path="cts/tools/host/src"/>
- <classpathentry kind="src" path="cts/tools/host/test"/>
<classpathentry kind="src" path="cts/tools/signature-tools/src"/>
<classpathentry kind="src" path="cts/tools/signature-tools/test"/>
<classpathentry kind="src" path="cts/tools/tradefed-host/src"/>
<classpathentry kind="src" path="cts/tools/tradefed-host/tests/src"/>
<classpathentry kind="src" path="cts/tools/utils"/>
- <classpathentry kind="src" path="cts/tools/vm-tests/src"/>
+ <classpathentry kind="src" path="cts/tools/vm-tests-tf/src"/>
<classpathentry kind="src" path="external/easymock/src"/>
- <classpathentry kind="src" path="out/target/common/obj/APPS/CtsAccessibilityServiceTestCases_intermediates/src/src"/>
- <classpathentry kind="src" path="out/target/common/obj/APPS/CtsTestStubs_intermediates/src/src"/>
- <classpathentry kind="src" path="out/target/common/obj/APPS/CtsTestStubs_intermediates/src/renderscript/src"/>
- <classpathentry kind="src" path="out/target/common/obj/APPS/CtsVerifier_intermediates/src"/>
- <classpathentry kind="src" path="out/target/common/obj/APPS/CtsVerifierTests_intermediates/src"/>
</classpath>
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java
index 702002c..a0590d9 100644
--- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java
+++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AppSecurityTests.java
@@ -17,6 +17,7 @@
package com.android.cts.appsecurity;
import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.Log;
import com.android.ddmlib.testrunner.InstrumentationResultParser;
import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
@@ -29,6 +30,8 @@
import com.android.tradefed.result.TestResult.TestStatus;
import com.android.tradefed.result.TestRunResult;
import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
import com.android.tradefed.testtype.IBuildReceiver;
import java.io.File;
@@ -38,7 +41,7 @@
/**
* Set of tests that verify various security checks involving multiple apps are properly enforced.
*/
-public class AppSecurityTests extends DeviceTestCase implements IBuildReceiver {
+public class AppSecurityTests extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
private static final String RUNNER = "android.support.test.runner.AndroidJUnitRunner";
@@ -104,8 +107,14 @@
private static final String LOG_TAG = "AppSecurityTests";
+ private IAbi mAbi;
private CtsBuildHelper mCtsBuild;
+ @Override
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
/**
* {@inheritDoc}
*/
@@ -136,12 +145,13 @@
getDevice().uninstallPackage(SHARED_UI_PKG);
getDevice().uninstallPackage(SHARED_UI_DIFF_CERT_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
String installResult = getDevice().installPackage(getTestAppFile(SHARED_UI_APK),
- false);
+ false, options);
assertNull(String.format("failed to install shared uid app, Reason: %s", installResult),
installResult);
installResult = getDevice().installPackage(getTestAppFile(SHARED_UI_DIFF_CERT_APK),
- false);
+ false, options);
assertNotNull("shared uid app with different cert than existing app installed " +
"successfully", installResult);
assertEquals("INSTALL_FAILED_SHARED_USER_INCOMPATIBLE", installResult);
@@ -162,12 +172,13 @@
// cleanup test app that might be installed from previous partial test run
getDevice().uninstallPackage(SIMPLE_APP_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
String installResult = getDevice().installPackage(getTestAppFile(SIMPLE_APP_APK),
- false);
+ false, options);
assertNull(String.format("failed to install simple app. Reason: %s", installResult),
installResult);
installResult = getDevice().installPackage(getTestAppFile(SIMPLE_APP_DIFF_CERT_APK),
- true /* reinstall */);
+ true /* reinstall */, options);
assertNotNull("app upgrade with different cert than existing app installed " +
"successfully", installResult);
assertEquals("INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES", installResult);
@@ -187,8 +198,9 @@
getDevice().uninstallPackage(APP_WITH_DATA_PKG);
getDevice().uninstallPackage(APP_ACCESS_DATA_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
String installResult = getDevice().installPackage(getTestAppFile(APP_WITH_DATA_APK),
- false);
+ false, options);
assertNull(String.format("failed to install app with data. Reason: %s", installResult),
installResult);
// run appwithdata's tests to create private data
@@ -196,7 +208,7 @@
APP_WITH_DATA_CLASS, APP_WITH_DATA_CREATE_METHOD));
installResult = getDevice().installPackage(getTestAppFile(APP_ACCESS_DATA_APK),
- false);
+ false, options);
assertNull(String.format("failed to install app access data. Reason: %s",
installResult), installResult);
// run appaccessdata's tests which attempt to access appwithdata's private data
@@ -216,8 +228,9 @@
wipePrimaryExternalStorage(getDevice());
getDevice().uninstallPackage(EXTERNAL_STORAGE_APP_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
assertNull(getDevice()
- .installPackage(getTestAppFile(EXTERNAL_STORAGE_APP_APK), false));
+ .installPackage(getTestAppFile(EXTERNAL_STORAGE_APP_APK), false, options));
assertTrue("Failed external storage with no permissions",
runDeviceTests(EXTERNAL_STORAGE_APP_PKG));
} finally {
@@ -235,8 +248,9 @@
wipePrimaryExternalStorage(getDevice());
getDevice().uninstallPackage(READ_EXTERNAL_STORAGE_APP_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
assertNull(getDevice()
- .installPackage(getTestAppFile(READ_EXTERNAL_STORAGE_APP_APK), false));
+ .installPackage(getTestAppFile(READ_EXTERNAL_STORAGE_APP_APK), false, options));
assertTrue("Failed external storage with read permissions",
runDeviceTests(READ_EXTERNAL_STORAGE_APP_PKG));
} finally {
@@ -254,8 +268,9 @@
wipePrimaryExternalStorage(getDevice());
getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
assertNull(getDevice()
- .installPackage(getTestAppFile(WRITE_EXTERNAL_STORAGE_APP_APK), false));
+ .installPackage(getTestAppFile(WRITE_EXTERNAL_STORAGE_APP_APK), false, options));
assertTrue("Failed external storage with write permissions",
runDeviceTests(WRITE_EXTERNAL_STORAGE_APP_PKG));
} finally {
@@ -274,12 +289,13 @@
getDevice().uninstallPackage(EXTERNAL_STORAGE_APP_PKG);
getDevice().uninstallPackage(READ_EXTERNAL_STORAGE_APP_PKG);
getDevice().uninstallPackage(WRITE_EXTERNAL_STORAGE_APP_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
assertNull(getDevice()
- .installPackage(getTestAppFile(EXTERNAL_STORAGE_APP_APK), false));
+ .installPackage(getTestAppFile(EXTERNAL_STORAGE_APP_APK), false, options));
assertNull(getDevice()
- .installPackage(getTestAppFile(READ_EXTERNAL_STORAGE_APP_APK), false));
+ .installPackage(getTestAppFile(READ_EXTERNAL_STORAGE_APP_APK), false, options));
assertNull(getDevice()
- .installPackage(getTestAppFile(WRITE_EXTERNAL_STORAGE_APP_APK), false));
+ .installPackage(getTestAppFile(WRITE_EXTERNAL_STORAGE_APP_APK), false, options));
assertTrue("Failed to write gifts", runDeviceTests(WRITE_EXTERNAL_STORAGE_APP_PKG,
WRITE_EXTERNAL_STORAGE_APP_CLASS, "doWriteGifts"));
@@ -305,8 +321,9 @@
// cleanup test app that might be installed from previous partial test run
getDevice().uninstallPackage(APP_WITH_DATA_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
String installResult = getDevice().installPackage(getTestAppFile(APP_WITH_DATA_APK),
- false);
+ false, options);
assertNull(String.format("failed to install app with data. Reason: %s", installResult),
installResult);
// run appwithdata's tests to create private data
@@ -316,7 +333,7 @@
getDevice().uninstallPackage(APP_WITH_DATA_PKG);
installResult = getDevice().installPackage(getTestAppFile(APP_WITH_DATA_APK),
- false);
+ false, options);
assertNull(String.format("failed to install app with data second time. Reason: %s",
installResult), installResult);
// run appwithdata's 'check if file exists' test
@@ -339,14 +356,15 @@
getDevice().uninstallPackage(TARGET_INSTRUMENT_PKG);
getDevice().uninstallPackage(INSTRUMENT_DIFF_CERT_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
String installResult = getDevice().installPackage(
- getTestAppFile(TARGET_INSTRUMENT_APK), false);
+ getTestAppFile(TARGET_INSTRUMENT_APK), false, options);
assertNull(String.format("failed to install target instrumentation app. Reason: %s",
installResult), installResult);
// the app will install, but will get error at runtime when starting instrumentation
installResult = getDevice().installPackage(getTestAppFile(INSTRUMENT_DIFF_CERT_APK),
- false);
+ false, options);
assertNull(String.format(
"failed to install instrumentation app with diff cert. Reason: %s",
installResult), installResult);
@@ -374,19 +392,20 @@
getDevice().uninstallPackage(DECLARE_PERMISSION_COMPAT_PKG);
getDevice().uninstallPackage(PERMISSION_DIFF_CERT_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
String installResult = getDevice().installPackage(
- getTestAppFile(DECLARE_PERMISSION_APK), false);
+ getTestAppFile(DECLARE_PERMISSION_APK), false, options);
assertNull(String.format("failed to install declare permission app. Reason: %s",
installResult), installResult);
installResult = getDevice().installPackage(
- getTestAppFile(DECLARE_PERMISSION_COMPAT_APK), false);
+ getTestAppFile(DECLARE_PERMISSION_COMPAT_APK), false, options);
assertNull(String.format("failed to install declare permission compat app. Reason: %s",
installResult), installResult);
// the app will install, but will get error at runtime
installResult = getDevice().installPackage(getTestAppFile(PERMISSION_DIFF_CERT_APK),
- false);
+ false, options);
assertNull(String.format("failed to install permission app with diff cert. Reason: %s",
installResult), installResult);
// run PERMISSION_DIFF_CERT_PKG tests which try to access the permission
@@ -421,8 +440,9 @@
// Install our test app
getDevice().uninstallPackage(MULTIUSER_STORAGE_PKG);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
final String installResult = getDevice()
- .installPackage(getTestAppFile(MULTIUSER_STORAGE_APK), false);
+ .installPackage(getTestAppFile(MULTIUSER_STORAGE_APK), false, options);
assertNull("Failed to install: " + installResult, installResult);
// Clear data from previous tests
diff --git a/tests/tests/telecomm/Android.mk b/hostsidetests/devicepolicy/Android.mk
similarity index 62%
copy from tests/tests/telecomm/Android.mk
copy to hostsidetests/devicepolicy/Android.mk
index de1d8b3..1f51494 100644
--- a/tests/tests/telecomm/Android.mk
+++ b/hostsidetests/devicepolicy/Android.mk
@@ -12,28 +12,21 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
-# don't include this package in any target
+LOCAL_MODULE := CtsDevicePolicyManagerTestCases
+
LOCAL_MODULE_TAGS := optional
-# and when built explicitly put it in the data partition
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-#LOCAL_JAVA_LIBRARIES := Telecomm
-
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_PACKAGE_NAME := CtsTelecomTestCases
+LOCAL_JAVA_LIBRARIES := junit ddmlib-prebuilt tradefed-prebuilt tools-common-prebuilt cts-tradefed
-LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
+LOCAL_CTS_TEST_PACKAGE := android.adminhostside
-# uncomment when b/13250611 is fixed
-#LOCAL_SDK_VERSION := current
-LOCAL_JAVA_LIBRARIES += android.test.runner
+include $(BUILD_CTS_HOST_JAVA_LIBRARY)
-include $(BUILD_CTS_PACKAGE)
+# Build the test APKs using their own makefiles
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/devicepolicy/app/Android.mk b/hostsidetests/devicepolicy/app/Android.mk
new file mode 100644
index 0000000..a22ef3f
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/Android.mk
@@ -0,0 +1,20 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# Build the test APKs using their own makefiles
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/telecomm/Android.mk b/hostsidetests/devicepolicy/app/ProfileOwner/Android.mk
similarity index 68%
rename from tests/tests/telecomm/Android.mk
rename to hostsidetests/devicepolicy/app/ProfileOwner/Android.mk
index de1d8b3..a845163 100644
--- a/tests/tests/telecomm/Android.mk
+++ b/hostsidetests/devicepolicy/app/ProfileOwner/Android.mk
@@ -12,28 +12,20 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
-# don't include this package in any target
+LOCAL_PACKAGE_NAME := CtsProfileOwnerApp
+
LOCAL_MODULE_TAGS := optional
-# and when built explicitly put it in the data partition
+
LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-#LOCAL_JAVA_LIBRARIES := Telecomm
-
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
-
LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_PACKAGE_NAME := CtsTelecomTestCases
+LOCAL_JAVA_LIBRARIES := android.test.runner
-LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
-
-# uncomment when b/13250611 is fixed
-#LOCAL_SDK_VERSION := current
-LOCAL_JAVA_LIBRARIES += android.test.runner
+LOCAL_SDK_VERSION := current
include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/ProfileOwner/AndroidManifest.xml b/hostsidetests/devicepolicy/app/ProfileOwner/AndroidManifest.xml
new file mode 100644
index 0000000..1aaf99f
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ProfileOwner/AndroidManifest.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2014 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.cts.profileowner">
+
+ <uses-sdk android:minSdkVersion="20"/>
+
+ <application>
+ <uses-library android:name="android.test.runner" />
+ <receiver
+ android:name="com.android.cts.profileowner.BaseProfileOwnerTest$BasicAdminReceiver"
+ android:permission="android.permission.BIND_DEVICE_ADMIN">
+ <meta-data android:name="android.app.device_admin"
+ android:resource="@xml/device_admin" />
+ <intent-filter>
+ <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
+ </intent-filter>
+ </receiver>
+ </application>
+
+ <instrumentation android:name="android.test.InstrumentationTestRunner"
+ android:targetPackage="com.android.cts.profileowner"
+ android:label="Profile Owner CTS Tests"/>
+</manifest>
diff --git a/hostsidetests/devicepolicy/app/ProfileOwner/res/values/strings.xml b/hostsidetests/devicepolicy/app/ProfileOwner/res/values/strings.xml
new file mode 100644
index 0000000..640b8b5
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ProfileOwner/res/values/strings.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2014 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <!-- Label for this package -->
+ <string name="label">Android CTS - Profile Owner</string>
+</resources>
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/ProfileOwner/res/xml/device_admin.xml b/hostsidetests/devicepolicy/app/ProfileOwner/res/xml/device_admin.xml
new file mode 100644
index 0000000..8f39ed0
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ProfileOwner/res/xml/device_admin.xml
@@ -0,0 +1,19 @@
+<!-- Copyright (C) 2014 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.
+-->
+<device-admin xmlns:android="http://schemas.android.com/apk/res/android" android:visible="false">
+ <uses-policies>
+ <wipe-data />
+ </uses-policies>
+</device-admin>
diff --git a/hostsidetests/devicepolicy/app/ProfileOwner/src/com/android/cts/profileowner/BaseProfileOwnerTest.java b/hostsidetests/devicepolicy/app/ProfileOwner/src/com/android/cts/profileowner/BaseProfileOwnerTest.java
new file mode 100644
index 0000000..e7ccc74
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ProfileOwner/src/com/android/cts/profileowner/BaseProfileOwnerTest.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2014 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.cts.profileowner;
+
+import android.app.admin.DeviceAdminReceiver;
+import android.app.admin.DevicePolicyManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.test.AndroidTestCase;
+
+/**
+ * Base class for profile-owner based tests.
+ *
+ * This class handles making sure that the test is the profile owner and that it has an active admin
+ * registered, so that all tests may assume these are done.
+ */
+public class BaseProfileOwnerTest extends AndroidTestCase {
+
+ public static class BasicAdminReceiver extends DeviceAdminReceiver {
+ }
+
+ static final ComponentName ADMIN_RECEIVER_COMPONENT = new ComponentName(
+ BasicAdminReceiver.class.getPackage().getName(), BasicAdminReceiver.class.getName());
+
+ protected DevicePolicyManager mDevicePolicyManager;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ mDevicePolicyManager = (DevicePolicyManager)
+ mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
+ assertNotNull(mDevicePolicyManager);
+ // TODO: Only check this if we are running as the profile user. Otherwise, maybe check
+ // that there is a profile and that the below holds for it? If we don't want to do these
+ // checks, we could get rid for this class altogether.
+ assertTrue(mDevicePolicyManager.isAdminActive(ADMIN_RECEIVER_COMPONENT));
+ assertTrue(mDevicePolicyManager.isProfileOwnerApp(
+ ADMIN_RECEIVER_COMPONENT.getPackageName()));
+ }
+}
diff --git a/tests/src/android/os/cts/CpuInstructions.java b/hostsidetests/devicepolicy/app/ProfileOwner/src/com/android/cts/profileowner/ProfileOwnerSetupTest.java
similarity index 61%
copy from tests/src/android/os/cts/CpuInstructions.java
copy to hostsidetests/devicepolicy/app/ProfileOwner/src/com/android/cts/profileowner/ProfileOwnerSetupTest.java
index e001ceb..6fc0eb9 100644
--- a/tests/src/android/os/cts/CpuInstructions.java
+++ b/hostsidetests/devicepolicy/app/ProfileOwner/src/com/android/cts/profileowner/ProfileOwnerSetupTest.java
@@ -13,17 +13,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+package com.android.cts.profileowner;
-package android.os.cts;
-public class CpuInstructions {
+public class ProfileOwnerSetupTest extends BaseProfileOwnerTest {
- static {
- System.loadLibrary("cts_jni");
+ // This test verifies that the setUp assertions on the base class are working to verify
+ // we are the profile owner and have a valid active admin.
+ public void testProfileOwnerSetup() {
+ // Empty test. We just want the assertions from super.setUp() to be executed.
}
- public static native boolean canReadCntvct();
- public static native boolean hasSwp();
- public static native boolean hasSetend();
- public static native boolean hasCp15Barriers();
}
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ProfileOwnerTest.java
new file mode 100644
index 0000000..e2f2f4e
--- /dev/null
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ProfileOwnerTest.java
@@ -0,0 +1,227 @@
+/*
+ * Copyright (C) 2014 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.cts.devicepolicy;
+
+import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.ddmlib.Log.LogLevel;
+import com.android.ddmlib.testrunner.InstrumentationResultParser;
+import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.result.CollectingTestListener;
+import com.android.tradefed.result.TestResult;
+import com.android.tradefed.result.TestResult.TestStatus;
+import com.android.tradefed.result.TestRunResult;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IBuildReceiver;
+
+import java.io.FileNotFoundException;
+import java.util.HashSet;
+import java.util.Map;
+
+import javax.annotation.Nullable;
+
+/**
+ * Set of tests for Profile Owner use cases.
+ */
+public class ProfileOwnerTest extends DeviceTestCase implements IBuildReceiver {
+
+ private static final String RUNNER = "android.test.InstrumentationTestRunner";
+
+ private static final String PROFILE_OWNER_PKG = "com.android.cts.profileowner";
+ private static final String PROFILE_OWNER_APK = "CtsProfileOwnerApp.apk";
+
+ private static final String ADMIN_RECEIVER_TEST_CLASS =
+ PROFILE_OWNER_PKG + ".BaseProfileOwnerTest$BasicAdminReceiver";
+
+ private static final String[] REQUIRED_DEVICE_FEATURES = new String[] {
+ "android.software.managed_users",
+ "android.software.device_admin" };
+
+ private CtsBuildHelper mCtsBuild;
+ private int mUserId;
+ private boolean mHasFeature;
+
+ @Override
+ public void setBuild(IBuildInfo buildInfo) {
+ mCtsBuild = CtsBuildHelper.createBuildHelper(buildInfo);
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ assertNotNull(mCtsBuild); // ensure build has been set before test is run.
+ mHasFeature = hasDeviceFeatures(REQUIRED_DEVICE_FEATURES);
+
+ if (mHasFeature) {
+ mUserId = createUser();
+ installApp(PROFILE_OWNER_APK);
+ setProfileOwner(PROFILE_OWNER_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS);
+ }
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ if (mHasFeature) {
+ // Remove the user that we created on setUp(), and the app that we installed.
+ String removeUserCommand = "pm remove-user " + mUserId;
+ CLog.logAndDisplay(LogLevel.INFO, "Output for command " + removeUserCommand + ": "
+ + getDevice().executeShellCommand(removeUserCommand));
+ getDevice().uninstallPackage(PROFILE_OWNER_PKG);
+ }
+
+ super.tearDown();
+ }
+
+ public void testProfileOwner() throws Exception {
+ if (!mHasFeature) {
+ return;
+ }
+ // Runs all tests classes from the package, as the profile user.
+ assertTrue(runDeviceTestsAsUser(PROFILE_OWNER_PKG, null /*testClassName*/, mUserId));
+ }
+
+ private boolean hasDeviceFeatures(String[] requiredFeatures)
+ throws DeviceNotAvailableException {
+ // TODO: Move this logic to ITestDevice.
+ String command = "pm list features";
+ String commandOutput = getDevice().executeShellCommand(command);
+
+ // Extract the id of the new user.
+ HashSet<String> availableFeatures = new HashSet<String>();
+ for (String feature: commandOutput.split("\\s+")) {
+ // Each line in the output of the command has the format "feature:{FEATURE_VALUE}".
+ String[] tokens = feature.split(":");
+ assertTrue(tokens.length > 1);
+ assertEquals("feature", tokens[0]);
+ availableFeatures.add(tokens[1]);
+ }
+
+ for (String requiredFeature : requiredFeatures) {
+ if(!availableFeatures.contains(requiredFeature)) {
+ CLog.logAndDisplay(LogLevel.INFO, "Device doesn't have required feature "
+ + requiredFeature + ". Tests won't run.");
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void installApp(String fileName)
+ throws FileNotFoundException, DeviceNotAvailableException {
+ String installResult = getDevice().installPackage(mCtsBuild.getTestApp(fileName), true);
+ assertNull(String.format("Failed to install %s, Reason: %s", fileName, installResult),
+ installResult);
+ }
+
+ private int createUser() throws DeviceNotAvailableException {
+ String command =
+ "pm create-user --profileOf 0 --managed TestProfile_" + System.currentTimeMillis();
+ String commandOutput = getDevice().executeShellCommand(command);
+ CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput);
+
+ // Extract the id of the new user.
+ String[] tokens = commandOutput.split("\\s+");
+ assertTrue(tokens.length > 0);
+ assertEquals("Success:", tokens[0]);
+ return Integer.parseInt(tokens[tokens.length-1]);
+ }
+
+ private void setProfileOwner(String componentName) throws DeviceNotAvailableException {
+ String command = "dpm set-profile-owner '" + componentName + "' " + mUserId;
+ String commandOutput = getDevice().executeShellCommand(command);
+ CLog.logAndDisplay(LogLevel.INFO, "Output for command " + command + ": " + commandOutput);
+ assertTrue(commandOutput.startsWith("Success:"));
+ }
+
+ /** Returns true if the specified tests passed. Tests are run as user owner. */
+ private boolean runDeviceTests(String pkgName, @Nullable String testClassName)
+ throws DeviceNotAvailableException {
+ return runDeviceTests(pkgName, testClassName, null /*testMethodName*/, null /*userId*/);
+ }
+
+ /** Returns true if the specified tests passed. Tests are run as given user. */
+ private boolean runDeviceTestsAsUser(String pkgName, @Nullable String testClassName, int userId)
+ throws DeviceNotAvailableException {
+ return runDeviceTests(pkgName, testClassName, null /*testMethodName*/, userId);
+ }
+
+ private boolean runDeviceTests(String pkgName, @Nullable String testClassName,
+ @Nullable String testMethodName, @Nullable Integer userId)
+ throws DeviceNotAvailableException {
+ TestRunResult runResult = (userId == null)
+ ? doRunTests(pkgName, testClassName, testMethodName)
+ : doRunTestsAsUser(pkgName, testClassName, testMethodName, userId);
+ printTestResult(runResult);
+ return !runResult.hasFailedTests() && runResult.getNumPassedTests() > 0;
+ }
+
+ /** Helper method to run tests and return the listener that collected the results. */
+ private TestRunResult doRunTests(
+ String pkgName, @Nullable String testClassName, @Nullable String testMethodName)
+ throws DeviceNotAvailableException {
+ RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(
+ pkgName, RUNNER, getDevice().getIDevice());
+ if (testClassName != null && testMethodName != null) {
+ testRunner.setMethodName(testClassName, testMethodName);
+ } else if (testClassName != null) {
+ testRunner.setClassName(testClassName);
+ }
+
+ CollectingTestListener listener = new CollectingTestListener();
+ assertTrue(getDevice().runInstrumentationTests(testRunner, listener));
+ return listener.getCurrentRunResults();
+ }
+
+ private TestRunResult doRunTestsAsUser(String pkgName, @Nullable String testClassName,
+ @Nullable String testMethodName, int userId)
+ throws DeviceNotAvailableException {
+ // TODO: move this to RemoteAndroidTestRunner once it supports users. Should be straight
+ // forward to add a RemoteAndroidTestRunner.setUser(userId) method. Then we can merge both
+ // doRunTests* methods.
+ StringBuilder testsToRun = new StringBuilder();
+ if (testClassName != null) {
+ testsToRun.append("-e class " + testClassName);
+ if (testMethodName != null) {
+ testsToRun.append("#" + testMethodName);
+ }
+ }
+ String command = "am instrument --user " + userId + " -w -r " + testsToRun + " "
+ + pkgName + "/" + RUNNER;
+ CLog.i("Running " + command);
+
+ CollectingTestListener listener = new CollectingTestListener();
+ InstrumentationResultParser parser = new InstrumentationResultParser(pkgName, listener);
+ getDevice().executeShellCommand(command, parser);
+ return listener.getCurrentRunResults();
+ }
+
+ private void printTestResult(TestRunResult runResult) {
+ for (Map.Entry<TestIdentifier, TestResult> testEntry :
+ runResult.getTestResults().entrySet()) {
+ TestResult testResult = testEntry.getValue();
+ CLog.logAndDisplay(LogLevel.INFO,
+ "Test " + testEntry.getKey() + ": " + testResult.getStatus());
+ if (testResult.getStatus() != TestStatus.PASSED) {
+ CLog.logAndDisplay(LogLevel.WARN, testResult.getStackTrace());
+ }
+ }
+ }
+}
diff --git a/hostsidetests/monkey/src/com/android/cts/monkey/AbstractMonkeyTest.java b/hostsidetests/monkey/src/com/android/cts/monkey/AbstractMonkeyTest.java
index 9c27b62..9e04274 100644
--- a/hostsidetests/monkey/src/com/android/cts/monkey/AbstractMonkeyTest.java
+++ b/hostsidetests/monkey/src/com/android/cts/monkey/AbstractMonkeyTest.java
@@ -1,28 +1,37 @@
package com.android.cts.monkey;
import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.util.AbiUtils;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
import com.android.tradefed.testtype.IBuildReceiver;
import java.io.File;
-abstract class AbstractMonkeyTest extends DeviceTestCase implements IBuildReceiver {
+abstract class AbstractMonkeyTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
static final String[] PKGS = {"com.android.cts.monkey", "com.android.cts.monkey2"};
static final String[] APKS = {"CtsMonkeyApp.apk", "CtsMonkeyApp2.apk"};
- /**
+ /**
* Base monkey command with flags to avoid side effects like airplane mode.
*/
static final String MONKEY_CMD = "monkey --pct-touch 0 --pct-motion 0 --pct-majornav 0 --pct-syskeys 0 --pct-anyevent 0 --pct-rotation 0";
+ IAbi mAbi;
CtsBuildHelper mBuild;
ITestDevice mDevice;
@Override
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
+ @Override
public void setBuild(IBuildInfo buildInfo) {
mBuild = CtsBuildHelper.createBuildHelper(buildInfo);
}
@@ -31,10 +40,11 @@
protected void setUp() throws Exception {
super.setUp();
mDevice = getDevice();
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
for (int i = 0; i < PKGS.length; i++) {
mDevice.uninstallPackage(PKGS[i]);
File app = mBuild.getTestApp(APKS[i]);
- mDevice.installPackage(app, false);
+ mDevice.installPackage(app, false, options);
}
clearLogCat();
}
diff --git a/hostsidetests/sample/src/android/sample/cts/SampleHostResultTest.java b/hostsidetests/sample/src/android/sample/cts/SampleHostResultTest.java
index a3bc08f..bed4c05 100644
--- a/hostsidetests/sample/src/android/sample/cts/SampleHostResultTest.java
+++ b/hostsidetests/sample/src/android/sample/cts/SampleHostResultTest.java
@@ -24,11 +24,12 @@
import com.android.cts.util.ResultUnit;
import com.android.cts.util.ReportLog;
import com.android.cts.util.Stat;
-import com.android.ddmlib.Log;
import com.android.ddmlib.IDevice;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.util.CommandResult;
import com.android.tradefed.util.CommandStatus;
@@ -41,7 +42,7 @@
/**
* Test to measure the transfer time of a file from the host to the device.
*/
-public class SampleHostResultTest extends DeviceTestCase implements IBuildReceiver {
+public class SampleHostResultTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
private static final String TAG = SampleHostResultTest.class.getSimpleName();
@@ -67,6 +68,16 @@
*/
private ITestDevice mDevice;
+ /**
+ * A reference to the ABI under test.
+ */
+ private IAbi mAbi;
+
+ @Override
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
@Override
public void setBuild(IBuildInfo buildInfo) {
// Get the build, this is used to access the APK.
@@ -122,7 +133,7 @@
// Compute the stats.
Stat.StatResult stat = Stat.getStat(result);
// Get the report for this test and add the results to record.
- HostReportLog report = new HostReportLog(mDevice.getSerialNumber(),
+ HostReportLog report = new HostReportLog(mDevice.getSerialNumber(), mAbi.getName(),
ReportLog.getClassMethodNames());
report.printArray("Times", result, ResultType.LOWER_BETTER, ResultUnit.MS);
report.printValue("Min", stat.mMin, ResultType.LOWER_BETTER, ResultUnit.MS);
diff --git a/hostsidetests/sample/src/android/sample/cts/SampleHostTest.java b/hostsidetests/sample/src/android/sample/cts/SampleHostTest.java
index 7ccde0e..3cc4aa9 100644
--- a/hostsidetests/sample/src/android/sample/cts/SampleHostTest.java
+++ b/hostsidetests/sample/src/android/sample/cts/SampleHostTest.java
@@ -17,9 +17,12 @@
package android.sample.cts;
import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.util.AbiUtils;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
import com.android.tradefed.testtype.IBuildReceiver;
import java.io.File;
@@ -29,11 +32,11 @@
/**
* Test to check the APK logs to Logcat.
*
- * When this test builds, it also builds {@see android.sample.app.SampleDeviceActivity} into an APK
+ * When this test builds, it also builds {@link android.sample.app.SampleDeviceActivity} into an APK
* which it then installs at runtime and starts. The activity simply prints a message to Logcat and
* then gets uninstalled.
*/
-public class SampleHostTest extends DeviceTestCase implements IBuildReceiver {
+public class SampleHostTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
/**
* The package name of the APK.
@@ -62,6 +65,11 @@
private static final String TEST_STRING = "SampleTestString";
/**
+ * The ABI to use.
+ */
+ private IAbi mAbi;
+
+ /**
* A reference to the build.
*/
private CtsBuildHelper mBuild;
@@ -72,6 +80,11 @@
private ITestDevice mDevice;
@Override
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
+ @Override
public void setBuild(IBuildInfo buildInfo) {
// Get the build, this is used to access the APK.
mBuild = CtsBuildHelper.createBuildHelper(buildInfo);
@@ -86,8 +99,10 @@
mDevice.uninstallPackage(PACKAGE);
// Get the APK from the build.
File app = mBuild.getTestApp(APK);
+ // Get the ABI flag.
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
// Install the APK on the device.
- mDevice.installPackage(app, false);
+ mDevice.installPackage(app, false, options);
}
@Override
@@ -118,6 +133,7 @@
testString = line.split(":")[1].trim();
}
}
+ in.close();
// Assert the logged string matches the test string.
assertEquals("Incorrect test string", TEST_STRING, testString);
}
diff --git a/hostsidetests/theme/app/Android.mk b/hostsidetests/theme/app/Android.mk
index d7ca509..1be2983 100644
--- a/hostsidetests/theme/app/Android.mk
+++ b/hostsidetests/theme/app/Android.mk
@@ -32,7 +32,7 @@
#Flags to tell the Android Asset Packaging Tool not to strip for some densities
LOCAL_AAPT_FLAGS = -c land -c xx_YY -c cs -c small -c normal -c large -c xlarge \
- -c 640dpi -c 480dpi -c 400dpi -c 320dpi -c 240dpi -c 213dpi -c 160dpi -c 120dpi
+ -c 640dpi -c 560dpi -c 480dpi -c 400dpi -c 320dpi -c 240dpi -c 213dpi -c 160dpi -c 120dpi
LOCAL_PACKAGE_NAME := CtsThemeDeviceApp
diff --git a/hostsidetests/theme/app/res/drawable-560dpi/display_info.png b/hostsidetests/theme/app/res/drawable-560dpi/display_info.png
new file mode 100644
index 0000000..babe0da
--- /dev/null
+++ b/hostsidetests/theme/app/res/drawable-560dpi/display_info.png
Binary files differ
diff --git a/hostsidetests/theme/app/src/android/theme/app/DisplayInfoActivity.java b/hostsidetests/theme/app/src/android/theme/app/DisplayInfoActivity.java
index 12504c1..f263eef 100644
--- a/hostsidetests/theme/app/src/android/theme/app/DisplayInfoActivity.java
+++ b/hostsidetests/theme/app/src/android/theme/app/DisplayInfoActivity.java
@@ -68,6 +68,9 @@
case DisplayMetrics.DENSITY_XXHIGH:
return "xxhdpi";
+ case DisplayMetrics.DENSITY_560:
+ return "560dpi";
+
case DisplayMetrics.DENSITY_XXXHIGH:
return "xxxhdpi";
diff --git a/hostsidetests/theme/assets/21/560dpi.zip b/hostsidetests/theme/assets/21/560dpi.zip
new file mode 100644
index 0000000..eff363c
--- /dev/null
+++ b/hostsidetests/theme/assets/21/560dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java b/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java
index 19c37c0..33e67e5 100644
--- a/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java
+++ b/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java
@@ -49,7 +49,6 @@
private final String mStoragePath;
-
public ComparisonTask(ITestDevice device, File reference, String name) {
mDevice = device;
mReference = reference;
diff --git a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
index c88fb44..90a0c72 100644
--- a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
+++ b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
@@ -17,16 +17,18 @@
package android.theme.cts;
import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.util.AbiUtils;
+import com.android.cts.util.TimeoutReq;
import com.android.ddmlib.Log;
import com.android.ddmlib.Log.LogLevel;
import com.android.ddmlib.IShellOutputReceiver;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
import com.android.tradefed.testtype.IBuildReceiver;
-import com.android.cts.util.TimeoutReq;
-
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
@@ -46,7 +48,7 @@
/**
* Test to check the Holo theme has not been changed.
*/
-public class ThemeHostTest extends DeviceTestCase implements IBuildReceiver {
+public class ThemeHostTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
private static final String TAG = ThemeHostTest.class.getSimpleName();
@@ -172,6 +174,9 @@
private final HashMap<String, File> mReferences = new HashMap<String, File>();
+ /** The ABI to use. */
+ private IAbi mAbi;
+
/** A reference to the build. */
private CtsBuildHelper mBuild;
@@ -183,6 +188,11 @@
private ExecutorCompletionService<Boolean> mCompletionService;
@Override
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
+ @Override
public void setBuild(IBuildInfo buildInfo) {
// Get the build, this is used to access the APK.
mBuild = CtsBuildHelper.createBuildHelper(buildInfo);
@@ -197,8 +207,10 @@
mDevice.uninstallPackage(PACKAGE);
// Get the APK from the build.
File app = mBuild.getTestApp(APK);
+ // Get the ABI flag.
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
// Install the APK on the device.
- mDevice.installPackage(app, false);
+ mDevice.installPackage(app, false, options);
final String densityProp;
@@ -328,6 +340,7 @@
}
}
}
+ in.close();
}
return success;
@@ -349,6 +362,8 @@
return "400dpi";
case 480:
return "xxhdpi";
+ case 560:
+ return "560dpi";
case 640:
return "xxxhdpi";
default:
diff --git a/hostsidetests/usb/src/com/android/cts/usb/TestUsbTest.java b/hostsidetests/usb/src/com/android/cts/usb/TestUsbTest.java
index a8ac3e0..2a69e39 100644
--- a/hostsidetests/usb/src/com/android/cts/usb/TestUsbTest.java
+++ b/hostsidetests/usb/src/com/android/cts/usb/TestUsbTest.java
@@ -16,6 +16,7 @@
package com.android.cts.usb;
import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.Log;
import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
@@ -29,6 +30,8 @@
import com.android.tradefed.result.InputStreamSource;
import com.android.tradefed.result.TestRunResult;
import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.util.CommandResult;
import com.android.tradefed.util.CommandStatus;
@@ -48,16 +51,23 @@
/**
* Functional tests for usb connection
*/
-public class TestUsbTest extends DeviceTestCase implements IBuildReceiver {
+public class TestUsbTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
private static final String LOG_TAG = "TestUsbTest";
private static final String CTS_RUNNER = "android.support.test.runner.AndroidJUnitRunner";
private static final String PACKAGE_NAME = "com.android.cts.usb.serialtest";
private static final String APK_NAME="CtsUsbSerialTestApp.apk";
private ITestDevice mDevice;
+ private IAbi mAbi;
+ private String mAbiBitness;
private CtsBuildHelper mBuild;
@Override
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
+ @Override
public void setBuild(IBuildInfo buildInfo) {
mBuild = CtsBuildHelper.createBuildHelper(buildInfo);
}
@@ -68,7 +78,8 @@
mDevice = getDevice();
mDevice.uninstallPackage(PACKAGE_NAME);
File app = mBuild.getTestApp(APK_NAME);
- mDevice.installPackage(app, false);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+ mDevice.installPackage(app, false, options);
}
@Override
diff --git a/libs/commonutil/src/com/android/cts/util/AbiUtils.java b/libs/commonutil/src/com/android/cts/util/AbiUtils.java
new file mode 100644
index 0000000..f28237c
--- /dev/null
+++ b/libs/commonutil/src/com/android/cts/util/AbiUtils.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2014 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.cts.util;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Utility class for handling device ABIs
+ */
+public class AbiUtils {
+
+ /**
+ * The set of 32Bit ABIs.
+ */
+ private static final Set<String> ABIS_32BIT = new HashSet<String>();
+
+ /**
+ * The set of 64Bit ABIs.
+ */
+ private static final Set<String> ABIS_64BIT = new HashSet<String>();
+
+ /**
+ * The set of ARM ABIs.
+ */
+ private static final Set<String> ARM_ABIS = new HashSet<String>();
+
+ /**
+ * The set of Intel ABIs.
+ */
+ private static final Set<String> INTEL_ABIS = new HashSet<String>();
+
+ /**
+ * The set of Mips ABIs.
+ */
+ private static final Set<String> MIPS_ABIS = new HashSet<String>();
+
+ /**
+ * The set of ABI names which CTS supports.
+ */
+ private static final Set<String> ABIS_SUPPORTED_BY_CTS = new HashSet<String>();
+
+ /**
+ * The map of architecture to ABI.
+ */
+ private static final Map<String, Set<String>> ARCH_TO_ABIS = new HashMap<String, Set<String>>();
+ static {
+ ABIS_32BIT.add("armeabi-v7a");
+ ABIS_32BIT.add("x86");
+ ABIS_32BIT.add("mips");
+
+ ABIS_64BIT.add("arm64-v8a");
+ ABIS_64BIT.add("x86_64");
+ ABIS_64BIT.add("mips64");
+
+ ARM_ABIS.add("armeabi-v7a");
+ ARM_ABIS.add("arm64-v8a");
+
+ INTEL_ABIS.add("x86");
+ INTEL_ABIS.add("x86_64");
+
+ MIPS_ABIS.add("mips");
+ MIPS_ABIS.add("mips64");
+
+ ARCH_TO_ABIS.put("arm", ARM_ABIS);
+ ARCH_TO_ABIS.put("arm64", ARM_ABIS);
+ ARCH_TO_ABIS.put("x86", INTEL_ABIS);
+ ARCH_TO_ABIS.put("x86_64", INTEL_ABIS);
+ ARCH_TO_ABIS.put("mips", MIPS_ABIS);
+ ARCH_TO_ABIS.put("mips64", MIPS_ABIS);
+
+ ABIS_SUPPORTED_BY_CTS.addAll(ARM_ABIS);
+ ABIS_SUPPORTED_BY_CTS.addAll(INTEL_ABIS);
+ ABIS_SUPPORTED_BY_CTS.addAll(MIPS_ABIS);
+ }
+
+ /**
+ * Private constructor to avoid instantiation.
+ */
+ private AbiUtils() {}
+
+ /**
+ * Returns the set of ABIs associated with the given architecture.
+ * @param arch The architecture to look up.
+ * @return a new Set containing the ABIs.
+ */
+ public static Set<String> getAbisForArch(String arch) {
+ return new HashSet<String>(ARCH_TO_ABIS.get(arch));
+ }
+
+ /**
+ * Returns the set of ABIs supported by CTS.
+ * @return a new Set containing the supported ABIs.
+ */
+ public static Set<String> getAbisSupportedByCts() {
+ return new HashSet<String>(ABIS_SUPPORTED_BY_CTS);
+ }
+
+ /**
+ * @param abi The ABI name to test.
+ * @return true if the given ABI is supported by CTS.
+ */
+ public static boolean isAbiSupportedByCts(String abi) {
+ return ABIS_SUPPORTED_BY_CTS.contains(abi);
+ }
+
+ /**
+ * Creates a flag for the given ABI.
+ * @param abi the ABI to create the flag for.
+ * @return a string which can be add to a command sent to ADB.
+ */
+ public static String createAbiFlag(String abi) {
+ if (abi == null || abi.isEmpty() || !isAbiSupportedByCts(abi)) {
+ return "";
+ }
+ return String.format("--abi %s ", abi);
+ }
+
+ /**
+ * Creates a unique id from the given ABI and name.
+ * @param abi The ABI to use.
+ * @param name The name to use.
+ * @return a string which uniquely identifies a run.
+ */
+ public static String createId(String abi, String name) {
+ return String.format("%s %s", abi, name);
+ }
+
+ /**
+ * Parses a unique id into the ABI and name.
+ * @param id The id to parse.
+ * @return a string array containing the ABI and name.
+ */
+ public static String[] parseId(String id) {
+ if (id == null || !id.contains(" ")) {
+ return new String[] {"", ""};
+ }
+ return id.split(" ");
+ }
+
+ /**
+ * @param name The name of the ABI.
+ * @return The bitness of the ABI with the given name
+ */
+ public static String getBitness(String name) {
+ return ABIS_32BIT.contains(name) ? "32" : "64";
+ }
+}
diff --git a/libs/commonutil/src/com/android/cts/util/CtsException.java b/libs/commonutil/src/com/android/cts/util/CtsException.java
deleted file mode 100644
index 7e79590..0000000
--- a/libs/commonutil/src/com/android/cts/util/CtsException.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.cts.util;
-
-/**
- * Exception throw by CTS test to pass the result to host
- * This should not be thrown by test app unless the result is complete.
- */
-@SuppressWarnings("serial")
-public class CtsException extends Exception {
- public CtsException(String message) {
- super(message);
- }
-}
diff --git a/libs/commonutil/src/com/android/cts/util/ReportLog.java b/libs/commonutil/src/com/android/cts/util/ReportLog.java
index 115cec6..56b431a 100644
--- a/libs/commonutil/src/com/android/cts/util/ReportLog.java
+++ b/libs/commonutil/src/com/android/cts/util/ReportLog.java
@@ -43,22 +43,19 @@
/**
* print array of values to output log
*/
- public void printArray(String message, double[] values, ResultType type,
- ResultUnit unit) {
+ public void printArray(String message, double[] values, ResultType type, ResultUnit unit) {
doPrintArray(message, values, type, unit);
}
/**
* Print a value to output log
*/
- public void printValue(String message, double value, ResultType type,
- ResultUnit unit) {
+ public void printValue(String message, double value, ResultType type, ResultUnit unit) {
double[] vals = { value };
doPrintArray(message, vals, type, unit);
}
- private void doPrintArray(String message, double[] values, ResultType type,
- ResultUnit unit) {
+ private void doPrintArray(String message, double[] values, ResultType type, ResultUnit unit) {
StringBuilder builder = new StringBuilder();
// note mDepth + 1 as this function will be called by printVaue or printArray
// and we need caller of printValue / printArray
@@ -104,17 +101,19 @@
/**
* For standard report summary without target value.
* Note that this function will not fail as there is no target.
- * @param messsage
+ * @param message
* @param value
* @param type type of the value
* @param unit unit of the data
*/
- public void printSummary(String message, double value, ResultType type,
- ResultUnit unit) {
+ public void printSummary(String message, double value, ResultType type, ResultUnit unit) {
mSummary = message + LOG_ELEM_SEPARATOR + " " + LOG_ELEM_SEPARATOR + type.getXmlString() +
LOG_ELEM_SEPARATOR + unit.getXmlString() + LOG_ELEM_SEPARATOR + value;
}
+ /**
+ * @return a string representation of this report.
+ */
protected String generateReport() {
if ((mSummary == null) && mMessages.isEmpty()) {
// just return empty string
diff --git a/libs/deviceutil/src/android/cts/util/DeviceReportLog.java b/libs/deviceutil/src/android/cts/util/DeviceReportLog.java
index a3ceecf..63b07b7 100644
--- a/libs/deviceutil/src/android/cts/util/DeviceReportLog.java
+++ b/libs/deviceutil/src/android/cts/util/DeviceReportLog.java
@@ -24,12 +24,12 @@
public class DeviceReportLog extends ReportLog {
private static final String TAG = "DeviceCtsReport";
- private static final String CTS_RESULT = "CTS_RESULT";
+ private static final String CTS_RESULT_KEY = "CTS_TEST_RESULT";
private static final int INST_STATUS_IN_PROGRESS = 2;
private static final int BASE_DEPTH = 4;
public DeviceReportLog() {
- mDepth = BASE_DEPTH;
+ this(0);
}
public DeviceReportLog(int depth) {
@@ -46,7 +46,7 @@
String report = generateReport();
if (!report.equals("")) {
Bundle output = new Bundle();
- output.putString(CTS_RESULT, report);
+ output.putString(CTS_RESULT_KEY, report);
instrumentation.sendStatus(INST_STATUS_IN_PROGRESS, output);
}
}
diff --git a/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java b/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java
index fe28a96..a009ce2 100644
--- a/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java
+++ b/suite/cts/deviceTests/videoperf/src/com/android/cts/videoperf/VideoEncoderDecoderTest.java
@@ -387,31 +387,36 @@
int res = codec.dequeueOutputBuffer(info, VIDEO_CODEC_WAIT_TIME_US);
if (res >= 0) {
int outputBufIndex = res;
- ByteBuffer buf = codecOutputBuffers[outputBufIndex];
- if (VERBOSE && (outFrameCount == 0)) {
- printByteBuffer("Y ", buf, 0, 20);
- printByteBuffer("UV ", buf, mVideoWidth * mVideoHeight, 20);
- printByteBuffer("UV ", buf, mVideoWidth * mVideoHeight + mVideoWidth * 60, 20);
- }
- Point origin = getOrigin(outFrameCount);
- for (int i = 0; i < PIXEL_CHECK_PER_FRAME; i++) {
- int w = mRandom.nextInt(mVideoWidth);
- int h = mRandom.nextInt(mVideoHeight);
- getPixelValuesFromYUVBuffers(origin.x, origin.y, w, h, expected);
- getPixelValuesFromOutputBuffer(buf, w, h, decoded);
- if (VERBOSE) {
- Log.i(TAG, outFrameCount + "-" + i + "- th round expcted " + expected.mY +
- "," + expected.mU + "," + expected.mV + " decoded " + decoded.mY +
- "," + decoded.mU + "," + decoded.mV);
+
+ // only do YUV compare on EOS frame if the buffer size is none-zero
+ if (info.size > 0) {
+ ByteBuffer buf = codecOutputBuffers[outputBufIndex];
+ if (VERBOSE && (outFrameCount == 0)) {
+ printByteBuffer("Y ", buf, 0, 20);
+ printByteBuffer("UV ", buf, mVideoWidth * mVideoHeight, 20);
+ printByteBuffer("UV ", buf,
+ mVideoWidth * mVideoHeight + mVideoWidth * 60, 20);
}
- totalErrorSquared += expected.calcErrorSquared(decoded);
+ Point origin = getOrigin(outFrameCount);
+ for (int i = 0; i < PIXEL_CHECK_PER_FRAME; i++) {
+ int w = mRandom.nextInt(mVideoWidth);
+ int h = mRandom.nextInt(mVideoHeight);
+ getPixelValuesFromYUVBuffers(origin.x, origin.y, w, h, expected);
+ getPixelValuesFromOutputBuffer(buf, w, h, decoded);
+ if (VERBOSE) {
+ Log.i(TAG, outFrameCount + "-" + i + "- th round expcted " + expected.mY
+ + "," + expected.mU + "," + expected.mV + " decoded "
+ + decoded.mY + "," + decoded.mU + "," + decoded.mV);
+ }
+ totalErrorSquared += expected.calcErrorSquared(decoded);
+ }
+ outFrameCount++;
}
codec.releaseOutputBuffer(outputBufIndex, false /* render */);
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
Log.d(TAG, "saw output EOS.");
sawOutputEOS = true;
}
- outFrameCount++;
} else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
codecOutputBuffers = codec.getOutputBuffers();
Log.d(TAG, "output buffers have changed.");
diff --git a/suite/cts/hostTests/jank/src/com/android/cts/jank/CtsHostJankTest.java b/suite/cts/hostTests/jank/src/com/android/cts/jank/CtsHostJankTest.java
index f8c7ec1..e196bfb 100644
--- a/suite/cts/hostTests/jank/src/com/android/cts/jank/CtsHostJankTest.java
+++ b/suite/cts/hostTests/jank/src/com/android/cts/jank/CtsHostJankTest.java
@@ -23,16 +23,19 @@
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
import com.android.tradefed.testtype.IBuildReceiver;
import java.io.File;
import java.util.HashMap;
import java.util.Scanner;
-public class CtsHostJankTest extends DeviceTestCase implements IBuildReceiver {
+public class CtsHostJankTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
private static final String TAG = CtsHostJankTest.class.getSimpleName();
private static final String DEVICE_LOCATION = "/data/local/tmp/";
+ // FIXME uiautomator is deprecated and does not support --abi flag
private static final String RUN_UI_AUTOMATOR_CMD = "uiautomator runtest %s -c %s";
private final String mHostTestClass;
private final String mDeviceTestClass;
@@ -40,6 +43,7 @@
private final String mJarPath;
protected ITestDevice mDevice;
protected CtsBuildHelper mBuild;
+ protected IAbi mAbi;
public CtsHostJankTest(String jarName, String deviceTestClass, String hostTestClass) {
this.mHostTestClass = hostTestClass;
@@ -49,6 +53,11 @@
}
@Override
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
+ @Override
public void setBuild(IBuildInfo buildInfo) {
mBuild = CtsBuildHelper.createBuildHelper(buildInfo);
}
@@ -80,6 +89,7 @@
new IShellOutputReceiver() {
private StringBuilder sb = new StringBuilder();
+ @Override
public void addOutput(byte[] data, int offset, int length) {
byte[] raw = new byte[length];
for (int i = 0; i < length; i++) {
@@ -88,10 +98,12 @@
sb.append(new String(raw));
}
+ @Override
public void flush() {
Log.logAndDisplay(LogLevel.INFO, TAG, sb.toString());
}
+ @Override
public boolean isCancelled() {
return false;
}
@@ -109,6 +121,7 @@
results.put(parts[0], Double.parseDouble(parts[1]));
}
}
+ in.close();
Log.logAndDisplay(LogLevel.INFO, TAG, "Results: " + results);
assertEquals("Could not parse the results file: ", 4, results.size());
@@ -118,8 +131,8 @@
double avgMaxAccFrames = results.get("average of max accumulated frames");
// Create and deliver the report.
- HostReportLog report =
- new HostReportLog(mDevice.getSerialNumber(), mHostTestClass + "#" + testName);
+ HostReportLog report = new HostReportLog(mDevice.getSerialNumber(), mAbi.getName(),
+ mHostTestClass + "#" + testName);
report.printValue(
"Average Frame Rate", avgFrameRate, ResultType.HIGHER_BETTER, ResultUnit.COUNT);
report.printValue("Average of Maximum Accumulated Frames", avgMaxAccFrames,
diff --git a/suite/cts/hostTests/jank/src/com/android/cts/jank/opengl/CtsHostJankOpenGl.java b/suite/cts/hostTests/jank/src/com/android/cts/jank/opengl/CtsHostJankOpenGl.java
index ebd5bfa..2942ecf 100644
--- a/suite/cts/hostTests/jank/src/com/android/cts/jank/opengl/CtsHostJankOpenGl.java
+++ b/suite/cts/hostTests/jank/src/com/android/cts/jank/opengl/CtsHostJankOpenGl.java
@@ -14,7 +14,7 @@
package com.android.cts.jank.opengl;
import com.android.cts.jank.CtsHostJankTest;
-
+import com.android.cts.util.AbiUtils;
import java.io.File;
public class CtsHostJankOpenGl extends CtsHostJankTest {
@@ -36,7 +36,8 @@
// Install the app.
mDevice.uninstallPackage(APK_PACKAGE);
File app = mBuild.getTestApp(APK);
- mDevice.installPackage(app, false);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+ mDevice.installPackage(app, false, options);
}
@Override
diff --git a/suite/cts/hostTests/jank/src/com/android/cts/jank/ui/CtsHostJankUi.java b/suite/cts/hostTests/jank/src/com/android/cts/jank/ui/CtsHostJankUi.java
index 3027899..a07171e 100644
--- a/suite/cts/hostTests/jank/src/com/android/cts/jank/ui/CtsHostJankUi.java
+++ b/suite/cts/hostTests/jank/src/com/android/cts/jank/ui/CtsHostJankUi.java
@@ -14,7 +14,7 @@
package com.android.cts.jank.ui;
import com.android.cts.jank.CtsHostJankTest;
-
+import com.android.cts.util.AbiUtils;
import java.io.File;
public class CtsHostJankUi extends CtsHostJankTest {
@@ -36,7 +36,8 @@
// Install the app.
mDevice.uninstallPackage(APK_PACKAGE);
File app = mBuild.getTestApp(APK);
- mDevice.installPackage(app, false);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+ mDevice.installPackage(app, false, options);
}
@Override
diff --git a/suite/cts/hostTests/uihost/src/com/android/cts/uihost/InstallTimeTest.java b/suite/cts/hostTests/uihost/src/com/android/cts/uihost/InstallTimeTest.java
index 63c2d84..75a2e92 100644
--- a/suite/cts/hostTests/uihost/src/com/android/cts/uihost/InstallTimeTest.java
+++ b/suite/cts/hostTests/uihost/src/com/android/cts/uihost/InstallTimeTest.java
@@ -18,6 +18,7 @@
import com.android.cts.tradefed.build.CtsBuildHelper;
import com.android.cts.tradefed.util.HostReportLog;
+import com.android.cts.util.AbiUtils;
import com.android.cts.util.MeasureRun;
import com.android.cts.util.MeasureTime;
import com.android.cts.util.ResultType;
@@ -28,6 +29,8 @@
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
import com.android.tradefed.testtype.IBuildReceiver;
import java.io.File;
@@ -36,9 +39,10 @@
/**
* Test to measure installation time of a APK.
*/
-public class InstallTimeTest extends DeviceTestCase implements IBuildReceiver {
+public class InstallTimeTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
private CtsBuildHelper mBuild;
private ITestDevice mDevice;
+ private IAbi mAbi;
private static final String TAG = "InstallTimeTest";
static final String PACKAGE = "com.replica.replicaisland";
@@ -46,6 +50,11 @@
private static final double OUTLIER_THRESHOLD = 0.1;
@Override
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
+ @Override
public void setBuild(IBuildInfo buildInfo) {
mBuild = CtsBuildHelper.createBuildHelper(buildInfo);
}
@@ -64,8 +73,8 @@
}
public void testInstallTime() throws Exception {
- HostReportLog report =
- new HostReportLog(mDevice.getSerialNumber(), ReportLog.getClassMethodNames());
+ HostReportLog report = new HostReportLog(mDevice.getSerialNumber(), mAbi.getName(),
+ ReportLog.getClassMethodNames());
final int NUMBER_REPEAT = 10;
final CtsBuildHelper build = mBuild;
final ITestDevice device = mDevice;
@@ -77,7 +86,8 @@
@Override
public void run(int i) throws Exception {
File app = build.getTestApp(APK);
- device.installPackage(app, false);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+ device.installPackage(app, false, options);
}
});
report.printArray("install time", result, ResultType.LOWER_BETTER,
diff --git a/suite/cts/hostTests/uihost/src/com/android/cts/uihost/TaskSwitchingTest.java b/suite/cts/hostTests/uihost/src/com/android/cts/uihost/TaskSwitchingTest.java
index 50a2047..9ccff10 100644
--- a/suite/cts/hostTests/uihost/src/com/android/cts/uihost/TaskSwitchingTest.java
+++ b/suite/cts/hostTests/uihost/src/com/android/cts/uihost/TaskSwitchingTest.java
@@ -17,9 +17,9 @@
package com.android.cts.uihost;
import com.android.cts.tradefed.build.CtsBuildHelper;
-import com.android.cts.tradefed.result.CtsReportUtil;
import com.android.cts.tradefed.util.CtsHostStore;
import com.android.cts.tradefed.util.HostReportLog;
+import com.android.cts.util.AbiUtils;
import com.android.cts.util.ReportLog;
import com.android.cts.util.TimeoutReq;
import com.android.ddmlib.Log;
@@ -34,6 +34,8 @@
import com.android.tradefed.result.TestResult;
import com.android.tradefed.result.TestRunResult;
import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
import com.android.tradefed.testtype.IBuildReceiver;
import java.io.File;
@@ -45,12 +47,13 @@
* Actual test is done in device, but this host side code installs all necessary APKs
* and starts device test which is in CtsDeviceTaskswitchingControl.
*/
-public class TaskSwitchingTest extends DeviceTestCase implements IBuildReceiver {
+public class TaskSwitchingTest extends DeviceTestCase implements IAbiReceiver, IBuildReceiver {
private static final String TAG = "TaskSwitchingTest";
private final static String RUNNER = "android.support.test.runner.AndroidJUnitRunner";
private CtsBuildHelper mBuild;
private ITestDevice mDevice;
private String mCtsReport = null;
+ private IAbi mAbi;
static final String[] PACKAGES = {
"com.android.cts.taskswitching.control",
@@ -64,6 +67,11 @@
};
@Override
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
+ @Override
public void setBuild(IBuildInfo buildInfo) {
mBuild = CtsBuildHelper.createBuildHelper(buildInfo);
}
@@ -72,10 +80,11 @@
protected void setUp() throws Exception {
super.setUp();
mDevice = getDevice();
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
for (int i = 0; i < PACKAGES.length; i++) {
mDevice.uninstallPackage(PACKAGES[i]);
File app = mBuild.getTestApp(APKS[i]);
- mDevice.installPackage(app, false);
+ mDevice.installPackage(app, false, options);
}
}
@@ -90,8 +99,9 @@
@TimeoutReq(minutes = 30)
public void testTaskswitching() throws Exception {
- HostReportLog report =
- new HostReportLog(mDevice.getSerialNumber(), ReportLog.getClassMethodNames());
+ // TODO is this used?
+ HostReportLog report = new HostReportLog(mDevice.getSerialNumber(), mAbi.getName(),
+ ReportLog.getClassMethodNames());
RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(PACKAGES[0], RUNNER,
mDevice.getIDevice());
LocalListener listener = new LocalListener();
@@ -101,7 +111,7 @@
fail(result.getRunFailureMessage());
}
assertNotNull("no performance data", mCtsReport);
- CtsHostStore.storeCtsResult(mDevice.getSerialNumber(),
+ CtsHostStore.storeCtsResult(mDevice.getSerialNumber(), mAbi.getName(),
ReportLog.getClassMethodNames(), mCtsReport);
}
@@ -110,7 +120,7 @@
@Override
public void testEnded(TestIdentifier test, Map<String, String> testMetrics) {
// necessary as testMetrics passed from CollectingTestListerner is empty
- mCtsReport = CtsReportUtil.getCtsResultFromMetrics(testMetrics);
+ mCtsReport = testMetrics.get("CTS_TEST_REPORT");
super.testEnded(test, testMetrics);
}
}
diff --git a/tests/Android.mk b/tests/Android.mk
index f66946a..39a27fe 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -19,13 +19,9 @@
LOCAL_SRC_FILES := $(call all-java-files-under, src)\
$(call all-renderscript-files-under, src)\
- src/android/app/cts/ISecondary.aidl\
- src/android/os/cts/IEmptyService.aidl\
LOCAL_JAVA_LIBRARIES := android.test.runner
-LOCAL_JNI_SHARED_LIBRARIES := libcts_jni
-
# Resource unit tests use a private locale and some densities
LOCAL_AAPT_FLAGS = -c xx_YY -c cs -c small -c normal -c large -c xlarge \
-c 320dpi -c 240dpi -c 160dpi -c 32dpi \
diff --git a/tests/AndroidManifest.xml b/tests/AndroidManifest.xml
index 9190da8..b3798b1 100644
--- a/tests/AndroidManifest.xml
+++ b/tests/AndroidManifest.xml
@@ -158,14 +158,6 @@
</intent-filter>
</activity>
- <activity android:name="android.view.cts.ViewStubStubActivity"
- android:label="ViewStubStubActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN"/>
- <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
- </intent-filter>
- </activity>
-
<activity android:name="android.widget.cts.ViewFlipperStubActivity"
android:label="ViewFlipperStubActivity">
<intent-filter>
@@ -199,20 +191,6 @@
</intent-filter>
</activity>
- <activity android:name="android.view.cts.UsingViewsStubActivity"
- android:label="Using Views Test">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
- </intent-filter>
- </activity>
- <activity android:name="android.view.cts.FocusHandlingStubActivity"
- android:label="Focus Handling Test">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
- </intent-filter>
- </activity>
<activity android:name="android.app.cts.MockActivity" android:label="MockActivity">
<meta-data android:name="android.app.alias"
android:resource="@xml/alias" />
@@ -328,36 +306,6 @@
</intent-filter>
</activity>
- <activity android:name="android.view.cts.ViewGroupStubActivity" android:label="ViewGroupStubActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN"/>
- <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
- </intent-filter>
- </activity>
- <activity android:name="android.view.cts.ViewTestStubActivity"
- android:label="ViewTestStubActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
- </intent-filter>
- </activity>
- <activity android:name="android.view.cts.ViewLayoutPositionTestStubActivity"
- android:label="ViewTestStubActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
- </intent-filter>
- </activity>
-
- <activity android:name="android.view.cts.WindowStubActivity"
- android:theme="@android:style/Theme.Holo.NoActionBar"
- android:label="WindowStubActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
- </intent-filter>
- </activity>
-
<activity android:name="android.widget.cts.ViewGroupStubActivity"
android:label="WidgetViewGroupStubActivity">
<intent-filter>
@@ -367,7 +315,7 @@
</activity>
<activity android:name="android.widget.cts.VideoViewStubActivity"
- android:configChanges="keyboardHidden|orientation|screenSize">
+ android:configChanges="keyboardHidden|orientation|screenSize"
android:label="VideoViewStubActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@@ -480,14 +428,6 @@
</intent-filter>
</activity>
- <activity android:name="android.view.animation.cts.AnimationTestStubActivity"
- android:label="AnimationTestStubActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN"/>
- <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
- </intent-filter>
- </activity>
-
<activity android:name="android.view.animation.cts.GridLayoutAnimStubActivity"
android:label="GridLayoutAnimStubActivity">
<intent-filter>
@@ -629,14 +569,6 @@
android:resource="@xml/method" />
</service>
- <activity android:name="android.view.cts.MenuInflaterStubActivity"
- android:label="MenuInflaterStubActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN"/>
- <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
- </intent-filter>
- </activity>
-
<activity android:name="android.text.method.cts.KeyListenerStubActivity"
android:label="KeyListenerStubActivity"/>
@@ -678,14 +610,6 @@
</intent-filter>
</activity>
- <activity android:name="android.view.cts.SurfaceViewStubActivity"
- android:label="SurfaceViewStubActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN"/>
- <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
- </intent-filter>
- </activity>
-
<activity android:name="android.app.cts.MockApplicationActivity"
android:label="MockApplicationActivity">
<intent-filter>
@@ -818,18 +742,6 @@
</intent-filter>
</activity>
- <activity android:name="android.view.cts.FocusFinderStubActivity"
- android:label="FocusFinderStubActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- </activity>
-
- <activity android:name="android.view.cts.GestureDetectorStubActivity"
- android:label="GestureDetectorStubActivity"
- android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />
-
<!--Test for PackageManager-->
<activity android:name="android.content.pm.cts.TestPmActivity"
android:icon="@drawable/start">
diff --git a/tests/expectations/knownfailures.txt b/tests/expectations/knownfailures.txt
index 706a663..3916531 100644
--- a/tests/expectations/knownfailures.txt
+++ b/tests/expectations/knownfailures.txt
@@ -69,5 +69,43 @@
"android.hardware.camera2.cts.AllocationTest#testParamSensitivity"
],
bug: 17530117
+},
+{
+ description: "these tests locks the screen with an emtpy password or swipe-to-unlock, blocking subsequent test to dismiss keyguard",
+ names: [
+ "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_something",
+ "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_numeric",
+ "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_alphabetic",
+ "android.admin.cts.DevicePolicyManagerTest#testPasswordQuality_alphanumeric",
+ "android.admin.cts.DevicePolicyManagerTest#testGetMaximumFailedPasswordsForWipe"
+ ],
+ bug: 17496766
+},
+{
+ description: "instrumentation target context and test context are the same after move test target inside the test itself",
+ names: [
+ "android.app.cts.InstrumentationTest#testContext"
+ ],
+ bug: 17614217
+},
+{
+ description: "Current implementation of uninstallAllUserCaCerts does not throw expected security exception, wait for fix from framework",
+ names: [
+ "android.admin.cts.DevicePolicyManagerTest#testUninstallAllUserCaCerts_failIfNotProfileOwner"
+ ],
+ bug: 17508787
+},
+{
+ description: "These tests fail on some devices.",
+ names: [
+ "android.uirendering.cts.testclasses.ExactCanvasTests#testBlueRect",
+ "android.uirendering.cts.testclasses.ExactCanvasTests#testBluePaddedSquare",
+ "android.uirendering.cts.testclasses.ViewClippingTests#testSimplePaddingClip",
+ "android.uirendering.cts.testclasses.ViewClippingTests#testSimpleClipBoundsClip",
+ "android.uirendering.cts.testclasses.ViewClippingTests#testSimpleOutlineClip",
+ "android.uirendering.cts.testclasses.ViewClippingTests#testSimpleBoundsClip",
+ "android.uirendering.cts.testclasses.InfrastructureTests#testViewInitializer"
+ ],
+ bug: 17511118
}
]
diff --git a/tests/expectations/unsupportedabis.txt b/tests/expectations/unsupportedabis.txt
index 7a244e3..520d750 100644
--- a/tests/expectations/unsupportedabis.txt
+++ b/tests/expectations/unsupportedabis.txt
@@ -2,182 +2,10 @@
{
description: "Tests not supporting: arm64-v8a, x86_64, mips64",
names: [
- "android.renderscript.cts.AllocationCopy2DRangeTest",
- "android.renderscript.cts.AllocationResize",
- "android.renderscript.cts.AllocationTest",
- "android.renderscript.cts.AtomicTest",
- "android.renderscript.cts.BaseObjTest",
- "android.renderscript.cts.ClearObjectTest",
- "android.renderscript.cts.CompilerTest",
- "android.renderscript.cts.ComputeTest",
- "android.renderscript.cts.DebugContext",
- "android.renderscript.cts.ElementTest",
- "android.renderscript.cts.ExceptionTest",
- "android.renderscript.cts.FieldPackerTest",
- "android.renderscript.cts.ForEachTest",
- "android.renderscript.cts.GetAllocationTest",
- "android.renderscript.cts.GetElementAt",
- "android.renderscript.cts.GlobalSync",
- "android.renderscript.cts.GlobalTest",
- "android.renderscript.cts.ImageProcessingTest",
- "android.renderscript.cts.InitTest",
- "android.renderscript.cts.Intrinsic3DLut",
- "android.renderscript.cts.IntrinsicBase",
- "android.renderscript.cts.IntrinsicBlur",
- "android.renderscript.cts.IntrinsicColorMatrix",
- "android.renderscript.cts.IntrinsicConvolve3x3",
- "android.renderscript.cts.IntrinsicConvolve5x5",
- "android.renderscript.cts.IntrinsicHistogram",
- "android.renderscript.cts.IsObjectTest",
- "android.renderscript.cts.KernelTest",
- "android.renderscript.cts.LeakTest",
- "android.renderscript.cts.Matrix2fTest",
- "android.renderscript.cts.Matrix3fTest",
- "android.renderscript.cts.Matrix4fTest",
- "android.renderscript.cts.RSBase",
- "android.renderscript.cts.RSBaseCompute",
- "android.renderscript.cts.RenderScriptTest",
- "android.renderscript.cts.RsPackColorTo8888Test",
- "android.renderscript.cts.RsUnpackColor8888Test",
- "android.renderscript.cts.SampleTest",
- "android.renderscript.cts.SamplerTest",
- "android.renderscript.cts.ScriptGroupTest",
- "android.renderscript.cts.ScriptTest",
- "android.renderscript.cts.SendToClient",
- "android.renderscript.cts.SendToClientBlockingTest",
- "android.renderscript.cts.SetObjectTest",
- "android.renderscript.cts.StructArrayTest",
- "android.renderscript.cts.StructPadTest",
- "android.renderscript.cts.TestAbs",
- "android.renderscript.cts.TestAcos",
- "android.renderscript.cts.TestAcosh",
- "android.renderscript.cts.TestAcospi",
- "android.renderscript.cts.TestAsin",
- "android.renderscript.cts.TestAsinh",
- "android.renderscript.cts.TestAsinpi",
- "android.renderscript.cts.TestAtan",
- "android.renderscript.cts.TestAtan2",
- "android.renderscript.cts.TestAtan2pi",
- "android.renderscript.cts.TestAtanh",
- "android.renderscript.cts.TestAtanpi",
- "android.renderscript.cts.TestCbrt",
- "android.renderscript.cts.TestCeil",
- "android.renderscript.cts.TestClamp",
- "android.renderscript.cts.TestClz",
- "android.renderscript.cts.TestConvert",
- "android.renderscript.cts.TestCopysign",
- "android.renderscript.cts.TestCos",
- "android.renderscript.cts.TestCosh",
- "android.renderscript.cts.TestCospi",
- "android.renderscript.cts.TestCross",
- "android.renderscript.cts.TestDegrees",
- "android.renderscript.cts.TestDistance",
- "android.renderscript.cts.TestDot",
- "android.renderscript.cts.TestErf",
- "android.renderscript.cts.TestErfc",
- "android.renderscript.cts.TestExp",
- "android.renderscript.cts.TestExp10",
- "android.renderscript.cts.TestExp2",
- "android.renderscript.cts.TestExpm1",
- "android.renderscript.cts.TestFabs",
- "android.renderscript.cts.TestFastDistance",
- "android.renderscript.cts.TestFastLength",
- "android.renderscript.cts.TestFastNormalize",
- "android.renderscript.cts.TestFdim",
- "android.renderscript.cts.TestFloor",
- "android.renderscript.cts.TestFma",
- "android.renderscript.cts.TestFmax",
- "android.renderscript.cts.TestFmin",
- "android.renderscript.cts.TestFmod",
- "android.renderscript.cts.TestFract",
- "android.renderscript.cts.TestFrexp",
- "android.renderscript.cts.TestHalfRecip",
- "android.renderscript.cts.TestHalfRsqrt",
- "android.renderscript.cts.TestHalfSqrt",
- "android.renderscript.cts.TestHypot",
- "android.renderscript.cts.TestIlogb",
- "android.renderscript.cts.TestLdexp",
- "android.renderscript.cts.TestLength",
- "android.renderscript.cts.TestLgamma",
- "android.renderscript.cts.TestLog",
- "android.renderscript.cts.TestLog10",
- "android.renderscript.cts.TestLog1p",
- "android.renderscript.cts.TestLog2",
- "android.renderscript.cts.TestLogb",
- "android.renderscript.cts.TestMad",
- "android.renderscript.cts.TestMax",
- "android.renderscript.cts.TestMin",
- "android.renderscript.cts.TestMix",
- "android.renderscript.cts.TestModf",
- "android.renderscript.cts.TestNan",
- "android.renderscript.cts.TestNativeAcos",
- "android.renderscript.cts.TestNativeAcosh",
- "android.renderscript.cts.TestNativeAcospi",
- "android.renderscript.cts.TestNativeAsin",
- "android.renderscript.cts.TestNativeAsinh",
- "android.renderscript.cts.TestNativeAsinpi",
- "android.renderscript.cts.TestNativeAtan",
- "android.renderscript.cts.TestNativeAtan2",
- "android.renderscript.cts.TestNativeAtan2pi",
- "android.renderscript.cts.TestNativeAtanh",
- "android.renderscript.cts.TestNativeAtanpi",
- "android.renderscript.cts.TestNativeCbrt",
- "android.renderscript.cts.TestNativeCos",
- "android.renderscript.cts.TestNativeCosh",
- "android.renderscript.cts.TestNativeCospi",
- "android.renderscript.cts.TestNativeDistance",
- "android.renderscript.cts.TestNativeDivide",
- "android.renderscript.cts.TestNativeExp",
- "android.renderscript.cts.TestNativeExp10",
- "android.renderscript.cts.TestNativeExp2",
- "android.renderscript.cts.TestNativeExpm1",
- "android.renderscript.cts.TestNativeHypot",
- "android.renderscript.cts.TestNativeLength",
- "android.renderscript.cts.TestNativeLog",
- "android.renderscript.cts.TestNativeLog10",
- "android.renderscript.cts.TestNativeLog1p",
- "android.renderscript.cts.TestNativeLog2",
- "android.renderscript.cts.TestNativeNormalize",
- "android.renderscript.cts.TestNativePowr",
- "android.renderscript.cts.TestNativeRecip",
- "android.renderscript.cts.TestNativeRootn",
- "android.renderscript.cts.TestNativeRsqrt",
- "android.renderscript.cts.TestNativeSin",
- "android.renderscript.cts.TestNativeSincos",
- "android.renderscript.cts.TestNativeSinh",
- "android.renderscript.cts.TestNativeSinpi",
- "android.renderscript.cts.TestNativeSqrt",
- "android.renderscript.cts.TestNativeTan",
- "android.renderscript.cts.TestNativeTanh",
- "android.renderscript.cts.TestNativeTanpi",
- "android.renderscript.cts.TestNextafter",
- "android.renderscript.cts.TestNormalize",
- "android.renderscript.cts.TestPow",
- "android.renderscript.cts.TestPown",
- "android.renderscript.cts.TestPowr",
- "android.renderscript.cts.TestRadians",
- "android.renderscript.cts.TestRemainder",
- "android.renderscript.cts.TestRemquo",
- "android.renderscript.cts.TestRint",
- "android.renderscript.cts.TestRootn",
- "android.renderscript.cts.TestRound",
- "android.renderscript.cts.TestRsqrt",
- "android.renderscript.cts.TestSign",
- "android.renderscript.cts.TestSin",
- "android.renderscript.cts.TestSincos",
- "android.renderscript.cts.TestSinh",
- "android.renderscript.cts.TestSinpi",
- "android.renderscript.cts.TestSqrt",
- "android.renderscript.cts.TestStep",
- "android.renderscript.cts.TestTan",
- "android.renderscript.cts.TestTanh",
- "android.renderscript.cts.TestTanpi",
- "android.renderscript.cts.TestTgamma",
- "android.renderscript.cts.TestTrunc",
- "android.renderscript.cts.TypeTest",
- "android.renderscript.cts.VersionTest",
- "android.renderscript.cts.VoidPtr",
- "android.renderscript.cts.YuvTest"
+ "android.sample.cts.SampleDeviceResultTest",
+ "android.sample.cts.SampleDeviceTest",
+ "android.sample.cts.SampleHostResultTest",
+ "android.sample.cts.SampleHostTest"
]
}
]
diff --git a/tests/src/android/text/EmojiStubActivity.java b/tests/src/android/text/EmojiStubActivity.java
deleted file mode 100644
index 8d09250..0000000
--- a/tests/src/android/text/EmojiStubActivity.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2013 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.cts;
-
-import com.android.cts.stub.R;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.webkit.WebView;
-import android.webkit.cts.NullWebViewUtils;
-
-public class EmojiStubActivity extends Activity {
- private WebView mWebView;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- try {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.webview_layout);
- mWebView = (WebView) findViewById(R.id.web_page);
- } catch (Exception e) {
- NullWebViewUtils.determineIfWebViewAvailable(this, e);
- }
- }
-
- public WebView getWebView() {
- return mWebView;
- }
-
- @Override
- public void onDestroy() {
- if (mWebView != null) {
- mWebView.destroy();
- }
- super.onDestroy();
- }
-}
diff --git a/tests/src/android/text/format/cts/LocaleUtils.java b/tests/src/android/text/format/cts/LocaleUtils.java
deleted file mode 100644
index 131d745..0000000
--- a/tests/src/android/text/format/cts/LocaleUtils.java
+++ /dev/null
@@ -1,31 +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.text.format.cts;
-
-import android.content.Context;
-
-import java.util.Locale;
-
-public class LocaleUtils {
-
- /** Return whether or not the given locale is the device's current locale. */
- public static boolean isCurrentLocale(Context context, Locale locale) {
- // TODO: Change the locale on the device using public API if it becomes available.
- Locale currentLocale = context.getResources().getConfiguration().locale;
- return locale.equals(currentLocale);
- }
-}
diff --git a/tests/src/android/text/method/cts/KeyListenerStubActivity.java b/tests/src/android/text/method/cts/KeyListenerStubActivity.java
deleted file mode 100644
index 149ad87..0000000
--- a/tests/src/android/text/method/cts/KeyListenerStubActivity.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2009 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.method.cts;
-
-import com.android.cts.stub.R;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.os.SystemClock;
-import android.text.method.BaseKeyListener;
-import android.text.method.DateKeyListener;
-import android.text.method.DateTimeKeyListener;
-import android.text.method.DigitsKeyListener;
-import android.text.method.MultiTapKeyListener;
-import android.text.method.NumberKeyListener;
-import android.text.method.QwertyKeyListener;
-import android.text.method.TextKeyListener;
-import android.text.method.TimeKeyListener;
-import android.util.Log;
-
-/**
- * This Activity is used for testing:
- * {@link DigitsKeyListener}
- * {@link BaseKeyListener}
- * {@link MultiTapKeyListener}
- * {@link NumberKeyListener}
- * {@link QwertyKeyListener}
- * {@link TextKeyListener}
- * {@link DateKeyListener}
- * {@link DateTimeKeyListener}
- * {@link TimeKeyListener}
- *
- * @see DigitsKeyListener
- * @see BaseKeyListener
- * @see MultiTapKeyListener
- * @see NumberKeyListener
- * @see QwertyKeyListener
- * @see TextKeyListener
- * @see DateKeyListener
- * @see DateTimeKeyListener
- * @see TimeKeyListener
- */
-
-public class KeyListenerStubActivity extends Activity {
- private boolean mHasWindowFocus = false;
- private Object mHasWindowFocusLock = new Object();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.keylistener_layout);
- }
-
- @Override
- public void onWindowFocusChanged(boolean hasFocus) {
- super.onWindowFocusChanged(hasFocus);
- if (!hasFocus) {
- Log.w("KeyListenerStubActivity", "KeyListenerStubActivity lost window focus");
- }
- synchronized(mHasWindowFocusLock) {
- mHasWindowFocus = hasFocus;
- mHasWindowFocusLock.notify();
- }
- }
-
- /**
- * Blocks the calling thread until the {@link KeyListenerStubActivity} has window focus or the
- * specified duration (in milliseconds) has passed.
- */
- public boolean waitForWindowFocus(long durationMillis) {
- long elapsedMillis = SystemClock.elapsedRealtime();
- synchronized(mHasWindowFocusLock) {
- mHasWindowFocus = hasWindowFocus();
- while (!mHasWindowFocus && durationMillis > 0) {
- long newElapsedMillis = SystemClock.elapsedRealtime();
- durationMillis -= (newElapsedMillis - elapsedMillis);
- elapsedMillis = newElapsedMillis;
- if (durationMillis > 0) {
- try {
- mHasWindowFocusLock.wait(durationMillis);
- } catch (InterruptedException e) {
- }
- }
- }
- return mHasWindowFocus;
- }
- }
-}
diff --git a/tests/src/android/text/method/cts/StubActivity.java b/tests/src/android/text/method/cts/StubActivity.java
deleted file mode 100644
index f3dad52..0000000
--- a/tests/src/android/text/method/cts/StubActivity.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2009 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.method.cts;
-
-import android.app.Activity;
-import android.text.method.ArrowKeyMovementMethod;
-import android.text.method.LinkMovementMethod;
-import android.text.method.ScrollingMovementMethod;
-
-/**
- * This Activity is used for testing:
- * {@link LinkMovementMethod}
- * {@link ArrowKeyMovementMethod}
- * {@link ScrollingMovementMethod}
- *
- * The content view will be set in the test cases.
- *
- * @see LinkMovementMethodTest
- * @see ArrowKeyMovementMethodTest
- * @see ScrollingMovementMethodTest
- */
-public class StubActivity extends Activity {
-}
diff --git a/tests/src/android/text/method/cts/TextMethodUtils.java b/tests/src/android/text/method/cts/TextMethodUtils.java
deleted file mode 100644
index 0785cff..0000000
--- a/tests/src/android/text/method/cts/TextMethodUtils.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2008 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.method.cts;
-
-import android.view.KeyEvent;
-
-import junit.framework.Assert;
-
-public class TextMethodUtils {
- /**
- * Assert that two char arrays are equal.
- *
- * @param expected the expected char array.
- * @param actual the actual char array.
- */
- public static void assertEquals(char[] expected, char[] actual) {
- if (expected != actual) {
- if (expected == null || actual == null) {
- Assert.fail("the char arrays are not equal");
- }
-
- Assert.assertEquals(String.valueOf(expected), String.valueOf(actual));
- }
- }
-
- /**
- * Get an unaccepted key code.
- *
- * @param acceptedChars accepted chars array.
- * @return return key code if we find unaccepted one, or return -1.
- */
- public static int getUnacceptedKeyCode(char[] acceptedChars) {
- for (int keyCode = KeyEvent.KEYCODE_A; keyCode <= KeyEvent.KEYCODE_Z; keyCode++) {
- KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
- if ('\0' == event.getMatch(acceptedChars)) {
- return keyCode;
- }
- }
- return -1;
- }
-}
diff --git a/tests/src/android/text/style/cts/URLSpanStubActivity.java b/tests/src/android/text/style/cts/URLSpanStubActivity.java
deleted file mode 100644
index a09a83e..0000000
--- a/tests/src/android/text/style/cts/URLSpanStubActivity.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2008 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.style.cts;
-
-import com.android.cts.stub.R;
-
-import android.app.Activity;
-import android.os.Bundle;
-
-/**
- * A minimal application for {@link URLSpan} test.
- */
-public class URLSpanStubActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.urlspan_layout);
- }
-}
diff --git a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
index bdc0cd5..cb0877d 100644
--- a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
+++ b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
@@ -4532,7 +4532,7 @@
AccessibilityNodeInfo.ACTION_PASTE));
// Verify the content.
- assertEquals(editText.getText().toString(), textContent + " " + textContent);
+ assertEquals(editText.getText().toString(), textContent + textContent);
// Select all text.
arguments.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, 0);
diff --git a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
index 43acbcd..f8cf4dd 100644
--- a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
+++ b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
@@ -29,12 +29,14 @@
import android.graphics.Rect;
import android.os.SystemClock;
import android.test.suitebuilder.annotation.MediumTest;
-import android.util.Log;
+import android.view.Gravity;
+import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
import android.view.accessibility.AccessibilityWindowInfo;
+import android.widget.Button;
import com.android.cts.accessibilityservice.R;
import java.util.ArrayList;
@@ -268,152 +270,26 @@
}
@MediumTest
- public void testInteractWithNavBarWindow() throws Exception {
- setAccessInteractiveWindowsFlag();
- try {
- final UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
- uiAutomation.executeAndWaitForEvent(new Runnable() {
- @Override
- public void run() {
- AccessibilityWindowInfo window = uiAutomation.getWindows().get(0);
- assertTrue(window.getRoot().performAction(
- AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS));
- }
- }, new UiAutomation.AccessibilityEventFilter() {
- @Override
- public boolean accept(AccessibilityEvent event) {
- return event.getEventType() ==
- AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED;
- }
- }, TIMEOUT_ASYNC_PROCESSING);
- } finally {
- ensureAccessibilityFocusCleared();
- clearAccessInteractiveWindowsFlag();
- }
- }
-
- @MediumTest
- public void testInteractWithStatusBarWindow() throws Exception {
- setAccessInteractiveWindowsFlag();
- try {
- final UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
- uiAutomation.executeAndWaitForEvent(new Runnable() {
- @Override
- public void run() {
- AccessibilityWindowInfo window = uiAutomation.getWindows().get(1);
- assertTrue(window.getRoot().performAction(
- AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS));
-
- }
- }, new UiAutomation.AccessibilityEventFilter() {
- @Override
- public boolean accept(AccessibilityEvent event) {
- return event.getEventType() ==
- AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED;
- }
- }, TIMEOUT_ASYNC_PROCESSING);
- } finally {
- ensureAccessibilityFocusCleared();
- clearAccessInteractiveWindowsFlag();
- }
- }
-
- @MediumTest
public void testSingleAccessibilityFocusAcrossWindows() throws Exception {
setAccessInteractiveWindowsFlag();
try {
- final UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
+ // Add two more windows.
+ addTwoAppPanelWindows();
- uiAutomation.waitForIdle(TIMEOUT_WINDOW_STATE_IDLE, TIMEOUT_ASYNC_PROCESSING);
-
- getInstrumentation().getUiAutomation().executeAndWaitForEvent(new Runnable() {
- @Override
- public void run() {
- // Set focus in the first window.
- List<AccessibilityWindowInfo> windows = uiAutomation.getWindows();
- AccessibilityNodeInfo firstWindowRoot = windows.get(0).getRoot();
- assertTrue(firstWindowRoot.performAction(
- AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS));
- }
- }, new UiAutomation.AccessibilityEventFilter() {
- @Override
- public boolean accept(AccessibilityEvent event) {
- return event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED;
- }
- }, TIMEOUT_ASYNC_PROCESSING);
-
- // Wait for things to settle.
- waitForIdle();
-
- List<AccessibilityWindowInfo> windows = uiAutomation.getWindows();
-
- AccessibilityNodeInfo firstWindowRoot = windows.get(0).getRoot();
- AccessibilityNodeInfo secondWindowRoot = windows.get(1).getRoot();
- AccessibilityNodeInfo thirdWindowRoot = windows.get(2).getRoot();
-
- // Ensure accessibility focus is where we put it.
- assertTrue(windows.get(0).isAccessibilityFocused());
-
+ // Put accessibility focus in the first app window.
+ ensureAppWindowFocusedOrFail(0);
// Make sure there only one accessibility focus.
- assertEquals(uiAutomation.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), firstWindowRoot);
- assertEquals(firstWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), firstWindowRoot);
- assertNull(secondWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
- assertNull(thirdWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
+ assertSingleAccessibilityFocus();
-
- // Set focus in the second window.
- assertTrue(secondWindowRoot.performAction(
- AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS));
-
- // Wait for things to settle.
- uiAutomation.waitForIdle(TIMEOUT_WINDOW_STATE_IDLE, TIMEOUT_ASYNC_PROCESSING);
-
+ // Put accessibility focus in the second app window.
+ ensureAppWindowFocusedOrFail(1);
// Make sure there only one accessibility focus.
- assertEquals(uiAutomation.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), secondWindowRoot);
- assertEquals(secondWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), secondWindowRoot);
- assertNull(firstWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
- assertNull(thirdWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
+ assertSingleAccessibilityFocus();
-
- // Set focus in the third window.
- assertTrue(thirdWindowRoot.performAction(
- AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS));
-
- // Wait for things to settle.
- uiAutomation.waitForIdle(TIMEOUT_WINDOW_STATE_IDLE, TIMEOUT_ASYNC_PROCESSING);
-
+ // Put accessibility focus in the third app window.
+ ensureAppWindowFocusedOrFail(2);
// Make sure there only one accessibility focus.
- assertEquals(uiAutomation.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), thirdWindowRoot);
- assertEquals(thirdWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), thirdWindowRoot);
- assertNull(firstWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
- assertNull(secondWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
-
-
- // Clear focus.
- assertTrue(thirdWindowRoot.performAction(
- AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS));
-
- // Make sure there is not accessibility focus.
- assertNull(uiAutomation.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
- assertNull(firstWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
- assertNull(secondWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
- assertNull(thirdWindowRoot.findFocus(
- AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
+ assertSingleAccessibilityFocus();
} finally {
ensureAccessibilityFocusCleared();
clearAccessInteractiveWindowsFlag();
@@ -761,6 +637,152 @@
}
}
+ private void assertSingleAccessibilityFocus() {
+ UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
+ List<AccessibilityWindowInfo> windows = uiAutomation.getWindows();
+ AccessibilityWindowInfo focused = null;
+
+ final int windowCount = windows.size();
+ for (int i = 0; i < windowCount; i++) {
+ AccessibilityWindowInfo window = windows.get(i);
+
+ if (window.isAccessibilityFocused()) {
+ if (focused == null) {
+ focused = window;
+
+ AccessibilityNodeInfo root = window.getRoot();
+ assertEquals(uiAutomation.findFocus(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), root);
+ assertEquals(root.findFocus(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY), root);
+ } else {
+ throw new AssertionError("Duplicate accessibility focus");
+ }
+ } else {
+ assertNull(window.getRoot().findFocus(
+ AccessibilityNodeInfo.FOCUS_ACCESSIBILITY));
+ }
+ }
+ }
+
+ private void ensureAppWindowFocusedOrFail(int appWindowIndex) throws TimeoutException {
+ UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
+ List<AccessibilityWindowInfo> windows = uiAutomation.getWindows();
+ AccessibilityWindowInfo focusTareget = null;
+
+ int visitedAppWindows = -1;
+ final int windowCount = windows.size();
+ for (int i = 0; i < windowCount; i++) {
+ AccessibilityWindowInfo window = windows.get(i);
+ if (window.getType() == AccessibilityWindowInfo.TYPE_APPLICATION) {
+ visitedAppWindows++;
+ if (appWindowIndex <= visitedAppWindows) {
+ focusTareget = window;
+ break;
+ }
+ }
+ }
+
+ if (focusTareget == null) {
+ throw new IllegalStateException("Couldn't find app window: " + appWindowIndex);
+ }
+
+ if (focusTareget.isAccessibilityFocused()) {
+ return;
+ }
+
+ final AccessibilityWindowInfo finalFocusTarget = focusTareget;
+ uiAutomation.executeAndWaitForEvent(new Runnable() {
+ @Override
+ public void run() {
+ assertTrue(finalFocusTarget.getRoot().performAction(
+ AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS));
+ }
+ }, new UiAutomation.AccessibilityEventFilter() {
+ @Override
+ public boolean accept(AccessibilityEvent event) {
+ return event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED;
+ }
+ }, TIMEOUT_ASYNC_PROCESSING);
+
+ windows = uiAutomation.getWindows();
+ for (int i = 0; i < windowCount; i++) {
+ AccessibilityWindowInfo window = windows.get(i);
+ if (window.getId() == focusTareget.getId()) {
+ assertTrue(window.isAccessibilityFocused());
+ break;
+ }
+ }
+ }
+
+ private void addTwoAppPanelWindows() throws TimeoutException {
+ final UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
+
+ uiAutomation.waitForIdle(TIMEOUT_WINDOW_STATE_IDLE, TIMEOUT_ASYNC_PROCESSING);
+
+ // Add the first window.
+ uiAutomation.executeAndWaitForEvent(new Runnable() {
+ @Override
+ public void run() {
+ getInstrumentation().runOnMainSync(new Runnable() {
+ @Override
+ public void run() {
+ WindowManager.LayoutParams params = new WindowManager.LayoutParams();
+ params.gravity = Gravity.TOP;
+ params.width = WindowManager.LayoutParams.MATCH_PARENT;
+ params.height = WindowManager.LayoutParams.WRAP_CONTENT;
+ params.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
+ | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
+ | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+ | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
+ params.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
+ params.token = getActivity().getWindow().getDecorView().getWindowToken();
+
+ Button button = new Button(getActivity());
+ button.setText(R.string.button1);
+ getActivity().getWindowManager().addView(button, params);
+ }
+ });
+ }
+ }, new UiAutomation.AccessibilityEventFilter() {
+ @Override
+ public boolean accept(AccessibilityEvent event) {
+ return event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED;
+ }
+ }, TIMEOUT_ASYNC_PROCESSING);
+
+ // Add the second window.
+ uiAutomation.executeAndWaitForEvent(new Runnable() {
+ @Override
+ public void run() {
+ getInstrumentation().runOnMainSync(new Runnable() {
+ @Override
+ public void run() {
+ WindowManager.LayoutParams params = new WindowManager.LayoutParams();
+ params.gravity = Gravity.BOTTOM;
+ params.width = WindowManager.LayoutParams.MATCH_PARENT;
+ params.height = WindowManager.LayoutParams.WRAP_CONTENT;
+ params.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
+ | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
+ | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+ | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
+ params.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
+ params.token = getActivity().getWindow().getDecorView().getWindowToken();
+
+ Button button = new Button(getActivity());
+ button.setText(R.string.button2);
+ getActivity().getWindowManager().addView(button, params);
+ }
+ });
+ }
+ }, new UiAutomation.AccessibilityEventFilter() {
+ @Override
+ public boolean accept(AccessibilityEvent event) {
+ return event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED;
+ }
+ }, TIMEOUT_ASYNC_PROCESSING);
+ }
+
private void setAccessInteractiveWindowsFlag () {
UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
AccessibilityServiceInfo info = uiAutomation.getServiceInfo();
diff --git a/tests/tests/accounts/Android.mk b/tests/tests/accounts/Android.mk
index 39dbfb1..1579822 100644
--- a/tests/tests/accounts/Android.mk
+++ b/tests/tests/accounts/Android.mk
@@ -21,7 +21,7 @@
# and when built explicitly put it in the data partition
LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-LOCAL_STATIC_JAVA_LIBRARIES += android-common ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
LOCAL_SRC_FILES := $(call all-java-files-under, src)
diff --git a/tests/tests/accounts/AndroidManifest.xml b/tests/tests/accounts/AndroidManifest.xml
index cf7f7d8..22362ab 100644
--- a/tests/tests/accounts/AndroidManifest.xml
+++ b/tests/tests/accounts/AndroidManifest.xml
@@ -28,6 +28,13 @@
<application>
<uses-library android:name="android.test.runner" />
+ <activity android:name="android.accounts.cts.AccountDummyActivity" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+
<service android:name="MockAccountService" android:exported="true"
android:process="android.accounts.cts">
<intent-filter>
diff --git a/tests/src/android/os/cts/TaggedPointer.java b/tests/tests/accounts/src/android/accounts/cts/AccountDummyActivity.java
similarity index 78%
copy from tests/src/android/os/cts/TaggedPointer.java
copy to tests/tests/accounts/src/android/accounts/cts/AccountDummyActivity.java
index 16e76c9..a345dcc 100644
--- a/tests/src/android/os/cts/TaggedPointer.java
+++ b/tests/tests/accounts/src/android/accounts/cts/AccountDummyActivity.java
@@ -14,13 +14,12 @@
* limitations under the License.
*/
-package android.os.cts;
+package android.accounts.cts;
-public class TaggedPointer {
+import android.app.Activity;
- static {
- System.loadLibrary("cts_jni");
- }
-
- public static native boolean hasTaggedPointer();
+/**
+ * An activity.
+ */
+public class AccountDummyActivity extends Activity {
}
diff --git a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
index f443d30..e5cc45a 100644
--- a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
+++ b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
@@ -28,8 +28,9 @@
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
+import android.os.Looper;
import android.os.StrictMode;
-import android.test.AndroidTestCase;
+import android.test.ActivityInstrumentationTestCase2;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
@@ -41,9 +42,9 @@
* adb shell am instrument
* -e debug false -w
* -e class android.accounts.cts.AccountManagerTest
- * android.accounts.cts/android.test.InstrumentationTestRunner
+ * android.accounts.cts/android.support.test.runner.AndroidJUnitRunner
*/
-public class AccountManagerTest extends AndroidTestCase {
+public class AccountManagerTest extends ActivityInstrumentationTestCase2<AccountDummyActivity> {
public static final String ACCOUNT_NAME = "android.accounts.cts.account.name";
public static final String ACCOUNT_NEW_NAME = "android.accounts.cts.account.name.rename";
@@ -70,7 +71,6 @@
public static final String[] REQUIRED_FEATURES = new String[] { FEATURE_1, FEATURE_2 };
- public static final Activity ACTIVITY = new Activity();
public static final Bundle OPTIONS_BUNDLE = new Bundle();
public static final Bundle USERDATA_BUNDLE = new Bundle();
@@ -94,18 +94,27 @@
return mockAuthenticator;
}
+ private Activity mActivity;
+ private Context mContext;
+
+ public AccountManagerTest() {
+ super(AccountDummyActivity.class);
+ }
+
@Override
public void setUp() throws Exception {
super.setUp();
+ mActivity = getActivity();
+ mContext = getInstrumentation().getTargetContext();
OPTIONS_BUNDLE.putString(OPTION_NAME_1, OPTION_VALUE_1);
OPTIONS_BUNDLE.putString(OPTION_NAME_2, OPTION_VALUE_2);
USERDATA_BUNDLE.putString(USERDATA_NAME_1, USERDATA_VALUE_1);
- getMockAuthenticator(getContext());
+ getMockAuthenticator(mContext);
- am = AccountManager.get(getContext());
+ am = AccountManager.get(mContext);
}
@Override
@@ -264,7 +273,7 @@
* Test singleton
*/
public void testGet() {
- assertNotNull(AccountManager.get(getContext()));
+ assertNotNull(AccountManager.get(mContext));
}
/**
@@ -278,7 +287,7 @@
AUTH_TOKEN_TYPE,
REQUIRED_FEATURES,
OPTIONS_BUNDLE,
- ACTIVITY,
+ mActivity,
null /* callback */,
null /* handler */);
@@ -302,7 +311,7 @@
AuthenticatorException, OperationCanceledException {
testAddAccountWithCallbackAndHandler(null /* handler */);
- testAddAccountWithCallbackAndHandler(new Handler());
+ testAddAccountWithCallbackAndHandler(new Handler(Looper.getMainLooper()));
}
private void testAddAccountWithCallbackAndHandler(Handler handler) throws IOException,
@@ -343,7 +352,7 @@
AUTH_TOKEN_TYPE,
REQUIRED_FEATURES,
OPTIONS_BUNDLE,
- ACTIVITY,
+ mActivity,
callback,
handler);
@@ -549,7 +558,7 @@
addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */);
testGetAccountsByTypeAndFeaturesWithCallbackAndHandler(null /* handler */);
- testGetAccountsByTypeAndFeaturesWithCallbackAndHandler(new Handler());
+ testGetAccountsByTypeAndFeaturesWithCallbackAndHandler(new Handler(Looper.getMainLooper()));
}
private void testGetAccountsByTypeAndFeaturesWithCallbackAndHandler(Handler handler) throws
@@ -702,7 +711,7 @@
addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */);
testGetAuthTokenWithCallbackAndHandler(null /* handler */);
- testGetAuthTokenWithCallbackAndHandler(new Handler());
+ testGetAuthTokenWithCallbackAndHandler(new Handler(Looper.getMainLooper()));
}
private void testGetAuthTokenWithCallbackAndHandler(Handler handler) throws IOException,
@@ -764,7 +773,7 @@
AccountManagerFuture<Bundle> futureBundle = am.getAuthToken(ACCOUNT,
AUTH_TOKEN_TYPE,
OPTIONS_BUNDLE,
- ACTIVITY,
+ mActivity,
null /* no callback */,
null /* no handler */
);
@@ -793,7 +802,7 @@
addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */);
testGetAuthTokenWithOptionsAndCallbackAndHandler(null /* handler */);
- testGetAuthTokenWithOptionsAndCallbackAndHandler(new Handler());
+ testGetAuthTokenWithOptionsAndCallbackAndHandler(new Handler(Looper.getMainLooper()));
}
private void testGetAuthTokenWithOptionsAndCallbackAndHandler(Handler handler) throws
@@ -827,7 +836,7 @@
AccountManagerFuture<Bundle> futureBundle = am.getAuthToken(ACCOUNT,
AUTH_TOKEN_TYPE,
OPTIONS_BUNDLE,
- ACTIVITY,
+ mActivity,
callback,
handler
);
@@ -871,7 +880,7 @@
// Now test with existing features and an activity
resultBundle = getAuthTokenByFeature(
new String[] { NON_EXISTING_FEATURE },
- ACTIVITY
+ mActivity
);
// Assert returned result
@@ -903,7 +912,7 @@
// Now test with existing features and an activity
resultBundle = getAuthTokenByFeature(
REQUIRED_FEATURES,
- ACTIVITY
+ mActivity
);
// Assert returned result
@@ -926,7 +935,7 @@
AccountManagerFuture<Bundle> futureBundle = am.confirmCredentials(ACCOUNT,
OPTIONS_BUNDLE,
- ACTIVITY,
+ mActivity,
null /* callback*/,
null /* handler */);
@@ -945,7 +954,7 @@
addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */);
testConfirmCredentialsWithCallbackAndHandler(null /* handler */);
- testConfirmCredentialsWithCallbackAndHandler(new Handler());
+ testConfirmCredentialsWithCallbackAndHandler(new Handler(Looper.getMainLooper()));
}
private void testConfirmCredentialsWithCallbackAndHandler(Handler handler) throws IOException,
@@ -979,7 +988,7 @@
AccountManagerFuture<Bundle> futureBundle = am.confirmCredentials(ACCOUNT,
OPTIONS_BUNDLE,
- ACTIVITY,
+ mActivity,
callback,
handler);
@@ -1004,7 +1013,7 @@
AccountManagerFuture<Bundle> futureBundle = am.updateCredentials(ACCOUNT,
AUTH_TOKEN_TYPE,
OPTIONS_BUNDLE,
- ACTIVITY,
+ mActivity,
null /* callback*/,
null /* handler */);
@@ -1025,7 +1034,7 @@
addAccountExplicitly(ACCOUNT, ACCOUNT_PASSWORD, null /* userData */);
testUpdateCredentialsWithCallbackAndHandler(null /* handler */);
- testUpdateCredentialsWithCallbackAndHandler(new Handler());
+ testUpdateCredentialsWithCallbackAndHandler(new Handler(Looper.getMainLooper()));
}
private void testUpdateCredentialsWithCallbackAndHandler(Handler handler) throws IOException,
@@ -1060,7 +1069,7 @@
AccountManagerFuture<Bundle> futureBundle = am.updateCredentials(ACCOUNT,
AUTH_TOKEN_TYPE,
OPTIONS_BUNDLE,
- ACTIVITY,
+ mActivity,
callback,
handler);
@@ -1081,7 +1090,7 @@
OperationCanceledException {
AccountManagerFuture<Bundle> futureBundle = am.editProperties(ACCOUNT_TYPE,
- ACTIVITY,
+ mActivity,
null /* callback */,
null /* handler*/);
@@ -1098,7 +1107,7 @@
*/
public void testEditPropertiesWithCallbackAndHandler() {
testEditPropertiesWithCallbackAndHandler(null /* handler */);
- testEditPropertiesWithCallbackAndHandler(new Handler());
+ testEditPropertiesWithCallbackAndHandler(new Handler(Looper.getMainLooper()));
}
private void testEditPropertiesWithCallbackAndHandler(Handler handler) {
@@ -1117,7 +1126,7 @@
};
AccountManagerFuture<Bundle> futureBundle = am.editProperties(ACCOUNT_TYPE,
- ACTIVITY,
+ mActivity,
callback,
handler);
@@ -1147,13 +1156,13 @@
// Need to cleanup intermediate state
assertTrue(removeAccount(am, ACCOUNT, null /* callback */));
- testAddOnAccountsUpdatedListenerWithHandler(new Handler(),
+ testAddOnAccountsUpdatedListenerWithHandler(new Handler(Looper.getMainLooper()),
false /* updateImmediately */);
// Need to cleanup intermediate state
assertTrue(removeAccount(am, ACCOUNT, null /* callback */));
- testAddOnAccountsUpdatedListenerWithHandler(new Handler(),
+ testAddOnAccountsUpdatedListenerWithHandler(new Handler(Looper.getMainLooper()),
true /* updateImmediately */);
}
@@ -1197,7 +1206,7 @@
// Need to cleanup intermediate state
assertTrue(removeAccount(am, ACCOUNT, null /* callback */));
- testRemoveOnAccountsUpdatedListenerWithHandler(new Handler());
+ testRemoveOnAccountsUpdatedListenerWithHandler(new Handler(Looper.getMainLooper()));
}
private void testRemoveOnAccountsUpdatedListenerWithHandler(Handler handler) {
@@ -1234,10 +1243,10 @@
throws IOException, AuthenticatorException, OperationCanceledException {
assertHasFeature(null /* handler */);
- assertHasFeature(new Handler());
+ assertHasFeature(new Handler(Looper.getMainLooper()));
assertHasFeatureWithCallback(null /* handler */);
- assertHasFeatureWithCallback(new Handler());
+ assertHasFeatureWithCallback(new Handler(Looper.getMainLooper()));
}
private void assertHasFeature(Handler handler)
@@ -1247,7 +1256,7 @@
AUTH_TOKEN_TYPE,
REQUIRED_FEATURES,
OPTIONS_BUNDLE,
- ACTIVITY,
+ mActivity,
null /* callback */,
null /* handler */);
@@ -1338,7 +1347,7 @@
AUTH_TOKEN_TYPE,
REQUIRED_FEATURES,
OPTIONS_BUNDLE,
- ACTIVITY,
+ mActivity,
null /* callback */,
null /* handler */);
diff --git a/tests/tests/animation/src/android/animation/cts/AnimatorTest.java b/tests/tests/animation/src/android/animation/cts/AnimatorTest.java
index 5f07afb..fac9ff9 100644
--- a/tests/tests/animation/src/android/animation/cts/AnimatorTest.java
+++ b/tests/tests/animation/src/android/animation/cts/AnimatorTest.java
@@ -19,6 +19,7 @@
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
import android.view.animation.AccelerateInterpolator;
import java.util.List;
@@ -55,7 +56,8 @@
assertEquals(startDelay, mAnimator.getStartDelay());
}
- public void testStart() {
+ @UiThreadTest
+ public void testStart() throws Exception {
mAnimator.start();
assertTrue(mAnimator.isRunning());
assertTrue(mAnimator.isStarted());
@@ -135,10 +137,20 @@
assertFalse(listener.mEnd);
assertTrue(listener.mRepeat >= 0);
- mAnimator.cancel();
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ mAnimator.cancel();
+ }
+ });
+ getInstrumentation().waitForIdleSync();
assertTrue(listener.mCancel);
- mAnimator.end();
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ mAnimator.end();
+ }
+ });
+ getInstrumentation().waitForIdleSync();
assertTrue(listener.mEnd);
}
diff --git a/tests/tests/animation/src/android/animation/cts/ObjectAnimatorTest.java b/tests/tests/animation/src/android/animation/cts/ObjectAnimatorTest.java
index f8f1f43..f0db168 100644
--- a/tests/tests/animation/src/android/animation/cts/ObjectAnimatorTest.java
+++ b/tests/tests/animation/src/android/animation/cts/ObjectAnimatorTest.java
@@ -88,13 +88,18 @@
int startColor = mActivity.view.RED;
int endColor = mActivity.view.BLUE;
- ObjectAnimator colorAnimator = ObjectAnimator.ofInt(object, property,
+ final ObjectAnimator colorAnimator = ObjectAnimator.ofInt(object, property,
startColor, endColor);
colorAnimator.setDuration(1000);
colorAnimator.setEvaluator(new ArgbEvaluator());
colorAnimator.setRepeatCount(1);
colorAnimator.setRepeatMode(ValueAnimator.REVERSE);
- colorAnimator.start();
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ colorAnimator.start();
+ }
+ });
+ getInstrumentation().waitForIdleSync();
startAnimation(mObjectAnimator, colorAnimator);
Thread.sleep(100);
Integer i = (Integer) colorAnimator.getAnimatedValue();
@@ -110,12 +115,17 @@
int endColor = mActivity.view.BLUE;
Object[] values = {new Integer(startColor), new Integer(endColor)};
ArgbEvaluator evaluator = new ArgbEvaluator();
- ObjectAnimator colorAnimator = ObjectAnimator.ofObject(object, property,
+ final ObjectAnimator colorAnimator = ObjectAnimator.ofObject(object, property,
evaluator, values);
colorAnimator.setDuration(1000);
colorAnimator.setRepeatCount(1);
colorAnimator.setRepeatMode(ValueAnimator.REVERSE);
- colorAnimator.start();
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ colorAnimator.start();
+ }
+ });
+ getInstrumentation().waitForIdleSync();
startAnimation(mObjectAnimator, colorAnimator);
Thread.sleep(100);
Integer i = (Integer) colorAnimator.getAnimatedValue();
@@ -132,12 +142,17 @@
int values[] = {startColor, endColor};
ArgbEvaluator evaluator = new ArgbEvaluator();
PropertyValuesHolder propertyValuesHolder = PropertyValuesHolder.ofInt(propertyName, values);
- ObjectAnimator colorAnimator = ObjectAnimator.ofPropertyValuesHolder(object,
+ final ObjectAnimator colorAnimator = ObjectAnimator.ofPropertyValuesHolder(object,
propertyValuesHolder);
colorAnimator.setDuration(1000);
colorAnimator.setRepeatCount(1);
colorAnimator.setRepeatMode(ValueAnimator.REVERSE);
- colorAnimator.start();
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ colorAnimator.start();
+ }
+ });
+ getInstrumentation().waitForIdleSync();
startAnimation(mObjectAnimator, colorAnimator);
Thread.sleep(100);
Integer i = (Integer) colorAnimator.getAnimatedValue();
diff --git a/tests/tests/app/Android.mk b/tests/tests/app/Android.mk
index d4387b4..136f072 100644
--- a/tests/tests/app/Android.mk
+++ b/tests/tests/app/Android.mk
@@ -23,12 +23,11 @@
LOCAL_JAVA_LIBRARIES := android.test.runner telephony-common voip-common
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner ctstestserver
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_SRC_FILES := $(call all-java-files-under, src) \
+ src/android/app/cts/ISecondary.aidl
LOCAL_PACKAGE_NAME := CtsAppTestCases
-LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
-
include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/app/AndroidManifest.xml b/tests/tests/app/AndroidManifest.xml
index a558564..6cafe80 100644
--- a/tests/tests/app/AndroidManifest.xml
+++ b/tests/tests/app/AndroidManifest.xml
@@ -16,23 +16,273 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.app.cts">
+ package="com.android.cts.app">
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
- <application>
+
+ <permission android:name="android.app.cts.permission.TEST_GRANTED"
+ android:protectionLevel="normal"
+ android:label="@string/permlab_testGranted"
+ android:description="@string/permdesc_testGranted">
+ <meta-data android:name="android.app.cts.string" android:value="foo" />
+ <meta-data android:name="android.app.cts.boolean" android:value="true" />
+ <meta-data android:name="android.app.cts.integer" android:value="100" />
+ <meta-data android:name="android.app.cts.color" android:value="#ff000000" />
+ <meta-data android:name="android.app.cts.float" android:value="100.1" />
+ <meta-data android:name="android.app.cts.reference" android:resource="@xml/metadata" />
+ </permission>
+
+ <uses-permission android:name="android.app.cts.permission.TEST_GRANTED" />
+ <uses-permission android:name="android.permission.READ_CONTACTS" />
+ <uses-permission android:name="android.permission.WRITE_CONTACTS" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <uses-permission android:name="android.permission.CAMERA" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+ <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+ <uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
+ <application android:label="Android TestCase"
+ android:icon="@drawable/size_48x48"
+ android:maxRecents="1"
+ android:multiArch="true"
+ android:name="android.app.cts.MockApplication"
+ android:supportsRtl="true">
<uses-library android:name="android.test.runner" />
- <service android:name="android.speech.tts.cts.StubTextToSpeechService">
+ <activity android:name="android.app.cts.ActionBarActivity" />
+
+ <activity android:name="android.app.cts.DialogCtsActivity"
+ android:label="DialogCtsActivity"
+ android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
- <action android:name="android.intent.action.TTS_SERVICE" />
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+ </intent-filter>
+ </activity>
+
+ <activity android:name="android.app.cts.MockActivity" android:label="MockActivity">
+ <meta-data android:name="android.app.alias"
+ android:resource="@xml/alias" />
+ <meta-data android:name="android.app.intent.filter"
+ android:resource="@xml/intentfilter" />
+ </activity>
+
+ <activity android:name="android.app.cts.MockApplicationActivity"
+ android:label="MockApplicationActivity">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN"/>
+ <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+ </intent-filter>
+ </activity>
+
+ <activity android:name="android.app.cts.InstrumentationTestActivity"
+ android:theme="@style/Theme_NoSwipeDismiss"
+ android:label="InstrumentationTestActivity">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <data android:mimeType="vnd.android.cursor.dir/person" />
+ </intent-filter>
+ </activity>
+
+ <activity android:name="android.app.cts.AliasActivityStub">
+ <meta-data android:name="android.app.alias"
+ android:resource="@xml/alias" />
+ </activity>
+
+ <activity android:name="android.app.cts.ChildActivity"
+ android:label="ChildActivity" />
+
+ <receiver android:name="android.app.cts.MockReceiver">
+ <intent-filter>
+ <action android:name="android.app.cts.PendingIntentTest.TEST_RECEIVER" />
+ </intent-filter>
+ </receiver>
+
+ <service android:name="android.app.cts.MockService" />
+
+ <activity android:name="android.app.cts.SearchManagerCtsActivity"
+ android:label="SearchManagerCtsActivity">
+ <intent-filter>
+ <action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
+ <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" />
+ </activity>
+
+ <service android:name="android.app.cts.LocalService">
+ <intent-filter>
+ <action android:name="android.app.cts.activity.SERVICE_LOCAL" />
+ </intent-filter>
+ <meta-data android:name="android.app.cts.string" android:value="foo" />
+ <meta-data android:name="android.app.cts.boolean" android:value="true" />
+ <meta-data android:name="android.app.cts.integer" android:value="100" />
+ <meta-data android:name="android.app.cts.color" android:value="#ff000000" />
+ <meta-data android:name="android.app.cts.float" android:value="100.1" />
+ <meta-data android:name="android.app.cts.reference" android:resource="@xml/metadata" />
</service>
+ <service android:name="android.app.cts.LocalGrantedService"
+ android:permission="android.app.cts.permission.TEST_GRANTED">
+ <intent-filter>
+ <action android:name="android.app.cts.activity.SERVICE_LOCAL_GRANTED" />
+ </intent-filter>
+ </service>
+
+ <service android:name="android.app.cts.LocalDeniedService"
+ android:permission="android.app.cts.permission.TEST_DENIED">
+ <intent-filter>
+ <action android:name="android.app.cts.activity.SERVICE_LOCAL_DENIED" />
+ </intent-filter>
+ </service>
+
+ <activity android:name="android.app.cts.TestedScreen"
+ android:process=":remoteScreen">
+ </activity>
+ <activity android:name="android.app.cts.LocalScreen" android:multiprocess="true">
+ </activity>
+ <activity android:name="android.app.cts.ClearTop" android:multiprocess="true"
+ android:launchMode="singleTop">
+ </activity>
+ <activity android:name="android.app.cts.LocalDialog" android:multiprocess="true"
+ android:theme="@android:style/Theme.Dialog">
+ </activity>
+
+ <activity android:name="android.app.cts.PendingIntentCtsActivity"
+ android:label="PendingIntentCtsActivity"/>
+
+ <activity android:name="android.app.cts.LocalActivityManagerCtsActivity"
+ android:label="LocalActivityManagerCtsActivity" />
+
+ <activity android:name="android.app.cts.LocalActivityManagerTestHelper"
+ android:label="LocalActivityManagerTestHelper" />
+
+ <activity android:name="android.app.cts.LaunchpadTabActivity" android:multiprocess="true">
+ </activity>
+
+ <activity android:name="android.app.cts.LocalActivity" android:multiprocess="true">
+ <meta-data android:name="android.app.cts.string" android:value="foo" />
+ <meta-data android:name="android.app.cts.boolean" android:value="true" />
+ <meta-data android:name="android.app.cts.integer" android:value="100" />
+ <meta-data android:name="android.app.cts.color" android:value="#ff000000" />
+ <meta-data android:name="android.app.cts.float" android:value="100.1" />
+ <meta-data android:name="android.app.cts.reference" android:resource="@xml/metadata" />
+ </activity>
+
+ <activity android:name="android.app.cts.TestedActivity"
+ android:process=":remoteActivity">
+ </activity>
+
+ <activity android:name="android.app.cts.ExpandableListTestActivity"
+ android:label="ExpandableListTestActivity">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+ </intent-filter>
+ </activity>
+
+ <activity android:name="android.app.cts.ChildTabActivity" android:label="ChildTabActivity" />
+
+ <activity android:name="android.app.cts.LauncherActivityStub"
+ android:label="LauncherActivityStub" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN"/>
+ <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+ </intent-filter>
+ </activity>
+
+ <activity android:name="android.app.cts.MockTabActivity" android:label="MockTabActivity" />
+
+ <activity android:name="android.app.cts.AppCtsActivity" android:label="AppCtsActivity">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+ </intent-filter>
+ </activity>
+
+ <activity android:name="android.app.cts.DialogCtsActivity"
+ android:theme="@style/Theme_NoSwipeDismiss"
+ android:label="DialogCtsActivity">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+ </intent-filter>
+ </activity>
+
+ <activity android:name="android.app.cts.ActivityManagerStubFooActivity"
+ android:label="ActivityManagerStubFooActivity">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+ </intent-filter>
+ </activity>
+
+ <activity android:name="android.app.cts.ActivityManagerRecentOneActivity"
+ android:label="ActivityManagerRecentOneActivity"
+ android:allowTaskReparenting="true"
+ android:taskAffinity="android.app.cts.recentOne">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ </intent-filter>
+ </activity>
+
+ <activity android:name="android.app.cts.ActivityManagerRecentTwoActivity"
+ android:label="ActivityManagerRecentTwoActivity"
+ android:allowTaskReparenting="true"
+ android:taskAffinity="android.app.cts.recentTwo">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ </intent-filter>
+ </activity>
+
+ <activity android:name="android.app.cts.ActivityManagerStubCrashActivity"
+ android:label="ActivityManagerStubCrashActivity"
+ android:multiprocess="true"
+ android:process=":ActivityManagerStubCrashActivity">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ </intent-filter>
+ </activity>
+
+ <service android:name="android.app.cts.StubRemoteService"
+ android:process=":remote">
+ <intent-filter>
+ <action
+ android:name="android.app.cts.ISecondary" />
+ <action
+ android:name="android.app.REMOTESERVICE" />
+ </intent-filter>
+ </service>
+
+ <activity android:name="android.app.ActivityGroup"
+ android:label="ActivityGroup" />
+
+ <activity android:name="android.app.cts.KeyguardManagerActivity"
+ android:label="KeyguardManagerActivity">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+ </intent-filter>
+ </activity>
+
+ <service android:name="android.app.cts.IntentServiceStub"/>
+
+ <activity android:name="android.app.cts.LaunchpadActivity"
+ android:configChanges="keyboardHidden|orientation|screenSize"
+ android:multiprocess="true">
+ </activity>
+
+ <activity android:name="android.app.cts.ActivityManagerMemoryClassLaunchActivity" />
+
+ <activity android:name="android.app.cts.ActivityManagerMemoryClassTestActivity"
+ android:process=":memoryclass" />
+
</application>
<instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
- android:targetPackage="com.android.cts.stub"
+ android:targetPackage="com.android.cts.app"
android:label="CTS tests of android.app">
<meta-data android:name="listener"
android:value="com.android.cts.runner.CtsTestRunListener" />
diff --git a/tests/assets/noiseandchirps b/tests/tests/app/assets/noiseandchirps
similarity index 100%
rename from tests/assets/noiseandchirps
rename to tests/tests/app/assets/noiseandchirps
Binary files differ
diff --git a/tests/assets/noiseandchirps.mp3 b/tests/tests/app/assets/noiseandchirps.mp3
similarity index 100%
rename from tests/assets/noiseandchirps.mp3
rename to tests/tests/app/assets/noiseandchirps.mp3
Binary files differ
diff --git a/tests/assets/noiseandchirps.ogg b/tests/tests/app/assets/noiseandchirps.ogg
similarity index 100%
rename from tests/assets/noiseandchirps.ogg
rename to tests/tests/app/assets/noiseandchirps.ogg
Binary files differ
diff --git a/tests/assets/noiseandchirps.wrong b/tests/tests/app/assets/noiseandchirps.wrong
similarity index 100%
rename from tests/assets/noiseandchirps.wrong
rename to tests/tests/app/assets/noiseandchirps.wrong
Binary files differ
diff --git a/tests/tests/app/res/drawable/icon_black.jpg b/tests/tests/app/res/drawable/icon_black.jpg
new file mode 100644
index 0000000..4c9062a
--- /dev/null
+++ b/tests/tests/app/res/drawable/icon_black.jpg
Binary files differ
diff --git a/tests/tests/app/res/drawable/icon_blue.jpg b/tests/tests/app/res/drawable/icon_blue.jpg
new file mode 100644
index 0000000..9e6c1c8
--- /dev/null
+++ b/tests/tests/app/res/drawable/icon_blue.jpg
Binary files differ
diff --git a/tests/tests/app/res/drawable/icon_green.jpg b/tests/tests/app/res/drawable/icon_green.jpg
new file mode 100644
index 0000000..55a78f2
--- /dev/null
+++ b/tests/tests/app/res/drawable/icon_green.jpg
Binary files differ
diff --git a/tests/tests/app/res/drawable/icon_red.jpg b/tests/tests/app/res/drawable/icon_red.jpg
new file mode 100644
index 0000000..6bc9e1f
--- /dev/null
+++ b/tests/tests/app/res/drawable/icon_red.jpg
Binary files differ
diff --git a/tests/tests/app/res/drawable/icon_yellow.jpg b/tests/tests/app/res/drawable/icon_yellow.jpg
new file mode 100644
index 0000000..e748059
--- /dev/null
+++ b/tests/tests/app/res/drawable/icon_yellow.jpg
Binary files differ
diff --git a/tests/tests/app/res/drawable/ninepatch_0.9.png b/tests/tests/app/res/drawable/ninepatch_0.9.png
new file mode 100644
index 0000000..24019d8
--- /dev/null
+++ b/tests/tests/app/res/drawable/ninepatch_0.9.png
Binary files differ
diff --git a/tests/tests/app/res/drawable/ninepatch_1.9.png b/tests/tests/app/res/drawable/ninepatch_1.9.png
new file mode 100644
index 0000000..c56b1db
--- /dev/null
+++ b/tests/tests/app/res/drawable/ninepatch_1.9.png
Binary files differ
diff --git a/tests/tests/app/res/drawable/pass.jpg b/tests/tests/app/res/drawable/pass.jpg
new file mode 100644
index 0000000..2f4b083
--- /dev/null
+++ b/tests/tests/app/res/drawable/pass.jpg
Binary files differ
diff --git a/tests/tests/app/res/drawable/robot.png b/tests/tests/app/res/drawable/robot.png
new file mode 100644
index 0000000..8a9e698
--- /dev/null
+++ b/tests/tests/app/res/drawable/robot.png
Binary files differ
diff --git a/tests/tests/app/res/drawable/size_48x48.jpg b/tests/tests/app/res/drawable/size_48x48.jpg
new file mode 100644
index 0000000..5c2291e
--- /dev/null
+++ b/tests/tests/app/res/drawable/size_48x48.jpg
Binary files differ
diff --git a/tests/tests/app/res/layout/alert_dialog_text_entry.xml b/tests/tests/app/res/layout/alert_dialog_text_entry.xml
new file mode 100644
index 0000000..8b87a5d
--- /dev/null
+++ b/tests/tests/app/res/layout/alert_dialog_text_entry.xml
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/username_view"
+ android:layout_height="wrap_content"
+ android:layout_width="wrap_content"
+ android:layout_marginLeft="20dip"
+ android:layout_marginRight="20dip"
+ android:text="@string/alert_dialog_username"
+ android:gravity="left"
+ android:textAppearance="?android:attr/textAppearanceMedium" />
+
+ <EditText
+ android:id="@+id/username_edit"
+ android:layout_height="wrap_content"
+ android:layout_width="match_parent"
+ android:layout_marginLeft="20dip"
+ android:layout_marginRight="20dip"
+ android:scrollHorizontally="true"
+ android:autoText="false"
+ android:capitalize="none"
+ android:gravity="fill_horizontal"
+ android:textAppearance="?android:attr/textAppearanceMedium" />
+
+ <TextView
+ android:id="@+id/password_view"
+ android:layout_height="wrap_content"
+ android:layout_width="wrap_content"
+ android:layout_marginLeft="20dip"
+ android:layout_marginRight="20dip"
+ android:text="@string/alert_dialog_password"
+ android:gravity="left"
+ android:textAppearance="?android:attr/textAppearanceMedium" />
+
+ <EditText
+ android:id="@+id/password_edit"
+ android:layout_height="wrap_content"
+ android:layout_width="match_parent"
+ android:layout_marginLeft="20dip"
+ android:layout_marginRight="20dip"
+ android:scrollHorizontally="true"
+ android:autoText="false"
+ android:capitalize="none"
+ android:gravity="fill_horizontal"
+ android:password="true"
+ android:textAppearance="?android:attr/textAppearanceMedium" />
+
+</LinearLayout>
diff --git a/tests/tests/app/res/layout/alert_dialog_text_entry_2.xml b/tests/tests/app/res/layout/alert_dialog_text_entry_2.xml
new file mode 100644
index 0000000..848b342
--- /dev/null
+++ b/tests/tests/app/res/layout/alert_dialog_text_entry_2.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/username_view"
+ android:layout_height="wrap_content"
+ android:layout_width="wrap_content"
+ android:layout_marginLeft="20dip"
+ android:layout_marginRight="20dip"
+ android:text="@string/alert_dialog_username"
+ android:gravity="left" />
+
+ <EditText
+ android:id="@+id/username_edit"
+ android:layout_height="wrap_content"
+ android:layout_width="match_parent"
+ android:layout_marginLeft="20dip"
+ android:layout_marginRight="20dip"
+ android:scrollHorizontally="true"
+ android:autoText="false"
+ android:capitalize="none"
+ android:gravity="fill_horizontal" />
+
+</LinearLayout>
diff --git a/tests/tests/app/res/layout/alertdialog_custom_title.xml b/tests/tests/app/res/layout/alertdialog_custom_title.xml
new file mode 100644
index 0000000..ff36f2a
--- /dev/null
+++ b/tests/tests/app/res/layout/alertdialog_custom_title.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 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.
+-->
+
+<TextView xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/alertdialog_custom_title"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:gravity="center_vertical|center_horizontal"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:text="@string/hello_world"/>
diff --git a/tests/tests/app/res/layout/app_activity.xml b/tests/tests/app/res/layout/app_activity.xml
new file mode 100644
index 0000000..8b7206f
--- /dev/null
+++ b/tests/tests/app/res/layout/app_activity.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2008 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.
+ -->
+
+<!-- Demonstrates receiving activity results.
+ See corresponding Java code com.android.sdk.app.ReceiveResult.java. -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
+ android:gravity="center_horizontal"
+ android:layout_width="match_parent" android:layout_height="match_parent">
+
+ <TextView
+ android:layout_width="match_parent" android:layout_height="wrap_content"
+ android:layout_weight="0"
+ android:paddingBottom="4dip"
+ android:text="@string/forwarding"/>
+
+ <Button android:id="@+id/go"
+ android:layout_width="wrap_content" android:layout_height="wrap_content"
+ android:text="@string/go">
+ <requestFocus />
+ </Button>
+
+</LinearLayout>
+
diff --git a/tests/tests/app/res/layout/checkbox_layout.xml b/tests/tests/app/res/layout/checkbox_layout.xml
new file mode 100644
index 0000000..a1f1718
--- /dev/null
+++ b/tests/tests/app/res/layout/checkbox_layout.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2008 The Android Open Source Project.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical">
+
+ <CheckBox android:id="@+id/check_box"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/hello_world" />
+
+</LinearLayout>
diff --git a/tests/tests/app/res/layout/dialog_stub_layout.xml b/tests/tests/app/res/layout/dialog_stub_layout.xml
new file mode 100644
index 0000000..c6eb10d
--- /dev/null
+++ b/tests/tests/app/res/layout/dialog_stub_layout.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ >
+</LinearLayout>
diff --git a/tests/tests/app/res/menu/browser.xml b/tests/tests/app/res/menu/browser.xml
new file mode 100644
index 0000000..29e5149
--- /dev/null
+++ b/tests/tests/app/res/menu/browser.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 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.
+-->
+
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+ <group android:id="@+id/MAIN_MENU">
+ <item android:id="@+id/goto_menu_id"
+ android:title="@string/hello_world"
+ android:alphabeticShortcut="l"/>
+ </group>
+
+</menu>
diff --git a/tests/tests/app/res/values/arrays.xml b/tests/tests/app/res/values/arrays.xml
new file mode 100644
index 0000000..71e0133
--- /dev/null
+++ b/tests/tests/app/res/values/arrays.xml
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2008 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.
+ -->
+
+<resources>
+ <item type="integer" name="reference" format="integer">101</item>
+
+ <string-array name="strings">
+ <item>zero</item>
+ <item>1</item>
+ <item>@string/reference</item>
+ </string-array>
+
+ <integer-array name="integers">
+ <item>0</item>
+ <item>1</item>
+ <item>@integer/reference</item>
+ </integer-array>
+
+ <array name="difficultyLevel">
+ <item>Easy</item>
+ <item>Medium</item>
+ <item>Hard</item>
+ </array>
+
+ <string-array name="string">
+ <item>Test String 1</item>
+ <item>Test String 2</item>
+ <item>Test String 3</item>
+ </string-array>
+
+ <integer-array name="table_row_layout">
+ <item>1</item>
+ <item>2</item>
+ <item>3</item>
+ <item>4</item>
+ <item>5</item>
+ <item>6</item>
+ <item>7</item>
+ <item>8</item>
+ <item>9</item>
+ <item>10</item>
+ </integer-array>
+</resources>
diff --git a/tests/tests/app/res/values/attrs.xml b/tests/tests/app/res/values/attrs.xml
new file mode 100644
index 0000000..4c3d9db
--- /dev/null
+++ b/tests/tests/app/res/values/attrs.xml
@@ -0,0 +1,145 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2008 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.
+ -->
+
+<resources>
+ <declare-styleable name="Style1">
+ <attr name="Type1" format="integer">
+ <enum name="type" value="28" />
+ <enum name="data" value="0xff00ff00" />
+ <enum name="asset_cookie" value="0" />
+ <enum name="resource_id" value="0" />
+ <enum name="changing_config" value="0" />
+ </attr>
+ <attr name="Type2" format="integer">
+ <enum name="type" value="28" />
+ <enum name="data" value="0xff0000ff" />
+ <enum name="asset_cookie" value="0" />
+ <enum name="resource_id" value="0" />
+ <enum name="changing_config" value="0" />
+ </attr>
+ </declare-styleable>
+ <attr name="type1" format="boolean"/>
+ <attr name="type2" format="boolean"/>
+ <attr name="type3" format="color"/>
+ <attr name="type4" format="reference|color"/>
+ <attr name="type5" format="dimension"/>
+ <attr name="type6" format="dimension"/>
+ <attr name="type7" format="dimension"/>
+ <attr name="type8" format="reference"/>
+ <attr name="type9" format="float"/>
+ <attr name="type10" format="fraction"/>
+ <attr name="type11" format="integer"/>
+ <attr name="type12" format="integer"/>
+ <attr name="type13" format="reference|string"/>
+ <attr name="type14" format="string"/>
+ <attr name="type15" format="reference"/>
+ <attr name="type16" format="string"/>
+ <declare-styleable name="style1">
+ <attr name="type1"/>
+ <attr name="type2"/>
+ <attr name="type3"/>
+ <attr name="type4"/>
+ <attr name="type5"/>
+ <attr name="type6"/>
+ <attr name="type7"/>
+ <attr name="type8"/>
+ <attr name="type9"/>
+ <attr name="type10"/>
+ <attr name="type11"/>
+ <attr name="type12"/>
+ <attr name="type13"/>
+ <attr name="type14"/>
+ <attr name="type15"/>
+ <attr name="type16"/>
+ </declare-styleable>
+ <attr name="testEnum">
+ <enum name="val1" value="1" />
+ <enum name="val2" value="2" />
+ <enum name="val10" value="10" />
+ </attr>
+ <attr name="testFlags">
+ <flag name="bit1" value="0x1" />
+ <flag name="bit2" value="0x2" />
+ <flag name="bit31" value="0x40000000" />
+ </attr>
+ <attr name="testString" format="string" />
+ <declare-styleable name="EnumStyle">
+ <attr name="testEnum" />
+ </declare-styleable>
+ <declare-styleable name="FlagStyle">
+ <attr name="testFlags" />
+ </declare-styleable>
+ <declare-styleable name="TestConfig">
+ <attr name="testString" />
+ </declare-styleable>
+ <!-- Size of text. Recommended dimension type for text is "sp" for scaled-pixels (example: 15sp).
+ Supported values include the following:<p/>
+ <ul>
+ <li><b>px</b> Pixels</li>
+ <li><b>sp</b> Scaled pixels (scaled to relative pixel size on screen). See {@link android.util.DisplayMetrics} for more information.</li>
+ <li><b>pt</b> Points</li>
+ <li><b>dip</b> Device independent pixels. See {@link android.util.DisplayMetrics} for more information.</li>
+ </ul>
+ -->
+ <attr name="textSize" format="dimension" />
+ <attr name="typeface">
+ <enum name="normal" value="0" />
+ <enum name="sans" value="1" />
+ <enum name="serif" value="2" />
+ <enum name="monospace" value="3" />
+ </attr>
+ <!-- Default text typeface style. -->
+ <attr name="textStyle">
+ <flag name="normal" value="0" />
+ <flag name="bold" value="1" />
+ <flag name="italic" value="2" />
+ </attr>
+ <!-- Color of text (usually same as colorForeground). -->
+ <attr name="textColor" format="reference|color" />
+ <!-- Color of highlighted text. -->
+ <attr name="textColorHighlight" format="reference|color" />
+ <!-- Color of hint text (displayed when the field is empty). -->
+ <attr name="textColorHint" format="reference|color" />
+ <!-- Color of link text (URLs). -->
+ <attr name="textColorLink" format="reference|color" />
+ <declare-styleable name="TextAppearance">
+ <attr name="textColor"/>
+ <attr name="textSize"/>
+ <attr name="textStyle"/>
+ <attr name="typeface"/>
+ <attr name="textColorHighlight"/>
+ <attr name="textColorHint"/>
+ <attr name="textColorLink"/>
+ </declare-styleable>
+ <!-- Integer used to uniquely identify theme overrides. -->
+ <attr name="themeType" format="integer"/>
+ <!-- Theme reference used to override parent theme. -->
+ <attr name="themeOverrideAttr" format="reference"/>
+
+ <!-- Drawable theming attributes -->
+ <attr name="themeBoolean" />
+ <attr name="themeColor" />
+ <attr name="themeFloat" />
+ <attr name="themeInteger" />
+ <attr name="themeDimension" />
+ <attr name="themeDrawable" />
+ <attr name="themeBitmap" />
+ <attr name="themeNinePatch" />
+ <attr name="themeGravity" />
+ <attr name="themeTileMode" />
+ <attr name="themeAngle" />
+</resources>
diff --git a/tests/tests/app/res/values/colors.xml b/tests/tests/app/res/values/colors.xml
new file mode 100644
index 0000000..f3cc325
--- /dev/null
+++ b/tests/tests/app/res/values/colors.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2008 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.
+ -->
+
+<resources>
+ <drawable name="red">#7f00</drawable>
+ <drawable name="blue">#770000ff</drawable>
+ <drawable name="black">#77ffffff</drawable>
+ <drawable name="yellow">#77ffff00</drawable>
+ <color name="testcolor1">#ff00ff00</color>
+ <color name="testcolor2">#ffff0000</color>
+ <color name="failColor">#ff0000ff</color>
+</resources>
diff --git a/tests/tests/app/res/values/strings.xml b/tests/tests/app/res/values/strings.xml
new file mode 100644
index 0000000..c167278
--- /dev/null
+++ b/tests/tests/app/res/values/strings.xml
@@ -0,0 +1,179 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string name="permlab_testGranted">Test Granted</string>
+ <string name="permdesc_testGranted">Used for running CTS tests, for testing operations
+ where we have the permission.</string>
+ <string name="permlab_testDynamic">Test Dynamic</string>
+ <string name="permdesc_testDynamic">Used for running CTS tests, for testing adding
+ dynamic permissions.</string>
+ <string name="permlab_testDenied">Test Denied</string>
+ <string name="permdesc_testDenied">Used for running CTS tests, for testing operations
+ where we do not have the permission.</string>
+ <string name="explain">1. click start. \n2. if above image shaked, then press pass button,
+ else press failed button.</string>
+ <string name="text_view_hello">Hello! Text view!</string>
+ <string name="text_view_hello_two_lines">Hello! \nText view!</string>
+ <string name="text_view_simple_hint">This is a hint.</string>
+ <string name="text_view_hint">This is a string for testing hint of textview.</string>
+ <string name="activity_forwarding">App/Forwarding</string>
+ <string name="forwarding">$$$</string>
+ <string name="go">Go</string>
+ <string name="back">Back</string>
+ <string name="forward_target">
+ Press back button and notice we don\'t see the previous activity.
+ </string>
+ <string name="edit_text">testing</string>
+ <string name="text">DialogTest</string>
+ <string name="text_country">Country</string>
+ <string name="text_name">Name</string>
+ <string name="hello_world">Hello, World!</string>
+ <string name="hello_android">Hello, Android!</string>
+ <string name="alert_dialog_username">Name:</string>
+ <string name="alert_dialog_password">Password:</string>
+ <string name="alert_dialog_positive">Positive</string>
+ <string name="alert_dialog_negative">Negative</string>
+ <string name="alert_dialog_neutral">Neutral</string>
+ <string name="notify">Notify </string>
+ <string name="tabs_1">testing</string>
+ <string name="table_layout_first">first</string>
+ <string name="table_layout_second">second</string>
+ <string name="table_layout_third">third</string>
+ <string name="table_layout_long">Very long to make the string out of the screen</string>
+ <string name="chronometer_text">Test Chronometer</string>
+ <string name="am">AM</string>
+ <string name="pm">PM</string>
+ <string name="viewgroup_test">ViewGroup test</string>
+ <string name="viewanimator_test">ViewAnimator test</string>
+ <string name="id_ok">OK</string>
+ <string name="id_cancel">Cancel</string>
+ <string name="context_test_string1">This is %s string.</string>
+ <string name="context_test_string2">This is test string.</string>
+ <string name="animationutils_test_instructions">Choose different animations</string>
+ <string name="animationutils_test_alpha">Alpha animation</string>
+ <string name="animationutils_test_scale">Scale animation</string>
+ <string name="animationutils_test_rotate">Rotate animation</string>
+ <string name="animationutils_test_translate">Translate animation</string>
+ <string name="animationutils_test_set">Animation set</string>
+ <string name="animationutils_test_layout">Layout animation</string>
+ <string name="animationutils_test_gridlayout">Grid layout animation</string>
+ <string name="twolinelistitem_test_text1">text1</string>
+ <string name="twolinelistitem_test_text2">text2</string>
+ <string name="metadata_text">metadata text</string>
+ <string name="horizontal_text_1">horizontal 1</string>
+ <string name="horizontal_text_2">horizontal 2</string>
+ <string name="horizontal_text_3">horizontal 3</string>
+ <string name="vertical_text_1">vertical 1</string>
+ <string name="vertical_text_2">vertical 2</string>
+ <string name="vertical_text_3">vertical 3</string>
+ <string name="reference">here</string>
+ <string name="coerceIntegerToString">100</string>
+ <string name="coerceBooleanToString">true</string>
+ <string name="coerceColorToString">#fff</string>
+ <string name="coerceFloatToString">100.0</string>
+ <string name="coerceDimensionToString">100px</string>
+ <string name="coerceFractionToString">100<xliff:g id="percent">%</xliff:g></string>
+ <string name="formattedStringNone">Format[]</string>
+ <string name="formattedStringOne">Format[<xliff:g id="format">%d</xliff:g>]</string>
+ <string name="formattedStringTwo">Format[<xliff:g id="format">%3$d,%2$s</xliff:g>]</string>
+ <string name="checkboxpref_key">checkboxpref_key</string>
+ <string name="checkboxpref_title">title of preference</string>
+ <string name="checkboxpref_summary">summary of preference</string>
+ <string name="checkboxpref_summary_on">summary on of preference</string>
+ <string name="checkboxpref_summary_off">summary off of preference</string>
+ <string name="checkboxpref_depend">checkboxpref_depend</string>
+ <string name="checkboxpref_depend_title"> depend title of preference</string>
+ <string name="checkboxpref_depend_summary"> depend summary of preference</string>
+ <string name="edittextpref_key">edittextpref_key</string>
+ <string name="edittextpref_default_value">default value of preference</string>
+ <string name="edittextpref_title">title of edit text preference</string>
+ <string name="edittextpref_summary">summary of edit text preference</string>
+ <string name="edittextpref_dialog_title">dialog title of edit text preference</string>
+ <string name="edittextpref_text">text of edit text preference</string>
+ <string name="listpref_key">listpref_key</string>
+ <string name="listpref_title">title of list preference</string>
+ <string name="listpref_summary">summary of list preference</string>
+ <string name="listpref_dialogtitle">dialog title of list preference</string>
+ <string name="easy">Easy</string>
+ <string name="medium">Medium</string>
+ <string name="hard">Hard</string>
+ <string name="footer_view">Footer view</string>
+ <string name="header_view">Header view</string>
+ <string name="dialogpref_title">title of dialog preference </string>
+ <string name="dialogpref_dialog_title">dialog title of dialog preference </string>
+ <string name="dialogpref_key">dialogpref_key</string>
+ <string name="dialogpref_default_value">default value of dialog preference</string>
+ <string name="dialogpref_summary">summary of dialog preference</string>
+ <string name="dialogpref_message">message of dialog preference</string>
+ <string name="dialogpref_sure">Sure</string>
+ <string name="dialogpref_cancel">Cancel</string>
+ <string name="pref_key">pref_key</string>
+ <string name="pref_title">title of preference</string>
+ <string name="pref_summary">summary of preference</string>
+ <string name="pref_depend_key">pref_depend_key</string>
+ <string name="pref_depend_title"> depend title of preference</string>
+ <string name="pref_depend_summary"> depend summary of preference</string>
+ <string name="android_intent_action_preference">android.intent.action.PREFERENCE</string>
+ <string name="def_pref_key">def_pref_key</string>
+ <string name="def_pref_title">default preference</string>
+ <string name="def_pref_summary">This is default preference of cts</string>
+ <string name="relative_view1">view 1</string>
+ <string name="relative_view2">view 2</string>
+ <string name="relative_view3">view 3</string>
+ <string name="relative_view4">view 4</string>
+ <string name="relative_view5">view 5</string>
+ <string name="relative_view6">view 6</string>
+ <string name="relative_view7">view 7</string>
+ <string name="relative_view8">view 8</string>
+ <string name="relative_view9">view 9</string>
+ <string name="relative_view10">view 10</string>
+ <string name="relative_view11">view 11</string>
+ <string name="relative_view12">view 12</string>
+ <string name="relative_view13">view 13</string>
+ <string name="country">Country:</string>
+ <string name="symbol">Symbol:</string>
+ <string name="country_warning">No such country registered</string>
+ <string name="version_cur">base</string>
+ <string name="version_old">base</string>
+ <string name="version_v3">base</string>
+ <string name="authenticator_label">Android CTS</string>
+ <string name="search_label">Android CTS</string>
+ <string name="tag1">tag 1</string>
+ <string name="tag2">tag 2</string>
+
+ <string name="button">Button</string>
+ <string name="holo_test">Holo Test</string>
+ <string name="holo_generator">Holo Generator</string>
+ <string name="holo_light_test">Holo Light Test</string>
+ <string name="holo_light_generator">Holo Light Generator</string>
+ <string name="reference_image">Reference Image: </string>
+ <string name="generated_image">Generated Image: </string>
+ <string name="themes_prompt">Select a Theme:</string>
+ <string name="sample_text">Sample text goes here. I wanted something creative and whimsical
+but then I just got bored...</string>
+ <string name="long_text">This is a really long string which exceeds the width of the view.
+New devices have a much larger screen which actually enables long strings to be displayed
+with no fading. I have made this string longer to fix this case. If you are correcting this
+text, I would love to see the kind of devices you guys now use! Guys, maybe some devices need longer string!
+I think so, so how about double this string, like copy and paste!
+This is a really long string which exceeds the width of the view.
+New devices have a much larger screen which actually enables long strings to be displayed
+with no fading. I have made this string longer to fix this case. If you are correcting this
+text, I would love to see the kind of devices you guys now use! Guys, maybe some devices need longer string!
+I think so, so how about double this string, like copy and paste! </string>
+ <string name="rectangle200">"M 0,0 l 200,0 l 0, 200 l -200, 0 z"</string>
+</resources>
diff --git a/tests/tests/app/res/values/styles.xml b/tests/tests/app/res/values/styles.xml
new file mode 100644
index 0000000..81925cc
--- /dev/null
+++ b/tests/tests/app/res/values/styles.xml
@@ -0,0 +1,172 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 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.
+-->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <style name="Whatever">
+ <item name="type1">true</item>
+ <item name="type2">false</item>
+ <item name="type3">#ff0000ff</item>
+ <item name="type4">#ff00ff00</item>
+ <item name="type5">0.75px</item>
+ <item name="type6">10px</item>
+ <item name="type7">18px</item>
+ <item name="type8">@drawable/pass</item>
+ <item name="type9">3.14</item>
+ <item name="type10">100%</item>
+ <item name="type11">365</item>
+ <item name="type12">86400</item>
+ <item name="type13">@string/hello_android</item>
+ <item name="type14">TypedArray Test!</item>
+ <item name="type15">@array/difficultyLevel</item>
+ <item name="type16">Typed Value!</item>
+ </style>
+
+ <style name="TextViewWithoutColorAndAppearance">
+ <item name="android:textSize">18sp</item>
+ </style>
+
+ <style name="TextViewWithColorButWithOutAppearance">
+ <item name="android:textColor">#ff0000ff</item>
+ </style>
+
+ <style name="TextViewWithColorAndAppearance">
+ <item name="android:textColor">#ff0000ff</item>
+ <item name="android:textAppearance">@style/TextAppearance.WithColor</item>
+ </style>
+
+ <style name="TextViewWithoutColorButWithAppearance">
+ <item name="android:textAppearance">@style/TextAppearance.WithColor</item>
+ </style>
+
+ <style name="TextAppearance" parent="android:TextAppearance">
+ </style>
+
+ <style name="TextAppearance.WithColor">
+ <item name="android:textColor">#ffff0000</item>
+ </style>
+
+ <style name="TextAppearance.All">
+ <item name="android:textColor">@drawable/black</item>
+ <item name="android:textSize">20px</item>
+ <item name="android:textStyle">bold</item>
+ <item name="android:textColorHint">@drawable/red</item>
+ <item name="android:textColorLink">@drawable/blue</item>
+ <item name="android:textColorHighlight">@drawable/yellow</item>
+ </style>
+
+ <style name="TextAppearance.Colors">
+ <item name="android:textColor">@drawable/black</item>
+ <item name="android:textColorHint">@drawable/blue</item>
+ <item name="android:textColorLink">@drawable/yellow</item>
+ <item name="android:textColorHighlight">@drawable/red</item>
+ </style>
+
+ <style name="TextAppearance.NotColors">
+ <item name="android:textSize">17px</item>
+ <item name="android:typeface">sans</item>
+ <item name="android:textStyle">normal</item>
+ </style>
+
+ <style name="TextAppearance.Style">
+ <item name="android:textStyle">normal</item>
+ </style>
+
+ <style name="TestEnum1">
+ <item name="testEnum">val1</item>
+ </style>
+
+ <style name="TestEnum2">
+ <item name="testEnum">val2</item>
+ </style>
+
+ <style name="TestEnum10">
+ <item name="testEnum">val10</item>
+ </style>
+
+ <style name="TestFlag1">
+ <item name="testFlags">bit1</item>
+ </style>
+
+ <style name="TestFlag2">
+ <item name="testFlags">bit2</item>
+ </style>
+
+ <style name="TestFlag31">
+ <item name="testFlags">bit31</item>
+ </style>
+
+ <style name="TestFlag1And2">
+ <item name="testFlags">bit1|bit2</item>
+ </style>
+
+ <style name="TestFlag1And2And31">
+ <item name="testFlags">bit1|bit2|bit31</item>
+ </style>
+
+ <style name="TestEnum1.EmptyInherit" />
+
+ <style name="Theme_AlertDialog">
+ <item name="android:textSize">18sp</item>
+ </style>
+
+ <style name="TestProgressBar">
+ <item name="android:indeterminateOnly">false</item>
+ <item name="android:progressDrawable">?android:drawable/progress_horizontal</item>
+ <item name="android:indeterminateDrawable">?android:drawable/progress_horizontal</item>
+ <item name="android:minHeight">20dip</item>
+ <item name="android:maxHeight">20dip</item>
+ <item name="android:focusable">true</item>
+ </style>
+
+ <style name="Test_Theme">
+ <item name="android:windowNoTitle">true</item>
+ <item name="android:panelColorForeground">#ff000000</item>
+ <item name="android:panelColorBackground">#ffffffff</item>
+ </style>
+
+ <style name="Theme_OverrideOuter">
+ <item name="themeType">1</item>
+ </style>
+
+ <style name="Theme_OverrideInner">
+ <item name="themeType">2</item>
+ <item name="themeOverrideAttr">@style/Theme_OverrideAttr</item>
+ </style>
+
+ <style name="Theme_OverrideAttr">
+ <item name="themeType">3</item>
+ </style>
+
+ <style name="Theme_ThemedDrawableTest">
+ <item name="themeBoolean">true</item>
+ <item name="themeColor">@android:color/black</item>
+ <item name="themeFloat">1.0</item>
+ <item name="themeAngle">45.0</item>
+ <item name="themeInteger">1</item>
+ <item name="themeDimension">1px</item>
+ <item name="themeDrawable">@drawable/icon_black</item>
+ <item name="themeBitmap">@drawable/icon_black</item>
+ <item name="themeNinePatch">@drawable/ninepatch_0</item>
+ <item name="themeGravity">48</item>
+ <item name="themeTileMode">2</item>
+ </style>
+
+ <style name="Theme_NoSwipeDismiss">
+ <item name="android:windowSwipeToDismiss">false</item>
+ </style>
+
+</resources>
diff --git a/tests/tests/app/res/xml/alias.xml b/tests/tests/app/res/xml/alias.xml
new file mode 100644
index 0000000..a03104f
--- /dev/null
+++ b/tests/tests/app/res/xml/alias.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+ * Copyright (C) 2008 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.
+ */
+-->
+
+<alias xmlns:android="http://schemas.android.com/apk/res/android">
+ <intent android:action="android.intent.action.MAIN"
+ android:targetPackage="com.android.cts.app"
+ android:targetClass="android.app.cts.ChildActivity"
+ android:data="http://www.google.com/">
+ </intent>
+</alias>
+
diff --git a/tests/tests/app/res/xml/intentfilter.xml b/tests/tests/app/res/xml/intentfilter.xml
new file mode 100644
index 0000000..7ed3a53
--- /dev/null
+++ b/tests/tests/app/res/xml/intentfilter.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+ * Copyright (C) 2008 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.
+ */
+-->
+<intent-filter xmlns="http://schemas.android.com/apk/res/android">
+ <action name="testAction"/>
+ <cat name="testCategory" />
+ <type name="vnd.android.cursor.dir/person"/>
+ <scheme name="testScheme"/>
+ <auth host="testHost" port="80"/>
+ <path name="testPath" literal="test"/>
+ <path name="testPath" prefix="test"/>
+ <path name="testPath" sglob="test"/>
+</intent-filter>
diff --git a/tests/tests/app/res/xml/metadata.xml b/tests/tests/app/res/xml/metadata.xml
new file mode 100644
index 0000000..336b931
--- /dev/null
+++ b/tests/tests/app/res/xml/metadata.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 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.
+-->
+
+<thedata xmlns:android="http://schemas.android.com/apk/res/android"
+ rawText="some raw text"
+ rawColor="#ffffff00"
+ android:color="#f00"
+ android:text="@string/metadata_text"/>
diff --git a/tests/tests/app/res/xml/searchable.xml b/tests/tests/app/res/xml/searchable.xml
new file mode 100644
index 0000000..f09c917
--- /dev/null
+++ b/tests/tests/app/res/xml/searchable.xml
@@ -0,0 +1,19 @@
+<?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.
+-->
+
+<searchable xmlns:android="http://schemas.android.com/apk/res/android"
+ android:label="@string/search_label"
+/>
diff --git a/tests/tests/app/src/android/app/backup/cts/BackupManagerTest.java b/tests/tests/app/src/android/app/backup/cts/BackupManagerTest.java
index f21f847..3ee1104 100644
--- a/tests/tests/app/src/android/app/backup/cts/BackupManagerTest.java
+++ b/tests/tests/app/src/android/app/backup/cts/BackupManagerTest.java
@@ -26,7 +26,7 @@
// Check that these don't crash as if they were called in an app...
BackupManager backupManager = new BackupManager(mContext);
backupManager.dataChanged();
- BackupManager.dataChanged("com.android.cts.stub");
+ BackupManager.dataChanged("com.android.cts.app");
// Backup isn't expected to work in this test but check for obvious bugs...
int result = backupManager.requestRestore(new RestoreObserver() {});
diff --git a/tests/src/android/app/cts/ActivityManagerMemoryClassLaunchActivity.java b/tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassLaunchActivity.java
similarity index 100%
rename from tests/src/android/app/cts/ActivityManagerMemoryClassLaunchActivity.java
rename to tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassLaunchActivity.java
diff --git a/tests/src/android/app/cts/ActivityManagerMemoryClassTestActivity.java b/tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassTestActivity.java
similarity index 100%
rename from tests/src/android/app/cts/ActivityManagerMemoryClassTestActivity.java
rename to tests/tests/app/src/android/app/cts/ActivityManagerMemoryClassTestActivity.java
diff --git a/tests/src/android/app/cts/ActivityManagerRecentOneActivity.java b/tests/tests/app/src/android/app/cts/ActivityManagerRecentOneActivity.java
similarity index 100%
rename from tests/src/android/app/cts/ActivityManagerRecentOneActivity.java
rename to tests/tests/app/src/android/app/cts/ActivityManagerRecentOneActivity.java
diff --git a/tests/src/android/app/cts/ActivityManagerRecentTwoActivity.java b/tests/tests/app/src/android/app/cts/ActivityManagerRecentTwoActivity.java
similarity index 100%
rename from tests/src/android/app/cts/ActivityManagerRecentTwoActivity.java
rename to tests/tests/app/src/android/app/cts/ActivityManagerRecentTwoActivity.java
diff --git a/tests/src/android/app/cts/ActivityManagerStubCrashActivity.java b/tests/tests/app/src/android/app/cts/ActivityManagerStubCrashActivity.java
similarity index 100%
rename from tests/src/android/app/cts/ActivityManagerStubCrashActivity.java
rename to tests/tests/app/src/android/app/cts/ActivityManagerStubCrashActivity.java
diff --git a/tests/src/android/app/cts/ActivityManagerStubFooActivity.java b/tests/tests/app/src/android/app/cts/ActivityManagerStubFooActivity.java
similarity index 100%
rename from tests/src/android/app/cts/ActivityManagerStubFooActivity.java
rename to tests/tests/app/src/android/app/cts/ActivityManagerStubFooActivity.java
diff --git a/tests/tests/app/src/android/app/cts/ActivityManagerTest.java b/tests/tests/app/src/android/app/cts/ActivityManagerTest.java
index 6a1ccb5..dfec7db 100644
--- a/tests/tests/app/src/android/app/cts/ActivityManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/ActivityManagerTest.java
@@ -35,7 +35,7 @@
import android.test.InstrumentationTestCase;
public class ActivityManagerTest extends InstrumentationTestCase {
- private static final String STUB_PACKAGE_NAME = "com.android.cts.stub";
+ private static final String STUB_PACKAGE_NAME = "com.android.cts.app";
private static final int WAITFOR_MSEC = 5000;
private static final String SERVICE_NAME = "android.app.cts.MockService";
private static final int WAIT_TIME = 2000;
@@ -222,13 +222,13 @@
assertTrue(hasSystemProcess && hasTestProcess);
for (RunningAppProcessInfo ra : list) {
- if (ra.processName.equals("com.android.cts.stub:remote")) {
- fail("should be no process named com.android.cts.stub:remote");
+ if (ra.processName.equals("com.android.cts.app:remote")) {
+ fail("should be no process named com.android.cts.app:remote");
}
}
// start a new process
mIntent = new Intent("android.app.REMOTESERVICE");
- mIntent.setPackage("com.android.cts.stub");
+ mIntent.setPackage("com.android.cts.app");
mInstrumentation.getTargetContext().startService(mIntent);
Thread.sleep(WAITFOR_MSEC);
@@ -236,11 +236,11 @@
assertTrue(list.size() <= listNew.size());
for (RunningAppProcessInfo ra : listNew) {
- if (ra.processName.equals("com.android.cts.stub:remote")) {
+ if (ra.processName.equals("com.android.cts.app:remote")) {
return;
}
}
- fail("com.android.cts.stub:remote process should be available");
+ fail("com.android.cts.app:remote process should be available");
}
public void testGetProcessInErrorState() throws Exception {
diff --git a/tests/src/android/app/cts/ActivityTestsBase.java b/tests/tests/app/src/android/app/cts/ActivityTestsBase.java
similarity index 100%
rename from tests/src/android/app/cts/ActivityTestsBase.java
rename to tests/tests/app/src/android/app/cts/ActivityTestsBase.java
diff --git a/tests/tests/app/src/android/app/cts/AlertDialogTest.java b/tests/tests/app/src/android/app/cts/AlertDialogTest.java
index aefcf01..a35fd9c 100644
--- a/tests/tests/app/src/android/app/cts/AlertDialogTest.java
+++ b/tests/tests/app/src/android/app/cts/AlertDialogTest.java
@@ -35,17 +35,17 @@
/*
* Test AlertDialog
*/
-public class AlertDialogTest extends ActivityInstrumentationTestCase2<DialogStubActivity> {
+public class AlertDialogTest extends ActivityInstrumentationTestCase2<DialogCtsActivity> {
private static final String ALERTDIALOG_CUSTOM_TITLE = "Hello, World!";
private Instrumentation mInstrumentation;
- private DialogStubActivity mActivity;
+ private DialogCtsActivity mActivity;
private Button mPositiveButton;
private Button mNegativeButton;
private Button mNeutralButton;
public AlertDialogTest() {
- super("com.android.cts.stub", DialogStubActivity.class);
+ super("com.android.cts.app", DialogCtsActivity.class);
}
@Override
@@ -55,7 +55,7 @@
}
protected void startDialogActivity(int dialogNumber) {
- mActivity = DialogStubActivity.startDialogActivity(this, dialogNumber);
+ mActivity = DialogCtsActivity.startDialogActivity(this, dialogNumber);
new PollingCheck() {
@Override
protected boolean check() {
@@ -65,7 +65,7 @@
}
public void testAlertDialog() throws Throwable {
- doTestAlertDialog(DialogStubActivity.TEST_ALERTDIALOG);
+ doTestAlertDialog(DialogCtsActivity.TEST_ALERTDIALOG);
}
private void doTestAlertDialog(int index) throws Throwable {
@@ -75,17 +75,17 @@
mPositiveButton = ((AlertDialog) (mActivity.getDialog())).getButton(
DialogInterface.BUTTON_POSITIVE);
assertNotNull(mPositiveButton);
- assertEquals(mActivity.getString(com.android.cts.stub.R.string.alert_dialog_positive),
+ assertEquals(mActivity.getString(com.android.cts.app.R.string.alert_dialog_positive),
mPositiveButton.getText());
mNeutralButton = ((AlertDialog) (mActivity.getDialog())).getButton(
DialogInterface.BUTTON_NEUTRAL);
assertNotNull(mNeutralButton);
- assertEquals(mActivity.getString(com.android.cts.stub.R.string.alert_dialog_neutral),
+ assertEquals(mActivity.getString(com.android.cts.app.R.string.alert_dialog_neutral),
mNeutralButton.getText());
mNegativeButton = ((AlertDialog) (mActivity.getDialog())).getButton(
DialogInterface.BUTTON_NEGATIVE);
assertNotNull(mNegativeButton);
- assertEquals(mActivity.getString(com.android.cts.stub.R.string.alert_dialog_negative),
+ assertEquals(mActivity.getString(com.android.cts.app.R.string.alert_dialog_negative),
mNegativeButton.getText());
assertFalse(mActivity.isPositiveButtonClicked);
@@ -102,40 +102,40 @@
}
public void testAlertDialogDeprecatedAPI() throws Throwable {
- doTestAlertDialog(DialogStubActivity.TEST_ALERTDIALOG_DEPRECATED);
+ doTestAlertDialog(DialogCtsActivity.TEST_ALERTDIALOG_DEPRECATED);
}
public void testAlertDialogDeprecatedAPIWithMessage() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_DEPRECATED_WITH_MESSAGE);
+ startDialogActivity(DialogCtsActivity.TEST_ALERTDIALOG_DEPRECATED_WITH_MESSAGE);
assertTrue(mActivity.getDialog().isShowing());
mPositiveButton = ((AlertDialog) (mActivity.getDialog())).getButton(
DialogInterface.BUTTON_POSITIVE);
assertNotNull(mPositiveButton);
- assertEquals(mActivity.getString(com.android.cts.stub.R.string.alert_dialog_positive),
+ assertEquals(mActivity.getString(com.android.cts.app.R.string.alert_dialog_positive),
mPositiveButton.getText());
mNegativeButton = ((AlertDialog) (mActivity.getDialog())).getButton(
DialogInterface.BUTTON_NEGATIVE);
assertNotNull(mNegativeButton);
- assertEquals(mActivity.getString(com.android.cts.stub.R.string.alert_dialog_negative),
+ assertEquals(mActivity.getString(com.android.cts.app.R.string.alert_dialog_negative),
mNegativeButton.getText());
mNeutralButton = ((AlertDialog) (mActivity.getDialog())).getButton(
DialogInterface.BUTTON_NEUTRAL);
assertNotNull(mNeutralButton);
- assertEquals(mActivity.getString(com.android.cts.stub.R.string.alert_dialog_neutral),
+ assertEquals(mActivity.getString(com.android.cts.app.R.string.alert_dialog_neutral),
mNeutralButton.getText());
- DialogStubActivity.buttonIndex = 0;
+ DialogCtsActivity.buttonIndex = 0;
performClick(mPositiveButton);
- assertEquals(DialogInterface.BUTTON_POSITIVE, DialogStubActivity.buttonIndex);
+ assertEquals(DialogInterface.BUTTON_POSITIVE, DialogCtsActivity.buttonIndex);
- DialogStubActivity.buttonIndex = 0;
+ DialogCtsActivity.buttonIndex = 0;
performClick(mNeutralButton);
- assertEquals(DialogInterface.BUTTON_NEUTRAL, DialogStubActivity.buttonIndex);
+ assertEquals(DialogInterface.BUTTON_NEUTRAL, DialogCtsActivity.buttonIndex);
- DialogStubActivity.buttonIndex = 0;
+ DialogCtsActivity.buttonIndex = 0;
performClick(mNegativeButton);
- assertEquals(DialogInterface.BUTTON_NEGATIVE, DialogStubActivity.buttonIndex);
+ assertEquals(DialogInterface.BUTTON_NEGATIVE, DialogCtsActivity.buttonIndex);
}
private void performClick(final Button button) throws Throwable {
@@ -148,18 +148,18 @@
}
public void testCustomAlertDialog() {
- startDialogActivity(DialogStubActivity.TEST_CUSTOM_ALERTDIALOG);
+ startDialogActivity(DialogCtsActivity.TEST_CUSTOM_ALERTDIALOG);
assertTrue(mActivity.getDialog().isShowing());
}
public void testCustomAlertDialogView() {
- startDialogActivity(DialogStubActivity.TEST_CUSTOM_ALERTDIALOG_VIEW);
+ startDialogActivity(DialogCtsActivity.TEST_CUSTOM_ALERTDIALOG_VIEW);
assertTrue(mActivity.getDialog().isShowing());
}
public void testCallback() {
- startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_CALLBACK);
+ startDialogActivity(DialogCtsActivity.TEST_ALERTDIALOG_CALLBACK);
assertTrue(mActivity.onCreateCalled);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_0);
@@ -169,12 +169,12 @@
}
public void testAlertDialogTheme() throws Exception {
- startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_ALERTDIALOG_THEME);
assertTrue(mActivity.getDialog().isShowing());
}
public void testAlertDialogCancelable() throws Exception {
- startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_CANCELABLE);
+ startDialogActivity(DialogCtsActivity.TEST_ALERTDIALOG_CANCELABLE);
assertTrue(mActivity.getDialog().isShowing());
assertFalse(mActivity.onCancelCalled);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
@@ -183,7 +183,7 @@
}
public void testAlertDialogNotCancelable() throws Exception {
- startDialogActivity(DialogStubActivity.TEST_ALERTDIALOG_NOT_CANCELABLE);
+ startDialogActivity(DialogCtsActivity.TEST_ALERTDIALOG_NOT_CANCELABLE);
assertTrue(mActivity.getDialog().isShowing());
assertFalse(mActivity.onCancelCalled);
mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
diff --git a/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java b/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java
index 5f826eb..b07a4d5 100644
--- a/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java
+++ b/tests/tests/app/src/android/app/cts/AlertDialog_BuilderTest.java
@@ -47,7 +47,7 @@
import android.widget.AdapterView.OnItemSelectedListener;
-public class AlertDialog_BuilderTest extends ActivityInstrumentationTestCase2<DialogStubActivity> {
+public class AlertDialog_BuilderTest extends ActivityInstrumentationTestCase2<DialogCtsActivity> {
private Builder mBuilder;
private Context mContext;
private Instrumentation mInstrumentation;
@@ -127,7 +127,7 @@
}
public AlertDialog_BuilderTest() {
- super("com.android.cts.stub", DialogStubActivity.class);
+ super("com.android.cts.app", DialogCtsActivity.class);
}
public void testConstructor() {
@@ -208,14 +208,14 @@
runTestOnUiThread(new Runnable() {
public void run() {
mBuilder = new AlertDialog.Builder(mContext);
- mBuilder.setNegativeButton(com.android.cts.stub.R.string.notify, mOnClickListener);
+ mBuilder.setNegativeButton(com.android.cts.app.R.string.notify, mOnClickListener);
mDialog = mBuilder.show();
mButton = mDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
mButton.performClick();
}
});
mInstrumentation.waitForIdleSync();
- assertEquals(mContext.getText(com.android.cts.stub.R.string.notify), mButton.getText());
+ assertEquals(mContext.getText(com.android.cts.app.R.string.notify), mButton.getText());
assertTrue(mResult);
}
@@ -223,14 +223,14 @@
runTestOnUiThread(new Runnable() {
public void run() {
mBuilder = new AlertDialog.Builder(mContext);
- mBuilder.setNeutralButton(com.android.cts.stub.R.string.notify, mOnClickListener);
+ mBuilder.setNeutralButton(com.android.cts.app.R.string.notify, mOnClickListener);
mDialog = mBuilder.show();
mButton = mDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
mButton.performClick();
}
});
mInstrumentation.waitForIdleSync();
- assertEquals(mContext.getText(com.android.cts.stub.R.string.notify), mButton.getText());
+ assertEquals(mContext.getText(com.android.cts.app.R.string.notify), mButton.getText());
assertTrue(mResult);
}
@@ -321,7 +321,7 @@
runTestOnUiThread(new Runnable() {
public void run() {
mBuilder = new AlertDialog.Builder(mContext);
- mBuilder.setItems(com.android.cts.stub.R.array.difficultyLevel, mOnClickListener);
+ mBuilder.setItems(com.android.cts.app.R.array.difficultyLevel, mOnClickListener);
mDialog = mBuilder.show();
mListView = mDialog.getListView();
}
@@ -329,13 +329,13 @@
mInstrumentation.waitForIdleSync();
final CharSequence[] levels = mContext.getResources().getTextArray(
- com.android.cts.stub.R.array.difficultyLevel);
+ com.android.cts.app.R.array.difficultyLevel);
assertEquals(levels[0], mListView.getItemAtPosition(0));
}
public void testSetItemsWithParamCharSequence() throws Throwable {
final CharSequence[] expect = mContext.getResources().getTextArray(
- com.android.cts.stub.R.array.difficultyLevel);
+ com.android.cts.app.R.array.difficultyLevel);
runTestOnUiThread(new Runnable() {
public void run() {
@@ -386,12 +386,12 @@
public void testSetMultiChoiceItemsWithParamInt() throws Throwable {
final CharSequence[] items = mContext.getResources().getTextArray(
- com.android.cts.stub.R.array.difficultyLevel);
+ com.android.cts.app.R.array.difficultyLevel);
runTestOnUiThread(new Runnable() {
public void run() {
mBuilder = new AlertDialog.Builder(mContext);
- mBuilder.setMultiChoiceItems(com.android.cts.stub.R.array.difficultyLevel, null,
+ mBuilder.setMultiChoiceItems(com.android.cts.app.R.array.difficultyLevel, null,
mOnMultiChoiceClickListener);
mDialog = mBuilder.show();
mListView = mDialog.getListView();
@@ -409,7 +409,7 @@
public void testSetMultiChoiceItemsWithParamCharSequence() throws Throwable {
final CharSequence[] items = mContext.getResources().getTextArray(
- com.android.cts.stub.R.array.difficultyLevel);
+ com.android.cts.app.R.array.difficultyLevel);
runTestOnUiThread(new Runnable() {
public void run() {
@@ -454,12 +454,12 @@
public void testSetSingleChoiceItemsWithParamInt() throws Throwable {
final CharSequence[] items = mContext.getResources().getTextArray(
- com.android.cts.stub.R.array.difficultyLevel);
+ com.android.cts.app.R.array.difficultyLevel);
runTestOnUiThread(new Runnable() {
public void run() {
mBuilder = new AlertDialog.Builder(mContext);
- mBuilder.setSingleChoiceItems(com.android.cts.stub.R.array.difficultyLevel, 0,
+ mBuilder.setSingleChoiceItems(com.android.cts.app.R.array.difficultyLevel, 0,
mOnClickListener);
mDialog = mBuilder.show();
mListView = mDialog.getListView();
@@ -507,7 +507,7 @@
public void testSetSingleChoiceItemsWithParamCharSequence() throws Throwable {
final CharSequence[] items = mContext.getResources().getTextArray(
- com.android.cts.stub.R.array.difficultyLevel);
+ com.android.cts.app.R.array.difficultyLevel);
runTestOnUiThread(new Runnable() {
public void run() {
@@ -527,7 +527,7 @@
public void testSetSingleChoiceItems() throws Throwable {
final CharSequence[] items = mContext.getResources().getTextArray(
- com.android.cts.stub.R.array.difficultyLevel);
+ com.android.cts.app.R.array.difficultyLevel);
runTestOnUiThread(new Runnable() {
public void run() {
@@ -552,7 +552,7 @@
public void run() {
mBuilder = new AlertDialog.Builder(mContext);
mBuilder.setOnItemSelectedListener(mOnItemSelectedListener);
- mBuilder.setItems(com.android.cts.stub.R.array.difficultyLevel, mOnClickListener);
+ mBuilder.setItems(com.android.cts.app.R.array.difficultyLevel, mOnClickListener);
mDialog = mBuilder.show();
mListView = mDialog.getListView();
mListView.pointToPosition(0, 0);
diff --git a/tests/src/android/app/cts/AliasActivityStub.java b/tests/tests/app/src/android/app/cts/AliasActivityStub.java
similarity index 100%
rename from tests/src/android/app/cts/AliasActivityStub.java
rename to tests/tests/app/src/android/app/cts/AliasActivityStub.java
diff --git a/tests/tests/app/src/android/app/cts/AliasActivityTest.java b/tests/tests/app/src/android/app/cts/AliasActivityTest.java
index e668496..d44050f 100644
--- a/tests/tests/app/src/android/app/cts/AliasActivityTest.java
+++ b/tests/tests/app/src/android/app/cts/AliasActivityTest.java
@@ -17,23 +17,31 @@
package android.app.cts;
import android.app.AliasActivity;
+import android.app.Instrumentation;
+import android.content.Context;
import android.content.Intent;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
-public class AliasActivityTest extends AndroidTestCase {
+public class AliasActivityTest extends InstrumentationTestCase {
private static final long SLEEP_TIME = 1000;
- public void testAliasActivity() throws InterruptedException {
- new AliasActivity();
+ public void testAliasActivity() throws Throwable {
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ new AliasActivity();
+ }
+ });
+ getInstrumentation().waitForIdleSync();
+ Context context = getInstrumentation().getTargetContext();
Intent intent = new Intent();
- intent.setClass(getContext(), AliasActivityStub.class);
+ intent.setClass(context, AliasActivityStub.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
assertFalse(ChildActivity.isStarted);
assertFalse(AliasActivityStub.isOnCreateCalled);
- getContext().startActivity(intent);
+ context.startActivity(intent);
Thread.sleep(SLEEP_TIME);
assertTrue(AliasActivityStub.isOnCreateCalled);
assertTrue(ChildActivity.isStarted);
diff --git a/tests/src/android/app/cts/AppStubActivity.java b/tests/tests/app/src/android/app/cts/AppCtsActivity.java
similarity index 97%
rename from tests/src/android/app/cts/AppStubActivity.java
rename to tests/tests/app/src/android/app/cts/AppCtsActivity.java
index fa786fa..a1722bb 100644
--- a/tests/src/android/app/cts/AppStubActivity.java
+++ b/tests/tests/app/src/android/app/cts/AppCtsActivity.java
@@ -26,12 +26,12 @@
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
-import com.android.cts.stub.R;
+import com.android.cts.app.R;
/**
* A minimal "Hello, World!" application.
*/
-public class AppStubActivity extends Activity {
+public class AppCtsActivity extends Activity {
private Dialog mDialog;
public boolean mOnPrepareDialog;
public boolean mOnOptionsMenuClosedCalled;
@@ -47,7 +47,7 @@
public boolean mCreateContextMenuCalled;
public boolean mRequestWinFeatureRet = false;
- public AppStubActivity() {
+ public AppCtsActivity() {
}
diff --git a/tests/src/android/app/cts/ChildActivity.java b/tests/tests/app/src/android/app/cts/ChildActivity.java
similarity index 100%
rename from tests/src/android/app/cts/ChildActivity.java
rename to tests/tests/app/src/android/app/cts/ChildActivity.java
diff --git a/tests/src/android/app/cts/ChildTabActivity.java b/tests/tests/app/src/android/app/cts/ChildTabActivity.java
similarity index 100%
rename from tests/src/android/app/cts/ChildTabActivity.java
rename to tests/tests/app/src/android/app/cts/ChildTabActivity.java
diff --git a/tests/src/android/app/cts/ClearTop.java b/tests/tests/app/src/android/app/cts/ClearTop.java
similarity index 100%
rename from tests/src/android/app/cts/ClearTop.java
rename to tests/tests/app/src/android/app/cts/ClearTop.java
diff --git a/tests/src/android/app/cts/DialogStubActivity.java b/tests/tests/app/src/android/app/cts/DialogCtsActivity.java
similarity index 97%
rename from tests/src/android/app/cts/DialogStubActivity.java
rename to tests/tests/app/src/android/app/cts/DialogCtsActivity.java
index 817e716..2fb293e 100644
--- a/tests/src/android/app/cts/DialogStubActivity.java
+++ b/tests/tests/app/src/android/app/cts/DialogCtsActivity.java
@@ -16,7 +16,7 @@
package android.app.cts;
-import com.android.cts.stub.R;
+import com.android.cts.app.R;
import android.app.Activity;
import android.app.AlertDialog;
@@ -43,7 +43,7 @@
/*
* Stub class for Dialog, AlertDialog, DatePickerDialog, TimePickerDialog etc.
*/
-public class DialogStubActivity extends Activity {
+public class DialogCtsActivity extends Activity {
public static final int TEST_DIALOG_WITHOUT_THEME = 0;
public static final int TEST_DIALOG_WITH_THEME = 1;
public static final int TEST_ALERTDIALOG = 2;
@@ -71,7 +71,7 @@
public static final String DEFAULT_ALERTDIALOG_TITLE = "AlertDialog";
public static final String DEFAULT_ALERTDIALOG_MESSAGE = "AlertDialog message";
- private static final String LOG_TAG = "DialogStubActivity";
+ private static final String LOG_TAG = "DialogCtsActivity";
public boolean isPositiveButtonClicked = false;
public boolean isNegativeButtonClicked = false;
@@ -235,8 +235,8 @@
@SuppressWarnings("deprecation")
private AlertDialog getAlertDialogInstance(boolean deprecated) {
- mAlertDialog = new AlertDialog.Builder(DialogStubActivity.this).create();
- mAlertDialog.setIcon(com.android.cts.stub.R.drawable.pass);
+ mAlertDialog = new AlertDialog.Builder(DialogCtsActivity.this).create();
+ mAlertDialog.setIcon(com.android.cts.app.R.drawable.pass);
mAlertDialog.setTitle(DEFAULT_ALERTDIALOG_TITLE);
mAlertDialog.setMessage(DEFAULT_ALERTDIALOG_MESSAGE);
mAlertDialog.setInverseBackgroundForced(true);
@@ -267,7 +267,7 @@
final LayoutInflater inflate = getLayoutInflater();
final View customTitleViewCustom = inflate.inflate(R.layout.alertdialog_custom_title, null);
final View textEntryView = inflate.inflate(R.layout.alert_dialog_text_entry_2, null);
- mAlertDialog = new AlertDialog.Builder(DialogStubActivity.this).create();
+ mAlertDialog = new AlertDialog.Builder(DialogCtsActivity.this).create();
mAlertDialog.setCustomTitle(customTitleViewCustom);
mAlertDialog.setMessage(DEFAULT_ALERTDIALOG_MESSAGE);
if (withSpacing) {
diff --git a/tests/tests/app/src/android/app/cts/DialogTest.java b/tests/tests/app/src/android/app/cts/DialogTest.java
index f0d00ba..2bbe346 100644
--- a/tests/tests/app/src/android/app/cts/DialogTest.java
+++ b/tests/tests/app/src/android/app/cts/DialogTest.java
@@ -15,7 +15,7 @@
*/
package android.app.cts;
-import com.android.cts.stub.R;
+import com.android.cts.app.R;
import android.app.Dialog;
import android.app.Instrumentation;
@@ -38,6 +38,7 @@
import android.os.Message;
import android.os.SystemClock;
import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
@@ -49,10 +50,10 @@
import java.lang.ref.WeakReference;
-public class DialogTest extends ActivityInstrumentationTestCase2<DialogStubActivity> {
+public class DialogTest extends ActivityInstrumentationTestCase2<DialogCtsActivity> {
protected static final long SLEEP_TIME = 200;
- private static final String STUB_ACTIVITY_PACKAGE = "com.android.cts.stub";
+ private static final String STUB_ACTIVITY_PACKAGE = "com.android.cts.app";
private static final long TEST_TIMEOUT = 1000L;
/**
@@ -68,11 +69,11 @@
private Instrumentation mInstrumentation;
private Context mContext;
- private DialogStubActivity mActivity;
+ private DialogCtsActivity mActivity;
public DialogTest() {
- super(STUB_ACTIVITY_PACKAGE, DialogStubActivity.class);
+ super(STUB_ACTIVITY_PACKAGE, DialogCtsActivity.class);
}
@Override
@@ -83,10 +84,11 @@
}
private void startDialogActivity(int dialogNumber) {
- mActivity = DialogStubActivity.startDialogActivity(this, dialogNumber);
+ mActivity = DialogCtsActivity.startDialogActivity(this, dialogNumber);
}
- public void testConstructor(){
+ @UiThreadTest
+ public void testConstructor() {
new Dialog(mContext);
Dialog d = new Dialog(mContext, 0);
// According to javadoc of constructors, it will set theme to system default theme,
@@ -104,14 +106,14 @@
}
public void testConstructor_protectedCancellable() {
- startDialogActivity(DialogStubActivity.TEST_PROTECTED_CANCELABLE);
+ startDialogActivity(DialogCtsActivity.TEST_PROTECTED_CANCELABLE);
mActivity.onCancelListenerCalled = false;
sendKeys(KeyEvent.KEYCODE_BACK);
assertTrue(mActivity.onCancelListenerCalled);
}
public void testConstructor_protectedNotCancellable() {
- startDialogActivity(DialogStubActivity.TEST_PROTECTED_NOT_CANCELABLE);
+ startDialogActivity(DialogCtsActivity.TEST_PROTECTED_NOT_CANCELABLE);
mActivity.onCancelListenerCalled = false;
sendKeys(KeyEvent.KEYCODE_BACK);
assertFalse(mActivity.onCancelListenerCalled);
@@ -140,7 +142,7 @@
}
public void testOnStartCreateStop(){
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertTrue(d.isOnStartCalled);
@@ -151,8 +153,8 @@
assertTrue(d.isOnStopCalled);
}
- public void testAccessOwnerActivity() {
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ public void testAccessOwnerActivity() throws Throwable {
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
Dialog d = mActivity.getDialog();
assertNotNull(d);
assertSame(mActivity, d.getOwnerActivity());
@@ -166,12 +168,17 @@
// expected
}
- d = new Dialog(mContext);
- assertNull(d.getOwnerActivity());
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ Dialog dialog = new Dialog(mContext);
+ assertNull(dialog.getOwnerActivity());
+ }
+ });
+ mInstrumentation.waitForIdleSync();
}
public void testShow() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
final View decor = d.getWindow().getDecorView();
@@ -199,7 +206,7 @@
}
public void testOnSaveInstanceState() {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertFalse(d.isOnSaveInstanceStateCalled);
@@ -219,7 +226,7 @@
}
public void testGetCurrentFocus() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertNull(d.getCurrentFocus());
runTestOnUiThread(new Runnable() {
@@ -236,7 +243,7 @@
}
public void testSetContentView() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
assertNotNull(d);
@@ -310,7 +317,7 @@
public void testSetTitle() {
final String expectedTitle = "Test Dialog Without theme";
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
assertNotNull(mActivity.getDialog());
mActivity.setUpTitle(expectedTitle);
@@ -326,7 +333,7 @@
}
public void testOnKeyDownKeyUp() {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertFalse(d.isOnKeyDownCalled);
assertFalse(d.isOnKeyUpCalled);
@@ -345,7 +352,7 @@
}
public void testOnKeyMultiple() {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertNull(d.keyMultipleEvent);
@@ -357,7 +364,7 @@
}
public void testTouchEvent() {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertNull(d.onTouchEvent);
@@ -408,7 +415,7 @@
}
public void testTrackballEvent() {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
long eventTime = SystemClock.uptimeMillis();
final MotionEvent trackBallEvent = MotionEvent.obtain(eventTime, eventTime,
@@ -437,7 +444,7 @@
}
public void testOnWindowAttributesChanged() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertTrue(d.isOnWindowAttributesChangedCalled);
@@ -457,7 +464,7 @@
}
public void testOnContentChanged() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertNotNull(d);
@@ -474,7 +481,7 @@
}
public void testOnWindowFocusChanged() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
assertTrue(d.isOnWindowFocusChangedCalled);
d.isOnWindowFocusChangedCalled = false;
@@ -482,7 +489,7 @@
// show a new dialog, the new dialog get focus
runTestOnUiThread(new Runnable() {
public void run() {
- mActivity.showDialog(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ mActivity.showDialog(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
}
});
mInstrumentation.waitForIdleSync();
@@ -496,7 +503,7 @@
}
public void testDispatchKeyEvent() {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
sendKeys(KeyEvent.KEYCODE_0);
@@ -544,7 +551,7 @@
* the user canceling the menu with the back/menu button, or when an item is selected).
*/
public void testContextMenu() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
final LinearLayout parent = new LinearLayout(mContext);
final MockView v = new MockView(mContext);
@@ -620,7 +627,7 @@
}
public void testTakeKeyEvents() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
final View v = d.getWindow().getDecorView();
assertNull(d.getCurrentFocus());
@@ -647,13 +654,13 @@
}
public void testRequestWindowFeature() {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
// called requestWindowFeature at TestDialog onCreate method
assertTrue(((TestDialog) mActivity.getDialog()).isRequestWindowFeature);
}
public void testSetFeatureDrawableResource() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
runTestOnUiThread(new Runnable() {
public void run() {
mActivity.getDialog().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
@@ -664,28 +671,28 @@
}
public void testSetFeatureDrawableUri() {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
mActivity.getDialog().setFeatureDrawableUri(0, Uri.parse("http://www.google.com"));
}
public void testSetFeatureDrawable() {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
mActivity.getDialog().setFeatureDrawable(0, new MockDrawable());
}
public void testSetFeatureDrawableAlpha() {
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
mActivity.getDialog().setFeatureDrawableAlpha(0, 0);
}
public void testGetLayoutInflater() {
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
assertEquals(d.getWindow().getLayoutInflater(), d.getLayoutInflater());
}
public void testSetCancelable_true() {
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
d.setCancelable(true);
@@ -695,7 +702,7 @@
}
public void testSetCancellable_false() {
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
d.setCancelable(false);
@@ -710,7 +717,7 @@
* 2. Set a listener to be invoked when the dialog is canceled.
*/
public void testCancel_listener() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
assertTrue(d.isShowing());
@@ -727,7 +734,7 @@
}
public void testCancel_noListener() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
assertTrue(d.isShowing());
@@ -741,7 +748,7 @@
public void testSetCancelMessage() throws Exception {
mCalledCallback = false;
- startDialogActivity(DialogStubActivity.TEST_ONSTART_AND_ONSTOP);
+ startDialogActivity(DialogCtsActivity.TEST_ONSTART_AND_ONSTOP);
final TestDialog d = (TestDialog) mActivity.getDialog();
final HandlerThread ht = new HandlerThread("DialogTest");
ht.start();
@@ -768,7 +775,7 @@
*/
public void testSetOnDismissListener_listener() throws Throwable {
mCalledCallback = false;
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
d.setOnDismissListener(new OnDismissListener() {
@@ -785,7 +792,7 @@
}
public void testSetOnDismissListener_noListener() throws Throwable {
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
assertTrue(d.isShowing());
mCalledCallback = false;
@@ -797,7 +804,7 @@
public void testSetDismissMessage() throws Throwable {
mCalledCallback = false;
- startDialogActivity(DialogStubActivity.TEST_DIALOG_WITHOUT_THEME);
+ startDialogActivity(DialogCtsActivity.TEST_DIALOG_WITHOUT_THEME);
final Dialog d = mActivity.getDialog();
final HandlerThread ht = new HandlerThread("DialogTest");
diff --git a/tests/src/android/app/cts/ExpandableListTestActivity.java b/tests/tests/app/src/android/app/cts/ExpandableListTestActivity.java
similarity index 100%
rename from tests/src/android/app/cts/ExpandableListTestActivity.java
rename to tests/tests/app/src/android/app/cts/ExpandableListTestActivity.java
diff --git a/tests/src/android/app/cts/IBinderParcelable.java b/tests/tests/app/src/android/app/cts/IBinderParcelable.java
similarity index 100%
rename from tests/src/android/app/cts/IBinderParcelable.java
rename to tests/tests/app/src/android/app/cts/IBinderParcelable.java
diff --git a/tests/src/android/app/cts/ISecondary.aidl b/tests/tests/app/src/android/app/cts/ISecondary.aidl
similarity index 100%
rename from tests/src/android/app/cts/ISecondary.aidl
rename to tests/tests/app/src/android/app/cts/ISecondary.aidl
diff --git a/tests/tests/app/src/android/app/cts/InstrumentationTest.java b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
index 16a4ee1..f528789 100644
--- a/tests/tests/app/src/android/app/cts/InstrumentationTest.java
+++ b/tests/tests/app/src/android/app/cts/InstrumentationTest.java
@@ -16,8 +16,7 @@
package android.app.cts;
-import com.android.cts.stub.R;
-
+import com.android.cts.app.R;
import android.app.Activity;
import android.app.Application;
@@ -38,6 +37,7 @@
import android.os.IBinder;
import android.os.SystemClock;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.view.InputQueue;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
@@ -58,6 +58,7 @@
private Intent mIntent;
private boolean mRunOnMainSyncResult;
private Context mContext;
+ private MockActivity mMockActivity;
@Override
protected void setUp() throws Exception {
@@ -254,14 +255,19 @@
}
public void testInvokeContextMenuAction() throws Exception {
- MockActivity activity = new MockActivity();
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ mMockActivity = new MockActivity();
+ }
+ });
+ mInstrumentation.waitForIdleSync();
final int id = 1;
final int flag = 2;
- mInstrumentation.invokeContextMenuAction(activity, id, flag);
+ mInstrumentation.invokeContextMenuAction(mMockActivity, id, flag);
mInstrumentation.waitForIdleSync();
- assertEquals(id, activity.mWindow.mId);
- assertEquals(flag, activity.mWindow.mFlags);
+ assertEquals(id, mMockActivity.mWindow.mId);
+ assertEquals(flag, mMockActivity.mWindow.mFlags);
}
public void testSendStringSync() {
@@ -365,6 +371,7 @@
assertEquals(KeyEvent.KEYCODE_0, mActivity.getKeyDownList().get(0).getKeyCode());
}
+ @UiThreadTest
public void testNewActivity() throws Exception {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
diff --git a/tests/src/android/app/cts/InstrumentationTestActivity.java b/tests/tests/app/src/android/app/cts/InstrumentationTestActivity.java
similarity index 99%
rename from tests/src/android/app/cts/InstrumentationTestActivity.java
rename to tests/tests/app/src/android/app/cts/InstrumentationTestActivity.java
index 1cedd9f..ac1039b 100644
--- a/tests/src/android/app/cts/InstrumentationTestActivity.java
+++ b/tests/tests/app/src/android/app/cts/InstrumentationTestActivity.java
@@ -29,7 +29,7 @@
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
-import com.android.cts.stub.R;
+import com.android.cts.app.R;
public class InstrumentationTestActivity extends Activity {
diff --git a/tests/src/android/app/cts/IntentServiceStub.java b/tests/tests/app/src/android/app/cts/IntentServiceStub.java
similarity index 100%
rename from tests/src/android/app/cts/IntentServiceStub.java
rename to tests/tests/app/src/android/app/cts/IntentServiceStub.java
diff --git a/tests/src/android/app/cts/KeyguardManagerActivity.java b/tests/tests/app/src/android/app/cts/KeyguardManagerActivity.java
similarity index 100%
rename from tests/src/android/app/cts/KeyguardManagerActivity.java
rename to tests/tests/app/src/android/app/cts/KeyguardManagerActivity.java
diff --git a/tests/tests/app/src/android/app/cts/KeyguardManagerTest.java b/tests/tests/app/src/android/app/cts/KeyguardManagerTest.java
index 13264ac..3f04340 100644
--- a/tests/tests/app/src/android/app/cts/KeyguardManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/KeyguardManagerTest.java
@@ -27,7 +27,7 @@
private static final String TAG = "KeyguardManagerTest";
public KeyguardManagerTest() {
- super("com.android.cts.stub", KeyguardManagerActivity.class);
+ super("com.android.cts.app", KeyguardManagerActivity.class);
}
public void testNewKeyguardLock() {
diff --git a/tests/src/android/app/cts/LauncherActivityStub.java b/tests/tests/app/src/android/app/cts/LauncherActivityStub.java
similarity index 100%
rename from tests/src/android/app/cts/LauncherActivityStub.java
rename to tests/tests/app/src/android/app/cts/LauncherActivityStub.java
diff --git a/tests/tests/app/src/android/app/cts/LauncherActivityTest.java b/tests/tests/app/src/android/app/cts/LauncherActivityTest.java
index a7e0481..040ff83 100644
--- a/tests/tests/app/src/android/app/cts/LauncherActivityTest.java
+++ b/tests/tests/app/src/android/app/cts/LauncherActivityTest.java
@@ -16,59 +16,54 @@
package android.app.cts;
-
+import android.app.Activity;
import android.app.Instrumentation;
import android.app.LauncherActivity;
import android.app.LauncherActivity.ListItem;
+import android.content.Context;
import android.content.Intent;
import android.test.InstrumentationTestCase;
+import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
import android.view.KeyEvent;
import java.util.List;
-public class LauncherActivityTest extends InstrumentationTestCase {
+public class LauncherActivityTest
+ extends ActivityInstrumentationTestCase2<LauncherActivityStub> {
+
private Instrumentation mInstrumentation;
private LauncherActivityStub mActivity;
+ public LauncherActivityTest() {
+ super("com.android.cts.app", LauncherActivityStub.class);
+ }
+
@Override
protected void setUp() throws Exception {
super.setUp();
mInstrumentation = getInstrumentation();
+ mActivity = getActivity();
}
- @Override
- protected void tearDown() throws Exception {
- if (mActivity != null) {
- if (!mActivity.isFinishing()) {
- mActivity.finish();
+ public void testLaunchActivity() throws Throwable {
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ // Test getTargetIntent. LaunchActivity#getTargetIntent() just returns a Intent() instance
+ // with no content, so we use LaunchActivityStub#getSuperIntent() to get the default Intent,
+ // and create a new intent for other tests.
+ assertNotNull(mActivity.getSuperIntent());
+
+ // Test makeListItems. Make sure the size > 0. The sorted order is related to the sort
+ // way, so it's mutable.
+ final List<ListItem> list = mActivity.makeListItems();
+ assertTrue(list.size() > 0);
+
+ // There should be an activity(but with uncertain content) in position 0.
+ assertNotNull(mActivity.intentForPosition(0));
}
- }
- super.tearDown();
- }
-
- public void testLaunchActivity() {
- // Constructor of LaunchActivity can't be invoked directly.
- new LauncherActivityStub();
- final String packageName = "com.android.cts.stub";
- final Intent intent = new Intent(Intent.ACTION_MAIN);
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.setClassName(packageName, LauncherActivityStub.class.getName());
- mActivity = (LauncherActivityStub) mInstrumentation.startActivitySync(intent);
- // Test onCreate
- assertTrue(mActivity.isOnCreateCalled);
-
- // Test getTargetIntent. LaunchActivity#getTargetIntent() just returns a Intent() instance
- // with no content, so we use LaunchActivityStub#getSuperIntent() to get the default Intent,
- // and create a new intent for other tests.
- assertNotNull(mActivity.getSuperIntent());
-
- // Test makeListItems. Make sure the size > 0. The sorted order is related to the sort
- // way, so it's mutable.
- final List<ListItem> list = mActivity.makeListItems();
- assertTrue(list.size() > 0);
-
- // There should be an activity(but with uncertain content) in position 0.
- assertNotNull(mActivity.intentForPosition(0));
+ });
+ mInstrumentation.waitForIdleSync();
// Test onListItemClick
sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
diff --git a/tests/tests/app/src/android/app/cts/LauncherActivity_IconResizerTest.java b/tests/tests/app/src/android/app/cts/LauncherActivity_IconResizerTest.java
index 695050a..e36cf57 100644
--- a/tests/tests/app/src/android/app/cts/LauncherActivity_IconResizerTest.java
+++ b/tests/tests/app/src/android/app/cts/LauncherActivity_IconResizerTest.java
@@ -16,7 +16,7 @@
package android.app.cts;
-import com.android.cts.stub.R;
+import com.android.cts.app.R;
import android.app.LauncherActivity;
@@ -27,7 +27,7 @@
public class LauncherActivity_IconResizerTest extends
ActivityInstrumentationTestCase2<LauncherActivityStub> {
- private static final String PACKAGE = "com.android.cts.stub";
+ private static final String PACKAGE = "com.android.cts.app";
private LauncherActivityStub mActivity;
public LauncherActivity_IconResizerTest() {
diff --git a/tests/src/android/app/cts/LaunchpadActivity.java b/tests/tests/app/src/android/app/cts/LaunchpadActivity.java
similarity index 100%
rename from tests/src/android/app/cts/LaunchpadActivity.java
rename to tests/tests/app/src/android/app/cts/LaunchpadActivity.java
diff --git a/tests/src/android/app/cts/LaunchpadTabActivity.java b/tests/tests/app/src/android/app/cts/LaunchpadTabActivity.java
similarity index 100%
rename from tests/src/android/app/cts/LaunchpadTabActivity.java
rename to tests/tests/app/src/android/app/cts/LaunchpadTabActivity.java
diff --git a/tests/src/android/app/cts/LocalActivity.java b/tests/tests/app/src/android/app/cts/LocalActivity.java
similarity index 100%
rename from tests/src/android/app/cts/LocalActivity.java
rename to tests/tests/app/src/android/app/cts/LocalActivity.java
diff --git a/tests/src/android/app/cts/LocalActivityManagerStubActivity.java b/tests/tests/app/src/android/app/cts/LocalActivityManagerCtsActivity.java
similarity index 95%
rename from tests/src/android/app/cts/LocalActivityManagerStubActivity.java
rename to tests/tests/app/src/android/app/cts/LocalActivityManagerCtsActivity.java
index e64c75a..93da3e4 100644
--- a/tests/src/android/app/cts/LocalActivityManagerStubActivity.java
+++ b/tests/tests/app/src/android/app/cts/LocalActivityManagerCtsActivity.java
@@ -19,7 +19,7 @@
import android.app.Activity;
import android.os.Bundle;
-public class LocalActivityManagerStubActivity extends Activity{
+public class LocalActivityManagerCtsActivity extends Activity{
public static boolean sIsOnResumeCalled;
public static boolean sIsOnStopCalled;
diff --git a/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java b/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
index 237a198..1b40476 100644
--- a/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/LocalActivityManagerTest.java
@@ -21,6 +21,7 @@
import android.app.LocalActivityManager;
import android.content.Intent;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
public class LocalActivityManagerTest extends InstrumentationTestCase implements CTSResult {
@@ -46,6 +47,7 @@
mInstrumentation.getTargetContext().startActivity(intent);
}
+ @UiThreadTest
public void testConstructor() {
new LocalActivityManager(new Activity(), true);
new LocalActivityManager(new Activity(), false);
diff --git a/tests/src/android/app/cts/LocalActivityManagerTestHelper.java b/tests/tests/app/src/android/app/cts/LocalActivityManagerTestHelper.java
similarity index 90%
rename from tests/src/android/app/cts/LocalActivityManagerTestHelper.java
rename to tests/tests/app/src/android/app/cts/LocalActivityManagerTestHelper.java
index 76af648..5c0aca0 100644
--- a/tests/src/android/app/cts/LocalActivityManagerTestHelper.java
+++ b/tests/tests/app/src/android/app/cts/LocalActivityManagerTestHelper.java
@@ -87,7 +87,7 @@
private void testRemoveAllActivity() {
final String id = "id_remove_activity";
- final Intent intent = new Intent(this, LocalActivityManagerStubActivity.class);
+ final Intent intent = new Intent(this, LocalActivityManagerCtsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mLocalActivityManager.startActivity(id, intent);
@@ -98,7 +98,7 @@
}
if (!activity.getClass().getName().equals("android.app.cts."
- + "LocalActivityManagerStubActivity")) {
+ + "LocalActivityManagerCtsActivity")) {
fail();
return;
}
@@ -115,27 +115,27 @@
private void testDispatchDestroy() {
final String id1 = "id_dispatch_destroy1";
final String id2 = "id_dispatch_destroy2";
- final Intent intent = new Intent(this, LocalActivityManagerStubActivity.class);
+ final Intent intent = new Intent(this, LocalActivityManagerCtsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mLocalActivityManager.startActivity(id1, intent);
- LocalActivityManagerStubActivity.sIsOnDestroyCalled = false;
+ LocalActivityManagerCtsActivity.sIsOnDestroyCalled = false;
mLocalActivityManager.dispatchDestroy(false);
if (mLocalActivityManager.getCurrentActivity().isFinishing()){
fail();
return;
}
- if (!LocalActivityManagerStubActivity.sIsOnDestroyCalled) {
+ if (!LocalActivityManagerCtsActivity.sIsOnDestroyCalled) {
fail();
return;
}
mLocalActivityManager.startActivity(id2, intent);
- LocalActivityManagerStubActivity.sIsOnDestroyCalled = false;
+ LocalActivityManagerCtsActivity.sIsOnDestroyCalled = false;
mLocalActivityManager.dispatchDestroy(true);
- if (!LocalActivityManagerStubActivity.sIsOnDestroyCalled) {
+ if (!LocalActivityManagerCtsActivity.sIsOnDestroyCalled) {
fail();
return;
}
@@ -157,7 +157,7 @@
}
final String id = "id_dispatch_pause";
- final Intent intent = new Intent(this, LocalActivityManagerStubActivity.class);
+ final Intent intent = new Intent(this, LocalActivityManagerCtsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mLocalActivityManager.startActivity(id, intent);
@@ -176,12 +176,12 @@
private void testDispatchPauseFalse() {
final String id = "id_dispatch_pause";
- final Intent intent = new Intent(this, LocalActivityManagerStubActivity.class);
+ final Intent intent = new Intent(this, LocalActivityManagerCtsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mLocalActivityManager.startActivity(id, intent);
- LocalActivityManagerStubActivity.sIsOnPauseCalled = false;
+ LocalActivityManagerCtsActivity.sIsOnPauseCalled = false;
mLocalActivityManager.dispatchPause(false);
- if (!LocalActivityManagerStubActivity.sIsOnPauseCalled) {
+ if (!LocalActivityManagerCtsActivity.sIsOnPauseCalled) {
fail();
return;
}
@@ -190,12 +190,12 @@
private void testDispatchPauseTrue() {
final String id = "id_dispatch_pause";
- final Intent intent = new Intent(this, LocalActivityManagerStubActivity.class);
+ final Intent intent = new Intent(this, LocalActivityManagerCtsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mLocalActivityManager.startActivity(id, intent);
- LocalActivityManagerStubActivity.sIsOnPauseCalled = false;
+ LocalActivityManagerCtsActivity.sIsOnPauseCalled = false;
mLocalActivityManager.dispatchPause(true);
- if (!LocalActivityManagerStubActivity.sIsOnPauseCalled) {
+ if (!LocalActivityManagerCtsActivity.sIsOnPauseCalled) {
fail();
return;
}
@@ -204,7 +204,7 @@
private void testDispatchStop() {
final String id = "id_dispatch_stop";
- final Intent intent = new Intent(this, LocalActivityManagerStubActivity.class);
+ final Intent intent = new Intent(this, LocalActivityManagerCtsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mLocalActivityManager.startActivity(id, intent);
if (mLocalActivityManager.getCurrentActivity() == null) {
@@ -212,10 +212,10 @@
return;
}
- LocalActivityManagerStubActivity.sIsOnStopCalled = false;
+ LocalActivityManagerCtsActivity.sIsOnStopCalled = false;
mLocalActivityManager.dispatchStop();
- if (!LocalActivityManagerStubActivity.sIsOnStopCalled) {
+ if (!LocalActivityManagerCtsActivity.sIsOnStopCalled) {
fail();
return;
}
@@ -226,7 +226,7 @@
final Bundle EXPECTED = new Bundle();
final String id = "id";
- final Intent intent = new Intent(this, LocalActivityManagerStubActivity.class);
+ final Intent intent = new Intent(this, LocalActivityManagerCtsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mLocalActivityManager.startActivity("_id" + System.currentTimeMillis(), intent);
final Bundle bundle = mLocalActivityManager.saveInstanceState();
@@ -261,7 +261,7 @@
}
private void testStartActivity() {
- final Intent intent = new Intent(this, LocalActivityManagerStubActivity.class);
+ final Intent intent = new Intent(this, LocalActivityManagerCtsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
final String id = "_id_resume_test";
final Window w = mLocalActivityManager.startActivity(id, intent);
@@ -315,13 +315,13 @@
}
private void testDispatchResume() {
- final Intent intent = new Intent(this, LocalActivityManagerStubActivity.class);
+ final Intent intent = new Intent(this, LocalActivityManagerCtsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mLocalActivityManager.startActivity("_id_resume_test", intent);
mLocalActivityManager.dispatchStop();
- LocalActivityManagerStubActivity.sIsOnResumeCalled = false;
+ LocalActivityManagerCtsActivity.sIsOnResumeCalled = false;
mLocalActivityManager.dispatchResume();
- if (LocalActivityManagerStubActivity.sIsOnResumeCalled) {
+ if (LocalActivityManagerCtsActivity.sIsOnResumeCalled) {
pass();
} else {
fail();
diff --git a/tests/src/android/app/cts/LocalDeniedService.java b/tests/tests/app/src/android/app/cts/LocalDeniedService.java
similarity index 100%
rename from tests/src/android/app/cts/LocalDeniedService.java
rename to tests/tests/app/src/android/app/cts/LocalDeniedService.java
diff --git a/tests/src/android/app/cts/LocalDialog.java b/tests/tests/app/src/android/app/cts/LocalDialog.java
similarity index 100%
rename from tests/src/android/app/cts/LocalDialog.java
rename to tests/tests/app/src/android/app/cts/LocalDialog.java
diff --git a/tests/src/android/app/cts/LocalGrantedService.java b/tests/tests/app/src/android/app/cts/LocalGrantedService.java
similarity index 100%
rename from tests/src/android/app/cts/LocalGrantedService.java
rename to tests/tests/app/src/android/app/cts/LocalGrantedService.java
diff --git a/tests/src/android/app/cts/LocalScreen.java b/tests/tests/app/src/android/app/cts/LocalScreen.java
similarity index 100%
rename from tests/src/android/app/cts/LocalScreen.java
rename to tests/tests/app/src/android/app/cts/LocalScreen.java
diff --git a/tests/src/android/app/cts/LocalService.java b/tests/tests/app/src/android/app/cts/LocalService.java
similarity index 100%
rename from tests/src/android/app/cts/LocalService.java
rename to tests/tests/app/src/android/app/cts/LocalService.java
diff --git a/tests/src/android/app/cts/MockActivity.java b/tests/tests/app/src/android/app/cts/MockActivity.java
similarity index 100%
rename from tests/src/android/app/cts/MockActivity.java
rename to tests/tests/app/src/android/app/cts/MockActivity.java
diff --git a/tests/src/android/app/cts/MockAlarmReceiver.java b/tests/tests/app/src/android/app/cts/MockAlarmReceiver.java
similarity index 100%
rename from tests/src/android/app/cts/MockAlarmReceiver.java
rename to tests/tests/app/src/android/app/cts/MockAlarmReceiver.java
diff --git a/tests/src/android/app/cts/MockApplication.java b/tests/tests/app/src/android/app/cts/MockApplication.java
similarity index 100%
rename from tests/src/android/app/cts/MockApplication.java
rename to tests/tests/app/src/android/app/cts/MockApplication.java
diff --git a/tests/src/android/app/cts/MockApplicationActivity.java b/tests/tests/app/src/android/app/cts/MockApplicationActivity.java
similarity index 100%
rename from tests/src/android/app/cts/MockApplicationActivity.java
rename to tests/tests/app/src/android/app/cts/MockApplicationActivity.java
diff --git a/tests/src/android/app/cts/MockReceiver.java b/tests/tests/app/src/android/app/cts/MockReceiver.java
similarity index 100%
rename from tests/src/android/app/cts/MockReceiver.java
rename to tests/tests/app/src/android/app/cts/MockReceiver.java
diff --git a/tests/src/android/app/cts/MockService.java b/tests/tests/app/src/android/app/cts/MockService.java
similarity index 100%
rename from tests/src/android/app/cts/MockService.java
rename to tests/tests/app/src/android/app/cts/MockService.java
diff --git a/tests/src/android/app/cts/MockTabActivity.java b/tests/tests/app/src/android/app/cts/MockTabActivity.java
similarity index 95%
rename from tests/src/android/app/cts/MockTabActivity.java
rename to tests/tests/app/src/android/app/cts/MockTabActivity.java
index aca19f5..ebbeb7b 100644
--- a/tests/src/android/app/cts/MockTabActivity.java
+++ b/tests/tests/app/src/android/app/cts/MockTabActivity.java
@@ -46,7 +46,7 @@
.setContent(new Intent(this, MockActivity.class)));
tabHost.addTab(tabHost.newTabSpec(TAB3).setIndicator(TAB3).setContent(
- new Intent(this, AppStubActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
+ new Intent(this, AppCtsActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
}
diff --git a/tests/tests/app/src/android/app/cts/NotificationManagerTest.java b/tests/tests/app/src/android/app/cts/NotificationManagerTest.java
index 4add582..94b410f 100644
--- a/tests/tests/app/src/android/app/cts/NotificationManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/NotificationManagerTest.java
@@ -24,7 +24,7 @@
import android.provider.Telephony.Threads;
import android.test.AndroidTestCase;
-import com.android.cts.stub.R;
+import com.android.cts.app.R;
public class NotificationManagerTest extends AndroidTestCase {
diff --git a/tests/src/android/app/cts/OrientationTestUtils.java b/tests/tests/app/src/android/app/cts/OrientationTestUtils.java
similarity index 100%
rename from tests/src/android/app/cts/OrientationTestUtils.java
rename to tests/tests/app/src/android/app/cts/OrientationTestUtils.java
diff --git a/tests/src/android/app/cts/PendingIntentStubActivity.java b/tests/tests/app/src/android/app/cts/PendingIntentCtsActivity.java
similarity index 93%
rename from tests/src/android/app/cts/PendingIntentStubActivity.java
rename to tests/tests/app/src/android/app/cts/PendingIntentCtsActivity.java
index a2a3bd8..f11fe10 100644
--- a/tests/src/android/app/cts/PendingIntentStubActivity.java
+++ b/tests/tests/app/src/android/app/cts/PendingIntentCtsActivity.java
@@ -19,7 +19,7 @@
import android.app.Activity;
import android.os.Bundle;
-public class PendingIntentStubActivity extends Activity {
+public class PendingIntentCtsActivity extends Activity {
public static final int INVALIDATE = -1;
public static final int ON_CREATE = 0;
diff --git a/tests/tests/app/src/android/app/cts/PendingIntentTest.java b/tests/tests/app/src/android/app/cts/PendingIntentTest.java
index d2c1b31..fb32291 100644
--- a/tests/tests/app/src/android/app/cts/PendingIntentTest.java
+++ b/tests/tests/app/src/android/app/cts/PendingIntentTest.java
@@ -95,11 +95,11 @@
}
public void testGetActivity() throws InterruptedException, CanceledException {
- PendingIntentStubActivity.status = PendingIntentStubActivity.INVALIDATE;
+ PendingIntentCtsActivity.status = PendingIntentCtsActivity.INVALIDATE;
mPendingIntent = null;
mIntent = new Intent();
- mIntent.setClass(mContext, PendingIntentStubActivity.class);
+ mIntent.setClass(mContext, PendingIntentCtsActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mPendingIntent = PendingIntent.getActivity(mContext, 1, mIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
@@ -109,7 +109,7 @@
Thread.sleep(WAIT_TIME);
assertNotNull(mPendingIntent);
- assertEquals(PendingIntentStubActivity.status, PendingIntentStubActivity.ON_CREATE);
+ assertEquals(PendingIntentCtsActivity.status, PendingIntentCtsActivity.ON_CREATE);
// test getActivity return null
mPendingIntent.cancel();
diff --git a/tests/tests/app/src/android/app/cts/ProgressDialogTest.java b/tests/tests/app/src/android/app/cts/ProgressDialogTest.java
index 1d08d30..106b504 100644
--- a/tests/tests/app/src/android/app/cts/ProgressDialogTest.java
+++ b/tests/tests/app/src/android/app/cts/ProgressDialogTest.java
@@ -48,10 +48,9 @@
private Context mContext;
private Instrumentation mInstrumentation;
private MockActivity mActivity;
- private ProgressDialog mProgressDialog;
public ProgressDialogTest() {
- super("com.android.cts.stub", MockActivity.class);
+ super("com.android.cts.app", MockActivity.class);
}
@Override
@@ -62,19 +61,21 @@
mInstrumentation = getInstrumentation();
mActivity = getActivity();
mContext = mActivity;
- mProgressDialog = new ProgressDialog(mContext);
mDrawable = getActivity().getResources().getDrawable(
- com.android.cts.stub.R.drawable.yellow);
+ com.android.cts.app.R.drawable.yellow);
}
+ @UiThreadTest
public void testProgressDialog1(){
new ProgressDialog(mContext);
}
+ @UiThreadTest
public void testProgressDialog2(){
- new ProgressDialog(mContext, com.android.cts.stub.R.style.Theme_AlertDialog);
+ new ProgressDialog(mContext, com.android.cts.app.R.style.Theme_AlertDialog);
}
+ @UiThreadTest
public void testOnStartCreateStop() {
MockProgressDialog pd = new MockProgressDialog(mContext);
@@ -91,21 +92,22 @@
@UiThreadTest
public void testShow1() {
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
+ ProgressDialog.show(mContext, TITLE, MESSAGE);
}
@UiThreadTest
public void testShow2() {
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE, false);
+ ProgressDialog dialog = buildDialog();
+ dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, false);
/*
* note: the progress bar's style only supports indeterminate mode,
* so can't change indeterminate
*/
- assertTrue(mProgressDialog.isIndeterminate());
+ assertTrue(dialog.isIndeterminate());
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true);
- assertTrue(mProgressDialog.isIndeterminate());
+ dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true);
+ assertTrue(dialog.isIndeterminate());
}
public void testShow3() throws Throwable {
@@ -118,10 +120,11 @@
// cancelable is false
runTestOnUiThread(new Runnable() {
public void run() {
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, false);
+ ProgressDialog dialog = buildDialog();
+ dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, false);
- mProgressDialog.setOnCancelListener(cL);
- mProgressDialog.onBackPressed();
+ dialog.setOnCancelListener(cL);
+ dialog.onBackPressed();
}
});
mInstrumentation.waitForIdleSync();
@@ -131,11 +134,11 @@
// cancelable is true
runTestOnUiThread(new Runnable() {
public void run() {
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, true);
-
+ ProgressDialog dialog = buildDialog();
+ dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, true);
assertFalse(mCanceled);
- mProgressDialog.setOnCancelListener(cL);
- mProgressDialog.onBackPressed();
+ dialog.setOnCancelListener(cL);
+ dialog.onBackPressed();
}
});
mInstrumentation.waitForIdleSync();
@@ -153,9 +156,10 @@
// cancelable is false
runTestOnUiThread(new Runnable() {
public void run() {
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, false, cL);
+ ProgressDialog dialog = buildDialog();
+ dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, false, cL);
- mProgressDialog.onBackPressed();
+ dialog.onBackPressed();
}
});
mInstrumentation.waitForIdleSync();
@@ -165,10 +169,11 @@
// cancelable is true
runTestOnUiThread(new Runnable() {
public void run() {
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, true, cL);
+ ProgressDialog dialog = buildDialog();
+ dialog = ProgressDialog.show(mContext, TITLE, MESSAGE, true, true, cL);
assertFalse(mCanceled);
- mProgressDialog.onBackPressed();
+ dialog.onBackPressed();
}
});
mInstrumentation.waitForIdleSync();
@@ -178,180 +183,152 @@
@UiThreadTest
public void testAccessMax() {
- // mProgress is null
- mProgressDialog.setMax(2008);
- assertEquals(2008, mProgressDialog.getMax());
+ // progressDialog is null
+ ProgressDialog progressDialog = buildDialog();
+ progressDialog.setMax(2008);
+ assertEquals(2008, progressDialog.getMax());
- // mProgress is not null
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
- mProgressDialog.setMax(2009);
- assertEquals(2009, mProgressDialog.getMax());
+ // progressDialog is not null
+ progressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
+ progressDialog.setMax(2009);
+ assertEquals(2009, progressDialog.getMax());
}
@UiThreadTest
public void testAccessProgress() {
- // mProgress is null
- mProgressDialog.setProgress(11);
- assertEquals(11, mProgressDialog.getProgress());
+ // progressDialog is null
+ ProgressDialog progressDialog = buildDialog();
+ progressDialog.setProgress(11);
+ assertEquals(11, progressDialog.getProgress());
- /* mProgress is not null
+ /* progressDialog is not null
* note: the progress bar's style only supports indeterminate mode,
* so can't change progress
*/
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
- mProgressDialog.setProgress(12);
- assertEquals(0, mProgressDialog.getProgress());
+ progressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
+ progressDialog.setProgress(12);
+ assertEquals(0, progressDialog.getProgress());
}
@UiThreadTest
public void testAccessSecondaryProgress() {
- // mProgress is null
- mProgressDialog.setSecondaryProgress(17);
- assertEquals(17, mProgressDialog.getSecondaryProgress());
+ // dialog is null
+ ProgressDialog dialog = buildDialog();
+ dialog.setSecondaryProgress(17);
+ assertEquals(17, dialog.getSecondaryProgress());
/* mProgress is not null
* note: the progress bar's style only supports indeterminate mode,
* so can't change secondary progress
*/
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
- mProgressDialog.setSecondaryProgress(18);
- assertEquals(0, mProgressDialog.getSecondaryProgress());
+ dialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
+ dialog.setSecondaryProgress(18);
+ assertEquals(0, dialog.getSecondaryProgress());
}
@UiThreadTest
public void testSetIndeterminate() {
- // mProgress is null
- mProgressDialog.setIndeterminate(true);
- assertTrue(mProgressDialog.isIndeterminate());
- mProgressDialog.setIndeterminate(false);
- assertFalse(mProgressDialog.isIndeterminate());
+ // progress is null
+ ProgressDialog dialog = buildDialog();
+ dialog.setIndeterminate(true);
+ assertTrue(dialog.isIndeterminate());
+ dialog.setIndeterminate(false);
+ assertFalse(dialog.isIndeterminate());
/* mProgress is not null
* note: the progress bar's style only supports indeterminate mode,
* so can't change indeterminate
*/
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
- mProgressDialog.setIndeterminate(true);
- assertTrue(mProgressDialog.isIndeterminate());
- mProgressDialog.setIndeterminate(false);
- assertTrue(mProgressDialog.isIndeterminate());
+ dialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
+ dialog.setIndeterminate(true);
+ assertTrue(dialog.isIndeterminate());
+ dialog.setIndeterminate(false);
+ assertTrue(dialog.isIndeterminate());
}
+ @UiThreadTest
public void testIncrementProgressBy() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- mProgressDialog = new ProgressDialog(mContext);
- mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- mProgressDialog.show();
- mProgressDialog.setProgress(10);
- mProgress1 = mProgressDialog.getProgress();
- mProgressDialog.incrementProgressBy(60);
- mProgress2 = mProgressDialog.getProgress();
- mProgressDialog.cancel();
- }
- });
- mInstrumentation.waitForIdleSync();
+ ProgressDialog dialog = new ProgressDialog(mContext);
+ dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
+ dialog.show();
+ dialog.setProgress(10);
+ mProgress1 = dialog.getProgress();
+ dialog.incrementProgressBy(60);
+ mProgress2 = dialog.getProgress();
+ dialog.cancel();
assertEquals(10, mProgress1);
assertEquals(70, mProgress2);
}
+ @UiThreadTest
public void testIncrementSecondaryProgressBy() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- mProgressDialog = new ProgressDialog(mContext);
- mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- mProgressDialog.show();
- mProgressDialog.setSecondaryProgress(10);
- mProgress1 = mProgressDialog.getSecondaryProgress();
- mProgressDialog.incrementSecondaryProgressBy(60);
- mProgress2 = mProgressDialog.getSecondaryProgress();
- }
- });
- mInstrumentation.waitForIdleSync();
+ ProgressDialog dialog = new ProgressDialog(mContext);
+ dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
+ dialog.show();
+ dialog.setSecondaryProgress(10);
+ mProgress1 = dialog.getSecondaryProgress();
+ dialog.incrementSecondaryProgressBy(60);
+ mProgress2 = dialog.getSecondaryProgress();
assertEquals(10, mProgress1);
assertEquals(70, mProgress2);
}
+ @UiThreadTest
public void testSetProgressDrawable() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
- final Window w = mProgressDialog.getWindow();
- final ProgressBar progressBar = (ProgressBar) w.findViewById(android.R.id.progress);
+ ProgressDialog dialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
+ Window w = dialog.getWindow();
+ ProgressBar progressBar = (ProgressBar) w.findViewById(android.R.id.progress);
- mProgressDialog.setProgressDrawable(mDrawable);
- mActualDrawable = progressBar.getProgressDrawable();
+ dialog.setProgressDrawable(mDrawable);
+ mActualDrawable = progressBar.getProgressDrawable();
- mProgressDialog.setProgressDrawable(null);
- mActualDrawableNull = progressBar.getProgressDrawable();
- }
- });
- mInstrumentation.waitForIdleSync();
+ dialog.setProgressDrawable(null);
+ mActualDrawableNull = progressBar.getProgressDrawable();
assertEquals(mDrawable, mActualDrawable);
assertEquals(null, mActualDrawableNull);
}
+ @UiThreadTest
public void testSetIndeterminateDrawable() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
- final Window w = mProgressDialog.getWindow();
- mProgressBar = (ProgressBar) w.findViewById(android.R.id.progress);
+ ProgressDialog dialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
+ Window w = dialog.getWindow();
+ mProgressBar = (ProgressBar) w.findViewById(android.R.id.progress);
- mProgressDialog.setIndeterminateDrawable(mDrawable);
- mActualDrawable = mProgressBar.getIndeterminateDrawable();
- assertEquals(mDrawable, mActualDrawable);
+ dialog.setIndeterminateDrawable(mDrawable);
+ mActualDrawable = mProgressBar.getIndeterminateDrawable();
+ assertEquals(mDrawable, mActualDrawable);
- mProgressDialog.setIndeterminateDrawable(null);
- mActualDrawableNull = mProgressBar.getIndeterminateDrawable();
- assertEquals(null, mActualDrawableNull);
- }
- });
- mInstrumentation.waitForIdleSync();
+ dialog.setIndeterminateDrawable(null);
+ mActualDrawableNull = mProgressBar.getIndeterminateDrawable();
+ assertEquals(null, mActualDrawableNull);
}
+ @UiThreadTest
public void testSetMessage() throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- // mProgress is null
- mProgressDialog = new ProgressDialog(mContext);
- mProgressDialog.setMessage(MESSAGE);
- mProgressDialog.show();
- }
- });
- mInstrumentation.waitForIdleSync();
-
- runTestOnUiThread(new Runnable() {
- public void run() {
- // mProgress is not null
- mProgressDialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
- mProgressDialog.setMessage("Bruce Li");
- }
- });
- mInstrumentation.waitForIdleSync();
+ ProgressDialog dialog = new ProgressDialog(mContext);
+ dialog = new ProgressDialog(mContext);
+ dialog.setMessage(MESSAGE);
+ dialog.show();
+ // dialog is not null
+ dialog = ProgressDialog.show(mContext, TITLE, MESSAGE);
+ dialog.setMessage("Chuck Norris");
}
+ @UiThreadTest
public void testSetProgressStyle() throws Throwable {
- setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
-
- setProgressStyle(ProgressDialog.STYLE_SPINNER);
- setProgressStyle(100);
+ ProgressDialog dialog = new ProgressDialog(mContext);
+ setProgressStyle(dialog, ProgressDialog.STYLE_HORIZONTAL);
+ setProgressStyle(dialog, ProgressDialog.STYLE_SPINNER);
+ setProgressStyle(dialog, 100);
}
- private void setProgressStyle(final int style) throws Throwable {
- runTestOnUiThread(new Runnable() {
- public void run() {
- mProgressDialog = new ProgressDialog(mContext);
- mProgressDialog.setProgressStyle(style);
-
- mProgressDialog.show();
- mProgressDialog.setProgress(10);
- mProgressDialog.setMax(100);
- }
- });
- mInstrumentation.waitForIdleSync();
+ private void setProgressStyle(ProgressDialog dialog, int style) {
+ dialog.setProgressStyle(style);
+ dialog.show();
+ dialog.setProgress(10);
+ dialog.setMax(100);
}
private static class MockProgressDialog extends ProgressDialog {
@@ -381,4 +358,8 @@
mIsOnStopCalled = true;
}
}
+
+ private ProgressDialog buildDialog() {
+ return new ProgressDialog(mContext);
+ }
}
diff --git a/tests/src/android/app/cts/SearchManagerStubActivity.java b/tests/tests/app/src/android/app/cts/SearchManagerCtsActivity.java
similarity index 97%
rename from tests/src/android/app/cts/SearchManagerStubActivity.java
rename to tests/tests/app/src/android/app/cts/SearchManagerCtsActivity.java
index 6385fef..7198e8d 100644
--- a/tests/src/android/app/cts/SearchManagerStubActivity.java
+++ b/tests/tests/app/src/android/app/cts/SearchManagerCtsActivity.java
@@ -25,9 +25,9 @@
import android.os.Message;
import android.util.Log;
-public class SearchManagerStubActivity extends Activity {
+public class SearchManagerCtsActivity extends Activity {
- private static final String TAG = "SearchManagerStubActivity";
+ private static final String TAG = "SearchManagerCtsActivity";
public static final String TEST_STOP_SEARCH = "stopSearch";
public static final String TEST_ON_DISMISSLISTENER = "setOnDismissListener";
diff --git a/tests/tests/app/src/android/app/cts/SearchManagerTest.java b/tests/tests/app/src/android/app/cts/SearchManagerTest.java
index 8e465e8..ef7a0e0 100644
--- a/tests/tests/app/src/android/app/cts/SearchManagerTest.java
+++ b/tests/tests/app/src/android/app/cts/SearchManagerTest.java
@@ -24,25 +24,25 @@
Intent intent = new Intent();
intent.setAction(action);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.setClass(getInstrumentation().getTargetContext(), SearchManagerStubActivity.class);
+ intent.setClass(getInstrumentation().getTargetContext(), SearchManagerCtsActivity.class);
getInstrumentation().getTargetContext().startActivity(intent);
}
public void testStopSearch() throws InterruptedException {
- SearchManagerStubActivity.setCTSResult(this);
- setupActivity(SearchManagerStubActivity.TEST_STOP_SEARCH);
+ SearchManagerCtsActivity.setCTSResult(this);
+ setupActivity(SearchManagerCtsActivity.TEST_STOP_SEARCH);
waitForResult();
}
public void testSetOnDismissListener() throws InterruptedException {
- SearchManagerStubActivity.setCTSResult(this);
- setupActivity(SearchManagerStubActivity.TEST_ON_DISMISSLISTENER);
+ SearchManagerCtsActivity.setCTSResult(this);
+ setupActivity(SearchManagerCtsActivity.TEST_ON_DISMISSLISTENER);
waitForResult();
}
public void testSetOnCancelListener() throws InterruptedException {
- SearchManagerStubActivity.setCTSResult(this);
- setupActivity(SearchManagerStubActivity.TEST_ON_CANCELLISTENER);
+ SearchManagerCtsActivity.setCTSResult(this);
+ setupActivity(SearchManagerCtsActivity.TEST_ON_CANCELLISTENER);
waitForResult();
}
}
diff --git a/tests/src/android/app/cts/StubRemoteService.java b/tests/tests/app/src/android/app/cts/StubRemoteService.java
similarity index 100%
rename from tests/src/android/app/cts/StubRemoteService.java
rename to tests/tests/app/src/android/app/cts/StubRemoteService.java
diff --git a/tests/tests/app/src/android/app/cts/SystemFeaturesTest.java b/tests/tests/app/src/android/app/cts/SystemFeaturesTest.java
index e3dca19..165e67b 100644
--- a/tests/tests/app/src/android/app/cts/SystemFeaturesTest.java
+++ b/tests/tests/app/src/android/app/cts/SystemFeaturesTest.java
@@ -136,9 +136,15 @@
}
if (frontCameraId > -1) {
- assertAvailable(PackageManager.FEATURE_CAMERA_FRONT);
+ assertTrue("Device has front-facing camera but does not report either " +
+ "the FEATURE_CAMERA_FRONT or FEATURE_CAMERA_EXTERNAL feature",
+ mPackageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT) ||
+ mPackageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_EXTERNAL));
} else {
- assertNotAvailable(PackageManager.FEATURE_CAMERA_FRONT);
+ assertFalse("Device does not have front-facing camera but reports either " +
+ "the FEATURE_CAMERA_FRONT or FEATURE_CAMERA_EXTERNAL feature",
+ mPackageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT) ||
+ mPackageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_EXTERNAL));
}
}
diff --git a/tests/tests/app/src/android/app/cts/TabActivityTest.java b/tests/tests/app/src/android/app/cts/TabActivityTest.java
index 04741b7..403b393 100644
--- a/tests/tests/app/src/android/app/cts/TabActivityTest.java
+++ b/tests/tests/app/src/android/app/cts/TabActivityTest.java
@@ -25,6 +25,7 @@
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.widget.TabHost;
public class TabActivityTest extends InstrumentationTestCase {
@@ -53,10 +54,14 @@
}
public void testTabActivity() throws Throwable {
- // Test constructor
- new TabActivity();
-
- final String packageName = "com.android.cts.stub";
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ // Test constructor
+ new TabActivity();
+ }
+ });
+ mInstrumentation.waitForIdleSync();
+ final String packageName = "com.android.cts.app";
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(packageName, MockTabActivity.class.getName());
@@ -77,6 +82,7 @@
assertNotNull(tabHost.getTabWidget());
}
+ @UiThreadTest
public void testChildTitleCallback() throws Exception {
final Context context = mInstrumentation.getTargetContext();
final Intent intent = new Intent(context, MockTabActivity.class);
diff --git a/tests/src/android/app/cts/TestDialog.java b/tests/tests/app/src/android/app/cts/TestDialog.java
similarity index 100%
rename from tests/src/android/app/cts/TestDialog.java
rename to tests/tests/app/src/android/app/cts/TestDialog.java
diff --git a/tests/src/android/app/cts/TestedActivity.java b/tests/tests/app/src/android/app/cts/TestedActivity.java
similarity index 100%
rename from tests/src/android/app/cts/TestedActivity.java
rename to tests/tests/app/src/android/app/cts/TestedActivity.java
diff --git a/tests/src/android/app/cts/TestedScreen.java b/tests/tests/app/src/android/app/cts/TestedScreen.java
similarity index 100%
rename from tests/src/android/app/cts/TestedScreen.java
rename to tests/tests/app/src/android/app/cts/TestedScreen.java
diff --git a/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java b/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java
index e03003b..2fe2d69 100644
--- a/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java
+++ b/tests/tests/app/src/android/app/cts/TimePickerDialogTest.java
@@ -22,12 +22,13 @@
import android.content.Context;
import android.os.Bundle;
import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
import android.widget.TimePicker;
/**
* Test {@link TimePickerDialog}.
*/
-public class TimePickerDialogTest extends ActivityInstrumentationTestCase2<DialogStubActivity> {
+public class TimePickerDialogTest extends ActivityInstrumentationTestCase2<DialogCtsActivity> {
private static final String HOUR = "hour";
private static final String MINUTE = "minute";
private static final String IS_24_HOUR = "is24hour";
@@ -41,11 +42,10 @@
private OnTimeSetListener mOnTimeSetListener;
private Context mContext;
- private DialogStubActivity mActivity;
- private TimePickerDialog mTimePickerDialog;
+ private DialogCtsActivity mActivity;
public TimePickerDialogTest() {
- super("com.android.cts.stub", DialogStubActivity.class);
+ super("com.android.cts.app", DialogCtsActivity.class);
}
@Override
@@ -59,13 +59,12 @@
mCallbackMinute = minute;
}
};
- mTimePickerDialog = new TimePickerDialog( mContext, mOnTimeSetListener, TARGET_HOUR,
- TARGET_MINUTE, true);
}
- public void testSaveInstanceState(){
- TimePickerDialog tD = new TimePickerDialog( mContext, mOnTimeSetListener, TARGET_HOUR,
- TARGET_MINUTE, true);
+ @UiThreadTest
+ public void testSaveInstanceState() {
+ TimePickerDialog tD = new TimePickerDialog(
+ mContext, mOnTimeSetListener, TARGET_HOUR, TARGET_MINUTE, true);
Bundle b = tD.onSaveInstanceState();
@@ -74,8 +73,9 @@
assertTrue(b.getBoolean(IS_24_HOUR));
int minute = 13;
- tD = new TimePickerDialog( mContext, com.android.cts.stub.R.style.Theme_AlertDialog,
- mOnTimeSetListener, TARGET_HOUR, minute, false);
+ tD = new TimePickerDialog(
+ mContext, com.android.cts.app.R.style.Theme_AlertDialog,
+ mOnTimeSetListener, TARGET_HOUR, minute, false);
b = tD.onSaveInstanceState();
@@ -84,8 +84,10 @@
assertFalse(b.getBoolean(IS_24_HOUR));
}
- public void testOnClick(){
- mTimePickerDialog.onClick(null, TimePickerDialog.BUTTON_POSITIVE);
+ @UiThreadTest
+ public void testOnClick() {
+ TimePickerDialog timePickerDialog = buildDialog();
+ timePickerDialog.onClick(null, TimePickerDialog.BUTTON_POSITIVE);
assertEquals(TARGET_HOUR, mCallbackHour);
assertEquals(TARGET_MINUTE, mCallbackMinute);
@@ -93,7 +95,7 @@
public void testOnTimeChanged() throws Throwable {
final int minute = 34;
- startDialogActivity(DialogStubActivity.TEST_TIMEPICKERDIALOG);
+ startDialogActivity(DialogCtsActivity.TEST_TIMEPICKERDIALOG);
final TimePickerDialog d = (TimePickerDialog) mActivity.getDialog();
runTestOnUiThread(new Runnable() {
@@ -105,28 +107,32 @@
}
- public void testUpdateTime(){
+ @UiThreadTest
+ public void testUpdateTime() {
+ TimePickerDialog timePickerDialog = buildDialog();
int minute = 18;
- mTimePickerDialog.updateTime(TARGET_HOUR, minute);
+ timePickerDialog.updateTime(TARGET_HOUR, minute);
- //here call onSaveInstanceState is to check the data put by updateTime
- Bundle b = mTimePickerDialog.onSaveInstanceState();
+ // here call onSaveInstanceState is to check the data put by updateTime
+ Bundle b = timePickerDialog.onSaveInstanceState();
assertEquals(TARGET_HOUR, b.getInt(HOUR));
assertEquals(minute, b.getInt(MINUTE));
}
- public void testOnRestoreInstanceState(){
+ @UiThreadTest
+ public void testOnRestoreInstanceState() {
int minute = 27;
Bundle b1 = new Bundle();
b1.putInt(HOUR, TARGET_HOUR);
b1.putInt(MINUTE, minute);
b1.putBoolean(IS_24_HOUR, false);
- mTimePickerDialog.onRestoreInstanceState(b1);
+ TimePickerDialog timePickerDialog = buildDialog();
+ timePickerDialog.onRestoreInstanceState(b1);
//here call onSaveInstanceState is to check the data put by onRestoreInstanceState
- Bundle b2 = mTimePickerDialog.onSaveInstanceState();
+ Bundle b2 = timePickerDialog.onSaveInstanceState();
assertEquals(TARGET_HOUR, b2.getInt(HOUR));
assertEquals(minute, b2.getInt(MINUTE));
@@ -134,6 +140,11 @@
}
private void startDialogActivity(int dialogNumber) {
- mActivity = DialogStubActivity.startDialogActivity(this, dialogNumber);
+ mActivity = DialogCtsActivity.startDialogActivity(this, dialogNumber);
+ }
+
+ private TimePickerDialog buildDialog() {
+ return new TimePickerDialog(
+ mContext, mOnTimeSetListener, TARGET_HOUR, TARGET_MINUTE, true);
}
}
diff --git a/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java b/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
index 654fb0d..5e72a78 100644
--- a/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
+++ b/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
@@ -40,7 +40,6 @@
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
-import android.content.pm.UserInfo;
import android.cts.appwidget.R;
import android.graphics.drawable.Drawable;
import android.net.Uri;
@@ -136,6 +135,7 @@
public void testBindAppWidget() throws Exception {
// Create a host and start listening.
AppWidgetHost host = new AppWidgetHost(getInstrumentation().getTargetContext(), 0);
+ host.deleteHost();
host.startListening();
// Allocate an app widget id to bind.
@@ -150,7 +150,7 @@
assertFalse(widgetBound);
// Well, app do not have this permission unless explicitly granted
- // by the user. Now we will pretent for the user and grant it.
+ // by the user. Now we will pretend for the user and grant it.
grantBindAppWidgetPermission();
try {
@@ -163,36 +163,28 @@
host.deleteAppWidgetId(appWidgetId);
} finally {
// Clean up.
+ host.deleteAppWidgetId(appWidgetId);
host.deleteHost();
revokeBindAppWidgetPermission();
}
}
public void testAppWidgetProviderCallbacks() throws Exception {
- final AtomicInteger disabledCallCounter = new AtomicInteger();
+ AtomicInteger invocationCounter = new AtomicInteger();
// Set a mock to intercept provider callbacks.
- AppWidgetProviderCallbacks callbacks = mock(AppWidgetProviderCallbacks.class);
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- synchronized (mLock) {
- disabledCallCounter.incrementAndGet();
- mLock.notifyAll();
- }
- return null;
- }
- }).when(callbacks).onDeleted(any(Context.class), any(int[].class));
+ AppWidgetProviderCallbacks callbacks = createAppWidgetProviderCallbacks(invocationCounter);
FirstAppWidgetProvider.setCallbacks(callbacks);
- final int firstAppWidgetId;
- final int secondAppWidgetId;
+ int firstAppWidgetId = 0;
+ int secondAppWidgetId = 0;
final Bundle firstOptions;
final Bundle secondOptions;
// Create a host and start listening.
AppWidgetHost host = spy(new AppWidgetHost(getInstrumentation().getTargetContext(), 0));
+ host.deleteHost();
host.startListening();
// We want to bind a widget.
@@ -208,6 +200,9 @@
getAppWidgetManager().bindAppWidgetIdIfAllowed(firstAppWidgetId,
provider.getProfile(), provider.provider, null);
+ // Wait for onEnabled and onUpdate
+ waitForCallCount(invocationCounter, 2);
+
// Update the first widget options.
firstOptions = new Bundle();
firstOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 1);
@@ -216,6 +211,9 @@
firstOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, 4);
getAppWidgetManager().updateAppWidgetOptions(firstAppWidgetId, firstOptions);
+ // Wait for onAppWidgetOptionsChanged
+ waitForCallCount(invocationCounter, 3);
+
// Allocate the second app widget id to bind.
secondAppWidgetId = host.allocateAppWidgetId();
@@ -223,6 +221,9 @@
getAppWidgetManager().bindAppWidgetIdIfAllowed(secondAppWidgetId,
provider.getProfile(), provider.provider, null);
+ // Wait for onUpdate
+ waitForCallCount(invocationCounter, 4);
+
// Update the second widget options.
secondOptions = new Bundle();
secondOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 5);
@@ -231,13 +232,20 @@
secondOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, 8);
getAppWidgetManager().updateAppWidgetOptions(secondAppWidgetId, secondOptions);
+ // Wait for onAppWidgetOptionsChanged
+ waitForCallCount(invocationCounter, 5);
+
// Delete the first widget.
host.deleteAppWidgetId(firstAppWidgetId);
+ // Wait for onDeleted
+ waitForCallCount(invocationCounter, 6);
+
// Delete the second widget.
host.deleteAppWidgetId(secondAppWidgetId);
- waitForCallCount(disabledCallCounter, 1);
+ // Wait for onDeleted and onDisabled
+ waitForCallCount(invocationCounter, 8);
// Make sure the provider callbacks are correct.
InOrder inOrder = inOrder(callbacks);
@@ -260,38 +268,34 @@
inOrder.verify(callbacks).onDisabled(any(Context.class));
} finally {
// Clean up.
+ host.deleteAppWidgetId(firstAppWidgetId);
+ host.deleteAppWidgetId(secondAppWidgetId);
+ host.deleteHost();
FirstAppWidgetProvider.setCallbacks(null);
revokeBindAppWidgetPermission();
}
}
public void testTwoAppWidgetProviderCallbacks() throws Exception {
- final AtomicInteger disabledCallCounter = new AtomicInteger();
+ AtomicInteger invocationCounter = new AtomicInteger();
// Set a mock to intercept first provider callbacks.
- AppWidgetProviderCallbacks firstCallbacks = mock(AppWidgetProviderCallbacks.class);
+ AppWidgetProviderCallbacks firstCallbacks = createAppWidgetProviderCallbacks(
+ invocationCounter);
FirstAppWidgetProvider.setCallbacks(firstCallbacks);
// Set a mock to intercept second provider callbacks.
- AppWidgetProviderCallbacks secondCallbacks = mock(AppWidgetProviderCallbacks.class);
- doAnswer(new Answer<Void>() {
- @Override
- public Void answer(InvocationOnMock invocation) throws Throwable {
- synchronized (mLock) {
- disabledCallCounter.incrementAndGet();
- mLock.notifyAll();
- }
- return null;
- }
- }).when(firstCallbacks).onDisabled(any(Context.class));
+ AppWidgetProviderCallbacks secondCallbacks = createAppWidgetProviderCallbacks(
+ invocationCounter);
SecondAppWidgetProvider.setCallbacks(secondCallbacks);
- final int firstAppWidgetId;
- final int secondAppWidgetId;
+ int firstAppWidgetId = 0;
+ int secondAppWidgetId = 0;
// Create a host and start listening.
AppWidgetHost host = spy(new AppWidgetHost(
getInstrumentation().getTargetContext(), 0));
+ host.deleteHost();
host.startListening();
// We want to bind widgets.
@@ -310,6 +314,9 @@
getAppWidgetManager().bindAppWidgetIdIfAllowed(firstAppWidgetId,
firstProvider.getProfile(), firstProvider.provider, null);
+ // Wait for onEnabled and onUpdate
+ waitForCallCount(invocationCounter, 2);
+
// Grab the second provider we defined to be bound.
AppWidgetProviderInfo secondProvider = getSecondAppWidgetProviderInfo();
@@ -317,14 +324,20 @@
getAppWidgetManager().bindAppWidgetIdIfAllowed(secondAppWidgetId,
secondProvider.getProfile(), secondProvider.provider, null);
+ // Wait for onEnabled and onUpdate
+ waitForCallCount(invocationCounter, 4);
+
// Delete the first widget.
host.deleteAppWidgetId(firstAppWidgetId);
+ // Wait for onDeleted and onDisabled
+ waitForCallCount(invocationCounter, 6);
+
// Delete the second widget.
host.deleteAppWidgetId(secondAppWidgetId);
- // Wait for all callbacks to settle.
- waitForCallCount(disabledCallCounter, 1);
+ // Wait for onDeleted and onDisabled
+ waitForCallCount(invocationCounter, 8);
// Make sure the first provider callbacks are correct.
InOrder firstInOrder = inOrder(firstCallbacks);
@@ -345,6 +358,9 @@
secondInOrder.verify(secondCallbacks).onDisabled(any(Context.class));
} finally {
// Clean up.
+ host.deleteAppWidgetId(firstAppWidgetId);
+ host.deleteAppWidgetId(secondAppWidgetId);
+ host.deleteHost();
FirstAppWidgetProvider.setCallbacks(null);
SecondAppWidgetProvider.setCallbacks(null);
revokeBindAppWidgetPermission();
@@ -358,8 +374,12 @@
// Create a host and start listening.
AppWidgetHost host = new AppWidgetHost(
getInstrumentation().getTargetContext(), 0);
+ host.deleteHost();
host.startListening();
+ int firstAppWidgetId = 0;
+ int secondAppWidgetId = 0;
+
try {
// Grab the provider we defined to be bound.
AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
@@ -369,14 +389,14 @@
assertTrue(widgetsIds.length == 0);
// Allocate the first widget id to bind.
- final int firstAppWidgetId = host.allocateAppWidgetId();
+ firstAppWidgetId = host.allocateAppWidgetId();
// Bind the first widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(firstAppWidgetId,
provider.getProfile(), provider.provider, null);
// Allocate the second widget id to bind.
- final int secondAppWidgetId = host.allocateAppWidgetId();
+ secondAppWidgetId = host.allocateAppWidgetId();
// Bind the second widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(secondAppWidgetId,
@@ -387,6 +407,8 @@
assertTrue(Arrays.equals(widgetsIds, new int[]{firstAppWidgetId, secondAppWidgetId}));
} finally {
// Clean up.
+ host.deleteAppWidgetId(firstAppWidgetId);
+ host.deleteAppWidgetId(secondAppWidgetId);
host.deleteHost();
revokeBindAppWidgetPermission();
}
@@ -399,11 +421,14 @@
// Create a host and start listening.
AppWidgetHost host = new AppWidgetHost(
getInstrumentation().getTargetContext(), 0);
+ host.deleteHost();
host.startListening();
+ int appWidgetId = 0;
+
try {
// Allocate an widget id to bind.
- final int appWidgetId = host.allocateAppWidgetId();
+ appWidgetId = host.allocateAppWidgetId();
// The widget is not bound, so no info.
AppWidgetProviderInfo foundProvider = getAppWidgetManager()
@@ -435,6 +460,7 @@
assertNotNull(previewImage);
} finally {
// Clean up.
+ host.deleteAppWidgetId(appWidgetId);
host.deleteHost();
revokeBindAppWidgetPermission();
}
@@ -447,14 +473,17 @@
// Create a host and start listening.
AppWidgetHost host = new AppWidgetHost(
getInstrumentation().getTargetContext(), 0);
+ host.deleteHost();
host.startListening();
+ int appWidgetId = 0;
+
try {
// Grab the provider we defined to be bound.
AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
// Allocate an widget id to bind.
- final int appWidgetId = host.allocateAppWidgetId();
+ appWidgetId = host.allocateAppWidgetId();
// Initially we have no options.
Bundle foundOptions = getAppWidgetManager().getAppWidgetOptions(appWidgetId);
@@ -476,6 +505,7 @@
assertTrue(equalOptions(setOptions, foundOptions));
} finally {
// Clean up.
+ host.deleteAppWidgetId(appWidgetId);
host.deleteHost();
revokeBindAppWidgetPermission();
}
@@ -488,11 +518,14 @@
// Create a host and start listening.
AppWidgetHost host = new AppWidgetHost(
getInstrumentation().getTargetContext(), 0);
+ host.deleteHost();
host.startListening();
+ int appWidgetId = 0;
+
try {
// Allocate an widget id to bind.
- final int appWidgetId = host.allocateAppWidgetId();
+ appWidgetId = host.allocateAppWidgetId();
// Grab the provider we defined to be bound.
AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
@@ -513,6 +546,8 @@
assertTrue(widgetIds.length == 0);
} finally {
// Clean up.
+ host.deleteAppWidgetId(appWidgetId);
+ host.deleteHost();
revokeBindAppWidgetPermission();
}
}
@@ -524,26 +559,31 @@
// Create the first host and start listening.
AppWidgetHost firstHost = new AppWidgetHost(
getInstrumentation().getTargetContext(), 0);
+ firstHost.deleteHost();
firstHost.startListening();
// Create the second host and start listening.
AppWidgetHost secondHost = new AppWidgetHost(
getInstrumentation().getTargetContext(), 1);
+ secondHost.deleteHost();
secondHost.startListening();
+ int firstAppWidgetId = 0;
+ int secondAppWidgetId = 0;
+
try {
// Grab the provider we defined to be bound.
AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
// Allocate the first widget id to bind.
- final int firstAppWidgetId = firstHost.allocateAppWidgetId();
+ firstAppWidgetId = firstHost.allocateAppWidgetId();
// Bind the first app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(firstAppWidgetId,
provider.getProfile(), provider.provider, null);
// Allocate the second widget id to bind.
- final int secondAppWidgetId = secondHost.allocateAppWidgetId();
+ secondAppWidgetId = secondHost.allocateAppWidgetId();
// Bind the second app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(secondAppWidgetId,
@@ -561,6 +601,9 @@
assertTrue(widgetIds.length == 0);
} finally {
// Clean up.
+ firstHost.deleteAppWidgetId(firstAppWidgetId);
+ secondHost.deleteAppWidgetId(secondAppWidgetId);
+ AppWidgetHost.deleteAllHosts();
revokeBindAppWidgetPermission();
}
}
@@ -582,14 +625,17 @@
}
}
};
+ host.deleteHost();
host.startListening();
+ int appWidgetId = 0;
+
try {
// Grab the provider we defined to be bound.
AppWidgetProviderInfo firstLookupProvider = getFirstAppWidgetProviderInfo();
// Allocate a widget id to bind.
- final int appWidgetId = host.allocateAppWidgetId();
+ appWidgetId = host.allocateAppWidgetId();
// Bind the first app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(appWidgetId,
@@ -609,7 +655,7 @@
AppWidgetProviderInfo secondLookupProvider = getFirstAppWidgetProviderInfo();
assertNull(secondLookupProvider);
- // Enable the provider we disbaled.
+ // Enable the provider we disabled.
packageManager.setComponentEnabledSetting(firstLookupProvider.provider,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
@@ -618,6 +664,7 @@
waitForCallCount(onProvidersChangedCallCounter, 2);
} finally {
// Clean up.
+ host.deleteAppWidgetId(appWidgetId);
host.deleteHost();
revokeBindAppWidgetPermission();
}
@@ -638,14 +685,18 @@
return new MyAppWidgetHostView(context);
}
};
+ host.deleteHost();
host.startListening();
+ int firstAppWidgetId = 0;
+ int secondAppWidgetId = 0;
+
try {
// Grab the provider to be bound.
AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
// Allocate the first widget id to bind.
- final int firstAppWidgetId = host.allocateAppWidgetId();
+ firstAppWidgetId = host.allocateAppWidgetId();
// Bind the first app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(firstAppWidgetId,
@@ -659,7 +710,7 @@
firstHostView.setOnUpdateAppWidgetListener(firstAppHostViewListener);
// Allocate the second widget id to bind.
- final int secondAppWidgetId = host.allocateAppWidgetId();
+ secondAppWidgetId = host.allocateAppWidgetId();
// Bind the second app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(secondAppWidgetId,
@@ -702,6 +753,8 @@
provider.provider.getPackageName())));
} finally {
// Clean up.
+ host.deleteAppWidgetId(firstAppWidgetId);
+ host.deleteAppWidgetId(secondAppWidgetId);
host.deleteHost();
revokeBindAppWidgetPermission();
}
@@ -722,14 +775,17 @@
return new MyAppWidgetHostView(context);
}
};
+ host.deleteHost();
host.startListening();
+ int firstAppWidgetId = 0;
+
try {
// Grab the provider to be bound.
AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
// Allocate the first widget id to bind.
- final int firstAppWidgetId = host.allocateAppWidgetId();
+ firstAppWidgetId = host.allocateAppWidgetId();
// Bind the first app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(firstAppWidgetId,
@@ -768,6 +824,7 @@
));
} finally {
// Clean up.
+ host.deleteAppWidgetId(firstAppWidgetId);
host.deleteHost();
revokeBindAppWidgetPermission();
}
@@ -788,14 +845,18 @@
return new MyAppWidgetHostView(context);
}
};
+ host.deleteHost();
host.startListening();
+ int firstAppWidgetId = 0;
+ int secondAppWidgetId = 0;
+
try {
// Grab the provider to be bound.
AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
// Allocate the first widget id to bind.
- final int firstAppWidgetId = host.allocateAppWidgetId();
+ firstAppWidgetId = host.allocateAppWidgetId();
// Bind the first app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(firstAppWidgetId,
@@ -809,7 +870,7 @@
firstHostView.setOnUpdateAppWidgetListener(firstAppHostViewListener);
// Allocate the second widget id to bind.
- final int secondAppWidgetId = host.allocateAppWidgetId();
+ secondAppWidgetId = host.allocateAppWidgetId();
// Bind the second app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(secondAppWidgetId,
@@ -854,6 +915,8 @@
);
} finally {
// Clean up.
+ host.deleteAppWidgetId(firstAppWidgetId);
+ host.deleteAppWidgetId(secondAppWidgetId);
host.deleteHost();
revokeBindAppWidgetPermission();
}
@@ -874,15 +937,17 @@
return new MyAppWidgetHostView(context);
}
};
-
+ host.deleteHost();
host.startListening();
+ int firstAppWidgetId = 0;
+
try {
// Grab the provider to be bound.
AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
// Allocate the first widget id to bind.
- final int firstAppWidgetId = host.allocateAppWidgetId();
+ firstAppWidgetId = host.allocateAppWidgetId();
// Bind the first app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(firstAppWidgetId,
@@ -913,7 +978,7 @@
waitForCallCount(updateAppWidgetCallCount, 1);
- // Partially update the content for all app widgets (pretent we changed somehting).
+ // Partially update the content for all app widgets (pretend we changed something).
getAppWidgetManager().partiallyUpdateAppWidget(firstAppWidgetId, content);
waitForCallCount(updateAppWidgetCallCount, 2);
@@ -925,6 +990,7 @@
provider.provider.getPackageName())));
} finally {
// Clean up.
+ host.deleteAppWidgetId(firstAppWidgetId);
host.deleteHost();
revokeBindAppWidgetPermission();
}
@@ -946,14 +1012,18 @@
return new MyAppWidgetHostView(context);
}
};
+ host.deleteHost();
host.startListening();
+ int firstAppWidgetId = 0;
+ int secondAppWidgetId = 0;
+
try {
// Grab the provider to be bound.
AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
// Allocate the first widget id to bind.
- final int firstAppWidgetId = host.allocateAppWidgetId();
+ firstAppWidgetId = host.allocateAppWidgetId();
// Bind the first app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(firstAppWidgetId,
@@ -977,7 +1047,7 @@
firstHostView.setOnUpdateAppWidgetListener(firstAppHostViewListener);
// Allocate the second widget id to bind.
- final int secondAppWidgetId = host.allocateAppWidgetId();
+ secondAppWidgetId = host.allocateAppWidgetId();
// Bind the second app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(secondAppWidgetId,
@@ -1010,7 +1080,7 @@
waitForCallCount(firstAppWidgetCallCounter, 1);
waitForCallCount(secondAppWidgetCallCounter, 1);
- // Partially update the content for all app widgets (pretend we changed somehting).
+ // Partially update the content for all app widgets (pretend we changed something).
getAppWidgetManager().partiallyUpdateAppWidget(new int[] {firstAppWidgetId,
secondAppWidgetId}, content);
@@ -1029,6 +1099,8 @@
provider.provider.getPackageName())));
} finally {
// Clean up.
+ host.deleteAppWidgetId(firstAppWidgetId);
+ host.deleteAppWidgetId(secondAppWidgetId);
host.deleteHost();
revokeBindAppWidgetPermission();
}
@@ -1038,16 +1110,20 @@
// We want to bind widgets.
grantBindAppWidgetPermission();
- final AtomicInteger getViewCounter = new AtomicInteger();
+ final AtomicInteger invocationCounter = new AtomicInteger();
final Context context = getInstrumentation().getTargetContext();
// Create a host and start listening.
- AppWidgetHost host = new AppWidgetHost(context, 0);
+ final AppWidgetHost host = new AppWidgetHost(context, 0);
+ host.deleteHost();
host.startListening();
+ final int appWidgetId;
+
try {
// Configure the provider behavior.
- AppWidgetProviderCallbacks callbacks = mock(AppWidgetProviderCallbacks.class);
+ AppWidgetProviderCallbacks callbacks = createAppWidgetProviderCallbacks(
+ invocationCounter);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
@@ -1063,6 +1139,11 @@
getAppWidgetManager().updateAppWidget(appWidgetId, removeViews);
+ synchronized (mLock) {
+ invocationCounter.incrementAndGet();
+ mLock.notifyAll();
+ }
+
return null;
}
}).when(callbacks).onUpdate(any(Context.class), any(AppWidgetManager.class),
@@ -1070,15 +1151,18 @@
FirstAppWidgetProvider.setCallbacks(callbacks);
// Grab the provider to be bound.
- AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
+ final AppWidgetProviderInfo provider = getFirstAppWidgetProviderInfo();
// Allocate a widget id to bind.
- final int appWidgetId = host.allocateAppWidgetId();
+ appWidgetId = host.allocateAppWidgetId();
// Bind the app widget.
getAppWidgetManager().bindAppWidgetIdIfAllowed(appWidgetId,
provider.getProfile(), provider.provider, null);
+ // Wait for onEnabled and onUpdate
+ waitForCallCount(invocationCounter, 2);
+
// Configure the app widget service behavior.
RemoteViewsFactory factory = mock(RemoteViewsFactory.class);
doAnswer(new Answer<Integer>() {
@@ -1094,7 +1178,7 @@
R.layout.collection_widget_item_layout);
remoteViews.setTextViewText(R.id.text_view, context.getText(R.string.foo));
synchronized (mLock) {
- getViewCounter.incrementAndGet();
+ invocationCounter.incrementAndGet();
}
return remoteViews;
}
@@ -1107,10 +1191,15 @@
}).when(factory).getViewTypeCount();
MyAppWidgetService.setFactory(factory);
- host.createView(context, appWidgetId, provider);
+ getInstrumentation().runOnMainSync(new Runnable() {
+ @Override
+ public void run() {
+ host.createView(context, appWidgetId, provider);
+ }
+ });
// Wait for the interactions to occur.
- waitForCallCount(getViewCounter, 1);
+ waitForCallCount(invocationCounter, 3);
// Verify the interactions.
verify(factory, atLeastOnce()).hasStableIds();
@@ -1133,7 +1222,7 @@
final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
final long remainingTimeMillis = OPERATION_TIMEOUT - elapsedTimeMillis;
if (remainingTimeMillis <= 0) {
- fail("Did not get expected call to onUpdateAppWidget");
+ fail("Did not get expected call");
}
try {
mLock.wait(remainingTimeMillis);
@@ -1289,15 +1378,98 @@
.getSystemService(Context.APPWIDGET_SERVICE);
}
+ private AppWidgetProviderCallbacks createAppWidgetProviderCallbacks(
+ final AtomicInteger callCounter) {
+ // Set a mock to intercept provider callbacks.
+ AppWidgetProviderCallbacks callbacks = mock(AppWidgetProviderCallbacks.class);
+
+ // onEnabled
+ doAnswer(new Answer<Void>() {
+ @Override
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ synchronized (mLock) {
+ callCounter.incrementAndGet();
+ mLock.notifyAll();
+ }
+ return null;
+ }
+ }).when(callbacks).onEnabled(any(Context.class));
+
+ // onUpdate
+ doAnswer(new Answer<Void>() {
+ @Override
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ synchronized (mLock) {
+ callCounter.incrementAndGet();
+ mLock.notifyAll();
+ }
+ return null;
+ }
+ }).when(callbacks).onUpdate(any(Context.class), any(AppWidgetManager.class),
+ any(int[].class));
+
+ // onAppWidgetOptionsChanged
+ doAnswer(new Answer<Void>() {
+ @Override
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ synchronized (mLock) {
+ callCounter.incrementAndGet();
+ mLock.notifyAll();
+ }
+ return null;
+ }
+ }).when(callbacks).onAppWidgetOptionsChanged(any(Context.class),
+ any(AppWidgetManager.class), any(int.class), any(Bundle.class));
+
+ // onDeleted
+ doAnswer(new Answer<Void>() {
+ @Override
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ synchronized (mLock) {
+ callCounter.incrementAndGet();
+ mLock.notifyAll();
+ }
+ return null;
+ }
+ }).when(callbacks).onDeleted(any(Context.class), any(int[].class));
+
+ // onDisabled
+ doAnswer(new Answer<Void>() {
+ @Override
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ synchronized (mLock) {
+ callCounter.incrementAndGet();
+ mLock.notifyAll();
+ }
+ return null;
+ }
+ }).when(callbacks).onDisabled(any(Context.class));
+
+ // onRestored
+ doAnswer(new Answer<Void>() {
+ @Override
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ synchronized (mLock) {
+ callCounter.incrementAndGet();
+ mLock.notifyAll();
+ }
+ return null;
+ }
+ }).when(callbacks).onRestored(any(Context.class), any(int[].class),
+ any(int[].class));
+
+ return callbacks;
+ }
+
private static boolean equalOptions(Bundle first, Bundle second) {
return first.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)
== second.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)
&& first.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)
== second.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)
&& first.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH)
- == second.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH)
+ == second.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH)
&& first.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT)
- == second.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
+ == second.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
}
private static final class OptionsMatcher extends BaseMatcher<Bundle> {
diff --git a/tests/tests/content/res/xml/alias.xml b/tests/tests/content/res/xml/alias.xml
index f88f3dc..c245ba8 100644
--- a/tests/tests/content/res/xml/alias.xml
+++ b/tests/tests/content/res/xml/alias.xml
@@ -19,8 +19,8 @@
<alias xmlns:android="http://schemas.android.com/apk/res/android">
<intent android:action="android.intent.action.MAIN"
- android:targetPackage="com.android.cts.stub"
- android:targetClass="android.app.cts.ChildActivity"
+ android:targetPackage="com.android.cts.content"
+ android:targetClass="android.content.cts.ChildActivity"
android:data="http://www.google.com/">
</intent>
</alias>
diff --git a/tests/tests/content/src/android/content/cts/AsyncQueryHandlerTest.java b/tests/tests/content/src/android/content/cts/AsyncQueryHandlerTest.java
index 18e0b2e..3d4ca81 100644
--- a/tests/tests/content/src/android/content/cts/AsyncQueryHandlerTest.java
+++ b/tests/tests/content/src/android/content/cts/AsyncQueryHandlerTest.java
@@ -25,14 +25,15 @@
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
/**
* Test {@link AsyncQueryHandler} and {@link WorkerHandler}}.
*
* @see DummyProvider
*/
-public class AsyncQueryHandlerTest extends AndroidTestCase {
+public class AsyncQueryHandlerTest extends InstrumentationTestCase {
private static final long TEST_TIME_OUT = DummyProvider.MOCK_OPERATION_SLEEP_TIME + 5000;
private static final int INSERT_TOKEN_1 = 100;
@@ -74,7 +75,7 @@
protected void setUp() throws Exception {
super.setUp();
- mResolver = mContext.getContentResolver();
+ mResolver = getInstrumentation().getTargetContext().getContentResolver();
ContentValues values0 = new ContentValues();
values0.put(DummyProvider.NAME, NAME0);
@@ -96,9 +97,9 @@
super.tearDown();
}
+ @UiThreadTest
public void testConstructor() {
new AsyncQueryHandler(mResolver) {};
-
new AsyncQueryHandler(null) {};
}
@@ -257,9 +258,10 @@
}
}
+ @UiThreadTest
public void testCreateHandler() {
MockAsyncQueryHandler wrapper = new MockAsyncQueryHandler(mResolver);
- Handler result = wrapper.createHandler(Looper.myLooper());
+ Handler result = wrapper.createHandler(Looper.getMainLooper());
assertNotNull(result);
assertSame(Looper.myLooper(), result.getLooper());
diff --git a/tests/src/android/app/cts/PendingIntentStubActivity.java b/tests/tests/content/src/android/content/cts/ChildActivity.java
similarity index 65%
copy from tests/src/android/app/cts/PendingIntentStubActivity.java
copy to tests/tests/content/src/android/content/cts/ChildActivity.java
index a2a3bd8..c8092ed 100644
--- a/tests/src/android/app/cts/PendingIntentStubActivity.java
+++ b/tests/tests/content/src/android/content/cts/ChildActivity.java
@@ -13,22 +13,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-package android.app.cts;
+package android.content.cts;
import android.app.Activity;
-import android.os.Bundle;
-public class PendingIntentStubActivity extends Activity {
+public class ChildActivity extends Activity {
- public static final int INVALIDATE = -1;
- public static final int ON_CREATE = 0;
- public static int status = INVALIDATE;
+ public static boolean isStarted = false;
@Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
- status = ON_CREATE;
+ protected void onStart() {
+ super.onStart();
+ isStarted = true;
}
-
}
diff --git a/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java b/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java
index bf0a175..e92834c 100644
--- a/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java
+++ b/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java
@@ -23,39 +23,44 @@
import android.content.Intent;
import android.content.ClipData.Item;
import android.net.Uri;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
-public class ClipboardManagerTest extends AndroidTestCase {
-
- private ClipboardManager mClipboardManager;
+public class ClipboardManagerTest extends InstrumentationTestCase {
+ private Context mContext;
@Override
protected void setUp() throws Exception {
super.setUp();
- mClipboardManager = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
+ mContext = getInstrumentation().getTargetContext();
}
+ @UiThreadTest
public void testSetGetText() {
- mClipboardManager.setText("Test Text 1");
- assertEquals("Test Text 1", mClipboardManager.getText());
+ ClipboardManager clipboardManager = makeClipboardManager();
+ clipboardManager.setText("Test Text 1");
+ assertEquals("Test Text 1", clipboardManager.getText());
- mClipboardManager.setText("Test Text 2");
- assertEquals("Test Text 2", mClipboardManager.getText());
+ clipboardManager.setText("Test Text 2");
+ assertEquals("Test Text 2", clipboardManager.getText());
}
+ @UiThreadTest
public void testHasPrimaryClip() {
- if (mClipboardManager.hasPrimaryClip()) {
- assertNotNull(mClipboardManager.getPrimaryClip());
- assertNotNull(mClipboardManager.getPrimaryClipDescription());
+ ClipboardManager clipboardManager = makeClipboardManager();
+ if (clipboardManager.hasPrimaryClip()) {
+ assertNotNull(clipboardManager.getPrimaryClip());
+ assertNotNull(clipboardManager.getPrimaryClipDescription());
} else {
- assertNull(mClipboardManager.getPrimaryClip());
- assertNull(mClipboardManager.getPrimaryClipDescription());
+ assertNull(clipboardManager.getPrimaryClip());
+ assertNull(clipboardManager.getPrimaryClipDescription());
}
- mClipboardManager.setPrimaryClip(ClipData.newPlainText("Label", "Text"));
- assertTrue(mClipboardManager.hasPrimaryClip());
+ clipboardManager.setPrimaryClip(ClipData.newPlainText("Label", "Text"));
+ assertTrue(clipboardManager.hasPrimaryClip());
}
+ @UiThreadTest
public void testSetPrimaryClip_plainText() {
ClipData textData = ClipData.newPlainText("TextLabel", "Text");
assertSetPrimaryClip(textData, "TextLabel",
@@ -63,6 +68,7 @@
new ExpectedClipItem("Text", null, null));
}
+ @UiThreadTest
public void testSetPrimaryClip_intent() {
Intent intent = new Intent(mContext, ClipboardManagerTest.class);
ClipData intentData = ClipData.newIntent("IntentLabel", intent);
@@ -71,6 +77,7 @@
new ExpectedClipItem(null, intent, null));
}
+ @UiThreadTest
public void testSetPrimaryClip_rawUri() {
Uri uri = Uri.parse("http://www.google.com");
ClipData uriData = ClipData.newRawUri("UriLabel", uri);
@@ -79,15 +86,17 @@
new ExpectedClipItem(null, null, uri));
}
+ @UiThreadTest
public void testSetPrimaryClip_contentUri() {
Uri contentUri = Uri.parse("content://cts/test/for/clipboardmanager");
- ClipData contentUriData = ClipData.newUri(getContext().getContentResolver(),
+ ClipData contentUriData = ClipData.newUri(mContext.getContentResolver(),
"ContentUriLabel", contentUri);
assertSetPrimaryClip(contentUriData, "ContentUriLabel",
new String[] {ClipDescription.MIMETYPE_TEXT_URILIST},
new ExpectedClipItem(null, null, contentUri));
}
+ @UiThreadTest
public void testSetPrimaryClip_complexItem() {
Intent intent = new Intent(mContext, ClipboardManagerTest.class);
Uri uri = Uri.parse("http://www.google.com");
@@ -103,6 +112,7 @@
new ExpectedClipItem("Text", intent, uri));
}
+ @UiThreadTest
public void testSetPrimaryClip_multipleItems() {
Intent intent = new Intent(mContext, ClipboardManagerTest.class);
Uri uri = Uri.parse("http://www.google.com");
@@ -134,22 +144,23 @@
String expectedLabel,
String[] expectedMimeTypes,
ExpectedClipItem... expectedClipItems) {
+ ClipboardManager clipboardManager = makeClipboardManager();
- mClipboardManager.setPrimaryClip(clipData);
- assertTrue(mClipboardManager.hasPrimaryClip());
+ clipboardManager.setPrimaryClip(clipData);
+ assertTrue(clipboardManager.hasPrimaryClip());
if (expectedClipItems != null
&& expectedClipItems.length > 0
&& expectedClipItems[0].mText != null) {
- assertTrue(mClipboardManager.hasText());
+ assertTrue(clipboardManager.hasText());
} else {
- assertFalse(mClipboardManager.hasText());
+ assertFalse(clipboardManager.hasText());
}
- assertNotNull(mClipboardManager.getPrimaryClip());
- assertNotNull(mClipboardManager.getPrimaryClipDescription());
+ assertNotNull(clipboardManager.getPrimaryClip());
+ assertNotNull(clipboardManager.getPrimaryClipDescription());
- ClipData data = mClipboardManager.getPrimaryClip();
+ ClipData data = clipboardManager.getPrimaryClip();
if (expectedClipItems != null) {
assertEquals(expectedClipItems.length, data.getItemCount());
for (int i = 0; i < expectedClipItems.length; i++) {
@@ -162,7 +173,7 @@
assertClipDescription(data.getDescription(),
expectedLabel, expectedMimeTypes);
- assertClipDescription(mClipboardManager.getPrimaryClipDescription(),
+ assertClipDescription(clipboardManager.getPrimaryClipDescription(),
expectedLabel, expectedMimeTypes);
}
@@ -189,4 +200,8 @@
assertNull(item.getUri());
}
}
+
+ private ClipboardManager makeClipboardManager() {
+ return (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
+ }
}
diff --git a/tests/tests/content/src/android/content/cts/ContentQueryMapTest.java b/tests/tests/content/src/android/content/cts/ContentQueryMapTest.java
index ac23a5b..2385b0f 100644
--- a/tests/tests/content/src/android/content/cts/ContentQueryMapTest.java
+++ b/tests/tests/content/src/android/content/cts/ContentQueryMapTest.java
@@ -20,11 +20,13 @@
import android.content.ContentQueryMap;
import android.content.ContentResolver;
import android.content.ContentValues;
+import android.content.Context;
import android.database.Cursor;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import java.util.Map;
import java.util.Observable;
@@ -33,7 +35,7 @@
/**
* Test {@link ContentQueryMap}.
*/
-public class ContentQueryMapTest extends AndroidTestCase {
+public class ContentQueryMapTest extends InstrumentationTestCase {
private static final int TEST_TIME_OUT = 5000;
private static final String NAME0 = "name0";
@@ -52,10 +54,12 @@
private ContentResolver mResolver;
private Cursor mCursor;
private ContentQueryMap mContentQueryMap;
+ private Context mContext;
@Override
protected void setUp() throws Exception {
super.setUp();
+ mContext = getInstrumentation().getTargetContext();
mResolver = mContext.getContentResolver();
ContentValues values0 = new ContentValues();
@@ -88,6 +92,7 @@
super.tearDown();
}
+ @UiThreadTest
public void testConstructor() {
new ContentQueryMap(mCursor, DummyProvider.NAME, true, null);
@@ -106,6 +111,7 @@
}
}
+ @UiThreadTest
public void testGetRows() {
// handler can be null
mContentQueryMap = new ContentQueryMap(mCursor, DummyProvider.NAME, true, null);
diff --git a/tests/tests/content/src/android/content/cts/MutableContextWrapperTest.java b/tests/tests/content/src/android/content/cts/MutableContextWrapperTest.java
index aaba30c..e7288af 100644
--- a/tests/tests/content/src/android/content/cts/MutableContextWrapperTest.java
+++ b/tests/tests/content/src/android/content/cts/MutableContextWrapperTest.java
@@ -18,9 +18,10 @@
import android.content.Context;
import android.content.MutableContextWrapper;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
-public class MutableContextWrapperTest extends AndroidTestCase {
+public class MutableContextWrapperTest extends InstrumentationTestCase {
MutableContextWrapper mMutableContextWrapper;
Context mContext;
@@ -29,7 +30,7 @@
protected void setUp() throws Exception {
super.setUp();
mMutableContextWrapper = null;
- mContext = getContext();
+ mContext = getInstrumentation().getTargetContext();
}
public void testConstructor() {
@@ -38,6 +39,7 @@
assertNotNull(mMutableContextWrapper);
}
+ @UiThreadTest
public void testSetBaseContext() {
mMutableContextWrapper = new MutableContextWrapper(mContext);
assertTrue(mContext.equals(mMutableContextWrapper.getBaseContext()));
diff --git a/tests/tests/content/src/android/content/pm/cts/FeatureTest.java b/tests/tests/content/src/android/content/pm/cts/FeatureTest.java
new file mode 100644
index 0000000..19bf128
--- /dev/null
+++ b/tests/tests/content/src/android/content/pm/cts/FeatureTest.java
@@ -0,0 +1,53 @@
+/**
+ * Copyright (C) 2014 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.cts;
+
+import android.app.ActivityManager;
+import android.content.Context;
+import android.content.pm.FeatureGroupInfo;
+import android.content.pm.FeatureInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+import java.util.Arrays;
+import java.util.Comparator;
+
+public class FeatureTest extends AndroidTestCase {
+
+ private static final String TAG = "FeatureTest";
+
+ private PackageManager mPackageManager;
+ private ActivityManager mActivityManager;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ mPackageManager = getContext().getPackageManager();
+ mActivityManager = (ActivityManager)getContext().getSystemService(Context.ACTIVITY_SERVICE);
+ }
+
+ public void testNoManagedUsersIfLowRamDevice() {
+ if (mPackageManager == null || mActivityManager == null) {
+ Log.w(TAG, "Skipping testNoManagedUsersIfLowRamDevice");
+ return;
+ }
+ if (mActivityManager.isLowRamDevice()) {
+ assertFalse(mPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS));
+ }
+ }
+}
diff --git a/tests/tests/graphics/AndroidManifest.xml b/tests/tests/graphics/AndroidManifest.xml
index 1a1e3e6..0006634 100644
--- a/tests/tests/graphics/AndroidManifest.xml
+++ b/tests/tests/graphics/AndroidManifest.xml
@@ -19,6 +19,7 @@
package="com.android.cts.graphics">
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
<uses-library android:name="android.test.runner" />
diff --git a/tests/tests/graphics/res/anim/animation_grouping_1_01.xml b/tests/tests/graphics/res/anim/animation_grouping_1_01.xml
new file mode 100644
index 0000000..8cc9f92
--- /dev/null
+++ b/tests/tests/graphics/res/anim/animation_grouping_1_01.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2014 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.
+-->
+
+<set xmlns:android="http://schemas.android.com/apk/res/android" >
+
+ <objectAnimator
+ android:duration="3300"
+ android:propertyName="rotation"
+ android:valueFrom="0"
+ android:valueTo="180"
+ android:repeatCount="-1" />
+</set>
\ No newline at end of file
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_render_order_1_golden.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_render_order_1_golden.png
index ea3be94..2fca8eb 100644
--- a/tests/tests/graphics/res/drawable-nodpi/vector_icon_render_order_1_golden.png
+++ b/tests/tests/graphics/res/drawable-nodpi/vector_icon_render_order_1_golden.png
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_transformation_6_golden.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_transformation_6_golden.png
index 64d07fa..3da7969 100644
--- a/tests/tests/graphics/res/drawable-nodpi/vector_icon_transformation_6_golden.png
+++ b/tests/tests/graphics/res/drawable-nodpi/vector_icon_transformation_6_golden.png
Binary files differ
diff --git a/tests/tests/graphics/res/drawable/animation_vector_drawable_grouping_1.xml b/tests/tests/graphics/res/drawable/animation_vector_drawable_grouping_1.xml
new file mode 100644
index 0000000..4a7e4f6
--- /dev/null
+++ b/tests/tests/graphics/res/drawable/animation_vector_drawable_grouping_1.xml
@@ -0,0 +1,26 @@
+<!--
+ Copyright (C) 2014 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.
+-->
+<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:drawable="@drawable/vector_drawable_grouping_1" >
+
+ <target
+ android:name="sun"
+ android:animation="@anim/animation_grouping_1_01" />
+ <target
+ android:name="earth"
+ android:animation="@anim/animation_grouping_1_01" />
+
+</animated-vector>
\ No newline at end of file
diff --git a/tests/tests/graphics/res/drawable/vector_drawable_grouping_1.xml b/tests/tests/graphics/res/drawable/vector_drawable_grouping_1.xml
new file mode 100644
index 0000000..7839ad1
--- /dev/null
+++ b/tests/tests/graphics/res/drawable/vector_drawable_grouping_1.xml
@@ -0,0 +1,52 @@
+<!--
+ Copyright (C) 2014 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:height="64dp"
+ android:width="64dp"
+ android:viewportHeight="256"
+ android:viewportWidth="256" >
+
+ <group
+ android:name="shape_layer_1"
+ android:translateX="128"
+ android:translateY="128" >
+ <group android:name="sun" >
+ <path
+ android:name="ellipse_path_1"
+ android:fillColor="#ffff8000"
+ android:pathData="m -25 0 a 25,25 0 1,0 50,0 a 25,25 0 1,0 -50,0" />
+
+ <group
+ android:name="earth"
+ android:translateX="75" >
+ <path
+ android:name="ellipse_path_1_1"
+ android:fillColor="#ff5656ea"
+ android:pathData="m -10 0 a 10,10 0 1,0 20,0 a 10,10 0 1,0 -20,0" />
+
+ <group
+ android:name="moon"
+ android:translateX="25" >
+ <path
+ android:name="ellipse_path_1_2"
+ android:fillColor="#ffadadad"
+ android:pathData="m -5 0 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0" />
+ </group>
+ </group>
+ </group>
+ </group>
+
+</vector>
\ No newline at end of file
diff --git a/tests/tests/graphics/res/drawable/vector_icon_render_order_1.xml b/tests/tests/graphics/res/drawable/vector_icon_render_order_1.xml
index 8639096..d4472e2 100644
--- a/tests/tests/graphics/res/drawable/vector_icon_render_order_1.xml
+++ b/tests/tests/graphics/res/drawable/vector_icon_render_order_1.xml
@@ -21,65 +21,65 @@
<group
android:name="FirstLevelGroup"
- android:alpha="0.9"
android:translateX="100.0"
android:translateY="0.0" >
<path
android:fillColor="#FFFF0000"
+ android:fillAlpha="0.9"
android:pathData="@string/rectangle200" />
<group
android:name="SecondLevelGroup1"
- android:alpha="0.9"
android:translateX="-100.0"
android:translateY="50.0" >
<path
android:fillColor="#FF00FF00"
+ android:fillAlpha="0.81"
android:pathData="@string/rectangle200" />
<group
android:name="ThridLevelGroup1"
- android:alpha="0.9"
android:translateX="-100.0"
android:translateY="50.0" >
<path
android:fillColor="#FF0000FF"
+ android:fillAlpha="0.729"
android:pathData="@string/rectangle200" />
</group>
<group
android:name="ThridLevelGroup2"
- android:alpha="0.8"
android:translateX="100.0"
android:translateY="50.0" >
<path
+ android:fillAlpha="0.72"
android:fillColor="#FF000000"
android:pathData="@string/rectangle200" />
</group>
</group>
<group
android:name="SecondLevelGroup2"
- android:alpha="0.8"
android:translateX="100.0"
android:translateY="50.0" >
<path
android:fillColor="#FF0000FF"
+ android:fillAlpha="0.72"
android:pathData="@string/rectangle200" />
<group
android:name="ThridLevelGroup3"
- android:alpha="0.9"
android:translateX="-100.0"
android:translateY="50.0" >
<path
+ android:fillAlpha="0.648"
android:fillColor="#FFFF0000"
android:pathData="@string/rectangle200" />
</group>
<group
android:name="ThridLevelGroup4"
- android:alpha="0.8"
android:translateX="100.0"
android:translateY="50.0" >
<path
+ android:fillAlpha="0.576"
android:fillColor="#FF00FF00"
android:pathData="@string/rectangle200" />
</group>
diff --git a/tests/tests/graphics/res/drawable/vector_icon_render_order_2.xml b/tests/tests/graphics/res/drawable/vector_icon_render_order_2.xml
index 069a531..6fcb355 100644
--- a/tests/tests/graphics/res/drawable/vector_icon_render_order_2.xml
+++ b/tests/tests/graphics/res/drawable/vector_icon_render_order_2.xml
@@ -21,67 +21,67 @@
<group
android:name="FirstLevelGroup"
- android:alpha="0.9"
android:translateX="100.0"
android:translateY="0.0" >
<group
android:name="SecondLevelGroup1"
- android:alpha="0.9"
android:translateX="-100.0"
android:translateY="50.0" >
<path
+ android:fillAlpha="0.81"
android:fillColor="#FF00FF00"
android:pathData="@string/rectangle200" />
<group
android:name="ThridLevelGroup1"
- android:alpha="0.9"
android:translateX="-100.0"
android:translateY="50.0" >
<path
+ android:fillAlpha="0.729"
android:fillColor="#FF0000FF"
android:pathData="@string/rectangle200" />
</group>
<group
android:name="ThridLevelGroup2"
- android:alpha="0.8"
android:translateX="100.0"
android:translateY="50.0" >
<path
+ android:fillAlpha="0.648"
android:fillColor="#FF000000"
android:pathData="@string/rectangle200" />
</group>
</group>
<group
android:name="SecondLevelGroup2"
- android:alpha="0.8"
android:translateX="100.0"
android:translateY="50.0" >
<path
+ android:fillAlpha="0.72"
android:fillColor="#FF0000FF"
android:pathData="@string/rectangle200" />
<group
android:name="ThridLevelGroup3"
- android:alpha="0.9"
android:translateX="-100.0"
android:translateY="50.0" >
<path
+ android:fillAlpha="0.648"
android:fillColor="#FFFF0000"
android:pathData="@string/rectangle200" />
</group>
<group
android:name="ThridLevelGroup4"
- android:alpha="0.8"
android:translateX="100.0"
android:translateY="50.0" >
<path
+ android:fillAlpha="0.576"
android:fillColor="#FF00FF00"
android:pathData="@string/rectangle200" />
</group>
</group>
<path
+ android:fillAlpha="0.9"
android:fillColor="#FFFF0000"
android:pathData="@string/rectangle200" />
</group>
diff --git a/tests/tests/graphics/res/drawable/vector_icon_transformation_6.xml b/tests/tests/graphics/res/drawable/vector_icon_transformation_6.xml
index 5e60c4a..2c174fb 100644
--- a/tests/tests/graphics/res/drawable/vector_icon_transformation_6.xml
+++ b/tests/tests/graphics/res/drawable/vector_icon_transformation_6.xml
@@ -17,10 +17,10 @@
android:height="64dp"
android:width="64dp"
android:viewportHeight="400"
- android:viewportWidth="400" >
-
- <group android:name="backgroundGroup"
+ android:viewportWidth="400"
android:alpha = "0.5" >
+
+ <group android:name="backgroundGroup">
<path
android:name="background1"
android:fillColor="#FF000000"
@@ -33,8 +33,7 @@
<group
android:name="translateToCenterGroup"
android:translateX="50.0"
- android:translateY="90.0"
- android:alpha = "0.5" >
+ android:translateY="90.0">
<path
android:name="twoLines"
android:pathData="M 0,0 v 100 M 0,0 h 100"
@@ -45,39 +44,39 @@
android:name="rotationGroup"
android:pivotX="0.0"
android:pivotY="0.0"
- android:rotation="-45.0"
- android:alpha = "0.5" >
+ android:rotation="-45.0" >
<path
android:name="twoLines1"
android:pathData="M 0,0 v 100 M 0,0 h 100"
android:strokeColor="#FF00FF00"
- android:strokeWidth="20" />
+ android:strokeWidth="20"
+ android:strokeAlpha="0.5" />
<group
android:name="translateGroup"
android:translateX="130.0"
- android:translateY="160.0"
- android:alpha = "0.5">
+ android:translateY="160.0">
<group android:name="scaleGroup" >
<path
android:name="twoLines3"
android:pathData="M 0,0 v 100 M 0,0 h 100"
android:strokeColor="#FF0000FF"
- android:strokeWidth="20" />
+ android:strokeWidth="20"
+ android:strokeAlpha="0.25" />
</group>
</group>
<group
android:name="translateGroupHalf"
android:translateX="65.0"
- android:translateY="80.0"
- android:alpha = "0.5">
+ android:translateY="80.0">
<group android:name="scaleGroup" >
<path
android:name="twoLines2"
android:pathData="M 0,0 v 100 M 0,0 h 100"
android:strokeColor="#FF0000FF"
- android:strokeWidth="20" />
+ android:strokeWidth="20"
+ android:strokeAlpha="0.5" />
</group>
</group>
</group>
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableTest.java
new file mode 100644
index 0000000..b4c64e2
--- /dev/null
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedVectorDrawableTest.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright (C) 2014 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.graphics.drawable.cts;
+
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.drawable.AnimatedVectorDrawable;
+import android.graphics.drawable.Drawable.ConstantState;
+import android.test.AndroidTestCase;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.util.Xml;
+
+import com.android.cts.graphics.R;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+public class AnimatedVectorDrawableTest extends AndroidTestCase {
+ private static final String LOGTAG = AnimatedVectorDrawableTest.class.getSimpleName();
+
+ private static final int IMAGE_WIDTH = 64;
+ private static final int IMAGE_HEIGHT = 64;
+
+ private Resources mResources;
+ private AnimatedVectorDrawable mAnimatedVectorDrawable;
+ private Bitmap mBitmap;
+ private Canvas mCanvas;
+ private static final boolean DBG_DUMP_PNG = false;
+ private int mResId = R.drawable.animation_vector_drawable_grouping_1;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ mBitmap = Bitmap.createBitmap(IMAGE_WIDTH, IMAGE_HEIGHT, Bitmap.Config.ARGB_8888);
+ mCanvas = new Canvas(mBitmap);
+ mAnimatedVectorDrawable = new AnimatedVectorDrawable();
+
+ mResources = mContext.getResources();
+ }
+
+ // This is only for debugging or golden image (re)generation purpose.
+ private void saveVectorDrawableIntoPNG(Bitmap bitmap, int resId) throws IOException {
+ // Save the image to the disk.
+ FileOutputStream out = null;
+ try {
+ String outputFolder = "/sdcard/temp/";
+ File folder = new File(outputFolder);
+ if (!folder.exists()) {
+ folder.mkdir();
+ }
+ String originalFilePath = mResources.getString(resId);
+ File originalFile = new File(originalFilePath);
+ String fileFullName = originalFile.getName();
+ String fileTitle = fileFullName.substring(0, fileFullName.lastIndexOf("."));
+ String outputFilename = outputFolder + fileTitle + "_golden.png";
+ File outputFile = new File(outputFilename);
+ if (!outputFile.exists()) {
+ outputFile.createNewFile();
+ }
+
+ out = new FileOutputStream(outputFile, false);
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
+ Log.v(LOGTAG, "Write test No." + outputFilename + " to file successfully.");
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (out != null) {
+ out.close();
+ }
+ }
+ }
+
+ public void testInflate() throws Exception {
+ // Setup AnimatedVectorDrawable from xml file
+ XmlPullParser parser = mResources.getXml(mResId);
+ AttributeSet attrs = Xml.asAttributeSet(parser);
+
+ int type;
+ while ((type=parser.next()) != XmlPullParser.START_TAG &&
+ type != XmlPullParser.END_DOCUMENT) {
+ // Empty loop
+ }
+
+ if (type != XmlPullParser.START_TAG) {
+ throw new XmlPullParserException("No start tag found");
+ }
+
+ mAnimatedVectorDrawable.inflate(mResources, parser, attrs);
+ mAnimatedVectorDrawable.setBounds(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
+ mBitmap.eraseColor(0);
+ mAnimatedVectorDrawable.draw(mCanvas);
+ int sunColor = mBitmap.getPixel(IMAGE_WIDTH / 2, IMAGE_HEIGHT / 2);
+ int earthColor = mBitmap.getPixel(IMAGE_WIDTH * 3 / 4 + 2, IMAGE_HEIGHT / 2);
+ assertTrue(sunColor == 0xFFFF8000);
+ assertTrue(earthColor == 0xFF5656EA);
+
+ if (DBG_DUMP_PNG) {
+ saveVectorDrawableIntoPNG(mBitmap, mResId);
+ }
+ }
+
+ public void testGetChangingConfigurations() {
+ AnimatedVectorDrawable avd = new AnimatedVectorDrawable();
+ ConstantState constantState = avd.getConstantState();
+
+ // default
+ assertEquals(0, constantState.getChangingConfigurations());
+ assertEquals(0, avd.getChangingConfigurations());
+
+ // change the drawable's configuration does not affect the state's configuration
+ avd.setChangingConfigurations(0xff);
+ assertEquals(0xff, avd.getChangingConfigurations());
+ assertEquals(0, constantState.getChangingConfigurations());
+
+ // the state's configuration get refreshed
+ constantState = avd.getConstantState();
+ assertEquals(0xff, constantState.getChangingConfigurations());
+
+ // set a new configuration to drawable
+ avd.setChangingConfigurations(0xff00);
+ assertEquals(0xff, constantState.getChangingConfigurations());
+ assertEquals(0xffff, avd.getChangingConfigurations());
+ }
+
+ public void testGetConstantState() {
+ AnimatedVectorDrawable AnimatedVectorDrawable = new AnimatedVectorDrawable();
+ ConstantState constantState = AnimatedVectorDrawable.getConstantState();
+ assertNotNull(constantState);
+ assertEquals(0, constantState.getChangingConfigurations());
+
+ AnimatedVectorDrawable.setChangingConfigurations(1);
+ constantState = AnimatedVectorDrawable.getConstantState();
+ assertNotNull(constantState);
+ assertEquals(1, constantState.getChangingConfigurations());
+ }
+
+ public void testMutate() {
+ Resources resources = mContext.getResources();
+
+ AnimatedVectorDrawable d1 = (AnimatedVectorDrawable) resources.getDrawable(mResId);
+ AnimatedVectorDrawable d2 = (AnimatedVectorDrawable) resources.getDrawable(mResId);
+ AnimatedVectorDrawable d3 = (AnimatedVectorDrawable) resources.getDrawable(mResId);
+ int originalAlpha = d2.getAlpha();
+ int newAlpha = (originalAlpha + 1) % 255;
+
+ // AVD is different than VectorDrawable. Every instance of it is a deep copy
+ // of the VectorDrawable.
+ // So every setAlpha operation will happen only to that specific object.
+ d1.setAlpha(newAlpha);
+ assertEquals(newAlpha, d1.getAlpha());
+ assertEquals(originalAlpha, d2.getAlpha());
+ assertEquals(originalAlpha, d3.getAlpha());
+
+ d1.mutate();
+ d1.setAlpha(0x40);
+ assertEquals(0x40, d1.getAlpha());
+ assertEquals(originalAlpha, d2.getAlpha());
+ assertEquals(originalAlpha, d3.getAlpha());
+
+ d2.setAlpha(0x20);
+ assertEquals(0x40, d1.getAlpha());
+ assertEquals(0x20, d2.getAlpha());
+ assertEquals(originalAlpha, d3.getAlpha());
+ }
+}
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableTest.java
index 323a2a7..3578d3c 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/VectorDrawableTest.java
@@ -57,6 +57,9 @@
R.drawable.vector_icon_transformation_3,
R.drawable.vector_icon_transformation_4,
R.drawable.vector_icon_transformation_5,
+ R.drawable.vector_icon_transformation_6,
+ R.drawable.vector_icon_render_order_1,
+ R.drawable.vector_icon_render_order_2,
R.drawable.vector_icon_stroke_1,
R.drawable.vector_icon_stroke_2,
R.drawable.vector_icon_stroke_3,
@@ -80,6 +83,9 @@
R.drawable.vector_icon_transformation_3_golden,
R.drawable.vector_icon_transformation_4_golden,
R.drawable.vector_icon_transformation_5_golden,
+ R.drawable.vector_icon_transformation_6_golden,
+ R.drawable.vector_icon_render_order_1_golden,
+ R.drawable.vector_icon_render_order_2_golden,
R.drawable.vector_icon_stroke_1_golden,
R.drawable.vector_icon_stroke_2_golden,
R.drawable.vector_icon_stroke_3_golden,
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
index 6fee8ce..9f50b43 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/CameraDeviceTest.java
@@ -48,7 +48,9 @@
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
@@ -78,6 +80,14 @@
CameraDevice.TEMPLATE_VIDEO_SNAPSHOT
};
+ // Request templates that are unsupported by LEGACY mode.
+ private static Set<Integer> sLegacySkipTemplates = new HashSet<>();
+ static {
+ sLegacySkipTemplates.add(CameraDevice.TEMPLATE_VIDEO_SNAPSHOT);
+ sLegacySkipTemplates.add(CameraDevice.TEMPLATE_ZERO_SHUTTER_LAG);
+ sLegacySkipTemplates.add(CameraDevice.TEMPLATE_MANUAL);
+ }
+
@Override
public void setContext(Context context) {
super.setContext(context);
@@ -744,11 +754,14 @@
.onError(
any(CameraDevice.class),
anyInt());
- }
- finally {
+ } catch (Exception e) {
+ mCollector.addError(e);
+ } finally {
try {
closeSession();
- } finally {
+ } catch (Exception e) {
+ mCollector.addError(e);
+ }finally {
closeDevice(mCameraIds[i], mCameraMockListener);
}
}
@@ -828,7 +841,7 @@
}
waitForSessionState(SESSION_ACTIVE, SESSION_READY_TIMEOUT_MS);
- int expectedResultCount = len;
+ int expectedResultCount = requests.size();
if (repeating) {
expectedResultCount *= REPEATING_CAPTURE_EXPECTED_RESULT_COUNT;
}
@@ -1294,7 +1307,7 @@
!mStaticInfo.isCapabilitySupported(CameraCharacteristics.
REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR)) {
// OK
- } else if (template == CameraDevice.TEMPLATE_VIDEO_SNAPSHOT &&
+ } else if (sLegacySkipTemplates.contains(template) &&
mStaticInfo.isHardwareLevelLegacy()) {
// OK
} else {
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureRequestTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureRequestTest.java
index 3d55c85..006b32c 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureRequestTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureRequestTest.java
@@ -351,10 +351,14 @@
* Test tone map modes and controls.
*/
public void testToneMapControl() throws Exception {
- for (int i = 0; i < mCameraIds.length; i++) {
+ for (String id : mCameraIds) {
try {
- openDevice(mCameraIds[i]);
-
+ openDevice(id);
+ if (!mStaticInfo.isManualToneMapSupported()) {
+ Log.i(TAG, "Camera " + id +
+ " doesn't support tone mapping controls, skipping test");
+ continue;
+ }
toneMapTestByCamera();
} finally {
closeDevice();
@@ -369,7 +373,11 @@
for (String id : mCameraIds) {
try {
openDevice(id);
-
+ if (!mStaticInfo.isManualColorCorrectionSupported()) {
+ Log.i(TAG, "Camera " + id +
+ " doesn't support color correction controls, skipping test");
+ continue;
+ }
colorCorrectionTestByCamera();
} finally {
closeDevice();
@@ -381,9 +389,9 @@
for (String id : mCameraIds) {
try {
openDevice(id);
- if (!mStaticInfo.getCharacteristics().getKeys().
- contains(CameraCharacteristics.EDGE_AVAILABLE_EDGE_MODES)) {
- Log.i(TAG, "Camera " + id + " doesn't support EDGE_MODE controls.");
+ if (!mStaticInfo.isEdgeModeControlSupported()) {
+ Log.i(TAG, "Camera " + id +
+ " doesn't support EDGE_MODE controls, skipping test");
continue;
}
@@ -402,7 +410,14 @@
try {
openDevice(id);
if (!mStaticInfo.hasFocuser()) {
- Log.i(TAG, "Camera " + id + " has no focuser");
+ Log.i(TAG, "Camera " + id + " has no focuser, skipping test");
+ continue;
+ }
+
+ if (!mStaticInfo.isCapabilitySupported(
+ CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR)) {
+ Log.i(TAG, "Camera " + id +
+ " does not support MANUAL_SENSOR, skipping test");
continue;
}
@@ -417,9 +432,9 @@
for (String id : mCameraIds) {
try {
openDevice(id);
- if (!mStaticInfo.getCharacteristics().getKeys().contains(
- CameraCharacteristics.NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES)) {
- Log.i(TAG, "Camera " + id + " doesn't support noise reduction mode");
+ if (!mStaticInfo.isNoiseReductionModeControlSupported()) {
+ Log.i(TAG, "Camera " + id +
+ " doesn't support noise reduction mode, skipping test");
continue;
}
@@ -1542,9 +1557,13 @@
verifyCaptureResultForKey(CaptureResult.CONTROL_AF_MODE, mode, listener,
NUM_FRAMES_VERIFIED);
- // Verify AF can finish a scan for CONTROL_AF_MODE_CONTINUOUS_* modes
- if (mode == CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE ||
- mode == CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO) {
+ // Verify AF can finish a scan for CONTROL_AF_MODE_CONTINUOUS_* modes.
+ // In LEGACY mode, a transition to one of the continuous AF modes does not necessarily
+ // result in a passive AF call if the camera has already been focused, and the scene has
+ // not changed enough to trigger an AF pass. Skip this constraint for LEGACY.
+ if (mStaticInfo.isHardwareLevelLimitedOrBetter() &&
+ (mode == CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE ||
+ mode == CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO)) {
List<Integer> afStateList = new ArrayList<Integer>();
afStateList.add(CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED);
afStateList.add(CaptureResult.CONTROL_AF_STATE_PASSIVE_UNFOCUSED);
@@ -2041,9 +2060,13 @@
fpsRange = fpsRanges[i];
Size previewSz = getMaxPreviewSizeForFpsRange(fpsRange);
// If unable to find a preview size, then log the failure, and skip this run.
- if (!mCollector.expectTrue(String.format(
- "Unable to find a preview size supporting given fps range %s",
- fpsRange), previewSz != null)) {
+ if (previewSz == null) {
+ if (mStaticInfo.isCapabilitySupported(
+ CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR)) {
+ mCollector.addMessage(String.format(
+ "Unable to find a preview size supporting given fps range %s",
+ fpsRange));
+ }
continue;
}
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureResultTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureResultTest.java
index 744f4ca..61bf36c 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureResultTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/CaptureResultTest.java
@@ -515,6 +515,11 @@
waiverKeys.add(CaptureResult.SENSOR_FRAME_DURATION);
waiverKeys.add(CaptureResult.SENSOR_SENSITIVITY);
waiverKeys.add(CaptureResult.BLACK_LEVEL_LOCK);
+ waiverKeys.add(CaptureResult.LENS_FOCUS_RANGE);
+ waiverKeys.add(CaptureResult.LENS_FOCUS_DISTANCE);
+ waiverKeys.add(CaptureResult.LENS_STATE);
+ waiverKeys.add(CaptureResult.LENS_APERTURE);
+ waiverKeys.add(CaptureResult.LENS_FILTER_DENSITY);
}
if (mStaticInfo.isHardwareLevelLimited()) {
@@ -529,15 +534,12 @@
waiverKeys.add(CaptureResult.CONTROL_AWB_STATE);
waiverKeys.add(CaptureResult.FLASH_STATE);
waiverKeys.add(CaptureResult.LENS_OPTICAL_STABILIZATION_MODE);
- waiverKeys.add(CaptureResult.LENS_FOCUS_RANGE);
- waiverKeys.add(CaptureResult.LENS_FOCUS_DISTANCE);
- waiverKeys.add(CaptureResult.LENS_STATE);
- waiverKeys.add(CaptureResult.LENS_APERTURE);
- waiverKeys.add(CaptureResult.LENS_FILTER_DENSITY);
waiverKeys.add(CaptureResult.SENSOR_ROLLING_SHUTTER_SKEW);
waiverKeys.add(CaptureResult.STATISTICS_LENS_SHADING_MAP_MODE);
waiverKeys.add(CaptureResult.STATISTICS_SCENE_FLICKER);
waiverKeys.add(CaptureResult.STATISTICS_HOT_PIXEL_MAP_MODE);
+ waiverKeys.add(CaptureResult.CONTROL_AE_TARGET_FPS_RANGE);
+ waiverKeys.add(CaptureResult.CONTROL_AF_TRIGGER);
return waiverKeys;
}
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
index 2ddff9f..1a00d9e 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
@@ -65,7 +65,7 @@
private static final int LEGACY = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY;
private static final int LIMITED = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED;
private static final int FULL = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL;
- private static final int OPT = -1; // For keys that are optional on all hardware levels.
+ private static final int OPT = Integer.MAX_VALUE; // For keys that are optional on all hardware levels.
/*
* Capabilities short hand
@@ -340,9 +340,7 @@
/**
* Check key is present in characteristics if the hardware level is at least {@code hwLevel};
- * check that the key is present if the actual capabilities are one of {@code capabilities};
- * lastly check that {@code LEGACY} devices don't list any addition keys that they shouldn't
- * be.
+ * check that the key is present if the actual capabilities are one of {@code capabilities}.
*
* @return value of the {@code key} from {@code c}
*/
@@ -387,23 +385,14 @@
allKeys.contains(key));
} else {
if (actualHwLevel == LEGACY && hwLevel != OPT) {
- mCollector.expectTrue(
- String.format("Key (%s) must not be in characteristics for LEGACY devices",
- key.getName()),
- value == null);
-
- mCollector.expectTrue(
- String.format("Key (%s) must not be in characteristics list of keys" +
- "for LEGACY devices",
- key.getName()),
- !allKeys.contains(key));
-
- // TODO: a few keys like aeLock, awbLock are optional in api1. Revisit this.
+ if (value != null || allKeys.contains(key)) {
+ Log.w(TAG, String.format(
+ "Key (%s) is not required for LEGACY devices but still appears",
+ key.getName()));
+ }
}
-
// OK: Key may or may not be present.
}
-
return value;
}
@@ -478,7 +467,7 @@
private static int remapHardwareLevel(int level) {
switch (level) {
case OPT:
- return -1;
+ return Integer.MAX_VALUE;
case LEGACY:
return 0; // lowest
case LIMITED:
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/PerformanceTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/PerformanceTest.java
index 3a7df4c..d4a0e73 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/PerformanceTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/PerformanceTest.java
@@ -211,8 +211,11 @@
new SimpleTimingResultListener();
SimpleImageListener imageListener = new SimpleImageListener();
+ Size maxYuvSize = CameraTestUtils.getSupportedPreviewSizes(id, mCameraManager,
+ /*bound*/null).get(0);
+
prepareCaptureAndStartPreview(previewBuilder, captureBuilder,
- mOrderedPreviewSizes.get(0), mOrderedStillSizes.get(0),
+ mOrderedPreviewSizes.get(0), maxYuvSize,
ImageFormat.YUV_420_888, previewResultListener,
NUM_MAX_IMAGES, imageListener);
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/RecordingTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/RecordingTest.java
index 83c3afb..fd2c2b9 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/RecordingTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/RecordingTest.java
@@ -78,7 +78,7 @@
private static final int MAX_VIDEO_SNAPSHOT_IMAGES = 5;
private static final int BURST_VIDEO_SNAPSHOT_NUM = 3;
private static final int SLOWMO_SLOW_FACTOR = 4;
-
+ private static final int MAX_NUM_FRAME_DROP_ALLOWED = 3;
private List<Size> mSupportedVideoSizes;
private Surface mRecordingSurface;
private MediaRecorder mMediaRecorder;
@@ -546,12 +546,26 @@
CamcorderProfile profile = CamcorderProfile.get(cameraId, profileId);
Size videoSz = new Size(profile.videoFrameWidth, profile.videoFrameHeight);
- assertTrue("Video size " + videoSz.toString() + " for profile ID " + profileId +
- " must be one of the camera device supported video size!",
- mSupportedVideoSizes.contains(videoSz));
+ if (!mSupportedVideoSizes.contains(videoSz)) {
+ mCollector.addMessage("Video size " + videoSz.toString() + " for profile ID " +
+ profileId + " must be one of the camera device supported video size!");
+ continue;
+ }
Size maxPreviewSize = mOrderedPreviewSizes.get(0);
- Size videoSnapshotSz = videoSz;
+
+ // For LEGACY, find closest supported smaller or equal JPEG size to the current video
+ // size; if no size is smaller than the video, pick the smallest JPEG size. The assert
+ // for video size above guarantees that for LIMITED or FULL, we select videoSz here.
+ Size videoSnapshotSz = mOrderedStillSizes.get(mOrderedStillSizes.size() - 1);
+ for (int i = mOrderedStillSizes.size() - 2; i >= 0; i--) {
+ Size candidateSize = mOrderedStillSizes.get(i);
+ if (candidateSize.getWidth() <= videoSz.getWidth() &&
+ candidateSize.getHeight() <= videoSz.getHeight()) {
+ videoSnapshotSz = candidateSize;
+ }
+ }
+
/**
* Only test full res snapshot when below conditions are all true.
* 1. Camera is a FULL device
@@ -584,7 +598,8 @@
SimpleCaptureCallback resultListener = new SimpleCaptureCallback();
SimpleImageReaderListener imageListener = new SimpleImageReaderListener();
CaptureRequest.Builder videoSnapshotRequestBuilder =
- mCamera.createCaptureRequest(CameraDevice.TEMPLATE_VIDEO_SNAPSHOT);
+ mCamera.createCaptureRequest((mStaticInfo.isHardwareLevelLegacy()) ?
+ CameraDevice.TEMPLATE_RECORD : CameraDevice.TEMPLATE_VIDEO_SNAPSHOT);
// prepare preview surface by using video size.
updatePreviewSurfaceWithVideoSize(videoSz);
@@ -866,8 +881,18 @@
mVideoSize.getWidth(), mVideoSize.getHeight(),
durationMs, expectedDurationMs
),
- durationMs < (expectedDurationMs * 2)
+ durationMs <= (expectedDurationMs * MAX_NUM_FRAME_DROP_ALLOWED)
);
+ // Log a warning is there is any frame drop detected.
+ if (durationMs >= expectedDurationMs * 2) {
+ Log.w(TAG, String.format(
+ "Video %dx%d Frame drop detected before video snapshot: " +
+ "duration %dms (expected %dms)",
+ mVideoSize.getWidth(), mVideoSize.getHeight(),
+ durationMs, expectedDurationMs
+ ));
+ }
+
durationMs = (int) (nextTS - currentTS) / 1000000;
mCollector.expectTrue(
String.format(
@@ -876,8 +901,17 @@
mVideoSize.getWidth(), mVideoSize.getHeight(),
durationMs, expectedDurationMs
),
- durationMs < (expectedDurationMs * 2)
+ durationMs <= (expectedDurationMs * MAX_NUM_FRAME_DROP_ALLOWED)
);
+ // Log a warning is there is any frame drop detected.
+ if (durationMs >= expectedDurationMs * 2) {
+ Log.w(TAG, String.format(
+ "Video %dx%d Frame drop detected after video snapshot: " +
+ "duration %dms (expected %dms)",
+ mVideoSize.getWidth(), mVideoSize.getHeight(),
+ durationMs, expectedDurationMs
+ ));
+ }
}
return;
}
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/RobustnessTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/RobustnessTest.java
index c394b47..11ba02c 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/RobustnessTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/RobustnessTest.java
@@ -331,6 +331,10 @@
// Set up outputs
List<Object> outputTargets = new ArrayList<>();
List<Surface> outputSurfaces = new ArrayList<>();
+ List<SurfaceTexture> privTargets = new ArrayList<SurfaceTexture>();
+ List<ImageReader> jpegTargets = new ArrayList<ImageReader>();
+ List<ImageReader> yuvTargets = new ArrayList<ImageReader>();
+ List<ImageReader> rawTargets = new ArrayList<ImageReader>();
for (int i = 0; i < config.length; i += 2) {
int format = config[i];
int sizeLimit = config[i + 1];
@@ -342,6 +346,7 @@
target.setDefaultBufferSize(targetSize.getWidth(), targetSize.getHeight());
outputTargets.add(target);
outputSurfaces.add(new Surface(target));
+ privTargets.add(target);
break;
}
case JPEG: {
@@ -350,6 +355,7 @@
targetSize.getWidth(), targetSize.getHeight(), JPEG, MIN_RESULT_COUNT);
outputTargets.add(target);
outputSurfaces.add(target.getSurface());
+ jpegTargets.add(target);
break;
}
case YUV: {
@@ -358,6 +364,7 @@
targetSize.getWidth(), targetSize.getHeight(), YUV, MIN_RESULT_COUNT);
outputTargets.add(target);
outputSurfaces.add(target.getSurface());
+ yuvTargets.add(target);
break;
}
case RAW: {
@@ -366,6 +373,7 @@
targetSize.getWidth(), targetSize.getHeight(), RAW, MIN_RESULT_COUNT);
outputTargets.add(target);
outputSurfaces.add(target.getSurface());
+ rawTargets.add(target);
break;
}
default:
@@ -417,6 +425,19 @@
MaxOutputSizes.configToString(config), e.getMessage()));
}
}
+
+ for (SurfaceTexture target : privTargets) {
+ target.release();
+ }
+ for (ImageReader target : jpegTargets) {
+ target.close();
+ }
+ for (ImageReader target : yuvTargets) {
+ target.close();
+ }
+ for (ImageReader target : rawTargets) {
+ target.close();
+ }
}
private static Size getMaxRecordingSize(String cameraId) {
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/StaticMetadataTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/StaticMetadataTest.java
index 1d28e6d..ec7ecf8 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/StaticMetadataTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/StaticMetadataTest.java
@@ -239,7 +239,6 @@
requestKeys.add(CaptureRequest.CONTROL_AE_LOCK);
requestKeys.add(CaptureRequest.CONTROL_AE_MODE);
requestKeys.add(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE);
- requestKeys.add(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER);
requestKeys.add(CaptureRequest.CONTROL_AF_MODE);
requestKeys.add(CaptureRequest.CONTROL_AF_TRIGGER);
requestKeys.add(CaptureRequest.CONTROL_AWB_LOCK);
@@ -255,7 +254,6 @@
requestKeys.add(CaptureRequest.JPEG_QUALITY);
requestKeys.add(CaptureRequest.JPEG_THUMBNAIL_QUALITY);
requestKeys.add(CaptureRequest.JPEG_THUMBNAIL_SIZE);
- requestKeys.add(CaptureRequest.LENS_FOCUS_DISTANCE);
requestKeys.add(CaptureRequest.SCALER_CROP_REGION);
requestKeys.add(CaptureRequest.STATISTICS_FACE_DETECT_MODE);
if (mStaticInfo.getAeMaxRegionsChecked() > 0) {
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
index b60df08..8dd35f6 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
@@ -572,8 +572,11 @@
if (canSetAfRegion) {
MeteringRectangle[] resultAfRegions =
getValueNotNull(result, CaptureResult.CONTROL_AF_REGIONS);
- mCollector.expectEquals("AF regions in result and request should be same",
- afRegions, resultAfRegions);
+ mCollector.expectMeteringRegionsAreSimilar(
+ "AF regions in result and request should be similar",
+ afRegions,
+ resultAfRegions,
+ METERING_REGION_ERROR_PERCENT_DELTA);
}
if (hasFocuser) {
@@ -680,8 +683,6 @@
dumpFile(rawFileName, rawBuffer);
}
- verifyRawCaptureResult(rawRequest, resultListener.getCaptureResultForRequest(rawRequest,
- NUM_RESULTS_WAIT_TIMEOUT));
stopPreview();
}
@@ -995,8 +996,10 @@
EXIF_TEST_DATA[i].thumbnailQuality,
stillResult.get(CaptureResult.JPEG_THUMBNAIL_QUALITY));
- // Validate other exif tags.
- jpegTestExifExtraTags(exif, maxStillSz, stillResult);
+ // Validate other exif tags for all non-legacy devices
+ if (!mStaticInfo.isHardwareLevelLegacy()) {
+ jpegTestExifExtraTags(exif, maxStillSz, stillResult);
+ }
}
}
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java b/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
index 578d03e..11d7ac0 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
@@ -630,10 +630,15 @@
checkTrueForKey(key, " value must be 0 if only OFF mode is supported in "
+ "availableFaceDetectionModes", count == 0);
} else {
- int maxFaceCountAtLeat = STATISTICS_INFO_MAX_FACE_COUNT_MIN_AT_LEAST;
- checkTrueForKey(key, " value must be no less than " + maxFaceCountAtLeat + " if SIMPLE"
+ int maxFaceCountAtLeast = STATISTICS_INFO_MAX_FACE_COUNT_MIN_AT_LEAST;
+
+ // Legacy mode may support fewer than STATISTICS_INFO_MAX_FACE_COUNT_MIN_AT_LEAST faces.
+ if (isHardwareLevelLegacy()) {
+ maxFaceCountAtLeast = 1;
+ }
+ checkTrueForKey(key, " value must be no less than " + maxFaceCountAtLeast + " if SIMPLE"
+ "or FULL is also supported in availableFaceDetectionModes",
- count >= maxFaceCountAtLeat);
+ count >= maxFaceCountAtLeast);
}
return count;
@@ -1047,8 +1052,11 @@
}
List<Integer> modesList = Arrays.asList(CameraTestUtils.toObject(afModes));
- checkTrueForKey(key, " All camera devices must support OFF mode",
- modesList.contains(CameraMetadata.CONTROL_AF_MODE_OFF));
+ if (isHardwareLevelLimitedOrBetter()) {
+ // Some LEGACY mode devices do not support AF OFF
+ checkTrueForKey(key, " All camera devices must support OFF mode",
+ modesList.contains(CameraMetadata.CONTROL_AF_MODE_OFF));
+ }
if (hasFocuser()) {
checkTrueForKey(key, " Camera devices that have focuser units must support AUTO mode",
modesList.contains(CameraMetadata.CONTROL_AF_MODE_AUTO));
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/rs/AllocationCache.java b/tests/tests/hardware/src/android/hardware/camera2/cts/rs/AllocationCache.java
index e65e819..b89f9bb 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/rs/AllocationCache.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/rs/AllocationCache.java
@@ -74,34 +74,30 @@
* @throws NullPointerException if type was null
* @throws IllegalStateException if the cache was closed with {@link #close}
*/
- public synchronized Allocation getOrCreateTyped(Type type, int usage) {
- checkNotNull("type", type);
- checkNotClosed();
+ public Allocation getOrCreateTyped(Type type, int usage) {
+ synchronized (this) {
+ checkNotNull("type", type);
+ checkNotClosed();
- AllocationKey key = new AllocationKey(type, usage);
- List<Allocation> list = mAllocationMap.get(key);
+ AllocationKey key = new AllocationKey(type, usage);
+ List<Allocation> list = mAllocationMap.get(key);
- Allocation alloc;
-
- if (list == null || list.isEmpty()) {
- alloc = Allocation.createTyped(mRS, type, usage);
-
- if (DEBUG) {
- sDebugMisses++;
- Log.d(TAG, String.format(
- "Cache MISS (%d): type = '%s', usage = '%x'", sDebugMisses, type, usage));
- }
- } else {
- alloc = list.remove(list.size() - 1);
-
- if (DEBUG) {
- sDebugHits++;
- Log.d(TAG, String.format(
- "Cache HIT (%d): type = '%s', usage = '%x'", sDebugHits, type, usage));
- }
+ if (list != null && !list.isEmpty()) {
+ Allocation alloc = list.remove(list.size() - 1);
+ if (DEBUG) {
+ sDebugHits++;
+ Log.d(TAG, String.format(
+ "Cache HIT (%d): type = '%s', usage = '%x'", sDebugHits, type, usage));
+ }
+ return alloc;
+ }
+ if (DEBUG) {
+ sDebugMisses++;
+ Log.d(TAG, String.format(
+ "Cache MISS (%d): type = '%s', usage = '%x'", sDebugMisses, type, usage));
+ }
}
-
- return alloc;
+ return Allocation.createTyped(mRS, type, usage);
}
/**
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java b/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
index 31fe8e3..bcc4061 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
@@ -34,6 +34,7 @@
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCaptureSession.CaptureCallback;
+import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
@@ -679,8 +680,12 @@
Long minDuration = mMinPreviewFrameDurationMap.get(size);
if (minDuration == null ||
minDuration == 0) {
- throw new IllegalArgumentException(
- "No min frame duration available for the selected format.");
+ if (mStaticInfo.isCapabilitySupported(
+ CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR)) {
+ throw new IllegalArgumentException(
+ "No min frame duration available for the size " + size);
+ }
+ continue;
}
if (minDuration <= frameDurationRange[0]) {
return size;
diff --git a/tests/tests/hardware/src/android/hardware/cts/CameraTest.java b/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
index ad16036..3476895 100644
--- a/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/CameraTest.java
@@ -905,7 +905,6 @@
exif = new ExifInterface(JPEG_PATH);
checkGpsDataNull(exif);
assertBitmapAndJpegSizeEqual(mJpegData, exif);
- assertTrue(failedCause.toString(), extraExiftestPassed);
// Reset the rotation to prevent from affecting other tests.
parameters.setRotation(0);
mCamera.setParameters(parameters);
diff --git a/tests/tests/hardware/src/android/hardware/cts/SensorBatchingTests.java b/tests/tests/hardware/src/android/hardware/cts/SensorBatchingTests.java
index 3d66b50..d00194f 100644
--- a/tests/tests/hardware/src/android/hardware/cts/SensorBatchingTests.java
+++ b/tests/tests/hardware/src/android/hardware/cts/SensorBatchingTests.java
@@ -16,12 +16,12 @@
package android.hardware.cts;
-import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.hardware.cts.helpers.SensorCtsHelper;
import android.hardware.cts.helpers.SensorStats;
import android.hardware.cts.helpers.SensorTestInformation;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.sensoroperations.TestSensorFlushOperation;
import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
import android.hardware.cts.helpers.sensoroperations.VerifiableSensorOperation;
@@ -255,36 +255,46 @@
private void runBatchingSensorTest(int sensorType, int rateUs, int maxBatchReportLatencySec)
throws Throwable {
- Context context = getContext();
int maxBatchReportLatencyUs = (int) TimeUnit.SECONDS.toMicros(maxBatchReportLatencySec);
int testDurationSec = maxBatchReportLatencySec + BATCHING_PADDING_TIME_S;
- TestSensorOperation operation = new TestSensorOperation(
- context,
+
+ TestSensorEnvironment environment = new TestSensorEnvironment(
+ getContext(),
+ sensorType,
+ shouldEmulateSensorUnderLoad(),
+ rateUs,
+ maxBatchReportLatencyUs);
+ TestSensorOperation operation =
+ new TestSensorOperation(environment, testDurationSec, TimeUnit.SECONDS);
+
+ executeTest(
+ operation,
sensorType,
rateUs,
maxBatchReportLatencyUs,
- testDurationSec,
- TimeUnit.SECONDS);
-
- boolean flushExpected = false;
- executeTest(operation, sensorType, rateUs, maxBatchReportLatencyUs, flushExpected);
+ false /* flushExpected */);
}
private void runFlushSensorTest(int sensorType, int rateUs, int maxBatchReportLatencySec)
throws Throwable {
- Context context = getContext();
int maxBatchReportLatencyUs = (int) TimeUnit.SECONDS.toMicros(maxBatchReportLatencySec);
int flushDurationSec = maxBatchReportLatencySec / 2;
- TestSensorFlushOperation operation = new TestSensorFlushOperation(
- context,
+
+ TestSensorEnvironment environment = new TestSensorEnvironment(
+ getContext(),
+ sensorType,
+ shouldEmulateSensorUnderLoad(),
+ rateUs,
+ maxBatchReportLatencyUs);
+ TestSensorFlushOperation operation =
+ new TestSensorFlushOperation(environment, flushDurationSec, TimeUnit.SECONDS);
+
+ executeTest(
+ operation,
sensorType,
rateUs,
maxBatchReportLatencyUs,
- flushDurationSec,
- TimeUnit.SECONDS);
-
- boolean flushExpected = true;
- executeTest(operation, sensorType, rateUs, maxBatchReportLatencyUs, flushExpected);
+ true /* flushExpected */);
}
private void executeTest(
diff --git a/tests/tests/hardware/src/android/hardware/cts/SensorIntegrationTests.java b/tests/tests/hardware/src/android/hardware/cts/SensorIntegrationTests.java
index c471b7a..3c9eef9 100644
--- a/tests/tests/hardware/src/android/hardware/cts/SensorIntegrationTests.java
+++ b/tests/tests/hardware/src/android/hardware/cts/SensorIntegrationTests.java
@@ -23,6 +23,7 @@
import android.hardware.SensorManager;
import android.hardware.cts.helpers.SensorCtsHelper;
import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.sensoroperations.ParallelSensorOperation;
import android.hardware.cts.helpers.sensoroperations.RepeatingSensorOperation;
import android.hardware.cts.helpers.sensoroperations.SequentialSensorOperation;
@@ -87,7 +88,7 @@
public void testSensorsWithSeveralClients() throws Throwable {
final int ITERATIONS = 50;
final int MAX_REPORTING_LATENCY_IN_SECONDS = 5;
- final Context context = this.getContext();
+ final Context context = getContext();
int sensorTypes[] = {
Sensor.TYPE_ACCELEROMETER,
@@ -96,21 +97,25 @@
ParallelSensorOperation operation = new ParallelSensorOperation();
for(int sensorType : sensorTypes) {
- TestSensorOperation continuousOperation = new TestSensorOperation(
+ TestSensorEnvironment environment = new TestSensorEnvironment(
context,
sensorType,
- SensorManager.SENSOR_DELAY_FASTEST,
- 0 /* reportLatencyInUs */,
- 100 /* event count */);
+ shouldEmulateSensorUnderLoad(),
+ SensorManager.SENSOR_DELAY_FASTEST);
+ TestSensorOperation continuousOperation =
+ new TestSensorOperation(environment, 100 /* eventCount */);
continuousOperation.addVerification(new EventOrderingVerification());
operation.add(new RepeatingSensorOperation(continuousOperation, ITERATIONS));
- TestSensorOperation batchingOperation = new TestSensorOperation(
+ Sensor sensor = TestSensorEnvironment.getSensor(context, sensorType);
+ TestSensorEnvironment batchingEnvironment = new TestSensorEnvironment(
context,
sensorType,
- SensorCtsHelper.getSensor(getContext(), sensorType).getMinDelay(),
- SensorCtsHelper.getSecondsAsMicroSeconds(MAX_REPORTING_LATENCY_IN_SECONDS),
- 100);
+ shouldEmulateSensorUnderLoad(),
+ sensor.getMinDelay(),
+ SensorCtsHelper.getSecondsAsMicroSeconds(MAX_REPORTING_LATENCY_IN_SECONDS));
+ TestSensorOperation batchingOperation =
+ new TestSensorOperation(batchingEnvironment, 100 /* eventCount */);
batchingOperation.addVerification(new EventOrderingVerification());
operation.add(new RepeatingSensorOperation(batchingOperation, ITERATIONS));
}
@@ -150,16 +155,19 @@
Sensor.TYPE_MAGNETIC_FIELD,
Sensor.TYPE_GYROSCOPE };
+ Context context = getContext();
for(int sensorType : sensorTypes) {
for(int instance = 0; instance < INSTANCES_TO_USE; ++instance) {
SequentialSensorOperation sequentialOperation = new SequentialSensorOperation();
for(int iteration = 0; iteration < ITERATIONS_TO_EXECUTE; ++iteration) {
- TestSensorOperation sensorOperation = new TestSensorOperation(
- this.getContext(),
+ TestSensorEnvironment environment = new TestSensorEnvironment(
+ context,
sensorType,
- this.generateSamplingRateInUs(sensorType),
- this.generateReportLatencyInUs(),
- 100);
+ shouldEmulateSensorUnderLoad(),
+ generateSamplingRateInUs(sensorType),
+ generateReportLatencyInUs());
+ TestSensorOperation sensorOperation =
+ new TestSensorOperation(environment, 100 /* eventCount */);
sensorOperation.addVerification(new EventOrderingVerification());
sequentialOperation.add(sensorOperation);
}
@@ -216,22 +224,24 @@
* of several clients can lead to the failing state.
*/
public void testSensorStoppingInteraction() throws Throwable {
- Context context = this.getContext();
+ Context context = getContext();
- TestSensorOperation tester = new TestSensorOperation(
+ TestSensorEnvironment testerEnvironment = new TestSensorEnvironment(
context,
mSensorTypeTester,
- SensorManager.SENSOR_DELAY_FASTEST,
- 0 /*reportLatencyInUs*/,
- 100 /* event count */);
+ shouldEmulateSensorUnderLoad(),
+ SensorManager.SENSOR_DELAY_FASTEST);
+ TestSensorOperation tester =
+ new TestSensorOperation(testerEnvironment, 100 /* event count */);
tester.addVerification(new EventOrderingVerification());
- VerifiableSensorOperation testee = new TestSensorOperation(
+ TestSensorEnvironment testeeEnvironment = new TestSensorEnvironment(
context,
mSensorTypeTestee,
- SensorManager.SENSOR_DELAY_FASTEST,
- 0 /*reportLatencyInUs*/,
- 100 /* event count */);
+ shouldEmulateSensorUnderLoad(),
+ SensorManager.SENSOR_DELAY_FASTEST);
+ VerifiableSensorOperation testee =
+ new TestSensorOperation(testeeEnvironment, 100 /* event count */);
testee.addVerification(new EventOrderingVerification());
ParallelSensorOperation operation = new ParallelSensorOperation();
@@ -256,8 +266,8 @@
rate = SensorManager.SENSOR_DELAY_FASTEST;
break;
default:
- int maxSamplingRate = SensorCtsHelper.getSensor(getContext(), sensorType)
- .getMinDelay();
+ Sensor sensor = TestSensorEnvironment.getSensor(getContext(), sensorType);
+ int maxSamplingRate = sensor.getMinDelay();
rate = maxSamplingRate * mGenerator.nextInt(10);
}
return rate;
diff --git a/tests/tests/hardware/src/android/hardware/cts/SensorTestCase.java b/tests/tests/hardware/src/android/hardware/cts/SensorTestCase.java
index aee00ed..6454678 100644
--- a/tests/tests/hardware/src/android/hardware/cts/SensorTestCase.java
+++ b/tests/tests/hardware/src/android/hardware/cts/SensorTestCase.java
@@ -22,8 +22,11 @@
import android.app.Instrumentation;
import android.cts.util.DeviceReportLog;
-import android.hardware.cts.helpers.SensorNotSupportedException;
+import android.hardware.Sensor;
import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.SensorTestStateNotSupportedException;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.sensoroperations.ISensorOperation;
import android.test.AndroidTestCase;
import android.util.Log;
@@ -34,18 +37,37 @@
// TODO: consolidate all log tags
protected final String LOG_TAG = "TestRunner";
+ /**
+ * By default tests need to run in a {@link TestSensorEnvironment} that assumes each sensor is
+ * running with a load of several listeners, requesting data at different rates.
+ *
+ * In a better world the component acting as builder of {@link ISensorOperation} would compute
+ * this value based on the tests composed.
+ *
+ * Ideally, each {@link Sensor} object would expose this information to clients.
+ */
+ private volatile boolean mEmulateSensorUnderLoad = true;
+
protected SensorTestCase() {}
@Override
public void runTest() throws Throwable {
try {
super.runTest();
- } catch (SensorNotSupportedException e) {
- // the sensor is not supported/available in the device, log a warning and skip the test
+ } catch (SensorTestStateNotSupportedException e) {
+ // the sensor state is not supported in the device, log a warning and skip the test
Log.w(LOG_TAG, e.getMessage());
}
}
+ public void setEmulateSensorUnderLoad(boolean value) {
+ mEmulateSensorUnderLoad = value;
+ }
+
+ protected boolean shouldEmulateSensorUnderLoad() {
+ return mEmulateSensorUnderLoad;
+ }
+
/**
* Utility method to log selected stats to a {@link ReportLog} object. The stats must be
* a number or an array of numbers.
diff --git a/tests/tests/hardware/src/android/hardware/cts/SingleSensorTests.java b/tests/tests/hardware/src/android/hardware/cts/SingleSensorTests.java
index 866e556..a323ffa 100644
--- a/tests/tests/hardware/src/android/hardware/cts/SingleSensorTests.java
+++ b/tests/tests/hardware/src/android/hardware/cts/SingleSensorTests.java
@@ -16,11 +16,13 @@
package android.hardware.cts;
+import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.hardware.cts.helpers.SensorCtsHelper;
import android.hardware.cts.helpers.SensorStats;
import android.hardware.cts.helpers.SensorTestInformation;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.sensoroperations.TestSensorOperation;
import java.util.HashMap;
@@ -110,15 +112,20 @@
expectedProperties.put(Sensor.TYPE_GYROSCOPE, new Object[]{10000});
expectedProperties.put(Sensor.TYPE_MAGNETIC_FIELD, new Object[]{100000});
+ SensorManager sensorManager =
+ (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
+ assertNotNull("SensorManager not present in the system.", sensorManager);
for (Entry<Integer, Object[]> entry : expectedProperties.entrySet()) {
- Sensor sensor = SensorCtsHelper.getSensor(getContext(), entry.getKey());
- String sensorName = SensorTestInformation.getSensorName(entry.getKey());
- if (entry.getValue()[0] != null) {
- int expected = (Integer) entry.getValue()[0];
- String msg = String.format(
- "%s: min delay %dus expected to be less than or equal to %dus",
- sensorName, sensor.getMinDelay(), expected);
- assertTrue(msg, sensor.getMinDelay() <= expected);
+ Sensor sensor = sensorManager.getDefaultSensor(entry.getKey());
+ if (sensor != null) {
+ String sensorName = SensorTestInformation.getSensorName(entry.getKey());
+ if (entry.getValue()[0] != null) {
+ int expected = (Integer) entry.getValue()[0];
+ String msg = String.format(
+ "%s: min delay %dus expected to be less than or equal to %dus",
+ sensorName, sensor.getMinDelay(), expected);
+ assertTrue(msg, sensor.getMinDelay() <= expected);
+ }
}
}
}
@@ -529,10 +536,13 @@
runSensorTest(Sensor.TYPE_LINEAR_ACCELERATION, RATE_1HZ);
}
- private void runSensorTest(int sensorType, int rateUs)
- throws Throwable {
- TestSensorOperation op = new TestSensorOperation(this.getContext(), sensorType,
- rateUs, 0 /* maxBatchReportLatencyUs */, 5, TimeUnit.SECONDS);
+ private void runSensorTest(int sensorType, int rateUs) throws Throwable {
+ TestSensorEnvironment environment = new TestSensorEnvironment(
+ getContext(),
+ sensorType,
+ shouldEmulateSensorUnderLoad(),
+ rateUs);
+ TestSensorOperation op = new TestSensorOperation(environment, 5, TimeUnit.SECONDS);
op.addDefaultVerifications();
op.setLogEvents(true);
try {
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/ActivityResultMultiplexedLatch.java b/tests/tests/hardware/src/android/hardware/cts/helpers/ActivityResultMultiplexedLatch.java
new file mode 100644
index 0000000..b5491a7
--- /dev/null
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/ActivityResultMultiplexedLatch.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2014 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.hardware.cts.helpers;
+
+import android.app.Activity;
+import android.util.Log;
+
+import java.util.HashMap;
+import java.util.concurrent.CountDownLatch;
+
+/**
+ * An abstraction on top of {@link CountDownLatch} to synchronize the results of Activities
+ * started by a parent activity.
+ *
+ * It holds a {@link CountDownLatch} latch for each thread that requests synchronization.
+ *
+ * Each thread requests a {@link Latch} to synchronize an Activity that will be started, by invoking
+ * {@link #bindThread()}, this guarantees that a latch is associated with the thread, and the result
+ * can be retrieved.
+ */
+public class ActivityResultMultiplexedLatch {
+ private static final String TAG = "ActivityResultMultiplexedLatch";
+
+ private final HashMap<Integer, Entry> mActivityEntries = new HashMap<Integer, Entry>();
+
+ /**
+ * A latch for a bound thread.
+ * Applications get an instance by invoking {@link ActivityResultMultiplexedLatch#bindThread()}.
+ */
+ public class Latch {
+ private Entry mEntry;
+
+ private Latch(Entry entry) {
+ mEntry = entry;
+ }
+
+ /**
+ * Awaits for the Activity bound to unblock the current thread.
+ *
+ * @return The result code of the Activity executed.
+ */
+ public int await() {
+ try {
+ mEntry.latch.await();
+ } catch (InterruptedException e) {
+ Log.e(TAG, "Error waiting for Activity result.", e);
+ return Activity.RESULT_CANCELED;
+ }
+ return mEntry.resultCode;
+ }
+
+ /**
+ * @return A request code for the bound thread. It can be passed to the Activity to start.
+ */
+ public int getRequestCode() {
+ return mEntry.requestCode;
+ }
+ }
+
+ /**
+ * A class that represents the state for each thread/Activity being tracked.
+ */
+ private class Entry {
+ public final CountDownLatch latch = new CountDownLatch(1);
+ public final int requestCode;
+
+ public volatile int resultCode;
+
+ public Entry(int requestCode) {
+ this.requestCode = requestCode;
+ }
+ }
+
+ /**
+ * Binds a thread with this object.
+ *
+ * @return A request code (or session Id) for the bound thread.
+ */
+ public Latch bindThread() {
+ Entry entry;
+ int requestCode = getRequestCode();
+
+ synchronized (mActivityEntries) {
+ if (mActivityEntries.containsKey(requestCode)) {
+ throw new IllegalStateException("The thread has already been bound.");
+ }
+ entry = new Entry(requestCode);
+ mActivityEntries.put(requestCode, entry);
+ }
+
+ return new Latch(entry);
+ }
+
+ /**
+ * Used by the owner of the instance to record an Activity's result.
+ */
+ public void onActivityResult(int requestCode, int resultCode) {
+ Entry entry;
+ synchronized (mActivityEntries) {
+ entry = mActivityEntries.get(requestCode);
+ }
+ if (entry == null) {
+ return;
+ }
+
+ entry.resultCode = resultCode;
+ entry.latch.countDown();
+ }
+
+ // there is no need for a better request Id, only one Activity can be launched at any time
+ private int getRequestCode() {
+ return Thread.currentThread().hashCode();
+ }
+}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCtsHelper.java b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCtsHelper.java
index b3f9fec..52f37e8 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCtsHelper.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorCtsHelper.java
@@ -15,10 +15,6 @@
*/
package android.hardware.cts.helpers;
-import android.content.Context;
-import android.hardware.Sensor;
-import android.hardware.SensorManager;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -104,30 +100,6 @@
}
/**
- * Get the default sensor for a given type.
- */
- public static Sensor getSensor(Context context, int sensorType) {
- SensorManager sensorManager = getSensorManager(context);
- Sensor sensor = sensorManager.getDefaultSensor(sensorType);
- if(sensor == null) {
- throw new SensorNotSupportedException(sensorType);
- }
- return sensor;
- }
-
- /**
- * Get all the sensors for a given type.
- */
- public static List<Sensor> getSensors(Context context, int sensorType) {
- SensorManager sensorManager = getSensorManager(context);
- List<Sensor> sensors = sensorManager.getSensorList(sensorType);
- if (sensors.size() == 0) {
- throw new SensorNotSupportedException(sensorType);
- }
- return sensors;
- }
-
- /**
* Convert a period to frequency in Hz.
*/
public static <TValue extends Number> double getFrequency(TValue period, TimeUnit unit) {
@@ -149,37 +121,6 @@
}
/**
- * Convert the sensor delay or rate in microseconds into delay in microseconds.
- * <p>
- * The flags SensorManager.SENSOR_DELAY_[GAME|UI|NORMAL] are not supported since the CDD does
- * not specify values for these flags. The rate is set to the max of
- * {@link Sensor#getMinDelay()} and the rate given.
- * </p>
- */
- public static int getDelay(Sensor sensor, int rateUs) {
- if (!isDelayRateTestable(rateUs)) {
- throw new IllegalArgumentException("rateUs cannot be SENSOR_DELAY_[GAME|UI|NORMAL]");
- }
- int delay;
- if (rateUs == SensorManager.SENSOR_DELAY_FASTEST) {
- delay = 0;
- } else {
- delay = rateUs;
- }
- return Math.max(delay, sensor.getMinDelay());
- }
-
- /**
- * Return true if the operation rate is not one of {@link SensorManager#SENSOR_DELAY_GAME},
- * {@link SensorManager#SENSOR_DELAY_UI}, or {@link SensorManager#SENSOR_DELAY_NORMAL}.
- */
- public static boolean isDelayRateTestable(int rateUs) {
- return (rateUs != SensorManager.SENSOR_DELAY_GAME
- && rateUs != SensorManager.SENSOR_DELAY_UI
- && rateUs != SensorManager.SENSOR_DELAY_NORMAL);
- }
-
- /**
* Helper method to sleep for a given duration.
*/
public static void sleep(long duration, TimeUnit timeUnit) {
@@ -194,34 +135,53 @@
/**
* Format an assertion message.
*
- * @param sensor the {@link Sensor}
* @param label the verification name
- * @param rateUs the rate of the sensor
- * @param maxBatchReportLatencyUs the max batch report latency of the sensor
+ * @param environment the environment of the test
+ *
* @return The formatted string
*/
- public static String formatAssertionMessage(Sensor sensor, String label, int rateUs,
- int maxBatchReportLatencyUs) {
- return String.format("%s | %s", label,
- SensorTestInformation.getSensorName(sensor.getType()));
+ public static String formatAssertionMessage(String label, TestSensorEnvironment environment) {
+ return formatAssertionMessage(label, environment, "");
}
/**
* Format an assertion message with a custom message.
*
- * @param sensor the {@link Sensor}
* @param label the verification name
- * @param rateUs the rate of the sensor
- * @param maxBatchReportLatencyUs the max batch report latency of the sensor
+ * @param environment the environment of the test
* @param format the additional format string
* @param params the additional format params
+ *
* @return The formatted string
*/
- public static String formatAssertionMessage(Sensor sensor, String label, int rateUs,
- int maxBatchReportLatencyUs, String format, Object ... params) {
- return String.format("%s | %s, rateUs: %d, maxBatchReportLatencyUs: %d | %s",
- label, SensorTestInformation.getSensorName(sensor.getType()),
- rateUs, maxBatchReportLatencyUs, String.format(format, params));
+ public static String formatAssertionMessage(
+ String label,
+ TestSensorEnvironment environment,
+ String format,
+ Object ... params) {
+ return formatAssertionMessage(label, environment, String.format(format, params));
+ }
+
+ /**
+ * Format an assertion message.
+ *
+ * @param label the verification name
+ * @param environment the environment of the test
+ * @param extras the additional information for the assertion
+ *
+ * @return The formatted string
+ */
+ public static String formatAssertionMessage(
+ String label,
+ TestSensorEnvironment environment,
+ String extras) {
+ return String.format(
+ "%s | sensor=%s, rateUs=%d, maxBatchReportLatenchUs=%d | %s",
+ label,
+ SensorTestInformation.getSensorName(environment.getSensor().getType()),
+ environment.getRequestedSamplingPeriodUs(),
+ environment.getMaxReportLatencyUs(),
+ extras);
}
/**
@@ -234,18 +194,4 @@
throw new IllegalStateException("Collection cannot be null or empty");
}
}
-
- /**
- * Get the SensorManager.
- *
- * @throws IllegalStateException if the SensorManager is not present in the system.
- */
- private static SensorManager getSensorManager(Context context) {
- SensorManager sensorManager = (SensorManager) context.getSystemService(
- Context.SENSOR_SERVICE);
- if(sensorManager == null) {
- throw new IllegalStateException("SensorService is not present in the system.");
- }
- return sensorManager;
- }
}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorNotSupportedException.java b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorNotSupportedException.java
index 4c413d7..53e4cae 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorNotSupportedException.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorNotSupportedException.java
@@ -18,14 +18,11 @@
/**
* Exception that indicates that a given sensor is not supported in the device.
- * This exception can be caught in tests to safely ignore test cases that are not necessary in a
- * given environment.
*/
-public class SensorNotSupportedException extends RuntimeException {
+public class SensorNotSupportedException extends SensorTestStateNotSupportedException {
public SensorNotSupportedException(int sensorType) {
- super(String.format(
- "Sensor '%s' of type %d is not supported.",
+ super("Sensor '%s' of type %d is not supported.",
SensorTestInformation.getSensorName(sensorType),
- sensorType));
+ sensorType);
}
}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorTestInformation.java b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorTestInformation.java
index b220b00..86c164d 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorTestInformation.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorTestInformation.java
@@ -25,41 +25,8 @@
public class SensorTestInformation {
private SensorTestInformation() {}
- public enum SensorReportingMode {
- CONTINUOUS,
- ON_CHANGE,
- ONE_SHOT,
- }
-
- @SuppressWarnings("deprecation")
- public static SensorReportingMode getReportingMode(int sensorType) {
- switch(sensorType) {
- case Sensor.TYPE_ACCELEROMETER:
- case Sensor.TYPE_MAGNETIC_FIELD:
- case Sensor.TYPE_ORIENTATION:
- case Sensor.TYPE_GYROSCOPE:
- case Sensor.TYPE_PRESSURE:
- case Sensor.TYPE_GRAVITY:
- case Sensor.TYPE_LINEAR_ACCELERATION:
- case Sensor.TYPE_ROTATION_VECTOR:
- case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
- case Sensor.TYPE_GAME_ROTATION_VECTOR:
- case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:
- case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR:
- return SensorReportingMode.CONTINUOUS;
- case Sensor.TYPE_LIGHT:
- case Sensor.TYPE_TEMPERATURE:
- case Sensor.TYPE_PROXIMITY:
- case Sensor.TYPE_RELATIVE_HUMIDITY:
- case Sensor.TYPE_AMBIENT_TEMPERATURE:
- case Sensor.TYPE_STEP_DETECTOR:
- case Sensor.TYPE_STEP_COUNTER:
- return SensorReportingMode.ON_CHANGE;
- case Sensor.TYPE_SIGNIFICANT_MOTION:
- return SensorReportingMode.ONE_SHOT;
- default:
- return null;
- }
+ public static String getSensorName(Sensor sensor) {
+ return getSensorName(sensor.getType());
}
public static String getSensorName(int sensorType) {
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/SensorTestStateNotSupportedException.java b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorTestStateNotSupportedException.java
new file mode 100644
index 0000000..435632d
--- /dev/null
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/SensorTestStateNotSupportedException.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2014 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.hardware.cts.helpers;
+
+/**
+ * Exception that indicates that a given state in sensor tests is not supported in the device.
+ * This exception can be caught in tests to safely ignore test cases that are not necessary in a
+ * given environment.
+ */
+public class SensorTestStateNotSupportedException extends RuntimeException {
+ public SensorTestStateNotSupportedException(String format, Object ... params) {
+ super(String.format(format, params));
+ }
+
+ public SensorTestStateNotSupportedException(String message) {
+ super(message);
+ }
+}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEnvironment.java b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEnvironment.java
new file mode 100644
index 0000000..c45d640
--- /dev/null
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEnvironment.java
@@ -0,0 +1,267 @@
+/*
+ * Copyright (C) 2014 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.hardware.cts.helpers;
+
+import android.content.Context;
+import android.hardware.Sensor;
+import android.hardware.SensorManager;
+import android.hardware.cts.helpers.sensoroperations.ISensorOperation;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * A class that encapsulates base environment information for the {@link ISensorOperation}.
+ * The environment is self contained and carries its state around all the sensor test framework.
+ */
+public class TestSensorEnvironment {
+ private final Context mContext;
+ private final Sensor mSensor;
+ private final boolean mSensorMightHaveMoreListeners;
+ private final int mSamplingPeriodUs;
+ private final int mMaxReportLatencyUs;
+
+ /**
+ * Constructs an environment for sensor testing.
+ *
+ * @param context The context for the test
+ * @param sensorType The type of the sensor under test
+ * @param samplingPeriodUs The requested collection period for the sensor under test
+ */
+ public TestSensorEnvironment(Context context, int sensorType, int samplingPeriodUs) {
+ this(context, sensorType, false /* sensorMightHaveMoreListeners */, samplingPeriodUs);
+ }
+
+ /**
+ * Constructs an environment for sensor testing.
+ *
+ * @param context The context for the test
+ * @param sensorType The type of the sensor under test
+ * @param samplingPeriodUs The requested collection period for the sensor under test
+ * @param maxReportLatencyUs The requested collection report latency for the sensor under test
+ */
+ public TestSensorEnvironment(
+ Context context,
+ int sensorType,
+ int samplingPeriodUs,
+ int maxReportLatencyUs) {
+ this(context,
+ sensorType,
+ false /* sensorMightHaveMoreListeners */,
+ samplingPeriodUs,
+ maxReportLatencyUs);
+ }
+
+ /**
+ * Constructs an environment for sensor testing.
+ *
+ * @param context The context for the test
+ * @param sensorType The type of the sensor under test
+ * @param sensorMightHaveMoreListeners Whether the sensor under test is acting under load
+ * @param samplingPeriodUs The requested collection period for the sensor under test
+ */
+ public TestSensorEnvironment(
+ Context context,
+ int sensorType,
+ boolean sensorMightHaveMoreListeners,
+ int samplingPeriodUs) {
+ this(context,
+ sensorType,
+ sensorMightHaveMoreListeners,
+ samplingPeriodUs,
+ 0 /* maxReportLatencyUs */);
+ }
+
+ /**
+ * Constructs an environment for sensor testing.
+ *
+ * @param context The context for the test
+ * @param sensorType The type of the sensor under test
+ * @param sensorMightHaveMoreListeners Whether the sensor under test is acting under load
+ * @param samplingPeriodUs The requested collection period for the sensor under test
+ * @param maxReportLatencyUs The requested collection report latency for the sensor under test
+ */
+ public TestSensorEnvironment(
+ Context context,
+ int sensorType,
+ boolean sensorMightHaveMoreListeners,
+ int samplingPeriodUs,
+ int maxReportLatencyUs) {
+ this(context,
+ getSensor(context, sensorType),
+ sensorMightHaveMoreListeners,
+ samplingPeriodUs,
+ maxReportLatencyUs);
+ }
+
+ /**
+ * Constructs an environment for sensor testing.
+ *
+ * @param context The context for the test
+ * @param sensor The sensor under test
+ * @param sensorMightHaveMoreListeners Whether the sensor under test is acting under load (this
+ * usually implies that there are several listeners
+ * requesting different sampling periods)
+ * @param samplingPeriodUs The requested collection period for the sensor under test
+ * @param maxReportLatencyUs The requested collection report latency for the sensor under test
+ */
+ public TestSensorEnvironment(
+ Context context,
+ Sensor sensor,
+ boolean sensorMightHaveMoreListeners,
+ int samplingPeriodUs,
+ int maxReportLatencyUs) {
+ mContext = context;
+ mSensor = sensor;
+ mSensorMightHaveMoreListeners = sensorMightHaveMoreListeners;
+ mSamplingPeriodUs = samplingPeriodUs;
+ mMaxReportLatencyUs = maxReportLatencyUs;
+ }
+
+ /**
+ * @return The context instance associated with the test.
+ */
+ public Context getContext() {
+ return mContext;
+ }
+
+ /**
+ * @return The sensor under test.
+ */
+ public Sensor getSensor() {
+ return mSensor;
+ }
+
+ /**
+ * @return The requested collection rate in microseconds.
+ */
+ public int getRequestedSamplingPeriodUs() {
+ return mSamplingPeriodUs;
+ }
+
+ /**
+ * @return The frequency equivalent to {@link #getRequestedSamplingPeriodUs()}.
+ */
+ public double getFrequencyHz() {
+ return SensorCtsHelper.getFrequency(mSamplingPeriodUs, TimeUnit.MICROSECONDS);
+ }
+
+ /**
+ * @return The requested collection max batch report latency in microseconds.
+ */
+ public int getMaxReportLatencyUs() {
+ return mMaxReportLatencyUs;
+ }
+
+ /**
+ * Returns {@code true} if there might be other listeners of {@link #getSensor()} requesting
+ * data at different sampling rates (the rates are unknown); false otherwise.
+ */
+ public boolean isSensorSamplingRateOverloaded() {
+ return mSensorMightHaveMoreListeners && mSamplingPeriodUs != SensorManager.SENSOR_DELAY_FASTEST;
+ }
+
+ /**
+ * Convert the {@link #getRequestedSamplingPeriodUs()} into delay in microseconds.
+ * <p>
+ * The flags SensorManager.SENSOR_DELAY_[GAME|UI|NORMAL] are not supported since the CDD does
+ * not specify values for these flags. The rate is set to the max of
+ * {@link Sensor#getMinDelay()} and the rate given.
+ * </p>
+ */
+ public int getExpectedSamplingPeriodUs() {
+ if (!isDelayRateTestable()) {
+ throw new IllegalArgumentException("rateUs cannot be SENSOR_DELAY_[GAME|UI|NORMAL]");
+ }
+
+ int expectedSamplingPeriodUs = mSamplingPeriodUs;
+ int sensorMaxDelay = mSensor.getMaxDelay();
+ if (sensorMaxDelay > 0) {
+ expectedSamplingPeriodUs = Math.min(expectedSamplingPeriodUs, sensorMaxDelay);
+ }
+
+ return Math.max(expectedSamplingPeriodUs, mSensor.getMinDelay());
+ }
+
+ /**
+ * Get the default sensor for a given type.
+ *
+ * @deprecated Used for historical reasons, sensor tests must be written around Sensor objects,
+ * so all sensors of a given type are exercised.
+ */
+ @Deprecated
+ public static Sensor getSensor(Context context, int sensorType) {
+ SensorManager sensorManager =
+ (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
+ if (sensorManager == null) {
+ throw new IllegalStateException("SensorService is not present in the system.");
+ }
+
+ Sensor sensor = sensorManager.getDefaultSensor(sensorType);
+ if(sensor == null) {
+ throw new SensorNotSupportedException(sensorType);
+ }
+ return sensor;
+ }
+
+ /**
+ * @return The maximum latency of a given sensor, on top of {@link #getMaxReportLatencyUs()}.
+ *
+ * NOTE: The latency is defined as the time between the event happens and the time the event is
+ * generated.
+ *
+ * - At time event_time (reported in the sensor event), the physical event happens
+ * - At time event_time + detection_latency, the physical event is detected and the event is
+ * saved in the hardware fifo
+ * - At time event_time + detection_latency + report_latency, the event is reported through the
+ * HAL
+ *
+ * Soon after that, the event is piped through the framework to the application. This time may
+ * vary depending on the CPU load. The time 'detection_latency' must be less than
+ * {@link #getSensorMaxDetectionLatencyNs(Sensor)}, and 'report_latency' must be less than
+ * {@link #getMaxReportLatencyUs()} passed through batch() at the HAL level.
+ */
+ // TODO: when all tests are moved to use the Sensor test framework, make this method non-static
+ public static long getSensorMaxDetectionLatencyNs(Sensor sensor) {
+ int reportLatencySec;
+ switch (sensor.getType()) {
+ case Sensor.TYPE_STEP_DETECTOR:
+ reportLatencySec = 2;
+ break;
+ case Sensor.TYPE_STEP_COUNTER:
+ reportLatencySec = 10;
+ break;
+ case Sensor.TYPE_SIGNIFICANT_MOTION:
+ reportLatencySec = 10;
+ break;
+ default:
+ reportLatencySec = 0;
+ }
+ return TimeUnit.SECONDS.toNanos(reportLatencySec);
+ }
+
+ /**
+ * Return true if {@link #getRequestedSamplingPeriodUs()} is not one of
+ * {@link SensorManager#SENSOR_DELAY_GAME}, {@link SensorManager#SENSOR_DELAY_UI}, or
+ * {@link SensorManager#SENSOR_DELAY_NORMAL}.
+ */
+ private boolean isDelayRateTestable() {
+ return (mSamplingPeriodUs >= 0
+ && mSamplingPeriodUs != SensorManager.SENSOR_DELAY_GAME
+ && mSamplingPeriodUs != SensorManager.SENSOR_DELAY_UI
+ && mSamplingPeriodUs != SensorManager.SENSOR_DELAY_NORMAL);
+ }
+}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEventListener.java b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEventListener.java
index f06b9d7..5197184 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEventListener.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorEventListener.java
@@ -40,13 +40,10 @@
private final SensorEventListener2 mListener;
- private volatile CountDownLatch mEventLatch = null;
+ private volatile CountDownLatch mEventLatch;
private volatile CountDownLatch mFlushLatch = new CountDownLatch(1);
-
- private Sensor mSensor = null;
- private int mRateUs = 0;
- private int mMaxBatchReportLatencyUs = 0;
- private boolean mLogEvents = false;
+ private volatile TestSensorEnvironment mEnvironment;
+ private volatile boolean mLogEvents;
/**
* Construct a {@link TestSensorEventListener}.
@@ -74,10 +71,8 @@
/**
* Set the sensor, rate, and batch report latency used for the assertions.
*/
- public void setSensorInfo(Sensor sensor, int rateUs, int maxBatchReportLatencyUs) {
- mSensor = sensor;
- mRateUs = rateUs;
- mMaxBatchReportLatencyUs = maxBatchReportLatencyUs;
+ public void setEnvironment(TestSensorEnvironment environment) {
+ mEnvironment = environment;
}
/**
@@ -111,7 +106,9 @@
Log.v(LOG_TAG, String.format(
"Sensor %d: sensor_timestamp=%d, received_timestamp=%d, values=%s",
- mSensor.getType(), event.timestamp, System.nanoTime(),
+ mEnvironment.getSensor().getType(),
+ event.timestamp,
+ System.nanoTime(),
Arrays.toString(event.values)));
}
}
@@ -146,9 +143,9 @@
CountDownLatch latch = mFlushLatch;
try {
if(latch != null) {
- String message = SensorCtsHelper.formatAssertionMessage(mSensor, "WaitForFlush",
- mRateUs, mMaxBatchReportLatencyUs);
- Assert.assertTrue(message, latch.await(FLUSH_TIMEOUT_US, TimeUnit.MICROSECONDS));
+ Assert.assertTrue(
+ SensorCtsHelper.formatAssertionMessage("WaitForFlush", mEnvironment),
+ latch.await(FLUSH_TIMEOUT_US, TimeUnit.MICROSECONDS));
}
} catch(InterruptedException e) {
// Ignore
@@ -163,14 +160,17 @@
public void waitForEvents(int eventCount) {
mEventLatch = new CountDownLatch(eventCount);
try {
- int rateUs = SensorCtsHelper.getDelay(mSensor, mRateUs);
+ int rateUs = mEnvironment.getExpectedSamplingPeriodUs();
// Timeout is 2 * event count * expected period + batch timeout + default wait
long timeoutUs = ((2 * eventCount * rateUs)
- + mMaxBatchReportLatencyUs + EVENT_TIMEOUT_US);
+ + mEnvironment.getMaxReportLatencyUs()
+ + EVENT_TIMEOUT_US);
- String message = SensorCtsHelper.formatAssertionMessage(mSensor, "WaitForEvents",
- mRateUs, mMaxBatchReportLatencyUs, "count:%d, available:%d", eventCount,
- mEventLatch.getCount());
+ String message = SensorCtsHelper.formatAssertionMessage(
+ "WaitForEvents",
+ mEnvironment,
+ "count:%d, available:%d",
+ eventCount, mEventLatch.getCount());
Assert.assertTrue(message, mEventLatch.await(timeoutUs, TimeUnit.MICROSECONDS));
} catch(InterruptedException e) {
// Ignore
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorManager.java b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorManager.java
index 1c1ea1c..a62107b 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorManager.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/TestSensorManager.java
@@ -53,21 +53,29 @@
private static final String LOG_TAG = "TestSensorManager";
private final SensorManager mSensorManager;
- private final Sensor mSensor;
- private final int mRateUs;
- private final int mMaxBatchReportLatencyUs;
+ private final TestSensorEnvironment mEnvironment;
- private TestSensorEventListener mTestSensorEventListener = null;
+ private TestSensorEventListener mTestSensorEventListener;
+
+ /**
+ * @Deprecated Use {@link #TestSensorManager(TestSensorEnvironment)} instead.
+ */
+ @Deprecated
+ public TestSensorManager(
+ Context context,
+ int sensorType,
+ int rateUs,
+ int maxBatchReportLatencyUs) {
+ this(new TestSensorEnvironment(context, sensorType, rateUs, maxBatchReportLatencyUs));
+ }
/**
* Construct a {@link TestSensorManager}.
*/
- public TestSensorManager(Context context, int sensorType, int rateUs,
- int maxBatchReportLatencyUs) {
- mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
- mSensor = SensorCtsHelper.getSensor(context, sensorType);
- mRateUs = rateUs;
- mMaxBatchReportLatencyUs = maxBatchReportLatencyUs;
+ public TestSensorManager(TestSensorEnvironment environment) {
+ mSensorManager =
+ (SensorManager) environment.getContext().getSystemService(Context.SENSOR_SERVICE);
+ mEnvironment = environment;
}
/**
@@ -83,12 +91,14 @@
}
mTestSensorEventListener = listener != null ? listener : new TestSensorEventListener();
- mTestSensorEventListener.setSensorInfo(mSensor, mRateUs, mMaxBatchReportLatencyUs);
+ mTestSensorEventListener.setEnvironment(mEnvironment);
- String message = SensorCtsHelper.formatAssertionMessage(mSensor, "registerListener",
- mRateUs, mMaxBatchReportLatencyUs);
- boolean result = mSensorManager.registerListener(mTestSensorEventListener, mSensor, mRateUs,
- mMaxBatchReportLatencyUs);
+ String message = SensorCtsHelper.formatAssertionMessage("registerListener", mEnvironment);
+ boolean result = mSensorManager.registerListener(
+ mTestSensorEventListener,
+ mEnvironment.getSensor(),
+ mEnvironment.getRequestedSamplingPeriodUs(),
+ mEnvironment.getMaxReportLatencyUs());
Assert.assertTrue(message, result);
}
@@ -101,7 +111,9 @@
return;
}
- mSensorManager.unregisterListener(mTestSensorEventListener, mSensor);
+ mSensorManager.unregisterListener(
+ mTestSensorEventListener,
+ mEnvironment.getSensor());
mTestSensorEventListener = null;
}
@@ -140,9 +152,9 @@
return;
}
- String message = SensorCtsHelper.formatAssertionMessage(mSensor, "Flush", mRateUs,
- mMaxBatchReportLatencyUs);
- Assert.assertTrue(message, mSensorManager.flush(mTestSensorEventListener));
+ Assert.assertTrue(
+ SensorCtsHelper.formatAssertionMessage("Flush", mEnvironment),
+ mSensorManager.flush(mTestSensorEventListener));
}
/**
@@ -234,11 +246,4 @@
unregisterListener();
}
}
-
- /**
- * Get the sensor under test.
- */
- public Sensor getSensor() {
- return mSensor;
- }
}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorFlushOperation.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorFlushOperation.java
index 135d674..1fb6bef 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorFlushOperation.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorFlushOperation.java
@@ -16,7 +16,7 @@
package android.hardware.cts.helpers.sensoroperations;
-import android.content.Context;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEventListener;
import java.util.concurrent.TimeUnit;
@@ -36,21 +36,15 @@
/**
* Create a {@link TestSensorOperation}.
*
- * @param context the {@link Context}.
- * @param sensorType the sensor type
- * @param rateUs the rate that
- * @param maxBatchReportLatencyUs the max batch report latency
+ * @param environment the test environment
* @param duration the duration to gather events before calling {@code SensorManager.flush()}
* @param timeUnit the time unit of the duration
*/
public TestSensorFlushOperation(
- Context context,
- int sensorType,
- int rateUs,
- int maxBatchReportLatencyUs,
+ TestSensorEnvironment environment,
long duration,
TimeUnit timeUnit) {
- super(context, sensorType, rateUs, maxBatchReportLatencyUs);
+ super(environment);
mDuration = duration;
mTimeUnit = timeUnit;
}
@@ -68,12 +62,6 @@
*/
@Override
protected VerifiableSensorOperation doClone() {
- return new TestSensorFlushOperation(
- mContext,
- mSensorType,
- mRateUs,
- mMaxBatchReportLatencyUs,
- mDuration,
- mTimeUnit);
+ return new TestSensorFlushOperation(mEnvironment, mDuration,mTimeUnit);
}
}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
index 5982d24..6c3851e 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
@@ -16,7 +16,7 @@
package android.hardware.cts.helpers.sensoroperations;
-import android.content.Context;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEventListener;
import java.util.concurrent.TimeUnit;
@@ -37,38 +37,36 @@
/**
* Create a {@link TestSensorOperation}.
*
- * @param context the {@link Context}.
- * @param sensorType the sensor type
- * @param rateUs the rate that
- * @param maxBatchReportLatencyUs the max batch report latency
+ * @param environment the test environment
* @param eventCount the number of events to gather
*/
- public TestSensorOperation(Context context, int sensorType, int rateUs,
- int maxBatchReportLatencyUs, int eventCount) {
- this(context, sensorType, rateUs, maxBatchReportLatencyUs, eventCount, null, null);
+ public TestSensorOperation(TestSensorEnvironment environment, int eventCount) {
+ this(environment, eventCount, null /* duration */, null /* timeUnit */);
}
/**
* Create a {@link TestSensorOperation}.
*
- * @param context the {@link Context}.
- * @param sensorType the sensor type
- * @param rateUs the rate that
- * @param maxBatchReportLatencyUs the max batch report latency
+ * @param environment the test environment
* @param duration the duration to gather events for
* @param timeUnit the time unit of the duration
*/
- public TestSensorOperation(Context context, int sensorType, int rateUs,
- int maxBatchReportLatencyUs, long duration, TimeUnit timeUnit) {
- this(context, sensorType, rateUs, maxBatchReportLatencyUs, null, duration, timeUnit);
+ public TestSensorOperation(
+ TestSensorEnvironment environment,
+ long duration,
+ TimeUnit timeUnit) {
+ this(environment, null /* eventCount */, duration, timeUnit);
}
/**
* Private helper constructor.
*/
- private TestSensorOperation(Context context, int sensorType, int rateUs,
- int maxBatchReportLatencyUs, Integer eventCount, Long duration, TimeUnit timeUnit) {
- super(context, sensorType, rateUs, maxBatchReportLatencyUs);
+ private TestSensorOperation(
+ TestSensorEnvironment environment,
+ Integer eventCount,
+ Long duration,
+ TimeUnit timeUnit) {
+ super(environment);
mEventCount = eventCount;
mDuration = duration;
mTimeUnit = timeUnit;
@@ -92,11 +90,9 @@
@Override
protected VerifiableSensorOperation doClone() {
if (mEventCount != null) {
- return new TestSensorOperation(mContext, mSensorType, mRateUs,
- mMaxBatchReportLatencyUs, mEventCount);
+ return new TestSensorOperation(mEnvironment, mEventCount);
} else {
- return new TestSensorOperation(mContext, mSensorType, mRateUs,
- mMaxBatchReportLatencyUs, mDuration, mTimeUnit);
+ return new TestSensorOperation(mEnvironment, mDuration, mTimeUnit);
}
}
}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/VerifiableSensorOperation.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/VerifiableSensorOperation.java
index d0a5673..55a880a 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/VerifiableSensorOperation.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensoroperations/VerifiableSensorOperation.java
@@ -18,11 +18,10 @@
import junit.framework.Assert;
-import android.content.Context;
-import android.hardware.Sensor;
import android.hardware.cts.helpers.SensorCtsHelper;
import android.hardware.cts.helpers.SensorStats;
import android.hardware.cts.helpers.SensorTestInformation;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEventListener;
import android.hardware.cts.helpers.TestSensorManager;
import android.hardware.cts.helpers.ValidatingSensorEventListener;
@@ -48,10 +47,7 @@
*/
public abstract class VerifiableSensorOperation extends AbstractSensorOperation {
protected final TestSensorManager mSensorManager;
- protected final Context mContext;
- protected final int mSensorType;
- protected final int mRateUs;
- protected final int mMaxBatchReportLatencyUs;
+ protected final TestSensorEnvironment mEnvironment;
private final Collection<ISensorVerification> mVerifications =
new HashSet<ISensorVerification>();
@@ -61,22 +57,11 @@
/**
* Create a {@link TestSensorOperation}.
*
- * @param context the {@link Context}.
- * @param sensorType the sensor type
- * @param rateUs the rate that
- * @param maxBatchReportLatencyUs the max batch report latency
+ * @param environment the test environment
*/
- public VerifiableSensorOperation(
- Context context,
- int sensorType,
- int rateUs,
- int maxBatchReportLatencyUs) {
- mContext = context;
- mSensorType = sensorType;
- mRateUs = rateUs;
- mMaxBatchReportLatencyUs = maxBatchReportLatencyUs;
- mSensorManager = new TestSensorManager(mContext, mSensorType, mRateUs,
- mMaxBatchReportLatencyUs);
+ public VerifiableSensorOperation(TestSensorEnvironment environment) {
+ mEnvironment = environment;
+ mSensorManager = new TestSensorManager(mEnvironment);
}
/**
@@ -90,15 +75,14 @@
* Set all of the default test expectations.
*/
public void addDefaultVerifications() {
- Sensor sensor = mSensorManager.getSensor();
- addVerification(EventGapVerification.getDefault(sensor, mRateUs));
- addVerification(EventOrderingVerification.getDefault(sensor));
- addVerification(FrequencyVerification.getDefault(sensor, mRateUs));
- addVerification(JitterVerification.getDefault(sensor, mRateUs));
- addVerification(MagnitudeVerification.getDefault(sensor));
- addVerification(MeanVerification.getDefault(sensor));
+ addVerification(EventGapVerification.getDefault(mEnvironment));
+ addVerification(EventOrderingVerification.getDefault(mEnvironment));
+ addVerification(FrequencyVerification.getDefault(mEnvironment));
+ addVerification(JitterVerification.getDefault(mEnvironment));
+ addVerification(MagnitudeVerification.getDefault(mEnvironment));
+ addVerification(MeanVerification.getDefault(mEnvironment));
// Skip SigNumVerification since it has no default
- addVerification(StandardDeviationVerification.getDefault(sensor));
+ addVerification(StandardDeviationVerification.getDefault(mEnvironment));
}
public void addVerification(ISensorVerification verification) {
@@ -112,7 +96,9 @@
*/
@Override
public void execute() {
- getStats().addValue("sensor_name", SensorTestInformation.getSensorName(mSensorType));
+ getStats().addValue(
+ "sensor_name",
+ SensorTestInformation.getSensorName(mEnvironment.getSensor()));
ValidatingSensorEventListener listener = new ValidatingSensorEventListener(mVerifications);
listener.setLogEvents(mLogEvents);
@@ -126,8 +112,8 @@
}
if (failed) {
- String msg = SensorCtsHelper.formatAssertionMessage(mSensorManager.getSensor(),
- "VerifySensorOperation", mRateUs, mMaxBatchReportLatencyUs, sb.toString());
+ String msg = SensorCtsHelper
+ .formatAssertionMessage("VerifySensorOperation", mEnvironment, sb.toString());
getStats().addValue(SensorStats.ERROR, msg);
Assert.fail(msg);
}
@@ -160,7 +146,7 @@
*/
private boolean evaluateResults(ISensorVerification verification, StringBuilder sb) {
try {
- verification.verify(getStats());
+ verification.verify(mEnvironment, getStats());
} catch (AssertionError e) {
if (sb.length() > 0) {
sb.append(", ");
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/AbstractMeanVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/AbstractMeanVerification.java
index 8d132a3..b755304 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/AbstractMeanVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/AbstractMeanVerification.java
@@ -16,10 +16,10 @@
package android.hardware.cts.helpers.sensorverification;
-import android.hardware.cts.helpers.TestSensorEvent;
-
import junit.framework.Assert;
+import android.hardware.cts.helpers.TestSensorEvent;
+
/**
* Abstract class that calculates of the mean event values.
*/
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerification.java
index 251ef3c..962e5ad 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerification.java
@@ -1,14 +1,12 @@
package android.hardware.cts.helpers.sensorverification;
-import android.hardware.Sensor;
-import android.hardware.cts.helpers.SensorCtsHelper;
-import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.SensorTestInformation;
-import android.hardware.cts.helpers.SensorTestInformation.SensorReportingMode;
-import android.hardware.cts.helpers.TestSensorEvent;
-
import junit.framework.Assert;
+import android.hardware.Sensor;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@@ -45,23 +43,27 @@
/**
* Get the default {@link EventGapVerification}.
*
- * @param sensor the {@link Sensor}
- * @param rateUs the requested rate in us
+ * @param environment the test environment
* @return the verification or null if the verification is not a continuous mode sensor.
*/
- public static EventGapVerification getDefault(Sensor sensor, int rateUs) {
- if (!SensorReportingMode.CONTINUOUS.equals(SensorTestInformation.getReportingMode(
- sensor.getType()))) {
+ public static EventGapVerification getDefault(TestSensorEnvironment environment) {
+ if (environment.getSensor().getReportingMode() != Sensor.REPORTING_MODE_CONTINUOUS) {
return null;
}
- return new EventGapVerification(SensorCtsHelper.getDelay(sensor, rateUs));
+ return new EventGapVerification(environment.getExpectedSamplingPeriodUs());
}
/**
* {@inheritDoc}
*/
@Override
- public void verify(SensorStats stats) {
+ public void verify(TestSensorEnvironment environment, SensorStats stats) {
+ if (environment.isSensorSamplingRateOverloaded()) {
+ // the verification is not reliable on environments under load
+ stats.addValue(PASSED_KEY, true);
+ return;
+ }
+
final int count = mEventGaps.size();
stats.addValue(PASSED_KEY, count == 0);
stats.addValue(SensorStats.EVENT_GAP_COUNT_KEY, count);
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerificationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerificationTest.java
index b7861b2..d01e108 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerificationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventGapVerificationTest.java
@@ -16,11 +16,12 @@
package android.hardware.cts.helpers.sensorverification;
-import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.TestSensorEvent;
-
import junit.framework.TestCase;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+
/**
* Tests for {@link EventGapVerification}.
*/
@@ -65,12 +66,13 @@
int[] indices) {
SensorStats stats = new SensorStats();
ISensorVerification verification = getVerification(expected, timestamps);
+ TestSensorEnvironment environment = new TestSensorEnvironment(null, null, false, 0, 0);
if (pass) {
- verification.verify(stats);
+ verification.verify(environment, stats);
} else {
boolean failed = false;
try {
- verification.verify(stats);
+ verification.verify(environment, stats);
} catch (AssertionError e) {
// Expected;
failed = true;
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerification.java
index c74c826..6598725 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerification.java
@@ -16,14 +16,13 @@
package android.hardware.cts.helpers.sensorverification;
+import junit.framework.Assert;
+
import android.hardware.Sensor;
import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.SensorTestInformation;
-import android.hardware.cts.helpers.SensorTestInformation.SensorReportingMode;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEvent;
-import junit.framework.Assert;
-
import java.util.LinkedList;
import java.util.List;
@@ -44,14 +43,14 @@
/**
* Get the default {@link EventOrderingVerification} for a sensor.
*
- * @param sensor a {@link Sensor}
+ * @param environment the test environment
* @return the verification or null if the verification does not apply to the sensor.
*/
@SuppressWarnings("deprecation")
- public static EventOrderingVerification getDefault(Sensor sensor) {
- SensorReportingMode mode = SensorTestInformation.getReportingMode(sensor.getType());
- if (!SensorReportingMode.CONTINUOUS.equals(mode)
- && !SensorReportingMode.ON_CHANGE.equals(mode)) {
+ public static EventOrderingVerification getDefault(TestSensorEnvironment environment) {
+ int reportingMode = environment.getSensor().getReportingMode();
+ if (reportingMode != Sensor.REPORTING_MODE_CONTINUOUS
+ && reportingMode != Sensor.REPORTING_MODE_ON_CHANGE) {
return null;
}
return new EventOrderingVerification();
@@ -65,7 +64,14 @@
* @throws AssertionError if the verification failed.
*/
@Override
- public void verify(SensorStats stats) {
+ public void verify(TestSensorEnvironment environment, SensorStats stats) {
+ verify(stats);
+ }
+
+ /**
+ * Visible for unit tests only.
+ */
+ void verify(SensorStats stats) {
final int count = mOutOfOrderEvents.size();
stats.addValue(PASSED_KEY, count == 0);
stats.addValue(SensorStats.EVENT_OUT_OF_ORDER_COUNT_KEY, count);
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java
index 28cbd01..88d5c19 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/EventOrderingVerificationTest.java
@@ -16,11 +16,11 @@
package android.hardware.cts.helpers.sensorverification;
+import junit.framework.TestCase;
+
import android.hardware.cts.helpers.SensorStats;
import android.hardware.cts.helpers.TestSensorEvent;
-import junit.framework.TestCase;
-
import java.util.ArrayList;
import java.util.List;
@@ -34,7 +34,7 @@
*/
public void testNoEvents() {
SensorStats stats = new SensorStats();
- ISensorVerification verification = getVerification();
+ EventOrderingVerification verification = getVerification();
verification.verify(stats);
verifyStats(stats, true, 0);
}
@@ -44,7 +44,7 @@
*/
public void testSameTimestamp() {
SensorStats stats = new SensorStats();
- ISensorVerification verification = getVerification(0, 0, 0, 0, 0);
+ EventOrderingVerification verification = getVerification(0, 0, 0, 0, 0);
verification.verify(stats);
verifyStats(stats, true, 0);
}
@@ -54,7 +54,7 @@
*/
public void testSequentialTimestamp() {
SensorStats stats = new SensorStats();
- ISensorVerification verification = getVerification(0, 1, 2, 3, 4);
+ EventOrderingVerification verification = getVerification(0, 1, 2, 3, 4);
verification.verify(stats);
verifyStats(stats, true, 0);
}
@@ -64,7 +64,7 @@
*/
public void testSingleOutofOrder() {
SensorStats stats = new SensorStats();
- ISensorVerification verification = getVerification(0, 2, 1, 3, 4);
+ EventOrderingVerification verification = getVerification(0, 2, 1, 3, 4);
try {
verification.verify(stats);
fail("Expected an AssertionError");
@@ -81,7 +81,7 @@
*/
public void testMultipleOutOfOrder() {
SensorStats stats = new SensorStats();
- ISensorVerification verification = getVerification(4, 0, 1, 2, 3);
+ EventOrderingVerification verification = getVerification(4, 0, 1, 2, 3);
try {
verification.verify(stats);
fail("Expected an AssertionError");
@@ -96,8 +96,8 @@
assertTrue(indices.contains(4));
}
- private ISensorVerification getVerification(long ... timestamps) {
- ISensorVerification verification = new EventOrderingVerification();
+ private EventOrderingVerification getVerification(long ... timestamps) {
+ EventOrderingVerification verification = new EventOrderingVerification();
for (long timestamp : timestamps) {
verification.addSensorEvent(new TestSensorEvent(null, timestamp, 0, null));
}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/FrequencyVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/FrequencyVerification.java
index b6704b6..cf34f28 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/FrequencyVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/FrequencyVerification.java
@@ -16,16 +16,15 @@
package android.hardware.cts.helpers.sensorverification;
+import junit.framework.Assert;
+
import android.hardware.Sensor;
import android.hardware.cts.helpers.SensorCtsHelper;
import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.SensorTestInformation;
-import android.hardware.cts.helpers.SensorTestInformation.SensorReportingMode;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEvent;
import android.util.Log;
-import junit.framework.Assert;
-
import java.util.concurrent.TimeUnit;
/**
@@ -41,10 +40,8 @@
// Highest acceptable frequency, as percentage of the requested one.
private static final int DEFAULT_UPPER_THRESHOLD = 220;
- private final double mRequestedFrequencyHz;
private final double mLowerThresholdHz;
private final double mUpperThresholdHz;
- private final String mSensorName;
private long mMinTimestamp = 0;
private long mMaxTimestamp = 0;
@@ -53,34 +50,31 @@
/**
* Construct a {@link FrequencyVerification}.
*
- * @param expected the expected frequency in Hz.
* @param lowerTheshold Lowest acceptable frequency Hz.
* @param upperThreshold Highest acceptable frequency Hz.
*/
- public FrequencyVerification(double expected, double lowerTheshold, double upperThreshold,
- String sensorName) {
- mRequestedFrequencyHz = expected;
+ public FrequencyVerification(double lowerTheshold, double upperThreshold) {
mLowerThresholdHz = lowerTheshold;
mUpperThresholdHz = upperThreshold;
- mSensorName = sensorName;
}
/**
* Get the default {@link FrequencyVerification} for a sensor.
*
- * @param sensor a {@link Sensor}
- * @param rateUs the desired rate of the sensor
+ * @param environment the test environment
* @return the verification or null if the verification does not apply to the sensor.
*/
- public static FrequencyVerification getDefault(Sensor sensor, int rateUs) {
- if (!SensorReportingMode.CONTINUOUS.equals(
- SensorTestInformation.getReportingMode(sensor.getType()))) {
+ public static FrequencyVerification getDefault(TestSensorEnvironment environment) {
+ Sensor sensor = environment.getSensor();
+ if (sensor.getReportingMode() != Sensor.REPORTING_MODE_CONTINUOUS) {
return null;
}
- Log.i(LOG_TAG, String.format("Preparing frequency test for \"%s\" for which "
- + "minDelay=%dus and maxDelay=%dus",
- sensor.getName(), sensor.getMinDelay(), sensor.getMaxDelay()));
+ Log.i(LOG_TAG, String.format(
+ "Preparing frequency test for \"%s\" for which minDelay=%dus and maxDelay=%dus",
+ sensor.getName(),
+ sensor.getMinDelay(),
+ sensor.getMaxDelay()));
double maxDelayUs = sensor.getMaxDelay();
if (maxDelayUs <= 0) {
// This sensor didn't report its maxDelay.
@@ -92,10 +86,12 @@
maxDelayUs = sensor.getMinDelay();
}
+ if (environment.isSensorSamplingRateOverloaded()) {
+ maxDelayUs = sensor.getMinDelay();
+ }
+
// Convert the rateUs parameter into a delay in microseconds and rate in Hz.
- double delayUs = SensorCtsHelper.getDelay(sensor, rateUs);
- double requestedFrequencyHz = SensorCtsHelper.getFrequency(
- delayUs, TimeUnit.MICROSECONDS);
+ double delayUs = environment.getRequestedSamplingPeriodUs();
// When rateUs > maxDelay, the sensor can do as if we requested maxDelay.
double upperExpectedHz = SensorCtsHelper.getFrequency(
@@ -108,8 +104,7 @@
double lowerThresholdHz = lowerExpectedHz * DEFAULT_LOWER_THRESHOLD / 100;
double upperThresholdHz = upperExpectedHz * DEFAULT_UPPER_THRESHOLD / 100;
- return new FrequencyVerification(requestedFrequencyHz, lowerThresholdHz, upperThresholdHz,
- sensor.getName());
+ return new FrequencyVerification(lowerThresholdHz, upperThresholdHz);
}
/**
@@ -119,7 +114,7 @@
* @throws AssertionError if the verification failed.
*/
@Override
- public void verify(SensorStats stats) {
+ public void verify(TestSensorEnvironment environment, SensorStats stats) {
if (mCount < 2) {
stats.addValue(PASSED_KEY, true);
return;
@@ -132,9 +127,13 @@
stats.addValue(SensorStats.FREQUENCY_KEY, measuredFrequencyHz);
stats.addValue(PASSED_KEY, !failed);
- String resultString = String.format("Requested \"" + mSensorName + "\" at %.2fHz "
- + "(expecting between %.2fHz and %.2fHz, measured %.2fHz)",
- mRequestedFrequencyHz, mLowerThresholdHz, mUpperThresholdHz, measuredFrequencyHz);
+ String resultString = String.format(
+ "Requested \"%s\" at %.2fHz (expecting between %.2fHz and %.2fHz, measured %.2fHz)",
+ environment.getSensor().getName(),
+ environment.getFrequencyHz(),
+ mLowerThresholdHz,
+ mUpperThresholdHz,
+ measuredFrequencyHz);
if (failed) {
Log.e(LOG_TAG, "Frequency test FAIL: " + resultString);
@@ -149,8 +148,7 @@
*/
@Override
public FrequencyVerification clone() {
- return new FrequencyVerification(mRequestedFrequencyHz, mLowerThresholdHz,
- mUpperThresholdHz, mSensorName);
+ return new FrequencyVerification(mLowerThresholdHz, mUpperThresholdHz);
}
/**
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/FrequencyVerificationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/FrequencyVerificationTest.java
index 82d93e5..24349ce 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/FrequencyVerificationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/FrequencyVerificationTest.java
@@ -16,15 +16,16 @@
package android.hardware.cts.helpers.sensorverification;
+import android.hardware.Sensor;
+import android.hardware.cts.SensorTestCase;
import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEvent;
-import junit.framework.TestCase;
-
/**
* Tests for {@link EventOrderingVerification}.
*/
-public class FrequencyVerificationTest extends TestCase {
+public class FrequencyVerificationTest extends SensorTestCase {
/**
* Test that the verifications passes/fails based on threshold given.
@@ -33,24 +34,24 @@
long[] timestamps = {0, 1000000, 2000000, 3000000, 4000000}; // 1000Hz
SensorStats stats = new SensorStats();
- ISensorVerification verification = getVerification(1000.0, 999.0, 1001.0, timestamps);
- verification.verify(stats);
+ ISensorVerification verification = getVerification(999.0, 1001.0, timestamps);
+ verification.verify(getEnvironment(1000), stats);
verifyStats(stats, true, 1000.0);
stats = new SensorStats();
- verification = getVerification(950.0, 850.0, 1050.0, timestamps);
- verification.verify(stats);
+ verification = getVerification(850.0, 1050.0, timestamps);
+ verification.verify(getEnvironment(950), stats);
verifyStats(stats, true, 1000.0);
stats = new SensorStats();
- verification = getVerification(1050.0, 950.0, 1150.0, timestamps);
- verification.verify(stats);
+ verification = getVerification(950.0, 1150.0, timestamps);
+ verification.verify(getEnvironment(1050), stats);
verifyStats(stats, true, 1000.0);
stats = new SensorStats();
- verification = getVerification(950.0, 850.0, 975.0, timestamps);
+ verification = getVerification(850.0, 975.0, timestamps);
try {
- verification.verify(stats);
+ verification.verify(getEnvironment(950), stats);
fail("Expected an AssertionError");
} catch (AssertionError e) {
// Expected;
@@ -58,9 +59,9 @@
verifyStats(stats, false, 1000.0);
stats = new SensorStats();
- verification = getVerification(1050.0, 1025.0, 1150.0, timestamps);
+ verification = getVerification(1025.0, 1150.0, timestamps);
try {
- verification.verify(stats);
+ verification.verify(getEnvironment(1050), stats);
fail("Expected an AssertionError");
} catch (AssertionError e) {
// Expected;
@@ -68,10 +69,16 @@
verifyStats(stats, false, 1000.0);
}
- private ISensorVerification getVerification(double expected, double lowerThreshold,
- double upperThreshold, long ... timestamps) {
- ISensorVerification verification = new FrequencyVerification(expected, lowerThreshold,
- upperThreshold, "Test sensor");
+ private TestSensorEnvironment getEnvironment(int rateUs) {
+ return new TestSensorEnvironment(getContext(), Sensor.TYPE_ALL, rateUs);
+ }
+
+ private ISensorVerification getVerification(
+ double lowerThreshold,
+ double upperThreshold,
+ long ... timestamps) {
+ ISensorVerification verification =
+ new FrequencyVerification(lowerThreshold, upperThreshold);
for (long timestamp : timestamps) {
verification.addSensorEvent(new TestSensorEvent(null, timestamp, 0, null));
}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/ISensorVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/ISensorVerification.java
index 07af392..4f7b65a 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/ISensorVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/ISensorVerification.java
@@ -17,13 +17,15 @@
package android.hardware.cts.helpers.sensorverification;
import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEvent;
/**
* Interface describing the sensor verification. This class was designed for to handle streaming
* events. The methods {@link #addSensorEvent(TestSensorEvent)} and
* {@link #addSensorEvents(TestSensorEvent...)} should be called in the order that the events are
- * received. The method {@link #verify(SensorStats)} should be called after all events are added.
+ * received. The method {@link #verify(TestSensorEnvironment, SensorStats)} should be called after
+ * all events are added.
*/
public interface ISensorVerification {
@@ -43,7 +45,7 @@
* @param stats a {@link SensorStats} object used to keep track of the stats.
* @throws AssertionError if the verification fails.
*/
- public void verify(SensorStats stats);
+ public void verify(TestSensorEnvironment environment, SensorStats stats);
/**
* Clones the {@link ISensorVerification}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerification.java
index 6feceb8..97d2f5b 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerification.java
@@ -16,13 +16,14 @@
package android.hardware.cts.helpers.sensorverification;
+import junit.framework.Assert;
+
import android.hardware.Sensor;
import android.hardware.cts.helpers.SensorCtsHelper;
import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEvent;
-import junit.framework.Assert;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
@@ -62,18 +63,18 @@
/**
* Get the default {@link JitterVerification} for a sensor.
*
- * @param sensor a {@link Sensor}
- * @param rateUs the desired rate of the sensor
+ * @param environment the test environment
* @return the verification or null if the verification does not apply to the sensor.
*/
- public static JitterVerification getDefault(Sensor sensor, int rateUs) {
- if (!DEFAULTS.containsKey(sensor.getType())) {
+ public static JitterVerification getDefault(TestSensorEnvironment environment) {
+ int sensorType = environment.getSensor().getType();
+ if (!DEFAULTS.containsKey(sensorType)) {
return null;
}
- int expected = (int) TimeUnit.NANOSECONDS.convert(SensorCtsHelper.getDelay(sensor, rateUs),
- TimeUnit.MICROSECONDS);
- return new JitterVerification(expected, DEFAULTS.get(sensor.getType()));
+ int expected = (int) TimeUnit.NANOSECONDS
+ .convert(environment.getExpectedSamplingPeriodUs(), TimeUnit.MICROSECONDS);
+ return new JitterVerification(expected, DEFAULTS.get(sensorType));
}
/**
@@ -84,8 +85,9 @@
* @throws AssertionError if the verification failed.
*/
@Override
- public void verify(SensorStats stats) {
- if (mTimestamps.size() < 2) {
+ public void verify(TestSensorEnvironment environment, SensorStats stats) {
+ if (mTimestamps.size() < 2 || environment.isSensorSamplingRateOverloaded()) {
+ // the verification is not reliable in environments under load
stats.addValue(PASSED_KEY, true);
return;
}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java
index a9e872a..26e3fa3 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/JitterVerificationTest.java
@@ -16,11 +16,12 @@
package android.hardware.cts.helpers.sensorverification;
-import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.TestSensorEvent;
-
import junit.framework.TestCase;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+
import java.util.List;
/**
@@ -31,6 +32,14 @@
public void testVerify() {
final int SAMPLE_SIZE = 100;
+ // for unit testing the verification, only the parameter 'sensorMightHaveMoreListeners' is
+ // required
+ TestSensorEnvironment environment = new TestSensorEnvironment(
+ null /* context */,
+ null /* sensor */,
+ false /* sensorMightHaveMoreListeners */,
+ 0 /*samplingPeriodUs */,
+ 0 /* maxReportLatencyUs */);
// 100 samples at 1000Hz
long[] timestamps = new long[SAMPLE_SIZE];
@@ -39,7 +48,7 @@
}
SensorStats stats = new SensorStats();
ISensorVerification verification = getVerification(1000, 1, timestamps);
- verification.verify(stats);
+ verification.verify(environment, stats);
verifyStats(stats, true, 0.0);
// 90 samples at 1000Hz, 10 samples at 2000Hz
@@ -51,7 +60,7 @@
stats = new SensorStats();
verification = getVerification(1000, 1, timestamps);
try {
- verification.verify(stats);
+ verification.verify(environment, stats);
fail("Expected an AssertionError");
} catch (AssertionError e) {
// Expected;
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerification.java
index 5e44273..2c90127 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerification.java
@@ -16,13 +16,14 @@
package android.hardware.cts.helpers.sensorverification;
+import junit.framework.Assert;
+
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEvent;
-import junit.framework.Assert;
-
import java.util.HashMap;
import java.util.Map;
@@ -60,15 +61,16 @@
/**
* Get the default {@link MagnitudeVerification} for a sensor.
*
- * @param sensor a {@link Sensor}
+ * @param environment the test environment
* @return the verification or null if the verification does not apply to the sensor.
*/
- public static MagnitudeVerification getDefault(Sensor sensor) {
- if (!DEFAULTS.containsKey(sensor.getType())) {
+ public static MagnitudeVerification getDefault(TestSensorEnvironment environment) {
+ int sensorType = environment.getSensor().getType();
+ if (!DEFAULTS.containsKey(sensorType)) {
return null;
}
- Float expected = DEFAULTS.get(sensor.getType())[0];
- Float threshold = DEFAULTS.get(sensor.getType())[1];
+ Float expected = DEFAULTS.get(sensorType)[0];
+ Float threshold = DEFAULTS.get(sensorType)[1];
return new MagnitudeVerification(expected, threshold);
}
@@ -79,7 +81,14 @@
* @throws AssertionError if the verification failed.
*/
@Override
- public void verify(SensorStats stats) {
+ public void verify(TestSensorEnvironment environment, SensorStats stats) {
+ verify(stats);
+ }
+
+ /**
+ * Visible for unit tests only.
+ */
+ void verify(SensorStats stats) {
if (mCount < 1) {
stats.addValue(PASSED_KEY, true);
return;
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerificationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerificationTest.java
index 9a50753..bb29330 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerificationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MagnitudeVerificationTest.java
@@ -16,18 +16,19 @@
package android.hardware.cts.helpers.sensorverification;
-import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.TestSensorEvent;
-
import junit.framework.TestCase;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+
/**
* Tests for {@link MagnitudeVerification}.
*/
public class MagnitudeVerificationTest extends TestCase {
/**
- * Test {@link MagnitudeVerification#verify(SensorStats)}.
+ * Test {@link MagnitudeVerification#verify(TestSensorEnvironment, SensorStats)}.
*/
public void testVerify() {
float[][] values = {
@@ -47,7 +48,7 @@
private void runStats(float expected, float threshold, float[][] values, boolean pass, float magnitude) {
SensorStats stats = new SensorStats();
- ISensorVerification verification = getVerification(expected, threshold, values);
+ MagnitudeVerification verification = getVerification(expected, threshold, values);
if (pass) {
verification.verify(stats);
} else {
@@ -62,9 +63,9 @@
assertEquals(magnitude, (Float) stats.getValue(SensorStats.MAGNITUDE_KEY), 0.01);
}
- private ISensorVerification getVerification(float expected, float threshold,
+ private MagnitudeVerification getVerification(float expected, float threshold,
float[] ... values) {
- ISensorVerification verification = new MagnitudeVerification(expected, threshold);
+ MagnitudeVerification verification = new MagnitudeVerification(expected, threshold);
for (float[] value : values) {
verification.addSensorEvent(new TestSensorEvent(null, 0, 0, value));
}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MeanVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MeanVerification.java
index d6769d0..6603895 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MeanVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MeanVerification.java
@@ -16,11 +16,12 @@
package android.hardware.cts.helpers.sensorverification;
+import junit.framework.Assert;
+
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.hardware.cts.helpers.SensorStats;
-
-import junit.framework.Assert;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import java.util.HashMap;
import java.util.Map;
@@ -55,15 +56,16 @@
/**
* Get the default {@link MeanVerification} for a sensor.
*
- * @param sensor a {@link Sensor}
+ * @param environment the test environment
* @return the verification or null if the verification does not apply to the sensor.
*/
- public static MeanVerification getDefault(Sensor sensor) {
- if (!DEFAULTS.containsKey(sensor.getType())) {
+ public static MeanVerification getDefault(TestSensorEnvironment environment) {
+ int sensorType = environment.getSensor().getType();
+ if (!DEFAULTS.containsKey(sensorType)) {
return null;
}
- float[] expected = (float[]) DEFAULTS.get(sensor.getType())[0];
- float[] threshold = (float[]) DEFAULTS.get(sensor.getType())[1];
+ float[] expected = (float[]) DEFAULTS.get(sensorType)[0];
+ float[] threshold = (float[]) DEFAULTS.get(sensorType)[1];
return new MeanVerification(expected, threshold);
}
@@ -74,7 +76,14 @@
* @throws AssertionError if the verification failed.
*/
@Override
- public void verify(SensorStats stats) {
+ public void verify(TestSensorEnvironment environment, SensorStats stats) {
+ verify(stats);
+ }
+
+ /**
+ * Visible for unit tests only.
+ */
+ void verify(SensorStats stats) {
if (getCount() < 1) {
stats.addValue(PASSED_KEY, true);
return;
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MeanVerificationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MeanVerificationTest.java
index 94b6362..b07ea50 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MeanVerificationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/MeanVerificationTest.java
@@ -16,18 +16,19 @@
package android.hardware.cts.helpers.sensorverification;
-import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.TestSensorEvent;
-
import junit.framework.TestCase;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+
/**
* Tests for {@link MeanVerification}.
*/
public class MeanVerificationTest extends TestCase {
/**
- * Test {@link MeanVerification#verify(SensorStats)}.
+ * Test {@link MeanVerification#verify(TestSensorEnvironment, SensorStats)}.
*/
public void testVerify() {
float[][] values = {
@@ -41,7 +42,7 @@
float[] expected = {2.0f, 3.0f, 6.0f};
float[] threshold = {0.1f, 0.1f, 0.1f};
SensorStats stats = new SensorStats();
- ISensorVerification verification = getVerification(expected, threshold, values);
+ MeanVerification verification = getVerification(expected, threshold, values);
verification.verify(stats);
verifyStats(stats, true, new float[]{2.0f, 3.0f, 6.0f});
@@ -76,7 +77,6 @@
}
verifyStats(stats, false, new float[]{2.0f, 3.0f, 6.0f});
- threshold = new float[]{2.5f, 2.5f, 5.5f};
threshold = new float[]{0.6f, 0.6f, 0.1f};
stats = new SensorStats();
verification = getVerification(expected, threshold, values);
@@ -89,9 +89,9 @@
verifyStats(stats, false, new float[]{2.0f, 3.0f, 6.0f});
}
- private ISensorVerification getVerification(float[] expected, float[] threshold,
+ private MeanVerification getVerification(float[] expected, float[] threshold,
float[] ... values) {
- ISensorVerification verification = new MeanVerification(expected, threshold);
+ MeanVerification verification = new MeanVerification(expected, threshold);
for (float[] value : values) {
verification.addSensorEvent(new TestSensorEvent(null, 0, 0, value));
}
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/SigNumVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/SigNumVerification.java
index 9428d1d..94a4c96 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/SigNumVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/SigNumVerification.java
@@ -16,10 +16,11 @@
package android.hardware.cts.helpers.sensorverification;
-import android.hardware.cts.helpers.SensorStats;
-
import junit.framework.Assert;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+
/**
* A {@link ISensorVerification} which verifies that the sign of each of the sensor values is
* correct.
@@ -60,7 +61,14 @@
* @throws AssertionError if the verification failed.
*/
@Override
- public void verify(SensorStats stats) {
+ public void verify(TestSensorEnvironment environment, SensorStats stats) {
+ verify(stats);
+ }
+
+ /**
+ * Visible for unit tests only.
+ */
+ void verify(SensorStats stats) {
if (getCount() < 1) {
stats.addValue(PASSED_KEY, true);
return;
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/SigNumVerificationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/SigNumVerificationTest.java
index 009ab65..c8ce87e 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/SigNumVerificationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/SigNumVerificationTest.java
@@ -16,18 +16,19 @@
package android.hardware.cts.helpers.sensorverification;
-import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.TestSensorEvent;
-
import junit.framework.TestCase;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+
/**
* Tests for {@link SigNumVerification}.
*/
public class SigNumVerificationTest extends TestCase {
/**
- * Test {@link SigNumVerification#verify(SensorStats)}.
+ * Test {@link SigNumVerification#verify(TestSensorEnvironment, SensorStats)}.
*/
public void testVerify() {
float[][] values = {{1.0f, 0.2f, 0.0f, -0.2f, -1.0f}};
@@ -65,7 +66,7 @@
private void runVerification(boolean passed, int[] expected, float[] threshold,
float[][] values) {
SensorStats stats = new SensorStats();
- ISensorVerification verification = getVerification(expected, threshold, values);
+ SigNumVerification verification = getVerification(expected, threshold, values);
if (passed) {
verification.verify(stats);
} else {
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/StandardDeviationVerification.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/StandardDeviationVerification.java
index 57b34b0..f7c2c53 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/StandardDeviationVerification.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/StandardDeviationVerification.java
@@ -16,12 +16,13 @@
package android.hardware.cts.helpers.sensorverification;
+import junit.framework.Assert;
+
import android.hardware.Sensor;
import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
import android.hardware.cts.helpers.TestSensorEvent;
-import junit.framework.Assert;
-
import java.util.HashMap;
import java.util.Map;
@@ -57,15 +58,16 @@
/**
* Get the default {@link StandardDeviationVerification} for a sensor.
*
- * @param sensor a {@link Sensor}
+ * @param environment the test environment
* @return the verification or null if the verification does not apply to the sensor.
*/
- public static StandardDeviationVerification getDefault(Sensor sensor) {
- if (!DEFAULTS.containsKey(sensor.getType())) {
+ public static StandardDeviationVerification getDefault(TestSensorEnvironment environment) {
+ int sensorType = environment.getSensor().getType();
+ if (!DEFAULTS.containsKey(sensorType)) {
return null;
}
- return new StandardDeviationVerification(DEFAULTS.get(sensor.getType()));
+ return new StandardDeviationVerification(DEFAULTS.get(sensorType));
}
/**
@@ -75,7 +77,14 @@
* @throws AssertionError if the verification failed.
*/
@Override
- public void verify(SensorStats stats) {
+ public void verify(TestSensorEnvironment environment, SensorStats stats) {
+ verify(stats);
+ }
+
+ /**
+ * Visible for unit tests only.
+ */
+ void verify(SensorStats stats) {
if (mCount < 2) {
stats.addValue(PASSED_KEY, true);
return;
diff --git a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/StandardDeviationVerificationTest.java b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/StandardDeviationVerificationTest.java
index 308f114..5d958f5 100644
--- a/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/StandardDeviationVerificationTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/helpers/sensorverification/StandardDeviationVerificationTest.java
@@ -16,18 +16,19 @@
package android.hardware.cts.helpers.sensorverification;
-import android.hardware.cts.helpers.SensorStats;
-import android.hardware.cts.helpers.TestSensorEvent;
-
import junit.framework.TestCase;
+import android.hardware.cts.helpers.SensorStats;
+import android.hardware.cts.helpers.TestSensorEnvironment;
+import android.hardware.cts.helpers.TestSensorEvent;
+
/**
* Tests for {@link StandardDeviationVerification}.
*/
public class StandardDeviationVerificationTest extends TestCase {
/**
- * Test {@link StandardDeviationVerification#verify(SensorStats)}.
+ * Test {@link StandardDeviationVerification#verify(TestSensorEnvironment, SensorStats)}.
*/
public void testVerify() {
// Stddev should be {sqrt(2.5), sqrt(2.5), sqrt(2.5)}
@@ -58,7 +59,7 @@
private void runVerification(float[] threshold, float[][] values, boolean pass,
float[] standardDeviations) {
SensorStats stats = new SensorStats();
- ISensorVerification verification = getVerification(threshold, values);
+ StandardDeviationVerification verification = getVerification(threshold, values);
if (pass) {
verification.verify(stats);
} else {
@@ -78,8 +79,8 @@
}
}
- private ISensorVerification getVerification(float[] threshold, float[] ... values) {
- ISensorVerification verification = new StandardDeviationVerification(threshold);
+ private StandardDeviationVerification getVerification(float[] threshold, float[] ... values) {
+ StandardDeviationVerification verification = new StandardDeviationVerification(threshold);
for (float[] value : values) {
verification.addSensorEvent(new TestSensorEvent(null, 0, 0, value));
}
diff --git a/tests/tests/location/src/android/location/cts/LocationManagerTest.java b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
index ab11b3c..a985aee 100644
--- a/tests/tests/location/src/android/location/cts/LocationManagerTest.java
+++ b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
@@ -37,6 +37,7 @@
import android.os.SystemClock;
import android.provider.Settings;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import java.util.List;
@@ -615,6 +616,7 @@
}
}
+ @UiThreadTest
public void testGpsStatusListener() {
MockGpsStatusListener listener = new MockGpsStatusListener();
mManager.addGpsStatusListener(listener);
diff --git a/tests/tests/media/src/android/media/cts/AudioTrackTest.java b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
index 5eaf725..7de3716 100644
--- a/tests/tests/media/src/android/media/cts/AudioTrackTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
@@ -16,19 +16,22 @@
package android.media.cts;
+import android.cts.util.CtsAndroidTestCase;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTimestamp;
import android.media.AudioTrack;
-import android.test.AndroidTestCase;
import android.util.Log;
+import com.android.cts.util.ReportLog;
+import com.android.cts.util.ResultType;
+import com.android.cts.util.ResultUnit;
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.nio.FloatBuffer;
-public class AudioTrackTest extends AndroidTestCase {
+public class AudioTrackTest extends CtsAndroidTestCase {
private String TAG = "AudioTrackTest";
private final long WAIT_MSEC = 200;
private final int OFFSET_DEFAULT = 0;
@@ -1535,70 +1538,127 @@
// constants for test
final String TEST_NAME = "testGetTimestamp";
final int TEST_SR = 22050;
- final int TEST_CONF = AudioFormat.CHANNEL_CONFIGURATION_MONO;
+ final int TEST_CONF = AudioFormat.CHANNEL_OUT_MONO;
final int TEST_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
final int TEST_MODE = AudioTrack.MODE_STREAM;
final int TEST_STREAM_TYPE = AudioManager.STREAM_MUSIC;
final int TEST_LOOP_CNT = 10;
-
- final int MILLIS_PER_SEC = 1000;
- final int NANOS_PER_MILLI = 1000000;
+ // For jitter we allow 30 msec in frames. This is a large margin.
+ // Often this is just 0 or 1 frames, but that can depend on hardware.
+ final int TEST_JITTER_FRAMES_ALLOWED = TEST_SR * 30 / 1000;
// -------- initialization --------------
- final int BYTES_PER_FRAME = 2;
- final int FRAMES_PER_100_MILLIS =
+ final int bytesPerFrame =
+ AudioFormat.getBytesPerSample(TEST_FORMAT)
+ * AudioFormat.channelCountFromOutChannelMask(TEST_CONF);
+ final int minBufferSizeInBytes =
AudioTrack.getMinBufferSize(TEST_SR, TEST_CONF, TEST_FORMAT);
- final int FRAMES_PER_SEC = FRAMES_PER_100_MILLIS * 10;
- byte[] data = new byte[FRAMES_PER_100_MILLIS * BYTES_PER_FRAME];
+ final int bufferSizeInBytes = minBufferSizeInBytes * 3;
+ byte[] data = new byte[bufferSizeInBytes];
AudioTrack track = new AudioTrack(TEST_STREAM_TYPE, TEST_SR, TEST_CONF, TEST_FORMAT,
- FRAMES_PER_SEC * BYTES_PER_FRAME, TEST_MODE);
+ minBufferSizeInBytes, TEST_MODE);
// -------- test --------------
assertTrue(TEST_NAME, track.getState() == AudioTrack.STATE_INITIALIZED);
- long framesWritten = 0, framesSeen = 0, framesPresented = 0;
- long lastFramesPresented = 0, lastFrameTime = 0, lastOutputFrequency = FRAMES_PER_SEC;
AudioTimestamp timestamp = new AudioTimestamp();
+ boolean hasPlayed = false;
+ long framesWritten = 0, lastFramesPresented = 0, lastFramesPresentedAt = 0;
+ int cumulativeJitterCount = 0;
+ float cumulativeJitter = 0;
+ float maxJitter = 0;
for (int i = 0; i < TEST_LOOP_CNT; i++) {
- for (int j = 0; j < FRAMES_PER_SEC; j += FRAMES_PER_100_MILLIS) {
- track.write(data, 0, data.length);
- framesWritten += FRAMES_PER_100_MILLIS;
+ final long writeTime = System.nanoTime();
+
+ for (int written = 0; written < data.length;) {
+ int ret = track.write(data, written,
+ Math.min(data.length - written, minBufferSizeInBytes));
+ assertTrue(TEST_NAME, ret >= 0);
+ written += ret;
+ if (!hasPlayed) {
+ track.play();
+ hasPlayed = true;
+ }
+ }
+ framesWritten += data.length / bytesPerFrame;
+
+ // track.getTimestamp may return false if there are no physical HAL outputs.
+ // This may occur on TV devices without connecting an HDMI monitor.
+ // It may also be true immediately after start-up, as the mixing thread could
+ // be idle, but since we've already pushed much more than the minimum buffer size,
+ // that is unlikely.
+ // Nevertheless, we don't want to have unnecessary failures, so we ignore the
+ // first iteration if we don't get a timestamp.
+ final boolean result = track.getTimestamp(timestamp);
+ assertTrue(TEST_NAME, result || i == 0);
+ if (!result) {
+ continue;
}
- track.play();
- Thread.sleep(MILLIS_PER_SEC);
- track.pause();
+ final long framesPresented = timestamp.framePosition;
+ final long framesPresentedAt = timestamp.nanoTime;
- framesSeen = track.getPlaybackHeadPosition();
+ // We read timestamp here to ensure that seen is greater than presented.
+ // This is an "on-the-fly" read without pausing because pausing may cause the
+ // timestamp to become stale and affect our jitter measurements.
+ final int framesSeen = track.getPlaybackHeadPosition();
assertTrue(TEST_NAME, framesWritten >= framesSeen);
-
- assertTrue(TEST_NAME, track.getTimestamp(timestamp));
- framesPresented = timestamp.framePosition;
assertTrue(TEST_NAME, framesSeen >= framesPresented);
- // check output frequency
- long outFrequency = framesPresented - lastFramesPresented;
- long freqDiff = Math.abs(FRAMES_PER_SEC - outFrequency);
- assertTrue(TEST_NAME, freqDiff < FRAMES_PER_100_MILLIS);
+ if (i > 1) { // need delta info from previous iteration (skipping first)
+ final long deltaFrames = framesPresented - lastFramesPresented;
+ final long deltaTime = framesPresentedAt - lastFramesPresentedAt;
+ final long NANOSECONDS_PER_SECOND = 1000000000;
+ final long expectedFrames = deltaTime * TEST_SR / NANOSECONDS_PER_SECOND;
+ final long jitterFrames = Math.abs(deltaFrames - expectedFrames);
- // check output frequency jitter
- freqDiff = Math.abs(outFrequency - lastOutputFrequency);
- assertTrue(TEST_NAME, freqDiff < FRAMES_PER_100_MILLIS);
+ //Log.d(TAG, "framesWritten(" + framesWritten
+ // + ") framesSeen(" + framesSeen
+ // + ") framesPresented(" + framesPresented
+ // + ") jitter(" + jitterFrames + ")");
+ // We check that the timestamp position is reasonably accurate.
+ assertTrue(TEST_NAME, deltaTime >= 0);
+ assertTrue(TEST_NAME, deltaFrames >= 0);
+ if (i > 2) {
+ // The first two periods may have inherent jitter as the audio pipe
+ // is filling up. We check jitter only after that.
+ assertTrue(TEST_NAME, jitterFrames < TEST_JITTER_FRAMES_ALLOWED);
+ cumulativeJitter += jitterFrames;
+ cumulativeJitterCount++;
+ if (jitterFrames > maxJitter) {
+ maxJitter = jitterFrames;
+ }
+ }
+
+ //Log.d(TAG, "lastFramesPresentedAt(" + lastFramesPresentedAt
+ // + ") writeTime(" + writeTime
+ // + ") framesPresentedAt(" + framesPresentedAt + ")");
+
+ // We check that the timestamp time is reasonably current.
+ assertTrue(TEST_NAME, framesPresentedAt >= writeTime);
+ assertTrue(TEST_NAME, writeTime >= lastFramesPresentedAt);
+ }
lastFramesPresented = framesPresented;
- lastOutputFrequency = outFrequency;
-
- long frameTime = timestamp.nanoTime;
- assertTrue(TEST_NAME, frameTime >= lastFrameTime);
- lastFrameTime = frameTime;
-
- long curTime = System.nanoTime();
- assertTrue(TEST_NAME, curTime >= frameTime);
- assertTrue(TEST_NAME, curTime - frameTime < 100 * NANOS_PER_MILLI);
+ lastFramesPresentedAt = framesPresentedAt;
}
+ // Full drain.
+ Thread.sleep(WAIT_MSEC);
track.stop();
- // -------- tear down --------------
+ Thread.sleep(WAIT_MSEC);
track.release();
+ // Log the average jitter
+ if (cumulativeJitterCount > 0) {
+ ReportLog log = getReportLog();
+ final float averageJitterInFrames = cumulativeJitter / cumulativeJitterCount;
+ final float averageJitterInMs = averageJitterInFrames * 1000 / TEST_SR;
+ final float maxJitterInMs = maxJitter * 1000 / TEST_SR;
+ // ReportLog needs at least one Value and Summary.
+ log.printValue("Maximum Jitter", maxJitterInMs,
+ ResultType.LOWER_BETTER, ResultUnit.MS);
+ log.printSummary("Average Jitter", averageJitterInMs,
+ ResultType.LOWER_BETTER, ResultUnit.MS);
+ }
}
/* Do not run in JB-MR1. will be re-opened in the next platform release.
diff --git a/tests/tests/media/src/android/media/cts/DecodeEditEncodeTest.java b/tests/tests/media/src/android/media/cts/DecodeEditEncodeTest.java
index bb430e3..9ee3118 100644
--- a/tests/tests/media/src/android/media/cts/DecodeEditEncodeTest.java
+++ b/tests/tests/media/src/android/media/cts/DecodeEditEncodeTest.java
@@ -190,17 +190,17 @@
InputSurface inputSurface = null;
try {
- MediaCodecInfo codecInfo = selectCodec(MIME_TYPE);
- if (codecInfo == null) {
+ // We avoid the device-specific limitations on width and height by using values that
+ // are multiples of 16, which all tested devices seem to be able to handle.
+ MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight);
+
+ String codecName = selectCodec(format);
+ if (codecName == null) {
// Don't fail CTS if they don't have an AVC codec (not here, anyway).
Log.e(TAG, "Unable to find an appropriate codec for " + MIME_TYPE);
return false;
}
- if (VERBOSE) Log.d(TAG, "found codec: " + codecInfo.getName());
-
- // We avoid the device-specific limitations on width and height by using values that
- // are multiples of 16, which all tested devices seem to be able to handle.
- MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight);
+ if (VERBOSE) Log.d(TAG, "found codec: " + codecName);
// Set some properties. Failing to specify some of these can cause the MediaCodec
// configure() call to throw an unhelpful exception.
@@ -214,7 +214,7 @@
// Create a MediaCodec for the desired codec, then configure it as an encoder with
// our desired properties.
- encoder = MediaCodec.createByCodecName(codecInfo.getName());
+ encoder = MediaCodec.createByCodecName(codecName);
encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
inputSurface = new InputSurface(encoder.createInputSurface());
inputSurface.makeCurrent();
@@ -240,23 +240,9 @@
* Returns the first codec capable of encoding the specified MIME type, or null if no
* match was found.
*/
- private static MediaCodecInfo selectCodec(String mimeType) {
- int numCodecs = MediaCodecList.getCodecCount();
- for (int i = 0; i < numCodecs; i++) {
- MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
-
- if (!codecInfo.isEncoder()) {
- continue;
- }
-
- String[] types = codecInfo.getSupportedTypes();
- for (int j = 0; j < types.length; j++) {
- if (types[j].equalsIgnoreCase(mimeType)) {
- return codecInfo;
- }
- }
- }
- return null;
+ private static String selectCodec(MediaFormat format) {
+ MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
+ return mcl.findEncoderForFormat(format);
}
/**
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
index e6530ec..08e6212 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
@@ -39,7 +39,7 @@
if (!supports(AVC_MIME, CodecProfileLevel.AVCProfileBaseline)) {
return;
}
- if (supports(AVC_MIME, CodecProfileLevel.AVCProfileBaseline,
+ if (!supports(AVC_MIME, CodecProfileLevel.AVCProfileBaseline,
CodecProfileLevel.AVCLevel1)) {
throw new RuntimeException("AVCLevel1 support is required by CDD");
}
diff --git a/tests/tests/media/src/android/media/cts/MediaPlayerTest.java b/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
index 10ec741..2815d81 100644
--- a/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
@@ -46,6 +46,8 @@
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
+import junit.framework.AssertionFailedError;
+
/**
* Tests for the MediaPlayer API and local video/audio playback.
*
@@ -1006,9 +1008,18 @@
}
}
- public void testDeselectTrack() throws Exception {
+ public void testDeselectTrack() throws Throwable {
loadResource(R.raw.testvideo_with_2_subtitles);
- loadSubtitleSource(R.raw.test_subtitle1_srt);
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ try {
+ loadSubtitleSource(R.raw.test_subtitle1_srt);
+ } catch (Exception e) {
+ throw new AssertionFailedError(e.getMessage());
+ }
+ }
+ });
+ getInstrumentation().waitForIdleSync();
mMediaPlayer.setDisplay(getActivity().getSurfaceHolder());
mMediaPlayer.setScreenOnWhilePlaying(true);
@@ -1068,7 +1079,7 @@
mMediaPlayer.stop();
}
- public void testChangeSubtitleTrack() throws Exception {
+ public void testChangeSubtitleTrack() throws Throwable {
loadResource(R.raw.testvideo_with_2_subtitles);
mMediaPlayer.setDisplay(getActivity().getSurfaceHolder());
@@ -1104,13 +1115,31 @@
mMediaPlayer.prepare();
assertFalse(mMediaPlayer.isPlaying());
- readTimedTextTracks();
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ try {
+ readTimedTextTracks();
+ } catch (Exception e) {
+ throw new AssertionFailedError(e.getMessage());
+ }
+ }
+ });
+ getInstrumentation().waitForIdleSync();
assertEquals(getTimedTextTrackCount(), 2);
- // Adds two more external subtitle files.
- loadSubtitleSource(R.raw.test_subtitle1_srt);
- loadSubtitleSource(R.raw.test_subtitle2_srt);
- readTimedTextTracks();
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ try {
+ // Adds two more external subtitle files.
+ loadSubtitleSource(R.raw.test_subtitle1_srt);
+ loadSubtitleSource(R.raw.test_subtitle2_srt);
+ readTimedTextTracks();
+ } catch (Exception e) {
+ throw new AssertionFailedError(e.getMessage());
+ }
+ }
+ });
+ getInstrumentation().waitForIdleSync();
assertEquals(getTimedTextTrackCount(), 4);
selectSubtitleTrack(0);
@@ -1138,10 +1167,19 @@
mMediaPlayer.stop();
}
- public void testGetTrackInfo() throws Exception {
+ public void testGetTrackInfo() throws Throwable {
loadResource(R.raw.testvideo_with_2_subtitles);
- loadSubtitleSource(R.raw.test_subtitle1_srt);
- loadSubtitleSource(R.raw.test_subtitle2_srt);
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ try {
+ loadSubtitleSource(R.raw.test_subtitle1_srt);
+ loadSubtitleSource(R.raw.test_subtitle2_srt);
+ } catch (Exception e) {
+ throw new AssertionFailedError(e.getMessage());
+ }
+ }
+ });
+ getInstrumentation().waitForIdleSync();
mMediaPlayer.prepare();
mMediaPlayer.start();
diff --git a/tests/tests/media/src/android/media/cts/Vp8CodecTestBase.java b/tests/tests/media/src/android/media/cts/Vp8CodecTestBase.java
index 40d09a5..5e38842 100644
--- a/tests/tests/media/src/android/media/cts/Vp8CodecTestBase.java
+++ b/tests/tests/media/src/android/media/cts/Vp8CodecTestBase.java
@@ -390,6 +390,32 @@
return yuv;
}
+ /**
+ * Packs YUV420 frame by moving it to a smaller size buffer with stride and slice
+ * height equal to the original frame width and height.
+ */
+ private static byte[] PackYUV420(int width, int height,
+ int stride, int sliceHeight, byte[] src) {
+ byte[] dst = new byte[width * height * 3 / 2];
+ // Y copy.
+ for (int i = 0; i < height; i++) {
+ System.arraycopy(src, i * stride, dst, i * width, width);
+ }
+ // U and V copy.
+ int u_src_offset = stride * sliceHeight;
+ int v_src_offset = u_src_offset + u_src_offset / 4;
+ int u_dst_offset = width * height;
+ int v_dst_offset = u_dst_offset + u_dst_offset / 4;
+ for (int i = 0; i < height / 2; i++) {
+ System.arraycopy(src, u_src_offset + i * (stride / 2),
+ dst, u_dst_offset + i * (width / 2), width / 2);
+ System.arraycopy(src, v_src_offset + i * (stride / 2),
+ dst, v_dst_offset + i * (width / 2), width / 2);
+ }
+ return dst;
+ }
+
+
private static void imageUpscale1To2(byte[] src, int srcByteOffset, int srcStride,
byte[] dst, int dstByteOffset, int dstWidth, int dstHeight) {
for (int i = 0; i < dstHeight/2 - 1; i++) {
@@ -624,15 +650,16 @@
}
Log.d(TAG, "Frame stride and slice height: " + frameStride +
" x " + frameSliceHeight);
+ frameStride = Math.max(frameWidth, frameStride);
+ frameSliceHeight = Math.max(frameHeight, frameSliceHeight);
}
result = decoder.dequeueOutputBuffer(bufferInfo, DEFAULT_DEQUEUE_TIMEOUT_US);
}
if (result >= 0) {
int outputBufIndex = result;
- int bufferSize = Math.min(frameWidth * frameHeight * 3 / 2, bufferInfo.size);
outPresentationTimeUs = bufferInfo.presentationTimeUs;
Log.v(TAG, "Writing buffer # " + outputFrameIndex +
- ". Size: " + bufferSize +
+ ". Size: " + bufferInfo.size +
". InTime: " + (inPresentationTimeUs + 500)/1000 +
". OutTime: " + (outPresentationTimeUs + 500)/1000);
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
@@ -640,25 +667,32 @@
Log.d(TAG, " Output EOS for frame # " + outputFrameIndex);
}
- if (bufferSize > 0) {
+ if (bufferInfo.size > 0) {
// Save decoder output to yuv file.
if (yuv != null) {
- byte[] frame = new byte[bufferSize];
+ byte[] frame = new byte[bufferInfo.size];
outputBuffers[outputBufIndex].position(bufferInfo.offset);
- outputBuffers[outputBufIndex].get(frame, 0, bufferSize);
- // Convert NV12 to YUV420 if necessary
+ outputBuffers[outputBufIndex].get(frame, 0, bufferInfo.size);
+ // Convert NV12 to YUV420 if necessary.
if (frameColorFormat != CodecCapabilities.COLOR_FormatYUV420Planar) {
frame = NV12ToYUV420(frameWidth, frameHeight,
frameStride, frameSliceHeight, frame);
}
- yuv.write(frame);
+ int writeLength = Math.min(frameWidth * frameHeight * 3 / 2, frame.length);
+ // Pack frame if necessary.
+ if (writeLength < frame.length &&
+ (frameStride > frameWidth || frameSliceHeight > frameHeight)) {
+ frame = PackYUV420(frameWidth, frameHeight,
+ frameStride, frameSliceHeight, frame);
+ }
+ yuv.write(frame, 0, writeLength);
}
outputFrameIndex++;
// Update statistics - store presentation time delay in offset
long presentationTimeUsDelta = inPresentationTimeUs - outPresentationTimeUs;
MediaCodec.BufferInfo bufferInfoCopy = new MediaCodec.BufferInfo();
- bufferInfoCopy.set((int)presentationTimeUsDelta, bufferSize,
+ bufferInfoCopy.set((int)presentationTimeUsDelta, bufferInfo.size,
outPresentationTimeUs, bufferInfo.flags);
bufferInfos.add(bufferInfoCopy);
}
diff --git a/tests/tests/opengl/AndroidManifest.xml b/tests/tests/opengl/AndroidManifest.xml
index 914b2d2..363b9aa 100644
--- a/tests/tests/opengl/AndroidManifest.xml
+++ b/tests/tests/opengl/AndroidManifest.xml
@@ -27,9 +27,11 @@
<meta-data android:name="listener"
android:value="com.android.cts.runner.CtsTestRunListener" />
</instrumentation>
+
<application
android:icon="@drawable/ic_launcher"
- android:label="@string/app_name" >
+ android:label="@string/app_name"
+ android:hardwareAccelerated="false" >
<activity
android:label="@string/app_name"
diff --git a/tests/tests/os/Android.mk b/tests/tests/os/Android.mk
index 0007a54..f0fb88a 100644
--- a/tests/tests/os/Android.mk
+++ b/tests/tests/os/Android.mk
@@ -23,17 +23,21 @@
LOCAL_PROGUARD_ENABLED := disabled
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner guava
+LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner guava
+
+LOCAL_JNI_SHARED_LIBRARIES := libctsos_jni
LOCAL_SRC_FILES := $(call all-java-files-under, src) \
- src/android/os/cts/IParcelFileDescriptorPeer.aidl
+ src/android/os/cts/IParcelFileDescriptorPeer.aidl \
+ src/android/os/cts/IEmptyService.aidl \
+ src/android/os/cts/ISecondary.aidl
LOCAL_PACKAGE_NAME := CtsOsTestCases
-LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
-
# uncomment when b/13282254 is fixed
#LOCAL_SDK_VERSION := current
LOCAL_JAVA_LIBRARIES += android.test.runner
include $(BUILD_CTS_PACKAGE)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/os/AndroidManifest.xml b/tests/tests/os/AndroidManifest.xml
index 155e772..f225903 100644
--- a/tests/tests/os/AndroidManifest.xml
+++ b/tests/tests/os/AndroidManifest.xml
@@ -18,11 +18,52 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.cts.os">
+ <permission android:name="android.os.cts.permission.TEST_GRANTED"
+ android:protectionLevel="normal"
+ android:label="@string/permlab_testGranted"
+ android:description="@string/permdesc_testGranted">
+ <meta-data android:name="android.os.cts.string" android:value="foo" />
+ <meta-data android:name="android.os.cts.boolean" android:value="true" />
+ <meta-data android:name="android.os.cts.integer" android:value="100" />
+ <meta-data android:name="android.os.cts.color" android:value="#ff000000" />
+ <meta-data android:name="android.os.cts.float" android:value="100.1" />
+ <meta-data android:name="android.os.cts.reference" android:resource="@xml/metadata" />
+ </permission>
+
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
+ <uses-permission android:name="android.permission.VIBRATE" />
+ <uses-permission android:name="android.permission.SEND_SMS" />
+ <uses-permission android:name="android.permission.RECEIVE_SMS" />
+ <uses-permission android:name="android.permission.READ_SMS"/>
+ <uses-permission android:name="android.permission.WRITE_SMS"/>
+ <uses-permission android:name="android.permission.CALL_PHONE" />
+ <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
+ <uses-permission android:name="android.permission.DEVICE_POWER" />
+ <uses-permission android:name="android.os.cts.permission.TEST_GRANTED" />
<application>
+ <activity android:name="android.os.cts.LaunchpadActivity"
+ android:configChanges="keyboardHidden|orientation|screenSize"
+ android:multiprocess="true">
+ </activity>
+
+ <activity android:name="android.os.cts.AliasActivityStub">
+ <meta-data android:name="android.os.alias"
+ android:resource="@xml/alias" />
+ </activity>
+
+ <activity android:name="android.os.cts.CountDownTimerTestStub"
+ android:label="CountDownTimerTestStub">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+ </intent-filter>
+ </activity>
+
<service
android:name="android.os.cts.ParcelFileDescriptorPeer$Red"
android:process=":red"
@@ -31,11 +72,63 @@
android:name="android.os.cts.ParcelFileDescriptorPeer$Blue"
android:process=":blue"
android:exported="true" />
+
+ <service android:name="android.os.cts.LocalService">
+ <intent-filter>
+ <action android:name="android.os.cts.activity.SERVICE_LOCAL" />
+ </intent-filter>
+ <meta-data android:name="android.os.cts.string" android:value="foo" />
+ <meta-data android:name="android.os.cts.boolean" android:value="true" />
+ <meta-data android:name="android.os.cts.integer" android:value="100" />
+ <meta-data android:name="android.os.cts.color" android:value="#ff000000" />
+ <meta-data android:name="android.os.cts.float" android:value="100.1" />
+ <meta-data android:name="android.os.cts.reference" android:resource="@xml/metadata" />
+ </service>
+
+ <service android:name="android.os.cts.LocalGrantedService"
+ android:permission="android.os.cts.permission.TEST_GRANTED">
+ <intent-filter>
+ <action android:name="android.os.cts.activity.SERVICE_LOCAL_GRANTED" />
+ </intent-filter>
+ </service>
+
+ <service android:name="android.os.cts.LocalDeniedService"
+ android:permission="android.os.cts.permission.TEST_DENIED">
+ <intent-filter>
+ <action android:name="android.os.cts.activity.SERVICE_LOCAL_DENIED" />
+ </intent-filter>
+ </service>
+
+
+ <service android:name="android.os.cts.EmptyService"
+ android:process=":remote">
+ <intent-filter>
+ <action
+ android:name="android.os.cts.IEmptyService" />
+ <action
+ android:name="android.os.REMOTESERVICE" />
+ </intent-filter>
+ </service>
+
+ <service android:name="android.os.cts.CtsRemoteService"
+ android:process=":remote">
+ <intent-filter>
+ <action
+ android:name="android.os.cts.ISecondary" />
+ <action
+ android:name="android.os.REMOTESERVICE" />
+ </intent-filter>
+ </service>
+
+ <service android:name="android.os.cts.MessengerService"
+ android:process=":messengerService">
+ </service>
+
<uses-library android:name="android.test.runner" />
</application>
<instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
- android:targetPackage="com.android.cts.stub"
+ android:targetPackage="com.android.cts.os"
android:label="CTS tests of android.os">
<meta-data android:name="listener"
android:value="com.android.cts.runner.CtsTestRunListener" />
diff --git a/tests/assets/alter-footer.zip b/tests/tests/os/assets/alter-footer.zip
similarity index 100%
rename from tests/assets/alter-footer.zip
rename to tests/tests/os/assets/alter-footer.zip
Binary files differ
diff --git a/tests/assets/alter-metadata.zip b/tests/tests/os/assets/alter-metadata.zip
similarity index 100%
rename from tests/assets/alter-metadata.zip
rename to tests/tests/os/assets/alter-metadata.zip
Binary files differ
diff --git a/tests/assets/fake-eocd.zip b/tests/tests/os/assets/fake-eocd.zip
similarity index 100%
rename from tests/assets/fake-eocd.zip
rename to tests/tests/os/assets/fake-eocd.zip
Binary files differ
diff --git a/tests/assets/jarsigned.zip b/tests/tests/os/assets/jarsigned.zip
similarity index 100%
rename from tests/assets/jarsigned.zip
rename to tests/tests/os/assets/jarsigned.zip
Binary files differ
diff --git a/tests/assets/otacerts.zip b/tests/tests/os/assets/otacerts.zip
similarity index 100%
rename from tests/assets/otacerts.zip
rename to tests/tests/os/assets/otacerts.zip
Binary files differ
diff --git a/tests/assets/otasigned.zip b/tests/tests/os/assets/otasigned.zip
similarity index 100%
rename from tests/assets/otasigned.zip
rename to tests/tests/os/assets/otasigned.zip
Binary files differ
diff --git a/tests/assets/random.zip b/tests/tests/os/assets/random.zip
similarity index 100%
rename from tests/assets/random.zip
rename to tests/tests/os/assets/random.zip
Binary files differ
diff --git a/tests/assets/unsigned.zip b/tests/tests/os/assets/unsigned.zip
similarity index 100%
rename from tests/assets/unsigned.zip
rename to tests/tests/os/assets/unsigned.zip
Binary files differ
diff --git a/tests/jni/Android.mk b/tests/tests/os/jni/Android.mk
similarity index 95%
rename from tests/jni/Android.mk
rename to tests/tests/os/jni/Android.mk
index a3e401e..a39b5d1 100644
--- a/tests/jni/Android.mk
+++ b/tests/tests/os/jni/Android.mk
@@ -16,13 +16,13 @@
include $(CLEAR_VARS)
-LOCAL_MODULE := libcts_jni
+LOCAL_MODULE := libctsos_jni
# Don't include this package in any configuration by default.
LOCAL_MODULE_TAGS := optional
LOCAL_SRC_FILES := \
- CtsJniOnLoad.cpp \
+ CtsOsJniOnLoad.cpp \
android_os_cts_CpuInstructions.cpp.arm \
android_os_cts_TaggedPointer.cpp \
android_os_cts_OSFeatures.cpp \
diff --git a/tests/jni/CtsJniOnLoad.cpp b/tests/tests/os/jni/CtsOsJniOnLoad.cpp
similarity index 100%
rename from tests/jni/CtsJniOnLoad.cpp
rename to tests/tests/os/jni/CtsOsJniOnLoad.cpp
diff --git a/tests/jni/android_os_cts_CpuFeatures.cpp b/tests/tests/os/jni/android_os_cts_CpuFeatures.cpp
similarity index 100%
rename from tests/jni/android_os_cts_CpuFeatures.cpp
rename to tests/tests/os/jni/android_os_cts_CpuFeatures.cpp
diff --git a/tests/jni/android_os_cts_CpuInstructions.cpp b/tests/tests/os/jni/android_os_cts_CpuInstructions.cpp
similarity index 100%
rename from tests/jni/android_os_cts_CpuInstructions.cpp
rename to tests/tests/os/jni/android_os_cts_CpuInstructions.cpp
diff --git a/tests/jni/android_os_cts_FileUtils.cpp b/tests/tests/os/jni/android_os_cts_FileUtils.cpp
similarity index 100%
rename from tests/jni/android_os_cts_FileUtils.cpp
rename to tests/tests/os/jni/android_os_cts_FileUtils.cpp
diff --git a/tests/jni/android_os_cts_OSFeatures.cpp b/tests/tests/os/jni/android_os_cts_OSFeatures.cpp
similarity index 100%
rename from tests/jni/android_os_cts_OSFeatures.cpp
rename to tests/tests/os/jni/android_os_cts_OSFeatures.cpp
diff --git a/tests/jni/android_os_cts_TaggedPointer.cpp b/tests/tests/os/jni/android_os_cts_TaggedPointer.cpp
similarity index 100%
rename from tests/jni/android_os_cts_TaggedPointer.cpp
rename to tests/tests/os/jni/android_os_cts_TaggedPointer.cpp
diff --git a/tests/tests/os/res/raw/test1.obb b/tests/tests/os/res/raw/test1.obb
new file mode 100644
index 0000000..33479aa
--- /dev/null
+++ b/tests/tests/os/res/raw/test1.obb
Binary files differ
diff --git a/tests/tests/os/res/raw/test1_nosig.obb b/tests/tests/os/res/raw/test1_nosig.obb
new file mode 100644
index 0000000..5c3573f
--- /dev/null
+++ b/tests/tests/os/res/raw/test1_nosig.obb
Binary files differ
diff --git a/tests/tests/os/res/raw/test1_wrongpackage.obb b/tests/tests/os/res/raw/test1_wrongpackage.obb
new file mode 100644
index 0000000..d0aafe1
--- /dev/null
+++ b/tests/tests/os/res/raw/test1_wrongpackage.obb
Binary files differ
diff --git a/tests/tests/os/res/values/strings.xml b/tests/tests/os/res/values/strings.xml
new file mode 100644
index 0000000..c167278
--- /dev/null
+++ b/tests/tests/os/res/values/strings.xml
@@ -0,0 +1,179 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string name="permlab_testGranted">Test Granted</string>
+ <string name="permdesc_testGranted">Used for running CTS tests, for testing operations
+ where we have the permission.</string>
+ <string name="permlab_testDynamic">Test Dynamic</string>
+ <string name="permdesc_testDynamic">Used for running CTS tests, for testing adding
+ dynamic permissions.</string>
+ <string name="permlab_testDenied">Test Denied</string>
+ <string name="permdesc_testDenied">Used for running CTS tests, for testing operations
+ where we do not have the permission.</string>
+ <string name="explain">1. click start. \n2. if above image shaked, then press pass button,
+ else press failed button.</string>
+ <string name="text_view_hello">Hello! Text view!</string>
+ <string name="text_view_hello_two_lines">Hello! \nText view!</string>
+ <string name="text_view_simple_hint">This is a hint.</string>
+ <string name="text_view_hint">This is a string for testing hint of textview.</string>
+ <string name="activity_forwarding">App/Forwarding</string>
+ <string name="forwarding">$$$</string>
+ <string name="go">Go</string>
+ <string name="back">Back</string>
+ <string name="forward_target">
+ Press back button and notice we don\'t see the previous activity.
+ </string>
+ <string name="edit_text">testing</string>
+ <string name="text">DialogTest</string>
+ <string name="text_country">Country</string>
+ <string name="text_name">Name</string>
+ <string name="hello_world">Hello, World!</string>
+ <string name="hello_android">Hello, Android!</string>
+ <string name="alert_dialog_username">Name:</string>
+ <string name="alert_dialog_password">Password:</string>
+ <string name="alert_dialog_positive">Positive</string>
+ <string name="alert_dialog_negative">Negative</string>
+ <string name="alert_dialog_neutral">Neutral</string>
+ <string name="notify">Notify </string>
+ <string name="tabs_1">testing</string>
+ <string name="table_layout_first">first</string>
+ <string name="table_layout_second">second</string>
+ <string name="table_layout_third">third</string>
+ <string name="table_layout_long">Very long to make the string out of the screen</string>
+ <string name="chronometer_text">Test Chronometer</string>
+ <string name="am">AM</string>
+ <string name="pm">PM</string>
+ <string name="viewgroup_test">ViewGroup test</string>
+ <string name="viewanimator_test">ViewAnimator test</string>
+ <string name="id_ok">OK</string>
+ <string name="id_cancel">Cancel</string>
+ <string name="context_test_string1">This is %s string.</string>
+ <string name="context_test_string2">This is test string.</string>
+ <string name="animationutils_test_instructions">Choose different animations</string>
+ <string name="animationutils_test_alpha">Alpha animation</string>
+ <string name="animationutils_test_scale">Scale animation</string>
+ <string name="animationutils_test_rotate">Rotate animation</string>
+ <string name="animationutils_test_translate">Translate animation</string>
+ <string name="animationutils_test_set">Animation set</string>
+ <string name="animationutils_test_layout">Layout animation</string>
+ <string name="animationutils_test_gridlayout">Grid layout animation</string>
+ <string name="twolinelistitem_test_text1">text1</string>
+ <string name="twolinelistitem_test_text2">text2</string>
+ <string name="metadata_text">metadata text</string>
+ <string name="horizontal_text_1">horizontal 1</string>
+ <string name="horizontal_text_2">horizontal 2</string>
+ <string name="horizontal_text_3">horizontal 3</string>
+ <string name="vertical_text_1">vertical 1</string>
+ <string name="vertical_text_2">vertical 2</string>
+ <string name="vertical_text_3">vertical 3</string>
+ <string name="reference">here</string>
+ <string name="coerceIntegerToString">100</string>
+ <string name="coerceBooleanToString">true</string>
+ <string name="coerceColorToString">#fff</string>
+ <string name="coerceFloatToString">100.0</string>
+ <string name="coerceDimensionToString">100px</string>
+ <string name="coerceFractionToString">100<xliff:g id="percent">%</xliff:g></string>
+ <string name="formattedStringNone">Format[]</string>
+ <string name="formattedStringOne">Format[<xliff:g id="format">%d</xliff:g>]</string>
+ <string name="formattedStringTwo">Format[<xliff:g id="format">%3$d,%2$s</xliff:g>]</string>
+ <string name="checkboxpref_key">checkboxpref_key</string>
+ <string name="checkboxpref_title">title of preference</string>
+ <string name="checkboxpref_summary">summary of preference</string>
+ <string name="checkboxpref_summary_on">summary on of preference</string>
+ <string name="checkboxpref_summary_off">summary off of preference</string>
+ <string name="checkboxpref_depend">checkboxpref_depend</string>
+ <string name="checkboxpref_depend_title"> depend title of preference</string>
+ <string name="checkboxpref_depend_summary"> depend summary of preference</string>
+ <string name="edittextpref_key">edittextpref_key</string>
+ <string name="edittextpref_default_value">default value of preference</string>
+ <string name="edittextpref_title">title of edit text preference</string>
+ <string name="edittextpref_summary">summary of edit text preference</string>
+ <string name="edittextpref_dialog_title">dialog title of edit text preference</string>
+ <string name="edittextpref_text">text of edit text preference</string>
+ <string name="listpref_key">listpref_key</string>
+ <string name="listpref_title">title of list preference</string>
+ <string name="listpref_summary">summary of list preference</string>
+ <string name="listpref_dialogtitle">dialog title of list preference</string>
+ <string name="easy">Easy</string>
+ <string name="medium">Medium</string>
+ <string name="hard">Hard</string>
+ <string name="footer_view">Footer view</string>
+ <string name="header_view">Header view</string>
+ <string name="dialogpref_title">title of dialog preference </string>
+ <string name="dialogpref_dialog_title">dialog title of dialog preference </string>
+ <string name="dialogpref_key">dialogpref_key</string>
+ <string name="dialogpref_default_value">default value of dialog preference</string>
+ <string name="dialogpref_summary">summary of dialog preference</string>
+ <string name="dialogpref_message">message of dialog preference</string>
+ <string name="dialogpref_sure">Sure</string>
+ <string name="dialogpref_cancel">Cancel</string>
+ <string name="pref_key">pref_key</string>
+ <string name="pref_title">title of preference</string>
+ <string name="pref_summary">summary of preference</string>
+ <string name="pref_depend_key">pref_depend_key</string>
+ <string name="pref_depend_title"> depend title of preference</string>
+ <string name="pref_depend_summary"> depend summary of preference</string>
+ <string name="android_intent_action_preference">android.intent.action.PREFERENCE</string>
+ <string name="def_pref_key">def_pref_key</string>
+ <string name="def_pref_title">default preference</string>
+ <string name="def_pref_summary">This is default preference of cts</string>
+ <string name="relative_view1">view 1</string>
+ <string name="relative_view2">view 2</string>
+ <string name="relative_view3">view 3</string>
+ <string name="relative_view4">view 4</string>
+ <string name="relative_view5">view 5</string>
+ <string name="relative_view6">view 6</string>
+ <string name="relative_view7">view 7</string>
+ <string name="relative_view8">view 8</string>
+ <string name="relative_view9">view 9</string>
+ <string name="relative_view10">view 10</string>
+ <string name="relative_view11">view 11</string>
+ <string name="relative_view12">view 12</string>
+ <string name="relative_view13">view 13</string>
+ <string name="country">Country:</string>
+ <string name="symbol">Symbol:</string>
+ <string name="country_warning">No such country registered</string>
+ <string name="version_cur">base</string>
+ <string name="version_old">base</string>
+ <string name="version_v3">base</string>
+ <string name="authenticator_label">Android CTS</string>
+ <string name="search_label">Android CTS</string>
+ <string name="tag1">tag 1</string>
+ <string name="tag2">tag 2</string>
+
+ <string name="button">Button</string>
+ <string name="holo_test">Holo Test</string>
+ <string name="holo_generator">Holo Generator</string>
+ <string name="holo_light_test">Holo Light Test</string>
+ <string name="holo_light_generator">Holo Light Generator</string>
+ <string name="reference_image">Reference Image: </string>
+ <string name="generated_image">Generated Image: </string>
+ <string name="themes_prompt">Select a Theme:</string>
+ <string name="sample_text">Sample text goes here. I wanted something creative and whimsical
+but then I just got bored...</string>
+ <string name="long_text">This is a really long string which exceeds the width of the view.
+New devices have a much larger screen which actually enables long strings to be displayed
+with no fading. I have made this string longer to fix this case. If you are correcting this
+text, I would love to see the kind of devices you guys now use! Guys, maybe some devices need longer string!
+I think so, so how about double this string, like copy and paste!
+This is a really long string which exceeds the width of the view.
+New devices have a much larger screen which actually enables long strings to be displayed
+with no fading. I have made this string longer to fix this case. If you are correcting this
+text, I would love to see the kind of devices you guys now use! Guys, maybe some devices need longer string!
+I think so, so how about double this string, like copy and paste! </string>
+ <string name="rectangle200">"M 0,0 l 200,0 l 0, 200 l -200, 0 z"</string>
+</resources>
diff --git a/tests/tests/os/res/xml/alias.xml b/tests/tests/os/res/xml/alias.xml
new file mode 100644
index 0000000..1166669
--- /dev/null
+++ b/tests/tests/os/res/xml/alias.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+ * Copyright (C) 2008 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.
+ */
+-->
+
+<alias xmlns:android="http://schemas.android.com/apk/res/android">
+ <intent android:action="android.intent.action.MAIN"
+ android:targetPackage="com.android.cts.os"
+ android:targetClass="android.os.cts.ChildActivity"
+ android:data="http://www.google.com/">
+ </intent>
+</alias>
+
diff --git a/tests/tests/os/res/xml/metadata.xml b/tests/tests/os/res/xml/metadata.xml
new file mode 100644
index 0000000..336b931
--- /dev/null
+++ b/tests/tests/os/res/xml/metadata.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 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.
+-->
+
+<thedata xmlns:android="http://schemas.android.com/apk/res/android"
+ rawText="some raw text"
+ rawColor="#ffffff00"
+ android:color="#f00"
+ android:text="@string/metadata_text"/>
diff --git a/tests/tests/os/src/android/os/cts/ActivityTestsBase.java b/tests/tests/os/src/android/os/cts/ActivityTestsBase.java
new file mode 100644
index 0000000..3f7d91d
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/ActivityTestsBase.java
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2008 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.cts;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.test.AndroidTestCase;
+import android.test.PerformanceTestCase;
+
+public class ActivityTestsBase extends AndroidTestCase implements PerformanceTestCase,
+ LaunchpadActivity.CallingTest {
+ public static final String PERMISSION_GRANTED = "android.os.cts.permission.TEST_GRANTED";
+ public static final String PERMISSION_DENIED = "android.os.cts.permission.TEST_DENIED";
+
+ private static final int TIMEOUT_MS = 60 * 1000;
+
+ protected Intent mIntent;
+
+ private PerformanceTestCase.Intermediates mIntermediates;
+ private String mExpecting;
+
+ // Synchronization of activity result.
+ private boolean mFinished;
+ private int mResultCode = 0;
+ private Intent mData;
+ private RuntimeException mResultStack = null;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ mIntent = new Intent(mContext, LaunchpadActivity.class);
+ mIntermediates = null;
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ mIntermediates = null;
+ super.tearDown();
+ }
+
+ public boolean isPerformanceOnly() {
+ return false;
+ }
+
+ public void setInternalIterations(int count) {
+ }
+
+ public void startTiming(boolean realTime) {
+ if (mIntermediates != null) {
+ mIntermediates.startTiming(realTime);
+ }
+ }
+
+ public void addIntermediate(String name) {
+ if (mIntermediates != null) {
+ mIntermediates.addIntermediate(name);
+ }
+ }
+
+ public void addIntermediate(String name, long timeInNS) {
+ if (mIntermediates != null) {
+ mIntermediates.addIntermediate(name, timeInNS);
+ }
+ }
+
+ public void finishTiming(boolean realTime) {
+ if (mIntermediates != null) {
+ mIntermediates.finishTiming(realTime);
+ }
+ }
+
+ public void activityFinished(int resultCode, Intent data, RuntimeException where) {
+ finishWithResult(resultCode, data, where);
+ }
+
+ public Intent editIntent() {
+ return mIntent;
+ }
+
+ @Override
+ public Context getContext() {
+ return mContext;
+ }
+
+ public int startPerformance(Intermediates intermediates) {
+ mIntermediates = intermediates;
+ return 1;
+ }
+
+ public void finishGood() {
+ finishWithResult(Activity.RESULT_OK, null);
+ }
+
+ public void finishBad(String error) {
+ finishWithResult(Activity.RESULT_CANCELED, new Intent().setAction(error));
+ }
+
+ public void finishWithResult(int resultCode, Intent data) {
+ final RuntimeException where = new RuntimeException("Original error was here");
+ where.fillInStackTrace();
+ finishWithResult(resultCode, data, where);
+ }
+
+ public void finishWithResult(int resultCode, Intent data, RuntimeException where) {
+ synchronized (this) {
+ mResultCode = resultCode;
+ mData = data;
+ mResultStack = where;
+ mFinished = true;
+ notifyAll();
+ }
+ }
+
+ public int runLaunchpad(String action) {
+ startLaunchpadActivity(action);
+ return waitForResultOrThrow(TIMEOUT_MS);
+ }
+
+ private void startLaunchpadActivity(String action) {
+ LaunchpadActivity.setCallingTest(this);
+
+ synchronized (this) {
+ mIntent.setAction(action);
+ mFinished = false;
+ mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ mContext.startActivity(mIntent);
+ }
+ }
+
+ public int waitForResultOrThrow(int timeoutMs) {
+ return waitForResultOrThrow(timeoutMs, null);
+ }
+
+ public int waitForResultOrThrow(int timeoutMs, String expected) {
+ final int res = waitForResult(timeoutMs, expected);
+
+ if (res == Activity.RESULT_CANCELED) {
+ if (mResultStack != null) {
+ throw new RuntimeException(mData != null ? mData.toString() : "Unable to launch",
+ mResultStack);
+ } else {
+ throw new RuntimeException(mData != null ? mData.toString() : "Unable to launch");
+ }
+ }
+ return res;
+ }
+
+ public int waitForResult(int timeoutMs, String expected) {
+ mExpecting = expected;
+
+ final long endTime = System.currentTimeMillis() + timeoutMs;
+
+ boolean timeout = false;
+ synchronized (this) {
+ while (!mFinished) {
+ final long delay = endTime - System.currentTimeMillis();
+ if (delay < 0) {
+ timeout = true;
+ break;
+ }
+
+ try {
+ wait(delay);
+ } catch (final java.lang.InterruptedException e) {
+ // do nothing
+ }
+ }
+ }
+
+ mFinished = false;
+
+ if (timeout) {
+ mResultCode = Activity.RESULT_CANCELED;
+ onTimeout();
+ }
+ return mResultCode;
+ }
+
+
+ public int getResultCode() {
+ return mResultCode;
+ }
+
+ public Intent getResultData() {
+ return mData;
+ }
+
+ public RuntimeException getResultStack() {
+ return mResultStack;
+ }
+
+ public void onTimeout() {
+ final String msg = mExpecting == null ? "Timeout" : "Timeout while expecting " + mExpecting;
+ finishWithResult(Activity.RESULT_CANCELED, new Intent().setAction(msg));
+ }
+}
diff --git a/tests/src/android/text/style/cts/MockURLSpanTestActivity.java b/tests/tests/os/src/android/os/cts/AliasActivityStub.java
similarity index 63%
rename from tests/src/android/text/style/cts/MockURLSpanTestActivity.java
rename to tests/tests/os/src/android/os/cts/AliasActivityStub.java
index 1edb3e0..cff405e 100644
--- a/tests/src/android/text/style/cts/MockURLSpanTestActivity.java
+++ b/tests/tests/os/src/android/os/cts/AliasActivityStub.java
@@ -13,21 +13,25 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+package android.os.cts;
-package android.text.style.cts;
-
-import com.android.cts.stub.R;
-
-import android.app.Activity;
+import android.app.AliasActivity;
import android.os.Bundle;
-/**
- * A Mock application for {@link URLSpan} test.
- */
-public class MockURLSpanTestActivity extends Activity {
+public class AliasActivityStub extends AliasActivity {
+
+ public static boolean isOnCreateCalled = false;
+ public static boolean isFinished = false;
+
@Override
- public void onCreate(Bundle savedInstanceState) {
+ protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- setContentView(R.layout.urlspan_layout);
+ isOnCreateCalled = true;
+ }
+
+ @Override
+ public void finish() {
+ super.finish();
+ isFinished = true;
}
}
diff --git a/tests/tests/os/src/android/os/cts/BinderTest.java b/tests/tests/os/src/android/os/cts/BinderTest.java
index 7a30169..435e247 100644
--- a/tests/tests/os/src/android/os/cts/BinderTest.java
+++ b/tests/tests/os/src/android/os/cts/BinderTest.java
@@ -20,8 +20,6 @@
import java.io.FileDescriptor;
import java.io.PrintWriter;
-import android.app.cts.ActivityTestsBase;
-import android.app.cts.LocalService;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
diff --git a/tests/tests/os/src/android/os/cts/ClearTop.java b/tests/tests/os/src/android/os/cts/ClearTop.java
new file mode 100644
index 0000000..278336c
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/ClearTop.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2008 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.cts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.util.Log;
+
+public class ClearTop extends Activity {
+ public static final String WAIT_CLEAR_TASK = "waitClearTask";
+ private static final String TAG = "ClearTop";
+ public ClearTop() {
+ }
+
+ @Override
+ public void onCreate(Bundle icicle) {
+ super.onCreate(icicle);
+ final Intent intent = new Intent(getIntent()).setAction(LocalScreen.CLEAR_TASK).setClass(
+ this, LocalScreen.class);
+ startActivity(intent);
+ }
+
+ @Override
+ public void onNewIntent(Intent intent) {
+ Log.i(TAG, "onNewIntent");
+ if (LocalScreen.CLEAR_TASK.equals(intent.getAction())) {
+ setResult(RESULT_OK);
+ } else {
+ setResult(RESULT_CANCELED, new Intent().setAction("New intent received " + intent
+ + ", expecting action " + TestedScreen.CLEAR_TASK));
+ }
+ finish();
+ }
+}
diff --git a/tests/src/android/os/cts/CountDownTimerTestStub.java b/tests/tests/os/src/android/os/cts/CountDownTimerTestStub.java
similarity index 100%
rename from tests/src/android/os/cts/CountDownTimerTestStub.java
rename to tests/tests/os/src/android/os/cts/CountDownTimerTestStub.java
diff --git a/tests/src/android/os/cts/CpuFeatures.java b/tests/tests/os/src/android/os/cts/CpuFeatures.java
similarity index 97%
rename from tests/src/android/os/cts/CpuFeatures.java
rename to tests/tests/os/src/android/os/cts/CpuFeatures.java
index fa6628b..553f264 100644
--- a/tests/src/android/os/cts/CpuFeatures.java
+++ b/tests/tests/os/src/android/os/cts/CpuFeatures.java
@@ -41,7 +41,7 @@
public static final int HWCAP_IDIVT = (1 << 18);
static {
- System.loadLibrary("cts_jni");
+ System.loadLibrary("ctsos_jni");
}
public static native boolean isArmCpu();
diff --git a/tests/src/android/os/cts/CpuInstructions.java b/tests/tests/os/src/android/os/cts/CpuInstructions.java
similarity index 95%
rename from tests/src/android/os/cts/CpuInstructions.java
rename to tests/tests/os/src/android/os/cts/CpuInstructions.java
index e001ceb..45fb2f1 100644
--- a/tests/src/android/os/cts/CpuInstructions.java
+++ b/tests/tests/os/src/android/os/cts/CpuInstructions.java
@@ -19,7 +19,7 @@
public class CpuInstructions {
static {
- System.loadLibrary("cts_jni");
+ System.loadLibrary("ctsos_jni");
}
public static native boolean canReadCntvct();
diff --git a/tests/tests/os/src/android/os/cts/CtsRemoteService.java b/tests/tests/os/src/android/os/cts/CtsRemoteService.java
new file mode 100644
index 0000000..daae49e
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/CtsRemoteService.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2008 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.cts;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.os.Process;
+
+public class CtsRemoteService extends Service{
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ android.util.Log.d("Process test stub", "CtsRemoteServiceProcessPid:" + Process.myPid());
+ }
+
+ private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() {
+ public int getPid() {
+ return Process.myPid();
+ }
+
+ public long getElapsedCpuTime() {
+ return Process.getElapsedCpuTime();
+ }
+
+ public String getTimeZoneID() {
+ return java.util.TimeZone.getDefault().getID();
+ }
+ };
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ if (ISecondary.class.getName().equals(intent.getAction())) {
+ return mSecondaryBinder;
+ }
+ return null;
+ }
+
+}
diff --git a/tests/src/android/os/cts/EmptyService.java b/tests/tests/os/src/android/os/cts/EmptyService.java
similarity index 100%
rename from tests/src/android/os/cts/EmptyService.java
rename to tests/tests/os/src/android/os/cts/EmptyService.java
diff --git a/tests/src/android/os/cts/FileUtils.java b/tests/tests/os/src/android/os/cts/FileUtils.java
similarity index 98%
rename from tests/src/android/os/cts/FileUtils.java
rename to tests/tests/os/src/android/os/cts/FileUtils.java
index ea31c54..8600d8b 100644
--- a/tests/src/android/os/cts/FileUtils.java
+++ b/tests/tests/os/src/android/os/cts/FileUtils.java
@@ -54,7 +54,7 @@
public static final int S_IXOTH = 00001;
static {
- System.loadLibrary("cts_jni");
+ System.loadLibrary("ctsos_jni");
}
public static class FileStatus {
diff --git a/tests/tests/os/src/android/os/cts/HandlerTest.java b/tests/tests/os/src/android/os/cts/HandlerTest.java
index 326218d..fc775e4 100644
--- a/tests/tests/os/src/android/os/cts/HandlerTest.java
+++ b/tests/tests/os/src/android/os/cts/HandlerTest.java
@@ -22,6 +22,7 @@
import android.os.Message;
import android.os.SystemClock;
import android.os.Handler.Callback;
+import android.test.UiThreadTest;
import android.util.Printer;
public class HandlerTest extends TestCase {
@@ -35,8 +36,9 @@
static final long DELAYED = RUNTIME + 50;
// Handler
- Handler mHandler = new Handler();
- MockHandler mHandler1 = new MockHandler();
+ private final Handler mHandler = new Handler(Looper.getMainLooper());
+ private final MockHandler mHandler1 = new MockHandler(Looper.getMainLooper());
+ private final Object mLock = new Object();
@Override
protected void tearDown() throws Exception {
@@ -44,18 +46,24 @@
super.tearDown();
}
- public void testConstructor() {
- Callback cb = new Callback() {
+ public void testConstructor() throws Throwable {
+ final Callback cb = new Callback() {
public boolean handleMessage(Message msg) {
return false;
}
};
+ new TestThread(new Runnable() {
+ public void run() {
+ Looper.prepare();
+ new Handler();
+ new Handler(cb);
+ }
+ }).runTest(RUNTIME);
+
// new the Handler instance
- new Handler();
- new Handler(Looper.myLooper());
- new Handler(cb);
- new Handler(Looper.myLooper(), cb);
+ new Handler(Looper.getMainLooper());
+ new Handler(Looper.getMainLooper(), cb);
}
public void testPostAtTime1() {
@@ -162,9 +170,9 @@
public void testGetLooper() {
// new the Handler instance
- Looper looper = Looper.myLooper();
- mHandler = new Handler(looper);
- assertSame(looper, mHandler.getLooper());
+ Looper looper = Looper.getMainLooper();
+ Handler handler = new Handler(looper);
+ assertSame(looper, handler.getLooper());
}
public void testRemoveCallbacks() {
@@ -280,7 +288,7 @@
public void testObtainMessageWithInt() {
// new the Handler instance
- Handler handler = new Handler();
+ Handler handler = new Handler(Looper.getMainLooper());
Message msg = handler.obtainMessage();
msg.what = 100;
Message msg1 = mHandler.obtainMessage(msg.what);
@@ -291,7 +299,7 @@
public void testObtainMessageWithIntObject() {
// new the Handler instance
- Handler handler = new Handler();
+ Handler handler = new Handler(Looper.getMainLooper());
Message msg = handler.obtainMessage();
msg.what = 100;
msg.obj = new Object();
@@ -304,7 +312,7 @@
public void testObtainMessageWithMutiInt() {
// new the Handler instance
- Handler handler = new Handler();
+ Handler handler = new Handler(Looper.getMainLooper());
Message msg = handler.obtainMessage();
msg.what = 100;
msg.arg1 = 101;
@@ -319,7 +327,7 @@
public void testObtainMessageWithMutiIntObject() {
// new the Handler instance
- Handler handler = new Handler();
+ Handler handler = new Handler(Looper.getMainLooper());
Message msg = handler.obtainMessage();
msg.what = 100;
msg.arg1 = 1000;
@@ -464,6 +472,14 @@
public Message message;
public int what;
+ MockHandler() {
+ super(Looper.getMainLooper());
+ }
+
+ MockHandler(Looper looper) {
+ super(looper);
+ }
+
@Override
public void handleMessage(Message msg) {
message = msg;
diff --git a/tests/tests/os/src/android/os/cts/IBinderParcelable.java b/tests/tests/os/src/android/os/cts/IBinderParcelable.java
new file mode 100644
index 0000000..e48f58a
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/IBinderParcelable.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2009 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.cts;
+
+import android.os.IBinder;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+public class IBinderParcelable implements Parcelable {
+ public IBinder binder;
+
+ public IBinderParcelable(IBinder source) {
+ binder = source;
+ }
+
+ public int describeContents() {
+ return 0;
+ }
+
+ public void writeToParcel(Parcel dest, int flags) {
+ dest.writeStrongBinder(binder);
+ }
+
+ public static final Parcelable.Creator<IBinderParcelable>
+ CREATOR = new Parcelable.Creator<IBinderParcelable>() {
+
+ public IBinderParcelable createFromParcel(Parcel source) {
+ return new IBinderParcelable(source);
+ }
+
+ public IBinderParcelable[] newArray(int size) {
+ return new IBinderParcelable[size];
+ }
+ };
+
+ private IBinderParcelable(Parcel source) {
+ binder = source.readStrongBinder();
+ }
+}
diff --git a/tests/src/android/os/cts/IEmptyService.aidl b/tests/tests/os/src/android/os/cts/IEmptyService.aidl
similarity index 100%
rename from tests/src/android/os/cts/IEmptyService.aidl
rename to tests/tests/os/src/android/os/cts/IEmptyService.aidl
diff --git a/tests/src/android/os/cts/TaggedPointer.java b/tests/tests/os/src/android/os/cts/ISecondary.aidl
similarity index 74%
copy from tests/src/android/os/cts/TaggedPointer.java
copy to tests/tests/os/src/android/os/cts/ISecondary.aidl
index 16e76c9..2c60149 100644
--- a/tests/src/android/os/cts/TaggedPointer.java
+++ b/tests/tests/os/src/android/os/cts/ISecondary.aidl
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2014 The Android Open Source Project
+ * Copyright (C) 2008 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.
@@ -16,11 +16,11 @@
package android.os.cts;
-public class TaggedPointer {
+interface ISecondary {
- static {
- System.loadLibrary("cts_jni");
- }
+ int getPid();
- public static native boolean hasTaggedPointer();
+ long getElapsedCpuTime();
+
+ String getTimeZoneID();
}
diff --git a/tests/tests/os/src/android/os/cts/LaunchpadActivity.java b/tests/tests/os/src/android/os/cts/LaunchpadActivity.java
new file mode 100644
index 0000000..3919ece
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/LaunchpadActivity.java
@@ -0,0 +1,648 @@
+/*
+ * Copyright (C) 2008 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.cts;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Binder;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Message;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.test.PerformanceTestCase;
+import android.util.Log;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+class MyBadParcelable implements Parcelable {
+ public MyBadParcelable() {
+ }
+
+ public void writeToParcel(Parcel out, int flags) {
+ out.writeString("I am bad");
+ }
+
+ public int describeContents() {
+ return 0;
+ }
+
+ public static final Parcelable.Creator<MyBadParcelable> CREATOR =
+ new Parcelable.Creator<MyBadParcelable>() {
+ public MyBadParcelable createFromParcel(Parcel in) {
+ return new MyBadParcelable(in);
+ }
+
+ public MyBadParcelable[] newArray(int size) {
+ return new MyBadParcelable[size];
+ }
+ };
+
+ public MyBadParcelable(Parcel in) {
+ in.readString();
+ }
+}
+
+public class LaunchpadActivity extends Activity {
+ public interface CallingTest extends PerformanceTestCase.Intermediates {
+ public void startTiming(boolean realTime);
+
+ public void addIntermediate(String name);
+
+ public void addIntermediate(String name, long timeInNS);
+
+ public void finishTiming(boolean realTime);
+
+ public void activityFinished(int resultCode, Intent data, RuntimeException where);
+ }
+
+ // Also used as the Binder interface descriptor string in these tests
+ public static final String LAUNCH = "android.os.cts.activity.LAUNCH";
+
+ public static final String FORWARD_RESULT = "android.os.cts.activity.FORWARD_RESULT";
+ public static final String RETURNED_RESULT = "android.os.cts.activity.RETURNED_RESULT";
+
+ public static final String BAD_PARCELABLE = "android.os.cts.activity.BAD_PARCELABLE";
+
+ public static final int LAUNCHED_RESULT = 1;
+ public static final int FORWARDED_RESULT = 2;
+
+ public static final String LIFECYCLE_BASIC = "android.os.cts.activity.LIFECYCLE_BASIC";
+ public static final String LIFECYCLE_SCREEN = "android.os.cts.activity.LIFECYCLE_SCREEN";
+ public static final String LIFECYCLE_DIALOG = "android.os.cts.activity.LIFECYCLE_DIALOG";
+
+ public static final String BROADCAST_REGISTERED = "android.os.cts.activity.BROADCAST_REGISTERED";
+ public static final String BROADCAST_LOCAL = "android.os.cts.activity.BROADCAST_LOCAL";
+ public static final String BROADCAST_REMOTE = "android.os.cts.activity.BROADCAST_REMOTE";
+ public static final String BROADCAST_ALL = "android.os.cts.activity.BROADCAST_ALL";
+ public static final String BROADCAST_REPEAT = "android.os.cts.activity.BROADCAST_REPEAT";
+ public static final String BROADCAST_MULTI = "android.os.cts.activity.BROADCAST_MULTI";
+ public static final String BROADCAST_ABORT = "android.os.cts.activity.BROADCAST_ABORT";
+
+ public static final String EXPANDLIST_SELECT = "EXPANDLIST_SELECT";
+ public static final String EXPANDLIST_VIEW = "EXPANDLIST_VIEW";
+ public static final String EXPANDLIST_CALLBACK = "EXPANDLIST_CALLBACK";
+
+ public static final String BROADCAST_STICKY1 = "android.os.cts.activity.BROADCAST_STICKY1";
+ public static final String BROADCAST_STICKY2 = "android.os.cts.activity.BROADCAST_STICKY2";
+
+ public static final String ALIAS_ACTIVITY = "android.os.cts.activity.ALIAS_ACTIVITY";
+
+ public static final String RECEIVER_REG = "receiver-reg";
+ public static final String RECEIVER_LOCAL = "receiver-local";
+ public static final String RECEIVER_REMOTE = "receiver-remote";
+ public static final String RECEIVER_ABORT = "receiver-abort";
+
+ public static final String DATA_1 = "one";
+ public static final String DATA_2 = "two";
+
+ public static final String ON_START = "onStart";
+ public static final String ON_RESTART = "onRestart";
+ public static final String ON_RESUME = "onResume";
+ public static final String ON_FREEZE = "onSaveInstanceState";
+ public static final String ON_PAUSE = "onPause";
+
+ // ON_STOP and ON_DESTROY are not tested because they may not be called.
+
+ public static final String DO_FINISH = "finish";
+ public static final String DO_LOCAL_SCREEN = "local-screen";
+ public static final String DO_LOCAL_DIALOG = "local-dialog";
+
+ private static final String TAG = "LaunchpadActivity";
+
+ private boolean mBadParcelable = false;
+
+ private boolean mStarted = false;
+
+ private int mResultCode = RESULT_CANCELED;
+ private Intent mData = new Intent().setAction("No result received");
+ private RuntimeException mResultStack = null;
+
+ /** Index into the {@link #mNextLifecycle} array. */
+ private int mNextLifecycle;
+
+ /** Current lifecycle expected to be followed. */
+ private String[] mExpectedLifecycle;
+
+ /** Other possible lifecycles. Never includes the current {@link #mExpectedLifecycle}. */
+ private List<String[]> mOtherPossibleLifecycles = new ArrayList<String[]>(2);
+
+ /** Map from lifecycle arrays to debugging log names. */
+ private Map<String[], String> mLifecycleNames = new HashMap<String[], String>(2);
+
+ private String[] mExpectedReceivers = null;
+ private int mNextReceiver;
+
+ private String[] mExpectedData = null;
+ private boolean[] mReceivedData = null;
+
+ boolean mReceiverRegistered = false;
+
+ private static CallingTest sCallingTest = null;
+
+ public static void setCallingTest(CallingTest ct) {
+ sCallingTest = ct;
+ }
+
+ public LaunchpadActivity() {
+ }
+
+ @Override
+ protected void onCreate(Bundle icicle) {
+ super.onCreate(icicle);
+
+ resetLifecycles();
+
+ // ON_STOP and ON_DESTROY are not tested because they may not be called.
+
+ final String action = getIntent().getAction();
+ if (LIFECYCLE_BASIC.equals(action)) {
+ addPossibleLifecycle(LIFECYCLE_BASIC, new String[] {
+ ON_START, ON_RESUME, DO_FINISH, ON_PAUSE
+ });
+ } else if (LIFECYCLE_SCREEN.equals(action)) {
+ addPossibleLifecycle(LIFECYCLE_SCREEN + "_RESTART", new String[] {
+ ON_START, ON_RESUME, DO_LOCAL_SCREEN, ON_PAUSE,
+ ON_RESTART, ON_START, ON_RESUME, DO_FINISH, ON_PAUSE
+ });
+ addPossibleLifecycle(LIFECYCLE_SCREEN + "_RESUME", new String[] {
+ ON_START, ON_RESUME, DO_LOCAL_SCREEN, ON_PAUSE,
+ ON_RESUME, DO_FINISH, ON_PAUSE
+ });
+ } else if (LIFECYCLE_DIALOG.equals(action)) {
+ addPossibleLifecycle(LIFECYCLE_DIALOG + "_RESTART", new String[] {
+ ON_START, ON_RESUME, DO_LOCAL_DIALOG, ON_PAUSE,
+ ON_RESTART, ON_START, ON_RESUME, DO_FINISH, ON_PAUSE
+ });
+ addPossibleLifecycle(LIFECYCLE_DIALOG + "_RESUME", new String[] {
+ ON_START, ON_RESUME, DO_LOCAL_DIALOG, ON_PAUSE,
+ ON_RESUME, DO_FINISH, ON_PAUSE
+ });
+ }
+ }
+
+ private void resetLifecycles() {
+ mNextLifecycle = 0;
+ mExpectedLifecycle = null;
+ mOtherPossibleLifecycles.clear();
+ mLifecycleNames.clear();
+ }
+
+ /**
+ * Add a potential lifecycle that this activity may follow, since there
+ * are usually multiple valid lifecycles. For instance, sometimes onPause
+ * will lead to onResume rather than onStop when another activity is
+ * raised over the current one.
+ *
+ * @param debugName for the lifecycle shown in the logs
+ * @param lifecycle array containing tokens indicating the expected lifecycle
+ */
+ private void addPossibleLifecycle(String debugName, String[] lifecycle) {
+ mLifecycleNames.put(lifecycle, debugName);
+ if (mExpectedLifecycle == null) {
+ mExpectedLifecycle = lifecycle;
+ } else {
+ mOtherPossibleLifecycles.add(lifecycle);
+ }
+ }
+
+ /**
+ * Switch to the next possible lifecycle and return if switching was
+ * successful. Call this method when mExpectedLifecycle doesn't match
+ * the current lifecycle and you need to check another possible lifecycle.
+ *
+ * @return whether on not there was a lifecycle to switch to
+ */
+ private boolean switchToNextPossibleLifecycle() {
+ if (!mOtherPossibleLifecycles.isEmpty()) {
+ String[] newLifecycle = mOtherPossibleLifecycles.remove(0);
+ Log.w(TAG, "Switching expected lifecycles from "
+ + mLifecycleNames.get(mExpectedLifecycle) + " to "
+ + mLifecycleNames.get(newLifecycle));
+ mExpectedLifecycle = newLifecycle;
+ return true;
+ } else {
+ Log.w(TAG, "No more lifecycles after "
+ + mLifecycleNames.get(mExpectedLifecycle));
+ mExpectedLifecycle = null;
+ return false;
+ }
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ checkLifecycle(ON_START);
+ }
+
+ @Override
+ protected void onRestart() {
+ super.onStart();
+ checkLifecycle(ON_RESTART);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+
+ checkLifecycle(ON_RESUME);
+
+ if (!mStarted) {
+ mStarted = true;
+
+ mHandler.postDelayed(mTimeout, 10 * 1000);
+
+ final String action = getIntent().getAction();
+
+ sCallingTest.startTiming(true);
+
+ if (LAUNCH.equals(action)) {
+ final Intent intent = getIntent();
+ intent.setFlags(0);
+ intent.setComponent((ComponentName) intent.getParcelableExtra("component"));
+ startActivityForResult(intent, LAUNCHED_RESULT);
+
+ } else if (FORWARD_RESULT.equals(action)) {
+ final Intent intent = getIntent();
+ intent.setFlags(0);
+ intent.setClass(this, LocalScreen.class);
+ startActivityForResult(intent, FORWARDED_RESULT);
+ } else if (BAD_PARCELABLE.equals(action)) {
+ mBadParcelable = true;
+ final Intent intent = getIntent();
+ intent.setFlags(0);
+ intent.setClass(this, LocalScreen.class);
+ startActivityForResult(intent, LAUNCHED_RESULT);
+ } else if (BROADCAST_REGISTERED.equals(action)) {
+ setExpectedReceivers(new String[] {
+ RECEIVER_REG
+ });
+ registerMyReceiver(new IntentFilter(BROADCAST_REGISTERED));
+ sCallingTest.addIntermediate("after-register");
+ sendBroadcast(makeBroadcastIntent(BROADCAST_REGISTERED));
+ } else if (BROADCAST_LOCAL.equals(action)) {
+ setExpectedReceivers(new String[] {
+ RECEIVER_LOCAL
+ });
+ sendBroadcast(makeBroadcastIntent(BROADCAST_LOCAL));
+ } else if (BROADCAST_REMOTE.equals(action)) {
+ setExpectedReceivers(new String[] {
+ RECEIVER_REMOTE
+ });
+ sendBroadcast(makeBroadcastIntent(BROADCAST_REMOTE));
+ } else if (BROADCAST_ALL.equals(action)) {
+ setExpectedReceivers(new String[] {
+ RECEIVER_REMOTE, RECEIVER_REG, RECEIVER_LOCAL
+ });
+ registerMyReceiver(new IntentFilter(BROADCAST_ALL));
+ sCallingTest.addIntermediate("after-register");
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_ALL), null);
+ } else if (BROADCAST_MULTI.equals(action)) {
+ setExpectedReceivers(new String[] {
+ RECEIVER_REMOTE, RECEIVER_REG, RECEIVER_LOCAL, RECEIVER_REMOTE,
+ RECEIVER_REG, RECEIVER_LOCAL, RECEIVER_REMOTE, RECEIVER_REG,
+ RECEIVER_LOCAL, RECEIVER_LOCAL, RECEIVER_REMOTE, RECEIVER_LOCAL,
+ RECEIVER_REMOTE, RECEIVER_REMOTE, RECEIVER_REG, RECEIVER_LOCAL,
+ RECEIVER_REMOTE, RECEIVER_REG, RECEIVER_LOCAL, RECEIVER_REMOTE,
+ RECEIVER_REG, RECEIVER_LOCAL, RECEIVER_REMOTE, RECEIVER_LOCAL,
+ RECEIVER_REMOTE, RECEIVER_LOCAL
+ });
+ registerMyReceiver(new IntentFilter(BROADCAST_ALL));
+ sCallingTest.addIntermediate("after-register");
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_ALL), null);
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_ALL), null);
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_ALL), null);
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_LOCAL), null);
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_REMOTE), null);
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_LOCAL), null);
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_REMOTE), null);
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_ALL), null);
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_ALL), null);
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_ALL), null);
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_REPEAT), null);
+ } else if (BROADCAST_ABORT.equals(action)) {
+ setExpectedReceivers(new String[] {
+ RECEIVER_REMOTE, RECEIVER_ABORT
+ });
+ registerMyReceiver(new IntentFilter(BROADCAST_ABORT));
+ sCallingTest.addIntermediate("after-register");
+ sendOrderedBroadcast(makeBroadcastIntent(BROADCAST_ABORT), null);
+ } else if (BROADCAST_STICKY1.equals(action)) {
+ setExpectedReceivers(new String[] {
+ RECEIVER_REG
+ });
+ setExpectedData(new String[] {
+ DATA_1
+ });
+ registerMyReceiver(new IntentFilter(BROADCAST_STICKY1));
+ sCallingTest.addIntermediate("after-register");
+ } else if (BROADCAST_STICKY2.equals(action)) {
+ setExpectedReceivers(new String[] {
+ RECEIVER_REG, RECEIVER_REG
+ });
+ setExpectedData(new String[] {
+ DATA_1, DATA_2
+ });
+ final IntentFilter filter = new IntentFilter(BROADCAST_STICKY1);
+ filter.addAction(BROADCAST_STICKY2);
+ registerMyReceiver(filter);
+ sCallingTest.addIntermediate("after-register");
+ } else if (ALIAS_ACTIVITY.equals(action)) {
+ final Intent intent = getIntent();
+ intent.setFlags(0);
+ intent.setClass(this, AliasActivityStub.class);
+ startActivityForResult(intent, LAUNCHED_RESULT);
+ } else if (EXPANDLIST_SELECT.equals(action)) {
+ final Intent intent = getIntent();
+ intent.setFlags(0);
+ intent.setAction(action);
+ intent.setComponent((ComponentName) intent.getParcelableExtra("component"));
+ startActivityForResult(intent, LAUNCHED_RESULT);
+ } else if (EXPANDLIST_VIEW.equals(action)) {
+ final Intent intent = getIntent();
+ intent.setFlags(0);
+ intent.setAction(action);
+ intent.setComponent((ComponentName) intent.getParcelableExtra("component"));
+ startActivityForResult(intent, LAUNCHED_RESULT);
+ } else if (EXPANDLIST_CALLBACK.equals(action)) {
+ final Intent intent = getIntent();
+ intent.setFlags(0);
+ intent.setAction(action);
+ intent.setComponent((ComponentName) intent.getParcelableExtra("component"));
+ startActivityForResult(intent, LAUNCHED_RESULT);
+ }
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle icicle) {
+ super.onSaveInstanceState(icicle);
+ if (mBadParcelable) {
+ icicle.putParcelable("baddy", new MyBadParcelable());
+ }
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ checkLifecycle(ON_PAUSE);
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ switch (requestCode) {
+ case LAUNCHED_RESULT:
+ sCallingTest.finishTiming(true);
+ finishWithResult(resultCode, data);
+ break;
+ case FORWARDED_RESULT:
+ sCallingTest.finishTiming(true);
+ if (RETURNED_RESULT.equals(data.getAction())) {
+ finishWithResult(resultCode, data);
+ } else {
+ finishWithResult(RESULT_CANCELED, new Intent().setAction("Bad data returned: "
+ + data));
+ }
+ break;
+ default:
+ sCallingTest.finishTiming(true);
+ finishWithResult(RESULT_CANCELED, new Intent()
+ .setAction("Unexpected request code: " + requestCode));
+ break;
+ }
+ }
+
+ private void checkLifecycle(String where) {
+ String action = getIntent().getAction();
+
+ if (mExpectedLifecycle == null) {
+ return;
+ }
+
+ if (mNextLifecycle >= mExpectedLifecycle.length) {
+ finishBad("Activity lifecycle for " + action + " incorrect: received " + where
+ + " but don't expect any more calls");
+ mExpectedLifecycle = null;
+ return;
+ }
+
+ do {
+ if (mExpectedLifecycle[mNextLifecycle].equals(where)) {
+ Log.w(TAG, "Matched: " + where);
+ break;
+ } else {
+ Log.w(TAG, "Expected " + mExpectedLifecycle[mNextLifecycle] + " but got " + where);
+ }
+ } while (switchToNextPossibleLifecycle());
+
+ if (mExpectedLifecycle == null) {
+ finishBad("Activity lifecycle for " + action + " incorrect: received " + where
+ + " at " + mNextLifecycle);
+ return;
+ }
+
+ mNextLifecycle++;
+
+ if (mNextLifecycle >= mExpectedLifecycle.length) {
+ finishGood();
+ return;
+ }
+
+ final String next = mExpectedLifecycle[mNextLifecycle];
+ if (next.equals(DO_FINISH)) {
+ mNextLifecycle++;
+ if (mNextLifecycle >= mExpectedLifecycle.length) {
+ setTestResult(RESULT_OK, null);
+ }
+ if (!isFinishing()) {
+ finish();
+ }
+ } else if (next.equals(DO_LOCAL_SCREEN)) {
+ mNextLifecycle++;
+ final Intent intent = new Intent(TestedScreen.WAIT_BEFORE_FINISH);
+ intent.setClass(this, LocalScreen.class);
+ startActivity(intent);
+ } else if (next.equals(DO_LOCAL_DIALOG)) {
+ mNextLifecycle++;
+ final Intent intent = new Intent(TestedScreen.WAIT_BEFORE_FINISH);
+ intent.setClass(this, LocalDialog.class);
+ startActivity(intent);
+ }
+ }
+
+ private void setExpectedReceivers(String[] receivers) {
+ mExpectedReceivers = receivers;
+ mNextReceiver = 0;
+ }
+
+ private void setExpectedData(String[] data) {
+ mExpectedData = data;
+ mReceivedData = new boolean[data.length];
+ }
+
+ @SuppressWarnings("deprecation")
+ private Intent makeBroadcastIntent(String action) {
+ final Intent intent = new Intent(action, null);
+ intent.putExtra("caller", mCallTarget);
+ return intent;
+ }
+
+ private void finishGood() {
+ finishWithResult(RESULT_OK, null);
+ }
+
+ private void finishBad(String error) {
+ finishWithResult(RESULT_CANCELED, new Intent().setAction(error));
+ }
+
+ private void finishWithResult(int resultCode, Intent data) {
+ setTestResult(resultCode, data);
+ finish();
+
+ // Member fields set by calling setTestResult above...
+ sCallingTest.activityFinished(mResultCode, mData, mResultStack);
+ }
+
+ private void setTestResult(int resultCode, Intent data) {
+ mHandler.removeCallbacks(mTimeout);
+ unregisterMyReceiver();
+ mResultCode = resultCode;
+ mData = data;
+ mResultStack = new RuntimeException("Original error was here");
+ mResultStack.fillInStackTrace();
+ }
+
+ private void registerMyReceiver(IntentFilter filter) {
+ mReceiverRegistered = true;
+ registerReceiver(mReceiver, filter);
+ }
+
+ private void unregisterMyReceiver() {
+ if (mReceiverRegistered) {
+ mReceiverRegistered = false;
+ unregisterReceiver(mReceiver);
+ }
+ }
+
+ private final Handler mHandler = new Handler() {
+ @Override
+ public void handleMessage(Message msg) {
+ }
+ };
+
+ static final int GOT_RECEIVE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION;
+ static final int ERROR_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 1;
+
+ private final Binder mCallTarget = new Binder() {
+ @Override
+ public boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
+ data.setDataPosition(0);
+ data.enforceInterface(LaunchpadActivity.LAUNCH);
+ if (code == GOT_RECEIVE_TRANSACTION) {
+ final String name = data.readString();
+ gotReceive(name, null);
+ return true;
+ } else if (code == ERROR_TRANSACTION) {
+ finishBad(data.readString());
+ return true;
+ }
+ return false;
+ }
+ };
+
+ private final void gotReceive(String name, Intent intent) {
+ synchronized (this) {
+
+ sCallingTest.addIntermediate(mNextReceiver + "-" + name);
+
+ if (mExpectedData != null) {
+ final int n = mExpectedData.length;
+ int i;
+ boolean prev = false;
+ for (i = 0; i < n; i++) {
+ if (mExpectedData[i].equals(intent.getStringExtra("test"))) {
+ if (mReceivedData[i]) {
+ prev = true;
+ continue;
+ }
+ mReceivedData[i] = true;
+ break;
+ }
+ }
+ if (i >= n) {
+ if (prev) {
+ finishBad("Receive got data too many times: "
+ + intent.getStringExtra("test"));
+ } else {
+ finishBad("Receive got unexpected data: " + intent.getStringExtra("test"));
+ }
+ return;
+ }
+ }
+
+ if (mNextReceiver >= mExpectedReceivers.length) {
+ finishBad("Got too many onReceiveIntent() calls!");
+ } else if (!mExpectedReceivers[mNextReceiver].equals(name)) {
+ finishBad("Receive out of order: got " + name + " but expected "
+ + mExpectedReceivers[mNextReceiver] + " at " + mNextReceiver);
+ } else {
+ mNextReceiver++;
+ if (mNextReceiver == mExpectedReceivers.length) {
+ mHandler.post(mUnregister);
+ }
+ }
+
+ }
+ }
+
+ private final Runnable mUnregister = new Runnable() {
+ public void run() {
+ if (mReceiverRegistered) {
+ sCallingTest.addIntermediate("before-unregister");
+ unregisterMyReceiver();
+ }
+ sCallingTest.finishTiming(true);
+ finishGood();
+ }
+ };
+
+ private final Runnable mTimeout = new Runnable() {
+ public void run() {
+ Log.i(TAG, "timeout");
+ String msg = "Timeout";
+ if (mExpectedReceivers != null && mNextReceiver < mExpectedReceivers.length) {
+ msg = msg + " waiting for " + mExpectedReceivers[mNextReceiver];
+ }
+ finishBad(msg);
+ }
+ };
+
+ private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ gotReceive(RECEIVER_REG, intent);
+ }
+ };
+}
diff --git a/tests/src/android/os/cts/TaggedPointer.java b/tests/tests/os/src/android/os/cts/LocalDialog.java
similarity index 75%
copy from tests/src/android/os/cts/TaggedPointer.java
copy to tests/tests/os/src/android/os/cts/LocalDialog.java
index 16e76c9..6ccca57 100644
--- a/tests/src/android/os/cts/TaggedPointer.java
+++ b/tests/tests/os/src/android/os/cts/LocalDialog.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2014 The Android Open Source Project
+ * Copyright (C) 2008 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.
@@ -16,11 +16,7 @@
package android.os.cts;
-public class TaggedPointer {
-
- static {
- System.loadLibrary("cts_jni");
+public class LocalDialog extends TestedScreen {
+ public LocalDialog() {
}
-
- public static native boolean hasTaggedPointer();
}
diff --git a/tests/src/android/os/cts/TaggedPointer.java b/tests/tests/os/src/android/os/cts/LocalScreen.java
similarity index 75%
copy from tests/src/android/os/cts/TaggedPointer.java
copy to tests/tests/os/src/android/os/cts/LocalScreen.java
index 16e76c9..0a017c4 100644
--- a/tests/src/android/os/cts/TaggedPointer.java
+++ b/tests/tests/os/src/android/os/cts/LocalScreen.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2014 The Android Open Source Project
+ * Copyright (C) 2008 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.
@@ -16,11 +16,7 @@
package android.os.cts;
-public class TaggedPointer {
-
- static {
- System.loadLibrary("cts_jni");
+public class LocalScreen extends TestedScreen {
+ public LocalScreen() {
}
-
- public static native boolean hasTaggedPointer();
}
diff --git a/tests/tests/os/src/android/os/cts/LocalService.java b/tests/tests/os/src/android/os/cts/LocalService.java
new file mode 100644
index 0000000..0353c23
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/LocalService.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2008 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.cts;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.Binder;
+import android.os.IBinder;
+import android.os.Parcel;
+import android.os.RemoteException;
+
+public class LocalService extends Service {
+ public static final String SERVICE_LOCAL =
+ "android.os.cts.activity.SERVICE_LOCAL";
+ public static final String SERVICE_LOCAL_GRANTED =
+ "android.os.cts.activity.SERVICE_LOCAL_GRANTED";
+ public static final String SERVICE_LOCAL_DENIED =
+ "android.os.cts.activity.SERVICE_LOCAL_DENIED";
+
+ public static final String REPORT_OBJ_NAME = "report";
+
+ public static final int STARTED_CODE = 1;
+ public static final int DESTROYED_CODE = 2;
+ public static final int SET_REPORTER_CODE = 3;
+ public static final int UNBIND_CODE = 4;
+ public static final int REBIND_CODE = 5;
+
+ private IBinder mReportObject;
+ private int mStartCount = 1;
+
+ private final IBinder mBinder = new Binder() {
+ @Override
+ protected boolean onTransact(int code, Parcel data, Parcel reply,
+ int flags) throws RemoteException {
+ if (code == SET_REPORTER_CODE) {
+ data.enforceInterface(SERVICE_LOCAL);
+ mReportObject = data.readStrongBinder();
+ return true;
+ } else {
+ return super.onTransact(code, data, reply, flags);
+ }
+ }
+ };
+
+
+ public LocalService() {
+ }
+
+ @Override
+ public void onStart(Intent intent, int startId) {
+ if (intent.getExtras() != null) {
+ IBinderParcelable parcelable
+ = (IBinderParcelable) intent.getExtras().getParcelable(REPORT_OBJ_NAME);
+ mReportObject = parcelable.binder;
+ if (mReportObject != null) {
+ bindAction(STARTED_CODE);
+ }
+ }
+ }
+
+ @Override
+ public void onDestroy() {
+ if (mReportObject != null) {
+ bindAction(DESTROYED_CODE);
+ }
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return mBinder;
+ }
+
+ @Override
+ public boolean onUnbind(Intent intent) {
+ if (mReportObject != null) {
+ bindAction(UNBIND_CODE);
+ }
+ return true;
+ }
+
+ @Override
+ public void onRebind(Intent intent) {
+ if (mReportObject != null) {
+ bindAction(REBIND_CODE);
+ }
+ }
+
+ private void bindAction(final int bindCode) {
+ try {
+ Parcel data = Parcel.obtain();
+ data.writeInterfaceToken(SERVICE_LOCAL);
+ if (bindCode == STARTED_CODE) {
+ data.writeInt(mStartCount);
+ mStartCount++;
+ }
+ mReportObject.transact(
+ bindCode, data, null, 0);
+ data.recycle();
+ } catch (RemoteException e) {
+ // fail
+ }
+ }
+}
diff --git a/tests/tests/os/src/android/os/cts/LooperTest.java b/tests/tests/os/src/android/os/cts/LooperTest.java
index 6631599..e71b752 100644
--- a/tests/tests/os/src/android/os/cts/LooperTest.java
+++ b/tests/tests/os/src/android/os/cts/LooperTest.java
@@ -38,7 +38,7 @@
public void testDump() {
StringBuilderPrinter printer = new StringBuilderPrinter(new StringBuilder());
final String prefix = "LooperTest";
- Looper.myLooper().dump(printer, prefix);
+ Looper.getMainLooper().dump(printer, prefix);
}
public void testGetMainLooper() {
@@ -78,9 +78,6 @@
}
public void testMyQueue() throws Throwable {
- MessageQueue mq = Looper.myQueue();
- assertNotNull(mq);
-
TestThread t = new TestThread(new Runnable() {
public void run() {
try {
@@ -89,6 +86,9 @@
} catch (Throwable e) {
// expected
}
+ Looper.prepare();
+ MessageQueue mq = Looper.myQueue();
+ assertNotNull(mq);
}
});
@@ -96,13 +96,6 @@
}
public void testPrepare() throws Throwable {
- try {
- Looper.prepare();
- fail("should throw exception because current thread already has a looper");
- } catch (RuntimeException e) {
- //expected
- }
-
TestThread t = new TestThread(new Runnable() {
public void run() {
Looper.prepare();
@@ -191,7 +184,7 @@
}
public void testToString() {
- assertNotNull(Looper.myLooper().toString());
+ assertNotNull(Looper.getMainLooper().toString());
}
class MockPrinter implements Printer {
diff --git a/tests/tests/os/src/android/os/cts/MessageQueueTest.java b/tests/tests/os/src/android/os/cts/MessageQueueTest.java
index 8c38d5f..5b5bf5c 100644
--- a/tests/tests/os/src/android/os/cts/MessageQueueTest.java
+++ b/tests/tests/os/src/android/os/cts/MessageQueueTest.java
@@ -208,17 +208,17 @@
public void testReleaseSyncBarrierThrowsIfTokenNotValid() throws Exception {
// Invalid token
try {
- Looper.myLooper().removeSyncBarrier(-1);
+ Looper.getMainLooper().removeSyncBarrier(-1);
fail("Should have thrown IllegalStateException");
} catch (IllegalStateException ex) {
// expected
}
// Token already removed.
- int barrierToken = Looper.myLooper().postSyncBarrier();
- Looper.myLooper().removeSyncBarrier(barrierToken);
+ int barrierToken = Looper.getMainLooper().postSyncBarrier();
+ Looper.getMainLooper().removeSyncBarrier(barrierToken);
try {
- Looper.myLooper().removeSyncBarrier(barrierToken);
+ Looper.getMainLooper().removeSyncBarrier(barrierToken);
fail("Should have thrown IllegalStateException");
} catch (IllegalStateException ex) {
// expected
diff --git a/tests/tests/os/src/android/os/cts/MessageTest.java b/tests/tests/os/src/android/os/cts/MessageTest.java
index cc45c4b..978897b 100644
--- a/tests/tests/os/src/android/os/cts/MessageTest.java
+++ b/tests/tests/os/src/android/os/cts/MessageTest.java
@@ -18,6 +18,7 @@
import android.os.Bundle;
import android.os.Handler;
+import android.os.Looper;
import android.os.Message;
import android.os.Parcel;
import android.test.AndroidTestCase;
@@ -33,7 +34,7 @@
private Message mMessage;
private boolean mMessageHandlerCalled;
- private Handler mHandler = new Handler() {
+ private Handler mHandler = new Handler(Looper.getMainLooper()) {
public void handleMessage(Message msg) {
mMessageHandlerCalled = true;
}
diff --git a/tests/src/android/os/cts/MessengerService.java b/tests/tests/os/src/android/os/cts/MessengerService.java
similarity index 100%
rename from tests/src/android/os/cts/MessengerService.java
rename to tests/tests/os/src/android/os/cts/MessengerService.java
diff --git a/tests/tests/os/src/android/os/cts/MessengerTest.java b/tests/tests/os/src/android/os/cts/MessengerTest.java
index 0512b23..72bf247 100644
--- a/tests/tests/os/src/android/os/cts/MessengerTest.java
+++ b/tests/tests/os/src/android/os/cts/MessengerTest.java
@@ -43,7 +43,7 @@
private static final int MSG_ARG1 = 100;
private static final int MSG_ARG2 = 1000;
private static final int WHAT = 2008;
- private Handler mHandler = new Handler() {
+ private Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
mResult = true;
diff --git a/tests/src/android/os/cts/OSFeatures.java b/tests/tests/os/src/android/os/cts/OSFeatures.java
similarity index 95%
rename from tests/src/android/os/cts/OSFeatures.java
rename to tests/tests/os/src/android/os/cts/OSFeatures.java
index 59556db..9c4660c 100644
--- a/tests/src/android/os/cts/OSFeatures.java
+++ b/tests/tests/os/src/android/os/cts/OSFeatures.java
@@ -18,7 +18,7 @@
public class OSFeatures {
static {
- System.loadLibrary("cts_jni");
+ System.loadLibrary("ctsos_jni");
}
public static native int getNoNewPrivs();
diff --git a/tests/tests/os/src/android/os/cts/ProcessTest.java b/tests/tests/os/src/android/os/cts/ProcessTest.java
index 90c2eb9..2ca0fd0 100644
--- a/tests/tests/os/src/android/os/cts/ProcessTest.java
+++ b/tests/tests/os/src/android/os/cts/ProcessTest.java
@@ -16,7 +16,6 @@
package android.os.cts;
-import android.app.cts.ISecondary;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
diff --git a/tests/src/android/os/cts/ReadElf.java b/tests/tests/os/src/android/os/cts/ReadElf.java
similarity index 100%
rename from tests/src/android/os/cts/ReadElf.java
rename to tests/tests/os/src/android/os/cts/ReadElf.java
diff --git a/tests/tests/os/src/android/os/cts/RemoteCallbackListTest.java b/tests/tests/os/src/android/os/cts/RemoteCallbackListTest.java
index 4c3f3cf..e00fe89 100644
--- a/tests/tests/os/src/android/os/cts/RemoteCallbackListTest.java
+++ b/tests/tests/os/src/android/os/cts/RemoteCallbackListTest.java
@@ -17,7 +17,6 @@
package android.os.cts;
-import android.app.cts.ISecondary;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
diff --git a/tests/tests/os/src/android/os/cts/ResultReceiverTest.java b/tests/tests/os/src/android/os/cts/ResultReceiverTest.java
index e784444..47a5d99 100644
--- a/tests/tests/os/src/android/os/cts/ResultReceiverTest.java
+++ b/tests/tests/os/src/android/os/cts/ResultReceiverTest.java
@@ -16,16 +16,15 @@
package android.os.cts;
-
-
import android.os.Bundle;
import android.os.Handler;
+import android.os.Looper;
import android.os.Parcel;
import android.os.ResultReceiver;
import android.test.AndroidTestCase;
public class ResultReceiverTest extends AndroidTestCase {
- private Handler mHandler = new Handler();
+ private Handler mHandler = new Handler(Looper.getMainLooper());
private static final long DURATION = 100l;
public void testResultReceiver() throws InterruptedException {
diff --git a/tests/src/android/os/cts/TaggedPointer.java b/tests/tests/os/src/android/os/cts/TaggedPointer.java
similarity index 94%
rename from tests/src/android/os/cts/TaggedPointer.java
rename to tests/tests/os/src/android/os/cts/TaggedPointer.java
index 16e76c9..11c3eba 100644
--- a/tests/src/android/os/cts/TaggedPointer.java
+++ b/tests/tests/os/src/android/os/cts/TaggedPointer.java
@@ -19,7 +19,7 @@
public class TaggedPointer {
static {
- System.loadLibrary("cts_jni");
+ System.loadLibrary("ctsos_jni");
}
public static native boolean hasTaggedPointer();
diff --git a/tests/tests/os/src/android/os/cts/TestThread.java b/tests/tests/os/src/android/os/cts/TestThread.java
new file mode 100644
index 0000000..1a28a20
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/TestThread.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2009 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.cts;
+
+/**
+ * Thread class for executing a Runnable containing assertions in a separate thread.
+ * Uncaught exceptions in the Runnable are rethrown in the context of the the thread
+ * calling the <code>runTest()</code> method.
+ */
+public final class TestThread extends Thread {
+ private Throwable mThrowable;
+ private Runnable mTarget;
+
+ public TestThread(Runnable target) {
+ mTarget = target;
+ }
+
+ @Override
+ public final void run() {
+ try {
+ mTarget.run();
+ } catch (Throwable t) {
+ mThrowable = t;
+ }
+ }
+
+ /**
+ * Run the target Runnable object and wait until the test finish or throw
+ * out Exception if test fail.
+ *
+ * @param runTime
+ * @throws Throwable
+ */
+ public void runTest(long runTime) throws Throwable {
+ start();
+ joinAndCheck(runTime);
+ }
+
+ /**
+ * Get the Throwable object which is thrown when test running
+ * @return The Throwable object
+ */
+ public Throwable getThrowable() {
+ return mThrowable;
+ }
+
+ /**
+ * Set the Throwable object which is thrown when test running
+ * @param t The Throwable object
+ */
+ public void setThrowable(Throwable t) {
+ mThrowable = t;
+ }
+
+ /**
+ * Wait for the test thread to complete and throw the stored exception if there is one.
+ *
+ * @param runTime The time to wait for the test thread to complete.
+ * @throws Throwable
+ */
+ public void joinAndCheck(long runTime) throws Throwable {
+ this.join(runTime);
+ if (this.isAlive()) {
+ this.interrupt();
+ this.join(runTime);
+ throw new Exception("Thread did not finish within allotted time.");
+ }
+ checkException();
+ }
+
+ /**
+ * Check whether there is an exception when running Runnable object.
+ * @throws Throwable
+ */
+ public void checkException() throws Throwable {
+ if (mThrowable != null) {
+ throw mThrowable;
+ }
+ }
+}
diff --git a/tests/tests/os/src/android/os/cts/TestedScreen.java b/tests/tests/os/src/android/os/cts/TestedScreen.java
new file mode 100644
index 0000000..49f3e70
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/TestedScreen.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2008 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.cts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.os.MessageQueue;
+import android.os.SystemClock;
+import android.util.Log;
+
+public class TestedScreen extends Activity {
+ public static final String WAIT_BEFORE_FINISH = "TestedScreen.WAIT_BEFORE_FINISH";
+ public static final String DELIVER_RESULT = "TestedScreen.DELIVER_RESULT";
+ public static final String CLEAR_TASK = "TestedScreen.CLEAR_TASK";
+ private static final String TAG = "TestedScreen" ;
+ public TestedScreen() {
+ }
+
+ @Override
+ public void onCreate(Bundle icicle) {
+ super.onCreate(icicle);
+ if (LaunchpadActivity.FORWARD_RESULT.equals(getIntent().getAction())) {
+ final Intent intent = new Intent(getIntent());
+ intent.setAction(DELIVER_RESULT);
+ intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
+ startActivity(intent);
+ finish();
+ } else if (DELIVER_RESULT.equals(getIntent().getAction())) {
+ setResult(RESULT_OK, new Intent().setAction(LaunchpadActivity.RETURNED_RESULT));
+ finish();
+ } else if (CLEAR_TASK.equals(getIntent().getAction())) {
+ if (!getIntent().getBooleanExtra(ClearTop.WAIT_CLEAR_TASK, false)) {
+ launchClearTask();
+ }
+ }
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle state) {
+ super.onRestoreInstanceState(state);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ if (CLEAR_TASK.equals(getIntent().getAction())) {
+ if (getIntent().getBooleanExtra(ClearTop.WAIT_CLEAR_TASK, false)) {
+ Looper.myLooper();
+ Looper.myQueue().addIdleHandler(new Idler());
+ }
+ } else {
+ Looper.myLooper();
+ Looper.myQueue().addIdleHandler(new Idler());
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ }
+
+ @Override
+ protected void onStop() {
+ super.onStop();
+ }
+
+ private void launchClearTask() {
+ final Intent intent = new Intent(getIntent()).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
+ .setClass(this, ClearTop.class);
+ startActivity(intent);
+ }
+
+ private final Handler mHandler = new Handler() {
+ @Override
+ public void handleMessage(Message msg) {
+ if (CLEAR_TASK.equals(getIntent().getAction())) {
+ launchClearTask();
+ } else {
+ setResult(RESULT_OK);
+ finish();
+ }
+ }
+ };
+
+ private class Idler implements MessageQueue.IdleHandler {
+ public final boolean queueIdle() {
+ Log.i(TAG, "idle");
+ if (WAIT_BEFORE_FINISH.equals(getIntent().getAction())) {
+ final Message m = Message.obtain();
+ mHandler.sendMessageAtTime(m, SystemClock.uptimeMillis() + 1000);
+ } else if (CLEAR_TASK.equals(getIntent().getAction())) {
+ final Message m = Message.obtain();
+ mHandler.sendMessageAtTime(m, SystemClock.uptimeMillis() + 1000);
+ } else {
+ setResult(RESULT_OK);
+ finish();
+ }
+ return false;
+ }
+ }
+}
diff --git a/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java b/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java
index 45c5e45..4183c2d 100644
--- a/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java
+++ b/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java
@@ -16,7 +16,7 @@
package android.os.storage.cts;
-import com.android.cts.stub.R;
+import com.android.cts.os.R;
import android.content.Context;
import android.content.res.Resources;
@@ -29,8 +29,13 @@
import android.test.ComparisonFailure;
import android.util.Log;
+import libcore.io.Streams;
+import org.junit.Assert;
+
import java.io.File;
+import java.io.FileInputStream;
import java.io.InputStream;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -43,6 +48,7 @@
private static final long WAIT_TIME_INCR = 5*1000;
private static final String OBB_MOUNT_PREFIX = "/mnt/obb/";
+ private static final String TEST1_CONTENTS = "1\n";
private StorageManager mStorageManager;
@@ -52,7 +58,7 @@
mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
}
- public void testMountAndUnmountObbNormal() {
+ public void testMountAndUnmountObbNormal() throws IOException {
for (File target : getTargetFiles()) {
target = new File(target, "test1.obb");
Log.d(TAG, "Testing path " + target);
@@ -60,17 +66,22 @@
}
}
- private void doMountAndUnmountObbNormal(File outFile) {
+ private void doMountAndUnmountObbNormal(File outFile) throws IOException {
final String canonPath = mountObb(R.raw.test1, outFile, OnObbStateChangeListener.MOUNTED);
mountObb(R.raw.test1, outFile, OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
- final String mountPath = checkMountedPath(canonPath);
- final File mountDir = new File(mountPath);
+ try {
+ final String mountPath = checkMountedPath(canonPath);
+ final File mountDir = new File(mountPath);
+ final File testFile = new File(mountDir, "test1.txt");
- assertTrue("OBB mounted path should be a directory", mountDir.isDirectory());
-
- unmountObb(outFile, OnObbStateChangeListener.UNMOUNTED);
+ assertTrue("OBB mounted path should be a directory", mountDir.isDirectory());
+ assertTrue("test1.txt does not exist in OBB dir", testFile.exists());
+ assertFileContains(testFile, TEST1_CONTENTS);
+ } finally {
+ unmountObb(outFile, OnObbStateChangeListener.UNMOUNTED);
+ }
}
public void testAttemptMountNonObb() {
@@ -110,7 +121,7 @@
mStorageManager.getMountedObbPath(outFile.getPath()));
}
- public void testMountAndUnmountTwoObbs() {
+ public void testMountAndUnmountTwoObbs() throws IOException {
for (File target : getTargetFiles()) {
Log.d(TAG, "Testing target " + target);
final File test1 = new File(target, "test1.obb");
@@ -119,7 +130,7 @@
}
}
- private void doMountAndUnmountTwoObbs(File file1, File file2) {
+ private void doMountAndUnmountTwoObbs(File file1, File file2) throws IOException {
ObbObserver oo1 = mountObbWithoutWait(R.raw.test1, file1);
ObbObserver oo2 = mountObbWithoutWait(R.raw.test1, file2);
@@ -128,16 +139,24 @@
Log.d(TAG, "Waiting for OBB #2 to complete mount");
waitForObbActionCompletion(file2, oo2, OnObbStateChangeListener.MOUNTED);
- final String mountPath1 = checkMountedPath(oo1.getPath());
- final File mountDir1 = new File(mountPath1);
- assertTrue("OBB mounted path should be a directory", mountDir1.isDirectory());
+ try {
+ final String mountPath1 = checkMountedPath(oo1.getPath());
+ final File mountDir1 = new File(mountPath1);
+ final File testFile1 = new File(mountDir1, "test1.txt");
+ assertTrue("OBB mounted path should be a directory", mountDir1.isDirectory());
+ assertTrue("test1.txt does not exist in OBB dir", testFile1.exists());
+ assertFileContains(testFile1, TEST1_CONTENTS);
- final String mountPath2 = checkMountedPath(oo2.getPath());
- final File mountDir2 = new File(mountPath2);
- assertTrue("OBB mounted path should be a directory", mountDir2.isDirectory());
-
- unmountObb(file1, OnObbStateChangeListener.UNMOUNTED);
- unmountObb(file2, OnObbStateChangeListener.UNMOUNTED);
+ final String mountPath2 = checkMountedPath(oo2.getPath());
+ final File mountDir2 = new File(mountPath2);
+ final File testFile2 = new File(mountDir2, "test1.txt");
+ assertTrue("OBB mounted path should be a directory", mountDir2.isDirectory());
+ assertTrue("test1.txt does not exist in OBB dir", testFile2.exists());
+ assertFileContains(testFile2, TEST1_CONTENTS);
+ } finally {
+ unmountObb(file1, OnObbStateChangeListener.UNMOUNTED);
+ unmountObb(file2, OnObbStateChangeListener.UNMOUNTED);
+ }
}
private static void assertStartsWith(String message, String prefix, String actual) {
@@ -146,6 +165,12 @@
}
}
+ private static void assertFileContains(File file, String contents) throws IOException {
+ byte[] actual = Streams.readFully(new FileInputStream(file));
+ byte[] expected = contents.getBytes("UTF-8");
+ Assert.assertArrayEquals(expected, actual);
+ }
+
private static class ObbObserver extends OnObbStateChangeListener {
private String path;
diff --git a/tests/tests/permission/src/android/permission/cts/AppWidgetManagerPermissionTest.java b/tests/tests/permission/src/android/permission/cts/AppWidgetManagerPermissionTest.java
index 4223f08..1328f88 100644
--- a/tests/tests/permission/src/android/permission/cts/AppWidgetManagerPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/AppWidgetManagerPermissionTest.java
@@ -51,11 +51,11 @@
}
try {
- mAppWidgetManager.bindAppWidgetId(1, new ComponentName(mContext, "foo"));
- fail("Was able to call bindAppWidgetId");
+ final boolean bound = mAppWidgetManager.bindAppWidgetIdIfAllowed(1,
+ new ComponentName(mContext, "foo"));
+ assertFalse("Was able to call bindAppWidgetId", bound);
} catch (SecurityException e) {
// expected
}
}
}
-
diff --git a/tests/tests/permission/src/android/permission/cts/ConnectivityManagerPermissionTest.java b/tests/tests/permission/src/android/permission/cts/ConnectivityManagerPermissionTest.java
index d9a61f4..8714100 100644
--- a/tests/tests/permission/src/android/permission/cts/ConnectivityManagerPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/ConnectivityManagerPermissionTest.java
@@ -55,22 +55,6 @@
}
/**
- * Verify that calling {@link ConnectivityManager#getNetworkPreference()}
- * requires permissions.
- * <p>Tests Permission:
- * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
- */
- @SmallTest
- public void testGetNetworkPreference() {
- try {
- mConnectivityManager.getNetworkPreference();
- fail("Was able to call getNetworkPreference");
- } catch (SecurityException e) {
- // expected
- }
- }
-
- /**
* Verify that calling {@link ConnectivityManager#requestRouteToHost(int, int)}
* requires permissions.
* <p>Tests Permission:
@@ -85,37 +69,5 @@
// expected
}
}
-
- /**
- * Verify that calling {@link ConnectivityManager#setNetworkPreference(int)}
- * requires permissions.
- * <p>Tests Permission:
- * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
- */
- @SmallTest
- public void testSetNetworkPreference() {
- try {
- mConnectivityManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
- fail("Was able to call setNetworkPreference");
- } catch (SecurityException e) {
- // expected
- }
- }
-
- /**
- * Verify that calling {@link ConnectivityManager#setNetworkPreference(int)}
- * requires permissions.
- * <p>Tests Permission:
- * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
- */
- @SmallTest
- public void testStartUsingNetworkPreference() {
- try {
- mConnectivityManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
- fail("Was able to call setNetworkPreference");
- } catch (SecurityException e) {
- // expected
- }
- }
}
diff --git a/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
index 62b3683..91ffdf4 100644
--- a/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoActivityRelatedPermissionTest.java
@@ -27,6 +27,8 @@
import android.view.WindowManager;
import android.view.WindowManager.BadTokenException;
+import java.util.List;
+
/**
* Verify the Activity related operations require specific permissions.
*/
@@ -54,18 +56,16 @@
public void testGetTask() {
ActivityManager manager = (ActivityManager) getActivity()
.getSystemService(Context.ACTIVITY_SERVICE);
- try {
- manager.getRunningTasks(1);
- fail("Activity.getRunningTasks did not throw SecurityException as expected");
- } catch (SecurityException e) {
- // Expected
- }
+ List<ActivityManager.RunningTaskInfo> runningTasks = manager.getRunningTasks(10);
+ // Current implementation should only return tasks for home and the caller.
+ // We'll be done and task this to mean it shouldn't return more than 2.
+ assertTrue("Found tasks: " + runningTasks,
+ runningTasks == null || runningTasks.size() <= 2);
- try {
- manager.getRecentTasks(1, 0);
- fail("Activity.getRunningTasks did not throw SecurityException as expected");
- } catch (SecurityException e) {
- // Expected
- }
+ List<ActivityManager.RecentTaskInfo> recentTasks = manager.getRecentTasks(10,
+ ActivityManager.RECENT_WITH_EXCLUDED);
+ // Current implementation should only return tasks for home and the caller.
+ // We'll be done and task this to mean it shouldn't return more than 2.
+ assertTrue("Found tasks: " + recentTasks, recentTasks == null || recentTasks.size() <= 2);
}
}
diff --git a/tests/tests/permission/src/android/permission/cts/NoLocationPermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoLocationPermissionTest.java
index a2cbfb7..93e26ac 100644
--- a/tests/tests/permission/src/android/permission/cts/NoLocationPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoLocationPermissionTest.java
@@ -28,28 +28,31 @@
import android.os.Looper;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
import android.test.suitebuilder.annotation.SmallTest;
+import android.test.UiThreadTest;
import java.util.List;
/**
* Verify the location access without specific permissions.
*/
-public class NoLocationPermissionTest extends AndroidTestCase {
+public class NoLocationPermissionTest extends InstrumentationTestCase {
private static final String TEST_PROVIDER_NAME = "testProvider";
private LocationManager mLocationManager;
private List<String> mAllProviders;
private boolean mHasTelephony;
+ private Context mContext;
@Override
protected void setUp() throws Exception {
super.setUp();
- mLocationManager = (LocationManager) getContext().getSystemService(
+ mContext = getInstrumentation().getTargetContext();
+ mLocationManager = (LocationManager) mContext.getSystemService(
Context.LOCATION_SERVICE);
mAllProviders = mLocationManager.getAllProviders();
- mHasTelephony = getContext().getPackageManager().hasSystemFeature(
+ mHasTelephony = mContext.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_TELEPHONY);
assertNotNull(mLocationManager);
@@ -66,13 +69,13 @@
* Requires Permission: {@link
* android.Manifest.permission#ACCESS_COARSE_LOCATION.}
*/
- @SmallTest
+ @UiThreadTest
public void testListenCellLocation() {
if (!mHasTelephony) {
return;
}
- TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(
+ TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(
Context.TELEPHONY_SERVICE);
PhoneStateListener phoneStateListener = new PhoneStateListener();
try {
@@ -97,13 +100,13 @@
* Requires Permission: {@link
* android.Manifest.permission#ACCESS_COARSE_LOCATION.}
*/
- @SmallTest
+ @UiThreadTest
public void testListenCellLocation2() {
if (!mHasTelephony) {
return;
}
- TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(
+ TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(
Context.TELEPHONY_SERVICE);
PhoneStateListener phoneStateListener = new PhoneStateListener();
@@ -159,7 +162,7 @@
* Requires Permission:
* {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
*/
- @SmallTest
+ @UiThreadTest
public void testRequestLocationUpdatesNetwork() {
checkRequestLocationUpdates(LocationManager.NETWORK_PROVIDER);
}
@@ -170,7 +173,7 @@
* Requires Permission:
* {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
*/
- @SmallTest
+ @UiThreadTest
public void testRequestLocationUpdatesGps() {
checkRequestLocationUpdates(LocationManager.GPS_PROVIDER);
}
@@ -183,7 +186,7 @@
*/
@SmallTest
public void testAddProximityAlert() {
- PendingIntent mockPendingIntent = PendingIntent.getBroadcast(getContext(),
+ PendingIntent mockPendingIntent = PendingIntent.getBroadcast(mContext,
0, new Intent("mockIntent"), PendingIntent.FLAG_ONE_SHOT);
try {
mLocationManager.addProximityAlert(0, 0, 100, -1, mockPendingIntent);
diff --git a/tests/tests/permission/src/android/permission/cts/NoNetworkStatePermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoNetworkStatePermissionTest.java
index 0f24cf5..0eae9cc 100644
--- a/tests/tests/permission/src/android/permission/cts/NoNetworkStatePermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoNetworkStatePermissionTest.java
@@ -27,9 +27,8 @@
*/
public class NoNetworkStatePermissionTest extends AndroidTestCase {
private ConnectivityManager mConnectivityManager;
- private static final int TEST_NETWORK_TYPE = 1;
- private static final int TEST_PREFERENCE = 1;
- private static final String TEST_FEATURE = "feature";
+ private static final int TEST_NETWORK_TYPE = ConnectivityManager.TYPE_MOBILE;
+ private static final String TEST_FEATURE = "enableHIPRI";
@Override
protected void setUp() throws Exception {
@@ -40,22 +39,6 @@
}
/**
- * Verify that ConnectivityManager#getNetworkPreference() requires permissions.
- * <p>Requires Permission:
- * {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
- */
- @SmallTest
- public void testGetNetworkPreference() {
- try {
- mConnectivityManager.getNetworkPreference();
- fail("ConnectivityManager.getNetworkPreference didn't throw SecurityException as"
- + " expected");
- } catch (SecurityException e) {
- // expected
- }
- }
-
- /**
* Verify that ConnectivityManager#getActiveNetworkInfo() requires permissions.
* <p>Requires Permission:
* {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
@@ -104,22 +87,6 @@
}
/**
- * Verify that ConnectivityManager#setNetworkPreference() requires permissions.
- * <p>Requires Permission:
- * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
- */
- @SmallTest
- public void testSetNetworkPreference() {
- try {
- mConnectivityManager.setNetworkPreference(TEST_PREFERENCE);
- fail("ConnectivityManager.setNetworkPreference didn't throw SecurityException as"
- + " expected");
- } catch (SecurityException e) {
- // expected
- }
- }
-
- /**
* Verify that ConnectivityManager#startUsingNetworkFeature() requires permissions.
* <p>Requires Permission:
* {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
@@ -136,22 +103,6 @@
}
/**
- * Verify that ConnectivityManager#stopUsingNetworkFeature() requires permissions.
- * <p>Requires Permission:
- * {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
- */
- @SmallTest
- public void testStopUsingNetworkFeature() {
- try {
- mConnectivityManager.stopUsingNetworkFeature(TEST_NETWORK_TYPE, TEST_FEATURE);
- fail("ConnectivityManager.stopUsingNetworkFeature didn't throw SecurityException as"
- + " expected");
- } catch (SecurityException e) {
- // expected
- }
- }
-
- /**
* Verify that ConnectivityManager#requestRouteToHost() requires permissions.
* <p>Requires Permission:
* {@link android.Manifest.permission#CHANGE_NETWORK_STATE}.
diff --git a/tests/tests/permission/src/android/permission/cts/NoReadLogsPermissionTest.java b/tests/tests/permission/src/android/permission/cts/NoReadLogsPermissionTest.java
index 9441319..8979a07 100644
--- a/tests/tests/permission/src/android/permission/cts/NoReadLogsPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/NoReadLogsPermissionTest.java
@@ -16,7 +16,10 @@
package android.permission.cts;
-import android.permission.cts.FileUtils.FileStatus;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
+import android.system.StructStat;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.util.Log;
@@ -72,19 +75,30 @@
}
}
- public void testLogFilePermissions() {
- File logDir = new File("/dev/log");
- File[] logFiles = logDir.listFiles();
- assertTrue("Where are the log files? Please check that they are not world readable.",
- logFiles.length > 0);
+ public void testEventsLogSane() throws ErrnoException {
+ testLogIsSane("/dev/log/events");
+ }
- FileStatus status = new FileStatus();
- for (File log : logFiles) {
- if (FileUtils.getFileStatus(log.getAbsolutePath(), status, false)) {
- assertEquals("Log file " + log.getAbsolutePath() + " should have user root.",
- 0, status.uid);
- assertTrue("Log file " + log.getAbsolutePath() + " should have group log.",
- "log".equals(FileUtils.getGroupName(status.gid)));
+ public void testMainLogSane() throws ErrnoException {
+ testLogIsSane("/dev/log/main");
+ }
+
+ public void testRadioLogSane() throws ErrnoException {
+ testLogIsSane("/dev/log/radio");
+ }
+
+ public void testSystemLogSane() throws ErrnoException {
+ testLogIsSane("/dev/log/system");
+ }
+
+ private static void testLogIsSane(String log) throws ErrnoException {
+ try {
+ StructStat stat = Os.stat(log);
+ assertEquals("not owned by uid=0", 0, stat.st_uid);
+ assertEquals("not owned by gid=logs", "log", FileUtils.getGroupName(stat.st_gid));
+ } catch (ErrnoException e) {
+ if (e.errno != OsConstants.ENOENT && e.errno != OsConstants.EACCES) {
+ throw e;
}
}
}
diff --git a/tests/tests/print/src/android/print/cts/BasePrintTest.java b/tests/tests/print/src/android/print/cts/BasePrintTest.java
index a8e8a95..1493bc9 100644
--- a/tests/tests/print/src/android/print/cts/BasePrintTest.java
+++ b/tests/tests/print/src/android/print/cts/BasePrintTest.java
@@ -39,8 +39,10 @@
import android.print.PrintDocumentAdapter.WriteResultCallback;
import android.print.PrintManager;
import android.print.PrinterId;
+import android.print.cts.services.FirstPrintService;
import android.print.cts.services.PrintServiceCallbacks;
import android.print.cts.services.PrinterDiscoverySessionCallbacks;
+import android.print.cts.services.SecondPrintService;
import android.print.cts.services.StubbablePrinterDiscoverySession;
import android.print.pdf.PrintedPdfDocument;
import android.printservice.PrintJob;
@@ -68,7 +70,7 @@
*/
public abstract class BasePrintTest extends UiAutomatorTestCase {
- private static final long OPERATION_TIMEOUT = 10000;
+ private static final long OPERATION_TIMEOUT = 100000000;
private static final String ARG_PRIVILEGED_OPS = "ARG_PRIVILEGED_OPS";
diff --git a/tests/tests/print/src/android/print/cts/PrintDocumentAdapterContractTest.java b/tests/tests/print/src/android/print/cts/PrintDocumentAdapterContractTest.java
index 64bc5d6..516db56 100644
--- a/tests/tests/print/src/android/print/cts/PrintDocumentAdapterContractTest.java
+++ b/tests/tests/print/src/android/print/cts/PrintDocumentAdapterContractTest.java
@@ -122,6 +122,9 @@
// Wait for finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -229,6 +232,9 @@
// Wait for finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -344,6 +350,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -510,6 +519,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -649,6 +661,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -765,6 +780,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -868,6 +886,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -967,6 +988,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -1055,6 +1079,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -1121,6 +1148,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -1197,6 +1227,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -1283,6 +1316,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -1348,6 +1384,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -1421,6 +1460,9 @@
// Wait for a finish.
waitForAdapterFinishCallbackCalled();
+ // Wait for the session to be destroyed to isolate tests.
+ waitForPrinterDiscoverySessionDestroyCallbackCalled();
+
// Verify the expected calls.
InOrder inOrder = inOrder(adapter);
@@ -1517,7 +1559,14 @@
}
return null;
}
- }, null, null, null, null, null);
+ }, null, null, null, null, new Answer<Void>() {
+ @Override
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ // Take a note onDestroy was called.
+ onPrinterDiscoverySessionDestroyCalled();
+ return null;
+ }
+ });
return createMockPrintServiceCallbacks(new Answer<PrinterDiscoverySessionCallbacks>() {
@Override
public PrinterDiscoverySessionCallbacks answer(InvocationOnMock invocation) {
diff --git a/tests/tests/provider/src/android/provider/cts/BrowserTest.java b/tests/tests/provider/src/android/provider/cts/BrowserTest.java
index ffeb2a1..2f0432a 100644
--- a/tests/tests/provider/src/android/provider/cts/BrowserTest.java
+++ b/tests/tests/provider/src/android/provider/cts/BrowserTest.java
@@ -36,7 +36,7 @@
public class BrowserTest extends ActivityInstrumentationTestCase2<BrowserStubActivity> {
public BrowserTest() {
- super("com.android.cts.stub", BrowserStubActivity.class);
+ super("com.android.cts.provider", BrowserStubActivity.class);
}
private Context mContext;
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStoreAudioTestHelper.java b/tests/tests/provider/src/android/provider/cts/MediaStoreAudioTestHelper.java
index a87cd3a..c9eb506 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStoreAudioTestHelper.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStoreAudioTestHelper.java
@@ -107,7 +107,7 @@
public static final String DISPLAY_NAME = "Jam -Michael Jackson";
public static final String INTERNAL_DATA =
- "/data/data/com.android.cts.stub/files/Jam.mp3";
+ "/data/data/com.android.cts.provider/files/Jam.mp3";
public static final String FILE_NAME = "Jam.mp3";
@@ -190,7 +190,7 @@
Environment.getExternalStorageDirectory().getPath() + "/" + FILE_NAME;
public static final String INTERNAL_DATA =
- "/data/data/com.android.cts.stub/files/Jam_live.mp3";
+ "/data/data/com.android.cts.provider/files/Jam_live.mp3";
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java
index 03a81b8..8dcb1a8 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_PlaylistsTest.java
@@ -112,7 +112,7 @@
public void testStoreAudioPlaylistsInternal() {
ContentValues values = new ContentValues();
values.put(Playlists.NAME, "My favourites");
- values.put(Playlists.DATA, "/data/data/com.android.cts.stub/files/my_favorites.pl");
+ values.put(Playlists.DATA, "/data/data/com.android.cts.provider/files/my_favorites.pl");
long dateAdded = System.currentTimeMillis();
values.put(Playlists.DATE_ADDED, dateAdded);
long dateModified = System.currentTimeMillis();
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java
index bf97848..58c1cdf 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStore_Audio_Playlists_MembersTest.java
@@ -454,7 +454,7 @@
public void testStoreAudioPlaylistsMembersInternal() {
ContentValues values = new ContentValues();
values.put(Playlists.NAME, "My favourites");
- values.put(Playlists.DATA, "/data/data/com.android.cts.stub/files/my_favorites.pl");
+ values.put(Playlists.DATA, "/data/data/com.android.cts.provider/files/my_favorites.pl");
long dateAdded = System.currentTimeMillis();
values.put(Playlists.DATE_ADDED, dateAdded);
long dateModified = System.currentTimeMillis();
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/TestGetSet.java b/tests/tests/renderscript/src/android/renderscript/cts/TestGetSet.java
new file mode 100644
index 0000000..d11de84
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/TestGetSet.java
@@ -0,0 +1,1084 @@
+ /*
+ * Copyright (C) 2014 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.renderscript.cts;
+
+import android.renderscript.*;
+
+public class TestGetSet extends RSBaseCompute {
+
+ private ScriptC_getset script;
+ private ScriptC_getset_relaxed scriptRelaxed;
+ Allocation walkAlloc;
+ Allocation in1DAlloc;
+ Allocation out1DAlloc;
+ Allocation in2DAlloc;
+ Allocation out2DAlloc;
+ Allocation in3DAlloc;
+ Allocation out3DAlloc;
+ private static java.util.Random random = new java.util.Random();
+
+ final int gWidth = 252;
+ final int gHeight = 31;
+ final int gDepth = 4;
+ final int gCount = gWidth * gHeight * gDepth;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ random.setSeed(10);
+ script = new ScriptC_getset(mRS);
+ scriptRelaxed = new ScriptC_getset_relaxed(mRS);
+ script.set_gWidth(gWidth);
+ script.set_gHeight(gHeight);
+ scriptRelaxed.set_gWidth(gWidth);
+ scriptRelaxed.set_gHeight(gHeight);
+ }
+
+
+
+ protected void createWalk(int vsize) {
+ // We do a random copy order to attempt to get multiple threads
+ // reading and writing the same cache line
+ // We could do this as a simple walk but that would likely miss
+ // some caching issues.
+ final int tw = gCount / vsize;
+ int tmp[] = new int[tw];
+ boolean b[] = new boolean[tw];
+ int toCopy = tw;
+ int i = 0;
+
+ while (toCopy > 0) {
+ int x = random.nextInt(tw);
+
+ while ((x < tw) && b[x]) {
+ x++;
+ if (x >= tw) {
+ x = 0;
+ }
+ }
+
+ b[x] = true;
+ toCopy --;
+
+ //android.util.Log.v("rs", "walk " + i + ", " + x);
+ tmp[i++] = x;
+ }
+
+ walkAlloc = Allocation.createSized(mRS, Element.I32(mRS), tw);
+ walkAlloc.copy1DRangeFrom(0, tw, tmp);
+ }
+
+ private void testSetup(Element e) {
+ int vs = e.getVectorSize();
+ if (vs == 3) {
+ vs = 4;
+ }
+ createWalk(vs);
+
+ Type t1 = Type.createX(mRS, e, gWidth * gHeight * gDepth / vs);
+ in1DAlloc = Allocation.createTyped(mRS, t1);
+ out1DAlloc = Allocation.createTyped(mRS, t1);
+ script.set_gAlloc1DIn(in1DAlloc);
+ script.set_gAlloc1DOut(out1DAlloc);
+ scriptRelaxed.set_gAlloc1DIn(in1DAlloc);
+ scriptRelaxed.set_gAlloc1DOut(out1DAlloc);
+
+ Type t2 = Type.createXY(mRS, e, gWidth / vs, gHeight * gDepth);
+ in2DAlloc = Allocation.createTyped(mRS, t2);
+ out2DAlloc = Allocation.createTyped(mRS, t2);
+ script.set_gAlloc2DIn(in2DAlloc);
+ script.set_gAlloc2DOut(out2DAlloc);
+ scriptRelaxed.set_gAlloc2DIn(in2DAlloc);
+ scriptRelaxed.set_gAlloc2DOut(out2DAlloc);
+
+ Type t3 = Type.createXYZ(mRS, e, gWidth / vs, gHeight, gDepth);
+ in3DAlloc = Allocation.createTyped(mRS, t3);
+ out3DAlloc = Allocation.createTyped(mRS, t3);
+ script.set_gAlloc3DIn(in3DAlloc);
+ script.set_gAlloc3DOut(out3DAlloc);
+ scriptRelaxed.set_gAlloc3DIn(in3DAlloc);
+ scriptRelaxed.set_gAlloc3DOut(out3DAlloc);
+ }
+
+ private void verify(byte[] a1, byte[] a2, Allocation alloc, String s, int vsize) {
+ alloc.copyTo(a2);
+ for (int i=0; i < gWidth; i++) {
+ if (a1[i] != a2[i]) {
+ if ((vsize == 3) && ((i % 4) == 3)) {
+ continue;
+ }
+ throw new RSRuntimeException(s + a1[i] + ", " + a2[i] + ", at " + i);
+ }
+ a2[i] = 0;
+ }
+ alloc.copyFrom(a2);
+ }
+
+ private void verify(short[] a1, short[] a2, Allocation alloc, String s, int vsize) {
+ alloc.copyTo(a2);
+ for (int i=0; i < gWidth; i++) {
+ if (a1[i] != a2[i]) {
+ if ((vsize == 3) && ((i % 4) == 3)) {
+ continue;
+ }
+ throw new RSRuntimeException(s + a1[i] + ", " + a2[i] + ", at " + i);
+ }
+ a2[i] = 0;
+ }
+ alloc.copyFrom(a2);
+ }
+
+ private void verify(int[] a1, int[] a2, Allocation alloc, String s, int vsize) {
+ alloc.copyTo(a2);
+ for (int i=0; i < gWidth; i++) {
+ if (a1[i] != a2[i]) {
+ if ((vsize == 3) && ((i % 4) == 3)) {
+ continue;
+ }
+ throw new RSRuntimeException(s + a1[i] + ", " + a2[i] + ", at " + i);
+ }
+ a2[i] = 0;
+ }
+ alloc.copyFrom(a2);
+ }
+
+ private void verify(long[] a1, long[] a2, Allocation alloc, String s, int vsize) {
+ alloc.copyTo(a2);
+ for (int i=0; i < gWidth; i++) {
+ if (a1[i] != a2[i]) {
+ if ((vsize == 3) && ((i % 4) == 3)) {
+ continue;
+ }
+ throw new RSRuntimeException(s + a1[i] + ", " + a2[i] + ", at " + i);
+ }
+ a2[i] = 0;
+ }
+ alloc.copyFrom(a2);
+ }
+
+ private void verify(float[] a1, float[] a2, Allocation alloc, String s, int vsize) {
+ alloc.copyTo(a2);
+ for (int i=0; i < gWidth; i++) {
+ if (a1[i] != a2[i]) {
+ if ((vsize == 3) && ((i % 4) == 3)) {
+ continue;
+ }
+ throw new RSRuntimeException(s + a1[i] + ", " + a2[i] + ", at " + i);
+ }
+ a2[i] = 0;
+ }
+ alloc.copyFrom(a2);
+ }
+
+ private void verify(double[] a1, double[] a2, Allocation alloc, String s, int vsize) {
+ alloc.copyTo(a2);
+ for (int i=0; i < gWidth; i++) {
+ if (a1[i] != a2[i]) {
+ if ((vsize == 3) && ((i % 4) == 3)) {
+ continue;
+ }
+ throw new RSRuntimeException(s + a1[i] + ", " + a2[i] + ", at " + i);
+ }
+ a2[i] = 0;
+ }
+ alloc.copyFrom(a2);
+ }
+
+ private byte[] randomByteArray(int len) {
+ byte t[] = new byte[len];
+ random.nextBytes(t);
+ in1DAlloc.copyFrom(t);
+ in2DAlloc.copyFrom(t);
+ in3DAlloc.copyFrom(t);
+ return t;
+ }
+
+ private short[] randomShortArray(int len) {
+ short t[] = new short[len];
+ for (int i = 0; i < t.length; i++) {
+ t[i] = (short)(random.nextInt() & 0xffff);
+ }
+ in1DAlloc.copyFrom(t);
+ in2DAlloc.copyFrom(t);
+ in3DAlloc.copyFrom(t);
+ return t;
+ }
+
+ private int[] randomIntArray(int len) {
+ int t[] = new int[len];
+ for (int i = 0; i < t.length; i++) {
+ t[i] = random.nextInt();
+ }
+ in1DAlloc.copyFrom(t);
+ in2DAlloc.copyFrom(t);
+ in3DAlloc.copyFrom(t);
+ return t;
+ }
+
+ private long[] randomLongArray(int len) {
+ long t[] = new long[len];
+ for (int i = 0; i < t.length; i++) {
+ t[i] = random.nextLong();
+ }
+ in1DAlloc.copyFrom(t);
+ in2DAlloc.copyFrom(t);
+ in3DAlloc.copyFrom(t);
+ return t;
+ }
+
+ private float[] randomFloatArray(int len) {
+ float t[] = new float[len];
+ for (int i = 0; i < t.length; i++) {
+ t[i] = random.nextFloat();
+ }
+ in1DAlloc.copyFrom(t);
+ in2DAlloc.copyFrom(t);
+ in3DAlloc.copyFrom(t);
+ return t;
+ }
+
+ private double[] randomDoubleArray(int len) {
+ double t[] = new double[len];
+ for (int i = 0; i < t.length; i++) {
+ t[i] = random.nextDouble();
+ }
+ in1DAlloc.copyFrom(t);
+ in2DAlloc.copyFrom(t);
+ in3DAlloc.copyFrom(t);
+ return t;
+ }
+
+ public void testGetSet_char() {
+ testSetup(Element.I8(mRS));
+ byte tmp[] = randomByteArray(gCount);
+ byte tmp2[] = new byte[gCount];
+
+ script.forEach_copy1D_char(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch char: ", 1);
+ scriptRelaxed.forEach_copy1D_char(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed char: ", 1);
+
+ script.forEach_copy2D_char(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch char: ", 1);
+ scriptRelaxed.forEach_copy2D_char(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed char: ", 1);
+
+ script.forEach_copy3D_char(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch char: ", 1);
+ scriptRelaxed.forEach_copy3D_char(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed char: ", 1);
+ }
+
+ public void testGetSet_char2() {
+ testSetup(Element.I8_2(mRS));
+ byte tmp[] = randomByteArray(gCount);
+ byte tmp2[] = new byte[gCount];
+ script.forEach_copy1D_char2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch char2: ", 2);
+ scriptRelaxed.forEach_copy1D_char2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed char2: ", 2);
+
+ script.forEach_copy2D_char2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch char2: ", 2);
+ scriptRelaxed.forEach_copy2D_char2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed char2: ", 2);
+
+ script.forEach_copy3D_char2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch char2: ", 2);
+ scriptRelaxed.forEach_copy3D_char2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed char2: ", 2);
+ }
+
+ public void testGetSet_char3() {
+ testSetup(Element.I8_3(mRS));
+ byte tmp[] = randomByteArray(gCount);
+ byte tmp2[] = new byte[gCount];
+ script.forEach_copy1D_char3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch char3: ", 3);
+ scriptRelaxed.forEach_copy1D_char3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed char3: ", 3);
+
+ script.forEach_copy2D_char3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch char3: ", 3);
+ scriptRelaxed.forEach_copy2D_char3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed char3: ", 3);
+
+ script.forEach_copy3D_char3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch char3: ", 3);
+ scriptRelaxed.forEach_copy3D_char3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed char3: ", 3);
+ }
+
+ public void testGetSet_char4() {
+ testSetup(Element.I8_4(mRS));
+ byte tmp[] = randomByteArray(gCount);
+ byte tmp2[] = new byte[gCount];
+ script.forEach_copy1D_char4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch char4: ", 4);
+ scriptRelaxed.forEach_copy1D_char4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed char4: ", 4);
+
+ script.forEach_copy2D_char4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch char4: ", 4);
+ scriptRelaxed.forEach_copy2D_char4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed char4: ", 4);
+
+ script.forEach_copy3D_char4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch char4: ", 4);
+ scriptRelaxed.forEach_copy3D_char4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed char4: ", 4);
+ }
+
+ public void testGetSet_uchar() {
+ testSetup(Element.U8(mRS));
+ byte tmp[] = randomByteArray(gCount);
+ byte tmp2[] = new byte[gCount];
+ script.forEach_copy1D_uchar(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch uchar: ", 1);
+ scriptRelaxed.forEach_copy1D_uchar(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed uchar: ", 1);
+
+ script.forEach_copy2D_uchar(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch uchar: ", 1);
+ scriptRelaxed.forEach_copy2D_uchar(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed uchar: ", 1);
+
+ script.forEach_copy3D_uchar(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch uchar: ", 1);
+ scriptRelaxed.forEach_copy3D_uchar(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed uchar: ", 1);
+ }
+
+ public void testGetSet_uchar2() {
+ testSetup(Element.U8_2(mRS));
+ byte tmp[] = randomByteArray(gCount);
+ byte tmp2[] = new byte[gCount];
+ script.forEach_copy1D_uchar2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch uchar2: ", 2);
+ scriptRelaxed.forEach_copy1D_uchar2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed uchar2: ", 2);
+
+ script.forEach_copy2D_uchar2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch uchar2: ", 2);
+ scriptRelaxed.forEach_copy2D_uchar2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed uchar2: ", 2);
+
+ script.forEach_copy3D_uchar2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch uchar2: ", 2);
+ scriptRelaxed.forEach_copy3D_uchar2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed uchar2: ", 2);
+ }
+
+ public void testGetSet_uchar3() {
+ testSetup(Element.U8_3(mRS));
+ byte tmp[] = randomByteArray(gCount);
+ byte tmp2[] = new byte[gCount];
+ script.forEach_copy1D_uchar3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch uchar3: ", 3);
+ scriptRelaxed.forEach_copy1D_uchar3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed uchar3: ", 3);
+
+ script.forEach_copy2D_uchar3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch uchar3: ", 3);
+ scriptRelaxed.forEach_copy2D_uchar3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed uchar3: ", 3);
+
+ script.forEach_copy3D_uchar3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch uchar3: ", 3);
+ scriptRelaxed.forEach_copy3D_uchar3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed uchar3: ", 3);
+ }
+
+ public void testGetSet_uchar4() {
+ testSetup(Element.U8_4(mRS));
+ byte tmp[] = randomByteArray(gCount);
+ byte tmp2[] = new byte[gCount];
+ script.forEach_copy1D_uchar4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch uchar4: ", 4);
+ scriptRelaxed.forEach_copy1D_uchar4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed uchar4: ", 4);
+
+ script.forEach_copy2D_uchar4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch uchar4: ", 4);
+ scriptRelaxed.forEach_copy2D_uchar4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed uchar4: ", 4);
+
+ script.forEach_copy3D_uchar4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch uchar4: ", 4);
+ scriptRelaxed.forEach_copy3D_uchar4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed uchar4: ", 4);
+ }
+
+
+
+
+
+
+ public void testGetSet_short() {
+ testSetup(Element.I16(mRS));
+ short tmp[] = randomShortArray(gCount);
+ short tmp2[] = new short[gCount];
+ script.forEach_copy1D_short(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch short: ", 1);
+ scriptRelaxed.forEach_copy1D_short(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed short: ", 1);
+
+ script.forEach_copy2D_short(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch short: ", 1);
+ scriptRelaxed.forEach_copy2D_short(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed short: ", 1);
+
+ script.forEach_copy3D_short(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch short: ", 1);
+ scriptRelaxed.forEach_copy3D_short(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed short: ", 1);
+ }
+
+ public void testGetSet_short2() {
+ testSetup(Element.I16_2(mRS));
+ short tmp[] = randomShortArray(gCount);
+ short tmp2[] = new short[gCount];
+ script.forEach_copy1D_short2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch short2: ", 2);
+ scriptRelaxed.forEach_copy1D_short2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed short2: ", 2);
+
+ script.forEach_copy2D_short2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch short2: ", 2);
+ scriptRelaxed.forEach_copy2D_short2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed short2: ", 2);
+
+ script.forEach_copy3D_short2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch short2: ", 2);
+ scriptRelaxed.forEach_copy3D_short2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed short2: ", 2);
+ }
+
+ public void testGetSet_short3() {
+ testSetup(Element.I16_3(mRS));
+ short tmp[] = randomShortArray(gCount);
+ short tmp2[] = new short[gCount];
+ script.forEach_copy1D_short3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch short3: ", 3);
+ scriptRelaxed.forEach_copy1D_short3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed short3: ", 3);
+
+ script.forEach_copy2D_short3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch short3: ", 3);
+ scriptRelaxed.forEach_copy2D_short3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed short3: ", 3);
+
+ script.forEach_copy3D_short3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch short3: ", 3);
+ scriptRelaxed.forEach_copy3D_short3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed short3: ", 3);
+ }
+
+ public void testGetSet_short4() {
+ testSetup(Element.I16_4(mRS));
+ short tmp[] = randomShortArray(gCount);
+ short tmp2[] = new short[gCount];
+ script.forEach_copy1D_short4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch short4: ", 4);
+ scriptRelaxed.forEach_copy1D_short4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed short4: ", 4);
+
+ script.forEach_copy2D_short4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch short4: ", 4);
+ scriptRelaxed.forEach_copy2D_short4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed short4: ", 4);
+
+ script.forEach_copy3D_short4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch short4: ", 4);
+ scriptRelaxed.forEach_copy3D_short4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed short4: ", 4);
+ }
+
+ public void testGetSet_ushort() {
+ testSetup(Element.U16(mRS));
+ short tmp[] = randomShortArray(gCount);
+ short tmp2[] = new short[gCount];
+ script.forEach_copy1D_ushort(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch ushort: ", 1);
+ scriptRelaxed.forEach_copy1D_ushort(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed ushort: ", 1);
+
+ script.forEach_copy2D_ushort(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch ushort: ", 1);
+ scriptRelaxed.forEach_copy2D_ushort(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed ushort: ", 1);
+
+ script.forEach_copy3D_ushort(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch ushort: ", 1);
+ scriptRelaxed.forEach_copy3D_ushort(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed ushort: ", 1);
+ }
+
+ public void testGetSet_ushort2() {
+ testSetup(Element.U16_2(mRS));
+ short tmp[] = randomShortArray(gCount);
+ short tmp2[] = new short[gCount];
+ script.forEach_copy1D_ushort2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch ushort2: ", 2);
+ scriptRelaxed.forEach_copy1D_ushort2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed ushort2: ", 2);
+
+ script.forEach_copy2D_ushort2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch ushort2: ", 2);
+ scriptRelaxed.forEach_copy2D_ushort2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed ushort2: ", 2);
+
+ script.forEach_copy3D_ushort2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch ushort2: ", 2);
+ scriptRelaxed.forEach_copy3D_ushort2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed ushort2: ", 2);
+ }
+
+ public void testGetSet_ushort3() {
+ testSetup(Element.U16_3(mRS));
+ short tmp[] = randomShortArray(gCount);
+ short tmp2[] = new short[gCount];
+ script.forEach_copy1D_ushort3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch ushort3: ", 3);
+ scriptRelaxed.forEach_copy1D_ushort3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed ushort3: ", 3);
+
+ script.forEach_copy2D_ushort3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch ushort3: ", 3);
+ scriptRelaxed.forEach_copy2D_ushort3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed ushort3: ", 3);
+
+ script.forEach_copy3D_ushort3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch ushort3: ", 3);
+ scriptRelaxed.forEach_copy3D_ushort3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed ushort3: ", 3);
+ }
+
+ public void testGetSet_ushort4() {
+ testSetup(Element.U16_4(mRS));
+ short tmp[] = randomShortArray(gCount);
+ short tmp2[] = new short[gCount];
+ script.forEach_copy1D_ushort4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch ushort4: ", 4);
+ scriptRelaxed.forEach_copy1D_ushort4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed ushort4: ", 4);
+
+ script.forEach_copy2D_ushort4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch ushort4: ", 4);
+ scriptRelaxed.forEach_copy2D_ushort4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed ushort4: ", 4);
+
+ script.forEach_copy3D_ushort4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch ushort4: ", 4);
+ scriptRelaxed.forEach_copy3D_ushort4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed ushort4: ", 4);
+ }
+
+
+
+
+ public void testGetSet_int() {
+ testSetup(Element.I32(mRS));
+ int tmp[] = randomIntArray(gCount);
+ int tmp2[] = new int[gCount];
+ script.forEach_copy1D_int(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch int: ", 1);
+ scriptRelaxed.forEach_copy1D_int(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed int: ", 1);
+
+ script.forEach_copy2D_int(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch int: ", 1);
+ scriptRelaxed.forEach_copy2D_int(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed int: ", 1);
+
+ script.forEach_copy3D_int(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch int: ", 1);
+ scriptRelaxed.forEach_copy3D_int(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed int: ", 1);
+ }
+
+ public void testGetSet_int2() {
+ testSetup(Element.I32_2(mRS));
+ int tmp[] = randomIntArray(gCount);
+ int tmp2[] = new int[gCount];
+ script.forEach_copy1D_int2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch int2: ", 2);
+ scriptRelaxed.forEach_copy1D_int2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed int2: ", 2);
+
+ script.forEach_copy2D_int2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch int2: ", 2);
+ scriptRelaxed.forEach_copy2D_int2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed int2: ", 2);
+
+ script.forEach_copy3D_int2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch int2: ", 2);
+ scriptRelaxed.forEach_copy3D_int2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed int2: ", 2);
+ }
+
+ public void testGetSet_int3() {
+ testSetup(Element.I32_3(mRS));
+ int tmp[] = randomIntArray(gCount);
+ int tmp2[] = new int[gCount];
+ script.forEach_copy1D_int3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch int3: ", 3);
+ scriptRelaxed.forEach_copy1D_int3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed int3: ", 3);
+
+ script.forEach_copy2D_int3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch int3: ", 3);
+ scriptRelaxed.forEach_copy2D_int3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed int3: ", 3);
+
+ script.forEach_copy3D_int3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch int3: ", 3);
+ scriptRelaxed.forEach_copy3D_int3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed int3: ", 3);
+ }
+
+ public void testGetSet_int4() {
+ testSetup(Element.I32_4(mRS));
+ int tmp[] = randomIntArray(gCount);
+ int tmp2[] = new int[gCount];
+ script.forEach_copy1D_int4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch int4: ", 4);
+ scriptRelaxed.forEach_copy1D_int4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed int4: ", 4);
+
+ script.forEach_copy2D_int4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch int4: ", 4);
+ scriptRelaxed.forEach_copy2D_int4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed int4: ", 4);
+
+ script.forEach_copy3D_int4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch int4: ", 4);
+ scriptRelaxed.forEach_copy3D_int4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed int4: ", 4);
+ }
+
+ public void testGetSet_uint() {
+ testSetup(Element.U32(mRS));
+ int tmp[] = randomIntArray(gCount);
+ int tmp2[] = new int[gCount];
+ script.forEach_copy1D_uint(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch uint: ", 1);
+ scriptRelaxed.forEach_copy1D_uint(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed uint: ", 1);
+
+ script.forEach_copy2D_uint(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch uint: ", 1);
+ scriptRelaxed.forEach_copy2D_uint(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed uint: ", 1);
+
+ script.forEach_copy3D_uint(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch uint: ", 1);
+ scriptRelaxed.forEach_copy3D_uint(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed uint: ", 1);
+ }
+
+ public void testGetSet_uint2() {
+ testSetup(Element.U32_2(mRS));
+ int tmp[] = randomIntArray(gCount);
+ int tmp2[] = new int[gCount];
+ script.forEach_copy1D_uint2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch uint2: ", 2);
+ scriptRelaxed.forEach_copy1D_uint2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed uint2: ", 2);
+
+ script.forEach_copy2D_uint2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch uint2: ", 2);
+ scriptRelaxed.forEach_copy2D_uint2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed uint2: ", 2);
+
+ script.forEach_copy3D_uint2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch uint2: ", 2);
+ scriptRelaxed.forEach_copy3D_uint2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed uint2: ", 2);
+ }
+
+ public void testGetSet_uint3() {
+ testSetup(Element.U32_3(mRS));
+ int tmp[] = randomIntArray(gCount);
+ int tmp2[] = new int[gCount];
+ script.forEach_copy1D_uint3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch uint3: ", 3);
+ scriptRelaxed.forEach_copy1D_uint3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed uint3: ", 3);
+
+ script.forEach_copy2D_uint3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch uint3: ", 3);
+ scriptRelaxed.forEach_copy2D_uint3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed uint3: ", 3);
+
+ script.forEach_copy3D_uint3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch uint3: ", 3);
+ scriptRelaxed.forEach_copy3D_uint3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed uint3: ", 3);
+ }
+
+ public void testGetSet_uint4() {
+ testSetup(Element.U32_4(mRS));
+ int tmp[] = randomIntArray(gCount);
+ int tmp2[] = new int[gCount];
+ script.forEach_copy1D_uint4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch uint4: ", 4);
+ scriptRelaxed.forEach_copy1D_uint4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed uint4: ", 4);
+
+ script.forEach_copy2D_uint4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch uint4: ", 4);
+ scriptRelaxed.forEach_copy2D_uint4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed uint4: ", 4);
+
+ script.forEach_copy3D_uint4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch uint4: ", 4);
+ scriptRelaxed.forEach_copy3D_uint4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed uint4: ", 4);
+ }
+
+
+
+
+ public void testGetSet_long() {
+ testSetup(Element.I64(mRS));
+ long tmp[] = randomLongArray(gCount);
+ long tmp2[] = new long[gCount];
+ script.forEach_copy1D_long(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch long: ", 1);
+ scriptRelaxed.forEach_copy1D_long(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed long: ", 1);
+
+ script.forEach_copy2D_long(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch long: ", 1);
+ scriptRelaxed.forEach_copy2D_long(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed long: ", 1);
+
+ script.forEach_copy3D_long(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch long: ", 1);
+ scriptRelaxed.forEach_copy3D_long(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed long: ", 1);
+ }
+
+ public void testGetSet_long2() {
+ testSetup(Element.I64_2(mRS));
+ long tmp[] = randomLongArray(gCount);
+ long tmp2[] = new long[gCount];
+ script.forEach_copy1D_long2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch long2: ", 2);
+ scriptRelaxed.forEach_copy1D_long2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed long2: ", 2);
+
+ script.forEach_copy2D_long2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch long2: ", 2);
+ scriptRelaxed.forEach_copy2D_long2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed long2: ", 2);
+
+ script.forEach_copy3D_long2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch long2: ", 2);
+ scriptRelaxed.forEach_copy3D_long2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed long2: ", 2);
+ }
+
+ public void testGetSet_long3() {
+ testSetup(Element.I64_3(mRS));
+ long tmp[] = randomLongArray(gCount);
+ long tmp2[] = new long[gCount];
+ script.forEach_copy1D_long3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch long3: ", 3);
+ scriptRelaxed.forEach_copy1D_long3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed long3: ", 3);
+
+ script.forEach_copy2D_long3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch long3: ", 3);
+ scriptRelaxed.forEach_copy2D_long3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed long3: ", 3);
+
+ script.forEach_copy3D_long3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch long3: ", 3);
+ scriptRelaxed.forEach_copy3D_long3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed long3: ", 3);
+ }
+
+ public void testGetSet_long4() {
+ testSetup(Element.I64_4(mRS));
+ long tmp[] = randomLongArray(gCount);
+ long tmp2[] = new long[gCount];
+ script.forEach_copy1D_long4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch long4: ", 4);
+ scriptRelaxed.forEach_copy1D_long4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed long4: ", 4);
+
+ script.forEach_copy2D_long4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch long4: ", 4);
+ scriptRelaxed.forEach_copy2D_long4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed long4: ", 4);
+
+ script.forEach_copy3D_long4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch long4: ", 4);
+ scriptRelaxed.forEach_copy3D_long4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed long4: ", 4);
+ }
+
+ public void testGetSet_ulong() {
+ testSetup(Element.U64(mRS));
+ long tmp[] = randomLongArray(gCount);
+ long tmp2[] = new long[gCount];
+ script.forEach_copy1D_ulong(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch ulong: ", 1);
+ scriptRelaxed.forEach_copy1D_ulong(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed ulong: ", 1);
+
+ script.forEach_copy2D_ulong(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch ulong: ", 1);
+ scriptRelaxed.forEach_copy2D_ulong(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed ulong: ", 1);
+
+ script.forEach_copy3D_ulong(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch ulong: ", 1);
+ scriptRelaxed.forEach_copy3D_ulong(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed ulong: ", 1);
+ }
+
+ public void testGetSet_ulong2() {
+ testSetup(Element.U64_2(mRS));
+ long tmp[] = randomLongArray(gCount);
+ long tmp2[] = new long[gCount];
+ script.forEach_copy1D_ulong2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch ulong2: ", 2);
+ scriptRelaxed.forEach_copy1D_ulong2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed ulong2: ", 2);
+
+ script.forEach_copy2D_ulong2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch ulong2: ", 2);
+ scriptRelaxed.forEach_copy2D_ulong2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed ulong2: ", 2);
+
+ script.forEach_copy3D_ulong2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch ulong2: ", 2);
+ scriptRelaxed.forEach_copy3D_ulong2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed ulong2: ", 2);
+ }
+
+ public void testGetSet_ulong3() {
+ testSetup(Element.U64_3(mRS));
+ long tmp[] = randomLongArray(gCount);
+ long tmp2[] = new long[gCount];
+ script.forEach_copy1D_ulong3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch ulong3: ", 3);
+ scriptRelaxed.forEach_copy1D_ulong3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed ulong3: ", 3);
+
+ script.forEach_copy2D_ulong3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch ulong3: ", 3);
+ scriptRelaxed.forEach_copy2D_ulong3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed ulong3: ", 3);
+
+ script.forEach_copy3D_ulong3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch ulong3: ", 3);
+ scriptRelaxed.forEach_copy3D_ulong3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed ulong3: ", 3);
+ }
+
+ public void testGetSet_ulong4() {
+ testSetup(Element.U64_4(mRS));
+ long tmp[] = randomLongArray(gCount);
+ long tmp2[] = new long[gCount];
+ script.forEach_copy1D_ulong4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch ulong4: ", 4);
+ scriptRelaxed.forEach_copy1D_ulong4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed ulong4: ", 4);
+
+ script.forEach_copy2D_ulong4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch ulong4: ", 4);
+ scriptRelaxed.forEach_copy2D_ulong4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed ulong4: ", 4);
+
+ script.forEach_copy3D_ulong4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch ulong4: ", 4);
+ scriptRelaxed.forEach_copy3D_ulong4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed ulong4: ", 4);
+ }
+
+
+
+
+ public void testGetSet_float() {
+ testSetup(Element.F32(mRS));
+ float tmp[] = randomFloatArray(gCount);
+ float tmp2[] = new float[gCount];
+ script.forEach_copy1D_float(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch float: ", 1);
+ scriptRelaxed.forEach_copy1D_float(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed float: ", 1);
+
+ script.forEach_copy2D_float(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch float: ", 1);
+ scriptRelaxed.forEach_copy2D_float(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed float: ", 1);
+
+ script.forEach_copy3D_float(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch float: ", 1);
+ scriptRelaxed.forEach_copy3D_float(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed float: ", 1);
+ }
+
+ public void testGetSet_float2() {
+ testSetup(Element.F32_2(mRS));
+ float tmp[] = randomFloatArray(gCount);
+ float tmp2[] = new float[gCount];
+ script.forEach_copy1D_float2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch float2: ", 2);
+ scriptRelaxed.forEach_copy1D_float2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed float2: ", 2);
+
+ script.forEach_copy2D_float2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch float2: ", 2);
+ scriptRelaxed.forEach_copy2D_float2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed float2: ", 2);
+
+ script.forEach_copy3D_float2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch float2: ", 2);
+ scriptRelaxed.forEach_copy3D_float2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed float2: ", 2);
+ }
+
+ public void testGetSet_float3() {
+ testSetup(Element.F32_3(mRS));
+ float tmp[] = randomFloatArray(gCount);
+ float tmp2[] = new float[gCount];
+ script.forEach_copy1D_float3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch float3: ", 3);
+ scriptRelaxed.forEach_copy1D_float3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed float3: ", 3);
+
+ script.forEach_copy2D_float3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch float3: ", 3);
+ scriptRelaxed.forEach_copy2D_float3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed float3: ", 3);
+
+ script.forEach_copy3D_float3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch float3: ", 3);
+ scriptRelaxed.forEach_copy3D_float3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed float3: ", 3);
+ }
+
+ public void testGetSet_float4() {
+ testSetup(Element.F32_4(mRS));
+ float tmp[] = randomFloatArray(gCount);
+ float tmp2[] = new float[gCount];
+ script.forEach_copy1D_float4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch float4: ", 4);
+ scriptRelaxed.forEach_copy1D_float4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed float4: ", 4);
+
+ script.forEach_copy2D_float4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch float4: ", 4);
+ scriptRelaxed.forEach_copy2D_float4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed float4: ", 4);
+
+ script.forEach_copy3D_float4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch float4: ", 4);
+ scriptRelaxed.forEach_copy3D_float4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed float4: ", 4);
+ }
+
+
+ public void testGetSet_double() {
+ testSetup(Element.F64(mRS));
+ double tmp[] = randomDoubleArray(gCount);
+ double tmp2[] = new double[gCount];
+ script.forEach_copy1D_double(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch double: ", 1);
+ scriptRelaxed.forEach_copy1D_double(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed double: ", 1);
+
+ script.forEach_copy2D_double(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch double: ", 1);
+ scriptRelaxed.forEach_copy2D_double(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed double: ", 1);
+
+ script.forEach_copy3D_double(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch double: ", 1);
+ scriptRelaxed.forEach_copy3D_double(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed double: ", 1);
+ }
+
+ public void testGetSet_double2() {
+ testSetup(Element.F64_2(mRS));
+ double tmp[] = randomDoubleArray(gCount);
+ double tmp2[] = new double[gCount];
+ script.forEach_copy1D_double2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch double2: ", 2);
+ scriptRelaxed.forEach_copy1D_double2(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed double2: ", 2);
+
+ script.forEach_copy2D_double2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch double2: ", 2);
+ scriptRelaxed.forEach_copy2D_double2(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed double2: ", 2);
+
+ script.forEach_copy3D_double2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch double2: ", 2);
+ scriptRelaxed.forEach_copy3D_double2(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed double2: ", 2);
+ }
+
+ public void testGetSet_double3() {
+ testSetup(Element.F64_3(mRS));
+ double tmp[] = randomDoubleArray(gCount);
+ double tmp2[] = new double[gCount];
+ script.forEach_copy1D_double3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch double3: ", 3);
+ scriptRelaxed.forEach_copy1D_double3(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed double3: ", 3);
+
+ script.forEach_copy2D_double3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch double3: ", 3);
+ scriptRelaxed.forEach_copy2D_double3(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed double3: ", 3);
+
+ script.forEach_copy3D_double3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch double3: ", 3);
+ scriptRelaxed.forEach_copy3D_double3(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed double3: ", 3);
+ }
+
+ public void testGetSet_double4() {
+ testSetup(Element.F64_4(mRS));
+ double tmp[] = randomDoubleArray(gCount);
+ double tmp2[] = new double[gCount];
+ script.forEach_copy1D_double4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch double4: ", 4);
+ scriptRelaxed.forEach_copy1D_double4(walkAlloc);
+ verify(tmp, tmp2, out1DAlloc, "Data mismatch relaxed double4: ", 4);
+
+ script.forEach_copy2D_double4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch double4: ", 4);
+ scriptRelaxed.forEach_copy2D_double4(walkAlloc);
+ verify(tmp, tmp2, out2DAlloc, "Data mismatch relaxed double4: ", 4);
+
+ script.forEach_copy3D_double4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch double4: ", 4);
+ scriptRelaxed.forEach_copy3D_double4(walkAlloc);
+ verify(tmp, tmp2, out3DAlloc, "Data mismatch relaxed double4: ", 4);
+ }
+
+
+}
+
diff --git a/tests/tests/renderscript/src/android/renderscript/cts/getset.rs b/tests/tests/renderscript/src/android/renderscript/cts/getset.rs
new file mode 100644
index 0000000..4a8fa7f
--- /dev/null
+++ b/tests/tests/renderscript/src/android/renderscript/cts/getset.rs
@@ -0,0 +1,143 @@
+ /*
+ * Copyright (C) 2014 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.
+ */
+
+#pragma version(1)
+#pragma rs java_package_name(android.renderscript.cts)
+
+rs_allocation gAlloc1DIn;
+rs_allocation gAlloc1DOut;
+rs_allocation gAlloc2DIn;
+rs_allocation gAlloc2DOut;
+rs_allocation gAlloc3DIn;
+rs_allocation gAlloc3DOut;
+
+uint gWidth;
+uint gHeight;
+
+
+
+
+#define COPY_1D(ty) \
+ void __attribute__((kernel)) copy1D_##ty(int idx) { \
+ ty i = rsGetElementAt_##ty(gAlloc1DIn, idx); \
+ rsSetElementAt_##ty(gAlloc1DOut, i, idx); \
+ } \
+ void __attribute__((kernel)) copy1D_##ty##2(int idx) { \
+ ty##2 i = rsGetElementAt_##ty##2(gAlloc1DIn, idx); \
+ rsSetElementAt_##ty##2(gAlloc1DOut, i, idx); \
+ } \
+ void __attribute__((kernel)) copy1D_##ty##3(int idx) { \
+ ty##3 i = rsGetElementAt_##ty##3(gAlloc1DIn, idx); \
+ rsSetElementAt_##ty##3(gAlloc1DOut, i, idx); \
+ } \
+ void __attribute__((kernel)) copy1D_##ty##4(int idx) { \
+ ty##4 i = rsGetElementAt_##ty##4(gAlloc1DIn, idx); \
+ rsSetElementAt_##ty##4(gAlloc1DOut, i, idx); \
+ }
+
+COPY_1D(char)
+COPY_1D(uchar)
+COPY_1D(short)
+COPY_1D(ushort)
+COPY_1D(int)
+COPY_1D(uint)
+COPY_1D(long)
+COPY_1D(ulong)
+COPY_1D(float)
+COPY_1D(double)
+
+
+
+#define COPY_2D(ty) \
+ void __attribute__((kernel)) copy2D_##ty(int idx) { \
+ uint x = idx % gWidth; \
+ uint y = idx / gWidth; \
+ ty i = rsGetElementAt_##ty(gAlloc2DIn, x, y); \
+ rsSetElementAt_##ty(gAlloc2DOut, i, x, y); \
+ } \
+ void __attribute__((kernel)) copy2D_##ty##2(int idx) { \
+ uint x = idx % gWidth; \
+ uint y = idx / gWidth; \
+ ty##2 i = rsGetElementAt_##ty##2(gAlloc2DIn, x, y); \
+ rsSetElementAt_##ty##2(gAlloc2DOut, i, x, y); \
+ } \
+ void __attribute__((kernel)) copy2D_##ty##3(int idx) { \
+ uint x = idx % gWidth; \
+ uint y = idx / gWidth; \
+ ty##3 i = rsGetElementAt_##ty##3(gAlloc2DIn, x, y); \
+ rsSetElementAt_##ty##3(gAlloc2DOut, i, x, y); \
+ } \
+ void __attribute__((kernel)) copy2D_##ty##4(int idx) { \
+ uint x = idx % gWidth; \
+ uint y = idx / gWidth; \
+ ty##4 i = rsGetElementAt_##ty##4(gAlloc2DIn, x, y); \
+ rsSetElementAt_##ty##4(gAlloc2DOut, i, x, y); \
+ }
+
+COPY_2D(char)
+COPY_2D(uchar)
+COPY_2D(short)
+COPY_2D(ushort)
+COPY_2D(int)
+COPY_2D(uint)
+COPY_2D(long)
+COPY_2D(ulong)
+COPY_2D(float)
+COPY_2D(double)
+
+
+
+#define COPY_3D(ty) \
+ void __attribute__((kernel)) copy3D_##ty(int idx) { \
+ uint x = idx % gWidth; \
+ uint y = (idx / gWidth) % gHeight; \
+ uint z = idx / (gWidth * gHeight); \
+ ty i = rsGetElementAt_##ty(gAlloc3DIn, x, y, z); \
+ rsSetElementAt_##ty(gAlloc3DOut, i, x, y, z); \
+ } \
+ void __attribute__((kernel)) copy3D_##ty##2(int idx) { \
+ uint x = idx % gWidth; \
+ uint y = (idx / gWidth) % gHeight; \
+ uint z = idx / (gWidth * gHeight); \
+ ty##2 i = rsGetElementAt_##ty##2(gAlloc3DIn, x, y, z); \
+ rsSetElementAt_##ty##2(gAlloc3DOut, i, x, y, z); \
+ } \
+ void __attribute__((kernel)) copy3D_##ty##3(int idx) { \
+ uint x = idx % gWidth; \
+ uint y = (idx / gWidth) % gHeight; \
+ uint z = idx / (gWidth * gHeight); \
+ ty##3 i = rsGetElementAt_##ty##3(gAlloc3DIn, x, y, z); \
+ rsSetElementAt_##ty##3(gAlloc3DOut, i, x, y, z); \
+ } \
+ void __attribute__((kernel)) copy3D_##ty##4(int idx) { \
+ uint x = idx % gWidth; \
+ uint y = (idx / gWidth) % gHeight; \
+ uint z = idx / (gWidth * gHeight); \
+ ty##4 i = rsGetElementAt_##ty##4(gAlloc3DIn, x, y, z); \
+ rsSetElementAt_##ty##4(gAlloc3DOut, i, x, y, z); \
+ }
+
+COPY_3D(char)
+COPY_3D(uchar)
+COPY_3D(short)
+COPY_3D(ushort)
+COPY_3D(int)
+COPY_3D(uint)
+COPY_3D(long)
+COPY_3D(ulong)
+COPY_3D(float)
+COPY_3D(double)
+
diff --git a/tests/src/android/os/cts/TaggedPointer.java b/tests/tests/renderscript/src/android/renderscript/cts/getset_relaxed.rs
similarity index 77%
copy from tests/src/android/os/cts/TaggedPointer.java
copy to tests/tests/renderscript/src/android/renderscript/cts/getset_relaxed.rs
index 16e76c9..6b62faf 100644
--- a/tests/src/android/os/cts/TaggedPointer.java
+++ b/tests/tests/renderscript/src/android/renderscript/cts/getset_relaxed.rs
@@ -1,4 +1,4 @@
-/*
+ /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,13 +14,7 @@
* limitations under the License.
*/
-package android.os.cts;
+#pragma rs_fp_relaxed
-public class TaggedPointer {
+#include "getset.rs"
- static {
- System.loadLibrary("cts_jni");
- }
-
- public static native boolean hasTaggedPointer();
-}
diff --git a/tests/tests/rscpp/librscpptest/setelementat.rs b/tests/tests/rscpp/librscpptest/setelementat.rs
index 1251ec1..5a84552 100644
--- a/tests/tests/rscpp/librscpptest/setelementat.rs
+++ b/tests/tests/rscpp/librscpptest/setelementat.rs
@@ -1,5 +1,5 @@
#pragma version(1)
-#pragma rs java_package_name(com.android.cts.stub)
+#pragma rs java_package_name(com.android.cts.rscpp)
#pragma rs_fp_relaxed
int memset_toValue = 0;
diff --git a/tests/tests/security/Android.mk b/tests/tests/security/Android.mk
index 032bec3..6a7833d 100644
--- a/tests/tests/security/Android.mk
+++ b/tests/tests/security/Android.mk
@@ -31,6 +31,22 @@
LOCAL_SDK_VERSION := current
+intermediates.COMMON := $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME),,COMMON)
+
+sepolicy_asset_dir := $(intermediates.COMMON)/assets
+
+LOCAL_ASSET_DIR := $(sepolicy_asset_dir)
+
include $(BUILD_CTS_PACKAGE)
+selinux_policy.xml := $(sepolicy_asset_dir)/selinux_policy.xml
+selinux_policy_parser := packages/experimental/SELinux/CTS/src/gen_SELinux_CTS.py
+general_sepolicy_policy.conf := $(call intermediates-dir-for,ETC,general_sepolicy.conf)/general_sepolicy.conf
+$(selinux_policy.xml): PRIVATE_POLICY_PARSER := $(selinux_policy_parser)
+$(selinux_policy.xml): $(general_sepolicy_policy.conf) $(selinux_policy_parser)
+ mkdir -p $(dir $@)
+ $(PRIVATE_POLICY_PARSER) $< $@ neverallow_only=t
+
+$(R_file_stamp): $(selinux_policy.xml)
+
include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/security/assets/selinux_policy.xml b/tests/tests/security/assets/selinux_policy.xml
deleted file mode 100644
index f7e816a..0000000
--- a/tests/tests/security/assets/selinux_policy.xml
+++ /dev/null
@@ -1,1733 +0,0 @@
-<?xml version="1.0" ?>
-<SELinux_AVC_Rules>
- <avc_rule name="1" type="neverallow">
- <type type="source">shell</type>
- <type type="source">nfc</type>
- <type type="source">platform_app</type>
- <type type="source">bluetooth</type>
- <type type="source">radio</type>
- <type type="source">isolated_app</type>
- <type type="source">untrusted_app</type>
- <type type="source">media_app</type>
- <type type="source">system_app</type>
- <type type="source">release_app</type>
- <type type="source">shared_app</type>
- <type type="target">kernel</type>
- <obj_class name="security">
- <permission>load_policy</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="2" type="neverallow">
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">runas</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">nfc</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">shared_app</type>
- <type type="target">audio_data_file</type>
- <type type="target">sysfs_nfc_power_writable</type>
- <type type="target">ion_device</type>
- <type type="target">debuggerd</type>
- <type type="target">netd</type>
- <type type="target">system_server_tmpfs</type>
- <type type="target">lmkd</type>
- <type type="target">uhid_device</type>
- <type type="target">init_shell</type>
- <type type="target">radio</type>
- <type type="target">zygote_socket</type>
- <type type="target">system_wpa_socket</type>
- <type type="target">sockfs</type>
- <type type="target">selinuxfs</type>
- <type type="target">dumpstate_socket</type>
- <type type="target">untrusted_app_devpts</type>
- <type type="target">shell_prop</type>
- <type type="target">property_socket</type>
- <type type="target">runas</type>
- <type type="target">debuggerd_exec</type>
- <type type="target">mqueue</type>
- <type type="target">shell_data_file</type>
- <type type="target">drmserver_tmpfs</type>
- <type type="target">debuggerd_tmpfs</type>
- <type type="target">init</type>
- <type type="target">netif</type>
- <type type="target">device</type>
- <type type="target">apk_tmp_file</type>
- <type type="target">logd</type>
- <type type="target">servicemanager</type>
- <type type="target">gpsd_tmpfs</type>
- <type type="target">bluetooth_socket</type>
- <type type="target">adb_keys_file</type>
- <type type="target">sdcardd_exec</type>
- <type type="target">system_app_tmpfs</type>
- <type type="target">mediaserver_exec</type>
- <type type="target">ppp_exec</type>
- <type type="target">media_rw_data_file</type>
- <type type="target">clatd_exec</type>
- <type type="target">ueventd</type>
- <type type="target">labeledfs</type>
- <type type="target">asec_image_file</type>
- <type type="target">camera_device</type>
- <type type="target">efs_file</type>
- <type type="target">media_app</type>
- <type type="target">tmpfs</type>
- <type type="target">bluetooth_prop</type>
- <type type="target">logdr_socket</type>
- <type type="target">nfc</type>
- <type type="target">zygote_tmpfs</type>
- <type type="target">cache_backup_file</type>
- <type type="target">drmserver_socket</type>
- <type type="target">logd_exec</type>
- <type type="target">nfc_tmpfs</type>
- <type type="target">zygote</type>
- <type type="target">hostapd</type>
- <type type="target">tee_data_file</type>
- <type type="target">lmkd_socket</type>
- <type type="target">zoneinfo_data_file</type>
- <type type="target">cgroup</type>
- <type type="target">platform_app</type>
- <type type="target">release_app</type>
- <type type="target">qtaguid_device</type>
- <type type="target">surfaceflinger_tmpfs</type>
- <type type="target">shm</type>
- <type type="target">hci_attach_tmpfs</type>
- <type type="target">rild_exec</type>
- <type type="target">kernel</type>
- <type type="target">system_ndebug_socket</type>
- <type type="target">hci_attach_dev</type>
- <type type="target">cpuctl_device</type>
- <type type="target">iio_device</type>
- <type type="target">dhcp</type>
- <type type="target">audio_device</type>
- <type type="target">bootanim_exec</type>
- <type type="target">tee</type>
- <type type="target">wpa_exec</type>
- <type type="target">bluetooth</type>
- <type type="target">sysfs_lowmemorykiller</type>
- <type type="target">mdnsd_exec</type>
- <type type="target">console_device</type>
- <type type="target">rild</type>
- <type type="target">hw_random_device</type>
- <type type="target">radio_prop</type>
- <type type="target">wallpaper_file</type>
- <type type="target">surfaceflinger_exec</type>
- <type type="target">audio_prop</type>
- <type type="target">port</type>
- <type type="target">gps_device</type>
- <type type="target">vcs_device</type>
- <type type="target">alarm_device</type>
- <type type="target">keystore_tmpfs</type>
- <type type="target">logd_socket</type>
- <type type="target">inputflinger_exec</type>
- <type type="target">gpu_device</type>
- <type type="target">unlabeled</type>
- <type type="target">racoon_exec</type>
- <type type="target">init_tmpfs</type>
- <type type="target">binder_device</type>
- <type type="target">servicemanager_tmpfs</type>
- <type type="target">sysfs_wake_lock</type>
- <type type="target">system_app</type>
- <type type="target">vold_exec</type>
- <type type="target">powerctl_prop</type>
- <type type="target">proc</type>
- <type type="target">tee_device</type>
- <type type="target">su_exec</type>
- <type type="target">usermodehelper</type>
- <type type="target">ppp_device</type>
- <type type="target">watchdog_device</type>
- <type type="target">netd_tmpfs</type>
- <type type="target">debugfs</type>
- <type type="target">wpa_socket</type>
- <type type="target">rpmsg_device</type>
- <type type="target">anr_data_file</type>
- <type type="target">lmkd_tmpfs</type>
- <type type="target">mdnsd_tmpfs</type>
- <type type="target">logd_tmpfs</type>
- <type type="target">proc_bluetooth_writable</type>
- <type type="target">dhcp_exec</type>
- <type type="target">gpsd</type>
- <type type="target">log_device</type>
- <type type="target">mediaserver_tmpfs</type>
- <type type="target">security_prop</type>
- <type type="target">vold_tmpfs</type>
- <type type="target">system_server</type>
- <type type="target">runas_exec</type>
- <type type="target">adbd_socket</type>
- <type type="target">radio_data_file</type>
- <type type="target">tee_exec</type>
- <type type="target">backup_data_file</type>
- <type type="target">full_device</type>
- <type type="target">kmsg_device</type>
- <type type="target">ram_device</type>
- <type type="target">inotify</type>
- <type type="target">loop_device</type>
- <type type="target">mtd_device</type>
- <type type="target">random_device</type>
- <type type="target">apk_private_tmp_file</type>
- <type type="target">installd_socket</type>
- <type type="target">camera_data_file</type>
- <type type="target">uncrypt</type>
- <type type="target">asec_public_file</type>
- <type type="target">mediaserver</type>
- <type type="target">graphics_device</type>
- <type type="target">dumpstate_tmpfs</type>
- <type type="target">usb_device</type>
- <type type="target">vold</type>
- <type type="target">drm_data_file</type>
- <type type="target">sdcard_external</type>
- <type type="target">gps_control</type>
- <type type="target">mdns_socket</type>
- <type type="target">logd_debug</type>
- <type type="target">rild_debug_socket</type>
- <type type="target">mtp_tmpfs</type>
- <type type="target">release_app_tmpfs</type>
- <type type="target">root_block_device</type>
- <type type="target">dnsmasq</type>
- <type type="target">sdcard_internal</type>
- <type type="target">dm_device</type>
- <type type="target">download_file</type>
- <type type="target">inputflinger_tmpfs</type>
- <type type="target">netd_socket</type>
- <type type="target">racoon_tmpfs</type>
- <type type="target">sensors_device</type>
- <type type="target">hostapd_exec</type>
- <type type="target">watchdogd</type>
- <type type="target">system_file</type>
- <type type="target">pipefs</type>
- <type type="target">fscklogs</type>
- <type type="target">rild_prop</type>
- <type type="target">hci_attach_exec</type>
- <type type="target">gpsd_exec</type>
- <type type="target">bootanim_tmpfs</type>
- <type type="target">servicemanager_exec</type>
- <type type="target">proc_net</type>
- <type type="target">shell_exec</type>
- <type type="target">null_device</type>
- <type type="target">debug_prop</type>
- <type type="target">serial_device</type>
- <type type="target">bluetooth_tmpfs</type>
- <type type="target">sysfs_writable</type>
- <type type="target">devpts</type>
- <type type="target">wpa_tmpfs</type>
- <type type="target">racoon</type>
- <type type="target">shell</type>
- <type type="target">video_device</type>
- <type type="target">racoon_socket</type>
- <type type="target">usbaccessory_device</type>
- <type type="target">dumpstate</type>
- <type type="target">adbd</type>
- <type type="target">bootanim</type>
- <type type="target">owntty_device</type>
- <type type="target">untrusted_app</type>
- <type type="target">sysfs_bluetooth_writable</type>
- <type type="target">mtp_device</type>
- <type type="target">vold_prop</type>
- <type type="target">ctl_default_prop</type>
- <type type="target">vpn_data_file</type>
- <type type="target">dnsmasq_exec</type>
- <type type="target">socket_device</type>
- <type type="target">keystore_data_file</type>
- <type type="target">installd_tmpfs</type>
- <type type="target">sysfs_devices_system_cpu</type>
- <type type="target">drmserver_exec</type>
- <type type="target">proc_security</type>
- <type type="target">sysfs</type>
- <type type="target">properties_device</type>
- <type type="target">block_device</type>
- <type type="target">gps_data_file</type>
- <type type="target">mtp</type>
- <type type="target">inputflinger</type>
- <type type="target">surfaceflinger</type>
- <type type="target">systemkeys_data_file</type>
- <type type="target">cache_file</type>
- <type type="target">dalvikcache_data_file</type>
- <type type="target">mdnsd</type>
- <type type="target">mdnsd_socket</type>
- <type type="target">lmkd_exec</type>
- <type type="target">netd_exec</type>
- <type type="target">nfc_device</type>
- <type type="target">kmem_device</type>
- <type type="target">ashmem_device</type>
- <type type="target">sdcardd</type>
- <type type="target">hci_attach</type>
- <type type="target">dnsproxyd_socket</type>
- <type type="target">wifi_data_file</type>
- <type type="target">gps_socket</type>
- <type type="target">fuse_device</type>
- <type type="target">dhcp_tmpfs</type>
- <type type="target">mtp_exec</type>
- <type type="target">nfc_data_file</type>
- <type type="target">tee_tmpfs</type>
- <type type="target">default_prop</type>
- <type type="target">input_device</type>
- <type type="target">dumpstate_exec</type>
- <type type="target">drmserver</type>
- <type type="target">logdw_socket</type>
- <type type="target">uncrypt_tmpfs</type>
- <type type="target">rild_tmpfs</type>
- <type type="target">zygote_exec</type>
- <type type="target">keystore</type>
- <type type="target">radio_tmpfs</type>
- <type type="target">clatd</type>
- <type type="target">zero_device</type>
- <type type="target">recovery</type>
- <type type="target">ctl_dumpstate_prop</type>
- <type type="target">adb_device</type>
- <type type="target">ppp</type>
- <type type="target">rild_socket</type>
- <type type="target">ptmx_device</type>
- <type type="target">apk_private_data_file</type>
- <type type="target">tun_device</type>
- <type type="target">uncrypt_exec</type>
- <type type="target">media_data_file</type>
- <type type="target">media_app_tmpfs</type>
- <type type="target">untrusted_app_tmpfs</type>
- <type type="target">ctl_rildaemon_prop</type>
- <type type="target">healthd</type>
- <type type="target">node</type>
- <type type="target">isolated_app_tmpfs</type>
- <type type="target">radio_device</type>
- <type type="target">urandom_device</type>
- <type type="target">tombstone_data_file</type>
- <type type="target">shared_app_tmpfs</type>
- <type type="target">security_file</type>
- <type type="target">system_data_file</type>
- <type type="target">qtaguid_proc</type>
- <type type="target">tty_device</type>
- <type type="target">sdcardd_tmpfs</type>
- <type type="target">isolated_app</type>
- <type type="target">ueventd_tmpfs</type>
- <type type="target">installd_exec</type>
- <type type="target">system_prop</type>
- <type type="target">platform_app_tmpfs</type>
- <type type="target">wpa</type>
- <type type="target">rootfs</type>
- <type type="target">app_data_file</type>
- <type type="target">apk_data_file</type>
- <type type="target">dhcp_data_file</type>
- <type type="target">asec_apk_file</type>
- <type type="target">platform_app_data_file</type>
- <type type="target">keystore_exec</type>
- <type type="target">bluetooth_data_file</type>
- <type type="target">klog_device</type>
- <type type="target">debuggerd_prop</type>
- <type type="target">vold_socket</type>
- <type type="target">bluetooth_efs_file</type>
- <type type="target">installd</type>
- <type type="target">shell_tmpfs</type>
- <type type="target">shared_app</type>
- <obj_class name="fifo_file">
- <permission>relabelto</permission>
- </obj_class>
- <obj_class name="chr_file">
- <permission>relabelto</permission>
- </obj_class>
- <obj_class name="file">
- <permission>relabelto</permission>
- </obj_class>
- <obj_class name="sock_file">
- <permission>relabelto</permission>
- </obj_class>
- <obj_class name="blk_file">
- <permission>relabelto</permission>
- </obj_class>
- <obj_class name="lnk_file">
- <permission>relabelto</permission>
- </obj_class>
- <obj_class name="dir">
- <permission>relabelto</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="3" type="neverallow">
- <type type="source">kernel</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">init</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">self</type>
- <obj_class name="capability">
- <permission>sys_ptrace</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="4" type="neverallow">
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">runas</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">untrusted_app</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">self</type>
- <obj_class name="capability">
- <permission>sys_rawio</permission>
- <permission>mknod</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="5" type="neverallow">
- <type type="source">kernel</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">vold</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">init</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">self</type>
- <obj_class name="capability2">
- <permission>mac_override</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="6" type="neverallow">
- <type type="source">kernel</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">vold</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">runas</type>
- <type type="source">init</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">self</type>
- <obj_class name="capability2">
- <permission>mac_admin</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="7" type="neverallow">
- <type type="source">kernel</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">vold</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">kernel</type>
- <obj_class name="security">
- <permission>load_policy</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="8" type="neverallow">
- <type type="source">vold</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">init</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">kernel</type>
- <obj_class name="security">
- <permission>setenforce</permission>
- <permission>setcheckreqprot</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="9" type="neverallow">
- <type type="source">kernel</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">vold</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">init</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">system_server_tmpfs</type>
- <type type="target">logdr_socket</type>
- <type type="target">lmkd_socket</type>
- <type type="target">system_wpa_socket</type>
- <type type="target">ueventd_tmpfs</type>
- <type type="target">dumpstate_socket</type>
- <type type="target">wpa_tmpfs</type>
- <type type="target">property_socket</type>
- <type type="target">shell_data_file</type>
- <type type="target">debuggerd_tmpfs</type>
- <type type="target">bootanim_tmpfs</type>
- <type type="target">apk_tmp_file</type>
- <type type="target">gpsd_tmpfs</type>
- <type type="target">bluetooth_socket</type>
- <type type="target">adb_keys_file</type>
- <type type="target">system_app_tmpfs</type>
- <type type="target">media_rw_data_file</type>
- <type type="target">shared_app_tmpfs</type>
- <type type="target">backup_data_file</type>
- <type type="target">zygote_socket</type>
- <type type="target">tee_data_file</type>
- <type type="target">cache_backup_file</type>
- <type type="target">drmserver_socket</type>
- <type type="target">system_ndebug_socket</type>
- <type type="target">nfc_tmpfs</type>
- <type type="target">zoneinfo_data_file</type>
- <type type="target">radio_data_file</type>
- <type type="target">surfaceflinger_tmpfs</type>
- <type type="target">apk_private_tmp_file</type>
- <type type="target">hci_attach_tmpfs</type>
- <type type="target">rild_debug_socket</type>
- <type type="target">wallpaper_file</type>
- <type type="target">sdcardd_tmpfs</type>
- <type type="target">keystore_tmpfs</type>
- <type type="target">bluetooth_data_file</type>
- <type type="target">init_tmpfs</type>
- <type type="target">servicemanager_tmpfs</type>
- <type type="target">efs_file</type>
- <type type="target">installd_socket</type>
- <type type="target">inputflinger_tmpfs</type>
- <type type="target">netd_tmpfs</type>
- <type type="target">wpa_socket</type>
- <type type="target">anr_data_file</type>
- <type type="target">lmkd_tmpfs</type>
- <type type="target">mdnsd_tmpfs</type>
- <type type="target">logd_tmpfs</type>
- <type type="target">mediaserver_tmpfs</type>
- <type type="target">vold_tmpfs</type>
- <type type="target">dnsproxyd_socket</type>
- <type type="target">adbd_socket</type>
- <type type="target">camera_data_file</type>
- <type type="target">asec_public_file</type>
- <type type="target">dumpstate_tmpfs</type>
- <type type="target">drm_data_file</type>
- <type type="target">gps_control</type>
- <type type="target">logd_debug</type>
- <type type="target">mtp_tmpfs</type>
- <type type="target">release_app_tmpfs</type>
- <type type="target">download_file</type>
- <type type="target">netd_socket</type>
- <type type="target">racoon_tmpfs</type>
- <type type="target">system_file</type>
- <type type="target">asec_image_file</type>
- <type type="target">tombstone_data_file</type>
- <type type="target">racoon_socket</type>
- <type type="target">logd_socket</type>
- <type type="target">untrusted_app_tmpfs</type>
- <type type="target">vpn_data_file</type>
- <type type="target">keystore_data_file</type>
- <type type="target">bluetooth_tmpfs</type>
- <type type="target">drmserver_tmpfs</type>
- <type type="target">gps_data_file</type>
- <type type="target">systemkeys_data_file</type>
- <type type="target">cache_file</type>
- <type type="target">dalvikcache_data_file</type>
- <type type="target">installd_tmpfs</type>
- <type type="target">mdnsd_socket</type>
- <type type="target">mdns_socket</type>
- <type type="target">wifi_data_file</type>
- <type type="target">gps_socket</type>
- <type type="target">dhcp_tmpfs</type>
- <type type="target">nfc_data_file</type>
- <type type="target">tee_tmpfs</type>
- <type type="target">zygote_tmpfs</type>
- <type type="target">uncrypt_tmpfs</type>
- <type type="target">rild_tmpfs</type>
- <type type="target">isolated_app_tmpfs</type>
- <type type="target">radio_tmpfs</type>
- <type type="target">rild_socket</type>
- <type type="target">media_data_file</type>
- <type type="target">media_app_tmpfs</type>
- <type type="target">audio_data_file</type>
- <type type="target">unlabeled</type>
- <type type="target">security_file</type>
- <type type="target">system_data_file</type>
- <type type="target">bluetooth_efs_file</type>
- <type type="target">platform_app_tmpfs</type>
- <type type="target">app_data_file</type>
- <type type="target">dhcp_data_file</type>
- <type type="target">asec_apk_file</type>
- <type type="target">platform_app_data_file</type>
- <type type="target">logdw_socket</type>
- <type type="target">apk_private_data_file</type>
- <type type="target">vold_socket</type>
- <type type="target">apk_data_file</type>
- <type type="target">shell_tmpfs</type>
- <obj_class name="file">
- <permission>entrypoint</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="10" type="neverallow">
- <type type="source">vold</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">kmem_device</type>
- <obj_class name="chr_file">
- <permission>rename</permission>
- <permission>lock</permission>
- <permission>quotaon</permission>
- <permission>execute_no_trans</permission>
- <permission>open</permission>
- <permission>append</permission>
- <permission>create</permission>
- <permission>write</permission>
- <permission>relabelfrom</permission>
- <permission>getattr</permission>
- <permission>entrypoint</permission>
- <permission>read</permission>
- <permission>mounton</permission>
- <permission>ioctl</permission>
- <permission>link</permission>
- <permission>unlink</permission>
- <permission>swapon</permission>
- <permission>execute</permission>
- <permission>setattr</permission>
- <permission>execmod</permission>
- <permission>relabelto</permission>
- <permission>audit_access</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="11" type="neverallow">
- <type type="source">kernel</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">vold</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">init</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">kmem_device</type>
- <obj_class name="chr_file">
- <permission>rename</permission>
- <permission>execute</permission>
- <permission>open</permission>
- <permission>read</permission>
- <permission>lock</permission>
- <permission>audit_access</permission>
- <permission>quotaon</permission>
- <permission>getattr</permission>
- <permission>execute_no_trans</permission>
- <permission>mounton</permission>
- <permission>write</permission>
- <permission>relabelfrom</permission>
- <permission>ioctl</permission>
- <permission>link</permission>
- <permission>entrypoint</permission>
- <permission>swapon</permission>
- <permission>execmod</permission>
- <permission>append</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="12" type="neverallow">
- <type type="source">kernel</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">vold</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">usermodehelper</type>
- <obj_class name="file">
- <permission>write</permission>
- <permission>append</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="13" type="neverallow">
- <type type="source">kernel</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">vold</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">proc_security</type>
- <obj_class name="file">
- <permission>write</permission>
- <permission>append</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="14" type="neverallow">
- <type type="source">kernel</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">vold</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">init</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">init</type>
- <obj_class name="process">
- <permission>ptrace</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="15" type="neverallow">
- <type type="source">kernel</type>
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">vold</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">recovery</type>
- <type type="source">runas</type>
- <type type="source">init</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">init</type>
- <obj_class name="binder">
- <permission>call</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="16" type="neverallow">
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">runas</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">zygote</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">block_device</type>
- <obj_class name="blk_file">
- <permission>read</permission>
- <permission>write</permission>
- <permission>open</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="17" type="neverallow">
- <type type="source">sdcardd</type>
- <type type="source">init_shell</type>
- <type type="source">adbd</type>
- <type type="source">debuggerd</type>
- <type type="source">netd</type>
- <type type="source">tee</type>
- <type type="source">bluetooth</type>
- <type type="source">lmkd</type>
- <type type="source">surfaceflinger</type>
- <type type="source">mdnsd</type>
- <type type="source">radio</type>
- <type type="source">hci_attach</type>
- <type type="source">clatd</type>
- <type type="source">watchdogd</type>
- <type type="source">drmserver</type>
- <type type="source">keystore</type>
- <type type="source">runas</type>
- <type type="source">servicemanager</type>
- <type type="source">dhcp</type>
- <type type="source">shell</type>
- <type type="source">uncrypt</type>
- <type type="source">untrusted_app</type>
- <type type="source">ueventd</type>
- <type type="source">gpsd</type>
- <type type="source">isolated_app</type>
- <type type="source">system_app</type>
- <type type="source">media_app</type>
- <type type="source">system_server</type>
- <type type="source">wpa</type>
- <type type="source">racoon</type>
- <type type="source">dumpstate</type>
- <type type="source">nfc</type>
- <type type="source">shared_app</type>
- <type type="source">hostapd</type>
- <type type="source">platform_app</type>
- <type type="source">mtp</type>
- <type type="source">inputflinger</type>
- <type type="source">logd</type>
- <type type="source">rild</type>
- <type type="source">dnsmasq</type>
- <type type="source">healthd</type>
- <type type="source">mediaserver</type>
- <type type="source">bootanim</type>
- <type type="source">ppp</type>
- <type type="source">release_app</type>
- <type type="source">installd</type>
- <type type="target">sysfs_nfc_power_writable</type>
- <type type="target">sysfs_lowmemorykiller</type>
- <type type="target">selinuxfs</type>
- <type type="target">untrusted_app_devpts</type>
- <type type="target">tmpfs</type>
- <type type="target">sysfs</type>
- <type type="target">sockfs</type>
- <type type="target">proc_net</type>
- <type type="target">sysfs_wake_lock</type>
- <type type="target">rootfs</type>
- <type type="target">proc</type>
- <type type="target">usermodehelper</type>
- <type type="target">devpts</type>
- <type type="target">debugfs</type>
- <type type="target">qtaguid_proc</type>
- <type type="target">sysfs_bluetooth_writable</type>
- <type type="target">labeledfs</type>
- <type type="target">device</type>
- <type type="target">pipefs</type>
- <type type="target">mqueue</type>
- <type type="target">sysfs_devices_system_cpu</type>
- <type type="target">sysfs_writable</type>
- <type type="target">proc_security</type>
- <type type="target">inotify</type>
- <type type="target">proc_bluetooth_writable</type>
- <type type="target">cgroup</type>
- <type type="target">shm</type>
- <obj_class name="filesystem">
- <permission>relabelfrom</permission>
- <permission>relabelto</permission>
- <permission>mount</permission>
- <permission>remount</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="18" type="neverallow">
- <type type="source">logd</type>
- <type type="target">ashmem_device</type>
- <type type="target">fscklogs</type>
- <type type="target">cpuctl_device</type>
- <type type="target">iio_device</type>
- <type type="target">audio_device</type>
- <type type="target">root_block_device</type>
- <type type="target">properties_device</type>
- <type type="target">console_device</type>
- <type type="target">dm_device</type>
- <type type="target">hw_random_device</type>
- <type type="target">sensors_device</type>
- <type type="target">input_device</type>
- <type type="target">full_device</type>
- <type type="target">gps_device</type>
- <type type="target">vcs_device</type>
- <type type="target">alarm_device</type>
- <type type="target">video_device</type>
- <type type="target">gpu_device</type>
- <type type="target">adb_device</type>
- <type type="target">ion_device</type>
- <type type="target">ptmx_device</type>
- <type type="target">binder_device</type>
- <type type="target">null_device</type>
- <type type="target">tun_device</type>
- <type type="target">mtp_device</type>
- <type type="target">rpmsg_device</type>
- <type type="target">fuse_device</type>
- <type type="target">watchdog_device</type>
- <type type="target">radio_device</type>
- <type type="target">urandom_device</type>
- <type type="target">usbaccessory_device</type>
- <type type="target">kmsg_device</type>
- <type type="target">serial_device</type>
- <type type="target">camera_device</type>
- <type type="target">log_device</type>
- <type type="target">owntty_device</type>
- <type type="target">device</type>
- <type type="target">zero_device</type>
- <type type="target">qtaguid_device</type>
- <type type="target">tty_device</type>
- <type type="target">socket_device</type>
- <type type="target">block_device</type>
- <type type="target">mtd_device</type>
- <type type="target">random_device</type>
- <type type="target">uhid_device</type>
- <type type="target">tee_device</type>
- <type type="target">loop_device</type>
- <type type="target">klog_device</type>
- <type type="target">ppp_device</type>
- <type type="target">graphics_device</type>
- <type type="target">nfc_device</type>
- <type type="target">ram_device</type>
- <type type="target">kmem_device</type>
- <type type="target">hci_attach_dev</type>
- <type type="target">usb_device</type>
- <obj_class name="blk_file">
- <permission>read</permission>
- <permission>write</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="19" type="neverallow">
- <type type="source">logd</type>
- <type type="target">kernel</type>
- <type type="target">sdcardd</type>
- <type type="target">init_shell</type>
- <type type="target">adbd</type>
- <type type="target">vold</type>
- <type type="target">debuggerd</type>
- <type type="target">netd</type>
- <type type="target">tee</type>
- <type type="target">bluetooth</type>
- <type type="target">lmkd</type>
- <type type="target">surfaceflinger</type>
- <type type="target">mdnsd</type>
- <type type="target">radio</type>
- <type type="target">hci_attach</type>
- <type type="target">clatd</type>
- <type type="target">watchdogd</type>
- <type type="target">drmserver</type>
- <type type="target">keystore</type>
- <type type="target">recovery</type>
- <type type="target">runas</type>
- <type type="target">init</type>
- <type type="target">servicemanager</type>
- <type type="target">dhcp</type>
- <type type="target">shell</type>
- <type type="target">uncrypt</type>
- <type type="target">untrusted_app</type>
- <type type="target">ueventd</type>
- <type type="target">gpsd</type>
- <type type="target">isolated_app</type>
- <type type="target">system_app</type>
- <type type="target">media_app</type>
- <type type="target">system_server</type>
- <type type="target">wpa</type>
- <type type="target">racoon</type>
- <type type="target">dumpstate</type>
- <type type="target">nfc</type>
- <type type="target">shared_app</type>
- <type type="target">hostapd</type>
- <type type="target">platform_app</type>
- <type type="target">mtp</type>
- <type type="target">inputflinger</type>
- <type type="target">logd</type>
- <type type="target">zygote</type>
- <type type="target">rild</type>
- <type type="target">dnsmasq</type>
- <type type="target">healthd</type>
- <type type="target">mediaserver</type>
- <type type="target">bootanim</type>
- <type type="target">ppp</type>
- <type type="target">release_app</type>
- <type type="target">installd</type>
- <obj_class name="process">
- <permission>ptrace</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="20" type="neverallow">
- <type type="source">logd</type>
- <type type="target">system_file</type>
- <obj_class name="fifo_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="chr_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="sock_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="blk_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="lnk_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="dir">
- <permission>write</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="21" type="neverallow">
- <type type="source">logd</type>
- <type type="target">app_data_file</type>
- <type type="target">system_data_file</type>
- <obj_class name="fifo_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="chr_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="sock_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="blk_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="lnk_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="dir">
- <permission>write</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="22" type="neverallow">
- <type type="source">netd</type>
- <type type="target">ashmem_device</type>
- <type type="target">fscklogs</type>
- <type type="target">cpuctl_device</type>
- <type type="target">iio_device</type>
- <type type="target">audio_device</type>
- <type type="target">root_block_device</type>
- <type type="target">properties_device</type>
- <type type="target">console_device</type>
- <type type="target">dm_device</type>
- <type type="target">hw_random_device</type>
- <type type="target">sensors_device</type>
- <type type="target">input_device</type>
- <type type="target">full_device</type>
- <type type="target">gps_device</type>
- <type type="target">vcs_device</type>
- <type type="target">alarm_device</type>
- <type type="target">video_device</type>
- <type type="target">gpu_device</type>
- <type type="target">adb_device</type>
- <type type="target">ion_device</type>
- <type type="target">ptmx_device</type>
- <type type="target">binder_device</type>
- <type type="target">null_device</type>
- <type type="target">tun_device</type>
- <type type="target">mtp_device</type>
- <type type="target">rpmsg_device</type>
- <type type="target">fuse_device</type>
- <type type="target">watchdog_device</type>
- <type type="target">radio_device</type>
- <type type="target">urandom_device</type>
- <type type="target">usbaccessory_device</type>
- <type type="target">kmsg_device</type>
- <type type="target">serial_device</type>
- <type type="target">camera_device</type>
- <type type="target">log_device</type>
- <type type="target">owntty_device</type>
- <type type="target">device</type>
- <type type="target">zero_device</type>
- <type type="target">qtaguid_device</type>
- <type type="target">tty_device</type>
- <type type="target">socket_device</type>
- <type type="target">block_device</type>
- <type type="target">mtd_device</type>
- <type type="target">random_device</type>
- <type type="target">uhid_device</type>
- <type type="target">tee_device</type>
- <type type="target">loop_device</type>
- <type type="target">klog_device</type>
- <type type="target">ppp_device</type>
- <type type="target">graphics_device</type>
- <type type="target">nfc_device</type>
- <type type="target">ram_device</type>
- <type type="target">kmem_device</type>
- <type type="target">hci_attach_dev</type>
- <type type="target">usb_device</type>
- <obj_class name="blk_file">
- <permission>read</permission>
- <permission>write</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="23" type="neverallow">
- <type type="source">netd</type>
- <type type="target">kernel</type>
- <obj_class name="security">
- <permission>setenforce</permission>
- <permission>setbool</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="24" type="neverallow">
- <type type="source">netd</type>
- <type type="target">kernel</type>
- <obj_class name="security">
- <permission>load_policy</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="25" type="neverallow">
- <type type="source">netd</type>
- <type type="target">kernel</type>
- <type type="target">sdcardd</type>
- <type type="target">init_shell</type>
- <type type="target">adbd</type>
- <type type="target">vold</type>
- <type type="target">debuggerd</type>
- <type type="target">netd</type>
- <type type="target">tee</type>
- <type type="target">bluetooth</type>
- <type type="target">lmkd</type>
- <type type="target">surfaceflinger</type>
- <type type="target">mdnsd</type>
- <type type="target">radio</type>
- <type type="target">hci_attach</type>
- <type type="target">clatd</type>
- <type type="target">watchdogd</type>
- <type type="target">drmserver</type>
- <type type="target">keystore</type>
- <type type="target">recovery</type>
- <type type="target">runas</type>
- <type type="target">init</type>
- <type type="target">servicemanager</type>
- <type type="target">dhcp</type>
- <type type="target">shell</type>
- <type type="target">uncrypt</type>
- <type type="target">untrusted_app</type>
- <type type="target">ueventd</type>
- <type type="target">gpsd</type>
- <type type="target">isolated_app</type>
- <type type="target">system_app</type>
- <type type="target">media_app</type>
- <type type="target">system_server</type>
- <type type="target">wpa</type>
- <type type="target">racoon</type>
- <type type="target">dumpstate</type>
- <type type="target">nfc</type>
- <type type="target">shared_app</type>
- <type type="target">hostapd</type>
- <type type="target">platform_app</type>
- <type type="target">mtp</type>
- <type type="target">inputflinger</type>
- <type type="target">logd</type>
- <type type="target">zygote</type>
- <type type="target">rild</type>
- <type type="target">dnsmasq</type>
- <type type="target">healthd</type>
- <type type="target">mediaserver</type>
- <type type="target">bootanim</type>
- <type type="target">ppp</type>
- <type type="target">release_app</type>
- <type type="target">installd</type>
- <obj_class name="process">
- <permission>ptrace</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="26" type="neverallow">
- <type type="source">netd</type>
- <type type="target">system_file</type>
- <obj_class name="fifo_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="chr_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="sock_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="blk_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="lnk_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="dir">
- <permission>write</permission>
- </obj_class>
- </avc_rule>
- <avc_rule name="27" type="neverallow">
- <type type="source">netd</type>
- <type type="target">app_data_file</type>
- <type type="target">system_data_file</type>
- <obj_class name="fifo_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="chr_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="sock_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="blk_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="lnk_file">
- <permission>write</permission>
- </obj_class>
- <obj_class name="dir">
- <permission>write</permission>
- </obj_class>
- </avc_rule>
-</SELinux_AVC_Rules>
diff --git a/tests/tests/telecomm/AndroidManifest.xml b/tests/tests/telecomm/AndroidManifest.xml
deleted file mode 100644
index 97906c6..0000000
--- a/tests/tests/telecomm/AndroidManifest.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 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.
--->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.cts.telecom">
-
- <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
- <!-- We won't be granted this, but we should at least ask for it (to make sure we don't get it). -->
- <uses-permission android:name="com.android.server.telecom.permission.REGISTER_PROVIDER_OR_SUBSCRIPTION" />
- <application>
- <uses-library android:name="android.test.runner" />
- </application>
-
- <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
- android:targetPackage="com.android.cts.stub"
- android:label="CTS tests of android.telecom">
- <meta-data android:name="listener"
- android:value="com.android.cts.runner.CtsTestRunListener" />
- </instrumentation>
-
-</manifest>
-
diff --git a/tests/tests/telecomm/src/android/telecom/cts/ConnectionTest.java b/tests/tests/telecomm/src/android/telecom/cts/ConnectionTest.java
deleted file mode 100644
index e552733..0000000
--- a/tests/tests/telecomm/src/android/telecom/cts/ConnectionTest.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2014 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.telecom.cts;
-
-import android.telecom.Connection;
-import android.telecom.DisconnectCause;
-import android.test.AndroidTestCase;
-
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-
-public class ConnectionTest extends AndroidTestCase {
- public void testStateCallbacks() {
- final Semaphore lock = new Semaphore(0);
- Connection connection = createConnection(lock);
-
- waitForStateChange(lock);
- assertEquals(Connection.STATE_NEW, connection.getState());
-
- connection.setInitializing();
- waitForStateChange(lock);
- assertEquals(Connection.STATE_INITIALIZING, connection.getState());
-
- connection.setInitialized();
- waitForStateChange(lock);
- assertEquals(Connection.STATE_NEW, connection.getState());
-
- connection.setRinging();
- waitForStateChange(lock);
- assertEquals(Connection.STATE_RINGING, connection.getState());
-
- connection.setDialing();
- waitForStateChange(lock);
- assertEquals(Connection.STATE_DIALING, connection.getState());
-
- connection.setActive();
- waitForStateChange(lock);
- assertEquals(Connection.STATE_ACTIVE, connection.getState());
-
- connection.setOnHold();
- waitForStateChange(lock);
- assertEquals(Connection.STATE_HOLDING, connection.getState());
-
- connection.setDisconnected(
- new DisconnectCause(DisconnectCause.LOCAL, "Test call"));
- waitForStateChange(lock);
- assertEquals(Connection.STATE_DISCONNECTED, connection.getState());
-
- connection.setRinging();
- waitForStateChange(lock);
- assertEquals("Connection should not move out of STATE_DISCONNECTED.",
- Connection.STATE_DISCONNECTED, connection.getState());
- }
-
- public void testFailedState() {
- Connection connection = Connection.createFailedConnection(
- new DisconnectCause(DisconnectCause.LOCAL, "Test call"));
- assertEquals(Connection.STATE_DISCONNECTED, connection.getState());
-
- connection.setRinging();
- assertEquals("Connection should not move out of STATE_DISCONNECTED.",
- Connection.STATE_DISCONNECTED, connection.getState());
- }
-
- public void testCanceledState() {
- Connection connection = Connection.createCanceledConnection();
- assertEquals(Connection.STATE_DISCONNECTED, connection.getState());
-
- connection.setDialing();
- assertEquals("Connection should not move out of STATE_DISCONNECTED",
- Connection.STATE_DISCONNECTED, connection.getState());
- }
-
- private static Connection createConnection(final Semaphore lock) {
- Connection.Listener listener = new Connection.Listener() {
- @Override
- public void onStateChanged(Connection c, int state) {
- lock.release();
- }
- };
-
- Connection connection = new BasicConnection();
- connection.addConnectionListener(listener);
- return connection;
- }
-
- private static void waitForStateChange(Semaphore lock) {
- try {
- lock.tryAcquire(1000, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {
- fail("State transition timed out");
- }
- }
-
- private static final class BasicConnection extends Connection {
- }
-}
diff --git a/tests/tests/telecomm/src/android/telecom/cts/TelecomManagerTest.java b/tests/tests/telecomm/src/android/telecom/cts/TelecomManagerTest.java
deleted file mode 100644
index 8f97d77..0000000
--- a/tests/tests/telecomm/src/android/telecom/cts/TelecomManagerTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2014 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.telecom.cts;
-
-import android.content.ComponentName;
-import android.content.pm.PackageManager;
-import android.net.Uri;
-import android.telecom.PhoneAccount;
-import android.telecom.PhoneAccountHandle;
-import android.telecom.PhoneCapabilities;
-import android.telecom.TelecomManager;
-import android.test.AndroidTestCase;
-import android.util.Log;
-
-import java.util.List;
-
-public class TelecomManagerTest extends AndroidTestCase {
- private static final String TAG = "TelecommManagerTest";
-
- public void testRegisterAccountsBlocked() {
- PackageManager pm = getContext().getPackageManager();
- if (!pm.hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) {
- Log.d(TAG, "Skipping the test because FEATURE_CONNECTION_SERVICE is disabled.");
- return;
- }
-
- PhoneAccount phoneAccount = new PhoneAccount.Builder(
- new PhoneAccountHandle(
- new ComponentName(getContext(), TelecomManagerTest.class),
- "testRegisterAccountsBlocked"),
- "Mock PhoneAccount")
- .setAddress(Uri.parse("tel:6502637643"))
- .setSubscriptionAddress(Uri.parse("tel:650-263-7643"))
- .setCapabilities(PhoneCapabilities.ALL)
- .setIconResId(0)
- .setShortDescription("PhoneAccount used in TelecomManagerTest")
- .build();
-
- TelecomManager tm = TelecomManager.from(getContext());
- List<PhoneAccountHandle> handles = tm.getCallCapablePhoneAccounts();
-
- try {
- tm.registerPhoneAccount(phoneAccount);
- fail("This should have failed (CTS can't get the permission)");
- } catch (SecurityException e) {
- assertEquals(handles, tm.getCallCapablePhoneAccounts());
- }
- }
-}
diff --git a/tests/tests/telephony/Android.mk b/tests/tests/telephony/Android.mk
index 676138d..e15d0d5 100644
--- a/tests/tests/telephony/Android.mk
+++ b/tests/tests/telephony/Android.mk
@@ -30,8 +30,6 @@
LOCAL_PACKAGE_NAME := CtsTelephonyTestCases
-LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
-
# uncomment when b/13250611 is fixed
#LOCAL_SDK_VERSION := current
LOCAL_JAVA_LIBRARIES += android.test.runner
diff --git a/tests/tests/telephony/AndroidManifest.xml b/tests/tests/telephony/AndroidManifest.xml
index 36d1e5e..cd3864e 100644
--- a/tests/tests/telephony/AndroidManifest.xml
+++ b/tests/tests/telephony/AndroidManifest.xml
@@ -18,12 +18,20 @@
package="com.android.cts.telephony">
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+ <uses-permission android:name="android.permission.READ_CONTACTS" />
+ <uses-permission android:name="android.permission.WRITE_CONTACTS" />
+ <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+ <uses-permission android:name="android.permission.SEND_SMS" />
+ <uses-permission android:name="android.permission.RECEIVE_SMS" />
+
<application>
<uses-library android:name="android.test.runner" />
</application>
<instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
- android:targetPackage="com.android.cts.stub"
+ android:targetPackage="com.android.cts.telephony"
android:label="CTS tests of android.telephony">
<meta-data android:name="listener"
android:value="com.android.cts.runner.CtsTestRunListener" />
diff --git a/tests/tests/telephony/src/android/telephony/cts/CellLocationTest.java b/tests/tests/telephony/src/android/telephony/cts/CellLocationTest.java
index 61b97b2..e58d26f 100644
--- a/tests/tests/telephony/src/android/telephony/cts/CellLocationTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/CellLocationTest.java
@@ -18,7 +18,6 @@
import android.content.Context;
import android.os.Looper;
-import android.os.cts.TestThread;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
diff --git a/tests/tests/telephony/src/android/telephony/cts/PhoneStateListenerTest.java b/tests/tests/telephony/src/android/telephony/cts/PhoneStateListenerTest.java
index bfc4c85..b084245 100644
--- a/tests/tests/telephony/src/android/telephony/cts/PhoneStateListenerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/PhoneStateListenerTest.java
@@ -17,7 +17,6 @@
import android.content.Context;
import android.os.Looper;
-import android.os.cts.TestThread;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
diff --git a/tests/tests/telephony/src/android/telephony/cts/SmsUsageMonitorShortCodeTest.java b/tests/tests/telephony/src/android/telephony/cts/SmsUsageMonitorShortCodeTest.java
index fbe65b1..67cdd24 100644
--- a/tests/tests/telephony/src/android/telephony/cts/SmsUsageMonitorShortCodeTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/SmsUsageMonitorShortCodeTest.java
@@ -18,17 +18,18 @@
import android.content.Context;
import android.content.pm.PackageManager;
-import android.test.AndroidTestCase;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import com.android.internal.telephony.SmsUsageMonitor;
/**
* Test cases for SMS short code pattern matching in SmsUsageMonitor.
*/
-public class SmsUsageMonitorShortCodeTest extends AndroidTestCase {
+public class SmsUsageMonitorShortCodeTest extends InstrumentationTestCase {
private PackageManager mPackageManager;
+ private Context mContext;
/** Return value from {@link SmsUsageMonitor#checkDestination} for regular phone numbers. */
static final int CATEGORY_NOT_SHORT_CODE = 0;
@@ -482,17 +483,18 @@
@Override
protected void setUp() throws Exception {
super.setUp();
- mPackageManager = getContext().getPackageManager();
+ mContext = getInstrumentation().getTargetContext();
+ mPackageManager = mContext.getPackageManager();
}
- @SmallTest
+ @UiThreadTest
public void testSmsUsageMonitor() {
if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
// do not test if device does not support telephony (voice or sms)
return;
}
- SmsUsageMonitor monitor = new SmsUsageMonitor(getContext());
+ SmsUsageMonitor monitor = new SmsUsageMonitor(mContext);
for (ShortCodeTest test : sShortCodeTests) {
assertEquals("country: " + test.countryIso + " number: " + test.address,
test.category, monitor.checkDestination(test.address, test.countryIso));
diff --git a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
index 9986e67..803baec 100644
--- a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
@@ -24,7 +24,6 @@
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Looper;
-import android.os.cts.TestThread;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
diff --git a/tests/tests/telephony/src/android/telephony/cts/TestThread.java b/tests/tests/telephony/src/android/telephony/cts/TestThread.java
new file mode 100644
index 0000000..9bf40de
--- /dev/null
+++ b/tests/tests/telephony/src/android/telephony/cts/TestThread.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2009 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.telephony.cts;
+
+/**
+ * Thread class for executing a Runnable containing assertions in a separate thread.
+ * Uncaught exceptions in the Runnable are rethrown in the context of the the thread
+ * calling the <code>runTest()</code> method.
+ */
+public final class TestThread extends Thread {
+ private Throwable mThrowable;
+ private Runnable mTarget;
+
+ public TestThread(Runnable target) {
+ mTarget = target;
+ }
+
+ @Override
+ public final void run() {
+ try {
+ mTarget.run();
+ } catch (Throwable t) {
+ mThrowable = t;
+ }
+ }
+
+ /**
+ * Run the target Runnable object and wait until the test finish or throw
+ * out Exception if test fail.
+ *
+ * @param runTime
+ * @throws Throwable
+ */
+ public void runTest(long runTime) throws Throwable {
+ start();
+ joinAndCheck(runTime);
+ }
+
+ /**
+ * Get the Throwable object which is thrown when test running
+ * @return The Throwable object
+ */
+ public Throwable getThrowable() {
+ return mThrowable;
+ }
+
+ /**
+ * Set the Throwable object which is thrown when test running
+ * @param t The Throwable object
+ */
+ public void setThrowable(Throwable t) {
+ mThrowable = t;
+ }
+
+ /**
+ * Wait for the test thread to complete and throw the stored exception if there is one.
+ *
+ * @param runTime The time to wait for the test thread to complete.
+ * @throws Throwable
+ */
+ public void joinAndCheck(long runTime) throws Throwable {
+ this.join(runTime);
+ if (this.isAlive()) {
+ this.interrupt();
+ this.join(runTime);
+ throw new Exception("Thread did not finish within allotted time.");
+ }
+ checkException();
+ }
+
+ /**
+ * Check whether there is an exception when running Runnable object.
+ * @throws Throwable
+ */
+ public void checkException() throws Throwable {
+ if (mThrowable != null) {
+ throw mThrowable;
+ }
+ }
+}
diff --git a/tests/tests/text/AndroidManifest.xml b/tests/tests/text/AndroidManifest.xml
index 0b31354..f247f82 100644
--- a/tests/tests/text/AndroidManifest.xml
+++ b/tests/tests/text/AndroidManifest.xml
@@ -20,9 +20,8 @@
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
- <application>
- <uses-library android:name="android.test.runner"
- android:maxRecents="1"/>
+ <application android:maxRecents="1">
+ <uses-library android:name="android.test.runner" />
<activity android:name="android.text.cts.EmojiCtsActivity"
android:label="AvailableIntentsActivity">
diff --git a/tests/tests/text/src/android/text/cts/ClipboardManagerTest.java b/tests/tests/text/src/android/text/cts/ClipboardManagerTest.java
index e62e0f8..f0fc0fa 100644
--- a/tests/tests/text/src/android/text/cts/ClipboardManagerTest.java
+++ b/tests/tests/text/src/android/text/cts/ClipboardManagerTest.java
@@ -18,36 +18,45 @@
import android.content.Context;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.text.ClipboardManager;
/**
* Test {@link ClipboardManager}.
*/
-public class ClipboardManagerTest extends AndroidTestCase {
- private ClipboardManager mClipboardManager;
+public class ClipboardManagerTest extends InstrumentationTestCase {
+
+ private Context mContext;
@Override
- protected void setUp() throws Exception {
- super.setUp();
- mClipboardManager = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
+ public void setUp() {
+ mContext = getInstrumentation().getContext();
}
+ @UiThreadTest
public void testAccessText() {
+ ClipboardManager clipboardManager =
+ (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
+
// set the expected value
CharSequence expected = "test";
- mClipboardManager.setText(expected);
- assertEquals(expected, mClipboardManager.getText());
+ clipboardManager.setText(expected);
+ assertEquals(expected, clipboardManager.getText());
}
+ @UiThreadTest
public void testHasText() {
- mClipboardManager.setText("");
- assertFalse(mClipboardManager.hasText());
+ ClipboardManager clipboardManager =
+ (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
- mClipboardManager.setText("test");
- assertTrue(mClipboardManager.hasText());
+ clipboardManager.setText("");
+ assertFalse(clipboardManager.hasText());
- mClipboardManager.setText(null);
- assertFalse(mClipboardManager.hasText());
+ clipboardManager.setText("test");
+ assertTrue(clipboardManager.hasText());
+
+ clipboardManager.setText(null);
+ assertFalse(clipboardManager.hasText());
}
}
diff --git a/tests/tests/text/src/android/text/cts/EmojiTest.java b/tests/tests/text/src/android/text/cts/EmojiTest.java
index 5e2ca93..b753739 100644
--- a/tests/tests/text/src/android/text/cts/EmojiTest.java
+++ b/tests/tests/text/src/android/text/cts/EmojiTest.java
@@ -31,7 +31,7 @@
public class EmojiTest extends ActivityInstrumentationTestCase2<EmojiCtsActivity> {
public EmojiTest() {
- super("com.android.cts.stub", EmojiCtsActivity.class);
+ super("com.android.cts.text", EmojiCtsActivity.class);
}
protected void setUp() throws Exception {
@@ -105,7 +105,7 @@
/**
* Tests EditText handles Emoji
*/
- public void testEmojiEditable() {
+ public void testEmojiEditable() throws Throwable {
int testedCodePoints[] = {
0xAE, // registered mark
0x2764, // heavy black heart
@@ -118,15 +118,21 @@
for (int i = 0; i < testedCodePoints.length; i++) {
origStr = "Test character ";
// cannot reuse CaptureTextView as 2nd setText call throws NullPointerException
- EditText editText = new EditText(getInstrumentation().getContext());
+ final EditText editText = new EditText(getInstrumentation().getContext());
editText.setText(origStr + String.valueOf(Character.toChars(testedCodePoints[i])));
// confirm the emoji is added.
newStr = editText.getText().toString();
assertEquals(newStr.codePointCount(0, newStr.length()), origStr.length() + 1);
- // Delete added character by sending KEYCODE_DEL event
- editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ // Delete added character by sending KEYCODE_DEL event
+ editText.dispatchKeyEvent(
+ new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
+ }
+ });
+ getInstrumentation().waitForIdleSync();
newStr = editText.getText().toString();
assertEquals(newStr.codePointCount(0, newStr.length()), origStr.length() + 1);
diff --git a/tests/tests/text/src/android/text/cts/MyanmarTest.java b/tests/tests/text/src/android/text/cts/MyanmarTest.java
index 60fe608..d59f2b9 100644
--- a/tests/tests/text/src/android/text/cts/MyanmarTest.java
+++ b/tests/tests/text/src/android/text/cts/MyanmarTest.java
@@ -25,7 +25,7 @@
public class MyanmarTest extends ActivityInstrumentationTestCase2<Activity> {
public MyanmarTest() {
- super("com.android.cts.stub", Activity.class);
+ super("com.android.cts.text", Activity.class);
}
protected void setUp() throws Exception {
diff --git a/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java b/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
index 74fab00..10d08d0 100644
--- a/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ArrowKeyMovementMethodTest.java
@@ -56,7 +56,7 @@
private MyMetaKeyKeyListener mMetaListener;
public ArrowKeyMovementMethodTest() {
- super("com.android.cts.stub", CtsActivity.class);
+ super("com.android.cts.text", CtsActivity.class);
}
@Override
diff --git a/tests/tests/text/src/android/text/method/cts/CharacterPickerDialogTest.java b/tests/tests/text/src/android/text/method/cts/CharacterPickerDialogTest.java
index 3c20988..382fc77 100644
--- a/tests/tests/text/src/android/text/method/cts/CharacterPickerDialogTest.java
+++ b/tests/tests/text/src/android/text/method/cts/CharacterPickerDialogTest.java
@@ -21,6 +21,7 @@
import android.content.Context;
import android.os.Bundle;
import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
import android.text.Editable;
import android.text.Selection;
import android.text.method.CharacterPickerDialog;
@@ -34,7 +35,7 @@
private Activity mActivity;
public CharacterPickerDialogTest() {
- super("com.android.cts.stub", CtsActivity.class);
+ super("com.android.cts.text", CtsActivity.class);
}
@Override
@@ -43,6 +44,7 @@
mActivity = getActivity();
}
+ @UiThreadTest
public void testConstructor() {
final CharSequence str = "123456";
final Editable content = Editable.Factory.getInstance().newEditable(str);
@@ -61,6 +63,7 @@
// Do not test. Implementation details.
}
+ @UiThreadTest
public void testOnItemClick() {
final Gallery parent = new Gallery(mActivity);
final CharSequence str = "123456";
@@ -102,6 +105,7 @@
assertFalse(insertPickerDialog.isShowing());
}
+ @UiThreadTest
public void testOnClick() {
final CharSequence str = "123456";
final Editable content = Editable.Factory.getInstance().newEditable(str);
diff --git a/tests/tests/text/src/android/text/method/cts/KeyListenerTestCase.java b/tests/tests/text/src/android/text/method/cts/KeyListenerTestCase.java
index a5a76af..8bb2adf 100644
--- a/tests/tests/text/src/android/text/method/cts/KeyListenerTestCase.java
+++ b/tests/tests/text/src/android/text/method/cts/KeyListenerTestCase.java
@@ -53,7 +53,7 @@
protected TextView mTextView;
public KeyListenerTestCase() {
- super("com.android.cts.stub", KeyListenerCtsActivity.class);
+ super("com.android.cts.text", KeyListenerCtsActivity.class);
}
@Override
diff --git a/tests/tests/text/src/android/text/method/cts/LinkMovementMethodTest.java b/tests/tests/text/src/android/text/method/cts/LinkMovementMethodTest.java
index 8027d49..336921a 100644
--- a/tests/tests/text/src/android/text/method/cts/LinkMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/LinkMovementMethodTest.java
@@ -56,7 +56,7 @@
private MockClickableSpan mClickable1;
public LinkMovementMethodTest() {
- super("com.android.cts.stub", CtsActivity.class);
+ super("com.android.cts.text", CtsActivity.class);
}
@Override
diff --git a/tests/tests/text/src/android/text/method/cts/PasswordTransformationMethodTest.java b/tests/tests/text/src/android/text/method/cts/PasswordTransformationMethodTest.java
index 66e4fc8..4262a31 100644
--- a/tests/tests/text/src/android/text/method/cts/PasswordTransformationMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/PasswordTransformationMethodTest.java
@@ -58,7 +58,7 @@
private CharSequence mTransformedText;
public PasswordTransformationMethodTest() {
- super("com.android.cts.stub", CtsActivity.class);
+ super("com.android.cts.text", CtsActivity.class);
}
@Override
diff --git a/tests/tests/text/src/android/text/method/cts/ReplacementTransformationMethodTest.java b/tests/tests/text/src/android/text/method/cts/ReplacementTransformationMethodTest.java
index 7dabd16..dadce15 100644
--- a/tests/tests/text/src/android/text/method/cts/ReplacementTransformationMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ReplacementTransformationMethodTest.java
@@ -37,7 +37,7 @@
private EditText mEditText;
public ReplacementTransformationMethodTest() {
- super("com.android.cts.stub", CtsActivity.class);
+ super("com.android.cts.text", CtsActivity.class);
}
@Override
diff --git a/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java b/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
index f9a7d0d..c186cde 100644
--- a/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/ScrollingMovementMethodTest.java
@@ -55,7 +55,7 @@
private int mScaledTouchSlop;
public ScrollingMovementMethodTest() {
- super("com.android.cts.stub", CtsActivity.class);
+ super("com.android.cts.text", CtsActivity.class);
}
@Override
diff --git a/tests/tests/text/src/android/text/method/cts/SingleLineTransformationMethodTest.java b/tests/tests/text/src/android/text/method/cts/SingleLineTransformationMethodTest.java
index 89f1026..460ce3d 100644
--- a/tests/tests/text/src/android/text/method/cts/SingleLineTransformationMethodTest.java
+++ b/tests/tests/text/src/android/text/method/cts/SingleLineTransformationMethodTest.java
@@ -28,7 +28,7 @@
public class SingleLineTransformationMethodTest
extends ActivityInstrumentationTestCase2<CtsActivity> {
public SingleLineTransformationMethodTest() {
- super("com.android.cts.stub", CtsActivity.class);
+ super("com.android.cts.text", CtsActivity.class);
}
public void testConstructor() {
diff --git a/tests/tests/text/src/android/text/method/cts/TouchTest.java b/tests/tests/text/src/android/text/method/cts/TouchTest.java
index 2d3d146..343847e 100644
--- a/tests/tests/text/src/android/text/method/cts/TouchTest.java
+++ b/tests/tests/text/src/android/text/method/cts/TouchTest.java
@@ -43,7 +43,7 @@
private boolean mReturnFromTouchEvent;
public TouchTest() {
- super("com.android.cts.stub", CtsActivity.class);
+ super("com.android.cts.text", CtsActivity.class);
}
@Override
diff --git a/tests/tests/text/src/android/text/style/cts/URLSpanTest.java b/tests/tests/text/src/android/text/style/cts/URLSpanTest.java
index 832e48d..7cfe56e 100644
--- a/tests/tests/text/src/android/text/style/cts/URLSpanTest.java
+++ b/tests/tests/text/src/android/text/style/cts/URLSpanTest.java
@@ -33,7 +33,7 @@
private Activity mActivity;
public URLSpanTest() {
- super("com.android.cts.stub", URLSpanCtsActivity.class);
+ super("com.android.cts.text", URLSpanCtsActivity.class);
}
@Override
diff --git a/tests/tests/tv/Android.mk b/tests/tests/tv/Android.mk
index 2ffe166..795b473 100644
--- a/tests/tests/tv/Android.mk
+++ b/tests/tests/tv/Android.mk
@@ -28,8 +28,6 @@
LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner
-LOCAL_INSTRUMENTATION_FOR := CtsTestStubs
-
LOCAL_SDK_VERSION := current
include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/ActivityTestBase.java b/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/ActivityTestBase.java
index c096c5d..9f9aa41 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/ActivityTestBase.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/ActivityTestBase.java
@@ -28,6 +28,7 @@
import android.util.Log;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
/**
@@ -42,6 +43,7 @@
public static final boolean USE_RS = false;
public static final int TEST_WIDTH = 180;
public static final int TEST_HEIGHT = 180; //The minimum height and width of a device
+ public static final int MAX_SCREEN_SHOTS = 100;
private int[] mHardwareArray = new int[TEST_HEIGHT * TEST_WIDTH];
private int[] mSoftwareArray = new int[TEST_HEIGHT * TEST_WIDTH];
@@ -114,7 +116,16 @@
}
public Bitmap takeScreenshot() {
- return getInstrumentation().getUiAutomation().takeScreenshot();
+ getInstrumentation().waitForIdleSync();
+ Bitmap bitmap1 = getInstrumentation().getUiAutomation().takeScreenshot();
+ Bitmap bitmap2;
+ int count = 0;
+ do {
+ bitmap2 = bitmap1;
+ bitmap1 = getInstrumentation().getUiAutomation().takeScreenshot();
+ count++;
+ } while (count < MAX_SCREEN_SHOTS && !Arrays.equals(bitmap2.mBuffer, bitmap1.mBuffer));
+ return bitmap1;
}
/**
diff --git a/tests/tests/view/src/android/view/cts/GestureDetectorTest.java b/tests/tests/view/src/android/view/cts/GestureDetectorTest.java
index 3d8ba05..c568cf1 100644
--- a/tests/tests/view/src/android/view/cts/GestureDetectorTest.java
+++ b/tests/tests/view/src/android/view/cts/GestureDetectorTest.java
@@ -18,7 +18,9 @@
import android.content.Context;
import android.os.Handler;
+import android.os.Looper;
import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
@@ -50,11 +52,13 @@
mActivity.onSingleTapConfirmed = false;
}
+ @UiThreadTest
public void testConstructor() {
- new GestureDetector(mContext, new SimpleOnGestureListener(), new Handler());
+ new GestureDetector(
+ mContext, new SimpleOnGestureListener(), new Handler(Looper.getMainLooper()));
new GestureDetector(mContext, new SimpleOnGestureListener());
- new GestureDetector(new SimpleOnGestureListener(), new Handler());
+ new GestureDetector(new SimpleOnGestureListener(), new Handler(Looper.getMainLooper()));
new GestureDetector(new SimpleOnGestureListener());
try {
diff --git a/tests/tests/view/src/android/view/cts/SurfaceViewTest.java b/tests/tests/view/src/android/view/cts/SurfaceViewTest.java
index d3902bb..a84653d 100644
--- a/tests/tests/view/src/android/view/cts/SurfaceViewTest.java
+++ b/tests/tests/view/src/android/view/cts/SurfaceViewTest.java
@@ -55,6 +55,7 @@
mMockSurfaceView = activity.getSurfaceView();
}
+ @UiThreadTest
public void testConstructor() {
new SurfaceView(mContext);
new SurfaceView(mContext, null);
diff --git a/tests/tests/view/src/android/view/cts/WindowTest.java b/tests/tests/view/src/android/view/cts/WindowTest.java
index 9df13dc..ead4d5b 100644
--- a/tests/tests/view/src/android/view/cts/WindowTest.java
+++ b/tests/tests/view/src/android/view/cts/WindowTest.java
@@ -36,6 +36,7 @@
import android.os.Handler;
import android.os.SystemClock;
import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ActionMode;
@@ -68,6 +69,7 @@
private Context mContext;
private Instrumentation mInstrumentation;
private WindowCtsActivity mActivity;
+ private SurfaceView surfaceView;
private static final int VIEWGROUP_LAYOUT_HEIGHT = 100;
private static final int VIEWGROUP_LAYOUT_WIDTH = 200;
@@ -97,6 +99,7 @@
super.tearDown();
}
+ @UiThreadTest
public void testConstructor() throws Exception {
mWindow = new MockWindow(mContext);
assertSame(mContext, mWindow.getContext());
@@ -652,7 +655,13 @@
* Test setLocalFocus together with injectInputEvent.
*/
public void testSetLocalFocus() throws Throwable {
- final SurfaceView surfaceView = new SurfaceView(mContext);
+ runTestOnUiThread(new Runnable() {
+ public void run() {
+ surfaceView = new SurfaceView(mContext);
+ }
+ });
+ mInstrumentation.waitForIdleSync();
+
final Semaphore waitingSemaphore = new Semaphore(0);
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
@@ -676,6 +685,7 @@
mWindow.setContentView(surfaceView);
}
});
+ mInstrumentation.waitForIdleSync();
assertTrue(waitingSemaphore.tryAcquire(5, TimeUnit.SECONDS));
assertNotNull(mVirtualDisplay);
assertNotNull(mPresentation);
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
index 05f6f00..2430c8c 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
@@ -373,7 +373,7 @@
assertEquals(view, mOnUiThread.getWebView());
// Save the main page request; discard any other requests (e.g. for favicon.ico)
- if (request.getUrl().toString().contains(mainPath)) {
+ if (request.getUrl().getPath().equals(mainPath)) {
assertNull(interceptRequest);
interceptRequest = request;
}
diff --git a/tests/tests/widget/src/android/widget/cts/AbsSpinnerTest.java b/tests/tests/widget/src/android/widget/cts/AbsSpinnerTest.java
index 70b37e6..10e1658 100644
--- a/tests/tests/widget/src/android/widget/cts/AbsSpinnerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AbsSpinnerTest.java
@@ -52,7 +52,7 @@
mContext = getInstrumentation().getTargetContext();
}
-
+ @UiThreadTest
public void testConstructor() {
new Spinner(mContext);
@@ -139,6 +139,7 @@
// There is neither limit in code nor description about it in javadoc.
}
+ @UiThreadTest
public void testRequestLayout() {
AbsSpinner absSpinner = new Spinner(mContext);
absSpinner.layout(0, 0, 200, 300);
@@ -176,6 +177,7 @@
* 1. Should return the position of the item which contains the specified point.
* 2. Should return INVALID_POSITION if the point does not intersect an item
*/
+ @UiThreadTest
public void testPointToPosition() {
AbsSpinner absSpinner = new Gallery(mContext);
MockSpinnerAdapter adapter = new MockSpinnerAdapter();
@@ -210,6 +212,7 @@
* 1. Should return the view corresponding to the currently selected item.
* 2. Should return null if nothing is selected.
*/
+ @UiThreadTest
public void testGetSelectedView() {
AbsSpinner absSpinner = new Gallery(mContext);
MockSpinnerAdapter adapter = new MockSpinnerAdapter();
diff --git a/tests/tests/widget/src/android/widget/cts/AnalogClockTest.java b/tests/tests/widget/src/android/widget/cts/AnalogClockTest.java
index b360fd1..ef1a45d 100644
--- a/tests/tests/widget/src/android/widget/cts/AnalogClockTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AnalogClockTest.java
@@ -23,6 +23,7 @@
import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
import android.util.AttributeSet;
import android.util.Xml;
import android.widget.AnalogClock;
@@ -44,6 +45,7 @@
mActivity = getActivity();
}
+ @UiThreadTest
public void testConstructor() {
new AnalogClock(mActivity);
new AnalogClock(mActivity, mAttrSet);
diff --git a/tests/tests/widget/src/android/widget/cts/ArrayAdapterTest.java b/tests/tests/widget/src/android/widget/cts/ArrayAdapterTest.java
index 3b00754..1e17ea7 100644
--- a/tests/tests/widget/src/android/widget/cts/ArrayAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ArrayAdapterTest.java
@@ -20,8 +20,10 @@
import java.util.Comparator;
import java.util.List;
+import android.content.Context;
import android.database.DataSetObserver;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
@@ -29,7 +31,7 @@
import com.android.cts.widget.R;
-public class ArrayAdapterTest extends AndroidTestCase {
+public class ArrayAdapterTest extends InstrumentationTestCase {
private static final int INVALD_ID = -1;
private static final String STR1 = "string1";
@@ -37,10 +39,13 @@
private static final String STR3 = "string3";
private ArrayAdapter<String> mArrayAdapter;
+ private Context mContext;
+
@Override
protected void setUp() throws Exception {
super.setUp();
- mArrayAdapter = new ArrayAdapter<String>(mContext, R.layout.simple_dropdown_item_1line);
+ mContext = getInstrumentation().getTargetContext();
+ mArrayAdapter = new ArrayAdapter<String>(mContext, R.layout.simple_dropdown_item_1line);
}
public void testConstructor() {
@@ -167,6 +172,7 @@
}
}
+ @UiThreadTest
public void testGetFilter() {
Filter filter = mArrayAdapter.getFilter();
diff --git a/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java b/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
index f3a58bc..9fa4959 100644
--- a/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AutoCompleteTextViewTest.java
@@ -104,6 +104,7 @@
}
}
+ @UiThreadTest
public void testConstructor() {
XmlPullParser parser;
@@ -159,6 +160,7 @@
assertFalse(mAutoCompleteTextView.enoughToFilter());
}
+ @UiThreadTest
public void testAccessAdapter() {
MockAutoCompleteTextView autoCompleteTextView = new MockAutoCompleteTextView(mActivity);
@@ -222,6 +224,7 @@
assertNull(mAutoCompleteTextView.getOnItemSelectedListener());
}
+ @UiThreadTest
public void testConvertSelectionToString() {
MockAutoCompleteTextView autoCompleteTextView = new MockAutoCompleteTextView(mActivity);
@@ -234,6 +237,7 @@
assertEquals(STRING_TEST, autoCompleteTextView.convertSelectionToString(STRING_TEST));
}
+ @UiThreadTest
public void testOnTextChanged() {
MockAutoCompleteTextView autoCompleteTextView = new MockAutoCompleteTextView(mActivity);
@@ -287,6 +291,7 @@
assertEquals(STRING_VALIDATED, mAutoCompleteTextView.getText().toString());
}
+ @UiThreadTest
public void testReplaceText() {
MockAutoCompleteTextView autoCompleteTextView = new MockAutoCompleteTextView(mActivity);
@@ -303,6 +308,7 @@
assertTrue(autoCompleteTextView.isOnTextChanged());
}
+ @UiThreadTest
public void testSetFrame() {
MockAutoCompleteTextView autoCompleteTextView = new MockAutoCompleteTextView(mActivity);
diff --git a/tests/tests/widget/src/android/widget/cts/ChronometerTest.java b/tests/tests/widget/src/android/widget/cts/ChronometerTest.java
index 992577c..7910274 100644
--- a/tests/tests/widget/src/android/widget/cts/ChronometerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ChronometerTest.java
@@ -37,6 +37,7 @@
mActivity = getActivity();
}
+ @UiThreadTest
public void testConstructor() {
new Chronometer(mActivity);
diff --git a/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java b/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java
index 6ff22b0..8cc0754 100644
--- a/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/CursorAdapterTest.java
@@ -25,7 +25,8 @@
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.os.Looper;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -40,7 +41,7 @@
/**
* Test {@link CursorAdapter}.
*/
-public class CursorAdapterTest extends AndroidTestCase {
+public class CursorAdapterTest extends InstrumentationTestCase {
private static final long TEST_TIME_OUT = 5000;
private static final int NUMBER_INDEX = 1;
private static final String FIRST_NUMBER = "123";
@@ -56,11 +57,13 @@
private Cursor mCursor;
private ViewGroup mParent;
private MockCursorAdapter mMockCursorAdapter;
+ private Context mContext;
@Override
protected void setUp() throws Exception {
super.setUp();
- File dbDir = getContext().getDir("tests", Context.MODE_WORLD_WRITEABLE);
+ mContext = getInstrumentation().getTargetContext();
+ File dbDir = mContext.getDir("tests", Context.MODE_WORLD_WRITEABLE);
mDatabaseFile = new File(dbDir, "database_test.db");
if (mDatabaseFile.exists()) {
mDatabaseFile.delete();
@@ -89,6 +92,7 @@
super.tearDown();
}
+ @UiThreadTest
public void testConstructor() {
new MockCursorAdapter(mContext, mCursor);
@@ -99,6 +103,7 @@
new MockCursorAdapter(null, null, false);
}
+ @UiThreadTest
public void testInit() {
MockCursorAdapter cursorAdapter = new MockCursorAdapter(null, null, false);
cursorAdapter.init(null, null, false);
@@ -143,6 +148,7 @@
}
}
+ @UiThreadTest
public void testGetCount() {
CursorAdapter cursorAdapter = new MockCursorAdapter(mContext, null);
assertEquals(0, cursorAdapter.getCount());
@@ -151,6 +157,7 @@
assertEquals(mCursor.getCount(), cursorAdapter.getCount());
}
+ @UiThreadTest
public void testAccessCursor() {
CursorAdapter cursorAdapter = new MockCursorAdapter(mContext, null);
assertNull(cursorAdapter.getCursor());
@@ -162,6 +169,7 @@
assertNull(cursorAdapter.getCursor());
}
+ @UiThreadTest
public void testConvertToString() {
CursorAdapter cursorAdapter = new MockCursorAdapter(mContext, null);
assertEquals("", cursorAdapter.convertToString(null));
@@ -169,6 +177,7 @@
assertEquals(mCursor.toString(), cursorAdapter.convertToString(mCursor));
}
+ @UiThreadTest
public void testHasStableIds() {
CursorAdapter cursorAdapter = new MockCursorAdapter(mContext, mCursor);
assertTrue(cursorAdapter.hasStableIds());
@@ -177,6 +186,7 @@
assertTrue(cursorAdapter.hasStableIds());
}
+ @UiThreadTest
public void testGetView() {
TextView textView = new TextView(mContext);
textView.setText("getView test");
@@ -208,6 +218,7 @@
assertEquals(SECOND_NUMBER, retView.getText().toString());
}
+ @UiThreadTest
public void testNewDropDownView() {
CursorAdapter cursorAdapter = new MockCursorAdapter(mContext, mCursor);
// null cursor
@@ -217,6 +228,7 @@
assertEquals(FIRST_NUMBER, textView.getText().toString());
}
+ @UiThreadTest
public void testGetDropDownView() {
MockCursorAdapter cursorAdapter = new MockCursorAdapter(mContext, null);
// null cursor
@@ -238,12 +250,14 @@
assertEquals(SECOND_NUMBER, retView.getText().toString());
}
+ @UiThreadTest
public void testGetFilter() {
CursorAdapter cursorAdapter = new MockCursorAdapter(mContext, mCursor);
Filter filter = cursorAdapter.getFilter();
assertNotNull(filter);
}
+ @UiThreadTest
public void testGetItem() {
CursorAdapter cursorAdapter = new MockCursorAdapter(mContext, null);
// cursor is null
@@ -261,6 +275,7 @@
assertEquals(SECOND_NUMBER, c.getString(NUMBER_INDEX));
}
+ @UiThreadTest
public void testGetItemId() {
CursorAdapter cursorAdapter = new MockCursorAdapter(mContext, null);
// cursor is null
@@ -275,6 +290,7 @@
assertEquals(0, cursorAdapter.getItemId(2));
}
+ @UiThreadTest
public void testAccessFilterQueryProvider() {
CursorAdapter cursorAdapter = new MockCursorAdapter(mContext, mCursor);
FilterQueryProvider filterProvider = new MockFilterQueryProvider();
@@ -286,6 +302,7 @@
assertSame(filterProvider, cursorAdapter.getFilterQueryProvider());
}
+ @UiThreadTest
public void testRunQueryOnBackgroundThread() {
CursorAdapter cursorAdapter = new MockCursorAdapter(mContext, mCursor);
final String constraint = "constraint";
diff --git a/tests/tests/widget/src/android/widget/cts/CursorTreeAdapterTest.java b/tests/tests/widget/src/android/widget/cts/CursorTreeAdapterTest.java
index 011a031..f74b997 100644
--- a/tests/tests/widget/src/android/widget/cts/CursorTreeAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/CursorTreeAdapterTest.java
@@ -22,7 +22,8 @@
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -37,7 +38,7 @@
/**
* Test {@link CursorTreeAdapter}.
*/
-public class CursorTreeAdapterTest extends AndroidTestCase {
+public class CursorTreeAdapterTest extends InstrumentationTestCase {
private static final int NAME_INDEX = 1;
private static final int VALUE_INDEX = 1;
private static final String GROUP_ONE = "group_one";
@@ -61,6 +62,7 @@
private Cursor mChildCursor1;
private Cursor mChildCursor2;
private ViewGroup mParent;
+ private Context mContext;
private Cursor createGroupCursor() {
mDatabase.execSQL("CREATE TABLE group_table (_id INTEGER PRIMARY KEY, name TEXT);");
@@ -93,7 +95,8 @@
@Override
protected void setUp() throws Exception {
super.setUp();
- File dbDir = getContext().getDir("tests", Context.MODE_WORLD_WRITEABLE);
+ mContext = getInstrumentation().getTargetContext();
+ File dbDir = mContext.getDir("tests", Context.MODE_WORLD_WRITEABLE);
mDatabaseFile = new File(dbDir, "database_test.db");
if (mDatabaseFile.exists()) {
mDatabaseFile.delete();
@@ -136,6 +139,7 @@
super.tearDown();
}
+ @UiThreadTest
public void testConstructor() {
new MockCursorTreeAdapter(mGroupCursor, mContext);
@@ -146,6 +150,7 @@
new MockCursorTreeAdapter(null, null, false);
}
+ @UiThreadTest
public void testGetCursor() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
assertSame(mGroupCursor, adapter.getCursor());
@@ -157,6 +162,7 @@
assertSame(mGroupCursor, adapter.getCursor());
}
+ @UiThreadTest
public void testSetGroupCursor() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
assertSame(mGroupCursor, adapter.getCursor());
@@ -168,6 +174,7 @@
assertSame(mGroupCursor, adapter.getCursor());
}
+ @UiThreadTest
public void testSetChildrenCursor() {
MockCursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
assertTrue(mGroupCursor.moveToFirst());
@@ -177,6 +184,7 @@
assertSame(mChildCursor2, adapter.getChild(0, 0));
}
+ @UiThreadTest
public void testChangeCursor() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(null, mContext);
assertNull(adapter.getCursor());
@@ -188,6 +196,7 @@
assertNull(adapter.getCursor());
}
+ @UiThreadTest
public void testNotifyDataSetChangedBoolean() {
MockCursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
MockDataSetObserver observer = new MockDataSetObserver();
@@ -226,6 +235,7 @@
assertFalse(adapter.hasAddedChild2IntoCache());
}
+ @UiThreadTest
public void testNotifyDataSetChanged() {
MockCursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
MockDataSetObserver observer = new MockDataSetObserver();
@@ -251,6 +261,7 @@
assertTrue(adapter.hasAddedChild2IntoCache());
}
+ @UiThreadTest
public void testNotifyDataSetInvalidated() {
MockCursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
MockDataSetObserver observer = new MockDataSetObserver();
@@ -276,6 +287,7 @@
assertTrue(adapter.hasAddedChild2IntoCache());
}
+ @UiThreadTest
public void testOnGroupCollapsed() {
MockCursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
@@ -313,6 +325,7 @@
}
}
+ @UiThreadTest
public void testHasStableIds() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
assertTrue(adapter.hasStableIds());
@@ -321,6 +334,7 @@
assertTrue(adapter.hasStableIds());
}
+ @UiThreadTest
public void testIsChildSelectable() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
assertTrue(adapter.isChildSelectable(0, 0));
@@ -330,6 +344,7 @@
assertTrue(adapter.isChildSelectable(0, 0));
}
+ @UiThreadTest
public void testConvertToString() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
assertEquals("", adapter.convertToString(null));
@@ -337,6 +352,7 @@
assertEquals(mGroupCursor.toString(), adapter.convertToString(mGroupCursor));
}
+ @UiThreadTest
public void testGetFilter() {
MockCursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
Filter filter = adapter.getFilter();
@@ -348,6 +364,7 @@
assertTrue(adapter.hasCalledConvertToString());
}
+ @UiThreadTest
public void testAccessQueryProvider() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
FilterQueryProvider filterProvider = new MockFilterQueryProvider();
@@ -359,6 +376,7 @@
assertSame(filterProvider, adapter.getFilterQueryProvider());
}
+ @UiThreadTest
public void testRunQueryOnBackgroundThread() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
final String constraint = "constraint";
@@ -372,6 +390,7 @@
assertNull(adapter.runQueryOnBackgroundThread(constraint));
}
+ @UiThreadTest
public void testGetGroup() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(null, mContext);
@@ -391,6 +410,7 @@
assertNull(adapter.getGroup(2));
}
+ @UiThreadTest
public void testGetGroupCount() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
assertEquals(mGroupCursor.getCount(), adapter.getGroupCount());
@@ -399,6 +419,7 @@
assertEquals(0, adapter.getGroupCount());
}
+ @UiThreadTest
public void testGetGroupId() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(null, mContext);
@@ -414,6 +435,7 @@
assertEquals(0, adapter.getGroupId(2));
}
+ @UiThreadTest
public void testGetGroupView() {
final String expectedStr = "getGroupView test";
TextView retView;
@@ -449,6 +471,7 @@
assertEquals(GROUP_ONE, retView.getText().toString());
}
+ @UiThreadTest
public void testGetChild() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(mGroupCursor, mContext);
assertEquals(2, adapter.getGroupCount());
@@ -476,6 +499,7 @@
assertEquals(CHILD_VALUE_THREE, retCursor.getString(VALUE_INDEX));
}
+ @UiThreadTest
public void testGetChildId() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(null, mContext);
@@ -504,6 +528,7 @@
assertEquals(0, adapter.getChildId(0, 2));
}
+ @UiThreadTest
public void testGetChildrenCount() {
CursorTreeAdapter adapter = new MockCursorTreeAdapter(null, mContext);
@@ -519,6 +544,7 @@
assertEquals(0, adapter.getChildrenCount(2));
}
+ @UiThreadTest
public void testGetChildView() {
final String expectedStr = "getChildView test";
TextView retView;
diff --git a/tests/tests/widget/src/android/widget/cts/DatePickerTest.java b/tests/tests/widget/src/android/widget/cts/DatePickerTest.java
index aa727b7..fdadc2c 100644
--- a/tests/tests/widget/src/android/widget/cts/DatePickerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/DatePickerTest.java
@@ -19,11 +19,11 @@
import com.android.cts.widget.R;
import com.android.internal.util.XmlUtils;
-
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.os.Parcelable;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.Xml;
@@ -33,7 +33,16 @@
/**
* Test {@link DatePicker}.
*/
-public class DatePickerTest extends AndroidTestCase {
+public class DatePickerTest extends InstrumentationTestCase {
+
+ private Context mContext;
+
+ @Override
+ public void setUp() {
+ mContext = getInstrumentation().getTargetContext();
+ }
+
+ @UiThreadTest
public void testConstructor() {
new DatePicker(mContext);
@@ -53,6 +62,7 @@
}
}
+ @UiThreadTest
public void testSetEnabled() {
MockDatePicker datePicker = createDatePicker();
@@ -65,6 +75,7 @@
assertTrue(datePicker.isEnabled());
}
+ @UiThreadTest
public void testInit() {
MockOnDateChangedListener onDateChangedListener = new MockOnDateChangedListener();
DatePicker datePicker = createDatePicker();
@@ -78,6 +89,7 @@
assertEquals(15, datePicker.getDayOfMonth());
}
+ @UiThreadTest
public void testAccessDate() {
DatePicker datePicker = createDatePicker();
@@ -96,6 +108,7 @@
assertEquals(19, datePicker.getDayOfMonth());
}
+ @UiThreadTest
public void testUpdateDate() {
DatePicker datePicker = createDatePicker();
@@ -109,6 +122,7 @@
assertEquals(19, datePicker.getDayOfMonth());
}
+ @UiThreadTest
public void testOnSaveInstanceState() {
MockDatePicker datePicker = createDatePicker();
diff --git a/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java b/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java
index 9b7fb56..a8584ae 100644
--- a/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/DialerFilterTest.java
@@ -64,6 +64,7 @@
mDialerFilter = (DialerFilter) mActivity.findViewById(R.id.dialer_filter);
}
+ @UiThreadTest
public void testConstructor() {
final XmlPullParser parser = mActivity.getResources().getXml(R.layout.dialerfilter_layout);
final AttributeSet attrs = Xml.asAttributeSet(parser);
@@ -72,6 +73,7 @@
new DialerFilter(mActivity, attrs);
}
+ @UiThreadTest
public void testIsQwertyKeyboard() {
// Simply call the method. Return value may depend on the default keyboard.
mDialerFilter.isQwertyKeyboard();
@@ -81,7 +83,7 @@
// The exact behavior depends on the implementation of DialerKeyListener and
// TextKeyListener, but even that may be changed. Simply assert basic scenarios.
- mInstrumentation.runOnMainSync(new Runnable() {
+ mActivity.runOnUiThread(new Runnable() {
public void run() {
mDialerFilter.setMode(DialerFilter.DIGITS_ONLY);
mDialerFilter.requestFocus();
@@ -95,7 +97,7 @@
assertEquals("", mDialerFilter.getLetters().toString());
assertEquals("123", mDialerFilter.getDigits().toString());
- mInstrumentation.runOnMainSync(new Runnable() {
+ mActivity.runOnUiThread(new Runnable() {
public void run() {
mDialerFilter.clearText();
mDialerFilter.setMode(DialerFilter.LETTERS_ONLY);
@@ -116,7 +118,7 @@
assertEquals("ADG", mDialerFilter.getLetters().toString());
assertEquals("", mDialerFilter.getDigits().toString());
- mInstrumentation.runOnMainSync(new Runnable() {
+ mActivity.runOnUiThread(new Runnable() {
public void run() {
mDialerFilter.clearText();
mDialerFilter.setMode(DialerFilter.DIGITS_AND_LETTERS);
@@ -135,7 +137,7 @@
assertEquals("ADG", mDialerFilter.getLetters().toString());
// A, D, K may map to numbers on some keyboards. Don't test.
- mInstrumentation.runOnMainSync(new Runnable() {
+ mActivity.runOnUiThread(new Runnable() {
public void run() {
mDialerFilter.clearText();
mDialerFilter.setMode(DialerFilter.DIGITS_AND_LETTERS);
diff --git a/tests/tests/widget/src/android/widget/cts/DigitalClockTest.java b/tests/tests/widget/src/android/widget/cts/DigitalClockTest.java
index 26caef0..2f2cc1a 100644
--- a/tests/tests/widget/src/android/widget/cts/DigitalClockTest.java
+++ b/tests/tests/widget/src/android/widget/cts/DigitalClockTest.java
@@ -52,6 +52,7 @@
mContext = getInstrumentation().getContext();
}
+ @UiThreadTest
public void testConstructor() {
// new the DigitalClock instance
new DigitalClock(mContext);
diff --git a/tests/tests/widget/src/android/widget/cts/FilterTest.java b/tests/tests/widget/src/android/widget/cts/FilterTest.java
index 3441431..76de481 100644
--- a/tests/tests/widget/src/android/widget/cts/FilterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/FilterTest.java
@@ -18,12 +18,14 @@
import android.cts.util.PollingCheck;
+import android.os.Looper;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.Filter;
import android.widget.Filter.FilterListener;
public class FilterTest extends ActivityInstrumentationTestCase2<CtsActivity> {
private static final long TIME_OUT = 10000;
+ private static final long RUN_TIME = 1000;
private static final String TEST_CONSTRAINT = "filter test";
private MockFilter mMockFilter;
@@ -31,16 +33,26 @@
super("com.android.cts.widget", CtsActivity.class);
}
- public void testConstructor() {
- new MockFilter();
+ public void testConstructor() throws Throwable {
+ TestThread t = new TestThread(new Runnable() {
+ public void run() {
+ Looper.prepare();
+ new MockFilter();
+ }
+ });
+ t.runTest(RUN_TIME);
}
- public void testConvertResultToString() {
- final MockFilter filter = new MockFilter();
- assertEquals("", filter.convertResultToString(null));
-
+ public void testConvertResultToString() throws Throwable {
final String testStr = "Test";
- assertEquals(testStr, filter.convertResultToString(testStr));
+ new TestThread(new Runnable() {
+ public void run() {
+ Looper.prepare();
+ MockFilter filter = new MockFilter();
+ assertEquals("", filter.convertResultToString(null));
+ assertEquals(testStr, filter.convertResultToString(testStr));
+ }
+ }).runTest(RUN_TIME);
}
public void testFilter1() {
diff --git a/tests/tests/widget/src/android/widget/cts/GalleryTest.java b/tests/tests/widget/src/android/widget/cts/GalleryTest.java
index d42c375..a2deab9 100644
--- a/tests/tests/widget/src/android/widget/cts/GalleryTest.java
+++ b/tests/tests/widget/src/android/widget/cts/GalleryTest.java
@@ -73,6 +73,7 @@
mGallery = (Gallery) mActivity.findViewById(R.id.gallery_test);
}
+ @UiThreadTest
public void testConstructor() {
new Gallery(mContext);
@@ -154,6 +155,7 @@
assertEquals(alpha, t.getAlpha(), DELTA);
}
+ @UiThreadTest
public void testGenerateLayoutParams() throws XmlPullParserException, IOException {
final int width = 320;
final int height = 240;
@@ -187,6 +189,7 @@
// how to check whether the context menu is showing.
}
+ @UiThreadTest
public void testDispatchKeyEvent() {
mGallery = new Gallery(mContext);
final KeyEvent validKeyEvent = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER);
@@ -222,6 +225,7 @@
mInstrumentation.waitForIdleSync();
}
+ @UiThreadTest
public void testCheckLayoutParams() {
MyGallery gallery = new MyGallery(mContext);
ViewGroup.LayoutParams p1 = new ViewGroup.LayoutParams(320, 480);
@@ -231,6 +235,7 @@
assertTrue(gallery.checkLayoutParams(p2));
}
+ @UiThreadTest
public void testComputeHorizontalScrollExtent() {
MyGallery gallery = new MyGallery(mContext);
@@ -238,6 +243,7 @@
assertEquals(1, gallery.computeHorizontalScrollExtent());
}
+ @UiThreadTest
public void testComputeHorizontalScrollOffset() {
MyGallery gallery = new MyGallery(mContext);
assertEquals(AdapterView.INVALID_POSITION, gallery.computeHorizontalScrollOffset());
@@ -247,6 +253,7 @@
assertEquals(gallery.getSelectedItemPosition(), gallery.computeHorizontalScrollOffset());
}
+ @UiThreadTest
public void testComputeHorizontalScrollRange() {
MyGallery gallery = new MyGallery(mContext);
ImageAdapter adapter = new ImageAdapter(mActivity);
@@ -270,6 +277,7 @@
assertFalse(gallery.getChildAt(1).isPressed());
}
+ @UiThreadTest
public void testGenerateDefaultLayoutParams() {
MyGallery gallery = new MyGallery(mContext);
ViewGroup.LayoutParams p = gallery.generateDefaultLayoutParams();
@@ -296,6 +304,7 @@
assertEquals(index + 1, gallery.getChildDrawingOrder(childCount, index));
}
+ @UiThreadTest
public void testGetContextMenuInfo() {
MockOnCreateContextMenuListener listener = new MockOnCreateContextMenuListener();
MyGallery gallery = new MyGallery(mContext);
diff --git a/tests/tests/widget/src/android/widget/cts/HeaderViewListAdapterTest.java b/tests/tests/widget/src/android/widget/cts/HeaderViewListAdapterTest.java
index e583dce..2b92a4d 100644
--- a/tests/tests/widget/src/android/widget/cts/HeaderViewListAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/HeaderViewListAdapterTest.java
@@ -16,9 +16,10 @@
package android.widget.cts;
-
+import android.content.Context;
import android.database.DataSetObserver;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
@@ -33,13 +34,16 @@
/**
* Test {@link HeaderViewListAdapter}.
*/
-public class HeaderViewListAdapterTest extends AndroidTestCase {
+public class HeaderViewListAdapterTest extends InstrumentationTestCase {
+ private Context mContext;
@Override
protected void setUp() throws Exception {
super.setUp();
+ mContext = getInstrumentation().getTargetContext();
}
+ @UiThreadTest
public void testConstructor() {
ArrayList<ListView.FixedViewInfo> header = new ArrayList<ListView.FixedViewInfo>();
ArrayList<ListView.FixedViewInfo> footer = new ArrayList<ListView.FixedViewInfo>(5);
@@ -52,7 +56,7 @@
HeaderViewListAdapter headerViewListAdapter = new HeaderViewListAdapter(null, null, null);
assertEquals(0, headerViewListAdapter.getHeadersCount());
- ListView lv = new ListView(getContext());
+ ListView lv = new ListView(mContext);
ArrayList<ListView.FixedViewInfo> header = new ArrayList<ListView.FixedViewInfo>(4);
header.add(lv.new FixedViewInfo());
headerViewListAdapter = new HeaderViewListAdapter(header, null, null);
@@ -63,13 +67,14 @@
HeaderViewListAdapter headerViewListAdapter = new HeaderViewListAdapter(null, null, null);
assertEquals(0, headerViewListAdapter.getFootersCount());
- ListView lv = new ListView(getContext());
+ ListView lv = new ListView(mContext);
ArrayList<ListView.FixedViewInfo> footer = new ArrayList<ListView.FixedViewInfo>(4);
footer.add(lv.new FixedViewInfo());
headerViewListAdapter = new HeaderViewListAdapter(null, footer, null);
assertEquals(1, headerViewListAdapter.getFootersCount());
}
+ @UiThreadTest
public void testIsEmpty() {
HeaderViewListAdapter headerViewListAdapter = new HeaderViewListAdapter(null, null, null);
assertTrue(headerViewListAdapter.isEmpty());
@@ -84,10 +89,10 @@
}
public void testRemoveHeader() {
- ListView lv = new ListView(getContext());
+ ListView lv = new ListView(mContext);
ArrayList<ListView.FixedViewInfo> header = new ArrayList<ListView.FixedViewInfo>(4);
- ListView lv1 = new ListView(getContext());
- ListView lv2 = new ListView(getContext());
+ ListView lv1 = new ListView(mContext);
+ ListView lv2 = new ListView(mContext);
ListView.FixedViewInfo info1 = lv.new FixedViewInfo();
info1.view = lv1;
ListView.FixedViewInfo info2 = lv.new FixedViewInfo();
@@ -96,7 +101,7 @@
header.add(info2);
HeaderViewListAdapter headerViewListAdapter = new HeaderViewListAdapter(header, null, null);
assertEquals(2, headerViewListAdapter.getHeadersCount());
- assertFalse(headerViewListAdapter.removeHeader(new ListView(getContext())));
+ assertFalse(headerViewListAdapter.removeHeader(new ListView(mContext)));
assertTrue(headerViewListAdapter.removeHeader(lv1));
assertEquals(1, headerViewListAdapter.getHeadersCount());
@@ -110,10 +115,10 @@
}
public void testRemoveFooter() {
- ListView lv = new ListView(getContext());
+ ListView lv = new ListView(mContext);
ArrayList<ListView.FixedViewInfo> footer = new ArrayList<ListView.FixedViewInfo>(4);
- ListView lv1 = new ListView(getContext());
- ListView lv2 = new ListView(getContext());
+ ListView lv1 = new ListView(mContext);
+ ListView lv2 = new ListView(mContext);
ListView.FixedViewInfo info1 = lv.new FixedViewInfo();
info1.view = lv1;
ListView.FixedViewInfo info2 = lv.new FixedViewInfo();
@@ -122,7 +127,7 @@
footer.add(info2);
HeaderViewListAdapter headerViewListAdapter = new HeaderViewListAdapter(null, footer, null);
assertEquals(2, headerViewListAdapter.getFootersCount());
- assertFalse(headerViewListAdapter.removeFooter(new ListView(getContext())));
+ assertFalse(headerViewListAdapter.removeFooter(new ListView(mContext)));
assertTrue(headerViewListAdapter.removeFooter(lv1));
assertEquals(1, headerViewListAdapter.getFootersCount());
@@ -135,11 +140,12 @@
}
}
+ @UiThreadTest
public void testGetCount() {
HeaderViewListAdapter headerViewListAdapter = new HeaderViewListAdapter(null, null, null);
assertEquals(0, headerViewListAdapter.getCount());
- ListView lv = new ListView(getContext());
+ ListView lv = new ListView(mContext);
ArrayList<ListView.FixedViewInfo> header = new ArrayList<ListView.FixedViewInfo>(4);
Object data1 = new Object();
Object data2 = new Object();
@@ -170,6 +176,7 @@
assertEquals(5, headerViewListAdapter.getCount());
}
+ @UiThreadTest
public void testAreAllItemsEnabled() {
HeaderViewListAdapter headerViewListAdapter = new HeaderViewListAdapter(null, null, null);
assertTrue(headerViewListAdapter.areAllItemsEnabled());
@@ -189,7 +196,7 @@
new HeaderViewListAdapter(null, null, fullAdapter);
assertTrue(headerViewListAdapter.isEnabled(0));
- ListView lv = new ListView(getContext());
+ ListView lv = new ListView(mContext);
ArrayList<ListView.FixedViewInfo> header = new ArrayList<ListView.FixedViewInfo>(4);
header.add(lv.new FixedViewInfo());
headerViewListAdapter = new HeaderViewListAdapter(header, null, fullAdapter);
@@ -212,7 +219,7 @@
}
public void testGetItem() {
- ListView lv = new ListView(getContext());
+ ListView lv = new ListView(mContext);
ArrayList<ListView.FixedViewInfo> header = new ArrayList<ListView.FixedViewInfo>(4);
Object data1 = new Object();
Object data2 = new Object();
@@ -243,10 +250,10 @@
}
public void testGetItemId() {
- ListView lv = new ListView(getContext());
+ ListView lv = new ListView(mContext);
ArrayList<ListView.FixedViewInfo> header = new ArrayList<ListView.FixedViewInfo>(4);
- ListView lv1 = new ListView(getContext());
- ListView lv2 = new ListView(getContext());
+ ListView lv1 = new ListView(mContext);
+ ListView lv2 = new ListView(mContext);
ListView.FixedViewInfo info1 = lv.new FixedViewInfo();
info1.view = lv1;
ListView.FixedViewInfo info2 = lv.new FixedViewInfo();
@@ -271,10 +278,10 @@
}
public void testGetView() {
- ListView lv = new ListView(getContext());
+ ListView lv = new ListView(mContext);
ArrayList<ListView.FixedViewInfo> header = new ArrayList<ListView.FixedViewInfo>(4);
- ListView lv1 = new ListView(getContext());
- ListView lv2 = new ListView(getContext());
+ ListView lv1 = new ListView(mContext);
+ ListView lv2 = new ListView(mContext);
ListView.FixedViewInfo info1 = lv.new FixedViewInfo();
info1.view = lv1;
ListView.FixedViewInfo info2 = lv.new FixedViewInfo();
@@ -345,6 +352,7 @@
assertNull(fullAdapter.getDataSetObserver());
}
+ @UiThreadTest
public void testGetFilter() {
HeaderViewListAdapter headerViewListAdapter = new HeaderViewListAdapter(null, null, null);
assertNull(headerViewListAdapter.getFilter());
@@ -426,7 +434,7 @@
private class HeaderViewFullAdapter implements ListAdapter {
private DataSetObserver mObserver;
private Object mItem;
- private final View mView = new View(getContext());
+ private final View mView = new View(mContext);
public DataSetObserver getDataSetObserver() {
return mObserver;
diff --git a/tests/tests/widget/src/android/widget/cts/MediaControllerTest.java b/tests/tests/widget/src/android/widget/cts/MediaControllerTest.java
index a12dba6..49bc767 100644
--- a/tests/tests/widget/src/android/widget/cts/MediaControllerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/MediaControllerTest.java
@@ -60,6 +60,7 @@
mInstrumentation = getInstrumentation();
}
+ @UiThreadTest
public void testConstructor() {
new MediaController(mActivity, null);
@@ -109,7 +110,12 @@
}
public void testShow() {
- mMediaController = new MediaController(mActivity, true);
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ mMediaController = new MediaController(mActivity, true);
+ }
+ });
+ mInstrumentation.waitForIdleSync();
assertFalse(mMediaController.isShowing());
final MockMediaPlayerControl mediaPlayerControl = new MockMediaPlayerControl();
@@ -185,7 +191,12 @@
}
public void testOnTrackballEvent() {
- mMediaController = new MediaController(mActivity);
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ mMediaController = new MediaController(mActivity);
+ }
+ });
+ mInstrumentation.waitForIdleSync();
final MockMediaPlayerControl mediaPlayerControl = new MockMediaPlayerControl();
mMediaController.setMediaPlayer(mediaPlayerControl);
@@ -238,6 +249,7 @@
assertFalse(mMediaController.isEnabled());
}
+ @UiThreadTest
public void testSetPrevNextListeners() {
final View videoView = mActivity.findViewById(R.id.mediacontroller_videoview);
final MockMediaPlayerControl mediaPlayerControl = new MockMediaPlayerControl();
diff --git a/tests/tests/widget/src/android/widget/cts/MultiAutoCompleteTextViewTest.java b/tests/tests/widget/src/android/widget/cts/MultiAutoCompleteTextViewTest.java
index 75f9242..4afdb80 100644
--- a/tests/tests/widget/src/android/widget/cts/MultiAutoCompleteTextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/MultiAutoCompleteTextViewTest.java
@@ -59,6 +59,7 @@
.findViewById(R.id.name_edit);
}
+ @UiThreadTest
public void testConstructor() {
XmlPullParser parser = mActivity.getResources()
.getXml(R.layout.multi_auto_complete_text_view_layout);
@@ -151,6 +152,7 @@
assertEquals(str + ", ", mMultiAutoCompleteTextView_country.getText().toString());
}
+ @UiThreadTest
public void testPerformFiltering() {
MyMultiAutoCompleteTextView multiAutoCompleteTextView =
new MyMultiAutoCompleteTextView(mActivity);
@@ -175,6 +177,7 @@
assertNotNull(multiAutoCompleteTextView.getFilter());
}
+ @UiThreadTest
public void testReplaceText() {
MyMultiAutoCompleteTextView multiAutoCompleteTextView =
new MyMultiAutoCompleteTextView(mActivity);
diff --git a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
index 9c4c3a3..4a14d2b 100644
--- a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
+++ b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
@@ -27,6 +27,7 @@
import android.graphics.drawable.Drawable;
import android.os.SystemClock;
import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
@@ -366,6 +367,7 @@
assertTrue(maxAvailableHeight <= avaliable);
}
+ @UiThreadTest
public void testDismiss() {
mPopupWindow = createPopupWindow(createPopupContent());
assertFalse(mPopupWindow.isShowing());
@@ -447,7 +449,13 @@
int[] sndXY = new int[2];
int[] viewInWindowXY = new int[2];
- mPopupWindow = createPopupWindow(createPopupContent());
+ mInstrumentation.runOnMainSync(new Runnable() {
+ public void run() {
+ mPopupWindow = createPopupWindow(createPopupContent());
+ }
+ });
+
+ mInstrumentation.waitForIdleSync();
// Do not update if it is not shown
assertFalse(mPopupWindow.isShowing());
assertEquals(100, mPopupWindow.getWidth());
@@ -492,30 +500,54 @@
}
public void testUpdateDimensionAndAlignAnchorView() {
- mPopupWindow = createPopupWindow(createPopupContent());
+ mInstrumentation.runOnMainSync(new Runnable() {
+ public void run() {
+ mPopupWindow = createPopupWindow(createPopupContent());
+ }
+ });
+ mInstrumentation.waitForIdleSync();
- View anchorView = mActivity.findViewById(R.id.anchor_upper);
+ final View anchorView = mActivity.findViewById(R.id.anchor_upper);
mPopupWindow.update(anchorView, 50, 50);
// Do not update if it is not shown
assertFalse(mPopupWindow.isShowing());
assertEquals(100, mPopupWindow.getWidth());
assertEquals(100, mPopupWindow.getHeight());
- mPopupWindow.showAsDropDown(anchorView);
+ mInstrumentation.runOnMainSync(new Runnable() {
+ public void run() {
+ mPopupWindow.showAsDropDown(anchorView);
+ }
+ });
mInstrumentation.waitForIdleSync();
// update if it is shown
- mPopupWindow.update(anchorView, 50, 50);
+ mInstrumentation.runOnMainSync(new Runnable() {
+ public void run() {
+ mPopupWindow.update(anchorView, 50, 50);
+ }
+ });
+ mInstrumentation.waitForIdleSync();
assertTrue(mPopupWindow.isShowing());
assertEquals(50, mPopupWindow.getWidth());
assertEquals(50, mPopupWindow.getHeight());
// ignore if width or height is -1
- mPopupWindow.update(anchorView, -1, -1);
+ mInstrumentation.runOnMainSync(new Runnable() {
+ public void run() {
+ mPopupWindow.update(anchorView, -1, -1);
+ }
+ });
+ mInstrumentation.waitForIdleSync();
assertTrue(mPopupWindow.isShowing());
assertEquals(50, mPopupWindow.getWidth());
assertEquals(50, mPopupWindow.getHeight());
- mPopupWindow.dismiss();
+ mInstrumentation.runOnMainSync(new Runnable() {
+ public void run() {
+ mPopupWindow.dismiss();
+ }
+ });
+ mInstrumentation.waitForIdleSync();
}
public void testUpdateDimensionAndAlignAnchorViewWithOffsets() {
@@ -633,7 +665,12 @@
}
public void testIsAboveAnchor() {
- mPopupWindow = createPopupWindow(createPopupContent());
+ mInstrumentation.runOnMainSync(new Runnable() {
+ public void run() {
+ mPopupWindow = createPopupWindow(createPopupContent());
+ }
+ });
+ mInstrumentation.waitForIdleSync();
final View upperAnchor = mActivity.findViewById(R.id.anchor_upper);
mInstrumentation.runOnMainSync(new Runnable() {
diff --git a/tests/tests/widget/src/android/widget/cts/RadioButtonTest.java b/tests/tests/widget/src/android/widget/cts/RadioButtonTest.java
index c6ee1b7..4ec4eb5 100644
--- a/tests/tests/widget/src/android/widget/cts/RadioButtonTest.java
+++ b/tests/tests/widget/src/android/widget/cts/RadioButtonTest.java
@@ -21,6 +21,7 @@
import android.content.Context;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.util.AttributeSet;
import android.widget.RadioButton;
@@ -66,6 +67,7 @@
new RadioButton(mContext, attrs, Integer.MIN_VALUE);
}
+ @UiThreadTest
public void testToggle() {
RadioButton button = new RadioButton(mContext);
assertFalse(button.isChecked());
diff --git a/tests/tests/widget/src/android/widget/cts/RadioGroupTest.java b/tests/tests/widget/src/android/widget/cts/RadioGroupTest.java
index ee912fc..a172ecb 100644
--- a/tests/tests/widget/src/android/widget/cts/RadioGroupTest.java
+++ b/tests/tests/widget/src/android/widget/cts/RadioGroupTest.java
@@ -24,6 +24,7 @@
import android.content.Context;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.util.AttributeSet;
import android.util.Xml;
import android.view.Gravity;
@@ -107,6 +108,7 @@
assertEquals(0, newButton.getId() & 0xFF000000);
}
+ @UiThreadTest
public void testInternalCheckedStateTracker() {
mDefaultRadioGroup = new RadioGroup(mContext);
RadioButton newButton = new RadioButton(mContext);
@@ -138,6 +140,7 @@
assertHaveNotCalledOnCheckedChanged(listener);
}
+ @UiThreadTest
public void testGetCheckedRadioButtonId() {
assertEquals(-1, mDefaultRadioGroup.getCheckedRadioButtonId());
@@ -158,6 +161,7 @@
assertEquals(-3, mDefaultRadioGroup.getCheckedRadioButtonId());
}
+ @UiThreadTest
public void testClearCheck() {
MockOnCheckedChangeListener listener = new MockOnCheckedChangeListener();
mDefaultRadioGroup.setOnCheckedChangeListener(listener);
@@ -194,6 +198,7 @@
assertOnCheckedChangedParams(listener, 0, mDefaultRadioGroup, -1);
}
+ @UiThreadTest
public void testCheck() {
MockOnCheckedChangeListener listener = new MockOnCheckedChangeListener();
mDefaultRadioGroup.setOnCheckedChangeListener(listener);
@@ -238,6 +243,7 @@
mDefaultRadioGroup.check(0);
}
+ @UiThreadTest
public void testSetOnCheckedChangeListener() {
MockOnCheckedChangeListener listener = new MockOnCheckedChangeListener();
mDefaultRadioGroup.setOnCheckedChangeListener(listener);
@@ -333,6 +339,7 @@
assertEquals(RadioGroup.LayoutParams.WRAP_CONTENT, p.height);
}
+ @UiThreadTest
public void testOnFinishInflate() {
MockRadioGroup radioGroup = new MockRadioGroup(mContext);
int checkId = 100;
@@ -371,6 +378,7 @@
assertFalse(button.isChecked());
}
+ @UiThreadTest
public void testAddView() {
mDefaultRadioGroup.check(BUTTON_ID_0);
assertEquals(BUTTON_ID_0, mDefaultRadioGroup.getCheckedRadioButtonId());
diff --git a/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java b/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
index c958d8c..8d1cddf 100644
--- a/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/RemoteViewsTest.java
@@ -16,6 +16,7 @@
package android.widget.cts;
+import android.test.UiThreadTest;
import com.android.cts.widget.R;
@@ -76,8 +77,13 @@
protected void setUp() throws Exception {
super.setUp();
mActivity = getActivity();
- mRemoteViews = new RemoteViews(PACKAGE_NAME, R.layout.remoteviews_good);
- mResult = mRemoteViews.apply(mActivity, null);
+ getInstrumentation().runOnMainSync(new Runnable() {
+ @Override
+ public void run() {
+ mRemoteViews = new RemoteViews(PACKAGE_NAME, R.layout.remoteviews_good);
+ mResult = mRemoteViews.apply(mActivity, null);
+ }
+ });
}
public void testConstructor() {
@@ -307,6 +313,7 @@
mRemoteViews.describeContents();
}
+ @UiThreadTest
public void testWriteToParcel() {
mRemoteViews.setTextViewText(R.id.remoteView_text, "This is content");
mRemoteViews.setViewVisibility(R.id.remoteView_frame, View.GONE);
diff --git a/tests/tests/widget/src/android/widget/cts/ResourceCursorAdapterTest.java b/tests/tests/widget/src/android/widget/cts/ResourceCursorAdapterTest.java
index ed9d09c..28bfd06 100644
--- a/tests/tests/widget/src/android/widget/cts/ResourceCursorAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ResourceCursorAdapterTest.java
@@ -23,6 +23,7 @@
import android.database.Cursor;
import android.database.MatrixCursor;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -51,6 +52,7 @@
mCursor = createTestCursor(3, 3);
}
+ @UiThreadTest
public void testConstructor() {
MockResourceCursorAdapter adapter = new MockResourceCursorAdapter(mContext, -1, null);
// the default is true
@@ -68,6 +70,7 @@
assertSame(mCursor, adapter.getCursor());
}
+ @UiThreadTest
public void testSetViewResource() {
mResourceCursorAdapter = new MockResourceCursorAdapter(mContext,
R.layout.cursoradapter_item0, mCursor);
@@ -83,6 +86,7 @@
assertEquals(R.id.cursorAdapter_item1, result.getId());
}
+ @UiThreadTest
public void testSetDropDownViewResource() {
mResourceCursorAdapter = new MockResourceCursorAdapter(mContext,
R.layout.cursoradapter_item0, mCursor);
@@ -107,6 +111,7 @@
}
// parameters Context and Cursor are never readin the method
+ @UiThreadTest
public void testNewDropDownView() {
mResourceCursorAdapter = new MockResourceCursorAdapter(mContext,
R.layout.cursoradapter_item0, mCursor);
@@ -122,6 +127,7 @@
}
// The parameters Context and Cursor are never read in the method
+ @UiThreadTest
public void testNewView() {
mResourceCursorAdapter = new MockResourceCursorAdapter(mContext,
R.layout.cursoradapter_item0, mCursor);
diff --git a/tests/tests/widget/src/android/widget/cts/ResourceCursorTreeAdapterTest.java b/tests/tests/widget/src/android/widget/cts/ResourceCursorTreeAdapterTest.java
index 4f137a0..760f7e4 100644
--- a/tests/tests/widget/src/android/widget/cts/ResourceCursorTreeAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ResourceCursorTreeAdapterTest.java
@@ -23,6 +23,7 @@
import android.database.Cursor;
import android.database.MatrixCursor;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -71,6 +72,7 @@
mParent = (ViewGroup) layoutInflater.inflate(R.layout.cursoradapter_host, null);
}
+ @UiThreadTest
public void testConstructor() {
mResourceCursorTreeAdapter = new MockResourceCursorTreeAdapter(mContext, null,
mGroupLayout, mChildLayout);
@@ -95,6 +97,7 @@
}
// The parameters Context and Cursor are never readin the method
+ @UiThreadTest
public void testNewChildView() {
mResourceCursorTreeAdapter = new MockResourceCursorTreeAdapter(mContext, null,
mGroupLayout, mChildLayout);
@@ -116,6 +119,7 @@
}
// The parameters Context and Cursor are never readin the method
+ @UiThreadTest
public void testNewGroupView() {
mResourceCursorTreeAdapter = new MockResourceCursorTreeAdapter(mContext, null,
mGroupLayout, mChildLayout);
diff --git a/tests/tests/widget/src/android/widget/cts/SimpleAdapterTest.java b/tests/tests/widget/src/android/widget/cts/SimpleAdapterTest.java
index 86a4bca..90ff617 100644
--- a/tests/tests/widget/src/android/widget/cts/SimpleAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/SimpleAdapterTest.java
@@ -23,6 +23,7 @@
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
@@ -342,6 +343,7 @@
assertEquals("", view.getText().toString());
}
+ @UiThreadTest
public void testGetFilter() {
assertNotNull(mSimpleAdapter.getFilter());
}
diff --git a/tests/tests/widget/src/android/widget/cts/SimpleCursorAdapterTest.java b/tests/tests/widget/src/android/widget/cts/SimpleCursorAdapterTest.java
index 2d73a03..f19dce7 100644
--- a/tests/tests/widget/src/android/widget/cts/SimpleCursorAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/SimpleCursorAdapterTest.java
@@ -25,6 +25,7 @@
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -41,6 +42,9 @@
/**
* Test {@link SimpleCursorAdapter}.
+ * The simple cursor adapter's cursor will be set to
+ * {@link SimpleCursorAdapterTest#mCursor} It will use internal
+ * R.layout.simple_list_item_1.
*/
public class SimpleCursorAdapterTest extends InstrumentationTestCase {
private static final int ADAPTER_ROW_COUNT = 20;
@@ -53,13 +57,6 @@
private static final String SAMPLE_IMAGE_NAME = "testimage.jpg";
- /**
- * The simple cursor adapter. Its cursor will be set to
- * {@link SimpleCursorAdapterTest#mCursor} It will use internal
- * R.layout.simple_list_item_1.
- */
- private SimpleCursorAdapter mSimpleCursorAdapter;
-
private Context mContext;
/**
@@ -96,89 +93,101 @@
mContext = getInstrumentation().getTargetContext();
mCursor = createTestCursor(DEFAULT_COLUMN_COUNT, ADAPTER_ROW_COUNT);
- mSimpleCursorAdapter = new SimpleCursorAdapter(mContext, R.layout.cursoradapter_item0,
- mCursor, COLUMNS_FROM, VIEWS_TO);
}
+ private SimpleCursorAdapter makeSimpleCursorAdapter() {
+ return new SimpleCursorAdapter(
+ mContext, R.layout.cursoradapter_item0, mCursor, COLUMNS_FROM, VIEWS_TO);
+ }
+
+ @UiThreadTest
public void testConstructor() {
new SimpleCursorAdapter(mContext, R.layout.cursoradapter_item0,
createTestCursor(DEFAULT_COLUMN_COUNT, ADAPTER_ROW_COUNT),
COLUMNS_FROM, VIEWS_TO);
}
+ @UiThreadTest
public void testBindView() {
- TextView listItem = (TextView) mSimpleCursorAdapter.newView(mContext, null, null);
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
+ TextView listItem = (TextView) simpleCursorAdapter.newView(mContext, null, null);
listItem.setText("");
mCursor.moveToFirst();
- mSimpleCursorAdapter.bindView(listItem, null, mCursor);
+ simpleCursorAdapter.bindView(listItem, null, mCursor);
assertEquals("01", listItem.getText().toString());
mCursor.moveToLast();
- mSimpleCursorAdapter.bindView(listItem, null, mCursor);
+ simpleCursorAdapter.bindView(listItem, null, mCursor);
assertEquals("191", listItem.getText().toString());
// the binder take care of binding
listItem.setText("");
MockViewBinder binder = new MockViewBinder(true);
- mSimpleCursorAdapter.setViewBinder(binder);
+ simpleCursorAdapter.setViewBinder(binder);
binder.reset();
mCursor.moveToFirst();
- mSimpleCursorAdapter.bindView(listItem, null, mCursor);
+ simpleCursorAdapter.bindView(listItem, null, mCursor);
assertTrue(binder.hasCalledSetViewValueCalledCount());
assertEquals("", listItem.getText().toString());
// the binder try to bind but fail
binder = new MockViewBinder(false);
- mSimpleCursorAdapter.setViewBinder(binder);
+ simpleCursorAdapter.setViewBinder(binder);
mCursor.moveToLast();
- mSimpleCursorAdapter.bindView(listItem, null, mCursor);
+ simpleCursorAdapter.bindView(listItem, null, mCursor);
assertTrue(binder.hasCalledSetViewValueCalledCount());
assertEquals("191", listItem.getText().toString());
final int [] to = { R.id.cursorAdapter_host };
- mSimpleCursorAdapter = new SimpleCursorAdapter(mContext, R.layout.cursoradapter_host,
+ simpleCursorAdapter = new SimpleCursorAdapter(mContext, R.layout.cursoradapter_host,
mCursor, COLUMNS_FROM, to);
- LinearLayout illegalView = (LinearLayout)mSimpleCursorAdapter.newView(mContext, null, null);
+ LinearLayout illegalView = (LinearLayout)simpleCursorAdapter.newView(mContext, null, null);
try {
// The IllegalStateException already gets thrown in the line above.
- mSimpleCursorAdapter.bindView(illegalView, null, mCursor);
+ simpleCursorAdapter.bindView(illegalView, null, mCursor);
fail("Should throw IllegalStateException if the view is not TextView or ImageView");
} catch (IllegalStateException e) {
// expected
}
}
+ @UiThreadTest
public void testAccessViewBinder() {
- assertNull(mSimpleCursorAdapter.getViewBinder());
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
+ assertNull(simpleCursorAdapter.getViewBinder());
MockViewBinder binder = new MockViewBinder(true);
- mSimpleCursorAdapter.setViewBinder(binder);
- assertSame(binder, mSimpleCursorAdapter.getViewBinder());
+ simpleCursorAdapter.setViewBinder(binder);
+ assertSame(binder, simpleCursorAdapter.getViewBinder());
binder = new MockViewBinder(false);
- mSimpleCursorAdapter.setViewBinder(binder);
- assertSame(binder, mSimpleCursorAdapter.getViewBinder());
+ simpleCursorAdapter.setViewBinder(binder);
+ assertSame(binder, simpleCursorAdapter.getViewBinder());
- mSimpleCursorAdapter.setViewBinder(null);
- assertNull(mSimpleCursorAdapter.getViewBinder());
+ simpleCursorAdapter.setViewBinder(null);
+ assertNull(simpleCursorAdapter.getViewBinder());
}
+ @UiThreadTest
public void testSetViewText() {
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
TextView view = new TextView(mContext);
- mSimpleCursorAdapter.setViewText(view, "expected");
+ simpleCursorAdapter.setViewText(view, "expected");
assertEquals("expected", view.getText().toString());
- mSimpleCursorAdapter.setViewText(view, null);
+ simpleCursorAdapter.setViewText(view, null);
assertEquals("", view.getText().toString());
}
+ @UiThreadTest
public void testSetViewImage() {
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
// resId
int sceneryImgResId = com.android.cts.widget.R.drawable.scenery;
ImageView view = new ImageView(mContext);
assertNull(view.getDrawable());
- mSimpleCursorAdapter.setViewImage(view, String.valueOf(sceneryImgResId));
+ simpleCursorAdapter.setViewImage(view, String.valueOf(sceneryImgResId));
assertNotNull(view.getDrawable());
BitmapDrawable d = (BitmapDrawable) mContext.getResources().getDrawable(
sceneryImgResId);
@@ -188,7 +197,7 @@
// blank
view = new ImageView(mContext);
assertNull(view.getDrawable());
- mSimpleCursorAdapter.setViewImage(view, "");
+ simpleCursorAdapter.setViewImage(view, "");
assertNull(view.getDrawable());
// null
@@ -196,7 +205,7 @@
assertNull(view.getDrawable());
try {
// Should declare NullPoinertException if the uri or value is null
- mSimpleCursorAdapter.setViewImage(view, null);
+ simpleCursorAdapter.setViewImage(view, null);
fail("Should throw NullPointerException if the uri or value is null");
} catch (NullPointerException e) {
// expected
@@ -207,7 +216,7 @@
assertNull(view.getDrawable());
try {
int testimgRawId = com.android.cts.widget.R.raw.testimage;
- mSimpleCursorAdapter.setViewImage(view,
+ simpleCursorAdapter.setViewImage(view,
createTestImage(mContext, SAMPLE_IMAGE_NAME, testimgRawId));
assertNotNull(view.getDrawable());
Bitmap actualBitmap = ((BitmapDrawable) view.getDrawable()).getBitmap();
@@ -219,44 +228,50 @@
}
}
+ @UiThreadTest
public void testAccessStringConversionColumn() {
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
// default is -1
- assertEquals(-1, mSimpleCursorAdapter.getStringConversionColumn());
+ assertEquals(-1, simpleCursorAdapter.getStringConversionColumn());
- mSimpleCursorAdapter.setStringConversionColumn(1);
- assertEquals(1, mSimpleCursorAdapter.getStringConversionColumn());
+ simpleCursorAdapter.setStringConversionColumn(1);
+ assertEquals(1, simpleCursorAdapter.getStringConversionColumn());
// Should check whether the column index is out of bounds
- mSimpleCursorAdapter.setStringConversionColumn(Integer.MAX_VALUE);
- assertEquals(Integer.MAX_VALUE, mSimpleCursorAdapter.getStringConversionColumn());
+ simpleCursorAdapter.setStringConversionColumn(Integer.MAX_VALUE);
+ assertEquals(Integer.MAX_VALUE, simpleCursorAdapter.getStringConversionColumn());
// Should check whether the column index is out of bounds
- mSimpleCursorAdapter.setStringConversionColumn(Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, mSimpleCursorAdapter.getStringConversionColumn());
+ simpleCursorAdapter.setStringConversionColumn(Integer.MIN_VALUE);
+ assertEquals(Integer.MIN_VALUE, simpleCursorAdapter.getStringConversionColumn());
}
+ @UiThreadTest
public void testAccessCursorToStringConverter() {
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
// default is null
- assertNull(mSimpleCursorAdapter.getCursorToStringConverter());
+ assertNull(simpleCursorAdapter.getCursorToStringConverter());
CursorToStringConverter converter = new MockCursorToStringConverter();
- mSimpleCursorAdapter.setCursorToStringConverter(converter);
- assertSame(converter, mSimpleCursorAdapter.getCursorToStringConverter());
+ simpleCursorAdapter.setCursorToStringConverter(converter);
+ assertSame(converter, simpleCursorAdapter.getCursorToStringConverter());
- mSimpleCursorAdapter.setCursorToStringConverter(null);
- assertNull(mSimpleCursorAdapter.getCursorToStringConverter());
+ simpleCursorAdapter.setCursorToStringConverter(null);
+ assertNull(simpleCursorAdapter.getCursorToStringConverter());
}
+ @UiThreadTest
public void testChangeCursor() {
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
// have "column1"
Cursor curWith3Columns = createTestCursor(3, ADAPTER_ROW_COUNT);
- mSimpleCursorAdapter.changeCursor(curWith3Columns);
- assertSame(curWith3Columns, mSimpleCursorAdapter.getCursor());
+ simpleCursorAdapter.changeCursor(curWith3Columns);
+ assertSame(curWith3Columns, simpleCursorAdapter.getCursor());
// does not have "column1"
Cursor curWith1Column = createTestCursor(1, ADAPTER_ROW_COUNT);
try {
- mSimpleCursorAdapter.changeCursor(curWith1Column);
+ simpleCursorAdapter.changeCursor(curWith1Column);
fail("Should throw exception if the cursor does not have the "
+ "original column passed in the constructor");
} catch (IllegalArgumentException e) {
@@ -264,23 +279,25 @@
}
}
+ @UiThreadTest
public void testConvertToString() {
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
mCursor.moveToFirst();
- assertEquals("", mSimpleCursorAdapter.convertToString(null));
+ assertEquals("", simpleCursorAdapter.convertToString(null));
// converter is null, StringConversionColumn is set to negative
- mSimpleCursorAdapter.setStringConversionColumn(Integer.MIN_VALUE);
- assertEquals(mCursor.toString(), mSimpleCursorAdapter.convertToString(mCursor));
+ simpleCursorAdapter.setStringConversionColumn(Integer.MIN_VALUE);
+ assertEquals(mCursor.toString(), simpleCursorAdapter.convertToString(mCursor));
// converter is null, StringConversionColumn is set to 1
- mSimpleCursorAdapter.setStringConversionColumn(1);
- assertEquals("01", mSimpleCursorAdapter.convertToString(mCursor));
+ simpleCursorAdapter.setStringConversionColumn(1);
+ assertEquals("01", simpleCursorAdapter.convertToString(mCursor));
// converter is null, StringConversionColumn is set to 3 (larger than columns count)
// the cursor has 3 columns including column0, column1 and _id which is added automatically
- mSimpleCursorAdapter.setStringConversionColumn(DEFAULT_COLUMN_COUNT + 1);
+ simpleCursorAdapter.setStringConversionColumn(DEFAULT_COLUMN_COUNT + 1);
try {
- mSimpleCursorAdapter.convertToString(mCursor);
+ simpleCursorAdapter.convertToString(mCursor);
fail("Should throw IndexOutOfBoundsException if index is beyond the columns count");
} catch (IndexOutOfBoundsException e) {
// expected
@@ -291,69 +308,75 @@
// converter is null, StringConversionColumn is set to 3
// and covert with a cursor which has 4 columns
- mSimpleCursorAdapter.setStringConversionColumn(2);
- assertEquals("02", mSimpleCursorAdapter.convertToString(curWith3Columns));
+ simpleCursorAdapter.setStringConversionColumn(2);
+ assertEquals("02", simpleCursorAdapter.convertToString(curWith3Columns));
// converter is not null, StringConversionColumn is 1
CursorToStringConverter converter = new MockCursorToStringConverter();
- mSimpleCursorAdapter.setCursorToStringConverter(converter);
- mSimpleCursorAdapter.setStringConversionColumn(1);
+ simpleCursorAdapter.setCursorToStringConverter(converter);
+ simpleCursorAdapter.setStringConversionColumn(1);
((MockCursorToStringConverter) converter).reset();
- mSimpleCursorAdapter.convertToString(curWith3Columns);
+ simpleCursorAdapter.convertToString(curWith3Columns);
assertTrue(((MockCursorToStringConverter) converter).hasCalledConvertToString());
}
+ @UiThreadTest
public void testNewView() {
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
ViewGroup viewGroup = (ViewGroup) layoutInflater.inflate(
com.android.cts.widget.R.layout.cursoradapter_host, null);
- View result = mSimpleCursorAdapter.newView(mContext, null, viewGroup);
+ View result = simpleCursorAdapter.newView(mContext, null, viewGroup);
assertNotNull(result);
assertEquals(R.id.cursorAdapter_item0, result.getId());
- result = mSimpleCursorAdapter.newView(mContext, null, null);
+ result = simpleCursorAdapter.newView(mContext, null, null);
assertNotNull(result);
assertEquals(R.id.cursorAdapter_item0, result.getId());
}
+ @UiThreadTest
public void testNewDropDownView() {
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
ViewGroup viewGroup = (ViewGroup) layoutInflater.inflate(
com.android.cts.widget.R.layout.cursoradapter_host, null);
- View result = mSimpleCursorAdapter.newDropDownView(null, null, viewGroup);
+ View result = simpleCursorAdapter.newDropDownView(null, null, viewGroup);
assertNotNull(result);
assertEquals(R.id.cursorAdapter_item0, result.getId());
}
+ @UiThreadTest
public void testChangeCursorAndColumns() {
- assertSame(mCursor, mSimpleCursorAdapter.getCursor());
+ SimpleCursorAdapter simpleCursorAdapter = makeSimpleCursorAdapter();
+ assertSame(mCursor, simpleCursorAdapter.getCursor());
- TextView listItem = (TextView) mSimpleCursorAdapter.newView(mContext, null, null);
+ TextView listItem = (TextView) simpleCursorAdapter.newView(mContext, null, null);
mCursor.moveToFirst();
- mSimpleCursorAdapter.bindView(listItem, null, mCursor);
+ simpleCursorAdapter.bindView(listItem, null, mCursor);
assertEquals("01", listItem.getText().toString());
mCursor.moveToLast();
- mSimpleCursorAdapter.bindView(listItem, null, mCursor);
+ simpleCursorAdapter.bindView(listItem, null, mCursor);
assertEquals("191", listItem.getText().toString());
Cursor newCursor = createTestCursor(3, ADAPTER_ROW_COUNT);
final String[] from = new String[] { "column2" };
- mSimpleCursorAdapter.changeCursorAndColumns(newCursor, from, VIEWS_TO);
- assertSame(newCursor, mSimpleCursorAdapter.getCursor());
+ simpleCursorAdapter.changeCursorAndColumns(newCursor, from, VIEWS_TO);
+ assertSame(newCursor, simpleCursorAdapter.getCursor());
newCursor.moveToFirst();
- mSimpleCursorAdapter.bindView(listItem, null, newCursor);
+ simpleCursorAdapter.bindView(listItem, null, newCursor);
assertEquals("02", listItem.getText().toString());
newCursor.moveToLast();
- mSimpleCursorAdapter.bindView(listItem, null, newCursor);
+ simpleCursorAdapter.bindView(listItem, null, newCursor);
assertEquals("192", listItem.getText().toString());
- mSimpleCursorAdapter.changeCursorAndColumns(null, null, null);
- assertNull(mSimpleCursorAdapter.getCursor());
+ simpleCursorAdapter.changeCursorAndColumns(null, null, null);
+ assertNull(simpleCursorAdapter.getCursor());
}
/**
diff --git a/tests/tests/widget/src/android/widget/cts/SimpleCursorTreeAdapterTest.java b/tests/tests/widget/src/android/widget/cts/SimpleCursorTreeAdapterTest.java
index 9085b55..0db5322 100644
--- a/tests/tests/widget/src/android/widget/cts/SimpleCursorTreeAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/SimpleCursorTreeAdapterTest.java
@@ -25,6 +25,7 @@
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.view.View;
import android.widget.ImageView;
import android.widget.SimpleCursorTreeAdapter;
@@ -70,6 +71,7 @@
mContext = getInstrumentation().getTargetContext();
}
+ @UiThreadTest
public void testConstructor() {
mGroupCursor = createTestCursor(2, 20, "group");
new MockSimpleCursorTreeAdapter(mContext, mGroupCursor,
@@ -85,6 +87,7 @@
CHILD_LAYOUT, CHILD_LAYOUT, COLUMNS_CHILD_FROM, VIEWS_CHILD_TO);
}
+ @UiThreadTest
public void testBindChildView() {
mGroupCursor = createTestCursor(2, 20, "group");
mChildCursor = createTestCursor(3, 4, "child");
@@ -104,6 +107,7 @@
}
// The param context and isExpanded is never readed.
+ @UiThreadTest
public void testBindGroupView() {
mGroupCursor = createTestCursor(2, 20, "group");
mGroupCursor.moveToFirst();
@@ -120,6 +124,7 @@
assertEquals("group11", view.getText().toString());
}
+ @UiThreadTest
public void testSetViewImage() {
mGroupCursor = createTestCursor(2, 20, "group");
mSimpleCursorTreeAdapter = new MockSimpleCursorTreeAdapter(mContext, mGroupCursor,
diff --git a/tests/tests/widget/src/android/widget/cts/SlidingDrawerTest.java b/tests/tests/widget/src/android/widget/cts/SlidingDrawerTest.java
index c4aaca1..862fccf 100644
--- a/tests/tests/widget/src/android/widget/cts/SlidingDrawerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/SlidingDrawerTest.java
@@ -61,6 +61,7 @@
mLock = new Object();
}
+ @UiThreadTest
public void testConstructor() throws XmlPullParserException, IOException {
XmlPullParser parser = mActivity.getResources().getLayout(R.layout.sliding_drawer_layout);
AttributeSet attrs = Xml.asAttributeSet(parser);
diff --git a/tests/tests/widget/src/android/widget/cts/SpinnerTest.java b/tests/tests/widget/src/android/widget/cts/SpinnerTest.java
index 7a2de0c..1989626 100644
--- a/tests/tests/widget/src/android/widget/cts/SpinnerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/SpinnerTest.java
@@ -44,6 +44,7 @@
mTargetContext = getInstrumentation().getTargetContext();
}
+ @UiThreadTest
public void testConstructor() {
new Spinner(mTargetContext);
@@ -69,6 +70,7 @@
assertTrue(spinner.getBaseline() > 0);
}
+ @UiThreadTest
public void testSetOnItemClickListener() {
Spinner spinner = new Spinner(mTargetContext);
@@ -89,6 +91,7 @@
// Or do UI check?
}
+ @UiThreadTest
public void testOnClick() {
Spinner spinner = new Spinner(mTargetContext);
// normal value
@@ -129,7 +132,8 @@
// TODO: find the dialog and get its title to assert whether setPrompt() takes effect?
}
- public void testsetPromptId() {
+ @UiThreadTest
+ public void testSetPromptId() {
Spinner spinner = new Spinner(mTargetContext);
spinner.setPromptId(R.string.hello_world);
diff --git a/tests/tests/widget/src/android/widget/cts/ToastTest.java b/tests/tests/widget/src/android/widget/cts/ToastTest.java
index 055b874..90a161e 100644
--- a/tests/tests/widget/src/android/widget/cts/ToastTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ToastTest.java
@@ -53,7 +53,6 @@
mActivity = getActivity();
mInstrumentation = getInstrumentation();
- mToast = new Toast(mActivity);
mLayoutDone = false;
mLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
@@ -62,6 +61,7 @@
};
}
+ @UiThreadTest
public void testConstructor() {
new Toast(mActivity);
@@ -113,13 +113,17 @@
view.getViewTreeObserver().removeOnGlobalLayoutListener(mLayoutListener);
}
- public void testShow() {
+ private void makeToast() {
mActivity.runOnUiThread(new Runnable() {
public void run() {
mToast = Toast.makeText(mActivity, TEST_TOAST_TEXT, Toast.LENGTH_LONG);
}
});
mInstrumentation.waitForIdleSync();
+ }
+
+ public void testShow() {
+ makeToast();
final View view = mToast.getView();
@@ -141,10 +145,11 @@
@UiThreadTest
public void testShowFailure() {
+ Toast toast = new Toast(mActivity);
// do not have any views.
- assertNull(mToast.getView());
+ assertNull(toast.getView());
try {
- mToast.show();
+ toast.show();
fail("did not throw RuntimeException when did not set any views.");
} catch (RuntimeException e) {
// expected, test success.
@@ -152,12 +157,7 @@
}
public void testCancel() throws InterruptedException {
- mActivity.runOnUiThread(new Runnable() {
- public void run() {
- mToast = Toast.makeText(mActivity, TEST_TOAST_TEXT, Toast.LENGTH_LONG);
- }
- });
- mInstrumentation.waitForIdleSync();
+ makeToast();
final View view = mToast.getView();
@@ -175,12 +175,7 @@
}
public void testAccessView() {
- mActivity.runOnUiThread(new Runnable() {
- public void run() {
- mToast = Toast.makeText(mActivity, TEST_TOAST_TEXT, Toast.LENGTH_LONG);
- }
- });
- mInstrumentation.waitForIdleSync();
+ makeToast();
assertFalse(mToast.getView() instanceof ImageView);
final ImageView imageView = new ImageView(mActivity);
@@ -197,11 +192,12 @@
assertSame(imageView, mToast.getView());
assertShowAndHide(imageView);
}
+
public void testAccessDuration() {
long start = SystemClock.uptimeMillis();
+ makeToast();
mActivity.runOnUiThread(new Runnable() {
public void run() {
- mToast = Toast.makeText(mActivity, TEST_TOAST_TEXT, Toast.LENGTH_LONG);
mToast.show();
}
});
@@ -230,12 +226,7 @@
}
public void testAccessMargin() {
- mActivity.runOnUiThread(new Runnable() {
- public void run() {
- mToast = Toast.makeText(mActivity, TEST_TOAST_TEXT, Toast.LENGTH_SHORT);
- }
- });
- mInstrumentation.waitForIdleSync();
+ makeToast();
View view = mToast.getView();
assertFalse(view.getLayoutParams() instanceof WindowManager.LayoutParams);
@@ -289,9 +280,9 @@
}
public void testAccessGravity() {
+ makeToast();
mActivity.runOnUiThread(new Runnable() {
public void run() {
- mToast = Toast.makeText(mActivity, TEST_TOAST_TEXT, Toast.LENGTH_SHORT);
mToast.setGravity(Gravity.CENTER, 0, 0);
mToast.show();
registerLayoutListener(mToast.getView());
@@ -357,26 +348,26 @@
@UiThreadTest
public void testMakeText1() {
- mToast = Toast.makeText(mActivity, "android", Toast.LENGTH_SHORT);
- assertNotNull(mToast);
- assertEquals(Toast.LENGTH_SHORT, mToast.getDuration());
- View view = mToast.getView();
+ Toast toast = Toast.makeText(mActivity, "android", Toast.LENGTH_SHORT);
+ assertNotNull(toast);
+ assertEquals(Toast.LENGTH_SHORT, toast.getDuration());
+ View view = toast.getView();
assertNotNull(view);
- mToast = Toast.makeText(mActivity, "cts", Toast.LENGTH_LONG);
- assertNotNull(mToast);
- assertEquals(Toast.LENGTH_LONG, mToast.getDuration());
- view = mToast.getView();
+ toast = Toast.makeText(mActivity, "cts", Toast.LENGTH_LONG);
+ assertNotNull(toast);
+ assertEquals(Toast.LENGTH_LONG, toast.getDuration());
+ view = toast.getView();
assertNotNull(view);
- mToast = Toast.makeText(mActivity, null, Toast.LENGTH_LONG);
- assertNotNull(mToast);
- assertEquals(Toast.LENGTH_LONG, mToast.getDuration());
- view = mToast.getView();
+ toast = Toast.makeText(mActivity, null, Toast.LENGTH_LONG);
+ assertNotNull(toast);
+ assertEquals(Toast.LENGTH_LONG, toast.getDuration());
+ view = toast.getView();
assertNotNull(view);
try {
- mToast = Toast.makeText(null, "test", Toast.LENGTH_LONG);
+ toast = Toast.makeText(null, "test", Toast.LENGTH_LONG);
fail("did not throw NullPointerException when context is null.");
} catch (NullPointerException e) {
//expected, test success.
@@ -385,21 +376,21 @@
@UiThreadTest
public void testMakeText2() {
- mToast = Toast.makeText(mActivity, R.string.hello_world, Toast.LENGTH_LONG);
+ Toast toast = Toast.makeText(mActivity, R.string.hello_world, Toast.LENGTH_LONG);
- assertNotNull(mToast);
- assertEquals(Toast.LENGTH_LONG, mToast.getDuration());
- View view = mToast.getView();
+ assertNotNull(toast);
+ assertEquals(Toast.LENGTH_LONG, toast.getDuration());
+ View view = toast.getView();
assertNotNull(view);
- mToast = Toast.makeText(mActivity, R.string.hello_android, Toast.LENGTH_SHORT);
- assertNotNull(mToast);
- assertEquals(Toast.LENGTH_SHORT, mToast.getDuration());
- view = mToast.getView();
+ toast = Toast.makeText(mActivity, R.string.hello_android, Toast.LENGTH_SHORT);
+ assertNotNull(toast);
+ assertEquals(Toast.LENGTH_SHORT, toast.getDuration());
+ view = toast.getView();
assertNotNull(view);
try {
- mToast = Toast.makeText(null, R.string.hello_android, Toast.LENGTH_SHORT);
+ toast = Toast.makeText(null, R.string.hello_android, Toast.LENGTH_SHORT);
fail("did not throw NullPointerException when context is null.");
} catch (NullPointerException e) {
//expected, test success.
@@ -408,16 +399,16 @@
@UiThreadTest
public void testSetText1() {
- mToast = Toast.makeText(mActivity, R.string.text, Toast.LENGTH_LONG);
+ Toast toast = Toast.makeText(mActivity, R.string.text, Toast.LENGTH_LONG);
- mToast.setText(R.string.hello_world);
+ toast.setText(R.string.hello_world);
// TODO: how to getText to assert?
- mToast.setText(R.string.hello_android);
+ toast.setText(R.string.hello_android);
// TODO: how to getText to assert?
try {
- mToast.setText(-1);
+ toast.setText(-1);
fail("did not throw RuntimeException when resource id is negative.");
} catch (RuntimeException e) {
//expected, test success.
@@ -426,17 +417,17 @@
@UiThreadTest
public void testSetText2() {
- mToast = Toast.makeText(mActivity, R.string.text, Toast.LENGTH_LONG);
+ Toast toast = Toast.makeText(mActivity, R.string.text, Toast.LENGTH_LONG);
- mToast.setText("cts");
+ toast.setText("cts");
// TODO: how to getText to assert?
- mToast.setText("android");
+ toast.setText("android");
// TODO: how to getText to assert?
try {
- mToast.setView(null);
- mToast.setText(null);
+ toast.setView(null);
+ toast.setText(null);
fail("did not throw RuntimeException when view is null.");
} catch (RuntimeException e) {
//expected, test success.
diff --git a/tests/tests/widget/src/android/widget/cts/ToggleButtonTest.java b/tests/tests/widget/src/android/widget/cts/ToggleButtonTest.java
index d5b74c3..b3bc31e 100644
--- a/tests/tests/widget/src/android/widget/cts/ToggleButtonTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ToggleButtonTest.java
@@ -21,7 +21,8 @@
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
-import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.test.UiThreadTest;
import android.util.AttributeSet;
import android.util.Xml;
import android.widget.ToggleButton;
@@ -32,7 +33,7 @@
/**
* Test {@link ToggleButton}.
*/
-public class ToggleButtonTest extends AndroidTestCase {
+public class ToggleButtonTest extends InstrumentationTestCase {
private static final String TEXT_OFF = "text off";
private static final String TEXT_ON = "text on";
ToggleButton mToggleButton;
@@ -43,7 +44,7 @@
protected void setUp() throws Exception {
super.setUp();
- mContext = getContext();
+ mContext = getInstrumentation().getTargetContext();
XmlPullParser parser = mContext.getResources().getXml(R.layout.togglebutton_layout);
mAttrSet = Xml.asAttributeSet(parser);
mToggleButton = new ToggleButton(mContext, mAttrSet);
@@ -88,6 +89,7 @@
assertEquals("", mToggleButton.getTextOff());
}
+ @UiThreadTest
public void testDrawableStateChanged() {
MockToggleButton toggleButton = new MockToggleButton(mContext);
@@ -111,6 +113,7 @@
toggleButton.onFinishInflate();
}
+ @UiThreadTest
public void testSetChecked() {
assertFalse(mToggleButton.isChecked());
@@ -121,6 +124,7 @@
assertFalse(mToggleButton.isChecked());
}
+ @UiThreadTest
public void testToggleText() {
mToggleButton.setText("default text");
mToggleButton.setTextOn(TEXT_ON);
diff --git a/tests/tests/widget/src/android/widget/cts/VideoViewTest.java b/tests/tests/widget/src/android/widget/cts/VideoViewTest.java
index 79b10df..6e514f8 100644
--- a/tests/tests/widget/src/android/widget/cts/VideoViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/VideoViewTest.java
@@ -29,6 +29,7 @@
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.test.ActivityInstrumentationTestCase2;
+import android.test.UiThreadTest;
import android.util.Log;
import android.view.View.MeasureSpec;
import android.widget.MediaController;
@@ -62,7 +63,6 @@
private Activity mActivity;
private Instrumentation mInstrumentation;
private String mVideoPath;
- private MediaController mMediaController;
private static class MockListener {
private boolean mTriggered;
@@ -180,10 +180,19 @@
mVideoPath = prepareSampleVideo();
assertNotNull(mVideoPath);
mVideoView = findVideoViewById(R.id.videoview);
- mMediaController = new MediaController(mActivity);
- mVideoView.setMediaController(mMediaController);
}
+ private void makeVideoView() {
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ MediaController mediaController = new MediaController(mActivity);
+ mVideoView.setMediaController(mediaController);
+ }
+ });
+ mInstrumentation.waitForIdleSync();
+ }
+
+ @UiThreadTest
public void testConstructor() {
new VideoView(mActivity);
@@ -193,6 +202,7 @@
}
public void testPlayVideo1() throws Throwable {
+ makeVideoView();
// Don't run the test if the codec isn't supported.
if (!hasCodec(MIME_TYPE)) {
Log.w(TAG, "Codec " + MIME_TYPE + " not supported. Return from testPlayVideo1.");
@@ -232,6 +242,7 @@
}
public void testSetOnErrorListener() throws Throwable {
+ makeVideoView();
final MockOnErrorListener listener = new MockOnErrorListener();
mVideoView.setOnErrorListener(listener);
@@ -253,6 +264,7 @@
}
public void testGetBufferPercentage() throws Throwable {
+ makeVideoView();
// Don't run the test if the codec isn't supported.
if (!hasCodec(MIME_TYPE)) {
Log.w(TAG, MIME_TYPE + " not supported. Return from testGetBufferPercentage.");
@@ -279,6 +291,7 @@
assertTrue(percent >= 0 && percent <= 100);
}
+ @UiThreadTest
public void testResolveAdjustedSize() {
mVideoView = new VideoView(mActivity);
@@ -310,6 +323,7 @@
assertTrue(Math.abs(mVideoView.getDuration() - TEST_VIDEO_DURATION) < DURATION_DELTA);
}
+ @UiThreadTest
public void testSetMediaController() {
final MediaController ctlr = new MediaController(mActivity);
mVideoView.setMediaController(ctlr);
diff --git a/tests/tests/widget/src/android/widget/cts/ViewFlipperTest.java b/tests/tests/widget/src/android/widget/cts/ViewFlipperTest.java
index ac06def..025fae4 100644
--- a/tests/tests/widget/src/android/widget/cts/ViewFlipperTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ViewFlipperTest.java
@@ -23,6 +23,7 @@
import android.app.Activity;
import android.test.ActivityInstrumentationTestCase;
+import android.test.UiThreadTest;
import android.util.AttributeSet;
import android.util.Xml;
import android.view.View;
@@ -45,6 +46,7 @@
assertNotNull(mActivity);
}
+ @UiThreadTest
public void testConstructor() {
new ViewFlipper(mActivity);
@@ -61,6 +63,7 @@
}
}
+ @UiThreadTest
public void testSetFlipInterval() {
ViewFlipper viewFlipper = new ViewFlipper(mActivity);
viewFlipper.setFlipInterval(0);
diff --git a/tests/tests/widget/src/android/widget/cts/ZoomButtonTest.java b/tests/tests/widget/src/android/widget/cts/ZoomButtonTest.java
index 47bcfed..3d906db 100644
--- a/tests/tests/widget/src/android/widget/cts/ZoomButtonTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ZoomButtonTest.java
@@ -48,6 +48,7 @@
mActivity = getActivity();
}
+ @UiThreadTest
public void testConstructor() {
new ZoomButton(mActivity);
diff --git a/tests/tests/widget/src/android/widget/cts/ZoomControlsTest.java b/tests/tests/widget/src/android/widget/cts/ZoomControlsTest.java
index 5dc7a0e..9b3ffba 100644
--- a/tests/tests/widget/src/android/widget/cts/ZoomControlsTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ZoomControlsTest.java
@@ -36,12 +36,14 @@
mContext = getInstrumentation().getContext();
}
+ @UiThreadTest
public void testConstructor() {
new ZoomControls(mContext);
new ZoomControls(mContext, null);
}
+ @UiThreadTest
public void testSetOnZoomInClickListener() {
ZoomControls zoomControls = new ZoomControls(mContext);
@@ -59,6 +61,7 @@
}
}
+ @UiThreadTest
public void testSetOnZoomOutClickListener() {
ZoomControls zoomControls = new ZoomControls(mContext);
@@ -70,6 +73,7 @@
zoomControls.setOnZoomOutClickListener(null);
}
+ @UiThreadTest
public void testSetZoomSpeed() {
ZoomControls zoomControls = new ZoomControls(mContext);
@@ -82,6 +86,7 @@
// onTouchEvent() is implementation details, do NOT test
}
+ @UiThreadTest
public void testShowAndHide() {
final ZoomControls zoomControls = new ZoomControls(mContext);
assertEquals(View.VISIBLE, zoomControls.getVisibility());
@@ -93,12 +98,14 @@
assertEquals(View.VISIBLE, zoomControls.getVisibility());
}
+ @UiThreadTest
public void testSetIsZoomInEnabled() {
ZoomControls zoomControls = new ZoomControls(mContext);
zoomControls.setIsZoomInEnabled(false);
zoomControls.setIsZoomInEnabled(true);
}
+ @UiThreadTest
public void testSetIsZoomOutEnabled() {
ZoomControls zoomControls = new ZoomControls(mContext);
zoomControls.setIsZoomOutEnabled(false);
diff --git a/tests/webgl/Android.mk b/tests/webgl/Android.mk
index ce22dd8..624d82a 100755
--- a/tests/webgl/Android.mk
+++ b/tests/webgl/Android.mk
@@ -24,7 +24,8 @@
LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_SRC_FILES := $(call all-java-files-under, src)\
+ ../src/android/webkit/cts/NullWebViewUtils.java
# Must match the package name in CtsTestCaseList.mk
LOCAL_PACKAGE_NAME := CtsWebGLTestCases
diff --git a/tests/webgl/src/android/webgl/WebGLActivity.java b/tests/webgl/src/android/webgl/WebGLActivity.java
index ae1032b..f851a76 100644
--- a/tests/webgl/src/android/webgl/WebGLActivity.java
+++ b/tests/webgl/src/android/webgl/WebGLActivity.java
@@ -24,6 +24,8 @@
import android.webgl.cts.R;
import android.webkit.WebView;
import android.webkit.JavascriptInterface;
+import android.webkit.WebViewClient;
+import android.webkit.cts.NullWebViewUtils;
import android.widget.Toast;
import java.lang.Override;
import java.io.InputStream;
@@ -50,10 +52,25 @@
super.onCreate(icicle);
mWebGlHarnessUrl = "file://" + getCacheDir() + "/harness.html";
- mWebView = new WebView(this);
+ try {
+ mWebView = new WebView(this);
+ } catch (Exception e) {
+ NullWebViewUtils.determineIfWebViewAvailable(this, e);
+ }
+
+ if (mWebView == null) {
+ return;
+ }
+
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
+ mWebView.setWebViewClient(new WebViewClient() {
+ @Override
+ public boolean shouldOverrideUrlLoading(WebView webView, String url) {
+ return false;
+ }
+ });
mWebView.addJavascriptInterface(new Object() {
@JavascriptInterface
@@ -85,6 +102,10 @@
}
public void navigateToTest(String url) throws Exception {
+ if (!NullWebViewUtils.isWebViewAvailable()) {
+ return;
+ }
+
synchronized(WebGLActivity.this) {
mWebGLTestUrl = url;
}
diff --git a/tools/cts-xml-generator/src/Android.mk b/tools/cts-xml-generator/src/Android.mk
index 62f8692..a6d85b6 100644
--- a/tools/cts-xml-generator/src/Android.mk
+++ b/tools/cts-xml-generator/src/Android.mk
@@ -14,12 +14,14 @@
LOCAL_PATH := $(call my-dir)
-
# cts-xml-generator java library
# ============================================================
include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
+LOCAL_SRC_FILES := \
+ $(call all-subdir-java-files) \
+ ../../../libs/commonutil/src/com/android/cts/util/AbiUtils.java
+
LOCAL_JAR_MANIFEST := MANIFEST.mf
LOCAL_MODULE := cts-xml-generator
diff --git a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/CtsXmlGenerator.java b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/CtsXmlGenerator.java
index 37e94ae..384466a 100644
--- a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/CtsXmlGenerator.java
+++ b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/CtsXmlGenerator.java
@@ -36,10 +36,10 @@
private static void usage(String[] args) {
System.err.println("Arguments: " + Arrays.asList(args));
- System.err.println("Usage: cts-xml-generator -p PACKAGE_NAME -n NAME [-t TEST_TYPE]"
- + " [-j JAR_PATH] [-i INSTRUMENTATION] [-m MANIFEST_FILE] [-e EXPECTATION_FILE]"
- + " [-b UNSUPPORTED_ABI_FILE] [-a ARCHITECTURE] [-o OUTPUT_FILE]"
- + " [-n APP_NAME_SPACE] [-x ADDITIONAL_ATTRIBUTE_KEY->VALUE]");
+ System.err.println("Usage: cts-xml-generator -p PACKAGE_NAME -n NAME [-s APP_NAME_SPACE]"
+ + " [-t TEST_TYPE] [-j JAR_PATH] [-i INSTRUMENTATION] [-m MANIFEST_FILE]"
+ + " [-e EXPECTATION_FILE] [-b UNSUPPORTED_ABI_FILE] [-o OUTPUT_FILE]"
+ + " [-x ADDITIONAL_ATTRIBUTE_KEY->VALUE]");
System.exit(1);
}
@@ -49,7 +49,6 @@
String outputPath = null;
Set<File> expectationFiles = new HashSet<File>();
Set<File> abiFiles = new HashSet<File>();
- String architecture = null;
File manifestFile = null;
String instrumentation = null;
String testType = null;
@@ -76,8 +75,6 @@
"Missing value for expectation store")));
} else if ("-b".equals(args[i])) {
abiFiles.add(new File(getArg(args, ++i, "Missing value for abi store")));
- } else if ("-a".equals(args[i])) {
- architecture = getArg(args, ++i, "Missing value for architecture");
} else if ("-o".equals(args[i])) {
outputPath = getArg(args, ++i, "Missing value for output file");
} else if ("-s".equals(args[i])) {
@@ -127,9 +124,9 @@
ExpectationStore failuresStore = ExpectationStore.parse(expectationFiles, ModeId.DEVICE);
ExpectationStore abiStore = ExpectationStore.parse(abiFiles, ModeId.DEVICE);
- XmlGenerator generator = new XmlGenerator(failuresStore, abiStore, architecture,
- appNameSpace, appPackageName, name, runner, instrumentation, targetNameSpace,
- jarPath, testType, outputPath, additionalAttributes);
+ XmlGenerator generator = new XmlGenerator(failuresStore, abiStore, appNameSpace,
+ appPackageName, name, runner, instrumentation, targetNameSpace, jarPath, testType,
+ outputPath, additionalAttributes);
generator.writePackageXml();
}
diff --git a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/XmlGenerator.java b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/XmlGenerator.java
index 59b9fb3..4a56a8e 100644
--- a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/XmlGenerator.java
+++ b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/XmlGenerator.java
@@ -16,6 +16,8 @@
package com.android.cts.xmlgenerator;
+import com.android.cts.util.AbiUtils;
+
import vogar.Expectation;
import vogar.ExpectationStore;
@@ -27,8 +29,6 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
import java.util.Map;
import java.util.List;
import java.util.Set;
@@ -50,29 +50,6 @@
*/
class XmlGenerator {
- private static final Set<String> ARM_ABI = new HashSet<String>();
- private static final Set<String> INTEL_ABI = new HashSet<String>();
- private static final Set<String> MIPS_ABI = new HashSet<String>();
- private static final Set<String> SUPPORTED_ABIS = new HashSet<String>();
- private static final Map<String, Set<String>> ARCH_TO_ABIS = new HashMap<String, Set<String>>();
- static {
- ARM_ABI.add("armeabi-v7a");
- ARM_ABI.add("arm64-v8a");
- INTEL_ABI.add("x86");
- INTEL_ABI.add("x86_64");
- MIPS_ABI.add("mips");
- MIPS_ABI.add("mips64");
- ARCH_TO_ABIS.put("arm", ARM_ABI);
- ARCH_TO_ABIS.put("arm64", ARM_ABI);
- ARCH_TO_ABIS.put("x86", INTEL_ABI);
- ARCH_TO_ABIS.put("x86_64", INTEL_ABI);
- ARCH_TO_ABIS.put("mips", MIPS_ABI);
- ARCH_TO_ABIS.put("mips64", MIPS_ABI);
- SUPPORTED_ABIS.addAll(ARM_ABI);
- SUPPORTED_ABIS.addAll(INTEL_ABI);
- SUPPORTED_ABIS.addAll(MIPS_ABI);
- }
-
/** Example: com.android.cts.holo */
private final String mAppNamespace;
@@ -102,14 +79,12 @@
/** ExpectationStore to filter out unsupported abis. */
private final ExpectationStore mUnsupportedAbis;
- private final String mArchitecture;
-
private final Map<String, String> mAdditionalAttributes;
XmlGenerator(ExpectationStore knownFailures, ExpectationStore unsupportedAbis,
- String architecture, String appNameSpace, String appPackageName, String name,
- String runner, String targetBinaryName, String targetNameSpace, String jarPath,
- String testType, String outputPath, Map<String, String> additionalAttributes) {
+ String appNameSpace, String appPackageName, String name, String runner,
+ String targetBinaryName, String targetNameSpace, String jarPath, String testType,
+ String outputPath, Map<String, String> additionalAttributes) {
mAppNamespace = appNameSpace;
mAppPackageName = appPackageName;
mName = name;
@@ -121,7 +96,6 @@
mOutputPath = outputPath;
mKnownFailures = knownFailures;
mUnsupportedAbis = unsupportedAbis;
- mArchitecture = architecture;
mAdditionalAttributes = additionalAttributes;
}
@@ -228,7 +202,7 @@
String className = nameCollector.toString();
nameCollector.append('#').append(test.getName());
writer.append("<Test name=\"").append(test.getName()).append("\"");
- String abis = getSupportedAbis(mUnsupportedAbis, mArchitecture, className).toString();
+ String abis = getSupportedAbis(mUnsupportedAbis, className).toString();
writer.append(" abis=\"" + abis.substring(1, abis.length() - 1) + "\"");
if (isKnownFailure(mKnownFailures, nameCollector.toString())) {
writer.append(" expectation=\"failure\"");
@@ -255,8 +229,8 @@
// Returns the list of ABIs supported by this TestCase on this architecture.
public static Set<String> getSupportedAbis(ExpectationStore expectationStore,
- String architecture, String className) {
- Set<String> supportedAbis = new HashSet<String>(ARCH_TO_ABIS.get(architecture));
+ String className) {
+ Set<String> supportedAbis = AbiUtils.getAbisSupportedByCts();
Expectation e = (expectationStore == null) ? null : expectationStore.get(className);
if (e != null && !e.getDescription().isEmpty()) {
// Description should be written in the form "blah blah: abi1, abi2..."
@@ -264,7 +238,7 @@
String[] unsupportedAbis = description.split(",");
for (String a : unsupportedAbis) {
String abi = a.trim();
- if (!SUPPORTED_ABIS.contains(abi)) {
+ if (!AbiUtils.isAbiSupportedByCts(abi)) {
throw new RuntimeException(
String.format("Unrecognised ABI %s in %s", abi, e.getDescription()));
}
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java
index ed82b08..00845bd 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoActivity.java
@@ -57,6 +57,7 @@
final CountDownLatch done = new CountDownLatch(1);
final int version = i;
DeviceInfoActivity.this.runOnUiThread(new Runnable() {
+ @Override
public void run() {
setContentView(new GLESSurfaceView(DeviceInfoActivity.this, version, done));
}
@@ -121,6 +122,7 @@
ConfigurationInfo info = am.getDeviceConfigurationInfo();
final int glVersion = (info.reqGlEsVersion & 0xffff0000) >> 16;
new Thread() {
+ @Override
public void run() {
runIterations(glVersion);
}
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java
index d77a44c..1eb4acb 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoConstants.java
@@ -51,6 +51,9 @@
public static final String VERSION_RELEASE = "buildVersion";
public static final String BUILD_ABI = "build_abi";
public static final String BUILD_ABI2 = "build_abi2";
+ public static final String BUILD_ABIS = "build_abis";
+ public static final String BUILD_ABIS_32 = "build_abis_32";
+ public static final String BUILD_ABIS_64 = "build_abis_64";
public static final String BUILD_FINGERPRINT = "build_fingerprint";
public static final String BUILD_TYPE = "build_type";
public static final String BUILD_MODEL = "build_model";
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
index cdf1df3..19349e5 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/DeviceInfoInstrument.java
@@ -28,6 +28,7 @@
import android.os.Environment;
import android.os.UserManager;
import android.telephony.TelephonyManager;
+import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
@@ -38,6 +39,7 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
@@ -71,6 +73,9 @@
addResult(BUILD_FINGERPRINT, Build.FINGERPRINT);
addResult(BUILD_ABI, Build.CPU_ABI);
addResult(BUILD_ABI2, Build.CPU_ABI2);
+ addResult(BUILD_ABIS, TextUtils.join(",", Build.SUPPORTED_ABIS));
+ addResult(BUILD_ABIS_32, TextUtils.join(",", Build.SUPPORTED_32_BIT_ABIS));
+ addResult(BUILD_ABIS_64, TextUtils.join(",", Build.SUPPORTED_64_BIT_ABIS));
addResult(SERIAL_NUMBER, Build.SERIAL);
addResult(VERSION_RELEASE, Build.VERSION.RELEASE);
@@ -163,7 +168,7 @@
* @param key the string of the key name.
* @param value integer value.
*/
- private void addResult(final String key, final int value){
+ static void addResult(final String key, final int value){
mResults.putInt(key, value);
}
@@ -173,7 +178,7 @@
* @param key the string of the key name.
* @param value float value.
*/
- private void addResult(final String key, final float value){
+ static void addResult(final String key, final float value){
mResults.putFloat(key, value);
}
@@ -361,7 +366,6 @@
count, getContext().getExternalFilesDirs(Environment.DIRECTORY_PICTURES).length);
count = Math.max(count, getContext().getObbDirs().length);
- final String result;
if (Environment.isExternalStorageEmulated()) {
if (count == 1) {
return "1 emulated";
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/GLESSurfaceView.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/GLESSurfaceView.java
index 1d3bf7f..04289e9 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/GLESSurfaceView.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/GLESSurfaceView.java
@@ -16,7 +16,6 @@
package android.tests.getinfo;
-import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
@@ -89,7 +88,7 @@
}
}
}
-
+ scanner.close();
mDone.countDown();
}
diff --git a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/RootProcessScanner.java b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/RootProcessScanner.java
index fefff99..d8018a1 100644
--- a/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/RootProcessScanner.java
+++ b/tools/device-setup/TestDeviceSetup/src/android/tests/getinfo/RootProcessScanner.java
@@ -146,13 +146,13 @@
try {
scanner = new Scanner(status);
- scanner = findToken(scanner, "Name:");
+ findToken(scanner, "Name:");
String name = scanner.next();
- scanner = findToken(scanner, "Uid:");
+ findToken(scanner, "Uid:");
boolean rootUid = hasRootId(scanner);
- scanner = findToken(scanner, "Gid:");
+ findToken(scanner, "Gid:");
boolean rootGid = hasRootId(scanner);
return !ROOT_PROCESS_WHITELIST_PATTERN.matcher(name).matches()
@@ -182,13 +182,12 @@
*
* @param scanner to call next() until the token is found
* @param token to find like "Name:"
- * @return scanner after finding token
*/
- private static Scanner findToken(Scanner scanner, String token) {
+ private static void findToken(Scanner scanner, String token) {
while (true) {
String next = scanner.next();
if (next.equals(token)) {
- return scanner;
+ return;
}
}
@@ -214,7 +213,7 @@
File status = getProcessStatus(processDir);
Scanner scanner = new Scanner(status);
try {
- scanner = findToken(scanner, "Name:");
+ findToken(scanner, "Name:");
return scanner.next();
} finally {
scanner.close();
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/command/CtsConsole.java b/tools/tradefed-host/src/com/android/cts/tradefed/command/CtsConsole.java
index 24190c5..7333de2 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/command/CtsConsole.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/command/CtsConsole.java
@@ -23,6 +23,7 @@
import com.android.cts.tradefed.result.TestResultRepo;
import com.android.cts.tradefed.testtype.ITestPackageRepo;
import com.android.cts.tradefed.testtype.TestPackageRepo;
+import com.android.cts.util.AbiUtils;
import com.android.tradefed.command.Console;
import com.android.tradefed.config.ArgsOptionParser;
import com.android.tradefed.config.ConfigurationException;
@@ -38,6 +39,7 @@
import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import java.util.Set;
/**
* Specialization of trade federation console that adds CTS commands to list plans and packages.
@@ -78,7 +80,7 @@
public void run() {
CtsBuildHelper ctsBuild = getCtsBuild();
if (ctsBuild != null) {
- listPackages(ctsBuild);
+ listPackages(ctsBuild, AbiUtils.getAbisSupportedByCts());
}
}
}, LIST_PATTERN, "packages");
@@ -114,7 +116,8 @@
}
CtsBuildHelper ctsBuild = getCtsBuild();
if (ctsBuild != null) {
- addDerivedPlan(ctsBuild, flatArgs);
+ // FIXME may want to only add certain ABIs
+ addDerivedPlan(ctsBuild, AbiUtils.getAbisSupportedByCts(), flatArgs);
}
}
};
@@ -190,10 +193,10 @@
}
}
- private void listPackages(CtsBuildHelper ctsBuild) {
- ITestPackageRepo testCaseRepo = new TestPackageRepo(ctsBuild.getTestCasesDir(), false);
- for (String packageUri : testCaseRepo.getPackageNames()) {
- printLine(packageUri);
+ private void listPackages(CtsBuildHelper ctsBuild, Set<String> abis) {
+ ITestPackageRepo testCaseRepo = new TestPackageRepo(ctsBuild.getTestCasesDir(), abis, false);
+ for (String packageName : testCaseRepo.getPackageNames()) {
+ printLine(packageName);
}
}
@@ -215,12 +218,12 @@
tableFormatter.displayTable(table, new PrintWriter(System.out, true));
}
- private void addDerivedPlan(CtsBuildHelper ctsBuild, String[] flatArgs) {
+ private void addDerivedPlan(CtsBuildHelper ctsBuild, Set<String> abis, String[] flatArgs) {
PlanCreator creator = new PlanCreator();
try {
ArgsOptionParser optionParser = new ArgsOptionParser(creator);
optionParser.parse(Arrays.asList(flatArgs));
- creator.createAndSerializeDerivedPlan(ctsBuild);
+ creator.createAndSerializeDerivedPlan(ctsBuild, abis);
} catch (ConfigurationException e) {
printLine("Error: " + e.getMessage());
printLine(ArgsOptionParser.getOptionHelp(false, creator));
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/device/DeviceInfoCollector.java b/tools/tradefed-host/src/com/android/cts/tradefed/device/DeviceInfoCollector.java
index 3aa57a0..903ac74 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/device/DeviceInfoCollector.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/device/DeviceInfoCollector.java
@@ -15,6 +15,7 @@
*/
package com.android.cts.tradefed.device;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.Log;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
@@ -22,6 +23,8 @@
import com.android.tradefed.testtype.InstrumentationTest;
import java.io.File;
+import java.util.HashSet;
+import java.util.Set;
/**
* Collects info from device under test.
@@ -36,16 +39,22 @@
private static final String APK_NAME = "TestDeviceSetup";
public static final String APP_PACKAGE_NAME = "android.tests.devicesetup";
private static final String INSTRUMENTATION_NAME = "android.tests.getinfo.DeviceInfoInstrument";
+ public static final Set<String> IDS = new HashSet<String>();
+ static {
+ for (String abi : AbiUtils.getAbisSupportedByCts()) {
+ IDS.add(AbiUtils.createId(abi, APP_PACKAGE_NAME));
+ }
+ }
/**
* Installs and runs the device info collector instrumentation, and forwards results
- * to the <var>listener</var>
+ * to the listener.
*
* @param device
* @param listener
* @throws DeviceNotAvailableException
*/
- public static void collectDeviceInfo(ITestDevice device, File testApkDir,
+ public static void collectDeviceInfo(ITestDevice device, String abi, File testApkDir,
ITestInvocationListener listener) throws DeviceNotAvailableException {
File apkFile = new File(testApkDir, String.format("%s.apk", APK_NAME));
if (!apkFile.exists()) {
@@ -59,6 +68,7 @@
// no need to collect tests and re-run
instrTest.setRerunMode(false);
instrTest.setPackageName(APP_PACKAGE_NAME);
+ instrTest.setRunName(AbiUtils.createId(abi, APP_PACKAGE_NAME));
instrTest.setRunnerName(INSTRUMENTATION_NAME);
instrTest.run(listener);
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsReportUtil.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsReportUtil.java
deleted file mode 100644
index 97f607e..0000000
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsReportUtil.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2013 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.cts.tradefed.result;
-
-import java.util.Map;
-
-/**
- * Static utility class for handling Cts Results.
- */
-public class CtsReportUtil {
- private static final String CTS_RESULT_KEY = "CTS_RESULT";
-
- /**
- * Utility method to extract CTS result from test metrics
- * @param testMetrics
- * @return result or null if not found
- */
- public static String getCtsResultFromMetrics(Map<String, String> testMetrics) {
- for (Map.Entry<String, String> entry: testMetrics.entrySet()) {
- if (CTS_RESULT_KEY.equals(entry.getKey())) {
- return entry.getValue();
- }
- }
- return null;
- }
-}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsTestLogReporter.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsTestLogReporter.java
index bbdcb05..4a1bfb5 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsTestLogReporter.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsTestLogReporter.java
@@ -17,6 +17,7 @@
package com.android.cts.tradefed.result;
import com.android.cts.tradefed.device.DeviceInfoCollector;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.Log;
import com.android.ddmlib.Log.LogLevel;
import com.android.ddmlib.testrunner.TestIdentifier;
@@ -49,24 +50,28 @@
}
/**
- * {@inheritDoc}
+ * Reports the start of a test run.
+ *
+ * @param id the unique identifier of this test run, generated by
+ * {@link AbiUtils#createId(String, String)}.
+ * @param numTests total number of tests in test run
*/
@Override
- public void testRunStarted(String name, int numTests) {
- if (mCurrentPkgResult != null && !name.equals(mCurrentPkgResult.getAppPackageName())) {
+ public void testRunStarted(String id, int numTests) {
+ if (mCurrentPkgResult != null && !id.equals(mCurrentPkgResult.getId())) {
// display results from previous run
logCompleteRun(mCurrentPkgResult);
}
- mIsDeviceInfoRun = name.equals(DeviceInfoCollector.APP_PACKAGE_NAME);
+ mIsDeviceInfoRun = DeviceInfoCollector.IDS.contains(id);
if (mIsDeviceInfoRun) {
logResult("Collecting device info");
} else {
- if (mCurrentPkgResult == null || !name.equals(mCurrentPkgResult.getAppPackageName())) {
+ if (mCurrentPkgResult == null || !id.equals(mCurrentPkgResult.getId())) {
logResult("-----------------------------------------");
- logResult("Test package %s started", name);
+ logResult("Test package %s started", id);
logResult("-----------------------------------------");
}
- mCurrentPkgResult = mResults.getOrCreatePackage(name);
+ mCurrentPkgResult = mResults.getOrCreatePackage(id);
}
}
@@ -91,7 +96,7 @@
*/
@Override
public void testEnded(TestIdentifier test, Map<String, String> testMetrics) {
- mCurrentPkgResult.reportTestEnded(test);
+ mCurrentPkgResult.reportTestEnded(test, testMetrics);
Test result = mCurrentPkgResult.findTest(test);
String stack = result.getStackTrace() == null ? "" : "\n" + result.getStackTrace();
logResult("%s#%s %s %s", test.getClassName(), test.getTestName(), result.getResult(),
@@ -123,7 +128,7 @@
return;
}
logResult("%s package complete: Passed %d, Failed %d, Not Executed %d",
- pkgResult.getAppPackageName(), pkgResult.countTests(CtsTestStatus.PASS),
+ pkgResult.getId(), pkgResult.countTests(CtsTestStatus.PASS),
pkgResult.countTests(CtsTestStatus.FAIL),
pkgResult.countTests(CtsTestStatus.NOT_EXECUTED));
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java
index 956f1b1..0d21fc6 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/CtsXmlResultReporter.java
@@ -19,7 +19,6 @@
import com.android.cts.tradefed.build.CtsBuildHelper;
import com.android.cts.tradefed.device.DeviceInfoCollector;
import com.android.cts.tradefed.testtype.CtsTest;
-import com.android.cts.tradefed.util.CtsHostStore;
import com.android.ddmlib.Log;
import com.android.ddmlib.Log.LogLevel;
import com.android.ddmlib.testrunner.TestIdentifier;
@@ -48,8 +47,6 @@
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
/**
* Writes results to an XML files in the CTS format.
@@ -104,13 +101,6 @@
private String mSuiteName;
private String mReferenceUrl;
- private static final Pattern mCtsLogPattern = Pattern.compile("(.*)\\+\\+\\+\\+(.*)");
-
- @Option(name = AbiFormatter.FORCE_ABI_STRING,
- description = AbiFormatter.FORCE_ABI_DESCRIPTION,
- importance = Importance.IF_UNSET)
- private String mForceAbi = null;
-
public void setReportDir(File reportDir) {
mReportDir = reportDir;
}
@@ -232,9 +222,9 @@
@Override
- public void testRunStarted(String name, int numTests) {
- mCurrentPkgResult = mResults.getOrCreatePackage(name);
- mIsDeviceInfoRun = name.equals(DeviceInfoCollector.APP_PACKAGE_NAME);
+ public void testRunStarted(String id, int numTests) {
+ mCurrentPkgResult = mResults.getOrCreatePackage(id);
+ mIsDeviceInfoRun = DeviceInfoCollector.IDS.contains(id);
}
/**
@@ -258,33 +248,7 @@
*/
@Override
public void testEnded(TestIdentifier test, Map<String, String> testMetrics) {
- collectCtsResults(test, testMetrics);
- mCurrentPkgResult.reportTestEnded(test);
- }
-
- /**
- * Collect Cts results for both device and host tests to the package result.
- * @param test test ran
- * @param testMetrics test metrics which can contain performance result for device tests
- */
- private void collectCtsResults(TestIdentifier test, Map<String, String> testMetrics) {
- // device test can have performance results in testMetrics
- String perfResult = CtsReportUtil.getCtsResultFromMetrics(testMetrics);
- // host test should be checked in CtsHostStore.
- if (perfResult == null) {
- perfResult = CtsHostStore.removeCtsResult(mDeviceSerial, test.toString());
- }
- if (perfResult != null) {
- // CTS result is passed in Summary++++Details format.
- // Extract Summary and Details, and pass them.
- Matcher m = mCtsLogPattern.matcher(perfResult);
- if (m.find()) {
- mCurrentPkgResult.reportPerformanceResult(test, CtsTestStatus.PASS, m.group(1),
- m.group(2));
- } else {
- logResult("CTS Result unrecognizable:" + perfResult);
- }
- }
+ mCurrentPkgResult.reportTestEnded(test, testMetrics);
}
/**
@@ -377,9 +341,6 @@
serializer.attribute(ns, "endtime", endTime);
serializer.attribute(ns, "version", CTS_RESULT_FILE_VERSION);
serializer.attribute(ns, "suite", mSuiteName);
- if (mForceAbi != null) {
- serializer.attribute(ns, "abi", mForceAbi);
- }
mResults.serialize(serializer);
// TODO: not sure why, but the serializer doesn't like this statement
//serializer.endTag(ns, RESULT_TAG);
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/DeviceInfoResult.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/DeviceInfoResult.java
index dd91af0..0c947c3 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/DeviceInfoResult.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/DeviceInfoResult.java
@@ -358,7 +358,8 @@
DeviceInfoConstants.BUILD_MANUFACTURER, DeviceInfoConstants.BUILD_BOARD,
DeviceInfoConstants.BUILD_DEVICE, DeviceInfoConstants.PRODUCT_NAME,
DeviceInfoConstants.BUILD_ABI, DeviceInfoConstants.BUILD_ABI2,
- DeviceInfoConstants.SCREEN_SIZE);
+ DeviceInfoConstants.BUILD_ABIS, DeviceInfoConstants.BUILD_ABIS_32,
+ DeviceInfoConstants.BUILD_ABIS_64, DeviceInfoConstants.SCREEN_SIZE);
}
private void combineMetrics(Map<String, String> metrics, String... keysToCombine) {
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/ITestResultRepo.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/ITestResultRepo.java
index d672f41..19b0540 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/ITestResultRepo.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/ITestResultRepo.java
@@ -41,7 +41,7 @@
/**
* Get the report directory for given result
* @param sessionId
- * @return
+ * @return A {@link File} representing the report directory for the given sessionId
*/
public File getReportDir(int sessionId);
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/ITestSummary.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/ITestSummary.java
index 98494ee..e7041ec 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/ITestSummary.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/ITestSummary.java
@@ -23,43 +23,43 @@
/**
* @return the session id
*/
- int getId();
+ public int getId();
/**
* @return the starting timestamp, also known as result directory name
*/
- String getTimestamp();
+ public String getTimestamp();
/**
* @return the num of not executed tests
*/
- int getNumIncomplete();
+ public int getNumIncomplete();
/**
* @return the number of failed tests
*/
- int getNumFailed();
+ public int getNumFailed();
/**
* @return the number of passed tests
*/
- int getNumPassed();
+ public int getNumPassed();
/**
* @return the test plan associated with result
*/
- String getTestPlan();
+ public String getTestPlan();
/**
* Return the user-friendly displayed start time stored in result XML.
* <p/>
* Expected format: {@link TimeUtil#getTimestamp()}
*/
- String getStartTime();
+ public String getStartTime();
/**
* @return a comma separated list of device serials associated with result
*/
- String getDeviceSerials();
+ public String getDeviceSerials();
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/IssueReporter.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/IssueReporter.java
index 9d903dd..319dd54 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/IssueReporter.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/IssueReporter.java
@@ -194,7 +194,7 @@
}
@Override
- public void testRunStarted(String name, int numTests) {
+ public void testRunStarted(String id, int numTests) {
}
@Override
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/PlanCreator.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/PlanCreator.java
index d263bc8..713e8fa 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/PlanCreator.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/PlanCreator.java
@@ -22,6 +22,7 @@
import com.android.cts.tradefed.testtype.ITestPlan;
import com.android.cts.tradefed.testtype.TestPackageRepo;
import com.android.cts.tradefed.testtype.TestPlan;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.Log;
import com.android.ddmlib.Log.LogLevel;
import com.android.ddmlib.testrunner.TestIdentifier;
@@ -37,6 +38,7 @@
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedHashSet;
+import java.util.Set;
/**
* Class for creating test plans from CTS result XML.
@@ -88,8 +90,9 @@
* {@link Option} values must all be set before this is called.
* @throws ConfigurationException
*/
- public void createAndSerializeDerivedPlan(CtsBuildHelper build) throws ConfigurationException {
- ITestPlan derivedPlan = createDerivedPlan(build);
+ public void createAndSerializeDerivedPlan(CtsBuildHelper build, Set<String> abis)
+ throws ConfigurationException {
+ ITestPlan derivedPlan = createDerivedPlan(build, abis);
if (derivedPlan != null) {
try {
derivedPlan.serialize(new BufferedOutputStream(new FileOutputStream(mPlanFile)));
@@ -110,25 +113,24 @@
* @return test plan
* @throws ConfigurationException
*/
- public ITestPlan createDerivedPlan(CtsBuildHelper build) throws ConfigurationException {
+ public ITestPlan createDerivedPlan(CtsBuildHelper build, Set<String> abis)
+ throws ConfigurationException {
checkFields(build);
ITestPackageRepo pkgDefRepo = new TestPackageRepo(build.getTestCasesDir(),
- mIncludeKnownFailures);
- ITestPlan derivedPlan = new TestPlan(mPlanName);
+ abis, mIncludeKnownFailures);
+ ITestPlan derivedPlan = new TestPlan(mPlanName, abis);
for (TestPackageResult pkg : mResult.getPackages()) {
Collection<TestIdentifier> filteredTests = pkg.getTestsWithStatus(mResultFilter);
- if (!filteredTests.isEmpty()) {
- String pkgUri = pkg.getAppPackageName();
- ITestPackageDef pkgDef = pkgDefRepo.getTestPackage(pkgUri);
- if (pkgDef != null) {
- Collection<TestIdentifier> excludedTests = new LinkedHashSet<TestIdentifier>(
- pkgDef.getTests());
- excludedTests.removeAll(filteredTests);
- derivedPlan.addPackage(pkgUri);
- derivedPlan.addExcludedTests(pkgUri, excludedTests);
- } else {
- CLog.e("Could not find package %s in repository", pkgUri);
- }
+ String pkgId = pkg.getId();
+ ITestPackageDef pkgDef = pkgDefRepo.getTestPackage(pkgId);
+ if (pkgDef != null) {
+ Collection<TestIdentifier> excludedTests =
+ new LinkedHashSet<TestIdentifier>(pkgDef.getTests());
+ excludedTests.removeAll(filteredTests);
+ derivedPlan.addPackage(pkgId);
+ derivedPlan.addExcludedTests(pkgId, excludedTests);
+ } else {
+ CLog.e("Could not find package %s in repository", pkgId);
}
}
return derivedPlan;
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/TestPackageResult.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestPackageResult.java
index 015a7ae..f5a3d02 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/TestPackageResult.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestPackageResult.java
@@ -15,10 +15,9 @@
*/
package com.android.cts.tradefed.result;
-import android.tests.getinfo.DeviceInfoConstants;
-
-import com.android.cts.tradefed.device.DeviceInfoCollector;
import com.android.cts.tradefed.testtype.CtsTest;
+import com.android.cts.tradefed.util.CtsHostStore;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.log.LogUtil.CLog;
@@ -31,34 +30,55 @@
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
/**
* Data structure for a CTS test package result.
* <p/>
* Provides methods to serialize to XML.
*/
-class TestPackageResult extends AbstractXmlPullParser {
+class TestPackageResult extends AbstractXmlPullParser {
static final String TAG = "TestPackage";
+
+ public static final String CTS_RESULT_KEY = "CTS_TEST_RESULT";
+
private static final String DIGEST_ATTR = "digest";
private static final String APP_PACKAGE_NAME_ATTR = "appPackageName";
private static final String NAME_ATTR = "name";
+ private static final String ABI_ATTR = "abi";
private static final String ns = CtsXmlResultReporter.ns;
private static final String SIGNATURE_TEST_PKG = "android.tests.sigtest";
+ private static final Pattern mCtsLogPattern = Pattern.compile("(.*)\\+\\+\\+\\+(.*)");
+
+ private String mDeviceSerial;
private String mAppPackageName;
private String mName;
+ private String mAbi;
private String mDigest;
private Map<String, String> mMetrics = new HashMap<String, String>();
+ private Map<TestIdentifier, Map<String, String>> mTestMetrics = new HashMap<TestIdentifier, Map<String, String>>();
private TestSuite mSuiteRoot = new TestSuite(null);
+ public void setDeviceSerial(String deviceSerial) {
+ mDeviceSerial = deviceSerial;
+ }
+
+ public String getDeviceSerial() {
+ return mDeviceSerial;
+ }
+
+ public String getId() {
+ return AbiUtils.createId(getAbi(), getAppPackageName());
+ }
+
public void setAppPackageName(String appPackageName) {
mAppPackageName = appPackageName;
}
@@ -75,6 +95,14 @@
return mName;
}
+ public void setAbi(String abi) {
+ mAbi = abi;
+ }
+
+ public String getAbi() {
+ return mAbi;
+ }
+
public void setDigest(String digest) {
mDigest = digest;
}
@@ -94,7 +122,6 @@
* Adds a test result to this test package
*
* @param testId
- * @param testResult
*/
public Test insertTest(TestIdentifier testId) {
return findTest(testId, true);
@@ -109,8 +136,8 @@
// should never happen
classNameSegments.add("UnknownTestClass");
}
- String testCaseName = classNameSegments.remove(classNameSegments.size()-1);
- return mSuiteRoot.findTest(classNameSegments, testCaseName, testId.getTestName(), insertIfMissing);
+ String testCaseName = classNameSegments.remove(classNameSegments.size() - 1);
+ return mSuiteRoot.findTest(classNameSegments, testCaseName, testId.getTestName(), insertIfMissing);
}
@@ -133,6 +160,7 @@
serializer.startTag(ns, TAG);
serializeAttribute(serializer, NAME_ATTR, mName);
serializeAttribute(serializer, APP_PACKAGE_NAME_ATTR, mAppPackageName);
+ serializeAttribute(serializer, ABI_ATTR, mAbi);
serializeAttribute(serializer, DIGEST_ATTR, getDigest());
if (SIGNATURE_TEST_PKG.equals(mName)) {
serializer.attribute(ns, "signatureCheck", "true");
@@ -170,6 +198,7 @@
}
setAppPackageName(getAttribute(parser, APP_PACKAGE_NAME_ATTR));
setName(getAttribute(parser, NAME_ATTR));
+ setAbi(getAttribute(parser, ABI_ATTR));
setDigest(getAttribute(parser, DIGEST_ATTR));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
@@ -186,10 +215,10 @@
}
/**
- * Return a list of {@link TestIdentifer}s contained in this result with the given status
+ * Return a list of {@link TestIdentifier}s contained in this result with the given status
*
* @param resultFilter the {@link CtsTestStatus} to filter by
- * @return a collection of {@link TestIdentifer}s
+ * @return a collection of {@link TestIdentifier}s
*/
public Collection<TestIdentifier> getTestsWithStatus(CtsTestStatus resultFilter) {
Collection<TestIdentifier> tests = new LinkedList<TestIdentifier>();
@@ -200,63 +229,43 @@
/**
* Populate values in this package result from run metrics
- * @param runResult
+ * @param metrics A map of metrics from the completed test run.
*/
public void populateMetrics(Map<String, String> metrics) {
String name = metrics.get(CtsTest.PACKAGE_NAME_METRIC);
if (name != null) {
setName(name);
}
+ String abi = metrics.get(CtsTest.PACKAGE_ABI_METRIC);
+ if (abi != null) {
+ setAbi(abi);
+ }
String digest = metrics.get(CtsTest.PACKAGE_DIGEST_METRIC);
if (digest != null) {
setDigest(digest);
}
- if (DeviceInfoCollector.APP_PACKAGE_NAME.equals(getAppPackageName())) {
- storeDeviceMetrics(metrics);
- } else {
- mMetrics.putAll(metrics);
- }
- }
+ mMetrics.putAll(metrics);
- /**
- * Check that the provided device info metrics are consistent with the currently stored metrics.
- * <p/>
- * If any inconsistencies occur, logs errors and stores error messages in the metrics map
- *
- * @param metrics
- */
- private void storeDeviceMetrics(Map<String, String> metrics) {
- // TODO centralize all the device metrics handling into a single class
- if (mMetrics.isEmpty()) {
- // nothing to check!
- mMetrics.putAll(metrics);
- return;
- }
- // ensure all the metrics we expect to be identical actually are
- checkMetrics(metrics, DeviceInfoConstants.BUILD_FINGERPRINT,
- DeviceInfoConstants.BUILD_MODEL, DeviceInfoConstants.BUILD_BRAND,
- DeviceInfoConstants.BUILD_MANUFACTURER, DeviceInfoConstants.BUILD_BOARD,
- DeviceInfoConstants.BUILD_DEVICE, DeviceInfoConstants.PRODUCT_NAME,
- DeviceInfoConstants.BUILD_ABI, DeviceInfoConstants.BUILD_ABI2,
- DeviceInfoConstants.SCREEN_SIZE);
- }
-
- private void checkMetrics(Map<String, String> metrics, String... keysToCheck) {
- Set<String> keyCheckSet = new HashSet<String>();
- Collections.addAll(keyCheckSet, keysToCheck);
- for (Map.Entry<String, String> metricEntry : metrics.entrySet()) {
- String currentValue = mMetrics.get(metricEntry.getKey());
- if (keyCheckSet.contains(metricEntry.getKey()) && currentValue != null
- && !metricEntry.getValue().equals(currentValue)) {
- CLog.e("Inconsistent info collected from devices. "
- + "Current result has %s='%s', Received '%s'. Are you sharding or " +
- "resuming a test run across different devices and/or builds?",
- metricEntry.getKey(), currentValue, metricEntry.getValue());
- mMetrics.put(metricEntry.getKey(),
- String.format("ERROR: Inconsistent results: %s, %s",
- metricEntry.getValue(), currentValue));
- } else {
- mMetrics.put(metricEntry.getKey(), metricEntry.getValue());
+ // Collect performance results
+ for (TestIdentifier test : mTestMetrics.keySet()) {
+ // device test can have performance results in test metrics
+ String perfResult = mTestMetrics.get(test).get(CTS_RESULT_KEY);
+ // host test should be checked in CtsHostStore.
+ if (perfResult == null) {
+ perfResult = CtsHostStore.removeCtsResult(mDeviceSerial, mAbi, test.toString());
+ }
+ if (perfResult != null) {
+ // CTS result is passed in Summary++++Details format.
+ // Extract Summary and Details, and pass them.
+ Matcher m = mCtsLogPattern.matcher(perfResult);
+ if (m.find()) {
+ Test result = findTest(test);
+ result.setResultStatus(CtsTestStatus.PASS);
+ result.setSummary(m.group(1));
+ result.setDetails(m.group(2));
+ } else {
+ CLog.e("CTS Result unrecognizable:" + perfResult);
+ }
}
}
}
@@ -275,29 +284,22 @@
}
/**
- * report performance result
- * @param test
- * @param status
- * @param perf
- */
- public void reportPerformanceResult(TestIdentifier test, CtsTestStatus status, String summary, String details) {
- Test result = findTest(test);
- result.setResultStatus(status);
- result.setSummary(summary);
- result.setDetails(details);
- }
-
- /**
* Report that the given test has completed.
*
- * @param test
+ * @param test The {@link TestIdentifier} of the completed test.
+ * @param testMetrics A map holding metrics about the completed test, if any.
*/
- public void reportTestEnded(TestIdentifier test) {
+ public void reportTestEnded(TestIdentifier test, Map<String, String> testMetrics) {
Test result = findTest(test);
if (!result.getResult().equals(CtsTestStatus.FAIL)) {
result.setResultStatus(CtsTestStatus.PASS);
}
result.updateEndTime();
+ if (mTestMetrics.containsKey(test)) {
+ CLog.e("Test metrics already contains key: " + test);
+ }
+ mTestMetrics.put(test, testMetrics);
+ CLog.i("Test metrics:" + testMetrics);
}
/**
@@ -311,9 +313,10 @@
}
/**
- * @return
+ * @return A map holding the metrics from the test run.
*/
public Map<String, String> getMetrics() {
return mMetrics;
}
+
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/result/TestResults.java b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestResults.java
index 2f9eadd..8c1a5bd 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/result/TestResults.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/result/TestResults.java
@@ -16,6 +16,7 @@
package com.android.cts.tradefed.result;
import com.android.cts.tradefed.build.CtsBuildProvider;
+import com.android.cts.util.AbiUtils;
import com.android.tradefed.log.LogUtil.CLog;
import org.kxml2.io.KXmlSerializer;
@@ -49,7 +50,7 @@
static final String NOT_EXECUTED_ATTR = "notExecuted";
static final String FAILED_ATTR = "failed";
- private Map<String, TestPackageResult> mPackageMap =
+ private Map<String, TestPackageResult> mPackageResults =
new LinkedHashMap<String, TestPackageResult>();
private DeviceInfoResult mDeviceInfo = new DeviceInfoResult();
@@ -68,10 +69,10 @@
TestPackageResult.TAG)) {
TestPackageResult pkg = new TestPackageResult();
pkg.parse(parser);
- if (pkg.getAppPackageName() != null) {
- mPackageMap.put(pkg.getAppPackageName(), pkg);
+ if (pkg.getId() != null) {
+ mPackageResults.put(pkg.getId(), pkg);
} else {
- CLog.w("Found package with no app package name");
+ CLog.w("Found package with no id");
}
}
eventType = parser.next();
@@ -82,17 +83,16 @@
* @return the list of {@link TestPackageResult}.
*/
public Collection<TestPackageResult> getPackages() {
- return mPackageMap.values();
+ return mPackageResults.values();
}
/**
* Count the number of tests with given status
- * @param pass
- * @return
+ * @param status
*/
public int countTests(CtsTestStatus status) {
int total = 0;
- for (TestPackageResult result : mPackageMap.values()) {
+ for (TestPackageResult result : mPackageResults.values()) {
total += result.countTests(status);
}
return total;
@@ -109,7 +109,7 @@
serializeHostInfo(serializer);
serializeTestSummary(serializer);
// sort before serializing
- List<TestPackageResult> pkgs = new ArrayList<TestPackageResult>(mPackageMap.values());
+ List<TestPackageResult> pkgs = new ArrayList<TestPackageResult>(mPackageResults.values());
Collections.sort(pkgs, new PkgComparator());
for (TestPackageResult r : pkgs) {
r.serialize(serializer);
@@ -174,27 +174,25 @@
private static class PkgComparator implements Comparator<TestPackageResult> {
- /**
- * {@inheritDoc}
- */
@Override
- public int compare(TestPackageResult o1, TestPackageResult o2) {
- return o1.getAppPackageName().compareTo(o2.getAppPackageName());
+ public int compare(TestPackageResult lhs, TestPackageResult rhs) {
+ return lhs.getId().compareTo(rhs.getId());
}
-
}
/**
- * Return existing package with given app package name. If not found, create a new one.
- * @param name
+ * Return existing package with given id. If not found, create a new one.
+ * @param id
* @return
*/
- public TestPackageResult getOrCreatePackage(String appPackageName) {
- TestPackageResult pkgResult = mPackageMap.get(appPackageName);
+ public TestPackageResult getOrCreatePackage(String id) {
+ TestPackageResult pkgResult = mPackageResults.get(id);
if (pkgResult == null) {
pkgResult = new TestPackageResult();
- pkgResult.setAppPackageName(appPackageName);
- mPackageMap.put(appPackageName, pkgResult);
+ String[] abiAndName = AbiUtils.parseId(id);
+ pkgResult.setAbi(abiAndName[0]);
+ pkgResult.setAppPackageName(abiAndName[1]);
+ mPackageResults.put(id, pkgResult);
}
return pkgResult;
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/Abi.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/Abi.java
new file mode 100644
index 0000000..926e14b
--- /dev/null
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/Abi.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2014 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.cts.tradefed.testtype;
+
+import com.android.tradefed.testtype.IAbi;
+/**
+ * A class representing an ABI.
+ */
+public class Abi implements IAbi {
+
+ private String mName;
+ private String mBitness;
+
+ public Abi(String name, String bitness) {
+ mName = name;
+ mBitness = bitness;
+ }
+
+ @Override
+ public String getName() {
+ return mName;
+ }
+
+ @Override
+ public String getBitness() {
+ return mBitness;
+ }
+
+}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/AccessibilityServiceTestRunner.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/AccessibilityServiceTestRunner.java
index 4cfd263..eafd608 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/AccessibilityServiceTestRunner.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/AccessibilityServiceTestRunner.java
@@ -16,8 +16,8 @@
package com.android.cts.tradefed.testtype;
-import com.android.cts.tradefed.build.CtsBuildHelper;
-import com.android.tradefed.build.IBuildInfo;
+import com.android.cts.util.AbiUtils;
+import com.android.ddmlib.Log;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.result.ITestInvocationListener;
import com.android.tradefed.util.FileUtil;
@@ -39,7 +39,10 @@
* maintained so cts-tradefed can run against older CTS builds that still
* require this class.
*/
-public class AccessibilityServiceTestRunner extends InstrumentationApkTest {
+@Deprecated
+public class AccessibilityServiceTestRunner extends CtsInstrumentationApkTest {
+
+ private static final String LOG_TAG = AccessibilityServiceTestRunner.class.getSimpleName();
private static final String DELEGATING_ACCESSIBLITY_SERVICE_PACKAGE_NAME =
"android.accessibilityservice.delegate";
@@ -50,14 +53,6 @@
private static final String DELEGATING_ACCESSIBLITY_SERVICE_APK =
"CtsDelegatingAccessibilityService.apk";
- private CtsBuildHelper mCtsBuild;
-
- @Override
- public void setBuild(IBuildInfo build) {
- super.setBuild(build);
- mCtsBuild = CtsBuildHelper.createBuildHelper(build);
- }
-
@Override
public void run(ITestInvocationListener listener) throws DeviceNotAvailableException {
beforeTest();
@@ -77,7 +72,8 @@
private void installApkAndAssert(String apkName) throws DeviceNotAvailableException {
File file = FileUtil.getFileForPath(mCtsBuild.getTestCasesDir(), apkName);
- String errorMessage = getDevice().installPackage(file, true);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+ String errorMessage = getDevice().installPackage(file, true, options);
TestCase.assertNull("Error installing: " + apkName, errorMessage);
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/AccessibilityTestRunner.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/AccessibilityTestRunner.java
index 2a4239a..9ba4109 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/AccessibilityTestRunner.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/AccessibilityTestRunner.java
@@ -16,9 +16,9 @@
package com.android.cts.tradefed.testtype;
-import com.android.cts.tradefed.build.CtsBuildHelper;
import com.android.cts.tradefed.targetprep.SettingsToggler;
-import com.android.tradefed.build.IBuildInfo;
+import com.android.cts.util.AbiUtils;
+import com.android.ddmlib.Log;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.result.ITestInvocationListener;
@@ -37,7 +37,9 @@
* these services, running the tests, disabling the services, and removing
* the accessibility services package.
*/
-public class AccessibilityTestRunner extends InstrumentationApkTest {
+public class AccessibilityTestRunner extends CtsInstrumentationApkTest {
+
+ private static final String LOG_TAG = AccessibilityTestRunner.class.getSimpleName();
private static final String SOME_ACCESSIBLITY_SERVICES_PACKAGE_NAME =
"android.view.accessibility.services";
@@ -51,14 +53,6 @@
private static final String SOME_ACCESSIBLITY_SERVICES_APK =
"CtsSomeAccessibilityServices.apk";
- private CtsBuildHelper mCtsBuild;
-
- @Override
- public void setBuild(IBuildInfo build) {
- super.setBuild(build);
- mCtsBuild = CtsBuildHelper.createBuildHelper(build);
- }
-
@Override
public void run(ITestInvocationListener listener) throws DeviceNotAvailableException {
beforeTest();
@@ -78,7 +72,8 @@
private void installApkAndAssert(String apkName) throws DeviceNotAvailableException {
File file = FileUtil.getFileForPath(mCtsBuild.getTestCasesDir(), apkName);
- String errorMessage = getDevice().installPackage(file, true);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+ String errorMessage = getDevice().installPackage(file, true, options);
TestCase.assertNull("Error installing: " + apkName, errorMessage);
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/InstrumentationApkTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsInstrumentationApkTest.java
similarity index 74%
rename from tools/tradefed-host/src/com/android/cts/tradefed/testtype/InstrumentationApkTest.java
rename to tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsInstrumentationApkTest.java
index 4195dda..6765305 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/InstrumentationApkTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsInstrumentationApkTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright (C) 2014 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.
@@ -16,18 +16,15 @@
package com.android.cts.tradefed.testtype;
import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.Log;
import com.android.tradefed.build.IBuildInfo;
-import com.android.tradefed.config.Option;
-import com.android.tradefed.config.Option.Importance;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.IAbi;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.testtype.InstrumentationTest;
-import com.android.tradefed.util.AbiFormatter;
-
-import junit.framework.Assert;
import java.io.File;
import java.io.FileNotFoundException;
@@ -35,25 +32,32 @@
import java.util.Collection;
/**
- * A {@link InstrumentationTest} that will install CTS apks
+ * An {@link InstrumentationTest} that will install CTS apks
* before test execution, and uninstall on execution completion.
*/
-public class InstrumentationApkTest extends InstrumentationTest implements IBuildReceiver {
+public class CtsInstrumentationApkTest extends InstrumentationTest implements IBuildReceiver {
- private static final String LOG_TAG = "InstrumentationApkTest";
+ private static final String LOG_TAG = "CtsInstrumentationApkTest";
/** the file names of the CTS apks to install */
private Collection<String> mInstallFileNames = new ArrayList<String>();
private Collection<String> mUninstallPackages = new ArrayList<String>();
+ protected CtsBuildHelper mCtsBuild = null;
+ protected IAbi mAbi = null;
- private CtsBuildHelper mCtsBuild = null;
+ /**
+ * @param abi the ABI to run the test on
+ */
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
/**
* {@inheritDoc}
*/
@Override
public void setBuild(IBuildInfo build) {
- mCtsBuild = CtsBuildHelper.createBuildHelper(build);
+ mCtsBuild = CtsBuildHelper.createBuildHelper(build);
}
/**
@@ -76,11 +80,11 @@
ITestDevice mTestDevice = getDevice();
if (mTestDevice == null) {
- Log.e(LOG_TAG, String.format("Missing device."));
+ Log.e(LOG_TAG, "Missing device.");
return;
}
if (mCtsBuild == null) {
- Log.e(LOG_TAG, String.format("Missing build %s", mCtsBuild));
+ Log.e(LOG_TAG, "Missing build");
return;
}
@@ -90,15 +94,7 @@
try {
File apkFile = mCtsBuild.getTestApp(apkFileName);
String errorCode = null;
- String[] options = {};
- String forceAbi = getForceAbi();
- if (forceAbi != null) {
- String abi = AbiFormatter.getDefaultAbi(mTestDevice, forceAbi);
- if (abi != null) {
- options = new String[]{String.format("--abi %s ", abi)};
- }
- }
- Log.d(LOG_TAG, "installPackage options: " + options);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
errorCode = mTestDevice.installPackage(apkFile, true, options);
if (errorCode != null) {
Log.e(LOG_TAG, String.format("Failed to install %s on %s. Reason: %s",
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
index 2e3fadc..fe92243 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
@@ -20,13 +20,13 @@
import com.android.cts.tradefed.device.DeviceInfoCollector;
import com.android.cts.tradefed.result.CtsTestStatus;
import com.android.cts.tradefed.result.PlanCreator;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.Log;
import com.android.ddmlib.Log.LogLevel;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.config.ConfigurationException;
import com.android.tradefed.config.Option;
-import com.android.tradefed.config.OptionSetter;
import com.android.tradefed.config.Option.Importance;
import com.android.tradefed.config.OptionCopier;
import com.android.tradefed.device.DeviceNotAvailableException;
@@ -42,7 +42,6 @@
import com.android.tradefed.testtype.IRemoteTest;
import com.android.tradefed.testtype.IResumableTest;
import com.android.tradefed.testtype.IShardableTest;
-import com.android.tradefed.testtype.InstrumentationTest;
import com.android.tradefed.util.AbiFormatter;
import com.android.tradefed.util.RunUtil;
import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
@@ -83,6 +82,7 @@
public static final String RUN_KNOWN_FAILURES_OPTION = "run-known-failures";
public static final String PACKAGE_NAME_METRIC = "packageName";
+ public static final String PACKAGE_ABI_METRIC = "packageAbi";
public static final String PACKAGE_DIGEST_METRIC = "packageDigest";
private ITestDevice mDevice;
@@ -207,7 +207,7 @@
* Return the test run name that should be used for the TestPackage
*/
String getTestRunName() {
- return mPackageDef.getUri();
+ return mPackageDef.getId();
}
}
@@ -434,7 +434,7 @@
// packages are using the same prerequisite apk (I'm looking at you, CtsTestStubs!)
Collection<String> prerequisiteApks = getPrerequisiteApks(mRemainingTestPkgs);
Collection<String> uninstallPackages = getPrerequisitePackageNames(mRemainingTestPkgs);
- ResultFilter filter = new ResultFilter(listener, mRemainingTestPkgs);
+ List<ResultFilter> filters = new ArrayList<ResultFilter>(mRemainingTestPkgs.size());
try {
installPrerequisiteApks(prerequisiteApks);
@@ -450,45 +450,18 @@
while (!mRemainingTestPkgs.isEmpty()) {
TestPackage knownTests = mRemainingTestPkgs.get(0);
+ ResultFilter filter = new ResultFilter(listener, knownTests);
+ filters.add(filter);
IRemoteTest test = knownTests.getTestForPackage();
-
- if (mForceAbi != null) {
- OptionSetter optionSetter = null;
- boolean hasField = false;
- try {
- optionSetter = new OptionSetter(test);
- if (optionSetter.getTypeForOption(AbiFormatter.FORCE_ABI_STRING)
- .equals("string")) {
- hasField = true;
- }
- } catch (ConfigurationException e) {
- // ignore if there are tests not taking force-abi option
- // for example native test do not need this option.
- }
- if (hasField) {
- try{
- optionSetter.setOptionValue(AbiFormatter.FORCE_ABI_STRING, mForceAbi);
- } catch (ConfigurationException e) {
- CLog.e(e);
- throw new RuntimeException(e);
- }
- }
- }
-
- if (test instanceof IDeviceTest) {
- ((IDeviceTest) test).setDevice(getDevice());
- }
if (test instanceof IBuildReceiver) {
((IBuildReceiver) test).setBuild(mBuildInfo);
}
- // setForceAbi should be exposed on device test.
- // This is not the best fix, but works.
- if (test instanceof InstrumentationTest) {
- ((InstrumentationTest)test).setForceAbi(mForceAbi);
+ if (test instanceof IDeviceTest) {
+ ((IDeviceTest) test).setDevice(getDevice());
}
- if (test instanceof DeqpTest) {
- ((DeqpTest)test).setCollectLogs(mCollectDeqpLogs);
+ if (test instanceof DeqpTestRunner) {
+ ((DeqpTestRunner)test).setCollectLogs(mCollectDeqpLogs);
}
forwardPackageDetails(knownTests.getPackageDef(), listener);
@@ -520,7 +493,9 @@
CLog.e(e);
throw e;
} finally {
- filter.reportUnexecutedTests();
+ for (ResultFilter filter : filters) {
+ filter.reportUnexecutedTests();
+ }
}
}
@@ -538,21 +513,19 @@
"CtsViewTestCases",
"CtsWidgetTestCases" );
long intervalInMSec = mRebootIntervalMin * 60 * 1000;
- if (mDevice.getSerialNumber().startsWith("emulator-")) {
+ if (mDisableReboot || mDevice.getSerialNumber().startsWith("emulator-")) {
return;
}
- if (!mDisableReboot) {
- long currentTime = System.currentTimeMillis();
- if (((currentTime - mPrevRebootTime) > intervalInMSec) ||
- rebootAfterList.contains(testFinished.getPackageDef().getName()) ||
- rebootBeforeList.contains(testToRun.getPackageDef().getName()) ) {
- Log.i(LOG_TAG,
- String.format("Rebooting after running package %s, before package %s",
- testFinished.getPackageDef().getName(),
- testToRun.getPackageDef().getName()));
- rebootDevice();
- mPrevRebootTime = System.currentTimeMillis();
- }
+ long currentTime = System.currentTimeMillis();
+ if (((currentTime - mPrevRebootTime) > intervalInMSec) ||
+ rebootAfterList.contains(testFinished.getPackageDef().getName()) ||
+ rebootBeforeList.contains(testToRun.getPackageDef().getName()) ) {
+ Log.i(LOG_TAG,
+ String.format("Rebooting after running package %s, before package %s",
+ testFinished.getPackageDef().getName(),
+ testToRun.getPackageDef().getName()));
+ rebootDevice();
+ mPrevRebootTime = System.currentTimeMillis();
}
}
@@ -592,13 +565,13 @@
}
/**
* Build the list of test packages to run
+ * @throws DeviceNotAvailableException
*/
- private List<TestPackage> buildTestsToRun() {
+ private List<TestPackage> buildTestsToRun() throws DeviceNotAvailableException {
List<TestPackage> testPkgList = new LinkedList<TestPackage>();
try {
ITestPackageRepo testRepo = createTestCaseRepo();
Collection<ITestPackageDef> testPkgDefs = getTestPackagesToRun(testRepo);
-
for (ITestPackageDef testPkgDef : testPkgDefs) {
addTestPackage(testPkgList, testPkgDef);
}
@@ -636,9 +609,10 @@
* @throws ParseException
* @throws FileNotFoundException
* @throws ConfigurationException
+ * @throws DeviceNotAvailableException
*/
private Collection<ITestPackageDef> getTestPackagesToRun(ITestPackageRepo testRepo)
- throws ParseException, FileNotFoundException, ConfigurationException {
+ throws ParseException, FileNotFoundException, ConfigurationException, DeviceNotAvailableException {
// use LinkedHashSet to have predictable iteration order
Set<ITestPackageDef> testPkgDefs = new LinkedHashSet<ITestPackageDef>();
if (mPlanName != null) {
@@ -646,55 +620,60 @@
File ctsPlanFile = mCtsBuild.getTestPlanFile(mPlanName);
ITestPlan plan = createPlan(mPlanName);
plan.parse(createXmlStream(ctsPlanFile));
- for (String uri : plan.getTestUris()) {
- if (!mExcludedPackageNames.contains(uri)) {
- ITestPackageDef testPackage = testRepo.getTestPackage(uri);
- if (testPackage != null) {
- testPackage.setExcludedTestFilter(plan.getExcludedTestFilter(uri));
- testPkgDefs.add(testPackage);
+ for (String id : plan.getTestIds()) {
+ if (!mExcludedPackageNames.contains(AbiUtils.parseId(id)[1])) {
+ ITestPackageDef testPackageDef = testRepo.getTestPackage(id);
+ if (testPackageDef != null) {
+ testPackageDef.setTestFilter(plan.getTestFilter(id));
+ testPkgDefs.add(testPackageDef);
} else {
- CLog.e("Could not find test package uri %s referenced in plan %s", uri,
+ CLog.e("Could not find test package id %s referenced in plan %s", id,
mPlanName);
}
}
}
} else if (mPackageNames.size() > 0){
Log.i(LOG_TAG, String.format("Executing CTS test packages %s", mPackageNames));
- for (String uri : mPackageNames) {
- ITestPackageDef testPackage = testRepo.getTestPackage(uri);
- if (testPackage != null) {
- testPkgDefs.add(testPackage);
+ for (String name : mPackageNames) {
+ Set<ITestPackageDef> testPackages = testRepo.getTestPackages(name);
+ if (!testPackages.isEmpty()) {
+ testPkgDefs.addAll(testPackages);
} else {
throw new IllegalArgumentException(String.format(
"Could not find test package %s. " +
- "Use 'list packages' to see available packages." , uri));
+ "Use 'list packages' to see available packages." , name));
}
}
} else if (mClassName != null) {
Log.i(LOG_TAG, String.format("Executing CTS test class %s", mClassName));
- // try to find package to run from class name
- String packageUri = testRepo.findPackageForTest(mClassName);
- if (packageUri != null) {
- ITestPackageDef testPackageDef = testRepo.getTestPackage(packageUri);
- testPackageDef.setClassName(mClassName, mMethodName);
- testPkgDefs.add(testPackageDef);
+ // try to find packages to run from class name
+ List<String> packageIds = testRepo.findPackageIdsForTest(mClassName);
+ if (!packageIds.isEmpty()) {
+ for (String packageId: packageIds) {
+ ITestPackageDef testPackageDef = testRepo.getTestPackage(packageId);
+ if (testPackageDef != null) {
+ testPackageDef.setClassName(mClassName, mMethodName);
+ testPkgDefs.add(testPackageDef);
+ }
+ }
} else {
Log.logAndDisplay(LogLevel.WARN, LOG_TAG, String.format(
"Could not find package for test class %s", mClassName));
}
} else if (mContinueSessionId != null) {
// create an in-memory derived plan that contains the notExecuted tests from previous
- // session
- // use timestamp as plan name so it will hopefully be unique
+ // session use timestamp as plan name so it will hopefully be unique
String uniquePlanName = Long.toString(System.currentTimeMillis());
PlanCreator planCreator = new PlanCreator(uniquePlanName, mContinueSessionId,
CtsTestStatus.NOT_EXECUTED);
ITestPlan plan = createPlan(planCreator);
- for (String uri : plan.getTestUris()) {
- if (!mExcludedPackageNames.contains(uri)) {
- ITestPackageDef testPackage = testRepo.getTestPackage(uri);
- testPackage.setExcludedTestFilter(plan.getExcludedTestFilter(uri));
- testPkgDefs.add(testPackage);
+ for (String id : plan.getTestIds()) {
+ if (!mExcludedPackageNames.contains(AbiUtils.parseId(id)[1])) {
+ ITestPackageDef testPackageDef = testRepo.getTestPackage(id);
+ if (testPackageDef != null) {
+ testPackageDef.setTestFilter(plan.getTestFilter(id));
+ testPkgDefs.add(testPackageDef);
+ }
}
}
} else {
@@ -735,6 +714,9 @@
}
/**
+ * FIXME eventually this should be removed once we get rid of CtsTestStubs, any other
+ * prerequisite apks should be installed by the test runner
+ *
* Install the collection of test apk file names
*
* @param prerequisiteApks
@@ -746,13 +728,8 @@
try {
File apkFile = mCtsBuild.getTestApp(apkName);
String errorCode = null;
- String[] options = {};
- if (mForceAbi != null) {
- String abi = AbiFormatter.getDefaultAbi(getDevice(), mForceAbi);
- if (abi != null) {
- options = new String[]{String.format("--abi %s ", abi)};
- }
- }
+ String abi = AbiFormatter.getDefaultAbi(getDevice(), mForceAbi);
+ String[] options = {AbiUtils.createAbiFlag(abi)};
errorCode = getDevice().installPackage(apkFile, true, options);
if (errorCode != null) {
CLog.e("Failed to install %s. Reason: %s", apkName, errorCode);
@@ -784,9 +761,14 @@
return null;
}
checkFields();
- List<TestPackage> allTests = buildTestsToRun();
+ List<TestPackage> allTests = null;
+ try {
+ allTests = buildTestsToRun();
+ } catch (DeviceNotAvailableException e) {
+ e.printStackTrace();
+ }
- if (allTests.size() <= 1) {
+ if (allTests == null || allTests.size() <= 1) {
Log.w(LOG_TAG, "no tests to shard!");
return null;
}
@@ -821,7 +803,8 @@
void collectDeviceInfo(ITestDevice device, CtsBuildHelper ctsBuild,
ITestInvocationListener listener) throws DeviceNotAvailableException {
if (!mSkipDeviceInfo) {
- DeviceInfoCollector.collectDeviceInfo(device, ctsBuild.getTestCasesDir(), listener);
+ String abi = AbiFormatter.getDefaultAbi(device, "");
+ DeviceInfoCollector.collectDeviceInfo(device, abi, ctsBuild.getTestCasesDir(), listener);
}
}
@@ -829,18 +812,39 @@
* Factory method for creating a {@link ITestPackageRepo}.
* <p/>
* Exposed for unit testing
+ * @throws DeviceNotAvailableException
*/
- ITestPackageRepo createTestCaseRepo() {
- return new TestPackageRepo(mCtsBuild.getTestCasesDir(), mIncludeKnownFailures);
+ ITestPackageRepo createTestCaseRepo() throws DeviceNotAvailableException {
+ return new TestPackageRepo(mCtsBuild.getTestCasesDir(), getAbis(), mIncludeKnownFailures);
}
/**
* Factory method for creating a {@link TestPlan}.
* <p/>
* Exposed for unit testing
+ * @throws DeviceNotAvailableException
*/
- ITestPlan createPlan(String planName) {
- return new TestPlan(planName);
+ ITestPlan createPlan(String planName) throws DeviceNotAvailableException {
+ return new TestPlan(planName, getAbis());
+ }
+
+ /**
+ * Gets the set of ABIs supported by both CTS and the device under test
+ * <p/>
+ * Exposed for unit testing
+ * @return The set of ABIs to run the tests on
+ * @throws DeviceNotAvailableException
+ */
+ Set<String> getAbis() throws DeviceNotAvailableException {
+ String bitness = (mForceAbi == null) ? "" : mForceAbi;
+ Set<String> abis = new HashSet<String>();
+ for (String abi : AbiFormatter.getSupportedAbis(mDevice, bitness)) {
+ if (AbiUtils.isAbiSupportedByCts(abi)) {
+ abis.add(abi);
+ }
+ }
+ Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "ABIs: " + abis);
+ return abis;
}
/**
@@ -848,9 +852,11 @@
* <p/>
* Exposed for unit testing
* @throws ConfigurationException
+ * @throws DeviceNotAvailableException
*/
- ITestPlan createPlan(PlanCreator planCreator) throws ConfigurationException {
- return planCreator.createDerivedPlan(mCtsBuild);
+ ITestPlan createPlan(PlanCreator planCreator)
+ throws ConfigurationException, DeviceNotAvailableException {
+ return planCreator.createDerivedPlan(mCtsBuild, getAbis());
}
/**
@@ -907,10 +913,11 @@
* @param listener
*/
private void forwardPackageDetails(ITestPackageDef def, ITestInvocationListener listener) {
- Map<String, String> metrics = new HashMap<String, String>(2);
+ Map<String, String> metrics = new HashMap<String, String>(3);
metrics.put(PACKAGE_NAME_METRIC, def.getName());
+ metrics.put(PACKAGE_ABI_METRIC, def.getAbi().getName());
metrics.put(PACKAGE_DIGEST_METRIC, def.getDigest());
- listener.testRunStarted(def.getUri(), 0);
+ listener.testRunStarted(def.getId(), 0);
listener.testRunEnded(0, metrics);
}
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DeqpTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DeqpTestRunner.java
similarity index 92%
rename from tools/tradefed-host/src/com/android/cts/tradefed/testtype/DeqpTest.java
rename to tools/tradefed-host/src/com/android/cts/tradefed/testtype/DeqpTestRunner.java
index 5149695..9077b89 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DeqpTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DeqpTestRunner.java
@@ -1,28 +1,19 @@
package com.android.cts.tradefed.testtype;
-import com.android.cts.tradefed.build.CtsBuildHelper;
-import com.android.ddmlib.IShellOutputReceiver;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.MultiLineReceiver;
import com.android.ddmlib.testrunner.ITestRunListener;
import com.android.ddmlib.testrunner.TestIdentifier;
-import com.android.tradefed.build.IBuildInfo;
-import com.android.tradefed.config.Option;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.result.ByteArrayInputStreamSource;
import com.android.tradefed.result.ITestInvocationListener;
import com.android.tradefed.result.LogDataType;
-import com.android.tradefed.testtype.IBuildReceiver;
+import com.android.tradefed.testtype.IAbi;
import com.android.tradefed.testtype.IDeviceTest;
import com.android.tradefed.testtype.IRemoteTest;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.lang.Thread;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -35,16 +26,17 @@
*
* Supports running drawElements Quality Program tests found under external/deqp.
*/
-public class DeqpTest implements IDeviceTest, IRemoteTest {
+public class DeqpTestRunner implements IDeviceTest, IRemoteTest {
final private int TESTCASE_BATCH_LIMIT = 1000;
private boolean mLogData;
private ITestDevice mDevice;
- private final String mUri;
+ private final String mPackageName;
private final String mName;
private Collection<TestIdentifier> mTests;
+ private IAbi mAbi;
private TestIdentifier mCurrentTestId;
private boolean mGotTestResult;
@@ -52,14 +44,21 @@
private ITestInvocationListener mListener;
- public DeqpTest(String uri, String name, Collection<TestIdentifier> tests) {
- mUri = uri;
+ public DeqpTestRunner(String packageName, String name, Collection<TestIdentifier> tests) {
+ mPackageName = packageName;
mName = name;
mTests = tests;
mLogData = false;
}
/**
+ * @param abi the ABI to run the test on
+ */
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
+ /**
* Enable or disable raw dEQP test log collection.
*/
public void setCollectLogs(boolean logData) {
@@ -70,14 +69,14 @@
* dEQP instrumentation parser
*/
class InstrumentationParser extends MultiLineReceiver {
- private DeqpTest mDeqpTests;
+ private DeqpTestRunner mDeqpTests;
private Map<String, String> mValues;
private String mCurrentName;
private String mCurrentValue;
- public InstrumentationParser(DeqpTest tests) {
+ public InstrumentationParser(DeqpTestRunner tests) {
mDeqpTests = tests;
}
@@ -86,8 +85,7 @@
*/
@Override
public void processNewLines(String[] lines) {
- for (String line : lines)
- {
+ for (String line : lines) {
if (mValues == null) mValues = new HashMap<String, String>();
if (line.startsWith("INSTRUMENTATION_STATUS_CODE: ")) {
@@ -151,8 +149,7 @@
/**
* Converts dEQP testcase path to TestIdentifier.
*/
- private TestIdentifier pathToIdentifier(String testPath)
- {
+ private TestIdentifier pathToIdentifier(String testPath) {
String[] components = testPath.split("\\.");
String name = components[components.length - 1];
String className = null;
@@ -172,7 +169,8 @@
* Handles beginning of dEQP session.
*/
private void handleBeginSession(Map<String, String> values) {
- mListener.testRunStarted(mUri, mTests.size());
+ String id = AbiUtils.createId(mAbi.getName(), mPackageName);
+ mListener.testRunStarted(id, mTests.size());
}
/**
@@ -286,8 +284,9 @@
public void handleStatus(Map<String, String> values) {
String eventType = values.get("dEQP-EventType");
- if (eventType == null)
+ if (eventType == null) {
return;
+ }
if (eventType.compareTo("BeginSession") == 0) {
handleBeginSession(values);
@@ -330,7 +329,7 @@
}
if (!tests.isEmpty()) {
- HashMap<String, ArrayList<String> > testGroups = new HashMap();
+ HashMap<String, ArrayList<String> > testGroups = new HashMap<>();
// Collect all sub testgroups
for (String test : tests) {
@@ -338,7 +337,7 @@
ArrayList<String> testGroup = testGroups.get(components[0]);
if (testGroup == null) {
- testGroup = new ArrayList();
+ testGroup = new ArrayList<String>();
testGroups.put(components[0], testGroup);
}
@@ -360,10 +359,10 @@
}
/**
- * Generates testacase trie from TestIdentifiers.
+ * Generates testcase trie from TestIdentifiers.
*/
private String generateTestCaseTrie(Collection<TestIdentifier> tests) {
- ArrayList<String> testPaths = new ArrayList();
+ ArrayList<String> testPaths = new ArrayList<String>();
for (TestIdentifier test : tests) {
testPaths.add(test.getClassName() + "." + test.getTestName());
@@ -391,6 +390,7 @@
String instrumentationName =
"com.drawelements.deqp/com.drawelements.deqp.testercore.DeqpInstrumentation";
+ // TODO run the test with the given ABI
String command = "am instrument -w -e deqpLogFileName \"" + logFileName
+ "\" -e deqpCmdLine \"--deqp-caselist-file=" + caseListFileName + " "
+ "--deqp-gl-config-name=rgba8888d24s8\" "
@@ -459,7 +459,8 @@
} else {
/* Pass all tests if OpenGL ES version is not supported */
Map <String, String> emptyMap = Collections.emptyMap();
- mListener.testRunStarted(mUri, mTests.size());
+ String id = AbiUtils.createId(mAbi.getName(), mPackageName);
+ mListener.testRunStarted(id, mTests.size());
for (TestIdentifier test : mTests) {
CLog.d("Skipping test '%s', Opengl ES version not supported", test.toString());
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DisplayTestRunner.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DisplayTestRunner.java
index 4c83aa9..59bfcf8 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DisplayTestRunner.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/DisplayTestRunner.java
@@ -25,7 +25,7 @@
* Secure settings cannot be changed from device CTS tests since system signature permission is
* required. Such settings can be modified by the shell user, so a host side test is used.
*/
-public class DisplayTestRunner extends InstrumentationApkTest {
+public class DisplayTestRunner extends CtsInstrumentationApkTest {
private static final String OVERLAY_DISPLAY_DEVICES_SETTING_NAME = "overlay_display_devices";
// Use a non-standard pattern, must match values in tests/tests/display/.../DisplayTest.java
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/GeeTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/GeeTest.java
index 035b4a2..9bfe151 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/GeeTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/GeeTest.java
@@ -23,6 +23,7 @@
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.IAbi;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.testtype.IDeviceTest;
import com.android.tradefed.testtype.IRemoteTest;
@@ -47,6 +48,7 @@
private CtsBuildHelper mCtsBuild;
private ITestDevice mDevice;
+ private IAbi mAbi;
private final String mPackageName;
private final String mExeName;
@@ -56,6 +58,13 @@
mExeName = exeName;
}
+ /**
+ * @param abi The ABI to run the test on
+ */
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
@Override
public void run(ITestInvocationListener listener) throws DeviceNotAvailableException {
if (installTest()) {
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/GeeTestResultParser.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/GeeTestResultParser.java
index c01da20..67bef35 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/GeeTestResultParser.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/GeeTestResultParser.java
@@ -99,7 +99,7 @@
private long mTotalRunTime = 0;
private boolean mTestInProgress = false;
private boolean mTestRunInProgress = false;
- private final String mTestRunName;
+ private final String mTestRunId;
private final Collection<ITestRunListener> mTestListeners;
/** Fake adding a package prefix if the test listener needs it. */
@@ -200,24 +200,24 @@
/**
* Creates the GTestResultParser.
*
- * @param testRunName the test run name to provide to
+ * @param testRunId the test run id to provide to
* {@link ITestRunListener#testRunStarted(String, int)}
* @param listeners informed of test results as the tests are executing
*/
- public GeeTestResultParser(String testRunName, Collection<ITestRunListener> listeners) {
- mTestRunName = testRunName;
+ public GeeTestResultParser(String testRunId, Collection<ITestRunListener> listeners) {
+ mTestRunId = testRunId;
mTestListeners = new ArrayList<ITestRunListener>(listeners);
}
/**
* Creates the GTestResultParser for a single listener.
*
- * @param testRunName the test run name to provide to
+ * @param testRunId the test run id to provide to
* {@link ITestRunListener#testRunStarted(String, int)}
* @param listener informed of test results as the tests are executing
*/
- public GeeTestResultParser(String testRunName, ITestRunListener listener) {
- mTestRunName = testRunName;
+ public GeeTestResultParser(String testRunId, ITestRunListener listener) {
+ mTestRunId = testRunId;
mTestListeners = new ArrayList<ITestRunListener>(1);
mTestListeners.add(listener);
}
@@ -355,7 +355,7 @@
// if start test run not reported yet
if (!mTestRunStartReported) {
for (ITestRunListener listener : mTestListeners) {
- listener.testRunStarted(mTestRunName, mNumTestsExpected);
+ listener.testRunStarted(mTestRunId, mNumTestsExpected);
}
mTestRunStartReported = true;
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java
index 0c3d9bc..ea01535 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageDef.java
@@ -17,6 +17,7 @@
package com.android.cts.tradefed.testtype;
import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.testtype.IAbi;
import com.android.tradefed.testtype.IRemoteTest;
import java.io.File;
@@ -30,10 +31,16 @@
public interface ITestPackageDef {
/**
- * Get the unique URI, aka the appPackageName, of the test package.
- * @return the {@link String} uri
+ * Get the id of the test package.
+ * @return the {@link String} id
*/
- public String getUri();
+ public String getId();
+
+ /**
+ * Get the appPackageName of the test package.
+ * @return the {@link String} appPackageName
+ */
+ public String getAppPackageName();
/**
* Creates a runnable {@link IRemoteTest} from info stored in this definition.
@@ -68,8 +75,7 @@
/**
* Return the sha1sum of the binary file for this test package.
* <p/>
- * Will only return a valid value after {@link #createTest(File, String, String)} has been
- * called.
+ * Will only return a valid value after {@link #createTest(File)} has been called.
*
* @return the sha1sum in {@link String} form
*/
@@ -81,11 +87,16 @@
public String getName();
/**
- * Set the filter to use to exclude tests
- *
- * @param excludedTestFilter
+ * @return the ABI of this test package.
*/
- public void setExcludedTestFilter(TestFilter excludedTestFilter);
+ public IAbi getAbi();
+
+ /**
+ * Set the filter to use for tests
+ *
+ * @param testFilter
+ */
+ public void setTestFilter(TestFilter testFilter);
/**
* Restrict this test package to run a specific class and method name
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageRepo.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageRepo.java
index 53451f1..d1d4111 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageRepo.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPackageRepo.java
@@ -16,8 +16,10 @@
package com.android.cts.tradefed.testtype;
-import java.util.Collection;
+import com.android.cts.util.AbiUtils;
+import java.util.List;
+import java.util.Set;
/**
* Interface for accessing tests from the CTS repository.
@@ -25,24 +27,38 @@
public interface ITestPackageRepo {
/**
- * Get a {@link TestPackageDef} given a uri
+ * Get a {@link TestPackageDef} given an id.
*
- * @param testUri the string uris
- * @return a {@link TestPackageDef} or <code>null</code> if the uri cannot be found in repo
+ * @param id the unique identifier of this test package, generated by
+ * {@link AbiUtils#createId(String, String)}.
+ * @return a {@link TestPackageDef}
*/
- public ITestPackageDef getTestPackage(String testUri);
+ public ITestPackageDef getTestPackage(String id);
/**
- * Attempt to find the package uri for a given test class name
+ * Get a {@link Set} of {@link TestPackageDef} given a name
+ *
+ * @param name the string package name
+ * @return a {@link Set} of {@link TestPackageDef}
+ */
+ public Set<ITestPackageDef> getTestPackages(String name);
+
+ /**
+ * Attempt to find the package ids for a given test class name
*
* @param testClassName the test class name
- * @return the package uri or <code>null</code> if the package cannot be found
+ * @return a {@link List} of package ids.
*/
- public String findPackageForTest(String testClassName);
+ public List<String> findPackageIdsForTest(String testClassName);
/**
- * Return a sorted {@link Collection} of all package names found in repo.
+ * @return a sorted {@link List} of all package ids found in repo.
*/
- public Collection<String> getPackageNames();
+ public List<String> getPackageIds();
+
+ /**
+ * @return a sorted {@link List} of all package names found in repo.
+ */
+ public List<String> getPackageNames();
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPlan.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPlan.java
index 191cefd..21b2d0a 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPlan.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ITestPlan.java
@@ -37,36 +37,36 @@
public void parse(InputStream xmlStream) throws ParseException;
/**
- * Gets the list of test uris contained in this plan.
+ * Gets a sorted list of test ids contained in this plan.
*/
- public Collection<String> getTestUris();
+ public Collection<String> getTestIds();
/**
- * Gets the {@link TestFilter} that should be used to exclude tests from given package.
+ * Gets the {@link TestFilter} that should be used to filter tests from given package.
*/
- public TestFilter getExcludedTestFilter(String uri);
+ public TestFilter getTestFilter(String id);
/**
* Add a package to this test plan
- * @param uri
+ * @param id
*/
- public void addPackage(String uri);
+ public void addPackage(String id);
/**
* Add a excluded test to this test plan
*
- * @param uri the package uri
+ * @param id the package id
* @param testToExclude the test to exclude for given package
*/
- public void addExcludedTest(String uri, TestIdentifier testToExclude);
+ public void addExcludedTest(String id, TestIdentifier testToExclude);
/**
* Adds the list of excluded tests for given package
*
- * @param pkgUri
+ * @param id
* @param excludedTests
*/
- public void addExcludedTests(String uri, Collection<TestIdentifier> excludedTests);
+ public void addExcludedTests(String id, Collection<TestIdentifier> excludedTests);
/**
* Serialize the contents of this test plan.
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JUnitDeviceTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JUnitDeviceTest.java
index 4adcb0b..5efa7cd 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JUnitDeviceTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JUnitDeviceTest.java
@@ -25,6 +25,7 @@
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.IAbi;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.testtype.IDeviceTest;
import com.android.tradefed.testtype.IRemoteTest;
@@ -52,10 +53,6 @@
private static final String TMP_DIR = "/data/local/tmp/";
- @Option(name = AbiFormatter.FORCE_ABI_STRING, description = AbiFormatter.FORCE_ABI_DESCRIPTION,
- importance = Importance.IF_UNSET)
- private String mForceAbi = null;
-
@Option(name = "junit-device-runtime",
description = "The name of the runtime to use on the device",
importance = Importance.ALWAYS)
@@ -79,12 +76,19 @@
private String mRuntimeArgs;
-
+ private IAbi mAbi;
private static final String JUNIT_JAR = "cts-junit.jar";
private Set<String> mTestJars = new HashSet<String>(Arrays.asList(JUNIT_JAR));
+ /**
+ * @param abi The ABI to run the test on
+ */
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
@Override
public ITestDevice getDevice() {
return mDevice;
@@ -127,7 +131,7 @@
"com.android.cts.junit.SingleJUnitTestRunner %s#%s",
mDeviceTestTmpPath, mRuntimePath, jarPath, mRuntimeArgs,
testId.getClassName(), testId.getTestName());
- String cmd = AbiFormatter.formatCmdForAbi(cmdLine, mForceAbi);
+ String cmd = AbiFormatter.formatCmdForAbi(cmdLine, mAbi.getBitness());
CLog.d("Running %s", cmd);
listener.testStarted(testId);
mDevice.executeShellCommand(cmd, resultParser, mMaxTimeToOutputResponse,
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JarHostTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JarHostTest.java
index 22a016a..9d9596e 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JarHostTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/JarHostTest.java
@@ -23,8 +23,9 @@
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.result.ITestInvocationListener;
-
import com.android.tradefed.testtype.DeviceTestResult.RuntimeDeviceNotAvailableException;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.testtype.IDeviceTest;
import com.android.tradefed.testtype.IRemoteTest;
@@ -59,10 +60,17 @@
private String mRunName;
private CtsBuildHelper mCtsBuild = null;
private IBuildInfo mBuildInfo = null;
-
+ private IAbi mAbi;
private ClassLoader mClassLoader;
/**
+ * @param abi the ABI to run the test on
+ */
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
+ /**
* {@inheritDoc}
*/
@Override
@@ -133,7 +141,7 @@
* Tests that take longer than this amount will be failed with a {@link TestTimeoutException}
* as the cause.
*
- * @param testTimeout
+ * @param testTimeoutMs
*/
void setTimeout(long testTimeoutMs) {
mTimeoutMs = testTimeoutMs;
@@ -190,14 +198,6 @@
}
/**
- * setOptions sets options to the tests invoked from this test.
- * It is used to passing options from JarHostTest to the tests started by JarHostTest.
- * The default implementation does nothing.
- */
- protected void setOptions(Test junitTest) throws ConfigurationException {
- }
-
- /**
* Run test with timeout support.
*/
private void runTest(TestIdentifier testId, final Test junitTest, final TestResult junitResult) {
@@ -210,14 +210,12 @@
deviceTest.setDevice(getDevice().getIDevice());
deviceTest.setTestAppPath(mCtsBuild.getTestCasesDir().getAbsolutePath());
}
+ if (junitTest instanceof IAbiReceiver) {
+ ((IAbiReceiver)junitTest).setAbi(mAbi);
+ }
if (junitTest instanceof IBuildReceiver) {
((IBuildReceiver)junitTest).setBuild(mBuildInfo);
}
- try {
- setOptions(junitTest);
- } catch (ConfigurationException e) {
- Log.e(LOG_TAG, e.toString());
- }
TestRunnable testRunnable = new TestRunnable(junitTest, junitResult);
CommandStatus status = RunUtil.getDefault().runTimed(mTimeoutMs, testRunnable, true);
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/PrintTestRunner.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/PrintTestRunner.java
index a7a6ccc..44d2d3a 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/PrintTestRunner.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/PrintTestRunner.java
@@ -18,12 +18,14 @@
import com.android.cts.tradefed.build.CtsBuildHelper;
import com.android.cts.tradefed.targetprep.SettingsToggler;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner;
import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner.TestSize;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.IAbi;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.testtype.IDeviceTest;
import com.android.tradefed.testtype.IRemoteTest;
@@ -65,6 +67,7 @@
private CtsBuildHelper mCtsBuild;
+ private IAbi mAbi;
private String mPackageName;
private String mRunnerName = "android.test.InstrumentationTestRunner";
private String mTestClassName;
@@ -75,6 +78,13 @@
private String mRunName = null;
private Map<String, String> mInstrArgMap = new HashMap<String, String>();
+ /**
+ * @param abi The ABI to run the test on
+ */
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
@Override
public void setBuild(IBuildInfo buildInfo) {
mCtsBuild = CtsBuildHelper.createBuildHelper(buildInfo);
@@ -191,8 +201,9 @@
private void installTestsAndServicesApk() throws DeviceNotAvailableException {
try {
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
String installCode = getDevice().installPackage(mCtsBuild.getTestApp(
- PRINT_TEST_AND_SERVICES_APP_NAME), true);
+ PRINT_TEST_AND_SERVICES_APP_NAME), true, options);
if (installCode != null) {
throw new IllegalArgumentException("Failed to install "
+ PRINT_TEST_AND_SERVICES_APP_NAME + " on " + getDevice().getSerialNumber()
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ResultFilter.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ResultFilter.java
index e8fdad8..e3fcdc4 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ResultFilter.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/ResultFilter.java
@@ -28,6 +28,7 @@
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
/**
* A {@link ITestInvocationListener} that filters test results based on the set of expected tests
@@ -38,37 +39,35 @@
*/
class ResultFilter extends ResultForwarder {
- private final Map<String, Collection<TestIdentifier>> mKnownTestsMap;
- private final Map<String, Collection<TestIdentifier>> mRemainingTestsMap;
- private String mCurrentTestRun = null;
+ private final Set<TestIdentifier> mKnownTests;
+ private final Set<TestIdentifier> mRemainingTests;
+ private final String mTestRun;
/**
* Create a {@link ResultFilter}.
*
* @param listener the real {@link ITestInvocationListener} to forward results to
*/
- ResultFilter(ITestInvocationListener listener, List<TestPackage> testPackages) {
+ ResultFilter(ITestInvocationListener listener, TestPackage testPackage) {
super(listener);
-
- mKnownTestsMap = new HashMap<String, Collection<TestIdentifier>>();
+ mTestRun = testPackage.getTestRunName();
+ Collection<TestIdentifier> tests = testPackage.getKnownTests();
+ mKnownTests = new HashSet<TestIdentifier>(tests);
// use LinkedHashMap for predictable test order
- mRemainingTestsMap = new LinkedHashMap<String, Collection<TestIdentifier>>();
-
- for (TestPackage testPkg : testPackages) {
- mKnownTestsMap.put(testPkg.getTestRunName(), new HashSet<TestIdentifier>(
- testPkg.getKnownTests()));
- mRemainingTestsMap.put(testPkg.getTestRunName(), new LinkedHashSet<TestIdentifier>(
- testPkg.getKnownTests()));
- }
+ mRemainingTests = new LinkedHashSet<TestIdentifier>(tests);
}
+
/**
* {@inheritDoc}
*/
@Override
public void testRunStarted(String runName, int testCount) {
- super.testRunStarted(runName, testCount);
- mCurrentTestRun = runName;
+ if (mTestRun.equals(runName)) {
+ super.testRunStarted(runName, testCount);
+ } else {
+ CLog.d("Skipping reporting unknown test run %s", runName);
+ }
}
/**
@@ -109,10 +108,7 @@
* @return
*/
private boolean isKnownTest(TestIdentifier test) {
- if (mCurrentTestRun != null && mKnownTestsMap.containsKey(mCurrentTestRun)) {
- return mKnownTestsMap.get(mCurrentTestRun).contains(test);
- }
- return false;
+ return mKnownTests.contains(test);
}
/**
@@ -120,26 +116,23 @@
* @param test
*/
private void removeExecutedTest(TestIdentifier test) {
- if (mCurrentTestRun != null && mRemainingTestsMap.containsKey(mCurrentTestRun)) {
- mRemainingTestsMap.get(mCurrentTestRun).remove(test);
- }
+ mRemainingTests.remove(test);
}
/**
* Report the set of expected tests that were not executed
*/
public void reportUnexecutedTests() {
- for (Map.Entry<String, Collection<TestIdentifier>> entry : mRemainingTestsMap.entrySet()) {
- if (!entry.getValue().isEmpty()) {
- super.testRunStarted(entry.getKey(), entry.getValue().size());
- for (TestIdentifier test : entry.getValue()) {
- // an unexecuted test is currently reported as a 'testStarted' event without a
- // 'testEnded'. TODO: consider adding an explict API for reporting an unexecuted
- // test
- super.testStarted(test);
- }
- super.testRunEnded(0, new HashMap<String,String>());
- }
+ if (mRemainingTests.isEmpty()) {
+ return;
}
+ super.testRunStarted(mTestRun, mRemainingTests.size());
+ for (TestIdentifier test : mRemainingTests) {
+ // an unexecuted test is currently reported as a 'testStarted' event without a
+ // 'testEnded'. TODO: consider adding an explict API for reporting an unexecuted
+ // test
+ super.testStarted(test);
+ }
+ super.testRunEnded(0, new HashMap<String, String>());
}
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
index 7a9756c..45c176a 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageDef.java
@@ -16,9 +16,11 @@
package com.android.cts.tradefed.testtype;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.Log.LogLevel;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.testtype.IAbi;
import com.android.tradefed.testtype.IRemoteTest;
import com.android.tradefed.testtype.InstrumentationTest;
import com.android.tradefed.util.StreamUtil;
@@ -61,7 +63,7 @@
private static final String SIGNATURE_TEST_METHOD = "testSignature";
private static final String SIGNATURE_TEST_CLASS = "android.tests.sigtest.SignatureTest";
- private String mUri = null;
+ private String mAppPackageName = null;
private String mAppNameSpace = null;
private String mName = null;
private String mRunner = null;
@@ -71,6 +73,7 @@
private boolean mIsSignatureTest = false;
private String mTestPackageName = null;
private String mDigest = null;
+ private IAbi mAbi = null;
// use a LinkedHashSet for predictable iteration insertion-order, and fast
// lookups
@@ -81,7 +84,7 @@
// dynamic options, not parsed from package xml
private String mClassName;
private String mMethodName;
- private TestFilter mExcludedTestFilter = new TestFilter();
+ private TestFilter mTestFilter = new TestFilter();
private String mTargetBinaryName;
private String mTargetNameSpace;
// only timeout per package is supported. To change this to method granularity,
@@ -89,16 +92,36 @@
// So for now, only max timeout for the package is used.
private int mTimeoutInMins = -1;
- void setUri(String uri) {
- mUri = uri;
+ @Override
+ public IAbi getAbi() {
+ return mAbi;
+ }
+
+ /**
+ * @param abi the ABI to run this package on
+ */
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
+ }
+
+ /**
+ * @return unique id representing this test package for this ABI.
+ */
+ @Override
+ public String getId() {
+ return AbiUtils.createId(getAbi().getName(), getAppPackageName());
+ }
+
+ void setAppPackageName(String appPackageName) {
+ mAppPackageName = appPackageName;
}
/**
* {@inheritDoc}
*/
@Override
- public String getUri() {
- return mUri;
+ public String getAppPackageName() {
+ return mAppPackageName;
}
void setRunTimeArgs(String runTimeArgs) {
@@ -193,8 +216,8 @@
* {@inheritDoc}
*/
@Override
- public void setExcludedTestFilter(TestFilter excludeFilter) {
- mExcludedTestFilter = excludeFilter;
+ public void setTestFilter(TestFilter testFilter) {
+ mTestFilter = testFilter;
}
/**
@@ -211,7 +234,7 @@
*/
@Override
public IRemoteTest createTest(File testCaseDir) {
- mExcludedTestFilter.setTestInclusion(mClassName, mMethodName);
+ mTestFilter.setTestInclusion(mClassName, mMethodName);
mTests = filterTests();
if (HOST_SIDE_ONLY_TEST.equals(mTestType)) {
@@ -221,26 +244,34 @@
CLog.d("Setting new timeout to " + mTimeoutInMins + " mins");
hostTest.setTimeout(mTimeoutInMins * 60 * 1000);
}
- hostTest.setRunName(getUri());
+ hostTest.setRunName(mAppPackageName);
hostTest.setJarFileName(mJarPath);
hostTest.setTests(mTests);
+ hostTest.setAbi(mAbi);
mDigest = generateDigest(testCaseDir, mJarPath);
return hostTest;
} else if (VM_HOST_TEST.equals(mTestType)) {
CLog.d("Creating vm host test for %s", mName);
VMHostTest vmHostTest = new VMHostTest();
- vmHostTest.setRunName(getUri());
+ vmHostTest.setRunName(mAppPackageName);
vmHostTest.setJarFileName(mJarPath);
vmHostTest.setTests(mTests);
+ vmHostTest.setAbi(mAbi);
mDigest = generateDigest(testCaseDir, mJarPath);
return vmHostTest;
} else if (DEQP_TEST.equals(mTestType)) {
- return new DeqpTest(mUri, mName, mTests);
+ DeqpTestRunner deqpTest = new DeqpTestRunner(mAppPackageName, mName, mTests);
+ deqpTest.setAbi(mAbi);
+ return deqpTest;
} else if (NATIVE_TEST.equals(mTestType)) {
- return new GeeTest(mUri, mName);
+ GeeTest geeTest = new GeeTest(mAppPackageName, mName);
+ geeTest.setAbi(mAbi);
+ return geeTest;
} else if (WRAPPED_NATIVE_TEST.equals(mTestType)) {
CLog.d("Creating new wrapped native test for %s", mName);
- return new WrappedGTest(mAppNameSpace, mUri, mName, mRunner);
+ WrappedGTest wrappedGeeTest = new WrappedGTest(mAppNameSpace, mAppPackageName, mName, mRunner);
+ wrappedGeeTest.setAbi(mAbi);
+ return wrappedGeeTest;
} else if (ACCESSIBILITY_TEST.equals(mTestType)) {
AccessibilityTestRunner test = new AccessibilityTestRunner();
return setInstrumentationTest(test, testCaseDir);
@@ -248,6 +279,7 @@
PrintTestRunner test = new PrintTestRunner();
return setPrintTest(test, testCaseDir);
} else if (ACCESSIBILITY_SERVICE_TEST.equals(mTestType)) {
+ @SuppressWarnings("deprecation")
AccessibilityServiceTestRunner test = new AccessibilityServiceTestRunner();
return setInstrumentationTest(test, testCaseDir);
} else if (DISPLAY_TEST.equals(mTestType)) {
@@ -261,14 +293,16 @@
// specialized instrumentation. Eventually this special case for signatureTest can be
// removed, and it can be treated just like a normal InstrumentationTest
CLog.d("Creating signature test %s", mName);
- InstrumentationApkTest instrTest = new InstrumentationApkTest();
+ CtsInstrumentationApkTest instrTest = new CtsInstrumentationApkTest();
instrTest.setPackageName(mAppNameSpace);
instrTest.setRunnerName("android.test.InstrumentationTestRunner");
instrTest.setClassName(SIGNATURE_TEST_CLASS);
instrTest.setMethodName(SIGNATURE_TEST_METHOD);
- // set expected tests to the single signature test
- TestIdentifier t = new TestIdentifier(SIGNATURE_TEST_CLASS, SIGNATURE_TEST_METHOD);
+ instrTest.setAbi(mAbi);
mTests.clear();
+ // set expected tests to the single signature test
+ TestIdentifier t = new TestIdentifier(
+ SIGNATURE_TEST_CLASS, SIGNATURE_TEST_METHOD);
mTests.add(t);
// mName means 'apk file name' for instrumentation tests
instrTest.addInstallApk(String.format("%s.apk", mName), mAppNameSpace);
@@ -277,15 +311,16 @@
} else if (JUNIT_DEVICE_TEST.equals(mTestType)){
CLog.d("Creating JUnit device test %s", mName);
JUnitDeviceTest jUnitDeviceTest = new JUnitDeviceTest();
- jUnitDeviceTest.setRunName(getUri());
+ jUnitDeviceTest.setRunName(mAppPackageName);
jUnitDeviceTest.addTestJarFileName(mJarPath);
jUnitDeviceTest.addRunTimeArgs(mRunTimeArgs);
jUnitDeviceTest.setTests(mTests);
+ jUnitDeviceTest.setAbi(mAbi);
mDigest = generateDigest(testCaseDir, mJarPath);
return jUnitDeviceTest;
} else {
CLog.d("Creating instrumentation test for %s", mName);
- InstrumentationApkTest instrTest = new InstrumentationApkTest();
+ CtsInstrumentationApkTest instrTest = new CtsInstrumentationApkTest();
if (mTimeoutInMins >= 0) {
// as timeout cannot be set for each test,
// increase the time-out of the whole package
@@ -298,31 +333,33 @@
private PrintTestRunner setPrintTest(PrintTestRunner printTest,
File testCaseDir) {
- printTest.setRunName(getUri());
+ printTest.setRunName(mAppPackageName);
printTest.setPackageName(mAppNameSpace);
printTest.setRunnerName(mRunner);
printTest.setTestPackageName(mTestPackageName);
printTest.setClassName(mClassName);
printTest.setMethodName(mMethodName);
+ printTest.setAbi(mAbi);
mDigest = generateDigest(testCaseDir, String.format("%s.apk", mName));
return printTest;
}
/**
- * Populates given {@link InstrumentationApkTest} with data from the package xml.
+ * Populates given {@link CtsInstrumentationApkTest} with data from the package xml.
*
* @param testCaseDir
* @param instrTest
* @return the populated {@link InstrumentationTest} or <code>null</code>
*/
- private InstrumentationTest setInstrumentationTest(InstrumentationApkTest instrTest,
+ private InstrumentationTest setInstrumentationTest(CtsInstrumentationApkTest instrTest,
File testCaseDir) {
- instrTest.setRunName(getUri());
+ instrTest.setRunName(mAppPackageName);
instrTest.setPackageName(mAppNameSpace);
instrTest.setRunnerName(mRunner);
instrTest.setTestPackageName(mTestPackageName);
instrTest.setClassName(mClassName);
instrTest.setMethodName(mMethodName);
+ instrTest.setAbi(mAbi);
instrTest.setTestsToRun(mTests, false
/* force batch mode off to always run using testFile */);
instrTest.setReRunUsingTestFile(true);
@@ -342,6 +379,7 @@
* @param uiautomatorTest
* @return the populated {@link UiAutomatorJarTest} or <code>null</code>
*/
+ @SuppressWarnings("deprecation")
private IRemoteTest setUiAutomatorTest(UiAutomatorJarTest uiautomatorTest) {
uiautomatorTest.setInstallArtifacts(getJarPath());
if (mClassName != null) {
@@ -353,19 +391,19 @@
} else {
uiautomatorTest.addClassNames(mTestClasses);
}
- uiautomatorTest.setRunName(getUri());
+ uiautomatorTest.setRunName(mAppPackageName);
uiautomatorTest.setCaptureLogs(false);
return uiautomatorTest;
}
/**
- * Filter the tests to run based on list of excluded tests, class and method name.
+ * Filter the tests to run based on list of included/excluded tests, class and method name.
*
* @return the filtered collection of tests
*/
private Collection<TestIdentifier> filterTests() {
- mExcludedTestFilter.setTestInclusion(mClassName, mMethodName);
- return mExcludedTestFilter.filter(mTests);
+ mTestFilter.setTestInclusion(mClassName, mMethodName);
+ return mTestFilter.filter(mTests);
}
/**
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageRepo.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageRepo.java
index 0f3704d..4c549e2 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageRepo.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageRepo.java
@@ -15,6 +15,7 @@
*/
package com.android.cts.tradefed.testtype;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.Log;
import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
@@ -25,11 +26,12 @@
import java.io.FilenameFilter;
import java.io.InputStream;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.Collections;
-import java.util.Hashtable;
+import java.util.HashSet;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
/**
* Retrieves CTS test package definitions from the repository.
@@ -40,19 +42,27 @@
private final File mTestCaseDir;
- /** mapping of uri to test definition */
- private final Map<String, TestPackageDef> mTestMap;
-
+ /** mapping of ABI to a mapping of appPackageName to test definition */
+ private final Map<String, Map<String, TestPackageDef>> mTestMap;
+ /** set of ABIs */
+ private final Set<String> mAbis;
private final boolean mIncludeKnownFailures;
/**
* Creates a {@link TestPackageRepo}, initialized from provided repo files
*
* @param testCaseDir directory containing all test case definition xml and build files
+ * @param abis Holds the ABIs which the test must be run against. This must be a subset of the
+ * ABIs supported by the device under test.
+ * @param includeKnownFailures Whether to run tests which are known to fail.
*/
- public TestPackageRepo(File testCaseDir, boolean includeKnownFailures) {
+ public TestPackageRepo(File testCaseDir, Set<String> abis, boolean includeKnownFailures) {
mTestCaseDir = testCaseDir;
- mTestMap = new Hashtable<String, TestPackageDef>();
+ mTestMap = new HashMap<String, Map<String, TestPackageDef>>();
+ mAbis = abis;
+ for (String abi : abis) {
+ mTestMap.put(abi, new HashMap<String, TestPackageDef>());
+ }
mIncludeKnownFailures = includeKnownFailures;
parse(mTestCaseDir);
}
@@ -68,12 +78,14 @@
}
private void parseTestFromXml(File xmlFile) {
- TestPackageXmlParser parser = new TestPackageXmlParser(mIncludeKnownFailures);
+ TestPackageXmlParser parser = new TestPackageXmlParser(mAbis, mIncludeKnownFailures);
try {
parser.parse(createStreamFromFile(xmlFile));
- TestPackageDef def = parser.getTestPackageDef();
- if (def != null) {
- mTestMap.put(def.getUri(), def);
+ Set<TestPackageDef> defs = parser.getTestPackageDefs();
+ if (!defs.isEmpty()) {
+ for (TestPackageDef def : defs) {
+ mTestMap.get(def.getAbi().getName()).put(def.getAppPackageName(), def);
+ }
} else {
Log.w(LOG_TAG, String.format("Could not find test package info in xml file %s",
xmlFile.getAbsolutePath()));
@@ -117,30 +129,74 @@
* {@inheritDoc}
*/
@Override
- public ITestPackageDef getTestPackage(String testUri) {
- return mTestMap.get(testUri);
+ public ITestPackageDef getTestPackage(String id) {
+ String[] parts = AbiUtils.parseId(id);
+ String abi = parts[0];
+ String name = parts[1];
+ if (mTestMap.containsKey(abi) && mTestMap.get(abi).containsKey(name)) {
+ return mTestMap.get(abi).get(name);
+ }
+ return null;
}
/**
* {@inheritDoc}
*/
@Override
- public String findPackageForTest(String testClassName) {
- for (Map.Entry<String, TestPackageDef> entry : mTestMap.entrySet()) {
- if (entry.getValue().isKnownTestClass(testClassName)) {
- return entry.getKey();
+ public Set<ITestPackageDef> getTestPackages(String appPackageName) {
+ Set<ITestPackageDef> defs = new HashSet<ITestPackageDef>();
+ for (String abi : mAbis) {
+ if (mTestMap.get(abi).containsKey(appPackageName)) {
+ defs.add(mTestMap.get(abi).get(appPackageName));
}
}
- return null;
+ return defs;
}
/**
- * @return list of all package names found in repo
+ * {@inheritDoc}
*/
@Override
- public Collection<String> getPackageNames() {
- List<String> packageNames = new ArrayList<String>();
- packageNames.addAll(mTestMap.keySet());
+ public List<String> findPackageIdsForTest(String testClassName) {
+ Set<String> ids = new HashSet<String>();
+ for (String abi : mTestMap.keySet()) {
+ for (String name : mTestMap.get(abi).keySet()) {
+ if (mTestMap.get(abi).get(name).isKnownTestClass(testClassName)) {
+ ids.add(AbiUtils.createId(abi, name));
+ }
+ }
+ }
+ List<String> idList = new ArrayList<String>(ids);
+ Collections.sort(idList);
+ return idList;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<String> getPackageIds() {
+ Set<String> ids = new HashSet<String>();
+ for (String abi : mAbis) {
+ for (String name : mTestMap.get(abi).keySet()) {
+ ids.add(AbiUtils.createId(abi, name));
+ }
+ }
+ List<String> idList = new ArrayList<String>(ids);
+ Collections.sort(idList);
+ return idList;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public List<String> getPackageNames() {
+ Set<String> names = new HashSet<String>();
+ for (String abi : mAbis) {
+ names.addAll(mTestMap.get(abi).keySet());
+ }
+ List<String> packageNames = new ArrayList<String>(names);
Collections.sort(packageNames);
return packageNames;
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
index 5d10dfc..71279c7 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPackageXmlParser.java
@@ -15,6 +15,7 @@
*/
package com.android.cts.tradefed.testtype;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.Log;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.util.xml.AbstractXmlParser;
@@ -22,7 +23,11 @@
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
import java.util.Stack;
/**
@@ -35,11 +40,18 @@
private static final String LOG_TAG = "TestPackageXmlParser";
+ private final Set<String> mAbis;
private final boolean mIncludeKnownFailures;
- private TestPackageDef mPackageDef;
+ private Map<String, TestPackageDef> mPackageDefs = new HashMap<String, TestPackageDef>();
- public TestPackageXmlParser(boolean includeKnownFailures) {
+ /**
+ * @param abis Holds the ABIs which the test must be run against. This must be a subset of the
+ * ABIs supported by the device under test.
+ * @param includeKnownFailures Whether to run tests which are known to fail.
+ */
+ public TestPackageXmlParser(Set<String> abis, boolean includeKnownFailures) {
+ mAbis = abis;
mIncludeKnownFailures = includeKnownFailures;
}
@@ -65,32 +77,37 @@
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) {
if (TEST_PACKAGE_TAG.equals(localName)) {
- // appPackageName is used as the uri
- final String entryUriValue = attributes.getValue("appPackageName");
+ final String appPackageName = attributes.getValue("appPackageName");
final String testPackageNameSpace = attributes.getValue("appNameSpace");
final String packageName = attributes.getValue("name");
final String runnerName = attributes.getValue("runner");
final String jarPath = attributes.getValue("jarPath");
- final String signatureCheck = attributes.getValue("signatureCheck");
+ final boolean signatureCheck = parseBoolean(attributes.getValue("signatureCheck"));
final String javaPackageFilter = attributes.getValue("javaPackageFilter");
final String targetBinaryName = attributes.getValue("targetBinaryName");
final String targetNameSpace = attributes.getValue("targetNameSpace");
final String runTimeArgs = attributes.getValue("runtimeArgs");
+ final String testType = getTestType(attributes);
- mPackageDef = new TestPackageDef();
- mPackageDef.setUri(entryUriValue);
- mPackageDef.setAppNameSpace(testPackageNameSpace);
- mPackageDef.setName(packageName);
- mPackageDef.setRunner(runnerName);
- mPackageDef.setTestType(getTestType(attributes));
- mPackageDef.setJarPath(jarPath);
- mPackageDef.setIsSignatureCheck(parseBoolean(signatureCheck));
- mPackageDef.setRunTimeArgs(runTimeArgs);
- if (!"".equals(javaPackageFilter)) {
- mPackageDef.setTestPackageName(javaPackageFilter);
+ for (String abiName : mAbis) {
+ Abi abi = new Abi(abiName, AbiUtils.getBitness(abiName));
+ TestPackageDef packageDef = new TestPackageDef();
+ packageDef.setAppPackageName(appPackageName);
+ packageDef.setAppNameSpace(testPackageNameSpace);
+ packageDef.setName(packageName);
+ packageDef.setRunner(runnerName);
+ packageDef.setTestType(testType);
+ packageDef.setJarPath(jarPath);
+ packageDef.setIsSignatureCheck(signatureCheck);
+ packageDef.setRunTimeArgs(runTimeArgs);
+ if (!"".equals(javaPackageFilter)) {
+ packageDef.setTestPackageName(javaPackageFilter);
+ }
+ packageDef.setTargetBinaryName(targetBinaryName);
+ packageDef.setTargetNameSpace(targetNameSpace);
+ packageDef.setAbi(abi);
+ mPackageDefs.put(abiName, packageDef);
}
- mPackageDef.setTargetBinaryName(targetBinaryName);
- mPackageDef.setTargetNameSpace(targetNameSpace);
// reset the class name
mClassNameStack = new Stack<String>();
@@ -112,7 +129,7 @@
}
} else if (TEST_TAG.equals(localName)) {
String methodName = attributes.getValue("name");
- if (mPackageDef == null) {
+ if (mPackageDefs.isEmpty()) {
Log.e(LOG_TAG, String.format(
"Invalid XML: encountered a '%s' tag not enclosed within a '%s' tag",
TEST_TAG, TEST_PACKAGE_TAG));
@@ -133,11 +150,26 @@
if (timeoutStr != null) {
timeout = Integer.parseInt(timeoutStr);
}
- TestIdentifier testId = new TestIdentifier(classNameBuilder.toString(),
- methodName);
boolean isKnownFailure = "failure".equals(attributes.getValue("expectation"));
if (!isKnownFailure || mIncludeKnownFailures) {
- mPackageDef.addTest(testId, timeout);
+ String abiList = attributes.getValue("abis");
+ Set<String> abis = new HashSet<String>();
+ if (abiList == null) {
+ // If no specification, add all supported abis
+ abis.addAll(mAbis);
+ } else {
+ for (String abi : abiList.split(", ")) {
+ if (mAbis.contains(abi)) {
+ // Else only add the abi which are supported
+ abis.add(abi);
+ }
+ }
+ }
+ for (String abi : abis) {
+ TestIdentifier testId = new TestIdentifier(
+ classNameBuilder.toString(), methodName);
+ mPackageDefs.get(abi).addTest(testId, timeout);
+ }
}
}
}
@@ -170,19 +202,15 @@
}
}
- /**
- * {@inheritDoc}
- */
@Override
protected DefaultHandler createXmlHandler() {
return new TestPackageHandler();
}
/**
- * @returns the {@link TestPackageDef} containing data parsed from xml or <code>null</code> if
- * xml did not contain the correct information.
+ * @returns the set of {@link TestPackageDef} containing data parsed from xml
*/
- public TestPackageDef getTestPackageDef() {
- return mPackageDef;
+ public Set<TestPackageDef> getTestPackageDefs() {
+ return new HashSet<TestPackageDef>(mPackageDefs.values());
}
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPlan.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPlan.java
index c2a1348..8737db6 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPlan.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/TestPlan.java
@@ -16,6 +16,7 @@
package com.android.cts.tradefed.testtype;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.util.ArrayUtil;
import com.android.tradefed.util.xml.AbstractXmlParser;
@@ -29,9 +30,11 @@
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
/**
* Implementation of {@link TestPlan}.
@@ -39,18 +42,20 @@
public class TestPlan extends AbstractXmlParser implements ITestPlan {
/**
- * Map of uri names found in plan, and their excluded tests
+ * Map of ids found in plan, and their filters
*/
- private Map<String, TestFilter> mUriExcludedTestsMap;
+ private Map<String, TestFilter> mIdFilterMap;
private static final String ENTRY_TAG = "Entry";
private static final String TEST_DELIM = ";";
private static final String METHOD_DELIM = "#";
private static final String EXCLUDE_ATTR = "exclude";
private static final String INCLUDE_ATTR = "include";
- private static final String URI_ATTR = "uri";
+ private static final String ABI_ATTR = "abi";
+ private static final String NAME_ATTR = "name";
private final String mName;
+ private final Set<String> mAbis;
/**
* SAX callback object. Handles parsing data from the xml tags.
@@ -61,10 +66,17 @@
public void startElement(String uri, String localName, String name, Attributes attributes)
throws SAXException {
if (ENTRY_TAG.equals(localName)) {
- final String entryUriValue = attributes.getValue(URI_ATTR);
TestFilter filter = parseTestList(
attributes.getValue(EXCLUDE_ATTR), attributes.getValue(INCLUDE_ATTR));
- mUriExcludedTestsMap.put(entryUriValue, filter);
+ final String entryNameValue = attributes.getValue(NAME_ATTR);
+ final String entryAbiValue = attributes.getValue(ABI_ATTR);
+ if (entryAbiValue != null) {
+ mIdFilterMap.put(AbiUtils.createId(entryAbiValue, entryNameValue), filter);
+ } else {
+ for (String abi : mAbis) {
+ mIdFilterMap.put(AbiUtils.createId(abi, entryNameValue), filter);
+ }
+ }
}
}
@@ -109,10 +121,11 @@
}
}
- public TestPlan(String name) {
+ public TestPlan(String name, Set<String> abis) {
mName = name;
+ mAbis = abis;
// Uses a LinkedHashMap to have predictable iteration order
- mUriExcludedTestsMap = new LinkedHashMap<String, TestFilter>();
+ mIdFilterMap = new LinkedHashMap<String, TestFilter>();
}
/**
@@ -127,24 +140,26 @@
* {@inheritDoc}
*/
@Override
- public Collection<String> getTestUris() {
- return mUriExcludedTestsMap.keySet();
+ public Collection<String> getTestIds() {
+ List<String> ids = new ArrayList<String>(mIdFilterMap.keySet());
+ Collections.sort(ids);
+ return ids;
}
/**
* {@inheritDoc}
*/
@Override
- public TestFilter getExcludedTestFilter(String uri) {
- return mUriExcludedTestsMap.get(uri);
+ public TestFilter getTestFilter(String id) {
+ return mIdFilterMap.get(id);
}
/**
* {@inheritDoc}
*/
@Override
- public void addPackage(String uri) {
- mUriExcludedTestsMap.put(uri, new TestFilter());
+ public void addPackage(String id) {
+ mIdFilterMap.put(id, new TestFilter());
}
/**
@@ -159,12 +174,12 @@
* {@inheritDoc}
*/
@Override
- public void addExcludedTest(String uri, TestIdentifier testToExclude) {
- TestFilter filter = mUriExcludedTestsMap.get(uri);
+ public void addExcludedTest(String id, TestIdentifier testToExclude) {
+ TestFilter filter = mIdFilterMap.get(id);
if (filter != null) {
filter.addExcludedTest(testToExclude);
} else {
- throw new IllegalArgumentException(String.format("Could not find package %s", uri));
+ throw new IllegalArgumentException(String.format("Could not find package %s", id));
}
}
@@ -172,12 +187,12 @@
* {@inheritDoc}
*/
@Override
- public void addExcludedTests(String uri, Collection<TestIdentifier> excludedTests) {
- TestFilter filter = mUriExcludedTestsMap.get(uri);
+ public void addExcludedTests(String id, Collection<TestIdentifier> excludedTests) {
+ TestFilter filter = mIdFilterMap.get(id);
if (filter != null) {
filter.getExcludedTests().addAll(excludedTests);
} else {
- throw new IllegalArgumentException(String.format("Could not find package %s", uri));
+ throw new IllegalArgumentException(String.format("Could not find package %s", id));
}
}
@@ -193,9 +208,11 @@
"http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag(null, "TestPlan");
serializer.attribute(null, "version", "1.0");
- for (Map.Entry<String, TestFilter> packageEntry : mUriExcludedTestsMap.entrySet()) {
+ for (Map.Entry<String, TestFilter> packageEntry : mIdFilterMap.entrySet()) {
serializer.startTag(null, ENTRY_TAG);
- serializer.attribute(null, "uri", packageEntry.getKey());
+ String[] parts = AbiUtils.parseId(packageEntry.getKey());
+ serializer.attribute(null, ABI_ATTR, parts[0]);
+ serializer.attribute(null, NAME_ATTR, parts[1]);
serializeFilter(serializer, packageEntry.getValue());
serializer.endTag(null, ENTRY_TAG);
}
@@ -206,10 +223,10 @@
/**
* Adds an xml attribute containing {@link TestFilter} contents.
* <p/>
- * If {@link TestFilter} is empty, no data will be outputted.
+ * If {@link TestFilter} is empty, no data will be output.
*
* @param serializer
- * @param value
+ * @param testFilter
* @throws IOException
*/
private void serializeFilter(KXmlSerializer serializer, TestFilter testFilter)
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/VMHostTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/VMHostTest.java
index 9b4c86d..0ebdeea 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/VMHostTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/VMHostTest.java
@@ -16,19 +16,12 @@
package com.android.cts.tradefed.testtype;
import com.android.cts.tradefed.build.CtsBuildHelper;
-import com.android.tradefed.config.ConfigurationException;
-import com.android.tradefed.config.Option;
-import com.android.tradefed.config.Option.Importance;
-import com.android.tradefed.config.OptionSetter;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.result.ITestInvocationListener;
-import com.android.tradefed.util.AbiFormatter;
import com.android.tradefed.util.FileUtil;
-import junit.framework.Test;
-
import java.io.File;
import java.io.IOException;
import java.util.zip.ZipFile;
@@ -42,12 +35,6 @@
private static final String VM_TEST_TEMP_DIR = "/data/local/tmp/vm-tests";
private static final String EMULATOR_TEMP_DIR = "/data/local/tmp";
- @Option(name = AbiFormatter.FORCE_ABI_STRING,
- description = AbiFormatter.FORCE_ABI_DESCRIPTION,
- importance = Importance.IF_UNSET)
- private String mForceAbi = null;
-
-
/**
* {@inheritDoc}
*/
@@ -108,14 +95,6 @@
return true;
}
- @Override
- protected void setOptions(Test junitTest) throws ConfigurationException{
- if (mForceAbi != null) {
- OptionSetter optionSetter = new OptionSetter(junitTest);
- optionSetter.setOptionValue(AbiFormatter.FORCE_ABI_STRING, mForceAbi);
- }
- }
-
/**
* Removes temporary file directory from device
*
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/WrappedGTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/WrappedGTest.java
index 78cd6f77..a5c3e4c 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/WrappedGTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/WrappedGTest.java
@@ -17,18 +17,17 @@
package com.android.cts.tradefed.testtype;
import com.android.cts.tradefed.build.CtsBuildHelper;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.testrunner.ITestRunListener;
import com.android.tradefed.build.IBuildInfo;
-import com.android.tradefed.config.Option;
-import com.android.tradefed.config.Option.Importance;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.IAbi;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.testtype.IDeviceTest;
import com.android.tradefed.testtype.IRemoteTest;
-import com.android.tradefed.util.AbiFormatter;
import java.io.File;
import java.io.FileNotFoundException;
@@ -38,26 +37,31 @@
*/
public class WrappedGTest implements IBuildReceiver, IDeviceTest, IRemoteTest {
+ private static final String LOG_TAG = WrappedGTest.class.getSimpleName();
+
private int mMaxTestTimeMs = 1 * 60 * 1000;
private CtsBuildHelper mCtsBuild;
private ITestDevice mDevice;
+ private IAbi mAbi;
private final String mAppNameSpace;
- private final String mRunner;
+ private final String mPackageName;
private final String mName;
- private final String mUri;
+ private final String mRunner;
- @Option(name = AbiFormatter.FORCE_ABI_STRING,
- description = AbiFormatter.FORCE_ABI_DESCRIPTION,
- importance = Importance.IF_UNSET)
- private String mForceAbi = null;
-
- public WrappedGTest(String appNameSpace, String uri, String name, String runner) {
+ public WrappedGTest(String appNameSpace, String packageName, String name, String runner) {
mAppNameSpace = appNameSpace;
- mRunner = runner;
+ mPackageName = packageName;
mName = name;
- mUri = uri;
+ mRunner = runner;
+ }
+
+ /**
+ * @param abi The ABI to run the test on
+ */
+ public void setAbi(IAbi abi) {
+ mAbi = abi;
}
@Override
@@ -88,7 +92,8 @@
private boolean installTest() throws DeviceNotAvailableException {
try {
File testApp = mCtsBuild.getTestApp(String.format("%s.apk", mName));
- String installCode = mDevice.installPackage(testApp, true);
+ String[] options = {AbiUtils.createAbiFlag(mAbi.getName())};
+ String installCode = mDevice.installPackage(testApp, true, options);
if (installCode != null) {
CLog.e("Failed to install %s.apk on %s. Reason: %s", mName,
@@ -104,16 +109,11 @@
}
private void runTest(ITestRunListener listener) throws DeviceNotAvailableException {
- WrappedGTestResultParser resultParser = new WrappedGTestResultParser(mUri, listener);
- resultParser.setFakePackagePrefix(mUri + ".");
+ String id = AbiUtils.createId(mAbi.getName(), mPackageName);
+ WrappedGTestResultParser resultParser = new WrappedGTestResultParser(id, listener);
+ resultParser.setFakePackagePrefix(mPackageName + ".");
try {
- String options = "";
- if (mForceAbi != null) {
- String abi = AbiFormatter.getDefaultAbi(getDevice(), mForceAbi);
- if (abi != null) {
- options = String.format("--abi %s ", abi);
- }
- }
+ String options = mAbi == null ? "" : String.format("--abi %s ", mAbi);
String command = String.format("am instrument -w %s%s/.%s", options, mAppNameSpace, mRunner);
mDevice.executeShellCommand(command, resultParser, mMaxTestTimeMs, 0);
} catch (DeviceNotAvailableException e) {
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/WrappedGTestResultParser.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/WrappedGTestResultParser.java
index cc3c53a..3050738 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/WrappedGTestResultParser.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/WrappedGTestResultParser.java
@@ -29,23 +29,23 @@
/**
* Creates the WrappedGTestResultParser.
*
- * @param testRunName the test run name to provide to
+ * @param testRunId the test run id to provide to
* {@link ITestRunListener#testRunStarted(String, int)}
* @param listeners informed of test results as the tests are executing
*/
- public WrappedGTestResultParser(String testRunName, Collection<ITestRunListener> listeners) {
- super(testRunName, listeners);
+ public WrappedGTestResultParser(String testRunId, Collection<ITestRunListener> listeners) {
+ super(testRunId, listeners);
}
/**
* Creates the WrappedGTestResultParser for a single listener.
*
- * @param testRunName the test run name to provide to
+ * @param testRunId the test run id to provide to
* {@link ITestRunListener#testRunStarted(String, int)}
* @param listener informed of test results as the tests are executing
*/
- public WrappedGTestResultParser(String testRunName, ITestRunListener listener) {
- super(testRunName, listener);
+ public WrappedGTestResultParser(String testRunId, ITestRunListener listener) {
+ super(testRunId, listener);
}
/**
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/util/CtsHostStore.java b/tools/tradefed-host/src/com/android/cts/tradefed/util/CtsHostStore.java
index 9c1e283..288b48c 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/util/CtsHostStore.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/util/CtsHostStore.java
@@ -23,7 +23,7 @@
*/
public class CtsHostStore {
- // needs concurrent verion as there can be multiple client accessing this.
+ // needs concurrent version as there can be multiple client accessing this.
// But there is no additional protection for the same key as that should not happen.
private static final ConcurrentHashMap<String, String> mMap =
new ConcurrentHashMap<String, String>();
@@ -33,26 +33,27 @@
* Note that key is generated in the form of device_serial#class#method name.
* So there should be no concurrent test for the same (serial, class, method).
* @param deviceSerial
+ * @param abi
* @param classMethodName
* @param result CTS result string
*/
- public static void storeCtsResult(String deviceSerial, String classMethodName, String result) {
- mMap.put(generateTestKey(deviceSerial, classMethodName), result);
+ public static void storeCtsResult(String deviceSerial, String abi, String classMethodName, String result) {
+ mMap.put(generateTestKey(deviceSerial, abi, classMethodName), result);
}
/**
* retrieves a CTS result for the given condition and remove it from the internal
* storage. If there is no result for the given condition, it will return null.
*/
- public static String removeCtsResult(String deviceSerial, String classMethodName) {
- return mMap.remove(generateTestKey(deviceSerial, classMethodName));
+ public static String removeCtsResult(String deviceSerial, String abi, String classMethodName) {
+ return mMap.remove(generateTestKey(deviceSerial, abi, classMethodName));
}
/**
- * return test key in the form of device_serial#class_name#method_name
+ * @return test key in the form of device_serial#abi#class_name#method_name
*/
- private static String generateTestKey(String deviceSerial, String classMethodName) {
- return String.format("%s#%s", deviceSerial, classMethodName);
+ private static String generateTestKey(String deviceSerial, String abi, String classMethodName) {
+ return String.format("%s#%s#%s", deviceSerial, abi, classMethodName);
}
}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/util/HostReportLog.java b/tools/tradefed-host/src/com/android/cts/tradefed/util/HostReportLog.java
index 125c56e..645dbb9 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/util/HostReportLog.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/util/HostReportLog.java
@@ -23,20 +23,23 @@
* Note that setTestInfo should be set before throwing report
*/
public class HostReportLog extends ReportLog {
- private String mDeviceSerial;
- private String mClassMethodName;
+ private final String mDeviceSerial;
+ private final String mAbiName;
+ private final String mClassMethodName;
/**
* @param deviceSerial serial number of the device
+ * @param abiName the name of the ABI on which the test was run
* @param classMethodName class name and method name of the test in class#method format.
* Note that ReportLog.getClassMethodNames() provide this.
*/
- public HostReportLog(String deviceSerial, String classMethodName) {
+ public HostReportLog(String deviceSerial, String abiName, String classMethodName) {
mDeviceSerial = deviceSerial;
+ mAbiName = abiName;
mClassMethodName = classMethodName;
}
public void deliverReportToHost() {
- CtsHostStore.storeCtsResult(mDeviceSerial, mClassMethodName, generateReport());
+ CtsHostStore.storeCtsResult(mDeviceSerial, mAbiName, mClassMethodName, generateReport());
}
}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java
index 65528b7..e46cfae 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java
@@ -21,14 +21,17 @@
import com.android.cts.tradefed.result.TestResultsTest;
import com.android.cts.tradefed.result.TestSummaryXmlTest;
import com.android.cts.tradefed.result.TestTest;
+import com.android.cts.tradefed.testtype.Abi;
import com.android.cts.tradefed.testtype.CtsTestTest;
-import com.android.cts.tradefed.testtype.DeqpTestTest;
+import com.android.cts.tradefed.testtype.DeqpTestRunnerTest;
import com.android.cts.tradefed.testtype.JarHostTestTest;
import com.android.cts.tradefed.testtype.TestFilterTest;
import com.android.cts.tradefed.testtype.TestPackageDefTest;
import com.android.cts.tradefed.testtype.TestPackageXmlParserTest;
import com.android.cts.tradefed.testtype.TestPlanTest;
import com.android.cts.tradefed.testtype.WrappedGTestResultParserTest;
+import com.android.cts.util.AbiUtils;
+import com.android.tradefed.testtype.IAbi;
import junit.framework.Test;
import junit.framework.TestSuite;
@@ -41,6 +44,8 @@
*/
public class UnitTests extends TestSuite {
+ public static final IAbi ABI = new Abi("armeabi-v7a", "32");
+
public UnitTests() {
super();
@@ -60,7 +65,7 @@
addTestSuite(TestPackageXmlParserTest.class);
addTestSuite(TestPlanTest.class);
addTestSuite(WrappedGTestResultParserTest.class);
- addTestSuite(DeqpTestTest.class);
+ addTestSuite(DeqpTestRunnerTest.class);
}
public static Test suite() {
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/device/DeviceInfoCollectorFuncTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/device/DeviceInfoCollectorFuncTest.java
index b0c9e6d..52a205b 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/device/DeviceInfoCollectorFuncTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/device/DeviceInfoCollectorFuncTest.java
@@ -15,6 +15,7 @@
*/
package com.android.cts.tradefed.device;
+import com.android.cts.tradefed.UnitTests;
import com.android.tradefed.build.BuildInfo;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.result.CollectingTestListener;
@@ -34,7 +35,7 @@
CollectingTestListener testListener = new CollectingTestListener();
testListener.invocationStarted(new BuildInfo());
- DeviceInfoCollector.collectDeviceInfo(getDevice(), new File(
+ DeviceInfoCollector.collectDeviceInfo(getDevice(), UnitTests.ABI.getName(), new File(
System.getProperty("java.io.tmpdir")), testListener);
assertNotNull(testListener.getCurrentRunResults());
assertTrue(testListener.getCurrentRunResults().getRunMetrics().size() > 0);
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java
index 26cf39c..b312526 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/CtsXmlResultReporterTest.java
@@ -17,6 +17,8 @@
import static com.android.cts.tradefed.result.CtsXmlResultReporter.CTS_RESULT_FILE_VERSION;
+import com.android.cts.tradefed.UnitTests;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.testrunner.ITestRunListener.TestFailure;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.build.IFolderBuildInfo;
@@ -48,6 +50,7 @@
new ArrayList<>(Arrays.asList(new TestSummary("TEST_SUMMARY_URL")));
private CtsXmlResultReporter mResultReporter;
private ByteArrayOutputStream mOutputStream;
+ private File mBuildDir;
private File mReportDir;
private IFolderBuildInfo mMockBuild;
@@ -73,8 +76,16 @@
// TODO: use mock file dir instead
mReportDir = FileUtil.createTempDir("foo");
mResultReporter.setReportDir(mReportDir);
+ mBuildDir = FileUtil.createTempDir("build");
+ File ctsDir = new File(mBuildDir, "android-cts");
+ File repoDir = new File(ctsDir, "repository");
+ File casesDir = new File(repoDir, "testcases");
+ File plansDir = new File(repoDir, "plans");
+ assertTrue(casesDir.mkdirs());
+ assertTrue(plansDir.mkdirs());
mMockBuild = EasyMock.createNiceMock(IFolderBuildInfo.class);
EasyMock.expect(mMockBuild.getDeviceSerial()).andStubReturn(null);
+ EasyMock.expect(mMockBuild.getRootDir()).andStubReturn(mBuildDir);
EasyMock.replay(mMockBuild);
}
@@ -83,6 +94,9 @@
if (mReportDir != null) {
FileUtil.recursiveDelete(mReportDir);
}
+ if (mBuildDir != null) {
+ FileUtil.recursiveDelete(mBuildDir);
+ }
super.tearDown();
}
@@ -117,19 +131,18 @@
Map<String, String> emptyMap = Collections.emptyMap();
final TestIdentifier testId = new TestIdentifier("com.foo.FooTest", "testFoo");
mResultReporter.invocationStarted(mMockBuild);
- mResultReporter.testRunStarted("run", 1);
+ mResultReporter.testRunStarted(AbiUtils.createId(UnitTests.ABI.getName(), "run"), 1);
mResultReporter.testStarted(testId);
mResultReporter.testEnded(testId, emptyMap);
mResultReporter.testRunEnded(3000, emptyMap);
mResultReporter.invocationEnded(1);
mResultReporter.putSummary(SUMMARY_LIST);
String output = getOutput();
- CLog.d("Actual output: %s", output);
- System.out.println(output);
// TODO: consider doing xml based compare
assertTrue(output.contains(
- "<Summary failed=\"0\" notExecuted=\"0\" timeout=\"0\" pass=\"1\" />"));
- assertTrue(output.contains("<TestPackage name=\"\" appPackageName=\"run\" digest=\"\">"));
+ "<Summary failed=\"0\" notExecuted=\"0\" timeout=\"0\" pass=\"1\" />"));
+ assertTrue(output.contains("<TestPackage name=\"\" appPackageName=\"run\" abi=\"" +
+ UnitTests.ABI.getName() + "\" digest=\"\">"));
assertTrue(output.contains("<TestCase name=\"FooTest\" priority=\"\">"));
final String testCaseTag = String.format(
@@ -145,20 +158,19 @@
final TestIdentifier testId = new TestIdentifier("FooTest", "testFoo");
final String trace = "this is a trace\nmore trace\nyet more trace";
mResultReporter.invocationStarted(mMockBuild);
- mResultReporter.testRunStarted("run", 1);
+ mResultReporter.testRunStarted(AbiUtils.createId(UnitTests.ABI.getName(), "run"), 1);
mResultReporter.testStarted(testId);
mResultReporter.testFailed(TestFailure.FAILURE, testId, trace);
mResultReporter.testEnded(testId, emptyMap);
mResultReporter.testRunEnded(3, emptyMap);
mResultReporter.invocationEnded(1);
- String output = getOutput();
- System.out.print(getOutput());
+ String output = getOutput();
// TODO: consider doing xml based compare
assertTrue(output.contains(
"<Summary failed=\"1\" notExecuted=\"0\" timeout=\"0\" pass=\"0\" />"));
final String failureTag =
- "<FailedScene message=\"this is a trace more trace\"> " +
- "<StackTrace>this is a tracemore traceyet more trace</StackTrace>";
+ "<FailedScene message=\"this is a trace more trace\"> " +
+ "<StackTrace>this is a tracemore traceyet more trace</StackTrace>";
assertTrue(output.contains(failureTag));
}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/TestPackageResultTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/TestPackageResultTest.java
index df80dbb..57d322e 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/TestPackageResultTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/TestPackageResultTest.java
@@ -20,6 +20,7 @@
import junit.framework.TestCase;
import java.util.Collection;
+import java.util.HashMap;
/**
* Unit tests for {@link TestPackageResult}.
@@ -33,7 +34,7 @@
TestPackageResult pkgResult = new TestPackageResult();
TestIdentifier excludedTest = new TestIdentifier("com.example.ExampleTest", "testPass");
pkgResult.insertTest(excludedTest);
- pkgResult.reportTestEnded(excludedTest);
+ pkgResult.reportTestEnded(excludedTest, new HashMap<String, String>());
TestIdentifier includedTest = new TestIdentifier("com.example.ExampleTest",
"testNotExecuted");
pkgResult.insertTest(includedTest);
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/TestSummaryXmlTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/TestSummaryXmlTest.java
index 3fc7dd2..f8b135a 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/TestSummaryXmlTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/result/TestSummaryXmlTest.java
@@ -38,7 +38,7 @@
"<Foo failed=\"1\" notExecuted=\"2\" pass=\"3\" timeout=\"4\"/>" +
"</TestResult>";
- public void testConstructor() throws ParseException {
+ public void testConstructor() {
TestSummaryXml result = new TestSummaryXml(1, "2011-11-01");
assertEquals(1, result.getId());
assertEquals("2011-11-01", result.getTimestamp());
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/CtsTestTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/CtsTestTest.java
index f0fd536..80f9e8c 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/CtsTestTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/CtsTestTest.java
@@ -15,8 +15,10 @@
*/
package com.android.cts.tradefed.testtype;
+import com.android.cts.tradefed.UnitTests;
import com.android.cts.tradefed.build.StubCtsBuildHelper;
import com.android.cts.tradefed.result.PlanCreator;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
@@ -33,14 +35,25 @@
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
-import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
/**
* Unit tests for {@link CtsTest}.
*/
public class CtsTestTest extends TestCase {
- private static final String PACKAGE_NAME = "test-uri";
+ private static final String PLAN_NAME = "CTS";
+ private static final String PACKAGE_NAME = "test-name";
+ private static final String ID = AbiUtils.createId(UnitTests.ABI.getName(), PACKAGE_NAME);
+ private static final List<String> NAMES = new ArrayList<>();
+ private static final List<String> IDS = new ArrayList<>();
+ static {
+ NAMES.add(PACKAGE_NAME);
+ IDS.add(ID);
+ }
+
/** the test fixture under test, with all external dependencies mocked out */
private CtsTest mCtsTest;
private ITestPackageRepo mMockRepo;
@@ -49,10 +62,9 @@
private ITestInvocationListener mMockListener;
private StubCtsBuildHelper mStubBuildHelper;
private ITestPackageDef mMockPackageDef;
+ private Set<ITestPackageDef> mMockPackageDefs;
private IRemoteTest mMockTest;
- private static final String PLAN_NAME = "CTS";
-
/**
* {@inheritDoc}
*/
@@ -64,7 +76,11 @@
mMockDevice = EasyMock.createMock(ITestDevice.class);
mMockListener = EasyMock.createNiceMock(ITestInvocationListener.class);
mStubBuildHelper = new StubCtsBuildHelper();
+ mMockPackageDefs = new HashSet<ITestPackageDef>();
mMockPackageDef = EasyMock.createMock(ITestPackageDef.class);
+ mMockPackageDefs.add(mMockPackageDef);
+ EasyMock.expect(mMockPackageDef.getTargetApkName()).andStubReturn(null);
+ EasyMock.expect(mMockPackageDef.getTargetPackageName()).andStubReturn(null);
mMockTest = EasyMock.createMock(IRemoteTest.class);
mCtsTest = new CtsTest() {
@@ -93,12 +109,13 @@
mCtsTest.setBuildHelper(mStubBuildHelper);
// turn off device collection for simplicity
mCtsTest.setSkipDeviceInfo(true);
- EasyMock.expect(mMockPackageDef.getTargetApkName()).andStubReturn(null);
- EasyMock.expect(mMockPackageDef.getTargetPackageName()).andStubReturn(null);
+ // only run tests on one ABI
+ EasyMock.expect(mMockDevice.getProperty("ro.product.cpu.abilist")).andReturn(
+ UnitTests.ABI.getName()).anyTimes();
}
/**
- * Test normal case {@link CtsTest#run(java.util.List)} when running a plan.
+ * Test normal case {@link CtsTest#run(ITestInvocationListener)} when running a plan.
*/
@SuppressWarnings("unchecked")
public void testRun_plan() throws DeviceNotAvailableException, ParseException {
@@ -112,7 +129,7 @@
}
/**
- * Test normal case {@link CtsTest#run(java.util.List)} when running a package.
+ * Test normal case {@link CtsTest#run(ITestInvocationListener)} when running a package.
*/
@SuppressWarnings("unchecked")
public void testRun_package() throws DeviceNotAvailableException {
@@ -138,8 +155,6 @@
// now expect test to be resumed
mMockTest.run((ITestInvocationListener)EasyMock.anyObject());
- EasyMock.expect(mMockPackageDef.getName()).andReturn(PACKAGE_NAME);
- EasyMock.expect(mMockPackageDef.getDigest()).andReturn("digest");
replayMocks();
try {
@@ -154,7 +169,7 @@
}
/**
- * Test normal case {@link CtsTest#run(java.util.List)} when running a class.
+ * Test normal case {@link CtsTest#run(ITestInvocationListener)} when running a class.
*/
@SuppressWarnings("unchecked")
public void testRun_class() throws DeviceNotAvailableException {
@@ -163,7 +178,7 @@
mCtsTest.setClassName(className);
mCtsTest.setMethodName(methodName);
- EasyMock.expect(mMockRepo.findPackageForTest(className)).andReturn(PACKAGE_NAME);
+ EasyMock.expect(mMockRepo.findPackageIdsForTest(className)).andReturn(IDS);
mMockPackageDef.setClassName(className, methodName);
setCreateAndRunTestExpectations();
@@ -174,14 +189,12 @@
}
/**
- * Test {@link CtsTest#run(java.util.List)} when --excluded-package is specified
+ * Test {@link CtsTest#run(ITestInvocationListener)} when --excluded-package is specified
*/
public void testRun_excludedPackage() throws DeviceNotAvailableException, ParseException {
mCtsTest.setPlanName(PLAN_NAME);
- mMockPlan.parse((InputStream)EasyMock.anyObject());
- Collection<String> uris = new ArrayList<String>(1);
- uris.add(PACKAGE_NAME);
- EasyMock.expect(mMockPlan.getTestUris()).andReturn(uris);
+ mMockPlan.parse((InputStream) EasyMock.anyObject());
+ EasyMock.expect(mMockPlan.getTestIds()).andReturn(IDS);
mCtsTest.addExcludedPackageName(PACKAGE_NAME);
@@ -192,17 +205,15 @@
}
/**
- * Test {@link CtsTest#run(ITestInvocationListener))} when --continue-session is specified
+ * Test {@link CtsTest#run(ITestInvocationListener)} when --continue-session is specified
*/
- public void testRun_continueSession() throws DeviceNotAvailableException, ParseException {
+ public void testRun_continueSession() throws DeviceNotAvailableException {
mCtsTest.setContinueSessionId(1);
- Collection<String> uris = new ArrayList<String>(1);
- uris.add(PACKAGE_NAME);
- EasyMock.expect(mMockPlan.getTestUris()).andReturn(uris);
+ EasyMock.expect(mMockPlan.getTestIds()).andReturn(IDS);
TestFilter filter = new TestFilter();
- EasyMock.expect(mMockPlan.getExcludedTestFilter(PACKAGE_NAME)).andReturn(
- filter);
- mMockPackageDef.setExcludedTestFilter(filter);
+ EasyMock.expect(mMockPlan.getTestFilter(ID)).andReturn(filter);
+
+ mMockPackageDef.setTestFilter(filter);
setCreateAndRunTestExpectations();
@@ -216,34 +227,33 @@
*/
private void setParsePlanExceptations() throws ParseException {
mCtsTest.setPlanName(PLAN_NAME);
- mMockPlan.parse((InputStream)EasyMock.anyObject());
- Collection<String> uris = new ArrayList<String>(1);
- uris.add(PACKAGE_NAME);
- EasyMock.expect(mMockPlan.getTestUris()).andReturn(uris);
+ mMockPlan.parse((InputStream) EasyMock.anyObject());
+ EasyMock.expect(mMockPlan.getTestIds()).andReturn(IDS);
TestFilter filter = new TestFilter();
- EasyMock.expect(mMockPlan.getExcludedTestFilter(PACKAGE_NAME)).andReturn(
- filter);
- mMockPackageDef.setExcludedTestFilter(filter);
+ EasyMock.expect(mMockPlan.getTestFilter(ID)).andReturn(filter);
+ mMockPackageDef.setTestFilter(filter);
}
/**
* Set EasyMock expectations for creating and running a package with PACKAGE_NAME
*/
private void setCreateAndRunTestExpectations() throws DeviceNotAvailableException {
- EasyMock.expect(mMockRepo.getTestPackage(PACKAGE_NAME)).andReturn(mMockPackageDef);
- EasyMock.expect(mMockPackageDef.createTest((File)EasyMock.anyObject())).andReturn(
- mMockTest);
+ EasyMock.expect(mMockRepo.getPackageNames()).andReturn(NAMES).anyTimes();
+ EasyMock.expect(mMockRepo.getPackageIds()).andReturn(IDS).anyTimes();
+ EasyMock.expect(mMockRepo.getTestPackages(PACKAGE_NAME)).andReturn(mMockPackageDefs).anyTimes();
+ EasyMock.expect(mMockRepo.getTestPackage(ID)).andReturn(mMockPackageDef).anyTimes();
+ EasyMock.expect(mMockPackageDef.createTest((File) EasyMock.anyObject())).andReturn(mMockTest);
EasyMock.expect(mMockPackageDef.getTests()).andReturn(new ArrayList<TestIdentifier>());
- EasyMock.expect(mMockPackageDef.getUri()).andStubReturn(PACKAGE_NAME);
- EasyMock.expect(mMockPackageDef.getName()).andReturn(PACKAGE_NAME);
- EasyMock.expect(mMockPackageDef.getDigest()).andReturn("digest");
-
- mMockTest.run((ITestInvocationListener)EasyMock.anyObject());
+ EasyMock.expect(mMockPackageDef.getName()).andReturn(PACKAGE_NAME).atLeastOnce();
+ EasyMock.expect(mMockPackageDef.getAbi()).andReturn(UnitTests.ABI).atLeastOnce();
+ EasyMock.expect(mMockPackageDef.getId()).andReturn(ID).atLeastOnce();
+ EasyMock.expect(mMockPackageDef.getDigest()).andReturn("digest").atLeastOnce();
+ mMockTest.run((ITestInvocationListener) EasyMock.anyObject());
}
/**
- * Test {@link CtsTest#run(java.util.List)} when --plan and --package options have not been
- * specified
+ * Test {@link CtsTest#run(ITestInvocationListener)} when --plan and --package options have not
+ * been specified
*/
public void testRun_nothingToRun() throws DeviceNotAvailableException {
try {
@@ -255,7 +265,7 @@
}
/**
- * Test {@link CtsTest#run(ITestInvocationListener))} when --plan and --package options have
+ * Test {@link CtsTest#run(ITestInvocationListener)} when --plan and --package options have
* been specified.
*/
public void testRun_packagePlan() throws DeviceNotAvailableException {
@@ -270,7 +280,7 @@
}
/**
- * Test {@link CtsTest#run(java.util.List)} when --plan and --class options have been
+ * Test {@link CtsTest#run(ITestInvocationListener)} when --plan and --class options have been
* specified
*/
public void testRun_planClass() throws DeviceNotAvailableException {
@@ -285,8 +295,8 @@
}
/**
- * Test {@link CtsTest#run(java.util.List)} when --package and --class options have been
- * specified
+ * Test {@link CtsTest#run(ITestInvocationListener)} when --package and --class options have
+ * been specified
*/
public void testRun_packageClass() throws DeviceNotAvailableException {
mCtsTest.addPackageName(PACKAGE_NAME);
@@ -300,8 +310,8 @@
}
/**
- * Test {@link CtsTest#run(java.util.List)} when --plan, --package and --class options have been
- * specified
+ * Test {@link CtsTest#run(ITestInvocationListener)} when --plan, --package and --class options
+ * have been specified
*/
public void testRun_planPackageClass() throws DeviceNotAvailableException {
mCtsTest.setPlanName(PLAN_NAME);
@@ -316,8 +326,8 @@
}
/**
- * Test {@link CtsTest#run(java.util.List)} when --plan, --continue-option options have been
- * specified
+ * Test {@link CtsTest#run(ITestInvocationListener)} when --plan, --continue-option options
+ * have been specified
*/
public void testRun_planContinue() throws DeviceNotAvailableException {
mCtsTest.setPlanName(PLAN_NAME);
@@ -331,14 +341,12 @@
}
private void replayMocks(Object... mocks) {
- EasyMock.replay(mMockRepo, mMockPlan, mMockDevice, mMockListener, mMockPackageDef,
- mMockTest);
+ EasyMock.replay(mMockRepo, mMockPlan, mMockDevice, mMockPackageDef, mMockListener, mMockTest);
EasyMock.replay(mocks);
}
private void verifyMocks(Object... mocks) {
- EasyMock.verify(mMockRepo, mMockPlan, mMockDevice, mMockListener, mMockPackageDef,
- mMockTest);
+ EasyMock.verify(mMockRepo, mMockPlan, mMockDevice, mMockPackageDef, mMockListener, mMockTest);
EasyMock.verify(mocks);
}
}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/DeqpTestTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/DeqpTestRunnerTest.java
similarity index 95%
rename from tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/DeqpTestTest.java
rename to tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/DeqpTestRunnerTest.java
index 0e7c26e..03ebfc5 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/DeqpTestTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/DeqpTestRunnerTest.java
@@ -15,11 +15,14 @@
*/
package com.android.cts.tradefed.testtype;
+import com.android.cts.tradefed.UnitTests;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.IShellOutputReceiver;
import com.android.ddmlib.testrunner.ITestRunListener;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.result.ITestInvocationListener;
+import com.android.tradefed.testtype.IAbi;
import junit.framework.TestCase;
@@ -28,14 +31,14 @@
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
/**
- * Unit tests for {@link DeqpTest}.
+ * Unit tests for {@link DeqpTestRunner}.
*/
-public class DeqpTestTest extends TestCase {
- private static final String URI = "dEQP-GLES3";
+public class DeqpTestRunnerTest extends TestCase {
+ private static final String NAME = "dEQP-GLES3";
+ private static final String ID = AbiUtils.createId(UnitTests.ABI.getName(), NAME);
private static final String CASE_LIST_FILE_NAME = "/sdcard/dEQP-TestCaseList.txt";
private static final String LOG_FILE_NAME = "/sdcard/TestLog.qpa";
private static final String INSTRUMENTATION_NAME =
@@ -102,10 +105,11 @@
tests.add(testId);
- DeqpTest deqpTest = new DeqpTest(URI,
+ DeqpTestRunner deqpTest = new DeqpTestRunner(NAME,
"dEQP-GLES" + Integer.toString(requiredMajorVersion)
+ (requiredMinorVersion > 0 ? Integer.toString(requiredMinorVersion) : ""),
tests);
+ deqpTest.setAbi(UnitTests.ABI);
int version = (majorVersion << 16) | minorVersion;
EasyMock.expect(mockDevice.getProperty("ro.opengles.version"))
@@ -145,7 +149,7 @@
});
}
- mockListener.testRunStarted(URI, 1);
+ mockListener.testRunStarted(ID, 1);
EasyMock.expectLastCall().once();
mockListener.testStarted(EasyMock.eq(testId));
@@ -210,11 +214,12 @@
tests.add(testId);
- DeqpTest deqpTest = new DeqpTest(URI, "dEQP-GLES3", tests);
+ DeqpTestRunner deqpTest = new DeqpTestRunner(NAME, NAME, tests);
+ deqpTest.setAbi(UnitTests.ABI);
int version = 3 << 16;
EasyMock.expect(mockDevice.getProperty("ro.opengles.version"))
- .andReturn(Integer.toString(version)).atLeastOnce();
+ .andReturn(Integer.toString(version)).atLeastOnce();
EasyMock.expect(mockDevice.executeShellCommand(EasyMock.eq("rm " + CASE_LIST_FILE_NAME)))
.andReturn("").once();
@@ -246,7 +251,7 @@
}
});
- mockListener.testRunStarted(URI, 1);
+ mockListener.testRunStarted(ID, 1);
EasyMock.expectLastCall().once();
mockListener.testStarted(EasyMock.eq(testId));
@@ -382,11 +387,12 @@
tests.add(id);
}
- DeqpTest deqpTest = new DeqpTest(URI, "dEQP-GLES3", tests);
+ DeqpTestRunner deqpTest = new DeqpTestRunner(NAME, NAME, tests);
+ deqpTest.setAbi(UnitTests.ABI);
int version = 3 << 16;
EasyMock.expect(mockDevice.getProperty("ro.opengles.version"))
- .andReturn(Integer.toString(version)).atLeastOnce();
+ .andReturn(Integer.toString(version)).atLeastOnce();
EasyMock.expect(mockDevice.executeShellCommand(EasyMock.eq("rm " + CASE_LIST_FILE_NAME)))
.andReturn("").once();
@@ -418,7 +424,7 @@
}
});
- mockListener.testRunStarted(URI, testPaths.length);
+ mockListener.testRunStarted(ID, testPaths.length);
EasyMock.expectLastCall().once();
for (int i = 0; i < testPaths.length; i++) {
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/TestPackageXmlParserTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/TestPackageXmlParserTest.java
index ac3d394..5591b65 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/TestPackageXmlParserTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/TestPackageXmlParserTest.java
@@ -16,6 +16,8 @@
package com.android.cts.tradefed.testtype;
+import com.android.cts.tradefed.command.CtsConsole;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
@@ -68,67 +70,76 @@
* Test parsing test case xml containing an instrumentation test definition.
*/
public void testParse_instrPackage() throws ParseException {
- TestPackageXmlParser parser = new TestPackageXmlParser(true);
+ TestPackageXmlParser parser = new TestPackageXmlParser(AbiUtils.getAbisSupportedByCts(),
+ true);
parser.parse(getStringAsStream(INSTR_TEST_DATA));
- TestPackageDef def = parser.getTestPackageDef();
- assertEquals("com.example", def.getAppNameSpace());
- assertEquals("android.example", def.getUri());
- assertEquals("android.test.InstrumentationTestRunner", def.getRunner());
+ for (TestPackageDef def : parser.getTestPackageDefs()) {
+ assertEquals("com.example", def.getAppNameSpace());
+ assertEquals("android.example", def.getAppPackageName());
+ assertEquals("android.test.InstrumentationTestRunner", def.getRunner());
+ assertTrue(AbiUtils.isAbiSupportedByCts(def.getAbi().getName()));
+ }
}
/**
* Test parsing test case xml containing an host test attribute and test data.
*/
public void testParse_hostTest() throws ParseException {
- TestPackageXmlParser parser = new TestPackageXmlParser(true);
+ TestPackageXmlParser parser = new TestPackageXmlParser(AbiUtils.getAbisSupportedByCts(),
+ true);
parser.parse(getStringAsStream(HOST_TEST_DATA));
- TestPackageDef def = parser.getTestPackageDef();
- assertEquals(TestPackageDef.HOST_SIDE_ONLY_TEST, def.getTestType());
- assertEquals(3, def.getTests().size());
- Iterator<TestIdentifier> iterator = def.getTests().iterator();
+ for (TestPackageDef def : parser.getTestPackageDefs()) {
+ assertEquals(TestPackageDef.HOST_SIDE_ONLY_TEST, def.getTestType());
+ assertEquals(3, def.getTests().size());
+ Iterator<TestIdentifier> iterator = def.getTests().iterator();
- TestIdentifier firstTest = iterator.next();
- assertEquals("com.example.ExampleTest", firstTest.getClassName());
- assertEquals("testFoo", firstTest.getTestName());
+ TestIdentifier firstTest = iterator.next();
+ assertEquals("com.example.ExampleTest", firstTest.getClassName());
+ assertEquals("testFoo", firstTest.getTestName());
- TestIdentifier secondTest = iterator.next();
- assertEquals("com.example.ExampleTest", secondTest.getClassName());
- assertEquals("testFoo2", secondTest.getTestName());
+ TestIdentifier secondTest = iterator.next();
+ assertEquals("com.example.ExampleTest", secondTest.getClassName());
+ assertEquals("testFoo2", secondTest.getTestName());
- TestIdentifier thirdTest = iterator.next();
- assertEquals("com.example2.Example2Test", thirdTest.getClassName());
- assertEquals("testFoo", thirdTest.getTestName());
+ TestIdentifier thirdTest = iterator.next();
+ assertEquals("com.example2.Example2Test", thirdTest.getClassName());
+ assertEquals("testFoo", thirdTest.getTestName());
- assertFalse(iterator.hasNext());
+ assertFalse(iterator.hasNext());
+ }
}
public void testParse_hostTest_noKnownFailures() throws ParseException {
- TestPackageXmlParser parser = new TestPackageXmlParser(false);
+ TestPackageXmlParser parser = new TestPackageXmlParser(AbiUtils.getAbisSupportedByCts(),
+ false);
parser.parse(getStringAsStream(HOST_TEST_DATA));
- TestPackageDef def = parser.getTestPackageDef();
- assertEquals(TestPackageDef.HOST_SIDE_ONLY_TEST, def.getTestType());
- assertEquals(2, def.getTests().size());
- Iterator<TestIdentifier> iterator = def.getTests().iterator();
+ for (TestPackageDef def : parser.getTestPackageDefs()) {
+ assertEquals(TestPackageDef.HOST_SIDE_ONLY_TEST, def.getTestType());
+ assertEquals(2, def.getTests().size());
+ Iterator<TestIdentifier> iterator = def.getTests().iterator();
- TestIdentifier firstTest = iterator.next();
- assertEquals("com.example.ExampleTest", firstTest.getClassName());
- assertEquals("testFoo", firstTest.getTestName());
+ TestIdentifier firstTest = iterator.next();
+ assertEquals("com.example.ExampleTest", firstTest.getClassName());
+ assertEquals("testFoo", firstTest.getTestName());
- TestIdentifier thirdTest = iterator.next();
- assertEquals("com.example2.Example2Test", thirdTest.getClassName());
- assertEquals("testFoo", thirdTest.getTestName());
+ TestIdentifier thirdTest = iterator.next();
+ assertEquals("com.example2.Example2Test", thirdTest.getClassName());
+ assertEquals("testFoo", thirdTest.getTestName());
- assertFalse(iterator.hasNext());
+ assertFalse(iterator.hasNext());
+ }
}
/**
* Test parsing test case xml containing an invalid host test attribute.
*/
public void testParse_badHostTest() throws ParseException {
- TestPackageXmlParser parser = new TestPackageXmlParser(true);
+ TestPackageXmlParser parser = new TestPackageXmlParser(AbiUtils.getAbisSupportedByCts(),
+ true);
parser.parse(getStringAsStream(BAD_HOST_TEST_DATA));
- TestPackageDef def = parser.getTestPackageDef();
- assertFalse(TestPackageDef.HOST_SIDE_ONLY_TEST.equals(def.getTestType()));
+ for (TestPackageDef def : parser.getTestPackageDefs()) {
+ assertFalse(TestPackageDef.HOST_SIDE_ONLY_TEST.equals(def.getTestType()));
+ }
}
public void testParse_vmHostTest() throws ParseException {
@@ -140,19 +151,22 @@
}
private void assertTestType(String expectedType, String xml) throws ParseException {
- TestPackageXmlParser parser = new TestPackageXmlParser(true);
+ TestPackageXmlParser parser = new TestPackageXmlParser(AbiUtils.getAbisSupportedByCts(),
+ true);
parser.parse(getStringAsStream(xml));
- TestPackageDef def = parser.getTestPackageDef();
- assertEquals(expectedType, def.getTestType());
+ for (TestPackageDef def : parser.getTestPackageDefs()) {
+ assertEquals(expectedType, def.getTestType());
+ }
}
/**
* Test parsing a test case xml with no test package data.
*/
public void testParse_noData() throws ParseException {
- TestPackageXmlParser parser = new TestPackageXmlParser(true);
+ TestPackageXmlParser parser = new TestPackageXmlParser(AbiUtils.getAbisSupportedByCts(),
+ true);
parser.parse(getStringAsStream(NO_TEST_DATA));
- assertNull(parser.getTestPackageDef());
+ assertTrue(parser.getTestPackageDefs().isEmpty());
}
private InputStream getStringAsStream(String input) {
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/TestPlanTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/TestPlanTest.java
index 18d4776..5b28539 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/TestPlanTest.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/testtype/TestPlanTest.java
@@ -16,6 +16,7 @@
package com.android.cts.tradefed.testtype;
+import com.android.cts.util.AbiUtils;
import com.android.ddmlib.testrunner.TestIdentifier;
import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
@@ -25,15 +26,19 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collections;
import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
/**
* Unit tests for {@link TestPlan}.
*/
public class TestPlanTest extends TestCase {
- private static final String TEST_URI1 = "foo";
- private static final String TEST_URI2 = "foo2";
+ private static final String TEST_NAME1 = "foo";
+ private static final String TEST_NAME2 = "foo2";
private static final String EXCLUDE_TEST_CLASS = "com.example.FooTest";
private static final String EXCLUDE_TEST_METHOD = "testFoo";
private static final String EXCLUDE_TEST_METHOD2 = "testFoo2";
@@ -42,26 +47,26 @@
static final String TEST_DATA =
"<TestPlan version=\"1.0\">" +
- String.format("<Entry uri=\"%s\" />", TEST_URI1) +
- String.format("<Entry uri=\"%s\" />", TEST_URI2) +
+ String.format("<Entry name=\"%s\" />", TEST_NAME1) +
+ String.format("<Entry name=\"%s\" />", TEST_NAME2) +
"</TestPlan>";
static final String TEST_EXCLUDED_DATA =
"<TestPlan version=\"1.0\">" +
- String.format("<Entry uri=\"%s\" exclude=\"%s#%s\" />", TEST_URI1, EXCLUDE_TEST_CLASS,
+ String.format("<Entry name=\"%s\" exclude=\"%s#%s\" />", TEST_NAME1, EXCLUDE_TEST_CLASS,
EXCLUDE_TEST_METHOD) +
"</TestPlan>";
static final String TEST_MULTI_EXCLUDED_DATA =
"<TestPlan version=\"1.0\">" +
- String.format("<Entry uri=\"%s\" exclude=\"%s#%s;%s#%s\" />", TEST_URI1,
+ String.format("<Entry name=\"%s\" exclude=\"%s#%s;%s#%s\" />", TEST_NAME1,
EXCLUDE_TEST_CLASS, EXCLUDE_TEST_METHOD, EXCLUDE_TEST_CLASS,
EXCLUDE_TEST_METHOD2) +
"</TestPlan>";
static final String TEST_CLASS_EXCLUDED_DATA =
"<TestPlan version=\"1.0\">" +
- String.format("<Entry uri=\"%s\" exclude=\"%s\" />", TEST_URI1,
+ String.format("<Entry name=\"%s\" exclude=\"%s\" />", TEST_NAME1,
EXCLUDE_TEST_CLASS) +
"</TestPlan>";
@@ -70,11 +75,11 @@
@Override
protected void setUp() throws Exception {
super.setUp();
- mPlan = new TestPlan("plan");
+ mPlan = new TestPlan("plan", AbiUtils.getAbisSupportedByCts());
}
/**
- * Simple test for parsing a plan containing two uris
+ * Simple test for parsing a plan containing two names
*/
public void testParse() throws ParseException {
mPlan.parse(getStringAsStream(TEST_DATA));
@@ -86,13 +91,20 @@
* @param plan
*/
private void assertTestData(TestPlan plan) {
- assertEquals(2, plan.getTestUris().size());
- Iterator<String> iter = plan.getTestUris().iterator();
- // assert uris in order
- assertEquals(TEST_URI1, iter.next());
- assertEquals(TEST_URI2, iter.next());
- assertFalse(plan.getExcludedTestFilter(TEST_URI1).hasExclusion());
- assertFalse(plan.getExcludedTestFilter(TEST_URI2).hasExclusion());
+ Set<String> abis = AbiUtils.getAbisSupportedByCts();
+ assertEquals(2 * abis.size(), plan.getTestIds().size());
+ List<String> sortedAbis = new ArrayList<String>(abis);
+ Collections.sort(sortedAbis);
+ Iterator<String> iter = plan.getTestIds().iterator();
+ for (String abi : sortedAbis) {
+ String test1Id = AbiUtils.createId(abi, TEST_NAME1);
+ String test2Id = AbiUtils.createId(abi, TEST_NAME2);
+ // assert names in order
+ assertEquals(test1Id, iter.next());
+ assertEquals(test2Id, iter.next());
+ assertFalse(plan.getTestFilter(test1Id).hasExclusion());
+ assertFalse(plan.getTestFilter(test2Id).hasExclusion());
+ }
}
/**
@@ -100,10 +112,15 @@
*/
public void testParse_exclude() throws ParseException {
mPlan.parse(getStringAsStream(TEST_EXCLUDED_DATA));
- assertEquals(1, mPlan.getTestUris().size());
- TestFilter filter = mPlan.getExcludedTestFilter(TEST_URI1);
- assertTrue(filter.getExcludedTests().contains(new TestIdentifier(EXCLUDE_TEST_CLASS,
- EXCLUDE_TEST_METHOD)));
+ Set<String> abis = AbiUtils.getAbisSupportedByCts();
+ assertEquals(abis.size(), mPlan.getTestIds().size());
+
+ for (String abi : abis) {
+ String test1Id = AbiUtils.createId(abi, TEST_NAME1);
+ TestFilter filter = mPlan.getTestFilter(test1Id);
+ assertTrue(filter.getExcludedTests().contains(new TestIdentifier(EXCLUDE_TEST_CLASS,
+ EXCLUDE_TEST_METHOD)));
+ }
}
/**
@@ -119,12 +136,17 @@
* @param plan
*/
private void assertMultiExcluded(TestPlan plan) {
- assertEquals(1, plan.getTestUris().size());
- TestFilter filter = plan.getExcludedTestFilter(TEST_URI1);
- assertTrue(filter.getExcludedTests().contains(new TestIdentifier(EXCLUDE_TEST_CLASS,
- EXCLUDE_TEST_METHOD)));
- assertTrue(filter.getExcludedTests().contains(new TestIdentifier(EXCLUDE_TEST_CLASS,
- EXCLUDE_TEST_METHOD2)));
+ Set<String> abis = AbiUtils.getAbisSupportedByCts();
+ assertEquals(abis.size(), plan.getTestIds().size());
+
+ for (String abi : abis) {
+ String test1Id = AbiUtils.createId(abi, TEST_NAME1);
+ TestFilter filter = plan.getTestFilter(test1Id);
+ assertTrue(filter.getExcludedTests().contains(new TestIdentifier(EXCLUDE_TEST_CLASS,
+ EXCLUDE_TEST_METHOD)));
+ assertTrue(filter.getExcludedTests().contains(new TestIdentifier(EXCLUDE_TEST_CLASS,
+ EXCLUDE_TEST_METHOD2)));
+ }
}
/**
@@ -132,16 +154,21 @@
*/
public void testParse_classExclude() throws ParseException {
mPlan.parse(getStringAsStream(TEST_CLASS_EXCLUDED_DATA));
- assertEquals(1, mPlan.getTestUris().size());
- TestFilter filter = mPlan.getExcludedTestFilter(TEST_URI1);
- assertTrue(filter.getExcludedClasses().contains(EXCLUDE_TEST_CLASS));
+ Set<String> abis = AbiUtils.getAbisSupportedByCts();
+ assertEquals(abis.size(), mPlan.getTestIds().size());
+
+ for (String abi : abis) {
+ String test1Id = AbiUtils.createId(abi, TEST_NAME1);
+ TestFilter filter = mPlan.getTestFilter(test1Id);
+ assertTrue(filter.getExcludedClasses().contains(EXCLUDE_TEST_CLASS));
+ }
}
/**
* Test serializing an empty plan
* @throws IOException
*/
- public void testSerialize_empty() throws ParseException, IOException {
+ public void testSerialize_empty() throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
mPlan.serialize(outStream);
assertTrue(outStream.toString().contains(EMPTY_DATA));
@@ -152,11 +179,14 @@
* @throws IOException
*/
public void testSerialize_packages() throws ParseException, IOException {
- mPlan.addPackage(TEST_URI1);
- mPlan.addPackage(TEST_URI2);
+ Set<String> abis = AbiUtils.getAbisSupportedByCts();
+ for (String abi : abis) {
+ mPlan.addPackage(AbiUtils.createId(abi, TEST_NAME1));
+ mPlan.addPackage(AbiUtils.createId(abi, TEST_NAME2));
+ }
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
mPlan.serialize(outStream);
- TestPlan parsedPlan = new TestPlan("parsed");
+ TestPlan parsedPlan = new TestPlan("parsed", AbiUtils.getAbisSupportedByCts());
parsedPlan.parse(getStringAsStream(outStream.toString()));
// parsedPlan should contain same contents as TEST_DATA
assertTestData(parsedPlan);
@@ -166,14 +196,19 @@
* Test serializing and deserializing plan with multiple excluded tests
*/
public void testSerialize_multiExclude() throws ParseException, IOException {
- mPlan.addPackage(TEST_URI1);
- mPlan.addExcludedTest(TEST_URI1, new TestIdentifier(EXCLUDE_TEST_CLASS,
- EXCLUDE_TEST_METHOD));
- mPlan.addExcludedTest(TEST_URI1, new TestIdentifier(EXCLUDE_TEST_CLASS,
- EXCLUDE_TEST_METHOD2));
+ Set<String> abis = AbiUtils.getAbisSupportedByCts();
+
+ for (String abi : abis) {
+ String test1Id = AbiUtils.createId(abi, TEST_NAME1);
+ mPlan.addPackage(test1Id);
+ mPlan.addExcludedTest(test1Id, new TestIdentifier(EXCLUDE_TEST_CLASS,
+ EXCLUDE_TEST_METHOD));
+ mPlan.addExcludedTest(test1Id, new TestIdentifier(EXCLUDE_TEST_CLASS,
+ EXCLUDE_TEST_METHOD2));
+ }
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
mPlan.serialize(outStream);
- TestPlan parsedPlan = new TestPlan("parsed");
+ TestPlan parsedPlan = new TestPlan("parsed", AbiUtils.getAbisSupportedByCts());
parsedPlan.parse(getStringAsStream(outStream.toString()));
// parsedPlan should contain same contents as TEST_DATA
assertMultiExcluded(parsedPlan);
diff --git a/tools/utils/buildCts.py b/tools/utils/buildCts.py
index aa5bbf1..f9228d7 100755
--- a/tools/utils/buildCts.py
+++ b/tools/utils/buildCts.py
@@ -169,15 +169,153 @@
plan.ExcludeTests(package, test_list)
self.__WritePlan(plan, 'CTS-stable')
- # CTS Flaky plan - inversion of CTS Stable
+ # CTS Flaky plan - list of tests known to be flaky in lab environment
plan = tools.TestPlan(packages)
plan.Exclude('.*')
plan.Include(r'com\.android\.cts\.browserbench')
for package, test_list in flaky_tests.iteritems():
- plan.Include(package)
+ plan.Include(package+'$')
plan.IncludeTests(package, test_list)
self.__WritePlan(plan, 'CTS-flaky')
+ small_tests = BuildAospSmallSizeTestList()
+ medium_tests = BuildAospMediumSizeTestList()
+
+ # CTS - sub plan for public, small size tests
+ plan = tools.TestPlan(packages)
+ plan.Exclude('.*')
+ for package, test_list in small_tests.iteritems():
+ plan.Include(package+'$')
+ for package, test_list in flaky_tests.iteritems():
+ plan.ExcludeTests(package, test_list)
+ self.__WritePlan(plan, 'CTS-kitkat-small')
+
+ # CTS - sub plan for public, medium size tests
+ plan = tools.TestPlan(packages)
+ plan.Exclude('.*')
+ for package, test_list in medium_tests.iteritems():
+ plan.Include(package+'$')
+ for package, test_list in flaky_tests.iteritems():
+ plan.ExcludeTests(package, test_list)
+ self.__WritePlan(plan, 'CTS-kitkat-medium')
+
+ # CTS - sub plan for hardware tests which is public, large
+ plan = tools.TestPlan(packages)
+ plan.Exclude('.*')
+ plan.Include(r'android\.hardware$')
+ for package, test_list in flaky_tests.iteritems():
+ plan.ExcludeTests(package, test_list)
+ self.__WritePlan(plan, 'CTS-hardware')
+
+ # CTS - sub plan for media tests which is public, large
+ plan = tools.TestPlan(packages)
+ plan.Exclude('.*')
+ plan.Include(r'android\.media$')
+ for package, test_list in flaky_tests.iteritems():
+ plan.ExcludeTests(package, test_list)
+ self.__WritePlan(plan, 'CTS-media')
+
+ # CTS - sub plan for mediastress tests which is public, large
+ plan = tools.TestPlan(packages)
+ plan.Exclude('.*')
+ plan.Include(r'android\.mediastress$')
+ for package, test_list in flaky_tests.iteritems():
+ plan.ExcludeTests(package, test_list)
+ self.__WritePlan(plan, 'CTS-mediastress')
+
+ #CTS - sub plan for new test packages added for staging
+ plan = tools.TestPlan(packages)
+ for package, test_list in small_tests.iteritems():
+ plan.Exclude(package+'$')
+ for package, test_list in medium_tests.iteritems():
+ plan.Exclude(package+'$')
+ plan.Exclude(r'android\.hardware$')
+ plan.Exclude(r'android\.media$')
+ plan.Exclude(r'android\.mediastress$')
+ for package, test_list in flaky_tests.iteritems():
+ plan.ExcludeTests(package, test_list)
+ self.__WritePlan(plan, 'CTS-staging')
+
+def BuildAospMediumSizeTestList():
+ """ Construct a defaultdic that lists package names of medium tests
+ already published to aosp. """
+ return {
+ 'android.app' : [],
+ 'android.core.tests.libcore.package.libcore' : [],
+ 'android.core.tests.libcore.package.org' : [],
+ 'android.core.vm-tests-tf' : [],
+ 'android.dpi' : [],
+ 'android.host.security' : [],
+ 'android.net' : [],
+ 'android.os' : [],
+ 'android.security' : [],
+ 'android.telephony' : [],
+ 'android.webkit' : [],
+ 'android.widget' : [],
+ 'com.android.cts.browserbench' : []}
+
+def BuildAospSmallSizeTestList():
+ """ Construct a defaultdict that lists packages names of small tests
+ already published to aosp. """
+ return {
+ 'android.aadb' : [],
+ 'android.acceleration' : [],
+ 'android.accessibility' : [],
+ 'android.accessibilityservice' : [],
+ 'android.accounts' : [],
+ 'android.admin' : [],
+ 'android.animation' : [],
+ 'android.bionic' : [],
+ 'android.bluetooth' : [],
+ 'android.calendarcommon' : [],
+ 'android.content' : [],
+ 'android.core.tests.libcore.package.com' : [],
+ 'android.core.tests.libcore.package.conscrypt' : [],
+ 'android.core.tests.libcore.package.dalvik' : [],
+ 'android.core.tests.libcore.package.sun' : [],
+ 'android.core.tests.libcore.package.tests' : [],
+ 'android.database' : [],
+ 'android.dreams' : [],
+ 'android.drm' : [],
+ 'android.effect' : [],
+ 'android.gesture' : [],
+ 'android.graphics' : [],
+ 'android.graphics2' : [],
+ 'android.jni' : [],
+ 'android.keystore' : [],
+ 'android.location' : [],
+ 'android.nativemedia.sl' : [],
+ 'android.nativemedia.xa' : [],
+ 'android.nativeopengl' : [],
+ 'android.ndef' : [],
+ 'android.opengl' : [],
+ 'android.openglperf' : [],
+ 'android.permission' : [],
+ 'android.permission2' : [],
+ 'android.preference' : [],
+ 'android.preference2' : [],
+ 'android.provider' : [],
+ 'android.renderscript' : [],
+ 'android.rscpp' : [],
+ 'android.rsg' : [],
+ 'android.sax' : [],
+ 'android.speech' : [],
+ 'android.tests.appsecurity' : [],
+ 'android.text' : [],
+ 'android.textureview' : [],
+ 'android.theme' : [],
+ 'android.usb' : [],
+ 'android.util' : [],
+ 'android.view' : [],
+ 'com.android.cts.dram' : [],
+ 'com.android.cts.filesystemperf' : [],
+ 'com.android.cts.jank' : [],
+ 'com.android.cts.opengl' : [],
+ 'com.android.cts.simplecpu' : [],
+ 'com.android.cts.ui' : [],
+ 'com.android.cts.uihost' : [],
+ 'com.android.cts.videoperf' : [],
+ 'zzz.android.monkey' : []}
def BuildCtsFlakyTestList():
""" Construct a defaultdict that maps package name to a list of tests
diff --git a/tools/utils/cts/tools.py b/tools/utils/cts/tools.py
index 0a4c97c..649e4d7 100644
--- a/tools/utils/cts/tools.py
+++ b/tools/utils/cts/tools.py
@@ -205,7 +205,7 @@
for package in self.all_packages:
if self.map[package]:
entry = doc.createElement('Entry')
- entry.setAttribute('uri', package)
+ entry.setAttribute('name', package)
if package in self.excludedTestsMap:
entry.setAttribute('exclude', ';'.join(self.excludedTestsMap[package]))
if package in self.includedTestsMap:
diff --git a/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java b/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
index 3630446..c772c33 100644
--- a/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
+++ b/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
@@ -211,22 +211,22 @@
curJunitFileData = getWarningMessage() +
"package " + pName + ";\n" +
"import java.io.IOException;\n" +
+ "import com.android.tradefed.testtype.IAbi;\n" +
+ "import com.android.tradefed.testtype.IAbiReceiver;\n" +
"import com.android.tradefed.testtype.DeviceTestCase;\n" +
- "import com.android.tradefed.config.Option;\n" +
- "import com.android.tradefed.config.Option.Importance;\n" +
"import com.android.tradefed.util.AbiFormatter;\n" +
"\n" +
- "public class " + sourceName + " extends DeviceTestCase {\n";
+ "public class " + sourceName + " extends DeviceTestCase implements IAbiReceiver {\n";
}
private String getShellExecJavaLine(String classpath, String mainclass) {
String cmd = String.format("ANDROID_DATA=%s dalvikvm|#ABI#| -Xmx512M -Xss32K " +
"-Djava.io.tmpdir=%s -classpath %s %s", TARGET_JAR_ROOT_PATH, TARGET_JAR_ROOT_PATH,
classpath, mainclass);
- return "String cmd = AbiFormatter.formatCmdForAbi(\"" + cmd + "\", mForceAbi);\n" +
- "String res = getDevice().executeShellCommand(cmd);\n" +
- "// A sucessful adb shell command returns an empty string.\n" +
- "assertEquals(cmd, \"\", res);";
+ return " String cmd = AbiFormatter.formatCmdForAbi(\"" + cmd + "\", mAbi.getBitness());\n" +
+ " String res = getDevice().executeShellCommand(cmd);\n" +
+ " // A sucessful adb shell command returns an empty string.\n" +
+ " assertEquals(cmd, \"\", res);";
}
private String getWarningMessage() {
@@ -257,8 +257,8 @@
//"dot.junit.opcodes.add_double_2addr.Main_testN2";
String mainclass = pName + ".Main_" + method;
- curJunitFileData += " " + getShellExecJavaLine(cp, mainclass);
- curJunitFileData += "}\n\n";
+ curJunitFileData += getShellExecJavaLine(cp, mainclass);
+ curJunitFileData += "\n}\n\n";
}
private void handleTests() throws IOException {
@@ -283,9 +283,12 @@
openCTSHostFileFor(pName, classOnlyName);
- curJunitFileData += "@Option(name = AbiFormatter.FORCE_ABI_STRING,\n" +
- "description = AbiFormatter.FORCE_ABI_DESCRIPTION,\n" +
- "importance = Importance.IF_UNSET)\nprivate String mForceAbi = null;\n\n";
+ curJunitFileData += "\n" +
+ "protected IAbi mAbi;\n" +
+ "@Override\n" +
+ "public void setAbi(IAbi abi) {\n" +
+ " mAbi = abi;\n" +
+ "}\n\n";
List<String> methods = entry.getValue();
Collections.sort(methods, new Comparator<String>() {