Merge "[wv-cts] Assert FindListener callbacks happen on the UI thread."
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 4ee6926..9143263 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -1448,10 +1448,8 @@
Test failed.\n\nUnexpected error. Check logcat.</string>
<string name="wifi_status_initiating_scan">Initiating scan.</string>
- <string name="wifi_status_scan_failure">Unable to initiate scan.</string>
- <string name="wifi_status_open_network_not_found">Unable to find any open network in scan results.</string>
+ <string name="wifi_status_scan_failure">Unable to initiate scan or find any open network in scan results.</string>
<string name="wifi_status_connected_to_other_network">Connected to some other network on the device. Please ensure that there is no saved networks on the device.</string>
-
<string name="wifi_status_initiating_network_request">Initiating network request.</string>
<string name="wifi_status_network_wait_for_available">Waiting for network connection. Please click the network in the dialog that pops up for approving the request.</string>
<string name="wifi_status_network_available">"Connected to network."</string>
@@ -1487,9 +1485,9 @@
<string name="wifi_test_network_suggestion">Network Suggestion tests</string>
<string name="wifi_test_network_suggestion_ssid">Network suggestion with SSID.</string>
<string name="wifi_test_network_suggestion_ssid_info">Tests whether the API can be used to suggest a network with SSID to the device and the device connects to it.</string>
- <string name="wifi_test_network_suggestion_ssid_bssid">Network Request with a specific SSID and BSSID.</string>
+ <string name="wifi_test_network_suggestion_ssid_bssid">Network suggestion with SSID and BSSID.</string>
<string name="wifi_test_network_suggestion_ssid_bssid_info">Tests whether the API can be used to suggest a network with SSID and specific BSSID to the device and the device connects to it.</string>
- <string name="wifi_test_network_suggestion_ssid_post_connect">Network Request with a specific SSID and BSSID.</string>
+ <string name="wifi_test_network_suggestion_ssid_post_connect">Network suggestion with SSID and post connection broadcast.</string>
<string name="wifi_test_network_suggestion_ssid_post_connect_info">Tests whether the API can be used to suggest a network with SSID to the device and the device connects to it and sends the post connect broadcast back to the app.</string>
<!-- Strings for P2pTestActivity -->
@@ -1724,6 +1722,11 @@
<string name="aware_status_lifecycle_failed">Discovery lifecycle FAILURE!</string>
<string name="aware_status_lifecycle_ok">Discovery lifecycle validated!</string>
+ <string name="aware_status_socket_failure">Failure on socket connection setup!</string>
+ <string name="aware_status_socket_server_socket_started">ServerSocket started on port %1$d!</string>
+ <string name="aware_status_socket_server_info_rx">Peer server info: IPv6=%1$s @ port=%2$d!</string>
+ <string name="aware_status_socket_server_message_from_peer">Message from peer: \'%1$s\'</string>
+
<string name="aware_data_path_open_unsolicited_publish">Data Path: Open: Unsolicited Publish</string>
<string name="aware_data_path_open_unsolicited_publish_info">The publisher is now ready.\n\nOn the other device: start the \'Data Path: Open: Unsolicited/Passive\' / \'Subscribe\' test.</string>
<string name="aware_data_path_open_passive_subscribe">Data Path: Open: Passive Subscribe</string>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/BaseTestCase.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/BaseTestCase.java
index 920119f..2ab8bdb 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/BaseTestCase.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/BaseTestCase.java
@@ -16,11 +16,8 @@
package com.android.cts.verifier.wifi;
-import android.annotation.Nullable;
import android.content.Context;
import android.content.res.Resources;
-import android.net.wifi.SupplicantState;
-import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.HandlerThread;
@@ -40,8 +37,8 @@
private Thread mThread;
private HandlerThread mHandlerThread;
protected Handler mHandler;
-
protected WifiManager mWifiManager;
+ protected TestUtils mTestUtils;
public BaseTestCase(Context context) {
mContext = context;
@@ -53,9 +50,10 @@
*/
protected void setUp() {
mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
+ mTestUtils = new TestUtils(mContext, mListener);
// Ensure we're not connected to any wifi network before we start the tests.
- if (isConnected(null, null)) {
+ if (mTestUtils.isConnected(null, null)) {
mListener.onTestFailed(mContext.getString(
R.string.wifi_status_connected_to_other_network));
throw new IllegalStateException("Should not be connected to any network");
@@ -71,27 +69,6 @@
}
/**
- * Checks whether the device is connected.
- *
- * @param ssid If ssid is specified, then check where the device is connected to a network
- * with the specified SSID.
- * @param bssid If bssid is specified, then check where the device is connected to a network
- * with the specified BSSID.
- * @return
- */
- protected boolean isConnected(@Nullable String ssid, @Nullable String bssid) {
- WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
- if (wifiInfo == null) {
- Log.e(TAG, "Failed to get WifiInfo");
- return false;
- }
- if (wifiInfo.getSupplicantState() != SupplicantState.COMPLETED) return false;
- if (ssid != null && !wifiInfo.getSSID().equals(ssid)) return false;
- if (bssid != null && !wifiInfo.getBSSID().equals(bssid)) return false;
- return true;
- }
-
- /**
* Tear down the test case. Executed after test finishes - whether on success or failure.
*/
protected void tearDown() {
@@ -147,7 +124,7 @@
} catch (Exception e) {
Log.e(TAG, "Execute failed", e);
mListener.onTestFailed(
- mContext.getString(R.string.aware_unexpected_error));
+ mContext.getString(R.string.wifi_unexpected_error));
} finally {
tearDown();
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/TestUtils.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/TestUtils.java
new file mode 100644
index 0000000..2b7b4b1
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/TestUtils.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2019 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.wifi;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.wifi.ScanResult;
+import android.net.wifi.SupplicantState;
+import android.net.wifi.WifiInfo;
+import android.net.wifi.WifiManager;
+import android.text.TextUtils;
+import android.util.Log;
+
+import com.android.cts.verifier.R;
+
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Test utility methods.
+ */
+public class TestUtils {
+ private static final String TAG = "NetworkRequestTestCase";
+ private static final boolean DBG = true;
+ private static final int SCAN_TIMEOUT_MS = 30_000;
+
+ private final Context mContext;
+ protected BaseTestCase.Listener mListener;
+ private final WifiManager mWifiManager;
+
+ public TestUtils(Context context, BaseTestCase.Listener listener) {
+ mContext = context;
+ mListener = listener;
+ mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
+ }
+
+ private boolean startScanAndWaitForResults() throws InterruptedException {
+ IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
+ final CountDownLatch countDownLatch = new CountDownLatch(1);
+ // Scan Results available broadcast receiver.
+ BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (DBG) Log.v(TAG, "Broadcast onReceive " + intent);
+ if (!intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) return;
+ if (!intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)) return;
+ if (DBG) Log.v(TAG, "Scan results received");
+ countDownLatch.countDown();
+ }
+ };
+ // Register the receiver for scan results broadcast.
+ mContext.registerReceiver(broadcastReceiver, intentFilter);
+
+ // Start scan.
+ if (DBG) Log.v(TAG, "Starting scan");
+ mListener.onTestMsgReceived(mContext.getString(R.string.wifi_status_initiating_scan));
+ if (!mWifiManager.startScan()) {
+ Log.e(TAG, "Failed to start scan");
+ // Unregister the receiver for scan results broadcast.
+ mContext.unregisterReceiver(broadcastReceiver);
+ return false;
+ }
+ // Wait for scan results.
+ if (DBG) Log.v(TAG, "Wait for scan results");
+ if (!countDownLatch.await(SCAN_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
+ Log.e(TAG, "No new scan results available");
+ // Unregister the receiver for scan results broadcast.
+ mContext.unregisterReceiver(broadcastReceiver);
+ return false;
+ }
+
+ // Unregister the receiver for scan results broadcast.
+ mContext.unregisterReceiver(broadcastReceiver);
+ return true;
+ }
+
+ // Helper to check if the scan result corresponds to an open network.
+ private static boolean isScanResultForOpenNetwork(@NonNull ScanResult scanResult) {
+ String capabilities = scanResult.capabilities;
+ return !capabilities.contains("PSK") && !capabilities.contains("EAP")
+ && !capabilities.contains("WEP") && !capabilities.contains("SAE")
+ && !capabilities.contains("SUITE-B-192") && !capabilities.contains("OWE");
+ }
+
+ /**
+ * Helper method to start a scan and find any open networks in the scan results returned by the
+ * device.
+ * @return ScanResult instance corresponding to an open network if one exists, null if the
+ * scan failed or if there are no open networks found.
+ */
+ public @Nullable ScanResult startScanAndFindAnyOpenNetworkInResults()
+ throws InterruptedException {
+ // Start scan and wait for new results.
+ if (!startScanAndWaitForResults()) {
+ Log.e(TAG,"Failed to initiate a new scan. Using cached results from device");
+ }
+ // Filter results to find an open network.
+ List<ScanResult> scanResults = mWifiManager.getScanResults();
+ for (ScanResult scanResult : scanResults) {
+ if (!TextUtils.isEmpty(scanResult.SSID)
+ && !TextUtils.isEmpty(scanResult.BSSID)
+ && isScanResultForOpenNetwork(scanResult)) {
+ if (DBG) Log.v(TAG, "Found open network " + scanResult);
+ return scanResult;
+ }
+ }
+ Log.e(TAG, "No open networks found in scan results");
+ return null;
+ }
+
+ /**
+ * Helper method to check if a scan result with the specified SSID & BSSID matches the scan
+ * results returned by the device.
+ *
+ * @param ssid SSID of the network.
+ * @param bssid BSSID of network.
+ * @return true if there is a match, false otherwise.
+ */
+ public boolean findNetworkInScanResultsResults(@NonNull String ssid, @NonNull String bssid) {
+ List<ScanResult> scanResults = mWifiManager.getScanResults();
+ for (ScanResult scanResult : scanResults) {
+ if (TextUtils.equals(scanResult.SSID, ssid)
+ && TextUtils.equals(scanResult.BSSID, bssid)) {
+ if (DBG) Log.v(TAG, "Found network " + scanResult);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Checks whether the device is connected.
+ *
+ * @param ssid If ssid is specified, then check where the device is connected to a network
+ * with the specified SSID.
+ * @param bssid If bssid is specified, then check where the device is connected to a network
+ * with the specified BSSID.
+ * @return true if the device is connected to a network with the specified params, false
+ * otherwise.
+ */
+ public boolean isConnected(@Nullable String ssid, @Nullable String bssid) {
+ WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
+ if (wifiInfo == null) {
+ Log.e(TAG, "Failed to get WifiInfo");
+ return false;
+ }
+ if (wifiInfo.getSupplicantState() != SupplicantState.COMPLETED) return false;
+ if (ssid != null && !wifiInfo.getSSID().equals(ssid)) return false;
+ if (bssid != null && !wifiInfo.getBSSID().equals(bssid)) return false;
+ return true;
+ }
+
+
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkRequestTestCase.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkRequestTestCase.java
index 528f7d6..b27407c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkRequestTestCase.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkRequestTestCase.java
@@ -21,21 +21,16 @@
import android.annotation.IntDef;
import android.annotation.NonNull;
-import android.annotation.Nullable;
import android.content.BroadcastReceiver;
import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.MacAddress;
import android.net.Network;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
import android.net.wifi.ScanResult;
-import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSpecifier;
import android.os.PatternMatcher;
-import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
@@ -45,9 +40,6 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
/**
* Test case for all {@link NetworkRequest} requests with specifier built using
@@ -60,7 +52,6 @@
private static final String UNAVAILABLE_SSID = "blahblahblah";
private static final int NETWORK_REQUEST_TIMEOUT_MS = 30_000;
private static final int CALLBACK_TIMEOUT_MS = 40_000;
- private static final int SCAN_TIMEOUT_MS = 30_000;
public static final int NETWORK_SPECIFIER_SPECIFIC_SSID_BSSID = 0;
public static final int NETWORK_SPECIFIER_PATTERN_SSID_BSSID = 1;
@@ -80,7 +71,6 @@
private ConnectivityManager mConnectivityManager;
private NetworkRequest mNetworkRequest;
private CallbackUtils.NetworkCallback mNetworkCallback;
- private BroadcastReceiver mBroadcastReceiver;
private String mFailureReason;
public NetworkRequestTestCase(Context context, @NetworkSpecifierType int networkSpecifierType) {
@@ -107,7 +97,7 @@
case NETWORK_SPECIFIER_UNAVAILABLE_SSID_BSSID:
String ssid = UNAVAILABLE_SSID;
MacAddress bssid = MacAddress.createRandomUnicastAddress();
- if (findNetworkInScanResultsResults(ssid, bssid.toString())) {
+ if (mTestUtils.findNetworkInScanResultsResults(ssid, bssid.toString())) {
Log.e(TAG, "The specifiers chosen match a network in scan results."
+ "Test will fail");
return null;
@@ -121,82 +111,6 @@
return configBuilder.build();
}
- private boolean startScanAndWaitForResults() throws InterruptedException {
- IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
- final CountDownLatch countDownLatch = new CountDownLatch(1);
- // Scan Results available broadcast receiver.
- mBroadcastReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- if (DBG) Log.v(TAG, "Broadcast onReceive " + intent);
- if (!intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) return;
- if (!intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)) return;
- if (DBG) Log.v(TAG, "Scan results received");
- countDownLatch.countDown();
- }
- };
- // Register the receiver for scan results broadcast.
- mContext.registerReceiver(mBroadcastReceiver, intentFilter);
-
- // Start scan.
- if (DBG) Log.v(TAG, "Starting scan");
- mListener.onTestMsgReceived(mContext.getString(R.string.wifi_status_initiating_scan));
- if (!mWifiManager.startScan()) {
- Log.e(TAG, "Failed to start scan");
- setFailureReason(mContext.getString(R.string.wifi_status_scan_failure));
- return false;
- }
- // Wait for scan results.
- if (DBG) Log.v(TAG, "Wait for scan results");
- if (!countDownLatch.await(SCAN_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
- Log.e(TAG, "No new scan results available");
- setFailureReason(mContext.getString(R.string.wifi_status_scan_failure));
- return false;
- }
- return true;
- }
-
- // Helper to check if the scan result corresponds to an open network.
- private static boolean isScanResultForOpenNetwork(@NonNull ScanResult scanResult) {
- String capabilities = scanResult.capabilities;
- return !capabilities.contains("PSK") && !capabilities.contains("EAP")
- && !capabilities.contains("WEP") && !capabilities.contains("SAE")
- && !capabilities.contains("SUITE-B-192") && !capabilities.contains("OWE");
- }
-
- private @Nullable ScanResult startScanAndFindAnyOpenNetworkInResults()
- throws InterruptedException {
- // Start scan and wait for new results.
- if (!startScanAndWaitForResults()) {
- return null;
- }
- // Filter results to find an open network.
- List<ScanResult> scanResults = mWifiManager.getScanResults();
- for (ScanResult scanResult : scanResults) {
- if (!TextUtils.isEmpty(scanResult.SSID)
- && !TextUtils.isEmpty(scanResult.BSSID)
- && isScanResultForOpenNetwork(scanResult)) {
- if (DBG) Log.v(TAG, "Found open network " + scanResult);
- return scanResult;
- }
- }
- Log.e(TAG, "No open networks found in scan results");
- setFailureReason(mContext.getString(R.string.wifi_status_open_network_not_found));
- return null;
- }
-
- private boolean findNetworkInScanResultsResults(@NonNull String ssid, @NonNull String bssid)
- throws InterruptedException {
- List<ScanResult> scanResults = mWifiManager.getScanResults();
- for (ScanResult scanResult : scanResults) {
- if (TextUtils.equals(scanResult.SSID, ssid)
- && TextUtils.equals(scanResult.BSSID, bssid)) {
- if (DBG) Log.v(TAG, "Found network " + scanResult);
- return true;
- }
- }
- return false;
- }
private void setFailureReason(String reason) {
synchronized (mLock) {
@@ -208,8 +122,11 @@
protected boolean executeTest() throws InterruptedException {
// Step 1: Scan and find any open network around.
if (DBG) Log.v(TAG, "Scan and find an open network");
- ScanResult openNetwork = startScanAndFindAnyOpenNetworkInResults();
- if (openNetwork == null) return false;
+ ScanResult openNetwork = mTestUtils.startScanAndFindAnyOpenNetworkInResults();
+ if (openNetwork == null) {
+ setFailureReason(mContext.getString(R.string.wifi_status_scan_failure));
+ return false;
+ }
// Step 2: Create a specifier for the chosen open network depending on the type of test.
NetworkSpecifier wns = createNetworkSpecifier(openNetwork);
@@ -287,9 +204,6 @@
@Override
protected void tearDown() {
- if (mBroadcastReceiver != null) {
- mContext.unregisterReceiver(mBroadcastReceiver);
- }
if (mNetworkCallback != null) {
mConnectivityManager.unregisterNetworkCallback(mNetworkCallback);
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkSuggestionTestCase.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkSuggestionTestCase.java
index 4d0cbc5..f8cf306 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkSuggestionTestCase.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifi/testcase/NetworkSuggestionTestCase.java
@@ -20,7 +20,6 @@
import static android.net.wifi.WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS;
import android.annotation.NonNull;
-import android.annotation.Nullable;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -32,7 +31,6 @@
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSuggestion;
-import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
@@ -54,7 +52,6 @@
private static final boolean DBG = true;
private static final int CALLBACK_TIMEOUT_MS = 40_000;
- private static final int SCAN_TIMEOUT_MS = 30_000;
private final Object mLock = new Object();
private final List<WifiNetworkSuggestion> mNetworkSuggestions = new ArrayList<>();
@@ -88,73 +85,6 @@
return builder.build();
}
- private boolean startScanAndWaitForResults() throws InterruptedException {
- IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
- final CountDownLatch countDownLatch = new CountDownLatch(1);
- // Scan Results available broadcast receiver.
- mBroadcastReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- if (DBG) Log.v(TAG, "Broadcast onReceive " + intent);
- if (!intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) return;
- if (!intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)) return;
- if (DBG) Log.v(TAG, "Scan results received");
- countDownLatch.countDown();
- }
- };
- // Register the receiver for scan results broadcast.
- mContext.registerReceiver(mBroadcastReceiver, intentFilter);
-
- // Start scan.
- if (DBG) Log.v(TAG, "Starting scan");
- mListener.onTestMsgReceived(mContext.getString(R.string.wifi_status_initiating_scan));
- if (!mWifiManager.startScan()) {
- Log.e(TAG, "Failed to start scan");
- setFailureReason(mContext.getString(R.string.wifi_status_scan_failure));
- return false;
- }
- // Wait for scan results.
- if (DBG) Log.v(TAG, "Wait for scan results");
- if (!countDownLatch.await(SCAN_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
- Log.e(TAG, "No new scan results available");
- setFailureReason(mContext.getString(R.string.wifi_status_scan_failure));
- return false;
- }
- // Unregister the scan receiver.
- mContext.unregisterReceiver(mBroadcastReceiver);
- mBroadcastReceiver = null;
- return true;
- }
-
- // Helper to check if the scan result corresponds to an open network.
- private static boolean isScanResultForOpenNetwork(@NonNull ScanResult scanResult) {
- String capabilities = scanResult.capabilities;
- return !capabilities.contains("PSK") && !capabilities.contains("EAP")
- && !capabilities.contains("WEP") && !capabilities.contains("SAE")
- && !capabilities.contains("SUITE-B-192") && !capabilities.contains("OWE");
- }
-
- private @Nullable ScanResult startScanAndFindAnyOpenNetworkInResults()
- throws InterruptedException {
- // Start scan and wait for new results.
- if (!startScanAndWaitForResults()) {
- return null;
- }
- // Filter results to find an open network.
- List<ScanResult> scanResults = mWifiManager.getScanResults();
- for (ScanResult scanResult : scanResults) {
- if (!TextUtils.isEmpty(scanResult.SSID)
- && !TextUtils.isEmpty(scanResult.BSSID)
- && isScanResultForOpenNetwork(scanResult)) {
- if (DBG) Log.v(TAG, "Found open network " + scanResult);
- return scanResult;
- }
- }
- Log.e(TAG, "No open networks found in scan results");
- setFailureReason(mContext.getString(R.string.wifi_status_open_network_not_found));
- return null;
- }
-
private void setFailureReason(String reason) {
synchronized (mLock) {
mFailureReason = reason;
@@ -165,8 +95,11 @@
protected boolean executeTest() throws InterruptedException {
// Step 1: Scan and find any open network around.
if (DBG) Log.v(TAG, "Scan and find an open network");
- ScanResult openNetwork = startScanAndFindAnyOpenNetworkInResults();
- if (openNetwork == null) return false;
+ ScanResult openNetwork = mTestUtils.startScanAndFindAnyOpenNetworkInResults();
+ if (openNetwork == null) {
+ setFailureReason(mContext.getString(R.string.wifi_status_scan_failure));
+ return false;
+ }
// Step 1.a (Optional): Register for the post connection broadcast.
final CountDownLatch countDownLatchForPostConnectionBcast = new CountDownLatch(1);
@@ -225,7 +158,7 @@
// Step 6: Ensure that we connected to the suggested network (optionally, the correct
// BSSID).
- if (!isConnected("\"" + openNetwork.SSID + "\"",
+ if (!mTestUtils.isConnected("\"" + openNetwork.SSID + "\"",
// TODO: This might fail if there are other BSSID's for the same network & the
// device decided to connect/roam to a different BSSID. We don't turn off roaming
// for suggestions.
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/CallbackUtils.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/CallbackUtils.java
index b1bd228..68c741e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/CallbackUtils.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/CallbackUtils.java
@@ -124,6 +124,7 @@
*/
public static class NetworkCb extends ConnectivityManager.NetworkCallback {
private CountDownLatch mBlocker = new CountDownLatch(1);
+ private Network mNetwork = null;
private NetworkCapabilities mNetworkCapabilities = null;
@Override
@@ -135,18 +136,20 @@
@Override
public void onCapabilitiesChanged(Network network,
NetworkCapabilities networkCapabilities) {
+ mNetwork = network;
mNetworkCapabilities = networkCapabilities;
mBlocker.countDown();
}
/**
- * Wait (blocks) for Available or Unavailable callbacks - or timesout.
+ * Wait (blocks) for Capabilities Changed callback - or timesout.
*
- * @return true if Available, false otherwise (Unavailable or timeout).
+ * @return Network + NetworkCapabilities (pair) if occurred, null otherwise.
*/
- public NetworkCapabilities waitForNetwork() throws InterruptedException {
+ public Pair<Network, NetworkCapabilities> waitForNetworkCapabilities()
+ throws InterruptedException {
if (mBlocker.await(CALLBACK_TIMEOUT_SEC, TimeUnit.SECONDS)) {
- return mNetworkCapabilities;
+ return Pair.create(mNetwork, mNetworkCapabilities);
}
return null;
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathInBandTestCase.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathInBandTestCase.java
index 2f9bf4c..c5175c4 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathInBandTestCase.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathInBandTestCase.java
@@ -20,13 +20,23 @@
import android.content.Context;
import android.net.ConnectivityManager;
+import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
+import android.net.wifi.aware.WifiAwareManager;
+import android.net.wifi.aware.WifiAwareNetworkInfo;
import android.util.Log;
+import android.util.Pair;
import com.android.cts.verifier.R;
import com.android.cts.verifier.wifiaware.CallbackUtils;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Inet6Address;
+import java.net.ServerSocket;
+import java.net.Socket;
import java.util.Arrays;
/**
@@ -44,7 +54,9 @@
* 5. Wait for rx message
* 6. Request network
* Wait for network
- * 7. Destroy session
+ * 7. Create socket and bind to server
+ * 8. Send/receive data to validate connection
+ * 9. Destroy session
*
* Publish test sequence:
* 1. Attach
@@ -52,11 +64,13 @@
* 2. Publish
* wait for results (publish session)
* 3. Wait for rx message
- * 4. Request network
- * 5. Send message
+ * 4. Start a ServerSocket
+ * 5. Request network
+ * 6. Send message
* Wait for success
- * 6. Wait for network
- * 7. Destroy session
+ * 7. Wait for network
+ * 8. Receive/Send data to validate connection
+ * 9. Destroy session
*/
public class DataPathInBandTestCase extends DiscoveryBaseTestCase {
private static final String TAG = "DataPathInBandTestCase";
@@ -65,8 +79,14 @@
private static final byte[] MSG_PUB_TO_SUB = "Ready".getBytes();
private static final String PASSPHRASE = "Some super secret password";
+ private static final byte[] MSG_CLIENT_TO_SERVER = "GET SOME BYTES".getBytes();
+ private static final byte[] MSG_SERVER_TO_CLIENT = "PUT SOME OTHER BYTES".getBytes();
+
private boolean mIsSecurityOpen;
private boolean mIsPublish;
+ private Thread mClientServerThread;
+ private ConnectivityManager mCm;
+ private CallbackUtils.NetworkCb mNetworkCb;
public DataPathInBandTestCase(Context context, boolean isSecurityOpen, boolean isPublish,
boolean isUnsolicited) {
@@ -84,6 +104,10 @@
+ ", mIsUnsolicited=" + mIsUnsolicited);
}
+ mCm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
+ mClientServerThread = null;
+ mNetworkCb = null;
+
boolean success;
if (mIsPublish) {
success = executeTestPublisher();
@@ -102,6 +126,18 @@
return true;
}
+ @Override
+ protected void tearDown() {
+ if (mClientServerThread != null) {
+ mClientServerThread.interrupt();
+ }
+ if (mNetworkCb != null) {
+ mCm.unregisterNetworkCallback(mNetworkCb);
+ }
+ super.tearDown();
+ }
+
+
private boolean executeTestSubscriber() throws InterruptedException {
if (DBG) Log.d(TAG, "executeTestSubscriber");
if (!executeSubscribe()) {
@@ -129,33 +165,118 @@
}
// 6. request network
- ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(
- Context.CONNECTIVITY_SERVICE);
+ WifiAwareManager.NetworkSpecifierBuilder nsBuilder =
+ new WifiAwareManager.NetworkSpecifierBuilder().setDiscoverySession(
+ mWifiAwareDiscoverySession).setPeerHandle(mPeerHandle);
+ if (!mIsSecurityOpen) {
+ nsBuilder.setPskPassphrase(PASSPHRASE);
+ }
NetworkRequest nr = new NetworkRequest.Builder().addTransportType(
NetworkCapabilities.TRANSPORT_WIFI_AWARE).setNetworkSpecifier(
- mIsSecurityOpen ? mWifiAwareDiscoverySession.createNetworkSpecifierOpen(mPeerHandle)
- : mWifiAwareDiscoverySession.createNetworkSpecifierPassphrase(mPeerHandle,
- PASSPHRASE)).build();
- CallbackUtils.NetworkCb networkCb = new CallbackUtils.NetworkCb();
- cm.requestNetwork(nr, networkCb, CALLBACK_TIMEOUT_SEC * 1000);
+ nsBuilder.build()).build();
+ mNetworkCb = new CallbackUtils.NetworkCb();
+ mCm.requestNetwork(nr, mNetworkCb, CALLBACK_TIMEOUT_SEC * 1000);
mListener.onTestMsgReceived(
mContext.getString(R.string.aware_status_network_requested));
if (DBG) Log.d(TAG, "executeTestSubscriber: requested network");
- NetworkCapabilities nc = networkCb.waitForNetwork();
- cm.unregisterNetworkCallback(networkCb);
- if (nc == null) {
+
+ // 7. wait for network
+ Pair<Network, NetworkCapabilities> info = mNetworkCb.waitForNetworkCapabilities();
+ if (info == null) {
setFailureReason(mContext.getString(R.string.aware_status_network_failed));
- Log.e(TAG, "executeTestSubscriber: network request rejected - ON_UNAVAILABLE");
+ Log.e(TAG, "executeTestSubscriber: network request rejected or timed-out");
return false;
}
- if (nc.getNetworkSpecifier() != null) {
+ if (info.first == null || info.second == null) {
+ setFailureReason(mContext.getString(R.string.aware_status_network_failed));
+ Log.e(TAG, "executeTestSubscriber: received a null Network or NetworkCapabilities!?");
+ return false;
+ }
+ if (info.second.getNetworkSpecifier() != null) {
setFailureReason(mContext.getString(R.string.aware_status_network_failed_leak));
Log.e(TAG, "executeTestSubscriber: network request accepted - but leaks NS!");
return false;
}
+
mListener.onTestMsgReceived(mContext.getString(R.string.aware_status_network_success));
if (DBG) Log.d(TAG, "executeTestSubscriber: network request granted - AVAILABLE");
+ if (!mIsSecurityOpen) {
+ if (!(info.second.getTransportInfo() instanceof WifiAwareNetworkInfo)) {
+ setFailureReason(mContext.getString(R.string.aware_status_network_failed));
+ Log.e(TAG, "executeTestSubscriber: did not get WifiAwareNetworkInfo from peer!?");
+ return false;
+ }
+ WifiAwareNetworkInfo peerAwareInfo =
+ (WifiAwareNetworkInfo) info.second.getTransportInfo();
+ Inet6Address peerIpv6 = peerAwareInfo.getPeerIpv6Addr();
+ int peerPort = peerAwareInfo.getPort();
+ int peerTransportProtocol = peerAwareInfo.getTransportProtocol();
+ mListener.onTestMsgReceived(
+ mContext.getString(R.string.aware_status_socket_server_info_rx,
+ peerIpv6.toString(),
+ peerPort));
+ if (DBG) {
+ Log.d(TAG,
+ "executeTestPublisher: rx peer info IPv6=" + peerIpv6 + ", port=" + peerPort
+ + ", transportProtocol=" + peerTransportProtocol);
+ }
+ if (peerTransportProtocol != 6) { // 6 == TCP: hard coded at peer
+ setFailureReason(mContext.getString(R.string.aware_status_network_failed));
+ Log.e(TAG, "executeTestSubscriber: Got incorrect transport protocol from peer");
+ return false;
+ }
+ if (peerPort <= 0) {
+ setFailureReason(mContext.getString(R.string.aware_status_network_failed));
+ Log.e(TAG, "executeTestSubscriber: Got invalid port from peer (<=0)");
+ return false;
+ }
+
+ // 8. send/receive - can happen inline here - no need for another thread
+ String currentMethod = "";
+ try {
+ currentMethod = "createSocket";
+ Socket socket = info.first.getSocketFactory().createSocket(peerIpv6, peerPort);
+
+ // simple interaction: write X bytes, read Y bytes
+ currentMethod = "getOutputStream()";
+ OutputStream os = socket.getOutputStream();
+ currentMethod = "write()";
+ os.write(MSG_CLIENT_TO_SERVER, 0, MSG_CLIENT_TO_SERVER.length);
+
+ byte[] buffer = new byte[1024];
+ currentMethod = "getInputStream()";
+ InputStream is = socket.getInputStream();
+ currentMethod = "read()";
+ int numBytes = is.read(buffer, 0, MSG_SERVER_TO_CLIENT.length);
+
+ mListener.onTestMsgReceived(
+ mContext.getString(R.string.aware_status_socket_server_message_from_peer,
+ new String(buffer, 0, numBytes)));
+
+ if (numBytes != MSG_SERVER_TO_CLIENT.length) {
+ setFailureReason(mContext.getString(R.string.aware_status_socket_failure));
+ Log.e(TAG,
+ "executeTestSubscriber: didn't read expected number of bytes - only "
+ + "got -- " + numBytes);
+ return false;
+ }
+ if (!Arrays.equals(MSG_SERVER_TO_CLIENT,
+ Arrays.copyOf(buffer, MSG_SERVER_TO_CLIENT.length))) {
+ setFailureReason(mContext.getString(R.string.aware_status_socket_failure));
+ Log.e(TAG, "executeTestSubscriber: did not get expected message from server.");
+ return false;
+ }
+
+ currentMethod = "close()";
+ os.close();
+ } catch (IOException e) {
+ setFailureReason(mContext.getString(R.string.aware_status_socket_failure));
+ Log.e(TAG, "executeTestSubscriber: failure while executing " + currentMethod);
+ return false;
+ }
+ }
+
return true;
}
@@ -165,21 +286,90 @@
return false;
}
- // 4. Request network
- ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(
- Context.CONNECTIVITY_SERVICE);
+ // 4. create a ServerSocket
+ int port = 0;
+ if (!mIsSecurityOpen) {
+ ServerSocket server;
+ try {
+ server = new ServerSocket(0);
+ } catch (IOException e) {
+ setFailureReason(
+ mContext.getString(R.string.aware_status_socket_failure));
+ Log.e(TAG, "executeTestPublisher: failure creating a ServerSocket -- " + e);
+ return false;
+ }
+ port = server.getLocalPort();
+ mListener.onTestMsgReceived(
+ mContext.getString(R.string.aware_status_socket_server_socket_started, port));
+ if (DBG) Log.d(TAG, "executeTestPublisher: server socket started on port=" + port);
+
+ // accept connections on the server socket - has to be done in a separate thread!
+ mClientServerThread = new Thread(() -> {
+ String currentMethod = "";
+
+ try {
+ currentMethod = "accept()";
+ Socket socket = server.accept();
+ currentMethod = "getInputStream()";
+ InputStream is = socket.getInputStream();
+
+ // simple interaction: read X bytes, write Y bytes
+ byte[] buffer = new byte[1024];
+ currentMethod = "read()";
+ int numBytes = is.read(buffer, 0, MSG_CLIENT_TO_SERVER.length);
+
+ mListener.onTestMsgReceived(mContext.getString(
+ R.string.aware_status_socket_server_message_from_peer,
+ new String(buffer, 0, numBytes)));
+
+ if (numBytes != MSG_CLIENT_TO_SERVER.length) {
+ setFailureReason(mContext.getString(R.string.aware_status_socket_failure));
+ Log.e(TAG,
+ "executeTestPublisher: didn't read expected number of bytes - only "
+ + "got -- " + numBytes);
+ return;
+ }
+ if (!Arrays.equals(MSG_CLIENT_TO_SERVER,
+ Arrays.copyOf(buffer, MSG_CLIENT_TO_SERVER.length))) {
+ setFailureReason(mContext.getString(R.string.aware_status_socket_failure));
+ Log.e(TAG,
+ "executeTestPublisher: did not get expected message from client.");
+ return;
+ }
+
+ currentMethod = "getOutputStream()";
+ OutputStream os = socket.getOutputStream();
+ currentMethod = "write()";
+ os.write(MSG_SERVER_TO_CLIENT, 0, MSG_SERVER_TO_CLIENT.length);
+ currentMethod = "close()";
+ os.close();
+ } catch (IOException e) {
+ setFailureReason(mContext.getString(R.string.aware_status_socket_failure));
+ Log.e(TAG, "executeTestPublisher: failure while executing " + currentMethod);
+ return;
+ }
+ });
+ mClientServerThread.start();
+ }
+
+ // 5. Request network
+ WifiAwareManager.NetworkSpecifierBuilder nsBuilder =
+ new WifiAwareManager.NetworkSpecifierBuilder().setDiscoverySession(
+ mWifiAwareDiscoverySession).setPeerHandle(mPeerHandle);
+ if (!mIsSecurityOpen) {
+ nsBuilder.setPskPassphrase(PASSPHRASE).setPort(port).setTransportProtocol(
+ 6); // 6 == TCP
+ }
NetworkRequest nr = new NetworkRequest.Builder().addTransportType(
NetworkCapabilities.TRANSPORT_WIFI_AWARE).setNetworkSpecifier(
- mIsSecurityOpen ? mWifiAwareDiscoverySession.createNetworkSpecifierOpen(mPeerHandle)
- : mWifiAwareDiscoverySession.createNetworkSpecifierPassphrase(mPeerHandle,
- PASSPHRASE)).build();
- CallbackUtils.NetworkCb networkCb = new CallbackUtils.NetworkCb();
- cm.requestNetwork(nr, networkCb, CALLBACK_TIMEOUT_SEC * 1000);
+ nsBuilder.build()).build();
+ mNetworkCb = new CallbackUtils.NetworkCb();
+ mCm.requestNetwork(nr, mNetworkCb, CALLBACK_TIMEOUT_SEC * 1000);
mListener.onTestMsgReceived(
mContext.getString(R.string.aware_status_network_requested));
if (DBG) Log.d(TAG, "executeTestPublisher: requested network");
- // 5. send message & wait for send status
+ // 6. send message & wait for send status
mWifiAwareDiscoverySession.sendMessage(mPeerHandle, MESSAGE_ID, MSG_PUB_TO_SUB);
CallbackUtils.DiscoveryCb.CallbackData callbackData = mDiscoveryCb.waitForCallbacks(
CallbackUtils.DiscoveryCb.ON_MESSAGE_SEND_SUCCEEDED
@@ -204,15 +394,19 @@
return false;
}
- // 6. wait for network
- NetworkCapabilities nc = networkCb.waitForNetwork();
- cm.unregisterNetworkCallback(networkCb);
- if (nc == null) {
+ // 7. wait for network
+ Pair<Network, NetworkCapabilities> info = mNetworkCb.waitForNetworkCapabilities();
+ if (info == null) {
setFailureReason(mContext.getString(R.string.aware_status_network_failed));
Log.e(TAG, "executeTestPublisher: request network rejected - ON_UNAVAILABLE");
return false;
}
- if (nc.getNetworkSpecifier() != null) {
+ if (info.first == null || info.second == null) {
+ setFailureReason(mContext.getString(R.string.aware_status_network_failed));
+ Log.e(TAG, "executeTestPublisher: received a null Network or NetworkCapabilities!?");
+ return false;
+ }
+ if (info.second.getNetworkSpecifier() != null) {
setFailureReason(mContext.getString(R.string.aware_status_network_failed_leak));
Log.e(TAG, "executeTestSubscriber: network request accepted - but leaks NS!");
return false;
@@ -220,6 +414,18 @@
mListener.onTestMsgReceived(mContext.getString(R.string.aware_status_network_success));
if (DBG) Log.d(TAG, "executeTestPublisher: network request granted - AVAILABLE");
+ // 8. Send/Receive data to validate connection - happens on thread above
+ if (!mIsSecurityOpen) {
+ mClientServerThread.join(CALLBACK_TIMEOUT_SEC * 1000);
+ if (mClientServerThread.isAlive()) {
+ setFailureReason(mContext.getString(R.string.aware_status_socket_failure));
+ Log.e(TAG,
+ "executeTestPublisher: failure while waiting for client-server thread to "
+ + "finish");
+ return false;
+ }
+ }
+
return true;
}
}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathOutOfBandTestCase.java b/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathOutOfBandTestCase.java
index be198e1..0d6ca8f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathOutOfBandTestCase.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/wifiaware/testcase/DataPathOutOfBandTestCase.java
@@ -20,6 +20,7 @@
import android.content.Context;
import android.net.ConnectivityManager;
+import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.wifi.aware.DiscoverySession;
@@ -284,14 +285,14 @@
cm.requestNetwork(nr, networkCb, CALLBACK_TIMEOUT_SEC * 1000);
mListener.onTestMsgReceived(mContext.getString(R.string.aware_status_network_requested));
if (DBG) Log.d(TAG, "executeTestResponder: requested network");
- NetworkCapabilities nc = networkCb.waitForNetwork();
+ Pair<Network, NetworkCapabilities> info = networkCb.waitForNetworkCapabilities();
cm.unregisterNetworkCallback(networkCb);
- if (nc == null) {
+ if (info == null) {
setFailureReason(mContext.getString(R.string.aware_status_network_failed));
Log.e(TAG, "executeTestResponder: network request rejected - ON_UNAVAILABLE");
return false;
}
- if (nc.getNetworkSpecifier() != null) {
+ if (info.second.getNetworkSpecifier() != null) {
setFailureReason(mContext.getString(R.string.aware_status_network_failed_leak));
Log.e(TAG, "executeTestSubscriber: network request accepted - but leaks NS!");
return false;
@@ -423,14 +424,14 @@
cm.requestNetwork(nr, networkCb, CALLBACK_TIMEOUT_SEC * 1000);
mListener.onTestMsgReceived(mContext.getString(R.string.aware_status_network_requested));
if (DBG) Log.d(TAG, "executeTestInitiator: requested network");
- NetworkCapabilities nc = networkCb.waitForNetwork();
+ Pair<Network, NetworkCapabilities> info = networkCb.waitForNetworkCapabilities();
cm.unregisterNetworkCallback(networkCb);
- if (nc == null) {
+ if (info == null) {
setFailureReason(mContext.getString(R.string.aware_status_network_failed));
Log.e(TAG, "executeTestInitiator: network request rejected - ON_UNAVAILABLE");
return false;
}
- if (nc.getNetworkSpecifier() != null) {
+ if (info.second.getNetworkSpecifier() != null) {
setFailureReason(mContext.getString(R.string.aware_status_network_failed_leak));
Log.e(TAG, "executeTestSubscriber: network request accepted - but leaks NS!");
return false;
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicConditionalTestCase.java b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicConditionalTestCase.java
deleted file mode 100644
index d12caa8..0000000
--- a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicConditionalTestCase.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.compatibility.common.util;
-
-import org.junit.Before;
-
-/**
- * Device-side base class for tests leveraging the Business Logic service for rules that are
- * conditionally added based on the device characteristics.
- */
-public class BusinessLogicConditionalTestCase extends BusinessLogicTestCase {
-
- @Override
- @Before
- public void handleBusinessLogic() {
- super.loadBusinessLogic();
- ensureAuthenticated();
- super.executeBusinessLogic();
- }
-
- protected void ensureAuthenticated() {
- if (!mCanReadBusinessLogic) {
- // super class handles the condition that the service is unavailable.
- return;
- }
-
- if (!mBusinessLogic.mConditionalTestsEnabled) {
- skipTest("Execution of device specific tests is not enabled. "
- + "Enable with '--conditional-business-logic-tests-enabled'");
- }
-
- if (mBusinessLogic.isAuthorized()) {
- // Run test as normal.
- return;
- }
- String message = mBusinessLogic.getAuthenticationStatusMessage();
-
- // Fail test since request was not authorized.
- failTest(String.format("Unable to execute because %s.", message));
- }
-}
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicTestCase.java b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicTestCase.java
index 671d33b..29607c3 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicTestCase.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicTestCase.java
@@ -51,6 +51,7 @@
@Before
public void handleBusinessLogic() {
loadBusinessLogic();
+ ensureAuthenticated();
executeBusinessLogic();
}
@@ -79,6 +80,27 @@
}
}
+ protected void ensureAuthenticated() {
+ if (!mCanReadBusinessLogic) {
+ // super class handles the condition that the service is unavailable.
+ return;
+ }
+
+ if (!mBusinessLogic.mConditionalTestsEnabled) {
+ skipTest("Execution of device specific tests is not enabled. "
+ + "Enable with '--conditional-business-logic-tests-enabled'");
+ }
+
+ if (mBusinessLogic.isAuthorized()) {
+ // Run test as normal.
+ return;
+ }
+ String message = mBusinessLogic.getAuthenticationStatusMessage();
+
+ // Fail test since request was not authorized.
+ failTest(String.format("Unable to execute because %s.", message));
+ }
+
protected static Instrumentation getInstrumentation() {
return InstrumentationRegistry.getInstrumentation();
}
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/RequiredServiceRule.java b/common/device-side/util/src/com/android/compatibility/common/util/RequiredServiceRule.java
index eee05e2..a4359fd 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/RequiredServiceRule.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/RequiredServiceRule.java
@@ -59,7 +59,10 @@
};
}
- private static boolean hasService(@NonNull String service) {
+ /**
+ * Checks if the device has the given service.
+ */
+ public static boolean hasService(@NonNull String service) {
// TODO: ideally should call SystemServiceManager directly, but we would need to open
// some @Testing APIs for that.
String command = "service check " + service;
diff --git a/hostsidetests/angle/AndroidTest.xml b/hostsidetests/angle/AndroidTest.xml
index c72618a..140da70 100644
--- a/hostsidetests/angle/AndroidTest.xml
+++ b/hostsidetests/angle/AndroidTest.xml
@@ -17,6 +17,8 @@
<configuration description="Config for CtsAngleIntegrationHostTestCases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="graphics" />
+ <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsAngleDriverTestCases.apk" />
diff --git a/hostsidetests/angle/app/driverTest/Android.mk b/hostsidetests/angle/app/driverTest/Android.mk
index 37a1140..114214e 100644
--- a/hostsidetests/angle/app/driverTest/Android.mk
+++ b/hostsidetests/angle/app/driverTest/Android.mk
@@ -27,7 +27,7 @@
LOCAL_SDK_VERSION := current
# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts
+LOCAL_COMPATIBILITY_SUITE := cts vts cts_instant
LOCAL_MULTILIB := both
diff --git a/hostsidetests/angle/app/driverTest/AndroidManifest.xml b/hostsidetests/angle/app/driverTest/AndroidManifest.xml
index be800a1..28bcb11 100755
--- a/hostsidetests/angle/app/driverTest/AndroidManifest.xml
+++ b/hostsidetests/angle/app/driverTest/AndroidManifest.xml
@@ -16,7 +16,8 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.angleIntegrationTest.driverTest">
+ package="com.android.angleIntegrationTest.driverTest"
+ android:targetSandboxVersion="2">
<application android:debuggable="true">
<uses-library android:name="android.test.runner" />
diff --git a/hostsidetests/angle/app/driverTestSecondary/Android.mk b/hostsidetests/angle/app/driverTestSecondary/Android.mk
index d361192..760a892 100644
--- a/hostsidetests/angle/app/driverTestSecondary/Android.mk
+++ b/hostsidetests/angle/app/driverTestSecondary/Android.mk
@@ -27,7 +27,7 @@
LOCAL_SDK_VERSION := current
# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts
+LOCAL_COMPATIBILITY_SUITE := cts vts cts_instant
LOCAL_MULTILIB := both
diff --git a/hostsidetests/angle/app/driverTestSecondary/AndroidManifest.xml b/hostsidetests/angle/app/driverTestSecondary/AndroidManifest.xml
index bd2739d..5a92e96 100755
--- a/hostsidetests/angle/app/driverTestSecondary/AndroidManifest.xml
+++ b/hostsidetests/angle/app/driverTestSecondary/AndroidManifest.xml
@@ -16,7 +16,8 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.angleIntegrationTest.driverTestSecondary">
+ package="com.android.angleIntegrationTest.driverTestSecondary"
+ android:targetSandboxVersion="2">
<application android:debuggable="true">
<uses-library android:name="android.test.runner" />
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/Android.mk b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/Android.mk
deleted file mode 100644
index 1adf0f8..0000000
--- a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/Android.mk
+++ /dev/null
@@ -1,36 +0,0 @@
-#
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_USE_AAPT2 := true
-LOCAL_MODULE_TAGS := tests
-LOCAL_SDK_VERSION := current
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-LOCAL_EXPORT_PACKAGE_RESOURCES := true
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner android-support-test
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_PACKAGE_NAME := CtsClassloaderSplitApp
-
-# Tag this module as a cts test artifact
-
-include $(BUILD_CTS_SUPPORT_PACKAGE)
-
-include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/Android.mk b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/Android.mk
deleted file mode 100644
index f37be44..0000000
--- a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/Android.mk
+++ /dev/null
@@ -1,35 +0,0 @@
-#
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_USE_AAPT2 := true
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-LOCAL_EXPORT_PACKAGE_RESOURCES := true
-LOCAL_PACKAGE_NAME := CtsClassloaderSplitAppFeatureA
-LOCAL_SDK_VERSION := current
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_APK_LIBRARIES := CtsClassloaderSplitApp
-LOCAL_RES_LIBRARIES := $(LOCAL_APK_LIBRARIES)
-
-LOCAL_AAPT_FLAGS += --custom-package com.android.cts.classloadersplitapp.feature_a
-LOCAL_AAPT_FLAGS += --package-id 0x80
-
-include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/Android.mk b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/Android.mk
deleted file mode 100644
index 3262e15..0000000
--- a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/Android.mk
+++ /dev/null
@@ -1,34 +0,0 @@
-#
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_USE_AAPT2 := true
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-LOCAL_PACKAGE_NAME := CtsClassloaderSplitAppFeatureB
-LOCAL_SDK_VERSION := current
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-LOCAL_APK_LIBRARIES := CtsClassloaderSplitApp CtsClassloaderSplitAppFeatureA
-LOCAL_RES_LIBRARIES := $(LOCAL_APK_LIBRARIES)
-
-LOCAL_AAPT_FLAGS := --custom-package com.android.cts.classloadersplitapp.feature_b
-LOCAL_AAPT_FLAGS += --package-id 0x81
-
-include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/Android.mk b/hostsidetests/appsecurity/test-apps/UsesLibraryApp/Android.mk
deleted file mode 100644
index df12f82..0000000
--- a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/Android.mk
+++ /dev/null
@@ -1,40 +0,0 @@
-#
-# Copyright (C) 2015 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-LOCAL_SDK_VERSION := current
-LOCAL_STATIC_JAVA_LIBRARIES := android-support-test compatibility-device-util ctstestrunner ub-uiautomator
-
-LOCAL_JAVA_LIBRARIES := android.test.base.stubs
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src) \
- ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
-
-LOCAL_PACKAGE_NAME := CtsUsesLibraryApp
-
-# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-
-LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
-
-LOCAL_PROGUARD_ENABLED := disabled
-LOCAL_DEX_PREOPT := false
-
-include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/backup/src/android/cts/backup/ProfileScheduledJobHostSideTest.java b/hostsidetests/backup/src/android/cts/backup/ProfileScheduledJobHostSideTest.java
index 627ff78..b74c7d5 100644
--- a/hostsidetests/backup/src/android/cts/backup/ProfileScheduledJobHostSideTest.java
+++ b/hostsidetests/backup/src/android/cts/backup/ProfileScheduledJobHostSideTest.java
@@ -126,6 +126,7 @@
mProfileUserId);
// Force run k/v job.
+ String startLog = mLogcatInspector.mark(TAG);
int jobId = getJobIdForUser(KEY_VALUE_MIN_JOB_ID, mProfileUserId);
mBackupUtils.executeShellCommandSync(JOB_SCHEDULER_RUN_COMMAND + " " + jobId);
@@ -133,7 +134,7 @@
mLogcatInspector.assertLogcatContainsInOrder(
LOGCAT_FILTER,
TIMEOUT_FOR_KEY_VALUE_SECONDS,
- mLogcatInspector.mark(TAG),
+ startLog,
KEY_VALUE_SUCCESS_LOG);
// Check job rescheduled.
@@ -176,6 +177,7 @@
mBackupUtils.backupNowAndAssertSuccessForUser(PACKAGE_MANAGER_SENTINEL, mProfileUserId);
// Force run full backup job.
+ String startLog = mLogcatInspector.mark(TAG);
int jobId = getJobIdForUser(FULL_BACKUP_MIN_JOB_ID, mProfileUserId);
mBackupUtils.executeShellCommandSync(JOB_SCHEDULER_RUN_COMMAND + " " + jobId);
@@ -183,7 +185,7 @@
mLogcatInspector.assertLogcatContainsInOrder(
LOGCAT_FILTER,
TIMEOUT_FOR_FULL_BACKUP_SECONDS,
- mLogcatInspector.mark(TAG),
+ startLog,
FULL_BACKUP_SUCCESS_LOG);
// Check job rescheduled.
diff --git a/hostsidetests/classloaders/splits/Android.bp b/hostsidetests/classloaders/splits/Android.bp
new file mode 100644
index 0000000..17f02a7
--- /dev/null
+++ b/hostsidetests/classloaders/splits/Android.bp
@@ -0,0 +1,34 @@
+// Copyright (C) 2019 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.
+
+java_test_host {
+ name: "CtsClassloaderSplitsHostTestCases",
+ defaults: [ "cts_defaults" ],
+ srcs: [ "src/**/*.java" ],
+ libs: [
+ "compatibility-host-util",
+ "cts-tradefed",
+ "tradefed",
+ ],
+ test_suites: [
+ "cts",
+ "vts",
+ "general-tests",
+ ],
+ required: [
+ "CtsClassloaderSplitApp",
+ "CtsClassloaderSplitAppFeatureA",
+ "CtsClassloaderSplitAppFeatureB",
+ ],
+}
diff --git a/hostsidetests/classloaders/splits/AndroidTest.xml b/hostsidetests/classloaders/splits/AndroidTest.xml
new file mode 100644
index 0000000..77b5bce
--- /dev/null
+++ b/hostsidetests/classloaders/splits/AndroidTest.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration description="Config for the CTS Classloader Splits host tests">
+ <option name="test-suite-tag" value="cts" />
+ <option name="config-descriptor:metadata" key="component" value="framework" />
+ <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+ <option name="jar" value="CtsClassloaderSplitsHostTestCases.jar" />
+ <option name="runtime-hint" value="1m" />
+ </test>
+</configuration>
diff --git a/hostsidetests/classloaders/splits/TEST_MAPPING b/hostsidetests/classloaders/splits/TEST_MAPPING
new file mode 100644
index 0000000..18f00dd
--- /dev/null
+++ b/hostsidetests/classloaders/splits/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "presubmit": [
+ {
+ "name": "CtsClassloaderSplitsHostTestCases"
+ }
+ ]
+}
diff --git a/hostsidetests/classloaders/splits/apps/Android.bp b/hostsidetests/classloaders/splits/apps/Android.bp
new file mode 100644
index 0000000..ebd9318
--- /dev/null
+++ b/hostsidetests/classloaders/splits/apps/Android.bp
@@ -0,0 +1,29 @@
+// Copyright (C) 2019 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.
+
+android_test {
+ name: "CtsClassloaderSplitApp",
+ defaults: [ "cts_support_defaults" ],
+ sdk_version: "current",
+ srcs: ["src/**/*.java"],
+ static_libs: [
+ "android-support-test",
+ "ctstestrunner",
+ ],
+ test_suites: [
+ "cts",
+ "vts",
+ "general-tests",
+ ],
+}
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/AndroidManifest.xml b/hostsidetests/classloaders/splits/apps/AndroidManifest.xml
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/AndroidManifest.xml
rename to hostsidetests/classloaders/splits/apps/AndroidManifest.xml
diff --git a/hostsidetests/classloaders/splits/apps/feature_a/Android.bp b/hostsidetests/classloaders/splits/apps/feature_a/Android.bp
new file mode 100644
index 0000000..0fd7091
--- /dev/null
+++ b/hostsidetests/classloaders/splits/apps/feature_a/Android.bp
@@ -0,0 +1,32 @@
+// Copyright (C) 2019 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.
+
+android_test_helper_app {
+ name: "CtsClassloaderSplitAppFeatureA",
+ defaults: [ "cts_support_defaults" ],
+ sdk_version: "current",
+ srcs: [ "src/**/*.java" ],
+ libs: [ "CtsClassloaderSplitApp" ],
+ aaptflags: [
+ "--custom-package",
+ "com.android.cts.classloadersplitapp.feature_a",
+ "--package-id",
+ "0x80",
+ ],
+ test_suites: [
+ "cts",
+ "vts",
+ "general-tests",
+ ],
+}
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/AndroidManifest.xml b/hostsidetests/classloaders/splits/apps/feature_a/AndroidManifest.xml
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/AndroidManifest.xml
rename to hostsidetests/classloaders/splits/apps/feature_a/AndroidManifest.xml
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAActivity.java b/hostsidetests/classloaders/splits/apps/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAActivity.java
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAActivity.java
rename to hostsidetests/classloaders/splits/apps/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAActivity.java
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAReceiver.java b/hostsidetests/classloaders/splits/apps/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAReceiver.java
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAReceiver.java
rename to hostsidetests/classloaders/splits/apps/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAReceiver.java
diff --git a/hostsidetests/classloaders/splits/apps/feature_b/Android.bp b/hostsidetests/classloaders/splits/apps/feature_b/Android.bp
new file mode 100644
index 0000000..2643840
--- /dev/null
+++ b/hostsidetests/classloaders/splits/apps/feature_b/Android.bp
@@ -0,0 +1,35 @@
+// Copyright (C) 2019 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.
+
+android_test_helper_app {
+ name: "CtsClassloaderSplitAppFeatureB",
+ defaults: [ "cts_support_defaults" ],
+ sdk_version: "current",
+ srcs: [ "src/**/*.java" ],
+ libs: [
+ "CtsClassloaderSplitApp",
+ "CtsClassloaderSplitAppFeatureA",
+ ],
+ aaptflags: [
+ "--custom-package",
+ "com.android.cts.classloadersplitapp.feature_a",
+ "--package-id",
+ "0x81",
+ ],
+ test_suites: [
+ "cts",
+ "vts",
+ "general-tests",
+ ],
+}
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/AndroidManifest.xml b/hostsidetests/classloaders/splits/apps/feature_b/AndroidManifest.xml
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/AndroidManifest.xml
rename to hostsidetests/classloaders/splits/apps/feature_b/AndroidManifest.xml
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/res/values-pl/values.xml b/hostsidetests/classloaders/splits/apps/feature_b/res/values-pl/values.xml
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/res/values-pl/values.xml
rename to hostsidetests/classloaders/splits/apps/feature_b/res/values-pl/values.xml
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/res/values/values.xml b/hostsidetests/classloaders/splits/apps/feature_b/res/values/values.xml
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/res/values/values.xml
rename to hostsidetests/classloaders/splits/apps/feature_b/res/values/values.xml
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBActivity.java b/hostsidetests/classloaders/splits/apps/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBActivity.java
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBActivity.java
rename to hostsidetests/classloaders/splits/apps/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBActivity.java
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBReceiver.java b/hostsidetests/classloaders/splits/apps/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBReceiver.java
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBReceiver.java
rename to hostsidetests/classloaders/splits/apps/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBReceiver.java
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/BaseActivity.java b/hostsidetests/classloaders/splits/apps/src/com/android/cts/classloadersplitapp/BaseActivity.java
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/BaseActivity.java
rename to hostsidetests/classloaders/splits/apps/src/com/android/cts/classloadersplitapp/BaseActivity.java
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/BaseReceiver.java b/hostsidetests/classloaders/splits/apps/src/com/android/cts/classloadersplitapp/BaseReceiver.java
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/BaseReceiver.java
rename to hostsidetests/classloaders/splits/apps/src/com/android/cts/classloadersplitapp/BaseReceiver.java
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/SplitAppTest.java b/hostsidetests/classloaders/splits/apps/src/com/android/cts/classloadersplitapp/SplitAppTest.java
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/SplitAppTest.java
rename to hostsidetests/classloaders/splits/apps/src/com/android/cts/classloadersplitapp/SplitAppTest.java
diff --git a/hostsidetests/classloaders/splits/src/android/classloaders/cts/BaseInstallMultiple.java b/hostsidetests/classloaders/splits/src/android/classloaders/cts/BaseInstallMultiple.java
new file mode 100644
index 0000000..f5170e9
--- /dev/null
+++ b/hostsidetests/classloaders/splits/src/android/classloaders/cts/BaseInstallMultiple.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+package android.classloaders.cts;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.util.AbiUtils;
+
+import junit.framework.TestCase;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Base class for invoking the install-multiple command via ADB. Subclass this for less typing:
+ *
+ * <code>
+ * private class InstallMultiple extends BaseInstallMultiple<InstallMultiple> {
+ * public InstallMultiple() {
+ * super(getDevice(), null, null);
+ * }
+ * }
+ * </code>
+ */
+public class BaseInstallMultiple<T extends BaseInstallMultiple<?>> {
+ private final ITestDevice mDevice;
+ private final IBuildInfo mBuild;
+ private final IAbi mAbi;
+
+ private final List<String> mArgs = new ArrayList<>();
+ private final List<File> mApks = new ArrayList<>();
+ private boolean mUseNaturalAbi;
+
+ public BaseInstallMultiple(ITestDevice device, IBuildInfo buildInfo, IAbi abi) {
+ mDevice = device;
+ mBuild = buildInfo;
+ mAbi = abi;
+ addArg("-g");
+ }
+
+ T addArg(String arg) {
+ mArgs.add(arg);
+ return (T) this;
+ }
+
+ T addApk(String apk) throws FileNotFoundException {
+ CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mBuild);
+ mApks.add(buildHelper.getTestFile(apk));
+ return (T) this;
+ }
+
+ T inheritFrom(String packageName) {
+ addArg("-r");
+ addArg("-p " + packageName);
+ return (T) this;
+ }
+
+ T useNaturalAbi() {
+ mUseNaturalAbi = true;
+ return (T) this;
+ }
+
+ T allowTest() {
+ addArg("-t");
+ return (T) this;
+ }
+
+ T locationAuto() {
+ addArg("--install-location 0");
+ return (T) this;
+ }
+
+ T locationInternalOnly() {
+ addArg("--install-location 1");
+ return (T) this;
+ }
+
+ T locationPreferExternal() {
+ addArg("--install-location 2");
+ return (T) this;
+ }
+
+ T forceUuid(String uuid) {
+ addArg("--force-uuid " + uuid);
+ return (T) this;
+ }
+
+ T forUser(int userId) {
+ addArg("--user " + userId);
+ return (T) this;
+ }
+
+ void run() throws DeviceNotAvailableException {
+ run(true, null);
+ }
+
+ void runExpectingFailure() throws DeviceNotAvailableException {
+ run(false, null);
+ }
+
+ void runExpectingFailure(String failure) throws DeviceNotAvailableException {
+ run(false, failure);
+ }
+
+ private void run(boolean expectingSuccess, String failure) throws DeviceNotAvailableException {
+ final ITestDevice device = mDevice;
+
+ // Create an install session
+ final StringBuilder cmd = new StringBuilder();
+ cmd.append("pm install-create");
+ for (String arg : mArgs) {
+ cmd.append(' ').append(arg);
+ }
+ if (!mUseNaturalAbi && mAbi != null) {
+ cmd.append(' ').append(AbiUtils.createAbiFlag(mAbi.getName()));
+ }
+
+ String result = device.executeShellCommand(cmd.toString());
+ TestCase.assertTrue(result, result.startsWith("Success"));
+
+ final int start = result.lastIndexOf("[");
+ final int end = result.lastIndexOf("]");
+ int sessionId = -1;
+ try {
+ if (start != -1 && end != -1 && start < end) {
+ sessionId = Integer.parseInt(result.substring(start + 1, end));
+ }
+ } catch (NumberFormatException e) {
+ }
+ if (sessionId == -1) {
+ throw new IllegalStateException("Failed to create install session: " + result);
+ }
+
+ // Push our files into session. Ideally we'd use stdin streaming,
+ // but ddmlib doesn't support it yet.
+ for (int i = 0; i < mApks.size(); i++) {
+ final File apk = mApks.get(i);
+ final String remotePath = "/data/local/tmp/" + i + "_" + apk.getName();
+ if (!device.pushFile(apk, remotePath)) {
+ throw new IllegalStateException("Failed to push " + apk);
+ }
+
+ cmd.setLength(0);
+ cmd.append("pm install-write");
+ cmd.append(' ').append(sessionId);
+ cmd.append(' ').append(i + "_" + apk.getName());
+ cmd.append(' ').append(remotePath);
+
+ result = device.executeShellCommand(cmd.toString());
+ TestCase.assertTrue(result, result.startsWith("Success"));
+ }
+
+ // Everything staged; let's pull trigger
+ cmd.setLength(0);
+ cmd.append("pm install-commit");
+ cmd.append(' ').append(sessionId);
+
+ result = device.executeShellCommand(cmd.toString()).trim();
+ if (failure == null) {
+ if (expectingSuccess) {
+ TestCase.assertTrue(result, result.startsWith("Success"));
+ } else {
+ TestCase.assertFalse(result, result.startsWith("Success"));
+ }
+ } else {
+ TestCase.assertTrue(result, result.contains(failure));
+ }
+ }
+}
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/ClassloaderSplitsTest.java b/hostsidetests/classloaders/splits/src/android/classloaders/cts/ClassloaderSplitsTest.java
similarity index 89%
rename from hostsidetests/appsecurity/src/android/appsecurity/cts/ClassloaderSplitsTest.java
rename to hostsidetests/classloaders/splits/src/android/classloaders/cts/ClassloaderSplitsTest.java
index 4e54bc4..1460bfc 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/ClassloaderSplitsTest.java
+++ b/hostsidetests/classloaders/splits/src/android/classloaders/cts/ClassloaderSplitsTest.java
@@ -13,11 +13,12 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
-package android.appsecurity.cts;
+package android.classloaders.cts;
import android.platform.test.annotations.AppModeFull;
import android.platform.test.annotations.AppModeInstant;
import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
import org.junit.After;
import org.junit.Before;
@@ -25,7 +26,7 @@
import org.junit.runner.RunWith;
@RunWith(DeviceJUnit4ClassRunner.class)
-public class ClassloaderSplitsTest extends BaseAppSecurityTest {
+public class ClassloaderSplitsTest extends BaseHostJUnit4Test {
private static final String PKG = "com.android.cts.classloadersplitapp";
private static final String TEST_CLASS = PKG + ".SplitAppTest";
@@ -47,7 +48,6 @@
@Before
public void setUp() throws Exception {
- Utils.prepareSingleUser(getDevice());
getDevice().uninstallPackage(PKG);
}
@@ -116,4 +116,14 @@
runDeviceTests(getDevice(), PKG, TEST_CLASS, "testBaseClassLoader");
runDeviceTests(getDevice(), PKG, TEST_CLASS, "testAllReceivers");
}
+
+ protected class InstallMultiple extends BaseInstallMultiple<InstallMultiple> {
+ public InstallMultiple() {
+ this(false);
+ }
+ public InstallMultiple(boolean instant) {
+ super(getDevice(), getBuild(), getAbi());
+ addArg(instant ? "--instant" : "");
+ }
+ }
}
diff --git a/hostsidetests/classloaders/useslibrary/Android.bp b/hostsidetests/classloaders/useslibrary/Android.bp
new file mode 100644
index 0000000..603b2ec
--- /dev/null
+++ b/hostsidetests/classloaders/useslibrary/Android.bp
@@ -0,0 +1,30 @@
+// Copyright (C) 2019 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.
+
+java_test_host {
+ name: "CtsUsesLibraryHostTestCases",
+ defaults: [ "cts_defaults" ],
+ srcs: [ "src/**/*.java" ],
+ libs: [
+ "compatibility-host-util",
+ "cts-tradefed",
+ "tradefed",
+ ],
+ test_suites: [
+ "cts",
+ "vts",
+ "general-tests",
+ ],
+ required: [ "CtsUsesLibraryApp" ],
+}
diff --git a/hostsidetests/classloaders/useslibrary/AndroidTest.xml b/hostsidetests/classloaders/useslibrary/AndroidTest.xml
new file mode 100644
index 0000000..b7796d7
--- /dev/null
+++ b/hostsidetests/classloaders/useslibrary/AndroidTest.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<configuration description="Config for the CTS UsesLibrary host tests">
+ <option name="test-suite-tag" value="cts" />
+ <option name="config-descriptor:metadata" key="component" value="framework" />
+ <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+ <option name="jar" value="CtsUsesLibraryHostTestCases.jar" />
+ <option name="runtime-hint" value="1m" />
+ </test>
+</configuration>
diff --git a/hostsidetests/classloaders/useslibrary/TEST_MAPPING b/hostsidetests/classloaders/useslibrary/TEST_MAPPING
new file mode 100644
index 0000000..72ef61b
--- /dev/null
+++ b/hostsidetests/classloaders/useslibrary/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "presubmit": [
+ {
+ "name": "CtsUsesLibraryHostTestCases"
+ }
+ ]
+}
diff --git a/hostsidetests/classloaders/useslibrary/app/Android.bp b/hostsidetests/classloaders/useslibrary/app/Android.bp
new file mode 100644
index 0000000..faf7a22
--- /dev/null
+++ b/hostsidetests/classloaders/useslibrary/app/Android.bp
@@ -0,0 +1,32 @@
+// Copyright (C) 2019 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.
+
+android_test {
+ name: "CtsUsesLibraryApp",
+ defaults: [ "cts_support_defaults" ],
+ sdk_version: "current",
+ srcs: ["src/**/*.java"],
+ libs: [
+ "android.test.base.stubs",
+ ],
+ static_libs: [
+ "android-support-test",
+ "ctstestrunner",
+ ],
+ test_suites: [
+ "cts",
+ "vts",
+ "general-tests",
+ ],
+}
diff --git a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/AndroidManifest.xml b/hostsidetests/classloaders/useslibrary/app/AndroidManifest.xml
similarity index 100%
rename from hostsidetests/appsecurity/test-apps/UsesLibraryApp/AndroidManifest.xml
rename to hostsidetests/classloaders/useslibrary/app/AndroidManifest.xml
diff --git a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java b/hostsidetests/classloaders/useslibrary/app/src/com/android/cts/useslibrary/UsesLibraryTest.java
similarity index 95%
rename from hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java
rename to hostsidetests/classloaders/useslibrary/app/src/com/android/cts/useslibrary/UsesLibraryTest.java
index 73b820d..7fa8b20 100644
--- a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java
+++ b/hostsidetests/classloaders/useslibrary/app/src/com/android/cts/useslibrary/UsesLibraryTest.java
@@ -16,11 +16,6 @@
package com.android.cts.useslibrary;
-import android.content.pm.PackageManager;
-import android.os.Environment;
-import android.support.test.uiautomator.UiDevice;
-import android.support.test.uiautomator.UiObject;
-import android.support.test.uiautomator.UiSelector;
import android.test.InstrumentationTestCase;
import dalvik.system.BaseDexClassLoader;
diff --git a/hostsidetests/classloaders/useslibrary/src/android/classloaders/cts/BaseInstallMultiple.java b/hostsidetests/classloaders/useslibrary/src/android/classloaders/cts/BaseInstallMultiple.java
new file mode 100644
index 0000000..f5170e9
--- /dev/null
+++ b/hostsidetests/classloaders/useslibrary/src/android/classloaders/cts/BaseInstallMultiple.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+package android.classloaders.cts;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.util.AbiUtils;
+
+import junit.framework.TestCase;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Base class for invoking the install-multiple command via ADB. Subclass this for less typing:
+ *
+ * <code>
+ * private class InstallMultiple extends BaseInstallMultiple<InstallMultiple> {
+ * public InstallMultiple() {
+ * super(getDevice(), null, null);
+ * }
+ * }
+ * </code>
+ */
+public class BaseInstallMultiple<T extends BaseInstallMultiple<?>> {
+ private final ITestDevice mDevice;
+ private final IBuildInfo mBuild;
+ private final IAbi mAbi;
+
+ private final List<String> mArgs = new ArrayList<>();
+ private final List<File> mApks = new ArrayList<>();
+ private boolean mUseNaturalAbi;
+
+ public BaseInstallMultiple(ITestDevice device, IBuildInfo buildInfo, IAbi abi) {
+ mDevice = device;
+ mBuild = buildInfo;
+ mAbi = abi;
+ addArg("-g");
+ }
+
+ T addArg(String arg) {
+ mArgs.add(arg);
+ return (T) this;
+ }
+
+ T addApk(String apk) throws FileNotFoundException {
+ CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mBuild);
+ mApks.add(buildHelper.getTestFile(apk));
+ return (T) this;
+ }
+
+ T inheritFrom(String packageName) {
+ addArg("-r");
+ addArg("-p " + packageName);
+ return (T) this;
+ }
+
+ T useNaturalAbi() {
+ mUseNaturalAbi = true;
+ return (T) this;
+ }
+
+ T allowTest() {
+ addArg("-t");
+ return (T) this;
+ }
+
+ T locationAuto() {
+ addArg("--install-location 0");
+ return (T) this;
+ }
+
+ T locationInternalOnly() {
+ addArg("--install-location 1");
+ return (T) this;
+ }
+
+ T locationPreferExternal() {
+ addArg("--install-location 2");
+ return (T) this;
+ }
+
+ T forceUuid(String uuid) {
+ addArg("--force-uuid " + uuid);
+ return (T) this;
+ }
+
+ T forUser(int userId) {
+ addArg("--user " + userId);
+ return (T) this;
+ }
+
+ void run() throws DeviceNotAvailableException {
+ run(true, null);
+ }
+
+ void runExpectingFailure() throws DeviceNotAvailableException {
+ run(false, null);
+ }
+
+ void runExpectingFailure(String failure) throws DeviceNotAvailableException {
+ run(false, failure);
+ }
+
+ private void run(boolean expectingSuccess, String failure) throws DeviceNotAvailableException {
+ final ITestDevice device = mDevice;
+
+ // Create an install session
+ final StringBuilder cmd = new StringBuilder();
+ cmd.append("pm install-create");
+ for (String arg : mArgs) {
+ cmd.append(' ').append(arg);
+ }
+ if (!mUseNaturalAbi && mAbi != null) {
+ cmd.append(' ').append(AbiUtils.createAbiFlag(mAbi.getName()));
+ }
+
+ String result = device.executeShellCommand(cmd.toString());
+ TestCase.assertTrue(result, result.startsWith("Success"));
+
+ final int start = result.lastIndexOf("[");
+ final int end = result.lastIndexOf("]");
+ int sessionId = -1;
+ try {
+ if (start != -1 && end != -1 && start < end) {
+ sessionId = Integer.parseInt(result.substring(start + 1, end));
+ }
+ } catch (NumberFormatException e) {
+ }
+ if (sessionId == -1) {
+ throw new IllegalStateException("Failed to create install session: " + result);
+ }
+
+ // Push our files into session. Ideally we'd use stdin streaming,
+ // but ddmlib doesn't support it yet.
+ for (int i = 0; i < mApks.size(); i++) {
+ final File apk = mApks.get(i);
+ final String remotePath = "/data/local/tmp/" + i + "_" + apk.getName();
+ if (!device.pushFile(apk, remotePath)) {
+ throw new IllegalStateException("Failed to push " + apk);
+ }
+
+ cmd.setLength(0);
+ cmd.append("pm install-write");
+ cmd.append(' ').append(sessionId);
+ cmd.append(' ').append(i + "_" + apk.getName());
+ cmd.append(' ').append(remotePath);
+
+ result = device.executeShellCommand(cmd.toString());
+ TestCase.assertTrue(result, result.startsWith("Success"));
+ }
+
+ // Everything staged; let's pull trigger
+ cmd.setLength(0);
+ cmd.append("pm install-commit");
+ cmd.append(' ').append(sessionId);
+
+ result = device.executeShellCommand(cmd.toString()).trim();
+ if (failure == null) {
+ if (expectingSuccess) {
+ TestCase.assertTrue(result, result.startsWith("Success"));
+ } else {
+ TestCase.assertFalse(result, result.startsWith("Success"));
+ }
+ } else {
+ TestCase.assertTrue(result, result.contains(failure));
+ }
+ }
+}
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/UsesLibraryHostTest.java b/hostsidetests/classloaders/useslibrary/src/android/classloaders/cts/UsesLibraryHostTest.java
similarity index 84%
rename from hostsidetests/appsecurity/src/android/appsecurity/cts/UsesLibraryHostTest.java
rename to hostsidetests/classloaders/useslibrary/src/android/classloaders/cts/UsesLibraryHostTest.java
index 41ce7a1..aecd87b 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/UsesLibraryHostTest.java
+++ b/hostsidetests/classloaders/useslibrary/src/android/classloaders/cts/UsesLibraryHostTest.java
@@ -14,12 +14,13 @@
* limitations under the License.
*/
-package android.appsecurity.cts;
+package android.classloaders.cts;
import android.platform.test.annotations.AppModeFull;
import android.platform.test.annotations.AppModeInstant;
import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
import org.junit.After;
import org.junit.Before;
@@ -32,7 +33,7 @@
*/
@AppModeFull(reason = "TODO verify whether or not these should run in instant mode")
@RunWith(DeviceJUnit4ClassRunner.class)
-public class UsesLibraryHostTest extends BaseAppSecurityTest {
+public class UsesLibraryHostTest extends BaseHostJUnit4Test {
private static final String PKG = "com.android.cts.useslibrary";
private static final String APK = "CtsUsesLibraryApp.apk";
@@ -79,4 +80,14 @@
new InstallMultiple(instant).addApk(APK).run();
Utils.runDeviceTests(getDevice(), PKG, ".UsesLibraryTest", "testDuplicateLibrary");
}
+
+ protected class InstallMultiple extends BaseInstallMultiple<InstallMultiple> {
+ public InstallMultiple() {
+ this(false);
+ }
+ public InstallMultiple(boolean instant) {
+ super(getDevice(), getBuild(), getAbi());
+ addArg(instant ? "--instant" : "");
+ }
+ }
}
diff --git a/hostsidetests/classloaders/useslibrary/src/android/classloaders/cts/Utils.java b/hostsidetests/classloaders/useslibrary/src/android/classloaders/cts/Utils.java
new file mode 100644
index 0000000..48497d8
--- /dev/null
+++ b/hostsidetests/classloaders/useslibrary/src/android/classloaders/cts/Utils.java
@@ -0,0 +1,159 @@
+/*
+ * 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.classloaders.cts;
+
+import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
+import com.android.ddmlib.testrunner.TestResult.TestStatus;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.result.CollectingTestListener;
+import com.android.tradefed.result.TestDescription;
+import com.android.tradefed.result.TestResult;
+import com.android.tradefed.result.TestRunResult;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+public class Utils {
+ public static final int USER_SYSTEM = 0;
+
+ public static void runDeviceTests(ITestDevice device, String packageName, String testClassName,
+ String testMethodName) throws DeviceNotAvailableException {
+ runDeviceTests(device, packageName, testClassName, testMethodName, USER_SYSTEM, null);
+ }
+
+ public static void runDeviceTests(ITestDevice device, String packageName, String testClassName,
+ String testMethodName, Map<String, String> testArgs)
+ throws DeviceNotAvailableException {
+ runDeviceTests(device, packageName, testClassName, testMethodName, USER_SYSTEM, testArgs);
+ }
+
+ public static void runDeviceTests(ITestDevice device, String packageName, String testClassName,
+ String testMethodName, int userId) throws DeviceNotAvailableException {
+ runDeviceTests(device, packageName, testClassName, testMethodName, userId, null);
+ }
+
+ public static void runDeviceTests(ITestDevice device, String packageName, String testClassName,
+ String testMethodName, int userId, Map<String, String> testArgs)
+ throws DeviceNotAvailableException {
+ // 60 min timeout per test by default
+ runDeviceTests(device, packageName, testClassName, testMethodName, userId, testArgs,
+ 60L, TimeUnit.MINUTES);
+ }
+
+ public static void runDeviceTests(ITestDevice device, String packageName, String testClassName,
+ String testMethodName, int userId, Map<String, String> testArgs, long timeout,
+ TimeUnit unit)
+ throws DeviceNotAvailableException {
+ if (testClassName != null && testClassName.startsWith(".")) {
+ testClassName = packageName + testClassName;
+ }
+ RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(packageName,
+ "android.support.test.runner.AndroidJUnitRunner", device.getIDevice());
+ // timeout_msec is the timeout per test for instrumentation
+ testRunner.addInstrumentationArg("timeout_msec", Long.toString(unit.toMillis(timeout)));
+ if (testClassName != null && testMethodName != null) {
+ testRunner.setMethodName(testClassName, testMethodName);
+ } else if (testClassName != null) {
+ testRunner.setClassName(testClassName);
+ }
+
+ if (testArgs != null && testArgs.size() > 0) {
+ for (String name : testArgs.keySet()) {
+ final String value = testArgs.get(name);
+ testRunner.addInstrumentationArg(name, value);
+ }
+ }
+ final CollectingTestListener listener = new CollectingTestListener();
+ device.runInstrumentationTestsAsUser(testRunner, userId, listener);
+
+ final TestRunResult result = listener.getCurrentRunResults();
+ if (result.isRunFailure()) {
+ throw new AssertionError("Failed to successfully run device tests for "
+ + result.getName() + ": " + result.getRunFailureMessage());
+ }
+ if (result.getNumTests() == 0) {
+ throw new AssertionError("No tests were run on the device");
+ }
+ if (result.hasFailedTests()) {
+ // build a meaningful error message
+ StringBuilder errorBuilder = new StringBuilder("on-device tests failed:\n");
+ for (Map.Entry<TestDescription, TestResult> resultEntry :
+ result.getTestResults().entrySet()) {
+ if (!resultEntry.getValue().getStatus().equals(TestStatus.PASSED)) {
+ errorBuilder.append(resultEntry.getKey().toString());
+ errorBuilder.append(":\n");
+ errorBuilder.append(resultEntry.getValue().getStackTrace());
+ }
+ }
+ throw new AssertionError(errorBuilder.toString());
+ }
+ }
+
+ /**
+ * Prepare and return a single user relevant for testing.
+ */
+ public static int[] prepareSingleUser(ITestDevice device)
+ throws DeviceNotAvailableException {
+ return prepareMultipleUsers(device, 1);
+ }
+
+ /**
+ * Prepare and return two users relevant for testing.
+ */
+ public static int[] prepareMultipleUsers(ITestDevice device)
+ throws DeviceNotAvailableException {
+ return prepareMultipleUsers(device, 2);
+ }
+
+ /**
+ * Prepare and return multiple users relevant for testing.
+ */
+ public static int[] prepareMultipleUsers(ITestDevice device, int maxUsers)
+ throws DeviceNotAvailableException {
+ final int[] userIds = getAllUsers(device);
+ for (int i = 1; i < userIds.length; i++) {
+ if (i < maxUsers) {
+ device.startUser(userIds[i]);
+ } else {
+ device.stopUser(userIds[i]);
+ }
+ }
+ if (userIds.length > maxUsers) {
+ return Arrays.copyOf(userIds, maxUsers);
+ } else {
+ return userIds;
+ }
+ }
+
+ public static int[] getAllUsers(ITestDevice device)
+ throws DeviceNotAvailableException {
+ Integer primary = device.getPrimaryUserId();
+ if (primary == null) {
+ primary = USER_SYSTEM;
+ }
+ int[] users = new int[] { primary };
+ for (Integer user : device.listUsers()) {
+ if ((user != USER_SYSTEM) && (user != primary)) {
+ users = Arrays.copyOf(users, users.length + 1);
+ users[users.length - 1] = user;
+ }
+ }
+ return users;
+ }
+}
diff --git a/hostsidetests/compilation/AndroidTest.xml b/hostsidetests/compilation/AndroidTest.xml
index fe17ac8..d2c6f87 100644
--- a/hostsidetests/compilation/AndroidTest.xml
+++ b/hostsidetests/compilation/AndroidTest.xml
@@ -16,6 +16,8 @@
<configuration description="Config for CTS Compilation Test">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="art" />
+ <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
<test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
<option name="jar" value="CtsCompilationTestCases.jar" />
<option name="runtime-hint" value="9m45s" />
diff --git a/hostsidetests/compilation/TEST_MAPPING b/hostsidetests/compilation/TEST_MAPPING
new file mode 100644
index 0000000..cdaa108
--- /dev/null
+++ b/hostsidetests/compilation/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "presubmit": [
+ {
+ "name": "CtsCompilationTestCases"
+ }
+ ]
+}
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskHostDrivenTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskHostDrivenTest.java
index 1d6105d..b2ae2cc 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskHostDrivenTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskHostDrivenTest.java
@@ -20,6 +20,7 @@
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
+import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -29,6 +30,7 @@
import android.support.test.uiautomator.UiDevice;
import android.util.Log;
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -45,6 +47,8 @@
private static final String TAG = LockTaskHostDrivenTest.class.getName();
+ private static final int ACTIVITY_RESUMED_TIMEOUT_MILLIS = 20000; // 20 seconds
+
private static final String LOCK_TASK_ACTIVITY
= LockTaskUtilityActivityIfWhitelisted.class.getName();
@@ -53,14 +57,45 @@
private ActivityManager mActivityManager;
private DevicePolicyManager mDevicePolicyManager;
+ private volatile boolean mIsActivityResumed;
+ private final Object mActivityResumedLock = new Object();
+
+ private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+ Log.d(TAG, "onReceive: " + action);
+ if (LockTaskUtilityActivity.RESUME_ACTION.equals(action)) {
+ synchronized (mActivityResumedLock) {
+ mIsActivityResumed = true;
+ mActivityResumedLock.notify();
+ }
+ } else if (LockTaskUtilityActivity.PAUSE_ACTION.equals(action)) {
+ synchronized (mActivityResumedLock) {
+ mIsActivityResumed = false;
+ mActivityResumedLock.notify();
+ }
+ }
+ }
+ };
+
@Before
public void setUp() {
mContext = InstrumentationRegistry.getContext();
mDevicePolicyManager = mContext.getSystemService(DevicePolicyManager.class);
mActivityManager = mContext.getSystemService(ActivityManager.class);
mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+ IntentFilter filter = new IntentFilter();
+ filter.addAction(LockTaskUtilityActivity.RESUME_ACTION);
+ filter.addAction(LockTaskUtilityActivity.PAUSE_ACTION);
+ mContext.registerReceiver(mReceiver, filter);
}
+ @After
+ public void tearDown() {
+ mContext.unregisterReceiver(mReceiver);
+ }
+
@Test
public void startLockTask() throws Exception {
Log.d(TAG, "startLockTask on host-driven test (no cleanup)");
@@ -77,6 +112,13 @@
public void testLockTaskIsActiveAndCantBeInterrupted() throws Exception {
mUiDevice.waitForIdle();
+ // We need to wait until the LockTaskActivity is ready
+ // since com.android.cts.deviceowner can be killed by AMS for reason "start instr".
+ synchronized (mActivityResumedLock) {
+ if (!mIsActivityResumed) {
+ mActivityResumedLock.wait(ACTIVITY_RESUMED_TIMEOUT_MILLIS);
+ }
+ }
checkLockedActivityIsRunning();
mUiDevice.pressBack();
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/QuietModeHostsideTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/QuietModeHostsideTest.java
index 803ae3f..fd9a0d6 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/QuietModeHostsideTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/QuietModeHostsideTest.java
@@ -49,18 +49,42 @@
super.tearDown();
}
- public void testQuietMode() throws Exception {
+ public void testQuietMode_defaultForegroundLauncher() throws Exception {
if (!mHasFeature) {
return;
}
runDeviceTestsAsUser(
TEST_PACKAGE,
TEST_CLASS,
- null,
+ "testTryEnableQuietMode_defaultForegroundLauncher",
mPrimaryUserId,
createParams(mProfileId));
}
+ public void testQuietMode_notForegroundLauncher() throws Exception {
+ if (!mHasFeature) {
+ return;
+ }
+ runDeviceTestsAsUser(
+ TEST_PACKAGE,
+ TEST_CLASS,
+ "testTryEnableQuietMode_notForegroundLauncher",
+ mPrimaryUserId,
+ createParams(mProfileId));
+ }
+
+ public void testQuietMode_notDefaultLauncher() throws Exception {
+ if (!mHasFeature) {
+ return;
+ }
+ runDeviceTestsAsUser(
+ TEST_PACKAGE,
+ TEST_CLASS,
+ "testTryEnableQuietMode_notDefaultLauncher",
+ mPrimaryUserId,
+ createParams(mProfileId));
+ }
+
private void createAndStartManagedProfile() throws Exception {
mProfileId = createManagedProfile(mPrimaryUserId);
switchUser(mPrimaryUserId);
diff --git a/hostsidetests/gputools/Android.mk b/hostsidetests/gputools/Android.mk
index b2946be..7f1d242 100644
--- a/hostsidetests/gputools/Android.mk
+++ b/hostsidetests/gputools/Android.mk
@@ -20,7 +20,7 @@
LOCAL_MODULE_TAGS := tests
# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts cts_instant
LOCAL_MODULE := CtsGpuToolsHostTestCases
diff --git a/hostsidetests/gputools/AndroidTest.xml b/hostsidetests/gputools/AndroidTest.xml
index 199f5e7..53419cd 100644
--- a/hostsidetests/gputools/AndroidTest.xml
+++ b/hostsidetests/gputools/AndroidTest.xml
@@ -17,6 +17,8 @@
<configuration description="Config for CtsGpuToolsHostTestCases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="graphics" />
+ <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsGpuToolsRootlessGpuDebugApp-DEBUG.apk" />
diff --git a/hostsidetests/gputools/apps/Android.mk b/hostsidetests/gputools/apps/Android.mk
index 138b4e9..0f2760a 100644
--- a/hostsidetests/gputools/apps/Android.mk
+++ b/hostsidetests/gputools/apps/Android.mk
@@ -34,7 +34,7 @@
LOCAL_SDK_VERSION := current
# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts cts_instant
LOCAL_MULTILIB := both
@@ -45,7 +45,8 @@
--rename-manifest-package android.rootlessgpudebug.DEBUG.app \
--debug-mode
-include $(call all-makefiles-under,$(LOCAL_PATH))
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
+
include $(BUILD_CTS_SUPPORT_PACKAGE)
@@ -68,6 +69,8 @@
LOCAL_AAPT_FLAGS := \
--rename-manifest-package android.rootlessgpudebug.RELEASE.app
-include $(call all-makefiles-under,$(LOCAL_PATH))
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
include $(BUILD_CTS_SUPPORT_PACKAGE)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/gputools/apps/AndroidManifest.xml b/hostsidetests/gputools/apps/AndroidManifest.xml
index fab44c3..0e033f3 100755
--- a/hostsidetests/gputools/apps/AndroidManifest.xml
+++ b/hostsidetests/gputools/apps/AndroidManifest.xml
@@ -16,7 +16,8 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="android.rootlessgpudebug.app">>
+ package="android.rootlessgpudebug.app"
+ android:targetSandboxVersion="2">
<application android:extractNativeLibs="true" >
<activity android:name=".RootlessGpuDebugDeviceActivity" >
diff --git a/hostsidetests/gputools/layers/Android.mk b/hostsidetests/gputools/layers/Android.mk
index f91b0d3..29e832f 100644
--- a/hostsidetests/gputools/layers/Android.mk
+++ b/hostsidetests/gputools/layers/Android.mk
@@ -89,7 +89,7 @@
LOCAL_SDK_VERSION := current
# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts cts_instant
LOCAL_MULTILIB := both
@@ -101,6 +101,8 @@
libGLES_glesLayer2 \
libGLES_glesLayer3
-include $(call all-makefiles-under,$(LOCAL_PATH))
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
include $(BUILD_CTS_SUPPORT_PACKAGE)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/gputools/layers/AndroidManifest.xml b/hostsidetests/gputools/layers/AndroidManifest.xml
index 2b187ad..6b58238 100755
--- a/hostsidetests/gputools/layers/AndroidManifest.xml
+++ b/hostsidetests/gputools/layers/AndroidManifest.xml
@@ -16,7 +16,8 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="android.rootlessgpudebug.LAYERS.app">
+ package="android.rootlessgpudebug.LAYERS.app"
+ android:targetSandboxVersion="2">
<application android:extractNativeLibs="true" android:debuggable="false"
android:hasCode="false">
diff --git a/hostsidetests/gputools/src/android/gputools/cts/CtsRootlessGpuDebugHostTest.java b/hostsidetests/gputools/src/android/gputools/cts/CtsRootlessGpuDebugHostTest.java
index a3e51e1..2a0ee1e 100644
--- a/hostsidetests/gputools/src/android/gputools/cts/CtsRootlessGpuDebugHostTest.java
+++ b/hostsidetests/gputools/src/android/gputools/cts/CtsRootlessGpuDebugHostTest.java
@@ -207,6 +207,10 @@
apkIn.close();
}
+ // If this assert fires , try increasing the timeout
+ Assert.assertTrue("Log scanning did not complete before timout (" +
+ LOG_SEARCH_TIMEOUT_MS + "ms)", scanComplete);
+
return result;
}
diff --git a/hostsidetests/inputmethodservice/deviceside/provider/Android.mk b/hostsidetests/inputmethodservice/deviceside/provider/Android.mk
index 365f792..73d4b84 100644
--- a/hostsidetests/inputmethodservice/deviceside/provider/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/provider/Android.mk
@@ -36,6 +36,6 @@
LOCAL_PACKAGE_NAME := CtsInputMethodServiceEventProvider
LOCAL_SDK_VERSION := test_current
-LOCAL_MIN_SDK_VERSION := 19
+LOCAL_MIN_SDK_VERSION := 26
include $(BUILD_PACKAGE)
diff --git a/hostsidetests/inputmethodservice/deviceside/provider/AndroidManifest.xml b/hostsidetests/inputmethodservice/deviceside/provider/AndroidManifest.xml
index 9189da3..841b7c1 100755
--- a/hostsidetests/inputmethodservice/deviceside/provider/AndroidManifest.xml
+++ b/hostsidetests/inputmethodservice/deviceside/provider/AndroidManifest.xml
@@ -18,7 +18,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.inputmethodservice.cts.provider">
- <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="25" />
+ <uses-sdk android:minSdkVersion="26" android:targetSdkVersion="26" />
<application android:label="CtsInputMethodServiceEventProvider">
<provider
diff --git a/hostsidetests/shortcuts/hostside/AndroidTest.xml b/hostsidetests/shortcuts/hostside/AndroidTest.xml
index 2f1c7f0..bc6ca74 100644
--- a/hostsidetests/shortcuts/hostside/AndroidTest.xml
+++ b/hostsidetests/shortcuts/hostside/AndroidTest.xml
@@ -18,6 +18,7 @@
<option name="config-descriptor:metadata" key="component" value="framework" />
<!-- Instant apps can't access ShortcutManager -->
<option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<target_preparer class="android.cts.backup.BackupPreparer">
<option name="enable-backup-if-needed" value="true" />
<option name="select-local-transport" value="true" />
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
index 410d01f..3c0eaff 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
@@ -1112,7 +1112,7 @@
}
// Make device side test package a role holder
- String callScreenAppRole = "android.app.role.CALL_SCREENING_APP";
+ String callScreenAppRole = "android.app.role.CALL_SCREENING";
getDevice().executeShellCommand(
"cmd role add-role-holder " + callScreenAppRole + " " + DEVICE_SIDE_TEST_PACKAGE);
diff --git a/hostsidetests/theme/app/src/android/theme/app/ConditionCheck.java b/hostsidetests/theme/app/src/android/theme/app/ConditionCheck.java
new file mode 100644
index 0000000..8954a8d
--- /dev/null
+++ b/hostsidetests/theme/app/src/android/theme/app/ConditionCheck.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2019 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.theme.app;
+
+import android.content.Context;
+import android.os.Handler;
+import android.util.Pair;
+
+import java.util.ArrayList;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+/**
+ * Runnable that re-posts itself on a handler until either all of the conditions are satisfied
+ * or a retry threshold is exceeded.
+ */
+class ConditionCheck implements Runnable {
+ private static final int MAX_RETRIES = 3;
+ private static final int RETRY_DELAY = 500;
+
+ private final Handler mHandler;
+ private final Runnable mOnSuccess;
+ private final Consumer<String> mOnFailure;
+ private final ArrayList<Pair<String, Supplier<Boolean>>> mConditions = new ArrayList<>();
+
+ private ArrayList<Pair<String, Supplier<Boolean>>> mRemainingConditions = new ArrayList<>();
+ private int mRemainingRetries;
+
+ ConditionCheck(Context context, Runnable onSuccess, Consumer<String> onFailure) {
+ mHandler = new Handler(context.getMainLooper());
+ mOnSuccess = onSuccess;
+ mOnFailure = onFailure;
+ }
+
+ public ConditionCheck addCondition(String summary, Supplier<Boolean> condition) {
+ mConditions.add(new Pair<>(summary, condition));
+ return this;
+ }
+
+ public void start() {
+ mRemainingConditions = new ArrayList<>(mConditions);
+ mRemainingRetries = 0;
+
+ mHandler.removeCallbacks(this);
+ mHandler.post(this);
+ }
+
+ public void cancel() {
+ mHandler.removeCallbacks(this);
+ }
+
+ @Override
+ public void run() {
+ mRemainingConditions.removeIf(condition -> condition.second.get());
+ if (mRemainingConditions.isEmpty()) {
+ mOnSuccess.run();
+ } else if (mRemainingRetries < MAX_RETRIES) {
+ mRemainingRetries++;
+ mHandler.removeCallbacks(this);
+ mHandler.postDelayed(this, RETRY_DELAY);
+ } else {
+ final StringBuffer buffer = new StringBuffer("Failed conditions:");
+ mRemainingConditions.forEach(condition ->
+ buffer.append("\n").append(condition.first));
+ mOnFailure.accept(buffer.toString());
+ }
+ }
+}
diff --git a/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java b/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java
index 3591410..a41e426 100644
--- a/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java
+++ b/hostsidetests/theme/app/src/android/theme/app/GenerateImagesActivity.java
@@ -16,27 +16,20 @@
package android.theme.app;
-import android.Manifest.permission;
+import static android.theme.app.TestConfiguration.THEMES;
+
import android.app.Activity;
-import android.app.KeyguardManager;
-import android.content.Context;
import android.content.Intent;
-import android.content.pm.PackageManager;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
-import android.os.Handler;
import android.util.Log;
-import android.util.Pair;
import android.view.WindowManager.LayoutParams;
import java.io.File;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import java.util.function.Consumer;
-import java.util.function.Supplier;
/**
* Generates images by iterating through all themes and launching instances of
@@ -69,16 +62,9 @@
mOutputDir = setupOutputDirectory();
if (mOutputDir == null) {
finish("Failed to create output directory " + mOutputDir.getAbsolutePath(), false);
+ } else {
+ generateNextImage();
}
-
- // The activity has been created, but we don't want to start image generation until various
- // asynchronous conditions are satisfied.
- new ConditionCheck(this, () -> generateNextImage(), message -> finish(message, false))
- .addCondition("Device is unlocked",
- () -> !getSystemService(KeyguardManager.class).isDeviceLocked())
- .addCondition("Window is focused",
- () -> hasWindowFocus())
- .start();
}
private File setupOutputDirectory() {
@@ -93,63 +79,6 @@
}
/**
- * Runnable that re-posts itself on a handler until either all of the conditions are satisfied
- * or a retry threshold is exceeded.
- */
- class ConditionCheck implements Runnable {
- private static final int MAX_RETRIES = 3;
- private static final int RETRY_DELAY = 500;
-
- private final Handler mHandler;
- private final Runnable mOnSuccess;
- private final Consumer<String> mOnFailure;
- private final ArrayList<Pair<String, Supplier<Boolean>>> mConditions = new ArrayList<>();
-
- private ArrayList<Pair<String, Supplier<Boolean>>> mRemainingConditions = new ArrayList<>();
- private int mRemainingRetries;
-
- ConditionCheck(Context context, Runnable onSuccess, Consumer<String> onFailure) {
- mHandler = new Handler(context.getMainLooper());
- mOnSuccess = onSuccess;
- mOnFailure = onFailure;
- }
-
- public ConditionCheck addCondition(String summary, Supplier<Boolean> condition) {
- mConditions.add(new Pair<>(summary, condition));
- return this;
- }
-
- public void start() {
- mRemainingConditions = new ArrayList<>(mConditions);
- mRemainingRetries = 0;
-
- mHandler.removeCallbacks(this);
- mHandler.post(this);
- }
-
- public void cancel() {
- mHandler.removeCallbacks(this);
- }
-
- @Override
- public void run() {
- mRemainingConditions.removeIf(condition -> condition.second.get());
- if (mRemainingConditions.isEmpty()) {
- mOnSuccess.run();
- } else if (mRemainingRetries < MAX_RETRIES) {
- mRemainingRetries++;
- mHandler.removeCallbacks(this);
- mHandler.postDelayed(this, RETRY_DELAY);
- } else {
- final StringBuffer buffer = new StringBuffer("Failed conditions:");
- mRemainingConditions.forEach(condition ->
- buffer.append("\n").append(condition.first));
- mOnFailure.accept(buffer.toString());
- }
- }
- }
-
- /**
* @return whether the test finished successfully
*/
public boolean isFinishSuccess() {
@@ -167,8 +96,23 @@
/**
* Starts the activity to generate the next image.
*/
- private boolean generateNextImage() {
- final ThemeDeviceActivity.Theme theme = ThemeDeviceActivity.THEMES[mCurrentTheme];
+ private void generateNextImage() {
+ // Keep trying themes until one works.
+ boolean success = false;
+ while (++mCurrentTheme < THEMES.length && !success) {
+ success = launchThemeDeviceActivity();
+ }
+
+ // If we ran out of themes, we're done.
+ if (!success) {
+ compressOutput();
+
+ finish("Image generation complete!", true);
+ }
+ }
+
+ private boolean launchThemeDeviceActivity() {
+ final ThemeInfo theme = THEMES[mCurrentTheme];
if (theme.apiLevel > VERSION.SDK_INT) {
Log.v(TAG, "Skipping theme \"" + theme.name
+ "\" (requires API " + theme.apiLevel + ")");
@@ -193,18 +137,7 @@
return;
}
- // Keep trying themes until one works.
- boolean success = false;
- while (++mCurrentTheme < ThemeDeviceActivity.THEMES.length && !success) {
- success = generateNextImage();
- }
-
- // If we ran out of themes, we're done.
- if (!success) {
- compressOutput();
-
- finish("Image generation complete!", true);
- }
+ generateNextImage();
}
private void compressOutput() {
diff --git a/hostsidetests/theme/app/src/android/theme/app/LayoutInfo.java b/hostsidetests/theme/app/src/android/theme/app/LayoutInfo.java
new file mode 100644
index 0000000..e7beab7e
--- /dev/null
+++ b/hostsidetests/theme/app/src/android/theme/app/LayoutInfo.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2019 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.theme.app;
+
+import android.theme.app.modifiers.AbstractLayoutModifier;
+
+/**
+ * A class to encapsulate information about a layout.
+ */
+class LayoutInfo {
+ public final int id;
+ public final String name;
+ public final AbstractLayoutModifier modifier;
+
+ LayoutInfo(int id, String name) {
+ this(id, name, null);
+ }
+
+ LayoutInfo(int id, String name, AbstractLayoutModifier modifier) {
+ this.id = id;
+ this.name = name;
+ this.modifier = modifier;
+ }
+}
diff --git a/hostsidetests/theme/app/src/android/theme/app/LayoutModifier.java b/hostsidetests/theme/app/src/android/theme/app/LayoutModifier.java
deleted file mode 100644
index e007129..0000000
--- a/hostsidetests/theme/app/src/android/theme/app/LayoutModifier.java
+++ /dev/null
@@ -1,41 +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.theme.app;
-
-import android.view.View;
-
-/**
- * Interface used to do further setup on a view after it has been inflated.
- */
-public interface LayoutModifier {
-
- /**
- * Modifies the view before it has been added to a parent. Useful for avoiding animations in
- * response to setter calls.
- *
- * @param view the view inflated by the test activity
- */
- void modifyViewBeforeAdd(View view);
-
- /**
- * Modifies the view after it has been added to a parent. Useful for running animations in
- * response to setter calls.
- *
- * @param view the view inflated by the test activity
- */
- void modifyViewAfterAdd(View view);
-}
diff --git a/hostsidetests/theme/app/src/android/theme/app/TestConfiguration.java b/hostsidetests/theme/app/src/android/theme/app/TestConfiguration.java
new file mode 100644
index 0000000..d6c9f1c
--- /dev/null
+++ b/hostsidetests/theme/app/src/android/theme/app/TestConfiguration.java
@@ -0,0 +1,229 @@
+/*
+ * Copyright (C) 2019 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.theme.app;
+
+import android.os.Build;
+import android.theme.app.modifiers.DatePickerModifier;
+import android.theme.app.modifiers.ProgressBarModifier;
+import android.theme.app.modifiers.SearchViewModifier;
+import android.theme.app.modifiers.ViewCheckedModifier;
+import android.theme.app.modifiers.ViewPressedModifier;
+import android.theme.app.modifiers.TimePickerModifier;
+
+/**
+ * Constants defining the themes and layouts to be verified.
+ */
+public class TestConfiguration {
+ @SuppressWarnings("deprecation")
+ static final ThemeInfo[] THEMES = {
+ // Holo
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo,
+ Build.VERSION_CODES.HONEYCOMB, "holo"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Dialog,
+ Build.VERSION_CODES.HONEYCOMB, "holo_dialog"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Dialog_MinWidth,
+ Build.VERSION_CODES.HONEYCOMB, "holo_dialog_minwidth"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Dialog_NoActionBar,
+ Build.VERSION_CODES.HONEYCOMB, "holo_dialog_noactionbar"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth,
+ Build.VERSION_CODES.HONEYCOMB, "holo_dialog_noactionbar_minwidth"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_DialogWhenLarge,
+ Build.VERSION_CODES.HONEYCOMB, "holo_dialogwhenlarge"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_DialogWhenLarge_NoActionBar,
+ Build.VERSION_CODES.HONEYCOMB, "holo_dialogwhenlarge_noactionbar"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_InputMethod,
+ Build.VERSION_CODES.HONEYCOMB, "holo_inputmethod"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_NoActionBar,
+ Build.VERSION_CODES.HONEYCOMB, "holo_noactionbar"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_NoActionBar_Fullscreen,
+ Build.VERSION_CODES.HONEYCOMB, "holo_noactionbar_fullscreen"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_NoActionBar_Overscan,
+ Build.VERSION_CODES.JELLY_BEAN_MR2, "holo_noactionbar_overscan"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_NoActionBar_TranslucentDecor,
+ Build.VERSION_CODES.KITKAT, "holo_noactionbar_translucentdecor"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Panel,
+ Build.VERSION_CODES.HONEYCOMB, "holo_panel"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Wallpaper,
+ Build.VERSION_CODES.HONEYCOMB, "holo_wallpaper"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Wallpaper_NoTitleBar,
+ Build.VERSION_CODES.HONEYCOMB, "holo_wallpaper_notitlebar"),
+
+ // Holo Light
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light,
+ Build.VERSION_CODES.HONEYCOMB, "holo_light"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_DarkActionBar,
+ Build.VERSION_CODES.ICE_CREAM_SANDWICH, "holo_light_darkactionbar"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_Dialog,
+ Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_Dialog_MinWidth,
+ Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog_minwidth"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_Dialog_NoActionBar,
+ Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog_noactionbar"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth,
+ Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog_noactionbar_minwidth"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_DialogWhenLarge,
+ Build.VERSION_CODES.HONEYCOMB, "holo_light_dialogwhenlarge"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_DialogWhenLarge_NoActionBar,
+ Build.VERSION_CODES.HONEYCOMB, "holo_light_dialogwhenlarge_noactionbar"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_NoActionBar,
+ Build.VERSION_CODES.HONEYCOMB_MR2, "holo_light_noactionbar"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_NoActionBar_Fullscreen,
+ Build.VERSION_CODES.HONEYCOMB_MR2, "holo_light_noactionbar_fullscreen"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_NoActionBar_Overscan,
+ Build.VERSION_CODES.JELLY_BEAN_MR2, "holo_light_noactionbar_overscan"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_NoActionBar_TranslucentDecor,
+ Build.VERSION_CODES.KITKAT, "holo_light_noactionbar_translucentdecor"),
+ new ThemeInfo(ThemeInfo.HOLO, android.R.style.Theme_Holo_Light_Panel,
+ Build.VERSION_CODES.HONEYCOMB, "holo_light_panel"),
+
+ // Material
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material,
+ Build.VERSION_CODES.LOLLIPOP, "material"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Dialog,
+ Build.VERSION_CODES.LOLLIPOP, "material_dialog"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Dialog_Alert,
+ Build.VERSION_CODES.LOLLIPOP, "material_dialog_alert"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Dialog_MinWidth,
+ Build.VERSION_CODES.LOLLIPOP, "material_dialog_minwidth"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Dialog_NoActionBar,
+ Build.VERSION_CODES.LOLLIPOP, "material_dialog_noactionbar"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Dialog_NoActionBar_MinWidth,
+ Build.VERSION_CODES.LOLLIPOP, "material_dialog_noactionbar_minwidth"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Dialog_Presentation,
+ Build.VERSION_CODES.LOLLIPOP, "material_dialog_presentation"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_DialogWhenLarge,
+ Build.VERSION_CODES.LOLLIPOP, "material_dialogwhenlarge"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_DialogWhenLarge_NoActionBar,
+ Build.VERSION_CODES.LOLLIPOP, "material_dialogwhenlarge_noactionbar"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_InputMethod,
+ Build.VERSION_CODES.LOLLIPOP, "material_inputmethod"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_NoActionBar,
+ Build.VERSION_CODES.LOLLIPOP, "material_noactionbar"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_NoActionBar_Fullscreen,
+ Build.VERSION_CODES.LOLLIPOP, "material_noactionbar_fullscreen"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_NoActionBar_Overscan,
+ Build.VERSION_CODES.LOLLIPOP, "material_noactionbar_overscan"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_NoActionBar_TranslucentDecor,
+ Build.VERSION_CODES.LOLLIPOP, "material_noactionbar_translucentdecor"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Panel,
+ Build.VERSION_CODES.LOLLIPOP, "material_panel"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Settings,
+ Build.VERSION_CODES.LOLLIPOP, "material_settings"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Voice,
+ Build.VERSION_CODES.LOLLIPOP, "material_voice"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Wallpaper,
+ Build.VERSION_CODES.LOLLIPOP, "material_wallpaper"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Wallpaper_NoTitleBar,
+ Build.VERSION_CODES.LOLLIPOP, "material_wallpaper_notitlebar"),
+
+ // Material Light
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light,
+ Build.VERSION_CODES.LOLLIPOP, "material_light"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_DarkActionBar,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_darkactionbar"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_Dialog,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_dialog"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_Dialog_Alert,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_alert"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_Dialog_MinWidth,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_minwidth"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_Dialog_NoActionBar,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_noactionbar"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_Dialog_NoActionBar_MinWidth,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_noactionbar_minwidth"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_Dialog_Presentation,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_presentation"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_DialogWhenLarge,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_dialogwhenlarge"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_DialogWhenLarge_NoActionBar,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_dialogwhenlarge_noactionbar"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_LightStatusBar,
+ Build.VERSION_CODES.M, "material_light_lightstatusbar"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_NoActionBar,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_NoActionBar_Fullscreen,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar_fullscreen"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_NoActionBar_Overscan,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar_overscan"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_NoActionBar_TranslucentDecor,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar_translucentdecor"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_Panel,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_panel"),
+ new ThemeInfo(ThemeInfo.MATERIAL, android.R.style.Theme_Material_Light_Voice,
+ Build.VERSION_CODES.LOLLIPOP, "material_light_voice")
+ };
+
+ static final LayoutInfo[] LAYOUTS = {
+ new LayoutInfo(R.layout.button, "button"),
+ new LayoutInfo(R.layout.button, "button_pressed",
+ new ViewPressedModifier()),
+ new LayoutInfo(R.layout.checkbox, "checkbox"),
+ new LayoutInfo(R.layout.checkbox, "checkbox_checked",
+ new ViewCheckedModifier()),
+ new LayoutInfo(R.layout.chronometer, "chronometer"),
+ new LayoutInfo(R.layout.color_blue_bright, "color_blue_bright"),
+ new LayoutInfo(R.layout.color_blue_dark, "color_blue_dark"),
+ new LayoutInfo(R.layout.color_blue_light, "color_blue_light"),
+ new LayoutInfo(R.layout.color_green_dark, "color_green_dark"),
+ new LayoutInfo(R.layout.color_green_light, "color_green_light"),
+ new LayoutInfo(R.layout.color_orange_dark, "color_orange_dark"),
+ new LayoutInfo(R.layout.color_orange_light, "color_orange_light"),
+ new LayoutInfo(R.layout.color_purple, "color_purple"),
+ new LayoutInfo(R.layout.color_red_dark, "color_red_dark"),
+ new LayoutInfo(R.layout.color_red_light, "color_red_light"),
+ new LayoutInfo(R.layout.datepicker, "datepicker",
+ new DatePickerModifier()),
+ new LayoutInfo(R.layout.edittext, "edittext"),
+ new LayoutInfo(R.layout.progressbar_horizontal_0, "progressbar_horizontal_0"),
+ new LayoutInfo(R.layout.progressbar_horizontal_100, "progressbar_horizontal_100"),
+ new LayoutInfo(R.layout.progressbar_horizontal_50, "progressbar_horizontal_50"),
+ new LayoutInfo(R.layout.progressbar_large, "progressbar_large",
+ new ProgressBarModifier()),
+ new LayoutInfo(R.layout.progressbar_small, "progressbar_small",
+ new ProgressBarModifier()),
+ new LayoutInfo(R.layout.progressbar, "progressbar",
+ new ProgressBarModifier()),
+ new LayoutInfo(R.layout.radiobutton_checked, "radiobutton_checked"),
+ new LayoutInfo(R.layout.radiobutton, "radiobutton"),
+ new LayoutInfo(R.layout.radiogroup_horizontal, "radiogroup_horizontal"),
+ new LayoutInfo(R.layout.radiogroup_vertical, "radiogroup_vertical"),
+ new LayoutInfo(R.layout.ratingbar_0, "ratingbar_0"),
+ new LayoutInfo(R.layout.ratingbar_2point5, "ratingbar_2point5"),
+ new LayoutInfo(R.layout.ratingbar_5, "ratingbar_5"),
+ new LayoutInfo(R.layout.ratingbar_0, "ratingbar_0_pressed",
+ new ViewPressedModifier()),
+ new LayoutInfo(R.layout.ratingbar_2point5, "ratingbar_2point5_pressed",
+ new ViewPressedModifier()),
+ new LayoutInfo(R.layout.ratingbar_5, "ratingbar_5_pressed",
+ new ViewPressedModifier()),
+ new LayoutInfo(R.layout.searchview, "searchview_query",
+ new SearchViewModifier(SearchViewModifier.QUERY)),
+ new LayoutInfo(R.layout.searchview, "searchview_query_hint",
+ new SearchViewModifier(SearchViewModifier.QUERY_HINT)),
+ new LayoutInfo(R.layout.seekbar_0, "seekbar_0"),
+ new LayoutInfo(R.layout.seekbar_100, "seekbar_100"),
+ new LayoutInfo(R.layout.seekbar_50, "seekbar_50"),
+ new LayoutInfo(R.layout.spinner, "spinner"),
+ new LayoutInfo(R.layout.switch_button_checked, "switch_button_checked"),
+ new LayoutInfo(R.layout.switch_button, "switch_button"),
+ new LayoutInfo(R.layout.textview, "textview"),
+ new LayoutInfo(R.layout.timepicker, "timepicker",
+ new TimePickerModifier()),
+ new LayoutInfo(R.layout.togglebutton_checked, "togglebutton_checked"),
+ new LayoutInfo(R.layout.togglebutton, "togglebutton"),
+ };
+}
diff --git a/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java b/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java
index b30ffd3..9227edd 100644
--- a/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java
+++ b/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java
@@ -16,19 +16,17 @@
package android.theme.app;
+import static android.theme.app.TestConfiguration.LAYOUTS;
+import static android.theme.app.TestConfiguration.THEMES;
+
import android.animation.ValueAnimator;
import android.app.Activity;
+import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
-import android.os.Build;
import android.os.Bundle;
-import android.theme.app.modifiers.DatePickerModifier;
-import android.theme.app.modifiers.ProgressBarModifier;
-import android.theme.app.modifiers.SearchViewModifier;
-import android.theme.app.modifiers.TimePickerModifier;
-import android.theme.app.modifiers.ViewCheckedModifier;
-import android.theme.app.modifiers.ViewPressedModifier;
+import android.theme.app.modifiers.AbstractLayoutModifier;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
@@ -36,7 +34,6 @@
import android.widget.DatePicker;
import java.io.File;
-import java.lang.Override;
/**
* A activity which display various UI elements with non-modifiable themes.
@@ -53,7 +50,7 @@
*/
private static final long HOLO_CALENDAR_VIEW_ADJUSTMENT_DURATION = 540;
- private Theme mTheme;
+ private ThemeInfo mTheme;
private ReferenceViewGroup mViewGroup;
private File mOutputDir;
private int mLayoutIndex;
@@ -94,9 +91,18 @@
mViewGroup = findViewById(R.id.reference_view_group);
- getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON
- | LayoutParams.FLAG_TURN_SCREEN_ON
- | LayoutParams.FLAG_DISMISS_KEYGUARD );
+ getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
+
+ // The activity has been created, but we don't want to start image generation until various
+ // asynchronous conditions are satisfied.
+ new ConditionCheck(this, () -> setNextLayout(), message -> finish(message, false))
+ .addCondition("Device is unlocked",
+ () -> !getSystemService(KeyguardManager.class).isDeviceLocked())
+ .addCondition("Window is focused",
+ () -> hasWindowFocus())
+ .addCondition("Activity is resumed",
+ () -> mIsRunning)
+ .start();
}
@Override
@@ -104,8 +110,6 @@
super.onResume();
mIsRunning = true;
-
- setNextLayout();
}
@Override
@@ -115,8 +119,7 @@
if (!isFinishing()) {
// The activity paused for some reason, likely a system crash
// dialog. Finish it so we can move to the next theme.
- Log.w(TAG, "onPause() called without a call to finish()", new RuntimeException());
- finish();
+ Log.e(TAG, "onPause() called without a call to finish(), check system dialogs");
}
super.onPause();
@@ -125,10 +128,7 @@
@Override
protected void onDestroy() {
if (mLayoutIndex < LAYOUTS.length) {
- final Intent data = new Intent();
- data.putExtra(GenerateImagesActivity.EXTRA_REASON, "Only rendered "
- + mLayoutIndex + "/" + LAYOUTS.length + " layouts");
- setResult(RESULT_CANCELED, data);
+ finish("Only rendered " + mLayoutIndex + "/" + LAYOUTS.length + " layouts", false);
}
super.onDestroy();
@@ -139,15 +139,14 @@
*/
private void setNextLayout() {
if (mLayoutIndex >= LAYOUTS.length) {
- setResult(RESULT_OK);
- finish();
+ finish("Rendered all layouts", true);
return;
}
mViewGroup.removeAllViews();
- final Layout layout = LAYOUTS[mLayoutIndex++];
- final LayoutModifier modifier = layout.modifier;
+ final LayoutInfo layout = LAYOUTS[mLayoutIndex++];
+ final AbstractLayoutModifier modifier = layout.modifier;
final String layoutName = String.format("%s_%s", mTheme.name, layout.name);
final LayoutInflater layoutInflater = LayoutInflater.from(mViewGroup.getContext());
final View view = layoutInflater.inflate(layout.id, mViewGroup, false);
@@ -166,9 +165,9 @@
+ " (" + mLayoutIndex + "/" + LAYOUTS.length + ")");
final Runnable generateBitmapRunnable = () ->
- new BitmapTask(view, layoutName, modifier).execute();
+ new BitmapTask(view, layoutName).execute();
- if (view instanceof DatePicker && mTheme.spec == Theme.HOLO) {
+ if (view instanceof DatePicker && mTheme.spec == ThemeInfo.HOLO) {
// The Holo-styled DatePicker uses a CalendarView that has a
// non-configurable adjustment duration of 540ms.
view.postDelayed(generateBitmapRunnable, HOLO_CALENDAR_VIEW_ADJUSTMENT_DURATION);
@@ -177,13 +176,20 @@
}
}
+ private void finish(String reason, boolean success) {
+ final Intent data = new Intent();
+ data.putExtra(GenerateImagesActivity.EXTRA_REASON, reason);
+ setResult(success ? RESULT_OK : RESULT_CANCELED, data);
+
+ if (!isFinishing()) {
+ finish();
+ }
+ }
+
private class BitmapTask extends GenerateBitmapTask {
- private final LayoutModifier mLayoutModifier;
- public BitmapTask(View view, String name, LayoutModifier modifier) {
+ public BitmapTask(View view, String name) {
super(view, mOutputDir, name);
-
- mLayoutModifier = modifier;
}
@Override
@@ -191,250 +197,9 @@
if (success && mIsRunning) {
setNextLayout();
} else {
- Log.e(TAG, "Failed to render view to bitmap: " + mName + " (activity running? "
- + mIsRunning + ")");
- finish();
+ finish("Failed to render view to bitmap: " + mName + " (activity running? "
+ + mIsRunning + ")", false);
}
}
}
-
- /**
- * A class to encapsulate information about a theme.
- */
- static class Theme {
- public static final int HOLO = 0;
- public static final int MATERIAL = 1;
-
- public final int spec;
- public final int id;
- public final int apiLevel;
- public final String name;
-
- private Theme(int spec, int id, int apiLevel, String name) {
- this.spec = spec;
- this.id = id;
- this.apiLevel = apiLevel;
- this.name = name;
- }
- }
-
- // List of themes to verify.
- @SuppressWarnings("deprecation")
- static final Theme[] THEMES = {
- // Holo
- new Theme(Theme.HOLO, android.R.style.Theme_Holo,
- Build.VERSION_CODES.HONEYCOMB, "holo"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Dialog,
- Build.VERSION_CODES.HONEYCOMB, "holo_dialog"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Dialog_MinWidth,
- Build.VERSION_CODES.HONEYCOMB, "holo_dialog_minwidth"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Dialog_NoActionBar,
- Build.VERSION_CODES.HONEYCOMB, "holo_dialog_noactionbar"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth,
- Build.VERSION_CODES.HONEYCOMB, "holo_dialog_noactionbar_minwidth"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_DialogWhenLarge,
- Build.VERSION_CODES.HONEYCOMB, "holo_dialogwhenlarge"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_DialogWhenLarge_NoActionBar,
- Build.VERSION_CODES.HONEYCOMB, "holo_dialogwhenlarge_noactionbar"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_InputMethod,
- Build.VERSION_CODES.HONEYCOMB, "holo_inputmethod"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_NoActionBar,
- Build.VERSION_CODES.HONEYCOMB, "holo_noactionbar"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_NoActionBar_Fullscreen,
- Build.VERSION_CODES.HONEYCOMB, "holo_noactionbar_fullscreen"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_NoActionBar_Overscan,
- Build.VERSION_CODES.JELLY_BEAN_MR2, "holo_noactionbar_overscan"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_NoActionBar_TranslucentDecor,
- Build.VERSION_CODES.KITKAT, "holo_noactionbar_translucentdecor"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Panel,
- Build.VERSION_CODES.HONEYCOMB, "holo_panel"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Wallpaper,
- Build.VERSION_CODES.HONEYCOMB, "holo_wallpaper"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Wallpaper_NoTitleBar,
- Build.VERSION_CODES.HONEYCOMB, "holo_wallpaper_notitlebar"),
-
- // Holo Light
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light,
- Build.VERSION_CODES.HONEYCOMB, "holo_light"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_DarkActionBar,
- Build.VERSION_CODES.ICE_CREAM_SANDWICH, "holo_light_darkactionbar"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_Dialog,
- Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_Dialog_MinWidth,
- Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog_minwidth"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_Dialog_NoActionBar,
- Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog_noactionbar"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth,
- Build.VERSION_CODES.HONEYCOMB, "holo_light_dialog_noactionbar_minwidth"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_DialogWhenLarge,
- Build.VERSION_CODES.HONEYCOMB, "holo_light_dialogwhenlarge"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_DialogWhenLarge_NoActionBar,
- Build.VERSION_CODES.HONEYCOMB, "holo_light_dialogwhenlarge_noactionbar"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_NoActionBar,
- Build.VERSION_CODES.HONEYCOMB_MR2, "holo_light_noactionbar"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_NoActionBar_Fullscreen,
- Build.VERSION_CODES.HONEYCOMB_MR2, "holo_light_noactionbar_fullscreen"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_NoActionBar_Overscan,
- Build.VERSION_CODES.JELLY_BEAN_MR2, "holo_light_noactionbar_overscan"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_NoActionBar_TranslucentDecor,
- Build.VERSION_CODES.KITKAT, "holo_light_noactionbar_translucentdecor"),
- new Theme(Theme.HOLO, android.R.style.Theme_Holo_Light_Panel,
- Build.VERSION_CODES.HONEYCOMB, "holo_light_panel"),
-
- // Material
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material,
- Build.VERSION_CODES.LOLLIPOP, "material"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Dialog,
- Build.VERSION_CODES.LOLLIPOP, "material_dialog"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Dialog_Alert,
- Build.VERSION_CODES.LOLLIPOP, "material_dialog_alert"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Dialog_MinWidth,
- Build.VERSION_CODES.LOLLIPOP, "material_dialog_minwidth"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Dialog_NoActionBar,
- Build.VERSION_CODES.LOLLIPOP, "material_dialog_noactionbar"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Dialog_NoActionBar_MinWidth,
- Build.VERSION_CODES.LOLLIPOP, "material_dialog_noactionbar_minwidth"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Dialog_Presentation,
- Build.VERSION_CODES.LOLLIPOP, "material_dialog_presentation"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_DialogWhenLarge,
- Build.VERSION_CODES.LOLLIPOP, "material_dialogwhenlarge"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_DialogWhenLarge_NoActionBar,
- Build.VERSION_CODES.LOLLIPOP, "material_dialogwhenlarge_noactionbar"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_InputMethod,
- Build.VERSION_CODES.LOLLIPOP, "material_inputmethod"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_NoActionBar,
- Build.VERSION_CODES.LOLLIPOP, "material_noactionbar"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_NoActionBar_Fullscreen,
- Build.VERSION_CODES.LOLLIPOP, "material_noactionbar_fullscreen"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_NoActionBar_Overscan,
- Build.VERSION_CODES.LOLLIPOP, "material_noactionbar_overscan"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_NoActionBar_TranslucentDecor,
- Build.VERSION_CODES.LOLLIPOP, "material_noactionbar_translucentdecor"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Panel,
- Build.VERSION_CODES.LOLLIPOP, "material_panel"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Settings,
- Build.VERSION_CODES.LOLLIPOP, "material_settings"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Voice,
- Build.VERSION_CODES.LOLLIPOP, "material_voice"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Wallpaper,
- Build.VERSION_CODES.LOLLIPOP, "material_wallpaper"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Wallpaper_NoTitleBar,
- Build.VERSION_CODES.LOLLIPOP, "material_wallpaper_notitlebar"),
-
- // Material Light
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light,
- Build.VERSION_CODES.LOLLIPOP, "material_light"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_DarkActionBar,
- Build.VERSION_CODES.LOLLIPOP, "material_light_darkactionbar"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_Dialog,
- Build.VERSION_CODES.LOLLIPOP, "material_light_dialog"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_Dialog_Alert,
- Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_alert"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_Dialog_MinWidth,
- Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_minwidth"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_Dialog_NoActionBar,
- Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_noactionbar"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_Dialog_NoActionBar_MinWidth,
- Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_noactionbar_minwidth"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_Dialog_Presentation,
- Build.VERSION_CODES.LOLLIPOP, "material_light_dialog_presentation"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_DialogWhenLarge,
- Build.VERSION_CODES.LOLLIPOP, "material_light_dialogwhenlarge"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_DialogWhenLarge_NoActionBar,
- Build.VERSION_CODES.LOLLIPOP, "material_light_dialogwhenlarge_noactionbar"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_LightStatusBar,
- Build.VERSION_CODES.M, "material_light_lightstatusbar"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_NoActionBar,
- Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_NoActionBar_Fullscreen,
- Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar_fullscreen"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_NoActionBar_Overscan,
- Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar_overscan"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_NoActionBar_TranslucentDecor,
- Build.VERSION_CODES.LOLLIPOP, "material_light_noactionbar_translucentdecor"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_Panel,
- Build.VERSION_CODES.LOLLIPOP, "material_light_panel"),
- new Theme(Theme.MATERIAL, android.R.style.Theme_Material_Light_Voice,
- Build.VERSION_CODES.LOLLIPOP, "material_light_voice")
- };
-
- /**
- * A class to encapsulate information about a layout.
- */
- private static class Layout {
- public final int id;
- public final String name;
- public final LayoutModifier modifier;
-
- private Layout(int id, String name) {
- this(id, name, null);
- }
-
- private Layout(int id, String name, LayoutModifier modifier) {
- this.id = id;
- this.name = name;
- this.modifier = modifier;
- }
- }
-
- // List of layouts to verify for each theme.
- private static final Layout[] LAYOUTS = {
- new Layout(R.layout.button, "button"),
- new Layout(R.layout.button, "button_pressed",
- new ViewPressedModifier()),
- new Layout(R.layout.checkbox, "checkbox"),
- new Layout(R.layout.checkbox, "checkbox_checked",
- new ViewCheckedModifier()),
- new Layout(R.layout.chronometer, "chronometer"),
- new Layout(R.layout.color_blue_bright, "color_blue_bright"),
- new Layout(R.layout.color_blue_dark, "color_blue_dark"),
- new Layout(R.layout.color_blue_light, "color_blue_light"),
- new Layout(R.layout.color_green_dark, "color_green_dark"),
- new Layout(R.layout.color_green_light, "color_green_light"),
- new Layout(R.layout.color_orange_dark, "color_orange_dark"),
- new Layout(R.layout.color_orange_light, "color_orange_light"),
- new Layout(R.layout.color_purple, "color_purple"),
- new Layout(R.layout.color_red_dark, "color_red_dark"),
- new Layout(R.layout.color_red_light, "color_red_light"),
- new Layout(R.layout.datepicker, "datepicker",
- new DatePickerModifier()),
- new Layout(R.layout.edittext, "edittext"),
- new Layout(R.layout.progressbar_horizontal_0, "progressbar_horizontal_0"),
- new Layout(R.layout.progressbar_horizontal_100, "progressbar_horizontal_100"),
- new Layout(R.layout.progressbar_horizontal_50, "progressbar_horizontal_50"),
- new Layout(R.layout.progressbar_large, "progressbar_large",
- new ProgressBarModifier()),
- new Layout(R.layout.progressbar_small, "progressbar_small",
- new ProgressBarModifier()),
- new Layout(R.layout.progressbar, "progressbar",
- new ProgressBarModifier()),
- new Layout(R.layout.radiobutton_checked, "radiobutton_checked"),
- new Layout(R.layout.radiobutton, "radiobutton"),
- new Layout(R.layout.radiogroup_horizontal, "radiogroup_horizontal"),
- new Layout(R.layout.radiogroup_vertical, "radiogroup_vertical"),
- new Layout(R.layout.ratingbar_0, "ratingbar_0"),
- new Layout(R.layout.ratingbar_2point5, "ratingbar_2point5"),
- new Layout(R.layout.ratingbar_5, "ratingbar_5"),
- new Layout(R.layout.ratingbar_0, "ratingbar_0_pressed",
- new ViewPressedModifier()),
- new Layout(R.layout.ratingbar_2point5, "ratingbar_2point5_pressed",
- new ViewPressedModifier()),
- new Layout(R.layout.ratingbar_5, "ratingbar_5_pressed",
- new ViewPressedModifier()),
- new Layout(R.layout.searchview, "searchview_query",
- new SearchViewModifier(SearchViewModifier.QUERY)),
- new Layout(R.layout.searchview, "searchview_query_hint",
- new SearchViewModifier(SearchViewModifier.QUERY_HINT)),
- new Layout(R.layout.seekbar_0, "seekbar_0"),
- new Layout(R.layout.seekbar_100, "seekbar_100"),
- new Layout(R.layout.seekbar_50, "seekbar_50"),
- new Layout(R.layout.spinner, "spinner"),
- new Layout(R.layout.switch_button_checked, "switch_button_checked"),
- new Layout(R.layout.switch_button, "switch_button"),
- new Layout(R.layout.textview, "textview"),
- new Layout(R.layout.timepicker, "timepicker",
- new TimePickerModifier()),
- new Layout(R.layout.togglebutton_checked, "togglebutton_checked"),
- new Layout(R.layout.togglebutton, "togglebutton"),
- };
}
diff --git a/hostsidetests/theme/app/src/android/theme/app/ThemeInfo.java b/hostsidetests/theme/app/src/android/theme/app/ThemeInfo.java
new file mode 100644
index 0000000..6a3d4aa
--- /dev/null
+++ b/hostsidetests/theme/app/src/android/theme/app/ThemeInfo.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2019 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.theme.app;
+
+/**
+ * A class to encapsulate information about a theme.
+ */
+class ThemeInfo {
+ public static final int HOLO = 0;
+ public static final int MATERIAL = 1;
+
+ public final int spec;
+ public final int id;
+ public final int apiLevel;
+ public final String name;
+
+ ThemeInfo(int spec, int id, int apiLevel, String name) {
+ this.spec = spec;
+ this.id = id;
+ this.apiLevel = apiLevel;
+ this.name = name;
+ }
+}
diff --git a/hostsidetests/theme/app/src/android/theme/app/modifiers/AbstractLayoutModifier.java b/hostsidetests/theme/app/src/android/theme/app/modifiers/AbstractLayoutModifier.java
index e9dca7a..2c71cc6 100644
--- a/hostsidetests/theme/app/src/android/theme/app/modifiers/AbstractLayoutModifier.java
+++ b/hostsidetests/theme/app/src/android/theme/app/modifiers/AbstractLayoutModifier.java
@@ -16,19 +16,30 @@
package android.theme.app.modifiers;
-import android.theme.app.LayoutModifier;
import android.view.View;
/**
- * {@link LayoutModifier} that does nothing.
+ * {@link AbstractLayoutModifier} that does nothing.
*/
-abstract class AbstractLayoutModifier implements LayoutModifier {
+public abstract class AbstractLayoutModifier {
- @Override
+ /**
+ * Modifies the view before it has been added to a parent. Useful for avoiding animations in
+ * response to setter calls.
+ *
+ * @param view the view inflated by the test activity
+ */
public void modifyViewBeforeAdd(View view) {
+
}
- @Override
+ /**
+ * Modifies the view after it has been added to a parent. Useful for running animations in
+ * response to setter calls.
+ *
+ * @param view the view inflated by the test activity
+ */
public void modifyViewAfterAdd(View view) {
+
}
}
diff --git a/hostsidetests/theme/app/src/android/theme/app/modifiers/DatePickerModifier.java b/hostsidetests/theme/app/src/android/theme/app/modifiers/DatePickerModifier.java
index f155fcb..58ddb43 100644
--- a/hostsidetests/theme/app/src/android/theme/app/modifiers/DatePickerModifier.java
+++ b/hostsidetests/theme/app/src/android/theme/app/modifiers/DatePickerModifier.java
@@ -16,12 +16,11 @@
package android.theme.app.modifiers;
-import android.theme.app.LayoutModifier;
import android.view.View;
import android.widget.DatePicker;
/**
- * {@link LayoutModifier} that sets a precise date on a {@link DatePicker}.
+ * {@link AbstractLayoutModifier} that sets a precise date on a {@link DatePicker}.
*/
public class DatePickerModifier extends AbstractLayoutModifier {
diff --git a/hostsidetests/theme/app/src/android/theme/app/modifiers/ProgressBarModifier.java b/hostsidetests/theme/app/src/android/theme/app/modifiers/ProgressBarModifier.java
index dcd8c89..325751f 100644
--- a/hostsidetests/theme/app/src/android/theme/app/modifiers/ProgressBarModifier.java
+++ b/hostsidetests/theme/app/src/android/theme/app/modifiers/ProgressBarModifier.java
@@ -16,7 +16,6 @@
package android.theme.app.modifiers;
-import android.animation.ValueAnimator;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.ProgressBar;
diff --git a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
index 199830f..7a931a4 100644
--- a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
+++ b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
@@ -159,7 +159,7 @@
return;
}
- assertTrue("Aborted image generation", generateDeviceImages());
+ assertTrue("Aborted image generation, see device log for details", generateDeviceImages());
// Pull ZIP file from remote device.
final File localZip = File.createTempFile("generated", ".zip");
diff --git a/hostsidetests/webkit/AndroidTest.xml b/hostsidetests/webkit/AndroidTest.xml
index 927d28f..54a6c9a 100644
--- a/hostsidetests/webkit/AndroidTest.xml
+++ b/hostsidetests/webkit/AndroidTest.xml
@@ -17,6 +17,7 @@
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="webview" />
<option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsWebViewStartupApp.apk" />
diff --git a/tests/acceleration/Android.mk b/tests/acceleration/Android.mk
index cef4379..8ae5ddc 100644
--- a/tests/acceleration/Android.mk
+++ b/tests/acceleration/Android.mk
@@ -32,7 +32,7 @@
LOCAL_SRC_FILES := $(call all-java-files-under, src)
# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
LOCAL_PACKAGE_NAME := CtsAccelerationTestCases
diff --git a/tests/acceleration/AndroidManifest.xml b/tests/acceleration/AndroidManifest.xml
index 1a21554..27ff97a 100644
--- a/tests/acceleration/AndroidManifest.xml
+++ b/tests/acceleration/AndroidManifest.xml
@@ -15,7 +15,8 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="android.acceleration.cts">
+ package="android.acceleration.cts"
+ android:targetSandboxVersion="2">
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
diff --git a/tests/acceleration/AndroidTest.xml b/tests/acceleration/AndroidTest.xml
index b28f845..68eb78f 100644
--- a/tests/acceleration/AndroidTest.xml
+++ b/tests/acceleration/AndroidTest.xml
@@ -16,6 +16,8 @@
<configuration description="Config for CTS Acceleration test cases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="location" />
+ <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsAccelerationTestCases.apk" />
diff --git a/tests/accessibilityservice/AndroidManifest.xml b/tests/accessibilityservice/AndroidManifest.xml
index 029dc51..8fbc3a2 100644
--- a/tests/accessibilityservice/AndroidManifest.xml
+++ b/tests/accessibilityservice/AndroidManifest.xml
@@ -81,7 +81,7 @@
</service>
<service
- android:name=".AccessibilityGestureDetectorTest$StubService"
+ android:name=".GestureDetectionStubAccessibilityService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
index 27ec20b..b1a4352 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
@@ -47,29 +47,23 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import java.util.ArrayList;
-
-/**
- * Verify that motion events are recognized as accessibility gestures.
- */
+/** Verify that motion events are recognized as accessibility gestures. */
@RunWith(AndroidJUnit4.class)
public class AccessibilityGestureDetectorTest {
// Constants
- static final float GESTURE_LENGTH_INCHES = 1.0f;
- static final long STROKE_MS = 400;
- static final long GESTURE_DISPATCH_TIMEOUT_MS = 3000;
- static final long GESTURE_RECOGNIZE_TIMEOUT_MS = 3000;
- static final long EVENT_DISPATCH_TIMEOUT_MS = 3000;
- static final long EVENT_RECOGNIZE_TIMEOUT_MS = 3000;
+ private static final float GESTURE_LENGTH_INCHES = 1.0f;
+ private static final long STROKE_MS = 400;
+ private static final long GESTURE_DISPATCH_TIMEOUT_MS = 3000;
+ private static final long EVENT_DISPATCH_TIMEOUT_MS = 3000;
- // Member variables
- StubService mService; // Test AccessibilityService that collects gestures.
+ // Test AccessibilityService that collects gestures.
+ GestureDetectionStubAccessibilityService mService;
boolean mHasTouchScreen;
boolean mScreenBigEnough;
- int mStrokeLenPxX; // Gesture stroke size, in pixels
+ int mStrokeLenPxX; // Gesture stroke size, in pixels
int mStrokeLenPxY;
- Point mCenter; // Center of screen. Gestures all start from this point.
+ Point mCenter; // Center of screen. Gestures all start from this point.
PointF mTapLocation;
@Mock AccessibilityService.GestureResultCallback mGestureDispatchCallback;
@@ -94,16 +88,14 @@
windowManager.getDefaultDisplay().getRealMetrics(metrics);
mCenter = new Point((int) metrics.widthPixels / 2, (int) metrics.heightPixels / 2);
mTapLocation = new PointF(mCenter);
- mStrokeLenPxX = (int)(GESTURE_LENGTH_INCHES * metrics.xdpi);
- mStrokeLenPxY = (int)(GESTURE_LENGTH_INCHES * metrics.ydpi);
- mScreenBigEnough = (metrics.widthPixels / (2 * metrics.xdpi) > GESTURE_LENGTH_INCHES)
- && (metrics.heightPixels / (2 * metrics.ydpi) > GESTURE_LENGTH_INCHES);
+ mStrokeLenPxX = (int) (GESTURE_LENGTH_INCHES * metrics.xdpi);
+ mStrokeLenPxY = (int) (GESTURE_LENGTH_INCHES * metrics.ydpi);
+ mScreenBigEnough = (metrics.widthPixels / (2 * metrics.xdpi) > GESTURE_LENGTH_INCHES);
if (!mScreenBigEnough) {
return;
}
-
// Start stub accessibility service.
- mService = StubService.enableSelf(instrumentation);
+ mService = GestureDetectionStubAccessibilityService.enableSelf(instrumentation);
}
@After
@@ -165,7 +157,7 @@
long pathDurationMs = numPathSegments * STROKE_MS;
GestureDescription gesture = new GestureDescription.Builder()
.addStroke(new StrokeDescription(
- linePath(mCenter, delta1, delta2), 0, pathDurationMs, false))
+ linePath(mCenter, delta1, delta2), 0, pathDurationMs, false))
.build();
// Dispatch gesture motions.
@@ -174,9 +166,8 @@
// sendPointerSync() injects events.
mService.clearGestures();
mService.runOnServiceSync(() ->
- mService.dispatchGesture(gesture, mGestureDispatchCallback, null));
- verify(mGestureDispatchCallback,
- timeout(GESTURE_DISPATCH_TIMEOUT_MS).atLeastOnce())
+ mService.dispatchGesture(gesture, mGestureDispatchCallback, null));
+ verify(mGestureDispatchCallback, timeout(GESTURE_DISPATCH_TIMEOUT_MS).atLeastOnce())
.onCompleted(any());
// Wait for gesture recognizer, and check recognized gesture.
@@ -225,15 +216,14 @@
/** Test touch for accessibility events */
private void assertEventAfterGesture(GestureDescription gesture, int... events) {
mService.clearEvents();
- mService.runOnServiceSync(() ->
- mService.dispatchGesture(gesture, mGestureDispatchCallback, null));
- verify(mGestureDispatchCallback,
- timeout(EVENT_DISPATCH_TIMEOUT_MS).atLeastOnce())
+ mService.runOnServiceSync(
+ () -> mService.dispatchGesture(gesture, mGestureDispatchCallback, null));
+ verify(mGestureDispatchCallback, timeout(EVENT_DISPATCH_TIMEOUT_MS).atLeastOnce())
.onCompleted(any());
mService.waitUntilEvent(events.length);
assertEquals(events.length, mService.getEventsSize());
- for (int i = 0 ; i < events.length ; i++) {
+ for (int i = 0; i < events.length; i++) {
assertEquals(events[i], mService.getEvent(i));
}
}
@@ -270,107 +260,4 @@
builder.addStroke(tap2);
return builder.build();
}
-
- /** Acessibility service stub, which will collect recognized gestures. */
- public static class StubService extends InstrumentedAccessibilityService {
- private final Object mLock = new Object();
- private ArrayList<Integer> mCollectedGestures = new ArrayList();
- private ArrayList<Integer> mCollectedEvents = new ArrayList();
-
- public static StubService enableSelf(Instrumentation instrumentation) {
- return InstrumentedAccessibilityService.enableService(
- instrumentation, StubService.class);
- }
-
- @Override
- protected boolean onGesture(int gestureId) {
- synchronized (mCollectedGestures) {
- mCollectedGestures.add(gestureId);
- mCollectedGestures.notifyAll(); // Stop waiting for gesture.
- }
- return true;
- }
-
- public void clearGestures() {
- synchronized (mCollectedGestures) {
- mCollectedGestures.clear();
- }
- }
-
- public int getGesturesSize() {
- synchronized (mCollectedGestures) {
- return mCollectedGestures.size();
- }
- }
-
- public int getGesture(int index) {
- synchronized (mCollectedGestures) {
- return mCollectedGestures.get(index);
- }
- }
-
- /** Wait for onGesture() to collect next gesture. */
- public void waitUntilGesture() {
- synchronized (mCollectedGestures) {
- if (mCollectedGestures.size() > 0) {
- return;
- }
- try {
- mCollectedGestures.wait(GESTURE_RECOGNIZE_TIMEOUT_MS);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- @Override
- public void onAccessibilityEvent(AccessibilityEvent event) {
- synchronized (mLock) {
- switch (event.getEventType()) {
- case AccessibilityEvent.TYPE_TOUCH_INTERACTION_END:
- mCollectedEvents.add(event.getEventType());
- mLock.notifyAll();
- break;
- case AccessibilityEvent.TYPE_TOUCH_INTERACTION_START:
- case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START:
- case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END:
- mCollectedEvents.add(event.getEventType());
- }
- }
- super.onAccessibilityEvent(event);
- }
-
- public void clearEvents() {
- synchronized (mLock) {
- mCollectedEvents.clear();
- }
- }
-
- public int getEventsSize() {
- synchronized (mLock) {
- return mCollectedEvents.size();
- }
- }
-
- public int getEvent(int index) {
- synchronized (mLock) {
- return mCollectedEvents.get(index);
- }
- }
-
- /** Wait for onAccessibilityEvent() to collect next gesture. */
- public void waitUntilEvent(int count) {
- synchronized (mLock) {
- if (mCollectedEvents.size() >= count) {
- return;
- }
- try {
- mLock.wait(EVENT_RECOGNIZE_TIMEOUT_MS);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
- }
-
}
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/GestureDetectionStubAccessibilityService.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/GestureDetectionStubAccessibilityService.java
new file mode 100644
index 0000000..63601cd
--- /dev/null
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/GestureDetectionStubAccessibilityService.java
@@ -0,0 +1,125 @@
+/**
+ * Copyright (C) 2019 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.accessibilityservice.cts;
+
+import android.app.Instrumentation;
+import android.view.accessibility.AccessibilityEvent;
+import java.util.ArrayList;
+
+/** Accessibility service stub, which will collect recognized gestures. */
+public class GestureDetectionStubAccessibilityService extends InstrumentedAccessibilityService {
+ private static final long GESTURE_RECOGNIZE_TIMEOUT_MS = 3000;
+ private static final long EVENT_RECOGNIZE_TIMEOUT_MS = 3000;
+ // Member variables
+ private final Object mLock = new Object();
+ private ArrayList<Integer> mCollectedGestures = new ArrayList();
+ private ArrayList<Integer> mCollectedEvents = new ArrayList();
+
+ public static GestureDetectionStubAccessibilityService enableSelf(
+ Instrumentation instrumentation) {
+ return InstrumentedAccessibilityService.enableService(
+ instrumentation, GestureDetectionStubAccessibilityService.class);
+ }
+
+ @Override
+ protected boolean onGesture(int gestureId) {
+ synchronized (mCollectedGestures) {
+ mCollectedGestures.add(gestureId);
+ mCollectedGestures.notifyAll(); // Stop waiting for gesture.
+ }
+ return true;
+ }
+
+ public void clearGestures() {
+ synchronized (mCollectedGestures) {
+ mCollectedGestures.clear();
+ }
+ }
+
+ public int getGesturesSize() {
+ synchronized (mCollectedGestures) {
+ return mCollectedGestures.size();
+ }
+ }
+
+ public int getGesture(int index) {
+ synchronized (mCollectedGestures) {
+ return mCollectedGestures.get(index);
+ }
+ }
+
+ /** Wait for onGesture() to collect next gesture. */
+ public void waitUntilGesture() {
+ synchronized (mCollectedGestures) {
+ if (mCollectedGestures.size() > 0) {
+ return;
+ }
+ try {
+ mCollectedGestures.wait(GESTURE_RECOGNIZE_TIMEOUT_MS);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ @Override
+ public void onAccessibilityEvent(AccessibilityEvent event) {
+ synchronized (mLock) {
+ switch (event.getEventType()) {
+ case AccessibilityEvent.TYPE_TOUCH_INTERACTION_END:
+ mCollectedEvents.add(event.getEventType());
+ mLock.notifyAll();
+ break;
+ case AccessibilityEvent.TYPE_TOUCH_INTERACTION_START:
+ case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START:
+ case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END:
+ mCollectedEvents.add(event.getEventType());
+ }
+ }
+ super.onAccessibilityEvent(event);
+ }
+
+ public void clearEvents() {
+ synchronized (mLock) {
+ mCollectedEvents.clear();
+ }
+ }
+
+ public int getEventsSize() {
+ synchronized (mLock) {
+ return mCollectedEvents.size();
+ }
+ }
+
+ public int getEvent(int index) {
+ synchronized (mLock) {
+ return mCollectedEvents.get(index);
+ }
+ }
+
+ /** Wait for onAccessibilityEvent() to collect next gesture. */
+ public void waitUntilEvent(int count) {
+ synchronized (mLock) {
+ if (mCollectedEvents.size() >= count) {
+ return;
+ }
+ try {
+ mLock.wait(EVENT_RECOGNIZE_TIMEOUT_MS);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+}
diff --git a/tests/app/src/android/app/cts/SystemFeaturesTest.java b/tests/app/src/android/app/cts/SystemFeaturesTest.java
index 3109a0e..94af896 100644
--- a/tests/app/src/android/app/cts/SystemFeaturesTest.java
+++ b/tests/app/src/android/app/cts/SystemFeaturesTest.java
@@ -188,7 +188,20 @@
assertFeature(manualPostProcessing,
PackageManager.FEATURE_CAMERA_CAPABILITY_MANUAL_POST_PROCESSING);
assertFeature(raw, PackageManager.FEATURE_CAMERA_CAPABILITY_RAW);
- assertFeature(motionTracking, PackageManager.FEATURE_CAMERA_AR);
+ if (!motionTracking) {
+ // FEATURE_CAMERA_AR requires the presence of
+ // CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MOTION_TRACKING but
+ // MOTION_TRACKING does not require the presence of FEATURE_CAMERA_AR
+ //
+ // Logic table:
+ // AR= F T
+ // MT=F Y N
+ // =T Y Y
+ //
+ // So only check the one disallowed condition: No motion tracking and FEATURE_CAMERA_AR is
+ // available
+ assertNotAvailable(PackageManager.FEATURE_CAMERA_AR);
+ }
}
private void checkFrontCamera() {
diff --git a/tests/autofillservice/AndroidManifest.xml b/tests/autofillservice/AndroidManifest.xml
index 5955274..eee73f5 100644
--- a/tests/autofillservice/AndroidManifest.xml
+++ b/tests/autofillservice/AndroidManifest.xml
@@ -27,7 +27,8 @@
<uses-library android:name="android.test.runner" />
- <activity android:name=".LoginActivity" >
+ <activity android:name=".LoginActivity"
+ android:screenOrientation="portrait">
<intent-filter>
<!-- This intent filter is not really needed by CTS, but it makes easier to launch
this app during CTS development... -->
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java b/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java
index be2625e..6997453 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java
@@ -19,6 +19,7 @@
import static android.autofillservice.cts.Helper.getContext;
import static android.autofillservice.cts.InstrumentedAutoFillService.SERVICE_NAME;
import static android.content.Context.CLIPBOARD_SERVICE;
+import static android.provider.Settings.Global.AUTOFILL_SMART_SUGGESTION_EMULATION_FLAGS;
import static com.android.compatibility.common.util.ShellUtils.runShellCommand;
@@ -38,7 +39,9 @@
import com.android.compatibility.common.util.RequiredFeatureRule;
import com.android.compatibility.common.util.RetryRule;
import com.android.compatibility.common.util.SafeCleanerRule;
+import com.android.compatibility.common.util.SettingsStateChangerRule;
import com.android.compatibility.common.util.SettingsStateKeeperRule;
+import com.android.compatibility.common.util.SettingsUtils;
import com.android.compatibility.common.util.TestNameUtils;
import org.junit.Before;
@@ -202,6 +205,10 @@
// mRetryRule should be closest to the main test as possible
.around(mRetryRule)
//
+ // Augmented Autofill should be disabled by default
+ .around(new SettingsStateChangerRule(sContext, SettingsUtils.NAMESPACE_GLOBAL,
+ AUTOFILL_SMART_SUGGESTION_EMULATION_FLAGS,
+ Integer.toString(getSmartSuggestionMode())))
//
// Finally, let subclasses add their own rules (like ActivityTestRule)
.around(getMainTestRule());
@@ -217,6 +224,10 @@
mUiBot.reset();
}
+ protected int getSmartSuggestionMode() {
+ return 0;
+ }
+
/**
* Gets how many times a test should be retried.
*
diff --git a/tests/autofillservice/src/android/autofillservice/cts/augmented/AugmentedAutofillAutoActivityLaunchTestCase.java b/tests/autofillservice/src/android/autofillservice/cts/augmented/AugmentedAutofillAutoActivityLaunchTestCase.java
index f1b262f..83a938d 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/augmented/AugmentedAutofillAutoActivityLaunchTestCase.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/augmented/AugmentedAutofillAutoActivityLaunchTestCase.java
@@ -17,31 +17,21 @@
import static android.autofillservice.cts.Helper.allowOverlays;
import static android.autofillservice.cts.Helper.disallowOverlays;
-import static android.provider.Settings.Global.AUTOFILL_SMART_SUGGESTION_EMULATION_FLAGS;
import android.autofillservice.cts.AbstractAutoFillActivity;
import android.autofillservice.cts.AutoFillServiceTestCase;
import android.autofillservice.cts.augmented.CtsAugmentedAutofillService.AugmentedReplier;
import android.view.autofill.AutofillManager;
-import com.android.compatibility.common.util.SettingsStateChangerRule;
-import com.android.compatibility.common.util.SettingsUtils;
-
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
-import org.junit.ClassRule;
// Must be public because of the @ClassRule
public abstract class AugmentedAutofillAutoActivityLaunchTestCase
<A extends AbstractAutoFillActivity> extends AutoFillServiceTestCase.AutoActivityLaunch<A> {
- @ClassRule
- public static final SettingsStateChangerRule sFeatureEnabler = new SettingsStateChangerRule(
- sContext, SettingsUtils.NAMESPACE_GLOBAL, AUTOFILL_SMART_SUGGESTION_EMULATION_FLAGS,
- Integer.toString(AutofillManager.FLAG_SMART_SUGGESTION_SYSTEM));
-
protected static AugmentedReplier sAugmentedReplier;
protected AugmentedUiBot mAugmentedUiBot;
@@ -70,6 +60,11 @@
AugmentedHelper.resetAugmentedService();
}
+ @Override
+ protected int getSmartSuggestionMode() {
+ return AutofillManager.FLAG_SMART_SUGGESTION_SYSTEM;
+ }
+
protected void enableAugmentedService() {
AugmentedHelper.setAugmentedService(CtsAugmentedAutofillService.SERVICE_NAME);
}
diff --git a/tests/camera/libctscamera2jni/native-camera-jni.cpp b/tests/camera/libctscamera2jni/native-camera-jni.cpp
index 9ab8222..7dac96f 100644
--- a/tests/camera/libctscamera2jni/native-camera-jni.cpp
+++ b/tests/camera/libctscamera2jni/native-camera-jni.cpp
@@ -653,22 +653,46 @@
}
int64_t getMinFrameDurationFor(int64_t format, int64_t width, int64_t height) {
- return getDurationFor(ACAMERA_SCALER_AVAILABLE_MIN_FRAME_DURATIONS, format, width, height);
+ int32_t minFrameDurationTag = (format == AIMAGE_FORMAT_HEIC) ?
+ ACAMERA_HEIC_AVAILABLE_HEIC_MIN_FRAME_DURATIONS :
+ ACAMERA_SCALER_AVAILABLE_MIN_FRAME_DURATIONS;
+ return getDurationFor(minFrameDurationTag, format, width, height);
}
int64_t getStallDurationFor(int64_t format, int64_t width, int64_t height) {
- return getDurationFor(ACAMERA_SCALER_AVAILABLE_STALL_DURATIONS, format, width, height);
+ int32_t stallDurationTag = (format == AIMAGE_FORMAT_HEIC) ?
+ ACAMERA_HEIC_AVAILABLE_HEIC_STALL_DURATIONS :
+ ACAMERA_SCALER_AVAILABLE_STALL_DURATIONS;
+ return getDurationFor(stallDurationTag, format, width, height);
}
bool getMaxSizeForFormat(int32_t format, int32_t *width, int32_t *height) {
ACameraMetadata_const_entry entry;
- ACameraMetadata_getConstEntry(mChars,
- ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS, &entry);
+
+ int32_t streamConfigTag, streamConfigOutputTag;
+ switch (format) {
+ case AIMAGE_FORMAT_HEIC:
+ streamConfigTag = ACAMERA_HEIC_AVAILABLE_HEIC_STREAM_CONFIGURATIONS;
+ streamConfigOutputTag = ACAMERA_HEIC_AVAILABLE_HEIC_STREAM_CONFIGURATIONS_OUTPUT;
+ break;
+ case AIMAGE_FORMAT_JPEG:
+ case AIMAGE_FORMAT_Y8:
+ default:
+ streamConfigTag = ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS;
+ streamConfigOutputTag = ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT;
+ break;
+ }
+
bool supported = false;
- int32_t w = 0, h = 0;
+ camera_status_t status = ACameraMetadata_getConstEntry(mChars, streamConfigTag, &entry);
+ if (status == ACAMERA_ERROR_METADATA_NOT_FOUND) {
+ return supported;
+ }
+
+ int32_t w = 0, h = 0;
for (uint32_t i = 0; i < entry.count; i += 4) {
if (entry.data.i32[i] == format &&
- entry.data.i32[i+3] == ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT &&
+ entry.data.i32[i+3] == streamConfigOutputTag &&
entry.data.i32[i+1] * entry.data.i32[i+2] > w * h) {
w = entry.data.i32[i+1];
h = entry.data.i32[i+2];
@@ -685,11 +709,25 @@
bool isSizeSupportedForFormat(int32_t format, int32_t width, int32_t height) {
ACameraMetadata_const_entry entry;
- ACameraMetadata_getConstEntry(mChars,
- ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS, &entry);
+
+ int32_t streamConfigTag, streamConfigOutputTag;
+ switch (format) {
+ case AIMAGE_FORMAT_HEIC:
+ streamConfigTag = ACAMERA_HEIC_AVAILABLE_HEIC_STREAM_CONFIGURATIONS;
+ streamConfigOutputTag = ACAMERA_HEIC_AVAILABLE_HEIC_STREAM_CONFIGURATIONS_OUTPUT;
+ break;
+ case AIMAGE_FORMAT_JPEG:
+ case AIMAGE_FORMAT_Y8:
+ default:
+ streamConfigTag = ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS;
+ streamConfigOutputTag = ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT;
+ break;
+ }
+
+ ACameraMetadata_getConstEntry(mChars, streamConfigTag, &entry);
for (uint32_t i = 0; i < entry.count; i += 4) {
if (entry.data.i32[i] == format &&
- entry.data.i32[i+3] == ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT &&
+ entry.data.i32[i+3] == streamConfigOutputTag &&
entry.data.i32[i+1] == width &&
entry.data.i32[i+2] == height) {
return true;
@@ -702,7 +740,9 @@
if (tag != ACAMERA_SCALER_AVAILABLE_MIN_FRAME_DURATIONS &&
tag != ACAMERA_SCALER_AVAILABLE_STALL_DURATIONS &&
tag != ACAMERA_DEPTH_AVAILABLE_DEPTH_MIN_FRAME_DURATIONS &&
- tag != ACAMERA_DEPTH_AVAILABLE_DEPTH_STALL_DURATIONS) {
+ tag != ACAMERA_DEPTH_AVAILABLE_DEPTH_STALL_DURATIONS &&
+ tag != ACAMERA_HEIC_AVAILABLE_HEIC_MIN_FRAME_DURATIONS &&
+ tag != ACAMERA_HEIC_AVAILABLE_HEIC_STALL_DURATIONS) {
return -1;
}
ACameraMetadata_const_entry entry;
@@ -2860,6 +2900,7 @@
testHeight = TEST_HEIGHT;
break;
case AIMAGE_FORMAT_Y8:
+ case AIMAGE_FORMAT_HEIC:
if (!staticInfo.getMaxSizeForFormat(format, &testWidth, &testHeight)) {
// This isn't an error condition: device does't support this
// format.
@@ -2956,13 +2997,13 @@
}
int64_t minFrameDurationNs = staticInfo.getMinFrameDurationFor(
- AIMAGE_FORMAT_JPEG, TEST_WIDTH, TEST_HEIGHT);
+ format, testWidth, testHeight);
if (minFrameDurationNs < 0) {
LOG_ERROR(errorString, "Get camera %s minFrameDuration failed", cameraId);
goto cleanup;
}
- int64_t stallDurationNs = staticInfo.getStallDurationFor(
- AIMAGE_FORMAT_JPEG, TEST_WIDTH, TEST_HEIGHT);
+ int64_t stallDurationNs = (format == AIMAGE_FORMAT_Y8) ? 0 :
+ staticInfo.getStallDurationFor(format, testWidth, testHeight);
if (stallDurationNs < 0) {
LOG_ERROR(errorString, "Get camera %s stallDuration failed", cameraId);
goto cleanup;
@@ -3053,6 +3094,15 @@
extern "C" jboolean
Java_android_hardware_camera2_cts_NativeImageReaderTest_\
+testHeicNative(
+ JNIEnv* env, jclass /*clazz*/, jstring jOutPath) {
+ ALOGV("%s", __FUNCTION__);
+ return nativeImageReaderTestBase(env, jOutPath, AIMAGE_FORMAT_HEIC,
+ ImageReaderListener::validateImageCb);
+}
+
+extern "C" jboolean
+Java_android_hardware_camera2_cts_NativeImageReaderTest_\
testImageReaderCloseAcquiredImagesNative(
JNIEnv* env, jclass /*clazz*/) {
ALOGV("%s", __FUNCTION__);
diff --git a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
index b095b8a..8eff888 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
@@ -187,6 +187,7 @@
boolean isMonochromeWithY8 = arrayContains(actualCapabilities, MONOCHROME)
&& arrayContains(outputFormats, ImageFormat.Y8);
+ boolean supportHeic = arrayContains(outputFormats, ImageFormat.HEIC);
assertArrayContains(
String.format("No valid YUV_420_888 preview formats found for: ID %s",
@@ -202,6 +203,7 @@
Size[] yuvSizes = config.getOutputSizes(ImageFormat.YUV_420_888);
Size[] y8Sizes = config.getOutputSizes(ImageFormat.Y8);
Size[] jpegSizes = config.getOutputSizes(ImageFormat.JPEG);
+ Size[] heicSizes = config.getOutputSizes(ImageFormat.HEIC);
Size[] privateSizes = config.getOutputSizes(ImageFormat.PRIVATE);
CameraTestUtils.assertArrayNotEmpty(yuvSizes,
@@ -224,6 +226,12 @@
"Required FULLHD size not found for format %x for: ID %s",
ImageFormat.JPEG, mIds[counter]), jpegSizes,
new Size[] {FULLHD, FULLHD_ALT});
+ if (supportHeic) {
+ assertArrayContainsAnyOf(String.format(
+ "Required FULLHD size not found for format %x for: ID %s",
+ ImageFormat.HEIC, mIds[counter]), heicSizes,
+ new Size[] {FULLHD, FULLHD_ALT});
+ }
}
if (activeArraySize.getWidth() >= HD.getWidth() &&
@@ -231,6 +239,11 @@
assertArrayContains(String.format(
"Required HD size not found for format %x for: ID %s",
ImageFormat.JPEG, mIds[counter]), jpegSizes, HD);
+ if (supportHeic) {
+ assertArrayContains(String.format(
+ "Required HD size not found for format %x for: ID %s",
+ ImageFormat.HEIC, mIds[counter]), heicSizes, HD);
+ }
}
if (activeArraySize.getWidth() >= VGA.getWidth() &&
@@ -238,6 +251,11 @@
assertArrayContains(String.format(
"Required VGA size not found for format %x for: ID %s",
ImageFormat.JPEG, mIds[counter]), jpegSizes, VGA);
+ if (supportHeic) {
+ assertArrayContains(String.format(
+ "Required VGA size not found for format %x for: ID %s",
+ ImageFormat.HEIC, mIds[counter]), heicSizes, VGA);
+ }
}
if (activeArraySize.getWidth() >= QVGA.getWidth() &&
@@ -245,6 +263,12 @@
assertArrayContains(String.format(
"Required QVGA size not found for format %x for: ID %s",
ImageFormat.JPEG, mIds[counter]), jpegSizes, QVGA);
+ if (supportHeic) {
+ assertArrayContains(String.format(
+ "Required QVGA size not found for format %x for: ID %s",
+ ImageFormat.HEIC, mIds[counter]), heicSizes, QVGA);
+ }
+
}
ArrayList<Size> jpegSizesList = new ArrayList<>(Arrays.asList(jpegSizes));
@@ -1363,6 +1387,8 @@
CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE);
Rect activeArray = c.get(
CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
+ float jpegAspectRatioThreshold = .01f;
+ boolean jpegSizeMatch = false;
// Verify pre-correction array encloses active array
mCollector.expectTrue("preCorrectionArray [" + precorrectionArray.left + ", " +
@@ -1392,6 +1418,7 @@
hasDepth16);
if (hasDepth16) {
Size[] depthSizes = configs.getOutputSizes(ImageFormat.DEPTH16);
+ Size[] jpegSizes = configs.getOutputSizes(ImageFormat.JPEG);
mCollector.expectTrue("Supports DEPTH_OUTPUT but no sizes for DEPTH16 supported!",
depthSizes != null && depthSizes.length > 0);
if (depthSizes != null) {
@@ -1408,6 +1435,24 @@
mCollector.expectTrue("Non-negative stall duration for depth size "
+ depthSize + " expected, got " + stallDuration,
stallDuration >= 0);
+ if ((jpegSizes != null) && (!jpegSizeMatch)) {
+ for (Size jpegSize : jpegSizes) {
+ if (jpegSize.equals(depthSize)) {
+ jpegSizeMatch = true;
+ break;
+ } else {
+ float depthAR = (float) depthSize.getWidth() /
+ (float) depthSize.getHeight();
+ float jpegAR = (float) jpegSize.getWidth() /
+ (float) jpegSize.getHeight();
+ if (Math.abs(depthAR - jpegAR) <=
+ jpegAspectRatioThreshold) {
+ jpegSizeMatch = true;
+ break;
+ }
+ }
+ }
+ }
}
}
}
@@ -1446,6 +1491,8 @@
mCollector.expectTrue("Supports DEPTH_JPEG " +
"but no sizes for DEPTH_JPEG supported!",
depthJpegSizes != null && depthJpegSizes.length > 0);
+ mCollector.expectTrue("Supports DEPTH_JPEG but there are no JPEG sizes with" +
+ " matching DEPTH16 aspect ratio", jpegSizeMatch);
if (depthJpegSizes != null) {
for (Size depthJpegSize : depthJpegSizes) {
mCollector.expectTrue("All depth jpeg sizes must be nonzero",
@@ -1462,6 +1509,11 @@
stallDuration >= 0);
}
}
+ } else {
+ boolean canSupportDynamicDepth = jpegSizeMatch && !depthIsExclusive;
+ mCollector.expectTrue("Device must support DEPTH_JPEG, please check whether " +
+ "library libdepthphoto.so is part of the device PRODUCT_PACKAGES",
+ !canSupportDynamicDepth);
}
diff --git a/tests/camera/src/android/hardware/camera2/cts/FastBasicsTest.java b/tests/camera/src/android/hardware/camera2/cts/FastBasicsTest.java
index af6e5e0..0716c24 100644
--- a/tests/camera/src/android/hardware/camera2/cts/FastBasicsTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/FastBasicsTest.java
@@ -91,7 +91,7 @@
SimpleImageReaderListener imageListener = new SimpleImageReaderListener();
prepareStillCaptureAndStartPreview(previewRequest, stillCaptureRequest,
- previewSize, stillSize, resultListener, imageListener);
+ previewSize, stillSize, resultListener, imageListener, false /*isHeic*/);
CaptureResult result = resultListener.getCaptureResult(WAIT_FOR_FRAMES_TIMEOUT_MS);
diff --git a/tests/camera/src/android/hardware/camera2/cts/ImageReaderTest.java b/tests/camera/src/android/hardware/camera2/cts/ImageReaderTest.java
index e275aa4..b8cf221 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ImageReaderTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ImageReaderTest.java
@@ -204,6 +204,17 @@
}
}
+ public void testHeic() throws Exception {
+ for (String id : mCameraIds) {
+ try {
+ Log.v(TAG, "Testing heic capture for Camera " + id);
+ openDevice(id);
+ bufferFormatTestByCamera(ImageFormat.HEIC, /*repeating*/false);
+ } finally {
+ closeDevice(id);
+ }
+ }
+ }
public void testRepeatingJpeg() throws Exception {
for (String id : mCameraIds) {
@@ -243,6 +254,18 @@
}
}
+ public void testRepeatingHeic() throws Exception {
+ for (String id : mCameraIds) {
+ try {
+ Log.v(TAG, "Testing repeating heic capture for Camera " + id);
+ openDevice(id);
+ bufferFormatTestByCamera(ImageFormat.HEIC, /*repeating*/true);
+ } finally {
+ closeDevice(id);
+ }
+ }
+ }
+
public void testLongProcessingRepeatingRaw() throws Exception {
for (String id : mCameraIds) {
try {
diff --git a/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java b/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java
index 4eee734..ce5f946 100644
--- a/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java
@@ -43,6 +43,11 @@
testY8Native(mDebugFileNameBase));
}
+ public void testHeic() {
+ assertTrue("testHeic fail, see log for details",
+ testHeicNative(mDebugFileNameBase));
+ }
+
public void testImageReaderCloseAcquiredImages() {
assertTrue("testImageReaderClose fail, see log for details",
testImageReaderCloseAcquiredImagesNative());
@@ -50,5 +55,6 @@
private static native boolean testJpegNative(String filePath);
private static native boolean testY8Native(String filePath);
+ private static native boolean testHeicNative(String filePath);
private static native boolean testImageReaderCloseAcquiredImagesNative();
}
diff --git a/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java b/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
index 0fa1741..fbb8cce 100644
--- a/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
@@ -363,7 +363,8 @@
readers = prepareStillCaptureAndStartPreview(previewBuilder, captureBuilder,
mOrderedPreviewSizes.get(0), imageSizes, formats,
- previewResultListener, NUM_MAX_IMAGES, imageListeners);
+ previewResultListener, NUM_MAX_IMAGES, imageListeners,
+ false /*isHeic*/);
if (addPreviewDelay) {
Thread.sleep(500);
@@ -1141,11 +1142,13 @@
* @param resultListener Capture result listener
* @param maxNumImages The max number of images set to the image reader
* @param imageListeners The single capture capture image listeners
+ * @param isHeic Capture HEIC image if true, JPEG image if false
*/
private ImageReader[] prepareStillCaptureAndStartPreview(
CaptureRequest.Builder previewRequest, CaptureRequest.Builder stillRequest,
Size previewSz, Size[] captureSizes, int[] formats, CaptureCallback resultListener,
- int maxNumImages, ImageReader.OnImageAvailableListener[] imageListeners)
+ int maxNumImages, ImageReader.OnImageAvailableListener[] imageListeners,
+ boolean isHeic)
throws Exception {
if ((captureSizes == null) || (formats == null) || (imageListeners == null) &&
diff --git a/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java
index 8fa1077..1420078 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ReprocessCaptureTest.java
@@ -116,6 +116,24 @@
}
/**
+ * Test YUV_420_888 -> HEIC with maximal supported sizes
+ */
+ @Test
+ public void testBasicYuvToHeicReprocessing() throws Exception {
+ for (String id : mCameraIds) {
+ if (!isYuvReprocessSupported(id)) {
+ continue;
+ }
+ if (!mAllStaticInfo.get(id).isHeicSupported()) {
+ continue;
+ }
+
+ // YUV_420_888 -> HEIC must be supported.
+ testBasicReprocessing(id, ImageFormat.YUV_420_888, ImageFormat.HEIC);
+ }
+ }
+
+ /**
* Test OPAQUE -> YUV_420_888 with maximal supported sizes
*/
@Test
@@ -146,6 +164,24 @@
}
/**
+ * Test OPAQUE -> HEIC with maximal supported sizes
+ */
+ @Test
+ public void testBasicOpaqueToHeicReprocessing() throws Exception {
+ for (String id : mCameraIds) {
+ if (!isOpaqueReprocessSupported(id)) {
+ continue;
+ }
+ if (!mAllStaticInfo.get(id).isHeicSupported()) {
+ continue;
+ }
+
+ // OPAQUE -> HEIC must be supported.
+ testBasicReprocessing(id, ImageFormat.PRIVATE, ImageFormat.HEIC);
+ }
+ }
+
+ /**
* Test all supported size and format combinations.
*/
@Test(timeout=60*60*1000) // timeout = 60 mins for long running tests
@@ -978,7 +1014,7 @@
Image image = getReprocessOutputImageReaderListener().getImage(CAPTURE_TIMEOUT_MS);
verifyJpegKeys(image, reprocessResults[i], reprocessOutputSize,
testThumbnailSizes[i], EXIF_TEST_DATA[i], mStaticInfo, mCollector,
- mDebugFileNameBase);
+ mDebugFileNameBase, ImageFormat.JPEG);
image.close();
}
@@ -1391,6 +1427,9 @@
case ImageFormat.JPEG:
filename += ".jpg";
break;
+ case ImageFormat.HEIC:
+ filename += ".heic";
+ break;
case ImageFormat.NV16:
case ImageFormat.NV21:
case ImageFormat.YUV_420_888:
diff --git a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
index 995a2c7..a519101 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
@@ -254,8 +254,10 @@
private void setupConfigurationTargets(List<MandatoryStreamInformation> streamsInfo,
List<SurfaceTexture> privTargets, List<ImageReader> jpegTargets,
List<ImageReader> yuvTargets, List<ImageReader> y8Targets,
- List<ImageReader> rawTargets, List<OutputConfiguration> outputConfigs,
- int numBuffers, boolean substituteY8, MandatoryStreamInformation overrideStreamInfo,
+ List<ImageReader> rawTargets, List<ImageReader> heicTargets,
+ List<OutputConfiguration> outputConfigs,
+ int numBuffers, boolean substituteY8, boolean substituteHeic,
+ MandatoryStreamInformation overrideStreamInfo,
List<String> overridePhysicalCameraIds, List<Size> overridePhysicalCameraSizes) {
ImageDropperListener imageDropperListener = new ImageDropperListener();
@@ -267,6 +269,8 @@
int format = streamInfo.getFormat();
if (substituteY8 && (format == ImageFormat.YUV_420_888)) {
format = ImageFormat.Y8;
+ } else if (substituteHeic && (format == ImageFormat.JPEG)) {
+ format = ImageFormat.HEIC;
}
Surface newSurface;
Size[] availableSizes = new Size[streamInfo.getAvailableSizes().size()];
@@ -345,6 +349,18 @@
}
break;
}
+ case ImageFormat.HEIC: {
+ ImageReader target = ImageReader.newInstance(targetSize.getWidth(),
+ targetSize.getHeight(), format, numBuffers);
+ target.setOnImageAvailableListener(imageDropperListener, mHandler);
+ OutputConfiguration config = new OutputConfiguration(target.getSurface());
+ if (numConfigs > 1) {
+ config.setPhysicalCameraId(overridePhysicalCameraIds.get(j));
+ }
+ outputConfigs.add(config);
+ heicTargets.add(target);
+ break;
+ }
default:
fail("Unknown output format " + format);
}
@@ -366,13 +382,36 @@
}
}
+ // Check whether substituting JPEG format with HEIC format
+ boolean substituteHeic = false;
+ if (mStaticInfo.isHeicSupported()) {
+ List<MandatoryStreamInformation> streamsInfo = combination.getStreamsInformation();
+ for (MandatoryStreamInformation streamInfo : streamsInfo) {
+ if (streamInfo.getFormat() == ImageFormat.JPEG) {
+ substituteHeic = true;
+ break;
+ }
+ }
+ }
+
// Test camera output combination
Log.i(TAG, "Testing mandatory stream combination: " + combination.getDescription() +
" on camera: " + cameraId);
- testMandatoryStreamCombination(cameraId, combination, /*substituteY8*/false);
+ testMandatoryStreamCombination(cameraId, combination, /*substituteY8*/false,
+ /*substituteHeic*/false);
if (substituteY8) {
- testMandatoryStreamCombination(cameraId, combination, substituteY8);
+ Log.i(TAG, "Testing mandatory stream combination: " + combination.getDescription() +
+ " on camera: " + cameraId + " with Y8");
+ testMandatoryStreamCombination(cameraId, combination, /*substituteY8*/true,
+ /*substituteHeic*/false);
+ }
+
+ if (substituteHeic) {
+ Log.i(TAG, "Testing mandatory stream combination: " + combination.getDescription() +
+ " on camera: " + cameraId + " with HEIC");
+ testMandatoryStreamCombination(cameraId, combination,
+ /*substituteY8*/false, /*substituteHeic*/true);
}
// Test substituting YUV_888/RAW with physical streams for logical camera
@@ -383,7 +422,7 @@
testMultiCameraOutputCombination(cameraId, combination, /*substituteY8*/false);
if (substituteY8) {
- testMultiCameraOutputCombination(cameraId, combination, substituteY8);
+ testMultiCameraOutputCombination(cameraId, combination, /*substituteY8*/true);
}
}
}
@@ -441,10 +480,12 @@
List<ImageReader> yuvTargets = new ArrayList<ImageReader>();
List<ImageReader> y8Targets = new ArrayList<ImageReader>();
List<ImageReader> rawTargets = new ArrayList<ImageReader>();
+ List<ImageReader> heicTargets = new ArrayList<ImageReader>();
setupConfigurationTargets(streamsInfo, privTargets, jpegTargets, yuvTargets,
- y8Targets, rawTargets, outputConfigs, MIN_RESULT_COUNT, substituteY8,
- streamInfo, physicalCamerasForSize, physicalCameraSizes);
+ y8Targets, rawTargets, heicTargets, outputConfigs, MIN_RESULT_COUNT,
+ substituteY8, /*substituteHeic*/false, streamInfo, physicalCamerasForSize,
+ physicalCameraSizes);
boolean haveSession = false;
try {
@@ -516,7 +557,8 @@
}
private void testMandatoryStreamCombination(String cameraId,
- MandatoryStreamCombination combination, boolean substituteY8) throws Exception {
+ MandatoryStreamCombination combination,
+ boolean substituteY8, boolean substituteHeic) throws Exception {
// Timeout is relaxed by 1 second for LEGACY devices to reduce false positive rate in CTS
final int TIMEOUT_FOR_RESULT_MS = (mStaticInfo.isHardwareLevelLegacy()) ? 2000 : 1000;
@@ -529,9 +571,11 @@
List<ImageReader> yuvTargets = new ArrayList<ImageReader>();
List<ImageReader> y8Targets = new ArrayList<ImageReader>();
List<ImageReader> rawTargets = new ArrayList<ImageReader>();
+ List<ImageReader> heicTargets = new ArrayList<ImageReader>();
setupConfigurationTargets(combination.getStreamsInformation(), privTargets, jpegTargets,
- yuvTargets, y8Targets, rawTargets, outputConfigs, MIN_RESULT_COUNT, substituteY8,
+ yuvTargets, y8Targets, rawTargets, heicTargets, outputConfigs, MIN_RESULT_COUNT,
+ substituteY8, substituteHeic,
null /*overrideStreamInfo*/, null /*overridePhysicalCameraIds*/,
null /* overridePhysicalCameraSizes) */);
@@ -600,6 +644,9 @@
for (ImageReader target : rawTargets) {
target.close();
}
+ for (ImageReader target : heicTargets) {
+ target.close();
+ }
}
/**
@@ -635,26 +682,42 @@
private void testMandatoryReprocessableStreamCombination(String cameraId,
MandatoryStreamCombination combination) {
// Test reprocess stream combination
- testMandatoryReprocessableStreamCombination(cameraId, combination, /*substituteY8*/false);
+ testMandatoryReprocessableStreamCombination(cameraId, combination,
+ /*substituteY8*/false, /*substituteHeic*/false);
// Test substituting YUV_888 format with Y8 format in reprocess stream combination.
if (mStaticInfo.isMonochromeWithY8()) {
List<MandatoryStreamInformation> streamsInfo = combination.getStreamsInformation();
- boolean hasY8 = false;
+ boolean substituteY8 = false;
for (MandatoryStreamInformation streamInfo : streamsInfo) {
if (streamInfo.getFormat() == ImageFormat.YUV_420_888) {
- hasY8 = true;
- break;
+ substituteY8 = true;
}
}
- if (hasY8) {
- testMandatoryReprocessableStreamCombination(cameraId, combination, hasY8);
+ if (substituteY8) {
+ testMandatoryReprocessableStreamCombination(cameraId, combination,
+ /*substituteY8*/true, /*substituteHeic*/false);
+ }
+ }
+
+ if (mStaticInfo.isHeicSupported()) {
+ List<MandatoryStreamInformation> streamsInfo = combination.getStreamsInformation();
+ boolean substituteHeic = false;
+ for (MandatoryStreamInformation streamInfo : streamsInfo) {
+ if (streamInfo.getFormat() == ImageFormat.JPEG) {
+ substituteHeic = true;
+ }
+ }
+ if (substituteHeic) {
+ testMandatoryReprocessableStreamCombination(cameraId, combination,
+ /*substituteY8*/false, /*substituteHeic*/true);
}
}
}
private void testMandatoryReprocessableStreamCombination(String cameraId,
- MandatoryStreamCombination combination, boolean substituteY8) {
+ MandatoryStreamCombination combination, boolean substituteY8,
+ boolean substituteHeic) {
final int TIMEOUT_FOR_RESULT_MS = 3000;
final int NUM_REPROCESS_CAPTURES_PER_CONFIG = 3;
@@ -664,6 +727,7 @@
List<ImageReader> yuvTargets = new ArrayList<>();
List<ImageReader> y8Targets = new ArrayList<>();
List<ImageReader> rawTargets = new ArrayList<>();
+ List<ImageReader> heicTargets = new ArrayList<>();
ArrayList<Surface> outputSurfaces = new ArrayList<>();
List<OutputConfiguration> outputConfigs = new ArrayList<OutputConfiguration>();
ImageReader inputReader = null;
@@ -685,13 +749,17 @@
inputFormat = ImageFormat.Y8;
}
+ Log.i(TAG, "testMandatoryReprocessableStreamCombination: " +
+ combination.getDescription() + ", substituteY8 = " + substituteY8 +
+ ", substituteHeic = " + substituteHeic);
try {
// The second stream information entry is the ZSL stream, which is configured
// separately.
setupConfigurationTargets(streamInfo.subList(2, streamInfo.size()), privTargets,
- jpegTargets, yuvTargets, y8Targets, rawTargets, outputConfigs,
- NUM_REPROCESS_CAPTURES_PER_CONFIG, substituteY8, null /*overrideStreamInfo*/,
- null /*overridePhysicalCameraIds*/, null /* overridePhysicalCameraSizes) */);
+ jpegTargets, yuvTargets, y8Targets, rawTargets, heicTargets, outputConfigs,
+ NUM_REPROCESS_CAPTURES_PER_CONFIG, substituteY8, substituteHeic,
+ null /*overrideStreamInfo*/, null /*overridePhysicalCameraIds*/,
+ null /* overridePhysicalCameraSizes) */);
outputSurfaces.ensureCapacity(outputConfigs.size());
for (OutputConfiguration config : outputConfigs) {
@@ -709,7 +777,8 @@
final boolean useY8 = inputIsY8 || y8Targets.size() > 0;
final int totalNumReprocessCaptures = NUM_REPROCESS_CAPTURES_PER_CONFIG * (
((inputIsYuv || inputIsY8) ? 1 : 0) +
- jpegTargets.size() + (useYuv ? yuvTargets.size() : y8Targets.size()));
+ (substituteHeic ? heicTargets.size() : jpegTargets.size()) +
+ (useYuv ? yuvTargets.size() : y8Targets.size()));
// It needs 1 input buffer for each reprocess capture + the number of buffers
// that will be used as outputs.
@@ -750,6 +819,10 @@
reprocessOutputs.add(reader.getSurface());
}
+ for (ImageReader reader : heicTargets) {
+ reprocessOutputs.add(reader.getSurface());
+ }
+
for (ImageReader reader : yuvTargets) {
reprocessOutputs.add(reader.getSurface());
}
@@ -803,6 +876,10 @@
target.close();
}
+ for (ImageReader target : heicTargets) {
+ target.close();
+ }
+
if (inputReader != null) {
inputReader.close();
}
@@ -1916,6 +1993,7 @@
static final int YUV = ImageFormat.YUV_420_888;
static final int RAW = ImageFormat.RAW_SENSOR;
static final int Y8 = ImageFormat.Y8;
+ static final int HEIC = ImageFormat.HEIC;
// Max resolution indices
static final int PREVIEW = 0;
@@ -1933,6 +2011,7 @@
StaticMetadata.StreamDirection.Output);
Size[] jpegSizes = sm.getJpegOutputSizesChecked();
Size[] rawSizes = sm.getRawOutputSizesChecked();
+ Size[] heicSizes = sm.getHeicOutputSizesChecked();
Size maxPreviewSize = getMaxPreviewSize(context, cameraId);
@@ -1975,6 +2054,13 @@
maxY8Sizes[MAXIMUM] = CameraTestUtils.getMaxSize(y8Sizes);
maxY8Sizes[VGA] = vgaSize;
}
+
+ if (sm.isHeicSupported()) {
+ maxHeicSizes[PREVIEW] = getMaxSize(heicSizes, maxPreviewSize);
+ maxHeicSizes[RECORD] = getMaxRecordingSize(cameraId);
+ maxHeicSizes[MAXIMUM] = CameraTestUtils.getMaxSize(heicSizes);
+ maxHeicSizes[VGA] = vgaSize;
+ }
}
Size[] privInputSizes = configs.getInputSizes(ImageFormat.PRIVATE);
@@ -1992,6 +2078,7 @@
public final Size[] maxJpegSizes = new Size[RESOLUTION_COUNT];
public final Size[] maxYuvSizes = new Size[RESOLUTION_COUNT];
public final Size[] maxY8Sizes = new Size[RESOLUTION_COUNT];
+ public final Size[] maxHeicSizes = new Size[RESOLUTION_COUNT];
public final Size maxRawSize;
// TODO: support non maximum reprocess input.
public final Size maxInputPrivSize;
@@ -2119,9 +2206,10 @@
List<ImageReader> yuvTargets = new ArrayList<ImageReader>();
List<ImageReader> y8Targets = new ArrayList<ImageReader>();
List<ImageReader> rawTargets = new ArrayList<ImageReader>();
+ List<ImageReader> heicTargets = new ArrayList<ImageReader>();
setupConfigurationTargets(config, maxSizes, privTargets, jpegTargets, yuvTargets,
- y8Targets, rawTargets, outputConfigs, MIN_RESULT_COUNT, i,
+ y8Targets, rawTargets, heicTargets, outputConfigs, MIN_RESULT_COUNT, i,
physicalCamerasForSize, physicalCameraSizes);
boolean haveSession = false;
@@ -2196,7 +2284,8 @@
private void setupConfigurationTargets(int[] configs, MaxStreamSizes maxSizes,
List<SurfaceTexture> privTargets, List<ImageReader> jpegTargets,
List<ImageReader> yuvTargets, List<ImageReader> y8Targets,
- List<ImageReader> rawTargets, List<OutputConfiguration> outputConfigs, int numBuffers,
+ List<ImageReader> rawTargets, List<ImageReader> heicTargets,
+ List<OutputConfiguration> outputConfigs, int numBuffers,
int overrideStreamIndex, List<String> overridePhysicalCameraIds,
List<Size> overridePhysicalCameraSizes) {
@@ -2241,6 +2330,20 @@
jpegTargets.add(target);
break;
}
+ case HEIC: {
+ Size targetSize = (numConfigs == 1) ? maxSizes.maxHeicSizes[sizeLimit] :
+ overridePhysicalCameraSizes.get(j);
+ ImageReader target = ImageReader.newInstance(
+ targetSize.getWidth(), targetSize.getHeight(), HEIC, numBuffers);
+ target.setOnImageAvailableListener(imageDropperListener, mHandler);
+ OutputConfiguration config = new OutputConfiguration(target.getSurface());
+ if (numConfigs > 1) {
+ config.setPhysicalCameraId(overridePhysicalCameraIds.get(j));
+ }
+ outputConfigs.add(config);
+ heicTargets.add(target);
+ break;
+ }
case YUV: {
Size targetSize = (numConfigs == 1) ? maxSizes.maxYuvSizes[sizeLimit] :
overridePhysicalCameraSizes.get(j);
diff --git a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
index a169fee..22e2424 100644
--- a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
@@ -100,7 +100,46 @@
continue;
}
openDevice(mCameraIds[i]);
- jpegExifTestByCamera();
+ Size maxJpegSize = mOrderedStillSizes.get(0);
+ stillExifTestByCamera(ImageFormat.JPEG, maxJpegSize);
+ } finally {
+ closeDevice();
+ closeImageReader();
+ }
+ }
+ }
+
+ /**
+ * Test HEIC capture exif fields for each camera.
+ */
+ @Test
+ public void testHeicExif() throws Exception {
+ for (int i = 0; i < mCameraIds.length; i++) {
+ try {
+ Log.i(TAG, "Testing HEIC exif for Camera " + mCameraIds[i]);
+ if (!mAllStaticInfo.get(mCameraIds[i]).isColorOutputSupported()) {
+ Log.i(TAG, "Camera " + mCameraIds[i] +
+ " does not support color outputs, skipping");
+ continue;
+ }
+ if (!mAllStaticInfo.get(mCameraIds[i]).isHeicSupported()) {
+ Log.i(TAG, "Camera " + mCameraIds[i] +
+ " does not support HEIC, skipping");
+ continue;
+ }
+
+ openDevice(mCameraIds[i]);
+
+ // Test maximum Heic size capture
+ List<Size> orderedHeicSizes = CameraTestUtils.getSupportedHeicSizes(
+ mCameraIds[i], mCameraManager, null/*bound*/);
+ Size maxHeicSize = orderedHeicSizes.get(0);
+ stillExifTestByCamera(ImageFormat.HEIC, maxHeicSize);
+
+ // Test preview size Heic capture
+ Size previewSize = mOrderedPreviewSizes.get(0);
+ stillExifTestByCamera(ImageFormat.HEIC, previewSize);
+
} finally {
closeDevice();
closeImageReader();
@@ -318,7 +357,7 @@
* Test all combination of available preview sizes and still sizes.
* <p>
* For each still capture, Only the jpeg buffer is validated, capture
- * result validation is covered by {@link #jpegExifTestByCamera} test.
+ * result validation is covered by {@link #stillExifTestByCamera} test.
* </p>
*/
@Test(timeout=60*60*1000) // timeout = 60 mins for long running tests
@@ -585,7 +624,7 @@
// Set the max number of images to number of focal lengths supported
prepareStillCaptureAndStartPreview(previewRequest, stillRequest, maxPreviewSz,
- maxStillSz, resultListener, focalLengths.length, imageListener);
+ maxStillSz, resultListener, focalLengths.length, imageListener, false /*isHeic*/);
for(float focalLength : focalLengths) {
@@ -613,7 +652,7 @@
validateJpegCapture(image, maxStillSz);
verifyJpegKeys(image, result, maxStillSz, thumbnailSize, exifTestData,
- mStaticInfo, mCollector, mDebugFileNameBase);
+ mStaticInfo, mCollector, mDebugFileNameBase, ImageFormat.JPEG);
}
}
@@ -633,7 +672,7 @@
CaptureRequest.Builder stillRequest =
mCamera.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
prepareStillCaptureAndStartPreview(previewRequest, stillRequest, maxPreviewSz,
- maxStillSz, resultListener, imageListener);
+ maxStillSz, resultListener, imageListener, false /*isHeic*/);
// make sure preview is actually running
waitForNumResults(resultListener, NUM_FRAMES_WAITED);
@@ -719,7 +758,7 @@
stillRequest = mCamera.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
}
prepareStillCaptureAndStartPreview(previewRequest, stillRequest, maxPreviewSz,
- maxStillSz, resultListener, imageListener);
+ maxStillSz, resultListener, imageListener, false /*isHeic*/);
// Set AE mode to ON_AUTO_FLASH if flash is available.
if (mStaticInfo.hasFlash()) {
@@ -930,7 +969,7 @@
CaptureRequest.Builder stillRequest =
mCamera.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
prepareStillCaptureAndStartPreview(previewRequest, stillRequest, previewSz,
- stillSz, resultListener, imageListener);
+ stillSz, resultListener, imageListener, false /*isHeic*/);
mSession.capture(stillRequest.build(), resultListener, mHandler);
Image image = imageListener.getImage((mStaticInfo.isHardwareLevelLegacy()) ?
RELAXED_CAPTURE_IMAGE_TIMEOUT_MS : CAPTURE_IMAGE_TIMEOUT_MS);
@@ -1049,7 +1088,7 @@
CaptureResult result = resultListener.getCaptureResultForRequest(multiRequest,
NUM_RESULTS_WAIT_TIMEOUT);
Image jpegImage = jpegListener.getImage(CAPTURE_IMAGE_TIMEOUT_MS);
- basicValidateJpegImage(jpegImage, maxStillSz);
+ basicValidateBlobImage(jpegImage, maxStillSz, ImageFormat.JPEG);
Image rawImage = rawListener.getImage(CAPTURE_IMAGE_TIMEOUT_MS);
validateRaw16Image(rawImage, size);
verifyRawCaptureResult(multiRequest, result);
@@ -1188,17 +1227,19 @@
}
/**
- * Issue a Jpeg capture and validate the exif information.
+ * Issue a still capture and validate the exif information.
* <p>
* TODO: Differentiate full and limited device, some of the checks rely on
* per frame control and synchronization, most of them don't.
* </p>
*/
- private void jpegExifTestByCamera() throws Exception {
+ private void stillExifTestByCamera(int format, Size stillSize) throws Exception {
+ assertTrue(format == ImageFormat.JPEG || format == ImageFormat.HEIC);
+ boolean isHeic = (format == ImageFormat.HEIC);
+
Size maxPreviewSz = mOrderedPreviewSizes.get(0);
- Size maxStillSz = mOrderedStillSizes.get(0);
if (VERBOSE) {
- Log.v(TAG, "Testing JPEG exif with jpeg size " + maxStillSz.toString()
+ Log.v(TAG, "Testing exif with size " + stillSize.toString()
+ ", preview size " + maxPreviewSz);
}
@@ -1209,8 +1250,8 @@
mCamera.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
SimpleCaptureCallback resultListener = new SimpleCaptureCallback();
SimpleImageReaderListener imageListener = new SimpleImageReaderListener();
- prepareStillCaptureAndStartPreview(previewBuilder, stillBuilder, maxPreviewSz, maxStillSz,
- resultListener, imageListener);
+ prepareStillCaptureAndStartPreview(previewBuilder, stillBuilder, maxPreviewSz, stillSize,
+ resultListener, imageListener, isHeic);
// Set the jpeg keys, then issue a capture
Size[] thumbnailSizes = mStaticInfo.getAvailableThumbnailSizesChecked();
@@ -1223,15 +1264,15 @@
for (int i = 0; i < EXIF_TEST_DATA.length; i++) {
setJpegKeys(stillBuilder, EXIF_TEST_DATA[i], testThumbnailSizes[i], mCollector);
- // Capture a jpeg image.
+ // Capture a jpeg/heic image.
CaptureRequest request = stillBuilder.build();
mSession.capture(request, resultListener, mHandler);
CaptureResult stillResult =
resultListener.getCaptureResultForRequest(request, NUM_RESULTS_WAIT_TIMEOUT);
Image image = imageListener.getImage(CAPTURE_IMAGE_TIMEOUT_MS);
- verifyJpegKeys(image, stillResult, maxStillSz, testThumbnailSizes[i], EXIF_TEST_DATA[i],
- mStaticInfo, mCollector, mDebugFileNameBase);
+ verifyJpegKeys(image, stillResult, stillSize, testThumbnailSizes[i], EXIF_TEST_DATA[i],
+ mStaticInfo, mCollector, mDebugFileNameBase, format);
// Free image resources
image.close();
@@ -1292,7 +1333,7 @@
// Set the max number of images to be same as the burst count, as the verification
// could be much slower than producing rate, and we don't want to starve producer.
prepareStillCaptureAndStartPreview(previewRequest, stillRequest, maxPreviewSz,
- maxStillSz, resultListener, numSteps, imageListener);
+ maxStillSz, resultListener, numSteps, imageListener, false /*isHeic*/);
for (int i = 0; i <= numSteps; i++) {
int exposureCompensation = i * stepsPerEv + compensationRange.getLower();
diff --git a/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java b/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
index 8c245bd..7a9ae93 100644
--- a/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
+++ b/tests/camera/src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java
@@ -285,9 +285,10 @@
protected void prepareStillCaptureAndStartPreview(CaptureRequest.Builder previewRequest,
CaptureRequest.Builder stillRequest, Size previewSz, Size stillSz,
CaptureCallback resultListener,
- ImageReader.OnImageAvailableListener imageListener) throws Exception {
+ ImageReader.OnImageAvailableListener imageListener, boolean isHeic) throws Exception {
prepareCaptureAndStartPreview(previewRequest, stillRequest, previewSz, stillSz,
- ImageFormat.JPEG, resultListener, MAX_READER_IMAGES, imageListener);
+ isHeic ? ImageFormat.HEIC : ImageFormat.JPEG, resultListener, MAX_READER_IMAGES,
+ imageListener);
}
/**
@@ -304,9 +305,9 @@
protected void prepareStillCaptureAndStartPreview(CaptureRequest.Builder previewRequest,
CaptureRequest.Builder stillRequest, Size previewSz, Size stillSz,
CaptureCallback resultListener, int maxNumImages,
- ImageReader.OnImageAvailableListener imageListener) throws Exception {
+ ImageReader.OnImageAvailableListener imageListener, boolean isHeic) throws Exception {
prepareCaptureAndStartPreview(previewRequest, stillRequest, previewSz, stillSz,
- ImageFormat.JPEG, resultListener, maxNumImages, imageListener);
+ isHeic ? ImageFormat.HEIC : ImageFormat.JPEG, resultListener, maxNumImages, imageListener);
}
/**
@@ -573,11 +574,13 @@
* @param resultListener Capture result listener
* @param maxNumImages The max number of images set to the image reader
* @param imageListeners The single capture capture image listeners
+ * @param isHeic HEIC still capture if true, JPEG still capture if false
*/
protected ImageReader[] prepareStillCaptureAndStartPreview(
CaptureRequest.Builder previewRequest, CaptureRequest.Builder stillRequest,
Size previewSz, Size[] captureSizes, int[] formats, CaptureCallback resultListener,
- int maxNumImages, ImageReader.OnImageAvailableListener[] imageListeners)
+ int maxNumImages, ImageReader.OnImageAvailableListener[] imageListeners,
+ boolean isHeic)
throws Exception {
if ((captureSizes == null) || (formats == null) || (imageListeners == null) &&
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
index 4fd4b39..883d86b 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
@@ -1035,11 +1035,12 @@
ByteBuffer buffer = null;
// JPEG doesn't have pixelstride and rowstride, treat it as 1D buffer.
- // Same goes for DEPTH_POINT_CLOUD and DEPTH_JPEG
+ // Same goes for DEPTH_POINT_CLOUD, RAW_PRIVATE, DEPTH_JPEG, and HEIC
if (format == ImageFormat.JPEG || format == ImageFormat.DEPTH_POINT_CLOUD ||
- format == ImageFormat.RAW_PRIVATE || format == ImageFormat.DEPTH_JPEG) {
+ format == ImageFormat.RAW_PRIVATE || format == ImageFormat.DEPTH_JPEG ||
+ format == ImageFormat.HEIC) {
buffer = planes[0].getBuffer();
- assertNotNull("Fail to get jpeg or depth ByteBuffer", buffer);
+ assertNotNull("Fail to get jpeg/depth/heic ByteBuffer", buffer);
data = new byte[buffer.remaining()];
buffer.get(data);
buffer.rewind();
@@ -1122,6 +1123,7 @@
case ImageFormat.DEPTH_POINT_CLOUD:
case ImageFormat.DEPTH_JPEG:
case ImageFormat.Y8:
+ case ImageFormat.HEIC:
assertEquals("JPEG/RAW/depth/Y8 Images should have one plane", 1, planes.length);
break;
default:
@@ -1364,6 +1366,11 @@
return getSortedSizesForFormat(cameraId, cameraManager, ImageFormat.JPEG, bound);
}
+ static public List<Size> getSupportedHeicSizes(String cameraId,
+ CameraManager cameraManager, Size bound) throws CameraAccessException {
+ return getSortedSizesForFormat(cameraId, cameraManager, ImageFormat.HEIC, bound);
+ }
+
static public Size getMinPreviewSize(String cameraId, CameraManager cameraManager)
throws CameraAccessException {
List<Size> sizes = getSupportedPreviewSizes(cameraId, cameraManager, null);
@@ -1551,6 +1558,9 @@
case ImageFormat.Y8:
validateY8Data(data, width, height, format, image.getTimestamp(), filePath);
break;
+ case ImageFormat.HEIC:
+ validateHeicData(data, width, height, filePath);
+ break;
default:
throw new UnsupportedOperationException("Unsupported format for validation: "
+ format);
@@ -1733,6 +1743,26 @@
}
+ private static void validateHeicData(byte[] heicData, int width, int height, String filePath) {
+ BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
+ // DecodeBound mode: only parse the frame header to get width/height.
+ // it doesn't decode the pixel.
+ bmpOptions.inJustDecodeBounds = true;
+ BitmapFactory.decodeByteArray(heicData, 0, heicData.length, bmpOptions);
+ assertEquals(width, bmpOptions.outWidth);
+ assertEquals(height, bmpOptions.outHeight);
+
+ // Pixel decoding mode: decode whole image. check if the image data
+ // is decodable here.
+ assertNotNull("Decoding heic failed",
+ BitmapFactory.decodeByteArray(heicData, 0, heicData.length));
+ if (DEBUG && filePath != null) {
+ String fileName =
+ filePath + "/" + width + "x" + height + ".heic";
+ dumpFile(fileName, heicData);
+ }
+ }
+
public static <T> T getValueNotNull(CaptureResult result, CaptureResult.Key<T> key) {
if (result == null) {
throw new IllegalArgumentException("Result must not be null");
@@ -2047,49 +2077,54 @@
* continue the test if the jpeg image captured has some serious failures.
* </p>
*
- * @param image The captured jpeg image
- * @param expectedSize Expected capture jpeg size
+ * @param image The captured JPEG/HEIC image
+ * @param expectedSize Expected capture JEPG/HEIC size
+ * @param format JPEG/HEIC image format
*/
- public static void basicValidateJpegImage(Image image, Size expectedSize) {
+ public static void basicValidateBlobImage(Image image, Size expectedSize, int format) {
Size imageSz = new Size(image.getWidth(), image.getHeight());
assertTrue(
String.format("Image size doesn't match (expected %s, actual %s) ",
expectedSize.toString(), imageSz.toString()), expectedSize.equals(imageSz));
- assertEquals("Image format should be JPEG", ImageFormat.JPEG, image.getFormat());
+ assertEquals("Image format should be " + ((format == ImageFormat.HEIC) ? "HEIC" : "JPEG"),
+ format, image.getFormat());
assertNotNull("Image plane shouldn't be null", image.getPlanes());
assertEquals("Image plane number should be 1", 1, image.getPlanes().length);
- // Jpeg decoding validate was done in ImageReaderTest, no need to duplicate the test here.
+ // Jpeg/Heic decoding validate was done in ImageReaderTest,
+ // no need to duplicate the test here.
}
/**
- * Verify the JPEG EXIF and JPEG related keys in a capture result are expected.
+ * Verify the EXIF and JPEG related keys in a capture result are expected.
* - Capture request get values are same as were set.
* - capture result's exif data is the same as was set by
* the capture request.
* - new tags in the result set by the camera service are
* present and semantically correct.
*
- * @param image The output JPEG image to verify.
+ * @param image The output JPEG/HEIC image to verify.
* @param captureResult The capture result to verify.
- * @param expectedSize The expected JPEG size.
+ * @param expectedSize The expected JPEG/HEIC size.
* @param expectedThumbnailSize The expected thumbnail size.
* @param expectedExifData The expected EXIF data
* @param staticInfo The static metadata for the camera device.
- * @param jpegFilename The filename to dump the jpeg to.
+ * @param blobFilename The filename to dump the jpeg/heic to.
* @param collector The camera error collector to collect errors.
+ * @param format JPEG/HEIC format
*/
public static void verifyJpegKeys(Image image, CaptureResult captureResult, Size expectedSize,
Size expectedThumbnailSize, ExifTestData expectedExifData, StaticMetadata staticInfo,
- CameraErrorCollector collector, String debugFileNameBase) throws Exception {
+ CameraErrorCollector collector, String debugFileNameBase, int format) throws Exception {
- basicValidateJpegImage(image, expectedSize);
+ basicValidateBlobImage(image, expectedSize, format);
- byte[] jpegBuffer = getDataFromImage(image);
+ byte[] blobBuffer = getDataFromImage(image);
// Have to dump into a file to be able to use ExifInterface
- String jpegFilename = debugFileNameBase + "/verifyJpegKeys.jpeg";
- dumpFile(jpegFilename, jpegBuffer);
- ExifInterface exif = new ExifInterface(jpegFilename);
+ String filePostfix = (format == ImageFormat.HEIC ? ".heic" : ".jpeg");
+ String blobFilename = debugFileNameBase + "/verifyJpegKeys" + filePostfix;
+ dumpFile(blobFilename, blobBuffer);
+ ExifInterface exif = new ExifInterface(blobFilename);
if (expectedThumbnailSize.equals(new Size(0,0))) {
collector.expectTrue("Jpeg shouldn't have thumbnail when thumbnail size is (0, 0)",
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
index 15701f1..6af6be5 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
@@ -1347,6 +1347,16 @@
}
/**
+ * Get supported heic output sizes and do the check.
+ *
+ * @return Empty size array if heic output is not supported
+ */
+ public Size[] getHeicOutputSizesChecked() {
+ return getAvailableSizesForFormatChecked(ImageFormat.HEIC,
+ StreamDirection.Output);
+ }
+
+ /**
* Used to determine the stream direction for various helpers that look up
* format or size information.
*/
@@ -2361,6 +2371,14 @@
}
/**
+ * Check if HEIC format is supported
+ */
+ public boolean isHeicSupported() {
+ int[] formats = getAvailableFormats(StaticMetadata.StreamDirection.Output);
+ return CameraTestUtils.contains(formats, ImageFormat.HEIC);
+ }
+
+ /**
* Check if the dynamic black level is supported.
*
* <p>
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/AbstractContentCaptureIntegrationTest.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/AbstractContentCaptureIntegrationTest.java
index 96f94b4..e827a62 100644
--- a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/AbstractContentCaptureIntegrationTest.java
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/AbstractContentCaptureIntegrationTest.java
@@ -16,19 +16,19 @@
package android.contentcaptureservice.cts;
import static android.contentcaptureservice.cts.Helper.GENERIC_TIMEOUT_MS;
+import static android.contentcaptureservice.cts.Helper.SYSTEM_SERVICE_NAME;
import static android.contentcaptureservice.cts.Helper.resetService;
+import static android.contentcaptureservice.cts.Helper.sContext;
import static android.contentcaptureservice.cts.Helper.setService;
import static android.contentcaptureservice.cts.common.ShellHelper.runShellCommand;
import static android.provider.Settings.Secure.CONTENT_CAPTURE_ENABLED;
import android.app.Application;
-import android.content.Context;
import android.content.Intent;
import android.contentcaptureservice.cts.CtsContentCaptureService.ServiceWatcher;
import android.contentcaptureservice.cts.common.ActivitiesWatcher;
import android.contentcaptureservice.cts.common.ActivitiesWatcher.ActivityWatcher;
import android.contentcaptureservice.cts.common.Visitor;
-import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
@@ -42,7 +42,9 @@
import com.android.compatibility.common.util.SettingsUtils;
import org.junit.After;
+import org.junit.AfterClass;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.RuleChain;
import org.junit.runner.RunWith;
@@ -54,21 +56,37 @@
public abstract class AbstractContentCaptureIntegrationTest
<A extends AbstractContentCaptureActivity> {
- private final String mTag = getClass().getSimpleName();
+ private static final String TAG = AbstractContentCaptureIntegrationTest.class.getSimpleName();
- protected static final Context sContext = InstrumentationRegistry.getTargetContext();
+ private final String mTag = getClass().getSimpleName();
protected ActivitiesWatcher mActivitiesWatcher;
private final Class<A> mActivityClass;
private final RequiredServiceRule mRequiredServiceRule =
- new RequiredServiceRule("content_capture");
+ new RequiredServiceRule(SYSTEM_SERVICE_NAME);
private final ContentCaptureLoggingTestRule mLoggingRule = new ContentCaptureLoggingTestRule();
+
+ /**
+ * Watcher set on {@link #enableService()} and used to wait until it's gone after the test
+ * finishes.
+ */
+ private ServiceWatcher mServiceWatcher;
+
protected final SafeCleanerRule mSafeCleanerRule = new SafeCleanerRule()
.setDumper(mLoggingRule)
+ .run(() -> {
+ Log.v(mTag, "@SafeCleaner: resetDefaultService()");
+ resetService();
+
+ if (mServiceWatcher != null) {
+ mServiceWatcher.waitOnDestroy();
+ }
+
+ })
.add(() -> {
return CtsContentCaptureService.getExceptions();
});
@@ -93,16 +111,22 @@
// Finally, let subclasses set their ActivityTestRule
.around(getActivityTestRule());
- /**
- * Watcher set on {@link #enableService()} and used to wait until it's gone after the test
- * finishes.
- */
- private ServiceWatcher mServiceWatcher;
-
protected AbstractContentCaptureIntegrationTest(@NonNull Class<A> activityClass) {
mActivityClass = activityClass;
}
+ @BeforeClass
+ public static void disableDefaultService() {
+ Log.v(TAG, "@BeforeClass: disableDefaultService()");
+ Helper.setDefaultServiceEnabled(false);
+ }
+
+ @AfterClass
+ public static void enableDefaultService() {
+ Log.v(TAG, "@AfterClass: enableDefaultService()");
+ Helper.setDefaultServiceEnabled(true);
+ }
+
@Before
public void prepareDevice() throws Exception {
Log.v(mTag, "@Before: prepareDevice()");
@@ -140,18 +164,6 @@
}
}
- // TODO(b/123539404): this method should be called from the SafeCleaner, but we'll need to
- // add a run() method that takes an object that can throw an exception
- @After
- public void restoreDefaultService() throws InterruptedException {
- Log.v(mTag, "@After: restoreDefaultService()");
- resetService();
-
- if (mServiceWatcher != null) {
- mServiceWatcher.waitOnDestroy();
- }
- }
-
@Nullable
public static void setFeatureEnabled(@Nullable String enabled) {
if (enabled == null) {
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/Assertions.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/Assertions.java
index b74b22c..e3792ee 100644
--- a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/Assertions.java
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/Assertions.java
@@ -279,8 +279,18 @@
assertThat(events).hasSize(minimumSize + 1);
final ContentCaptureEvent batchDisappearEvent = events.get(minimumSize);
- final List<AutofillId> actualIds = batchDisappearEvent.getIds();
- assertThat(actualIds).containsExactly((Object[]) expectedIds);
+ if (expectedIds.length == 1) {
+ assertWithMessage("Should have just one deleted id on %s", batchDisappearEvent)
+ .that(batchDisappearEvent.getIds()).isNull();
+ assertWithMessage("wrong deleted id on %s", batchDisappearEvent)
+ .that(batchDisappearEvent.getId()).isEqualTo(expectedIds[0]);
+ } else {
+ assertWithMessage("Should not have individual deleted id on %s", batchDisappearEvent)
+ .that(batchDisappearEvent.getId()).isNull();
+ final List<AutofillId> actualIds = batchDisappearEvent.getIds();
+ assertWithMessage("wrong deleteds id on %s", batchDisappearEvent)
+ .that(actualIds).containsExactly((Object[]) expectedIds);
+ }
}
/**
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CanaryTest.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CanaryTest.java
new file mode 100644
index 0000000..e512d1d
--- /dev/null
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CanaryTest.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2019 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.contentcaptureservice.cts;
+
+import static android.contentcaptureservice.cts.Helper.RESOURCE_STRING_SERVICE_NAME;
+import static android.contentcaptureservice.cts.Helper.SYSTEM_SERVICE_NAME;
+import static android.contentcaptureservice.cts.Helper.getInternalString;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.junit.Assume.assumeTrue;
+
+import android.provider.DeviceConfig;
+import android.text.TextUtils;
+import android.util.Log;
+
+import com.android.compatibility.common.util.RequiredServiceRule;
+
+import org.junit.Test;
+
+/**
+ * No-op test used to make sure the other tests are not passing because the feature is disabled.
+ */
+public class CanaryTest {
+
+ private static final String TAG = CanaryTest.class.getSimpleName();
+
+ @Test
+ public void logHasService() {
+ final boolean hasService = RequiredServiceRule.hasService(SYSTEM_SERVICE_NAME);
+ Log.d(TAG, "has " + SYSTEM_SERVICE_NAME + ": " + hasService);
+ assumeTrue("device doesn't have service " + SYSTEM_SERVICE_NAME, hasService);
+ }
+
+ @Test
+ public void assertHasService() {
+ final String serviceName = getInternalString(RESOURCE_STRING_SERVICE_NAME);
+ final String enableSettings = DeviceConfig.getProperty(
+ DeviceConfig.ContentCapture.NAMESPACE,
+ DeviceConfig.ContentCapture.PROPERTY_CONTENTCAPTURE_ENABLED);
+ final boolean hasService = RequiredServiceRule.hasService(SYSTEM_SERVICE_NAME);
+ Log.d(TAG, "Service resource: '" + serviceName + "' Settings: '" + enableSettings
+ + "' Has '" + SYSTEM_SERVICE_NAME + "': " + hasService);
+
+ // We're only asserting when the OEM defines a service
+ assumeTrue("service resource (" + serviceName + ")is not defined",
+ !TextUtils.isEmpty(serviceName));
+ assertWithMessage("Should be enabled when resource '%s' is not empty (settings='%s')",
+ serviceName, enableSettings).that(hasService).isTrue();
+ }
+}
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/ChildlessActivityTest.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/ChildlessActivityTest.java
index 8dbda23..d9364ca 100644
--- a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/ChildlessActivityTest.java
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/ChildlessActivityTest.java
@@ -29,6 +29,7 @@
import static android.contentcaptureservice.cts.Assertions.assertViewsDisappeared;
import static android.contentcaptureservice.cts.Assertions.assertViewsOptionallyDisappeared;
import static android.contentcaptureservice.cts.Helper.newImportantView;
+import static android.contentcaptureservice.cts.Helper.sContext;
import static android.contentcaptureservice.cts.common.ActivitiesWatcher.ActivityLifecycle.DESTROYED;
import static android.contentcaptureservice.cts.common.ActivitiesWatcher.ActivityLifecycle.RESUMED;
@@ -60,7 +61,6 @@
import org.junit.After;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
import java.util.Arrays;
@@ -108,7 +108,6 @@
activity.assertDefaultEvents(session);
}
- @Ignore("not implemented yet, pending on b/123658889")
@Test
public void testGetContentCapture_disabledWhenNoService() throws Exception {
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CtsContentCaptureService.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CtsContentCaptureService.java
index e869fc1..04213ba 100644
--- a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CtsContentCaptureService.java
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CtsContentCaptureService.java
@@ -58,11 +58,6 @@
private static ServiceWatcher sServiceWatcher;
- // TODO(b/123421324): reuse with allSessions
- /** Used by {@link #getOnlyFinishedSession()}. */
- private static ContentCaptureSessionId sFirstSessionId;
-
-
private final int mId = ++sIdCounter;
private static final ArrayList<Throwable> sExceptions = new ArrayList<>();
@@ -118,7 +113,6 @@
public static void resetStaticState() {
- sFirstSessionId = null;
sExceptions.clear();
// TODO(b/123540602): should probably set sInstance to null as well, but first we would need
// to make sure each test unbinds the service.
@@ -202,11 +196,8 @@
public void onCreateContentCaptureSession(ContentCaptureContext context,
ContentCaptureSessionId sessionId) {
Log.i(TAG, "onCreateContentCaptureSession(id=" + mId + ", ctx=" + context
- + ", session=" + sessionId + ", firstId=" + sFirstSessionId + ")");
+ + ", session=" + sessionId);
mAllSessions.add(sessionId);
- if (sFirstSessionId == null) {
- sFirstSessionId = sessionId;
- }
safeRun(() -> {
final Session session = mOpenSessions.get(sessionId);
@@ -289,9 +280,11 @@
*/
@NonNull
public Session getOnlyFinishedSession() throws InterruptedException {
- // TODO(b/123421324): add some assertions to make sure There Can Be Only One!
- assertWithMessage("No session yet").that(sFirstSessionId).isNotNull();
- return getFinishedSession(sFirstSessionId);
+ final ArrayList<ContentCaptureSessionId> allSessions = mAllSessions;
+ assertWithMessage("Wrong number of sessions").that(allSessions).hasSize(1);
+ final ContentCaptureSessionId id = allSessions.get(0);
+ Log.d(TAG, "getOnlyFinishedSession(): id=" + id);
+ return getFinishedSession(id);
}
/**
@@ -319,7 +312,6 @@
super.dump(fd, pw, args);
pw.print("sServiceWatcher: "); pw.println(sServiceWatcher);
- pw.print("sFirstSessionId: "); pw.println(sFirstSessionId);
pw.print("sExceptions: "); pw.println(sExceptions);
pw.print("sIdCounter: "); pw.println(sIdCounter);
pw.print("mId: "); pw.println(mId);
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivity.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivity.java
index 92b4f53..33cd31f 100644
--- a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivity.java
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivity.java
@@ -101,13 +101,16 @@
@NonNull
private List<ContentCaptureEvent> assertJustInitialViewsAppeared(@NonNull Session session,
int additionalEvents) {
- final List<ContentCaptureEvent> events = session.getEvents();
- Log.v(TAG, "events(" + events.size() + "): " + events);
- assertThat(events.size()).isAtLeast(MIN_EVENTS + additionalEvents);
-
final View grandpa1 = (View) mCustomView.getParent();
final View grandpa2 = (View) grandpa1.getParent();
final View decorView = getDecorView();
+ Log.v(TAG, "assertJustInitialViewsAppeared(): grandpa1=" + grandpa1.getAutofillId()
+ + ", grandpa2=" + grandpa2.getAutofillId() + ", decor="
+ + decorView.getAutofillId());
+
+ final List<ContentCaptureEvent> events = session.getEvents();
+ Log.v(TAG, "events(" + events.size() + "): " + events);
+ assertThat(events.size()).isAtLeast(MIN_EVENTS + additionalEvents);
// Assert just the relevant events
assertViewHierarchyStarted(events, 0);
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivityTest.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivityTest.java
index bd7e217..0ab1425 100644
--- a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivityTest.java
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/CustomViewActivityTest.java
@@ -15,7 +15,11 @@
*/
package android.contentcaptureservice.cts;
+import static android.contentcaptureservice.cts.Assertions.assertDecorViewAppeared;
import static android.contentcaptureservice.cts.Assertions.assertRightActivity;
+import static android.contentcaptureservice.cts.Assertions.assertViewAppeared;
+import static android.contentcaptureservice.cts.Assertions.assertViewHierarchyFinished;
+import static android.contentcaptureservice.cts.Assertions.assertViewHierarchyStarted;
import static android.contentcaptureservice.cts.Assertions.assertViewWithUnknownParentAppeared;
import static android.contentcaptureservice.cts.Assertions.assertVirtualViewAppeared;
import static android.contentcaptureservice.cts.Assertions.assertVirtualViewDisappeared;
@@ -34,6 +38,7 @@
import android.platform.test.annotations.AppModeFull;
import android.support.test.rule.ActivityTestRule;
import android.util.Log;
+import android.view.View;
import android.view.ViewStructure;
import android.view.autofill.AutofillId;
import android.view.contentcapture.ContentCaptureEvent;
@@ -41,7 +46,6 @@
import androidx.annotation.NonNull;
-import org.junit.Ignore;
import org.junit.Test;
import java.util.Arrays;
@@ -91,7 +95,6 @@
* the session notification methods instead - this is wrong because the main view will be
* notified last, but we cannot prevent the apps from doing so...
*/
- @Ignore("current broken, will be fixed by b/123777277")
@Test
public void testVirtualView_wrongWay() throws Exception {
final CtsContentCaptureService service = enableService();
@@ -125,24 +128,36 @@
assertRightActivity(session, session.id, activity);
-
- final int additionalEvents = 3;
- final List<ContentCaptureEvent> events = activity.assertInitialViewsAppeared(session,
- additionalEvents);
-
+ final View grandpa1 = (View) activity.mCustomView.getParent();
+ final View grandpa2 = (View) grandpa1.getParent();
+ final View decorView = activity.getDecorView();
final AutofillId customViewId = activity.mCustomView.getAutofillId();
+ Log.v(TAG, "assertJustInitialViewsAppeared(): grandpa1=" + grandpa1.getAutofillId()
+ + ", grandpa2=" + grandpa2.getAutofillId() + ", decor="
+ + decorView.getAutofillId() + "customView=" + customViewId);
+
+ final List<ContentCaptureEvent> events = session.getEvents();
+ Log.v(TAG, "events(" + events.size() + "): " + events);
+ final int additionalEvents = 2;
+
+ assertThat(events.size()).isAtLeast(CustomViewActivity.MIN_EVENTS + additionalEvents);
+
+ // Assert just the relevant events
+ assertViewHierarchyStarted(events, 0);
+ assertDecorViewAppeared(events, 1, decorView);
+ assertViewAppeared(events, 2, grandpa2, decorView.getAutofillId());
+ assertViewAppeared(events, 3, grandpa1, grandpa2.getAutofillId());
+
final ContentCaptureSession mainSession = activity.mCustomView.getContentCaptureSession();
-
- final int i = CustomViewActivity.MIN_EVENTS;
-
- assertVirtualViewAppeared(events, i, mainSession, customViewId, 1, "child");
- assertVirtualViewDisappeared(events, i + 1, customViewId, mainSession, 1);
+ assertVirtualViewAppeared(events, 4, mainSession, customViewId, 1, "child");
+ assertVirtualViewDisappeared(events, 5, customViewId, mainSession, 1);
// This is the "wrong" part - the parent is notified last
- assertViewWithUnknownParentAppeared(events, i + 2, session.id, activity.mCustomView);
+ assertViewWithUnknownParentAppeared(events, 6, session.id, activity.mCustomView);
+
+ assertViewHierarchyFinished(events, 7);
activity.assertInitialViewsDisappeared(events, additionalEvents);
- // TODO(b/122315042): assert views disappeared
}
/**
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/Helper.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/Helper.java
index 9784213..fbbd454 100644
--- a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/Helper.java
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/Helper.java
@@ -19,7 +19,9 @@
import android.content.ComponentName;
import android.content.Context;
+import android.content.res.Resources;
import android.os.SystemClock;
+import android.support.test.InstrumentationRegistry;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
@@ -33,7 +35,7 @@
/**
* Helper for common funcionalities.
*/
-final class Helper {
+public final class Helper {
public static final String TAG = "ContentCaptureTest";
@@ -43,6 +45,12 @@
public static final long MY_EPOCH = SystemClock.uptimeMillis();
+ public static final String SYSTEM_SERVICE_NAME = "content_capture";
+
+ public static final String RESOURCE_STRING_SERVICE_NAME = "config_defaultContentCaptureService";
+
+ public static final Context sContext = InstrumentationRegistry.getTargetContext();
+
/**
* Awaits for a latch to be counted down.
*/
@@ -74,6 +82,15 @@
}
/**
+ * Enables / disables the default service.
+ */
+ public static void setDefaultServiceEnabled(boolean enabled) {
+ Log.d(TAG, "setDefaultServiceEnabled(): " + enabled);
+ runShellCommand("cmd content_capture set default-service-enabled 0 %s",
+ Boolean.toString(enabled));
+ }
+
+ /**
* Gets the component name for a given class.
*/
public static ComponentName componentNameFor(@NonNull Class<?> clazz) {
@@ -90,6 +107,15 @@
return child;
}
+ /**
+ * Gets a string from the Android resources.
+ */
+ public static String getInternalString(@NonNull String id) {
+ final Resources resources = sContext.getResources();
+ final int stringId = resources.getIdentifier(id, "string", "android");
+ return resources.getString(stringId);
+ }
+
private Helper() {
throw new UnsupportedOperationException("contain static methods only");
}
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/ContentCaptureContextTest.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/unit/ContentCaptureContextTest.java
similarity index 98%
rename from tests/contentcaptureservice/src/android/contentcaptureservice/cts/ContentCaptureContextTest.java
rename to tests/contentcaptureservice/src/android/contentcaptureservice/cts/unit/ContentCaptureContextTest.java
index c19f0f7..ed1ffce 100644
--- a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/ContentCaptureContextTest.java
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/unit/ContentCaptureContextTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package android.contentcaptureservice.cts;
+package android.contentcaptureservice.cts.unit;
import static com.google.common.truth.Truth.assertThat;
@@ -34,8 +34,8 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
+@AppModeFull(reason = "unit test")
@RunWith(JUnit4.class)
-@AppModeFull // Unit test
public class ContentCaptureContextTest {
private static final Uri URI = Uri.parse("file:/dev/null");
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/unit/UserDataRemovalRequestTest.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/unit/UserDataRemovalRequestTest.java
new file mode 100644
index 0000000..93a15ec
--- /dev/null
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/unit/UserDataRemovalRequestTest.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2019 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.contentcaptureservice.cts.unit;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertThrows;
+
+import android.net.Uri;
+import android.platform.test.annotations.AppModeFull;
+import android.view.contentcapture.UserDataRemovalRequest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+
+@AppModeFull(reason = "unit test")
+@RunWith(MockitoJUnitRunner.class)
+public class UserDataRemovalRequestTest {
+
+ @Mock
+ private final Uri mUri = Uri.parse("content://com.example/");
+
+ private UserDataRemovalRequest.Builder mBuilder = new UserDataRemovalRequest.Builder();
+
+ @Test
+ public void testBuilder_addUri_invalid() {
+ assertThrows(NullPointerException.class, () -> mBuilder.addUri(null, false));
+ }
+
+ @Test
+ public void testBuilder_addUri_valid() {
+ assertThat(mBuilder.addUri(mUri, false)).isNotNull();
+ assertThat(mBuilder.addUri(Uri.parse("content://com.example2"), true)).isNotNull();
+ }
+
+ @Test
+ public void testBuilder_addUriAfterForEverything() {
+ assertThat(mBuilder.forEverything()).isNotNull();
+ assertThrows(IllegalStateException.class, () -> mBuilder.addUri(mUri, false));
+ }
+
+ @Test
+ public void testBuilder_forEverythingAfterAddingUri() {
+ assertThat(mBuilder.addUri(mUri, false)).isNotNull();
+ assertThrows(IllegalStateException.class, () -> mBuilder.forEverything());
+ }
+
+ @Test
+ public void testBuild_invalid() {
+ assertThrows(IllegalStateException.class, () -> mBuilder.build());
+ }
+
+ @Test
+ public void testBuild_valid() {
+ assertThat(new UserDataRemovalRequest.Builder().forEverything().build())
+ .isNotNull();
+ assertThat(new UserDataRemovalRequest.Builder().addUri(mUri, false).build())
+ .isNotNull();
+ }
+
+ @Test
+ public void testNoMoreInteractionsAfterBuild() {
+ assertThat(mBuilder.forEverything().build()).isNotNull();
+
+ assertThrows(IllegalStateException.class, () -> mBuilder.addUri(mUri, false));
+ assertThrows(IllegalStateException.class, () -> mBuilder.forEverything());
+ assertThrows(IllegalStateException.class, () -> mBuilder.build());
+
+ }
+}
diff --git a/tests/contentcaptureservice/src/android/contentcaptureservice/cts/unit/ViewNodeTest.java b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/unit/ViewNodeTest.java
new file mode 100644
index 0000000..8d9cdeb
--- /dev/null
+++ b/tests/contentcaptureservice/src/android/contentcaptureservice/cts/unit/ViewNodeTest.java
@@ -0,0 +1,415 @@
+/*
+ * Copyright (C) 2019 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.contentcaptureservice.cts.unit;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.testng.Assert.assertThrows;
+
+import android.content.Context;
+import android.os.Bundle;
+import android.os.LocaleList;
+import android.os.Parcel;
+import android.platform.test.annotations.AppModeFull;
+import android.support.test.InstrumentationRegistry;
+import android.view.View;
+import android.view.ViewStructure.HtmlInfo;
+import android.view.autofill.AutofillId;
+import android.view.autofill.AutofillValue;
+import android.view.contentcapture.ViewNode;
+import android.view.contentcapture.ViewNode.ViewStructureImpl;
+import android.widget.FrameLayout;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import java.util.Locale;
+
+@AppModeFull(reason = "unit test")
+@RunWith(MockitoJUnitRunner.class)
+public class ViewNodeTest {
+
+ private final Context mContext = InstrumentationRegistry.getTargetContext();
+
+ @Mock
+ private HtmlInfo mHtmlInfoMock;
+
+ @Test
+ public void testAutofillIdMethods_orphanView() {
+ View view = new View(mContext);
+ AutofillId initialId = new AutofillId(42);
+ view.setAutofillId(initialId);
+
+ ViewStructureImpl structure = new ViewStructureImpl(view);
+ ViewNode node = structure.getNode();
+
+ assertThat(node.getAutofillId()).isEqualTo(initialId);
+ assertThat(node.getParentAutofillId()).isNull();
+
+ AutofillId newId = new AutofillId(108);
+ structure.setAutofillId(newId);
+ assertThat(node.getAutofillId()).isEqualTo(newId);
+ assertThat(node.getParentAutofillId()).isNull();
+
+ structure.setAutofillId(new AutofillId(66), 6);
+ assertThat(node.getAutofillId()).isEqualTo(new AutofillId(66, 6));
+ assertThat(node.getParentAutofillId()).isEqualTo(new AutofillId(66));
+ }
+
+ @Test
+ public void testAutofillIdMethods_parentedView() {
+ FrameLayout parent = new FrameLayout(mContext);
+ AutofillId initialParentId = new AutofillId(48);
+ parent.setAutofillId(initialParentId);
+
+ View child = new View(mContext);
+ AutofillId initialChildId = new AutofillId(42);
+ child.setAutofillId(initialChildId);
+
+ parent.addView(child);
+
+ ViewStructureImpl structure = new ViewStructureImpl(child);
+ ViewNode node = structure.getNode();
+
+ assertThat(node.getAutofillId()).isEqualTo(initialChildId);
+ assertThat(node.getParentAutofillId()).isEqualTo(initialParentId);
+
+ AutofillId newChildId = new AutofillId(108);
+ structure.setAutofillId(newChildId);
+ assertThat(node.getAutofillId()).isEqualTo(newChildId);
+ assertThat(node.getParentAutofillId()).isEqualTo(initialParentId);
+
+ AutofillId newParentId = new AutofillId(15162342);
+ parent.setAutofillId(newParentId);
+ assertThat(node.getAutofillId()).isEqualTo(newChildId);
+ assertThat(node.getParentAutofillId()).isEqualTo(initialParentId);
+
+ structure.setAutofillId(new AutofillId(66), 6);
+ assertThat(node.getAutofillId()).isEqualTo(new AutofillId(66, 6));
+ assertThat(node.getParentAutofillId()).isEqualTo(new AutofillId(66));
+ }
+
+ @Test
+ public void testAutofillIdMethods_explicitIdsConstructor() {
+ AutofillId initialParentId = new AutofillId(42);
+ ViewStructureImpl structure = new ViewStructureImpl(initialParentId, 108, 666);
+ ViewNode node = structure.getNode();
+
+ assertThat(node.getAutofillId()).isEqualTo(new AutofillId(initialParentId, 108, 666));
+ assertThat(node.getParentAutofillId()).isEqualTo(initialParentId);
+
+ AutofillId newChildId = new AutofillId(108);
+ structure.setAutofillId(newChildId);
+ assertThat(node.getAutofillId()).isEqualTo(newChildId);
+ assertThat(node.getParentAutofillId()).isEqualTo(initialParentId);
+
+ structure.setAutofillId(new AutofillId(66), 6);
+ assertThat(node.getAutofillId()).isEqualTo(new AutofillId(66, 6));
+ assertThat(node.getParentAutofillId()).isEqualTo(new AutofillId(66));
+ }
+
+ @Test
+ public void testInvalidSetters() {
+ View view = new View(mContext);
+ AutofillId initialId = new AutofillId(42);
+ view.setAutofillId(initialId);
+
+ ViewStructureImpl structure = new ViewStructureImpl(view);
+ ViewNode node = structure.getNode();
+ assertThat(node.getAutofillId()).isEqualTo(initialId); // sanity check
+
+ assertThrows(NullPointerException.class, () -> structure.setAutofillId(null));
+ assertThat(node.getAutofillId()).isEqualTo(initialId); // invariant
+
+ assertThrows(NullPointerException.class, () -> structure.setAutofillId(null, 666));
+ assertThat(node.getAutofillId()).isEqualTo(initialId); // invariant
+
+ assertThrows(NullPointerException.class, () -> structure.setTextIdEntry(null));
+ assertThat(node.getTextIdEntry()).isNull();
+ }
+
+ @Test
+ public void testValidProperties_directly() {
+ ViewStructureImpl structure = newSimpleStructure();
+ assertSimpleStructure(structure);
+ assertSimpleNode(structure.getNode());
+ }
+
+ @Test
+ public void testValidProperties_throughParcel() {
+ ViewStructureImpl structure = newSimpleStructure();
+ final ViewNode node = structure.getNode();
+ assertSimpleNode(node); // sanity check
+
+ final ViewNode clone = cloneThroughParcel(node);
+ assertSimpleNode(clone);
+ }
+
+ @Test
+ public void testComplexText_directly() {
+ ViewStructureImpl structure = newStructureWithComplexText();
+ assertStructureWithComplexText(structure);
+ assertNodeWithComplexText(structure.getNode());
+ }
+
+ @Test
+ public void testComplexText_throughParcel() {
+ ViewStructureImpl structure = newStructureWithComplexText();
+ final ViewNode node = structure.getNode();
+ assertNodeWithComplexText(node); // sanity check
+
+ ViewNode clone = cloneThroughParcel(node);
+ assertNodeWithComplexText(clone);
+ }
+
+ @Test
+ public void testVisibility() {
+ // Visibility is a special case becase it use flag masks, so we want to make sure it works
+ // fine
+ View view = new View(mContext);
+ ViewStructureImpl structure = new ViewStructureImpl(view);
+ ViewNode node = structure.getNode();
+
+ structure.setVisibility(View.VISIBLE);
+ assertThat(node.getVisibility()).isEqualTo(View.VISIBLE);
+ assertThat(cloneThroughParcel(node).getVisibility()).isEqualTo(View.VISIBLE);
+
+ structure.setVisibility(View.GONE);
+ assertThat(node.getVisibility()).isEqualTo(View.GONE);
+ assertThat(cloneThroughParcel(node).getVisibility()).isEqualTo(View.GONE);
+
+ structure.setVisibility(View.VISIBLE);
+ assertThat(node.getVisibility()).isEqualTo(View.VISIBLE);
+ assertThat(cloneThroughParcel(node).getVisibility()).isEqualTo(View.VISIBLE);
+
+ structure.setVisibility(View.INVISIBLE);
+ assertThat(node.getVisibility()).isEqualTo(View.INVISIBLE);
+ assertThat(cloneThroughParcel(node).getVisibility()).isEqualTo(View.INVISIBLE);
+
+ structure.setVisibility(View.INVISIBLE | View.GONE);
+ assertThat(node.getVisibility()).isEqualTo(View.INVISIBLE | View.GONE);
+ assertThat(cloneThroughParcel(node).getVisibility()).isEqualTo(View.INVISIBLE | View.GONE);
+
+
+ final int invalidValue = Math.max(Math.max(View.VISIBLE, View.INVISIBLE), View.GONE) * 2;
+ structure.setVisibility(View.VISIBLE);
+ structure.setVisibility(invalidValue); // should be ignored
+ assertThat(node.getVisibility()).isEqualTo(View.VISIBLE);
+ assertThat(cloneThroughParcel(node).getVisibility()).isEqualTo(View.VISIBLE);
+
+ structure.setVisibility(View.GONE | invalidValue);
+ assertThat(node.getVisibility()).isEqualTo(View.GONE);
+ assertThat(cloneThroughParcel(node).getVisibility()).isEqualTo(View.GONE);
+ }
+
+ /**
+ * Creates a {@link ViewStructureImpl} that can be asserted through
+ * {@link #assertSimpleNode(ViewNode)}.
+ */
+ private ViewStructureImpl newSimpleStructure() {
+ View view = new View(mContext);
+ view.setAutofillId(new AutofillId(42));
+
+ ViewStructureImpl structure = new ViewStructureImpl(view);
+
+ // Basic properties
+ structure.setText("Text is set!");
+ structure.setClassName("Classy!");
+ structure.setContentDescription("Described I am!");
+ structure.setVisibility(View.INVISIBLE);
+
+ // Autofill properties
+ structure.setAutofillType(View.AUTOFILL_TYPE_TEXT);
+ structure.setAutofillHints(new String[] { "Auto", "Man" });
+ structure.setAutofillOptions(new String[] { "Maybe" });
+ structure.setAutofillValue(AutofillValue.forText("Malkovich"));
+
+ // Extra text properties
+ structure.setMinTextEms(6);
+ structure.setMaxTextLength(66);
+ structure.setMaxTextEms(666);
+ structure.setInputType(42);
+ structure.setTextIdEntry("TEXT, Y U NO ENTRY?");
+ structure.setLocaleList(new LocaleList(Locale.US, Locale.ENGLISH));
+
+ // Resource id
+ structure.setId(16, "package.name", "type.name", "entry.name");
+
+ // Dimensions
+ structure.setDimens(4, 8, 15, 16, 23, 42);
+
+ // Boolean properties
+ structure.setAssistBlocked(true);
+ structure.setEnabled(true);
+ structure.setClickable(true);
+ structure.setLongClickable(true);
+ structure.setContextClickable(true);
+ structure.setFocusable(true);
+ structure.setFocused(true);
+ structure.setAccessibilityFocused(true);
+ structure.setChecked(true);
+ structure.setActivated(true);
+ structure.setOpaque(true);
+
+ // Bundle
+ assertThat(structure.hasExtras()).isFalse();
+ final Bundle bundle = structure.getExtras();
+ assertThat(bundle).isNotNull();
+ bundle.putString("Marlon", "Bundle");
+ assertThat(structure.hasExtras()).isTrue();
+ return structure;
+ }
+
+ /**
+ * Asserts the properties of a {@link ViewNode} that was created by
+ * {@link #newSimpleStructure()}.
+ */
+ private void assertSimpleNode(ViewNode node) {
+
+ // Basic properties
+ assertThat(node.getAutofillId()).isEqualTo(new AutofillId(42));
+ assertThat(node.getParentAutofillId()).isNull();
+ assertThat(node.getText()).isEqualTo("Text is set!");
+ assertThat(node.getClassName()).isEqualTo("Classy!");
+ assertThat(node.getContentDescription().toString()).isEqualTo("Described I am!");
+ assertThat(node.getVisibility()).isEqualTo(View.INVISIBLE);
+
+ // Autofill properties
+ assertThat(node.getAutofillType()).isEqualTo(View.AUTOFILL_TYPE_TEXT);
+ assertThat(node.getAutofillHints()).asList().containsExactly("Auto", "Man").inOrder();
+ assertThat(node.getAutofillOptions()).asList().containsExactly("Maybe").inOrder();
+ assertThat(node.getAutofillValue().getTextValue()).isEqualTo("Malkovich");
+
+ // Extra text properties
+ assertThat(node.getMinTextEms()).isEqualTo(6);
+ assertThat(node.getMaxTextLength()).isEqualTo(66);
+ assertThat(node.getMaxTextEms()).isEqualTo(666);
+ assertThat(node.getInputType()).isEqualTo(42);
+ assertThat(node.getTextIdEntry()).isEqualTo("TEXT, Y U NO ENTRY?");
+ assertThat(node.getLocaleList()).isEqualTo(new LocaleList(Locale.US, Locale.ENGLISH));
+
+ // Resource id
+ assertThat(node.getId()).isEqualTo(16);
+ assertThat(node.getIdPackage()).isEqualTo("package.name");
+ assertThat(node.getIdType()).isEqualTo("type.name");
+ assertThat(node.getIdEntry()).isEqualTo("entry.name");
+
+ // Dimensions
+ assertThat(node.getLeft()).isEqualTo(4);
+ assertThat(node.getTop()).isEqualTo(8);
+ assertThat(node.getScrollX()).isEqualTo(15);
+ assertThat(node.getScrollY()).isEqualTo(16);
+ assertThat(node.getWidth()).isEqualTo(23);
+ assertThat(node.getHeight()).isEqualTo(42);
+
+ // Boolean properties
+ assertThat(node.isAssistBlocked()).isTrue();
+ assertThat(node.isEnabled()).isTrue();
+ assertThat(node.isClickable()).isTrue();
+ assertThat(node.isLongClickable()).isTrue();
+ assertThat(node.isContextClickable()).isTrue();
+ assertThat(node.isFocusable()).isTrue();
+ assertThat(node.isFocused()).isTrue();
+ assertThat(node.isAccessibilityFocused()).isTrue();
+ assertThat(node.isChecked()).isTrue();
+ assertThat(node.isActivated()).isTrue();
+ assertThat(node.isOpaque()).isTrue();
+
+ // Bundle
+ final Bundle bundle = node.getExtras();
+ assertThat(bundle).isNotNull();
+ assertThat(bundle.size()).isEqualTo(1);
+ assertThat(bundle.getString("Marlon")).isEqualTo("Bundle");
+ }
+
+ /**
+ * Asserts the properties of a {@link ViewStructureImpl} that was created by
+ * {@link #newSimpleStructure()}.
+ */
+ private void assertSimpleStructure(ViewStructureImpl structure) {
+ assertThat(structure.getAutofillId()).isEqualTo(new AutofillId(42));
+ assertThat(structure.getText()).isEqualTo("Text is set!");
+
+ // Bundle
+ final Bundle bundle = structure.getExtras();
+ assertThat(bundle.size()).isEqualTo(1);
+ assertThat(bundle.getString("Marlon")).isEqualTo("Bundle");
+ }
+
+ /**
+ * Creates a {@link ViewStructureImpl} with "complex" text properties (such as selection); it
+ * can be asserted through {@link #assertNodeWithComplexText(ViewNode)}.
+ */
+ private ViewStructureImpl newStructureWithComplexText() {
+ View view = new View(mContext);
+ ViewStructureImpl structure = new ViewStructureImpl(view);
+ structure.setText("IGNORE ME!");
+ structure.setText("Now we're talking!", 4, 8);
+ structure.setHint("Soylent Green is SPOILER ALERT");
+ structure.setTextStyle(15.0f, 16, 23, 42);
+ structure.setTextLines(new int[] {4, 8, 15} , new int[] {16, 23, 42});
+ return structure;
+ }
+
+ /**
+ * Asserts the properties of a {@link ViewNode} that was created by
+ * {@link #newStructureWithComplexText()}.
+ */
+ private void assertNodeWithComplexText(ViewNode node) {
+ assertThat(node.getText()).isEqualTo("Now we're talking!");
+ assertThat(node.getTextSelectionStart()).isEqualTo(4);
+ assertThat(node.getTextSelectionEnd()).isEqualTo(8);
+ assertThat(node.getHint()).isEqualTo("Soylent Green is SPOILER ALERT");
+ assertThat(node.getTextSize()).isWithin(1.0e-10f).of(15.0f);
+ assertThat(node.getTextColor()).isEqualTo(16);
+ assertThat(node.getTextBackgroundColor()).isEqualTo(23);
+ assertThat(node.getTextStyle()).isEqualTo(42);
+ assertThat(node.getTextLineCharOffsets()).asList().containsExactly(4, 8, 15).inOrder();
+ assertThat(node.getTextLineBaselines()).asList().containsExactly(16, 23, 42).inOrder();
+ }
+
+ /**
+ * Asserts the properties of a {@link ViewStructureImpl} that was created by
+ * {@link #newStructureWithComplexText()}.
+ */
+ private void assertStructureWithComplexText(ViewStructureImpl structure) {
+ assertThat(structure.getText()).isEqualTo("Now we're talking!");
+ assertThat(structure.getTextSelectionStart()).isEqualTo(4);
+ assertThat(structure.getTextSelectionEnd()).isEqualTo(8);
+ assertThat(structure.getHint()).isEqualTo("Soylent Green is SPOILER ALERT");
+ }
+
+ private ViewNode cloneThroughParcel(ViewNode node) {
+ Parcel parcel = Parcel.obtain();
+
+ try {
+ // Write to parcel
+ parcel.setDataPosition(0); // Sanity / paranoid check
+ ViewNode.writeToParcel(parcel, node, 0);
+
+ // Read from parcel
+ parcel.setDataPosition(0);
+ ViewNode clone = ViewNode.readFromParcel(parcel);
+ assertThat(clone).isNotNull();
+ return clone;
+ } finally {
+ parcel.recycle();
+ }
+ }
+}
diff --git a/tests/fragment/Android.bp b/tests/fragment/Android.bp
new file mode 100644
index 0000000..64a4486
--- /dev/null
+++ b/tests/fragment/Android.bp
@@ -0,0 +1,47 @@
+// Copyright (C) 2016 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.
+
+android_test {
+ name: "CtsFragmentTestCases",
+ defaults: ["cts_defaults"],
+
+ dex_preopt: {
+ enabled: false,
+ },
+
+ optimize: {
+ enabled: false,
+ },
+
+ static_libs: [
+ "android-support-test",
+ "mockito-target-minus-junit4",
+ "android-common",
+ "compatibility-device-util",
+ "ctstestrunner",
+ ],
+ libs: ["android.test.base.stubs"],
+
+ srcs: ["src/**/*.java"],
+
+ // Tag this module as a cts test artifact
+ test_suites: [
+ "cts",
+ "vts",
+ "general-tests",
+ "cts_instant",
+ ],
+
+ sdk_version: "test_current",
+}
diff --git a/tests/fragment/Android.mk b/tests/fragment/Android.mk
deleted file mode 100644
index 94a4d91..0000000
--- a/tests/fragment/Android.mk
+++ /dev/null
@@ -1,49 +0,0 @@
-# Copyright (C) 2016 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)
-
-LOCAL_PACKAGE_NAME := CtsFragmentTestCases
-
-# don't include this package in any target
-LOCAL_MODULE_TAGS := tests
-
-# and when built explicitly put it in the data partition
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_DEX_PREOPT := false
-
-LOCAL_PROGUARD_ENABLED := disabled
-
-LOCAL_STATIC_JAVA_LIBRARIES += \
- android-support-test \
- mockito-target-minus-junit4 \
- android-common \
- compatibility-device-util \
- ctstestrunner
-LOCAL_JAVA_LIBRARIES := android.test.base.stubs
-#LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util android-support-test
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_CTS_PACKAGE)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/fragment/TEST_MAPPING b/tests/fragment/TEST_MAPPING
new file mode 100644
index 0000000..a5be057
--- /dev/null
+++ b/tests/fragment/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "presubmit": [
+ {
+ "name": "CtsFragmentTestCases"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/tests/fragment/sdk26/Android.bp b/tests/fragment/sdk26/Android.bp
new file mode 100644
index 0000000..303c3cd
--- /dev/null
+++ b/tests/fragment/sdk26/Android.bp
@@ -0,0 +1,36 @@
+// Copyright (C) 2016 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.
+
+android_test {
+ name: "CtsFragmentTestCasesSdk26",
+ defaults: ["cts_defaults"],
+
+ optimize: {
+ enabled: false,
+ },
+
+ static_libs: ["android-support-test"],
+
+ srcs: ["src/**/*.java"],
+
+ // Tag this module as a cts test artifact
+ test_suites: [
+ "cts",
+ "vts",
+ "general-tests",
+ "cts_instant",
+ ],
+
+ sdk_version: "26",
+}
diff --git a/tests/fragment/sdk26/Android.mk b/tests/fragment/sdk26/Android.mk
deleted file mode 100644
index 5947137..0000000
--- a/tests/fragment/sdk26/Android.mk
+++ /dev/null
@@ -1,40 +0,0 @@
-# Copyright (C) 2016 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)
-
-LOCAL_PACKAGE_NAME := CtsFragmentTestCasesSdk26
-
-# don't include this package in any target
-LOCAL_MODULE_TAGS := tests
-
-# and when built explicitly put it in the data partition
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_DEX_PREOPT := false
-
-LOCAL_PROGUARD_ENABLED := disabled
-
-LOCAL_STATIC_JAVA_LIBRARIES += android-support-test
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
-
-LOCAL_SDK_VERSION := 26
-
-include $(BUILD_CTS_PACKAGE)
diff --git a/tests/fragment/sdk26/TEST_MAPPING b/tests/fragment/sdk26/TEST_MAPPING
new file mode 100644
index 0000000..28bdfed
--- /dev/null
+++ b/tests/fragment/sdk26/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "presubmit": [
+ {
+ "name": "CtsFragmentTestCasesSdk26"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/tests/framework/base/activitymanager/appPrereleaseSdk/fake-framework/res/values/values.xml b/tests/framework/base/activitymanager/appPrereleaseSdk/fake-framework/res/values/values.xml
index 04cace4..5085834 100644
--- a/tests/framework/base/activitymanager/appPrereleaseSdk/fake-framework/res/values/values.xml
+++ b/tests/framework/base/activitymanager/appPrereleaseSdk/fake-framework/res/values/values.xml
@@ -37,6 +37,9 @@
<public type="attr" name="targetSdkVersion" id="0x01010270" />
<attr name="targetSdkVersion" format="integer|string" />
+ <public type="attr" name="extractNativeLibs" id="0x10104ea" />
+ <attr name="extractNativeLibs" format="boolean" />
+
<public type="attr" name="compileSdkVersion" id="0x01010572" />
<attr name="compileSdkVersion" format="integer" />
diff --git a/tests/providerui/AndroidTest.xml b/tests/providerui/AndroidTest.xml
index 6a123f6..9ef1d6c 100644
--- a/tests/providerui/AndroidTest.xml
+++ b/tests/providerui/AndroidTest.xml
@@ -16,7 +16,9 @@
<configuration description="Config for CTS Provider UI test cases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="framework" />
- <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <!-- Instant apps cannot access external storage -->
+ <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsProviderUiTestCases.apk" />
diff --git a/tests/sample/AndroidTest.xml b/tests/sample/AndroidTest.xml
index c398ab05..e2a3139 100644
--- a/tests/sample/AndroidTest.xml
+++ b/tests/sample/AndroidTest.xml
@@ -17,6 +17,7 @@
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="misc" />
<option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsSampleDeviceTestCases.apk" />
diff --git a/tests/signature/api-check/build_signature_apk.mk b/tests/signature/api-check/build_signature_apk.mk
index b883d6a..23457d3 100644
--- a/tests/signature/api-check/build_signature_apk.mk
+++ b/tests/signature/api-check/build_signature_apk.mk
@@ -74,6 +74,8 @@
LOCAL_DEX_PREOPT := false
LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
+
include $(BUILD_CTS_PACKAGE)
LOCAL_SIGNATURE_API_FILES :=
diff --git a/tests/signature/api-check/hidden-api-killswitch-debug-class/Android.mk b/tests/signature/api-check/hidden-api-killswitch-debug-class/Android.mk
index 7423448..003eb7f 100644
--- a/tests/signature/api-check/hidden-api-killswitch-debug-class/Android.mk
+++ b/tests/signature/api-check/hidden-api-killswitch-debug-class/Android.mk
@@ -27,4 +27,6 @@
LOCAL_SDK_VERSION := current
LOCAL_STATIC_JAVA_LIBRARIES := cts-api-signature-test
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
+
include $(BUILD_CTS_PACKAGE)
diff --git a/tests/signature/api-check/hidden-api-killswitch-whitelist/Android.mk b/tests/signature/api-check/hidden-api-killswitch-whitelist/Android.mk
index 9364286..5dca9c1 100644
--- a/tests/signature/api-check/hidden-api-killswitch-whitelist/Android.mk
+++ b/tests/signature/api-check/hidden-api-killswitch-whitelist/Android.mk
@@ -27,4 +27,6 @@
LOCAL_SDK_VERSION := current
LOCAL_STATIC_JAVA_LIBRARIES := cts-api-signature-test
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
+
include $(BUILD_CTS_PACKAGE)
diff --git a/tests/signature/api-check/hidden-api-killswitch-wildcard/Android.mk b/tests/signature/api-check/hidden-api-killswitch-wildcard/Android.mk
index 2274762..ab0eef9 100644
--- a/tests/signature/api-check/hidden-api-killswitch-wildcard/Android.mk
+++ b/tests/signature/api-check/hidden-api-killswitch-wildcard/Android.mk
@@ -27,4 +27,6 @@
LOCAL_SDK_VERSION := current
LOCAL_STATIC_JAVA_LIBRARIES := cts-api-signature-test
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
+
include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/alarmclock/src/android/alarmclock/cts/DismissTimerTest.java b/tests/tests/alarmclock/src/android/alarmclock/cts/DismissTimerTest.java
index a4c0d0a..31cb55a 100644
--- a/tests/tests/alarmclock/src/android/alarmclock/cts/DismissTimerTest.java
+++ b/tests/tests/alarmclock/src/android/alarmclock/cts/DismissTimerTest.java
@@ -3,6 +3,7 @@
import android.alarmclock.common.Utils;
import android.content.Context;
import android.media.AudioManager;
+import android.support.test.filters.Suppress;
public class DismissTimerTest extends AlarmClockTestBase {
@@ -27,6 +28,7 @@
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, mSavedVolume, 0);
}
+ @Suppress // b/122662463 - Flaky on AOSP
public void testAll() throws Exception {
assertEquals(Utils.COMPLETION_RESULT, runTest(Utils.TestcaseType.SET_TIMER_FOR_DISMISSAL));
try {
diff --git a/tests/tests/alarmclock/src/android/alarmclock/cts/SetAlarmTest.java b/tests/tests/alarmclock/src/android/alarmclock/cts/SetAlarmTest.java
index a95a1dd..ec1e349 100644
--- a/tests/tests/alarmclock/src/android/alarmclock/cts/SetAlarmTest.java
+++ b/tests/tests/alarmclock/src/android/alarmclock/cts/SetAlarmTest.java
@@ -18,12 +18,14 @@
import android.alarmclock.common.Utils;
import android.alarmclock.common.Utils.TestcaseType;
+import android.support.test.filters.Suppress;
public class SetAlarmTest extends AlarmClockTestBase {
public SetAlarmTest() {
super();
}
+ @Suppress // b/122662463 - Flaky on AOSP
public void testAll() throws Exception {
assertEquals(Utils.COMPLETION_RESULT, runTest(TestcaseType.SET_ALARM));
}
diff --git a/tests/tests/animation/src/android/animation/cts/ObjectAnimatorTest.java b/tests/tests/animation/src/android/animation/cts/ObjectAnimatorTest.java
index 8650b7a..b0718fe 100644
--- a/tests/tests/animation/src/android/animation/cts/ObjectAnimatorTest.java
+++ b/tests/tests/animation/src/android/animation/cts/ObjectAnimatorTest.java
@@ -846,7 +846,7 @@
public void testCachedValues() throws Throwable {
final AnimTarget target = new AnimTarget();
final ObjectAnimator anim = ObjectAnimator.ofFloat(target, "testValue", 100);
- anim.setDuration(200);
+ anim.setDuration(100);
final CountDownLatch twoFramesLatch = new CountDownLatch(2);
mActivityRule.runOnUiThread(() -> {
anim.start();
@@ -865,7 +865,7 @@
});
assertTrue("Animation didn't start in a reasonable time",
- twoFramesLatch.await(200, TimeUnit.MILLISECONDS));
+ twoFramesLatch.await(800, TimeUnit.MILLISECONDS));
mActivityRule.runOnUiThread(() -> {
assertTrue("Start value should readjust to current position",
diff --git a/tests/tests/contactsproviderwipe/AndroidTest.xml b/tests/tests/contactsproviderwipe/AndroidTest.xml
index 7bbb519..d73a717 100644
--- a/tests/tests/contactsproviderwipe/AndroidTest.xml
+++ b/tests/tests/contactsproviderwipe/AndroidTest.xml
@@ -18,6 +18,7 @@
<option name="config-descriptor:metadata" key="component" value="framework" />
<!-- This is a test for apps with READ/WRITE_CONTACTS, which instant apps don't have -->
<option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<option name="not-shardable" value="true" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
diff --git a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
index 969ee21..3ceb414 100644
--- a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
+++ b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
@@ -30,7 +30,6 @@
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.Telephony;
-import android.speech.RecognizerIntent;
import android.telecom.TelecomManager;
import android.test.AndroidTestCase;
@@ -343,6 +342,13 @@
}
}
+ public void testUsageAccessSettings() {
+ PackageManager packageManager = mContext.getPackageManager();
+ if (!packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)) {
+ assertCanBeHandled(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
+ }
+ }
+
public void testPictureInPictureSettings() {
PackageManager packageManager = mContext.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
diff --git a/tests/tests/dynamic_linker/AndroidTest.xml b/tests/tests/dynamic_linker/AndroidTest.xml
index e4fa4cb..58fe8a0 100644
--- a/tests/tests/dynamic_linker/AndroidTest.xml
+++ b/tests/tests/dynamic_linker/AndroidTest.xml
@@ -16,7 +16,7 @@
<configuration description="Config for CTS dynamic linker test cases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="bionic" />
- <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
<option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
diff --git a/tests/tests/graphics/AndroidManifest.xml b/tests/tests/graphics/AndroidManifest.xml
index 76552a1..659c56d 100644
--- a/tests/tests/graphics/AndroidManifest.xml
+++ b/tests/tests/graphics/AndroidManifest.xml
@@ -16,7 +16,8 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="android.graphics.cts">
+ package="android.graphics.cts"
+ android:targetSandboxVersion="2">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
diff --git a/tests/tests/graphics/AndroidTest.xml b/tests/tests/graphics/AndroidTest.xml
index f6eb47f..1fcf520 100644
--- a/tests/tests/graphics/AndroidTest.xml
+++ b/tests/tests/graphics/AndroidTest.xml
@@ -16,6 +16,8 @@
<configuration description="Config for CTS Graphics test cases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="uitoolkit" />
+ <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsGraphicsTestCases.apk" />
diff --git a/tests/tests/jni/Android.mk b/tests/tests/jni/Android.mk
index f0ebe63..7de8b1e 100644
--- a/tests/tests/jni/Android.mk
+++ b/tests/tests/jni/Android.mk
@@ -46,6 +46,8 @@
LOCAL_SDK_VERSION := current
LOCAL_NDK_STL_VARIANT := c++_shared
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
+
include $(BUILD_CTS_PACKAGE)
# Include the associated library's makefile.
diff --git a/tests/tests/jni/TEST_MAPPING b/tests/tests/jni/TEST_MAPPING
new file mode 100644
index 0000000..5d9eea5
--- /dev/null
+++ b/tests/tests/jni/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "presubmit": [
+ {
+ "name": "CtsJniTestCases"
+ }
+ ]
+}
diff --git a/tests/tests/media/res/raw/audio_aac_mono_70kbs_44100hz_aac_mono_70kbs_44100hz.mp4 b/tests/tests/media/res/raw/audio_aac_mono_70kbs_44100hz_aac_mono_70kbs_44100hz.mp4
index 8820340..157c222 100644
--- a/tests/tests/media/res/raw/audio_aac_mono_70kbs_44100hz_aac_mono_70kbs_44100hz.mp4
+++ b/tests/tests/media/res/raw/audio_aac_mono_70kbs_44100hz_aac_mono_70kbs_44100hz.mp4
Binary files differ
diff --git a/tests/tests/media/src/android/media/cts/CodecUtils.java b/tests/tests/media/src/android/media/cts/CodecUtils.java
index ae785b2..15314ef 100644
--- a/tests/tests/media/src/android/media/cts/CodecUtils.java
+++ b/tests/tests/media/src/android/media/cts/CodecUtils.java
@@ -54,6 +54,8 @@
for (int i = 0; i < planes.length; i++) {
mPlanes[i] = new PlaneWrapper(planes[i]);
}
+
+ setCropRect(image.getCropRect());
}
public static ImageWrapper createFromImage(Image image) {
diff --git a/tests/tests/media/src/android/media/cts/DecodeAccuracyTestBase.java b/tests/tests/media/src/android/media/cts/DecodeAccuracyTestBase.java
index 72eddf1..5704b70 100644
--- a/tests/tests/media/src/android/media/cts/DecodeAccuracyTestBase.java
+++ b/tests/tests/media/src/android/media/cts/DecodeAccuracyTestBase.java
@@ -1122,20 +1122,22 @@
public void release() {
looper.quit();
- if (eglDisplay != EGL10.EGL_NO_DISPLAY) {
- egl10.eglMakeCurrent(eglDisplay,
- EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
- egl10.eglDestroySurface(eglDisplay, eglSurface);
- egl10.eglDestroyContext(eglDisplay, eglContext);
- egl10.eglTerminate(eglDisplay);
- }
- eglDisplay = EGL10.EGL_NO_DISPLAY;
- eglContext = EGL10.EGL_NO_CONTEXT;
- eglSurface = EGL10.EGL_NO_SURFACE;
surface.release();
surfaceTexture.release();
byteBufferIsReady = false;
byteBuffer = null;
+ if (eglDisplay != EGL10.EGL_NO_DISPLAY) {
+ egl10.eglMakeCurrent(eglDisplay,
+ EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
+ egl10.eglDestroySurface(eglDisplay, eglSurface);
+ egl10.eglDestroyContext(eglDisplay, eglContext);
+ //TODO: uncomment following line after fixing crash in GL driver libGLESv2_adreno.so
+ //TODO: see b/123755902
+ //egl10.eglTerminate(eglDisplay);
+ }
+ eglDisplay = EGL10.EGL_NO_DISPLAY;
+ eglContext = EGL10.EGL_NO_CONTEXT;
+ eglSurface = EGL10.EGL_NO_SURFACE;
}
/* Makes our EGL context and surface current. */
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecListTest.java b/tests/tests/media/src/android/media/cts/MediaCodecListTest.java
index 648cf26..4ff7274 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecListTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecListTest.java
@@ -34,10 +34,14 @@
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import static android.media.MediaCodecInfo.CodecCapabilities.FEATURE_SecurePlayback;
+import static android.media.MediaCodecInfo.CodecCapabilities.FEATURE_TunneledPlayback;
+
@SmallTest
@RequiresDevice
public class MediaCodecListTest extends AndroidTestCase {
@@ -452,6 +456,9 @@
CodecCapabilities cap = info.getCapabilitiesForType(types[j]);
AudioCapabilities audioCap = cap.getAudioCapabilities();
if (audioCap == null) {
+ assertFalse("no audio capabilities for audio media type " + types[j] + " of "
+ + info.getName(),
+ types[j].toLowerCase().startsWith("audio/"));
continue;
}
int n = audioCap.getMaxInputChannelCount();
@@ -460,4 +467,263 @@
}
}
}
+
+ private void testCanonicalCodecIsNotAnAlias(String canonicalName) {
+ // canonical name must point to a non-alias
+ for (MediaCodecInfo canonical : mAllInfos) {
+ if (canonical.getName().equals(canonicalName)) {
+ assertFalse(canonical.isAlias());
+ return;
+ }
+ }
+ fail("could not find info to canonical name '" + canonicalName + "'");
+ }
+
+ private String getCustomPartOfComponentName(MediaCodecInfo info) {
+ String name = info.getName();
+ if (name.startsWith("OMX.") || name.startsWith("c2.")) {
+ // strip off OMX.<vendor_name>.
+ return name.replaceFirst("^OMX\\.([^.]+)\\.", "");
+ }
+ return name;
+ }
+
+ private void testKindInCodecNamesIsMeaningful(MediaCodecInfo info) {
+ String name = getCustomPartOfComponentName(info);
+ // codec names containing 'encoder' or 'enc' must be encoders, 'decoder' or 'dec' must
+ // be decoders
+ if (name.matches("(?i)\\b(encoder|enc)\\b")) {
+ assertTrue(info.isEncoder());
+ }
+ if (name.matches("(?i)\\b(decoder|dec)\\b")) {
+ assertFalse(info.isEncoder());
+ }
+ }
+
+ private void testMediaTypeInCodecNamesIsMeaningful(MediaCodecInfo info) {
+ // Codec names containing media type names must support that media type
+ String name = getCustomPartOfComponentName(info);
+
+ Set<String> supportedTypes = new HashSet<String>(Arrays.asList(info.getSupportedTypes()));
+
+ // video types
+ if (name.matches("(?i)\\b(mp(eg)?2)\\b")) {
+ // this may refer to audio mpeg1-layer2 or video mpeg2
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_VIDEO_MPEG2)
+ || supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_MPEG + "-L2"));
+ }
+ if (name.matches("(?i)\\b(h\\.?263)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_VIDEO_H263));
+ }
+ if (name.matches("(?i)\\b(mp(eg)?4)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_VIDEO_MPEG4));
+ }
+ if (name.matches("(?i)\\b(h\\.?264|avc)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_VIDEO_AVC));
+ }
+ if (name.matches("(?i)\\b(vp8)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_VIDEO_VP8));
+ }
+ if (name.matches("(?i)\\b(h\\.?265|hevc)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_VIDEO_HEVC));
+ }
+ if (name.matches("(?i)\\b(vp9)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_VIDEO_VP9));
+ }
+ if (name.matches("(?i)\\b(av0?1)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_VIDEO_AV1));
+ }
+
+ // audio types
+ if (name.matches("(?i)\\b(mp(eg)?3)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_MPEG));
+ }
+ if (name.matches("(?i)\\b(x?aac)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_AAC));
+ }
+ if (name.matches("(?i)\\b(pcm)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_RAW));
+ }
+ if (name.matches("(?i)\\b(raw)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_RAW)
+ || supportedTypes.contains(MediaFormat.MIMETYPE_VIDEO_RAW));
+ }
+ if (name.matches("(?i)\\b(amr)\\b")) {
+ if (name.matches("(?i)\\b(nb)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_AMR_NB));
+ } else if (name.matches("(?i)\\b(wb)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_AMR_WB));
+ } else {
+ assertTrue(
+ supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_AMR_NB)
+ || supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_AMR_WB));
+ }
+ }
+ if (name.matches("(?i)\\b(opus)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_OPUS));
+ }
+ if (name.matches("(?i)\\b(vorbis)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_VORBIS));
+ }
+ if (name.matches("(?i)\\b(flac)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_FLAC));
+ }
+ if (name.matches("(?i)\\b(ac3)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_AC3));
+ }
+ if (name.matches("(?i)\\b(ac4)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_AC4));
+ }
+ if (name.matches("(?i)\\b(eac3)\\b")) {
+ assertTrue(supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_EAC3)
+ || supportedTypes.contains(MediaFormat.MIMETYPE_AUDIO_EAC3_JOC));
+ }
+ }
+
+ public void testCodecCharacterizations() {
+ for (MediaCodecInfo info : mAllInfos) {
+ Log.d(TAG, "codec: " + info.getName() + " canonical: " + info.getCanonicalName());
+
+ // AOSP codecs must not be marked as vendor or hardware accelerated
+ if (info.getName().startsWith("OMX.google.")) {
+ assertFalse(info.isVendor());
+ assertFalse(info.isHardwareAccelerated());
+ }
+
+ // Codec 2.0 based AOSP codecs must run in a software-only process
+ if (info.getName().startsWith("c2.android.")) {
+ assertTrue(info.isSoftwareOnly());
+ assertFalse(info.isVendor());
+ assertFalse(info.isHardwareAccelerated());
+ }
+
+ // validate aliases
+ if (info.isAlias()) {
+ assertFalse(info.getName().equals(info.getCanonicalName()));
+ testCanonicalCodecIsNotAnAlias(info.getCanonicalName());
+ } else {
+ // validate codec names: (Canonical) codec names must be meaningful.
+ // We only test this on canonical infos as we allow aliases to support
+ // existing codec names that do not fit this.
+ assertEquals(info.getName(), info.getCanonicalName());
+ testKindInCodecNamesIsMeaningful(info);
+ testMediaTypeInCodecNamesIsMeaningful(info);
+ }
+
+ // hardware accelerated codecs cannot be software only
+ assertFalse(info.isHardwareAccelerated() && info.isSoftwareOnly());
+ }
+ }
+
+ public void testVideoPerformancePointsSanity() {
+ MediaFormat hd25Format =
+ MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 1280, 720);
+ hd25Format.setFloat(MediaFormat.KEY_FRAME_RATE, 25.f);
+
+ MediaFormat portraitHd240Format =
+ MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 720, 1280);
+ portraitHd240Format.setInteger(MediaFormat.KEY_FRAME_RATE, 240);
+
+ assertTrue(VideoCapabilities.PerformancePoint.HD_30.covers(hd25Format));
+ assertTrue(VideoCapabilities.PerformancePoint.HD_25.covers(hd25Format));
+ assertFalse(VideoCapabilities.PerformancePoint.HD_24.covers(hd25Format));
+ assertTrue(VideoCapabilities.PerformancePoint.FHD_30.covers(hd25Format));
+ assertTrue(VideoCapabilities.PerformancePoint.FHD_25.covers(hd25Format));
+ assertFalse(VideoCapabilities.PerformancePoint.FHD_24.covers(hd25Format));
+
+ assertTrue(VideoCapabilities.PerformancePoint.HD_240.covers(portraitHd240Format));
+ assertFalse(VideoCapabilities.PerformancePoint.HD_200.covers(portraitHd240Format));
+ assertTrue(VideoCapabilities.PerformancePoint.FHD_240.covers(portraitHd240Format));
+ assertFalse(VideoCapabilities.PerformancePoint.FHD_200.covers(portraitHd240Format));
+ }
+
+ public void verifyPerformancePoints(
+ MediaCodecInfo info, String mediaType,
+ List<VideoCapabilities.PerformancePoint> points) {
+ // TODO: verify performance points listed conform to the requirements ... once those
+ // requirements are agreed upon.
+ }
+
+ public void testAllHardwareAcceleratedVideoCodecsPublishPerformancePoints() {
+ List<String> mandatoryTypes = Arrays.asList(
+ MediaFormat.MIMETYPE_VIDEO_AVC,
+ MediaFormat.MIMETYPE_VIDEO_VP8,
+ MediaFormat.MIMETYPE_VIDEO_DOLBY_VISION,
+ MediaFormat.MIMETYPE_VIDEO_HEVC,
+ MediaFormat.MIMETYPE_VIDEO_VP9,
+ MediaFormat.MIMETYPE_VIDEO_AV1);
+
+ String[] featuresToConfig = new String[] {
+ FEATURE_SecurePlayback,
+ FEATURE_TunneledPlayback,
+ };
+
+ for (MediaCodecInfo info : mAllInfos) {
+ String[] types = info.getSupportedTypes();
+ for (int j = 0; j < types.length; ++j) {
+ CodecCapabilities cap = info.getCapabilitiesForType(types[j]);
+ MediaFormat defaultFormat = cap.getDefaultFormat();
+ VideoCapabilities videoCap = cap.getVideoCapabilities();
+
+ Log.d(TAG, "codec: " + info.getName() + " canonical: " + info.getCanonicalName()
+ + " type: " + types[j]);
+
+ if (videoCap == null) {
+ assertFalse("no video capabilities for video media type " + types[j] + " of "
+ + info.getName(),
+ types[j].toLowerCase().startsWith("video/"));
+ continue;
+ }
+
+ List<VideoCapabilities.PerformancePoint> pps =
+ videoCap.getSupportedPerformancePoints();
+
+ // see which feature combinations are supported by this codec
+ // we do this by counting in binary up to a number of bits
+ List<Integer> supportedFeatureConfigs = new ArrayList<Integer>();
+ for (int cfg_ix = 1 << featuresToConfig.length; --cfg_ix >= 0; ) {
+ boolean supported = true;
+ for (int f_ix = 0; supported && f_ix < featuresToConfig.length; ++f_ix) {
+ if (((cfg_ix >> f_ix) & 1) != 0) {
+ // feature is to be enabled
+ supported = supported && cap.isFeatureSupported(featuresToConfig[f_ix]);
+ } else {
+ // feature is not to be enabled
+ supported = supported && !cap.isFeatureRequired(featuresToConfig[f_ix]);
+ }
+ }
+ if (supported) {
+ supportedFeatureConfigs.add(cfg_ix);
+ }
+ }
+ int[] supportedFeatureConfigsArray =
+ supportedFeatureConfigs.stream().mapToInt(Integer::intValue).toArray();
+
+ Log.d(TAG, "codec supports configs "
+ + Arrays.toString(supportedFeatureConfigsArray));
+ if (pps == null) {
+ // Hardware-accelerated video components must publish performance points,
+ // even if it is an empty list.
+ assertFalse("HW-accelerated codec '" + info.getName()
+ + "' must publish performance points", info.isHardwareAccelerated());
+
+ continue;
+ }
+
+ // At least one hardware accelerated codec for each media type (including secure
+ // codecs) must publish valid performance points for AVC/VP8/VP9/HEVC/AV1.
+ if (pps.size() == 0) {
+ if (mandatoryTypes.contains(types[j])) {
+ Log.d(TAG, "empty performance points list published by HW accelerated" +
+ "component " + info.getName() + " for " + types[j]);
+ }
+ } else {
+ for (VideoCapabilities.PerformancePoint p : pps) {
+ Log.d(TAG, "got performance point "
+ + p.width + " x " + p.height + " x " + p.frameRate);
+ }
+ }
+ }
+ }
+ }
}
diff --git a/tests/tests/media/src/android/media/cts/MediaFormatTest.java b/tests/tests/media/src/android/media/cts/MediaFormatTest.java
new file mode 100644
index 0000000..2beae2b
--- /dev/null
+++ b/tests/tests/media/src/android/media/cts/MediaFormatTest.java
@@ -0,0 +1,638 @@
+/*
+ * Copyright (C) 2018 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.media.cts;
+
+import android.media.MediaFormat;
+import android.test.AndroidTestCase;
+
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+public class MediaFormatTest extends AndroidTestCase {
+ private static ByteBuffer defaultByteBuffer = ByteBuffer.allocateDirect(16);
+
+ private void assertGetByteBuffersThrowClassCastException(
+ MediaFormat format, String key, String type) {
+ try {
+ ByteBuffer value = format.getByteBuffer(key);
+ throw new AssertionError("read " + type + " as ByteBuffer " + value);
+ } catch (ClassCastException e) {
+ }
+
+ try {
+ ByteBuffer value = format.getByteBuffer(key, defaultByteBuffer);
+ throw new AssertionError("read " + type + " with default as ByteBuffer " + value);
+ } catch (ClassCastException e) {
+ }
+ }
+
+ private void assertGetFloatsThrowClassCastException(
+ MediaFormat format, String key, String type) {
+ try {
+ float value = format.getFloat(key);
+ throw new AssertionError("read " + type + " as float " + value);
+ } catch (ClassCastException e) {
+ }
+
+ try {
+ float value = format.getFloat(key, 321.f);
+ throw new AssertionError("read " + type + " with default as float " + value);
+ } catch (ClassCastException e) {
+ }
+ }
+
+ private void assertGetIntegersThrowClassCastException(
+ MediaFormat format, String key, String type) {
+ try {
+ int value = format.getInteger(key);
+ throw new AssertionError("read " + type + " as int " + value);
+ } catch (ClassCastException e) {
+ }
+
+ try {
+ int value = format.getInteger(key, 123);
+ throw new AssertionError("read " + type + " with default as int " + value);
+ } catch (ClassCastException e) {
+ }
+ }
+
+ private void assertGetLongsThrowClassCastException(
+ MediaFormat format, String key, String type) {
+ try {
+ long value = format.getLong(key);
+ throw new AssertionError("read " + type + " as long " + value);
+ } catch (ClassCastException e) {
+ }
+
+ try {
+ long value = format.getLong(key, 321L);
+ throw new AssertionError("read " + type + " with default as long " + value);
+ } catch (ClassCastException e) {
+ }
+ }
+
+ private void assertGetNumbersThrowClassCastException(
+ MediaFormat format, String key, String type) {
+ try {
+ Number value = format.getNumber(key);
+ throw new AssertionError("read " + type + " as Number " + value);
+ } catch (ClassCastException e) {
+ }
+
+ try {
+ Number value = format.getNumber(key, 321.f);
+ throw new AssertionError("read " + type + " with default as Number " + value);
+ } catch (ClassCastException e) {
+ }
+ }
+
+ private void assertGetStringsThrowClassCastException(
+ MediaFormat format, String key, String type) {
+ try {
+ String value = format.getString(key);
+ throw new AssertionError("read " + type + " as string " + value);
+ } catch (ClassCastException e) {
+ }
+
+ try {
+ String value = format.getString(key, "321");
+ throw new AssertionError("read " + type + " with default as string " + value);
+ } catch (ClassCastException e) {
+ }
+ }
+
+ public void testIntegerValue() throws Exception {
+ MediaFormat format = new MediaFormat();
+ format.setInteger("int", 123);
+
+ assertEquals(123, format.getInteger("int"));
+
+ // We should be able to read int values as numbers.
+ assertEquals(123, format.getNumber("int").intValue());
+ assertEquals(123, format.getNumber("int", 321).intValue());
+
+ // We should not be able to get an integer value as any other type. Instead,
+ // we should receive a ClassCastException
+ assertGetByteBuffersThrowClassCastException(format, "int", "int");
+ assertGetFloatsThrowClassCastException(format, "int", "int");
+ assertGetLongsThrowClassCastException(format, "int", "int");
+ assertGetStringsThrowClassCastException(format, "int", "int");
+
+ // We should not have a feature enabled for an integer value
+ try {
+ boolean value = format.getFeatureEnabled("int");
+ throw new AssertionError("read int as feature " + value);
+ } catch (IllegalArgumentException e) {
+ }
+
+ testSingleKeyRemoval(format, "int", MediaFormat.TYPE_INTEGER);
+ }
+
+ public void testLongValue() throws Exception {
+ MediaFormat format = new MediaFormat();
+ format.setLong("long", 9876543210L);
+
+ assertEquals(9876543210L, format.getLong("long"));
+
+ // We should be able to read long values as numbers.
+ assertEquals(9876543210L, format.getNumber("long").longValue());
+ assertEquals(9876543210L, format.getNumber("long", 9012345678L).longValue());
+
+ // We should not be able to get a long value as any other type. Instead,
+ // we should receive a ClassCastException
+ assertGetByteBuffersThrowClassCastException(format, "long", "long");
+ assertGetFloatsThrowClassCastException(format, "long", "long");
+ assertGetIntegersThrowClassCastException(format, "long", "long");
+ assertGetStringsThrowClassCastException(format, "long", "long");
+
+ // We should not have a feature enabled for a long value
+ try {
+ boolean value = format.getFeatureEnabled("long");
+ throw new AssertionError("read long as feature " + value);
+ } catch (IllegalArgumentException e) {
+ }
+
+ testSingleKeyRemoval(format, "long", MediaFormat.TYPE_LONG);
+ }
+
+ public void testFloatValue() throws Exception {
+ MediaFormat format = new MediaFormat();
+ format.setFloat("float", 3.14f);
+
+ assertEquals(3.14f, format.getFloat("float"));
+
+ // We should be able to read float values as numbers.
+ assertEquals(3.14f, format.getNumber("float").floatValue());
+ assertEquals(3.14f, format.getNumber("float", 2.81f).floatValue());
+
+ // We should not be able to get a float value as any other type. Instead,
+ // we should receive a ClassCastException
+ assertGetByteBuffersThrowClassCastException(format, "float", "float");
+ assertGetIntegersThrowClassCastException(format, "float", "float");
+ assertGetLongsThrowClassCastException(format, "float", "float");
+ assertGetStringsThrowClassCastException(format, "float", "float");
+
+ // We should not have a feature enabled for a float value
+ try {
+ boolean value = format.getFeatureEnabled("float");
+ throw new AssertionError("read float as feature " + value);
+ } catch (IllegalArgumentException e) {
+ }
+
+ testSingleKeyRemoval(format, "float", MediaFormat.TYPE_FLOAT);
+ }
+
+ public void testStringValue() throws Exception {
+ MediaFormat format = new MediaFormat();
+ format.setString("string", "value");
+
+ assertEquals("value", format.getString("string"));
+
+ // We should not be able to get a string value as any other type. Instead,
+ // we should receive a ClassCastException
+ assertGetByteBuffersThrowClassCastException(format, "string", "string");
+ assertGetFloatsThrowClassCastException(format, "string", "string");
+ assertGetIntegersThrowClassCastException(format, "string", "string");
+ assertGetLongsThrowClassCastException(format, "string", "string");
+ assertGetNumbersThrowClassCastException(format, "string", "string");
+
+ // We should not have a feature enabled for an integer value
+ try {
+ boolean value = format.getFeatureEnabled("string");
+ throw new AssertionError("read string as feature " + value);
+ } catch (IllegalArgumentException e) {
+ }
+
+ testSingleKeyRemoval(format, "string", MediaFormat.TYPE_STRING);
+ }
+
+ public void testByteBufferValue() throws Exception {
+ MediaFormat format = new MediaFormat();
+ ByteBuffer buffer = ByteBuffer.allocateDirect(123);
+ format.setByteBuffer("buffer", buffer);
+
+ assertEquals(buffer, format.getByteBuffer("buffer"));
+
+ // We should not be able to get a string value as any other type. Instead,
+ // we should receive a ClassCastException
+ assertGetFloatsThrowClassCastException(format, "buffer", "ByteBuffer");
+ assertGetIntegersThrowClassCastException(format, "buffer", "ByteBuffer");
+ assertGetLongsThrowClassCastException(format, "buffer", "ByteBuffer");
+ assertGetNumbersThrowClassCastException(format, "buffer", "ByteBuffer");
+ assertGetStringsThrowClassCastException(format, "buffer", "ByteBuffer");
+
+ // We should not have a feature enabled for an integer value
+ try {
+ boolean value = format.getFeatureEnabled("buffer");
+ throw new AssertionError("read ByteBuffer as feature " + value);
+ } catch (IllegalArgumentException e) {
+ }
+
+ testSingleKeyRemoval(format, "buffer", MediaFormat.TYPE_BYTE_BUFFER);
+ }
+
+ public void testNullStringValue() throws Exception {
+ MediaFormat format = new MediaFormat();
+ format.setString("null", null);
+ testNullOrMissingValue(format, "null");
+ testSingleKeyRemoval(format, "null", MediaFormat.TYPE_NULL);
+ }
+
+ public void testNullByteBufferValue() throws Exception {
+ MediaFormat format = new MediaFormat();
+ format.setByteBuffer("null", null);
+ testNullOrMissingValue(format, "null");
+ testSingleKeyRemoval(format, "null", MediaFormat.TYPE_NULL);
+ }
+
+ public void testMissingValue() throws Exception {
+ MediaFormat format = new MediaFormat();
+ // null values should be handled the same as missing values
+ assertEquals(MediaFormat.TYPE_NULL, format.getValueTypeForKey("missing"));
+ testNullOrMissingValue(format, "missing");
+ }
+
+ private void testSingleKeyRemoval(
+ MediaFormat format, String key, @MediaFormat.Type int type) {
+ assertEquals(type, format.getValueTypeForKey(key));
+ assertTrue(format.containsKey(key));
+
+ Set<String> keySet = format.getKeys();
+ assertEquals(1, keySet.size());
+ assertTrue(keySet.contains(key));
+
+ format.removeKey(key);
+ assertFalse(format.containsKey(key));
+
+ // test that keySet is connected to the format
+ assertFalse(keySet.contains(key));
+ assertEquals(0, keySet.size());
+ }
+
+ private static Set<String> asSet(String ... values) {
+ return new HashSet<>(Arrays.asList(values));
+ }
+
+ private void assertStringSetEquals(Set<String> set, String ... expected_members) {
+ Set<String> expected = new HashSet<>(Arrays.asList(expected_members));
+ assertEquals(expected, set);
+ }
+
+ public void testKeySetContainsAndRemove() {
+ MediaFormat format = new MediaFormat();
+ format.setInteger("int", 123);
+ format.setLong("long", 9876543210L);
+ format.setFloat("float", 321.f);
+ format.setFeatureEnabled("int", true);
+ format.setFeatureEnabled("long", false);
+ format.setFeatureEnabled("float", true);
+ format.setFeatureEnabled("string", false);
+
+ Set<String> keySet = format.getKeys();
+ // test size and contains
+ assertEquals(3, keySet.size());
+ assertTrue(keySet.contains("int"));
+ assertTrue(keySet.contains("long"));
+ assertTrue(keySet.contains("float"));
+ assertFalse(keySet.contains("string"));
+ assertStringSetEquals(keySet, "int", "long", "float");
+
+ // test adding an element
+ format.setString("string", "value");
+
+ // test that key set reflects format change in size and contains
+ assertEquals(4, keySet.size());
+ assertTrue(keySet.contains("int"));
+ assertTrue(keySet.contains("long"));
+ assertTrue(keySet.contains("float"));
+ assertTrue(keySet.contains("string"));
+
+ // test iterator
+ {
+ Set<String> toFind = asSet("int", "long", "float", "string");
+ Iterator<String> it = keySet.iterator();
+ while (it.hasNext()) {
+ String k = it.next();
+ assertTrue(toFind.remove(k));
+ }
+ assertEquals(0, toFind.size());
+ }
+
+ // remove via format
+ format.removeKey("float");
+
+ // test that key set reflects format change in size and contains
+ assertEquals(3, keySet.size());
+ assertTrue(keySet.contains("int"));
+ assertTrue(keySet.contains("long"));
+ assertFalse(keySet.contains("float"));
+ assertTrue(keySet.contains("string"));
+
+ // re-test iterator after removal
+ {
+ Set<String> toFind = asSet("int", "long", "string");
+ for (String k : keySet) {
+ assertTrue(toFind.remove(k));
+ }
+ assertEquals(0, toFind.size());
+ }
+
+ // test remove
+ keySet.remove("long");
+ assertEquals(2, keySet.size());
+ assertTrue(keySet.contains("int"));
+ assertFalse(keySet.contains("long"));
+ assertFalse(keySet.contains("float"));
+ assertTrue(keySet.contains("string"));
+ assertTrue(format.containsKey("int"));
+ assertFalse(format.containsKey("long"));
+ assertFalse(format.containsKey("float"));
+ assertTrue(format.containsKey("string"));
+
+ // test iterator by its interface as well as its remove
+ {
+ Set<String> toFind = asSet("int", "string");
+ Iterator<String> it = keySet.iterator();
+ while (it.hasNext()) {
+ String k = it.next();
+ assertTrue(toFind.remove(k));
+ if (k.equals("int")) {
+ it.remove();
+ }
+ }
+ assertEquals(0, toFind.size());
+ }
+
+ // test that removing via iterator also removes from format
+ assertEquals(1, keySet.size());
+ assertFalse(keySet.contains("int"));
+ assertFalse(keySet.contains("long"));
+ assertFalse(keySet.contains("float"));
+ assertTrue(keySet.contains("string"));
+ assertFalse(format.containsKey("int"));
+ assertFalse(format.containsKey("long"));
+ assertFalse(format.containsKey("float"));
+ assertTrue(format.containsKey("string"));
+
+ // verify that features are still present
+ assertTrue(format.getFeatureEnabled("int"));
+ assertFalse(format.getFeatureEnabled("long"));
+ assertTrue(format.getFeatureEnabled("float"));
+ assertFalse(format.getFeatureEnabled("string"));
+ }
+
+ public void testFeatureKeySetContainsAndRemove() {
+ MediaFormat format = new MediaFormat();
+ format.setInteger("int", 123);
+ format.setLong("long", 9876543210L);
+ format.setFloat("float", 321.f);
+ format.setString("string", "value");
+ format.setFeatureEnabled("int", true);
+ format.setFeatureEnabled("long", false);
+ format.setFeatureEnabled("float", true);
+
+ Set<String> featureSet = format.getFeatures();
+ // test size and contains
+ assertEquals(3, featureSet.size());
+ assertTrue(featureSet.contains("int"));
+ assertTrue(featureSet.contains("long"));
+ assertTrue(featureSet.contains("float"));
+ assertFalse(featureSet.contains("string"));
+ assertStringSetEquals(featureSet, "int", "long", "float");
+
+ // test adding an element
+ format.setFeatureEnabled("string", false);
+
+ // test that key set reflects format change in size and contains
+ assertEquals(4, featureSet.size());
+ assertTrue(featureSet.contains("int"));
+ assertTrue(featureSet.contains("long"));
+ assertTrue(featureSet.contains("float"));
+ assertTrue(featureSet.contains("string"));
+
+ // test iterator
+ {
+ Set<String> toFind = asSet("int", "long", "float", "string");
+ Iterator<String> it = featureSet.iterator();
+ while (it.hasNext()) {
+ String k = it.next();
+ assertTrue(toFind.remove(k));
+ }
+ assertEquals(0, toFind.size());
+ }
+
+ // test that features cannot be removed via format as keys, even though for backward
+ // compatibility, they can be accessed as integers and can be found via containsKey
+ format.removeKey("feature-float");
+ assertEquals(4, featureSet.size());
+ assertTrue(featureSet.contains("float"));
+
+ format.removeFeature("float");
+
+ // TODO: deprecate this usage
+ assertEquals(1, format.getInteger("feature-int"));
+ assertEquals(0, format.getInteger("feature-long"));
+ assertTrue(format.containsKey("feature-int"));
+
+ // Along these lines also verify that this is not true for the getKeys() set
+ assertFalse(format.getKeys().contains("feature-int"));
+
+ // Also verify that getKeys() cannot be used to remove a feature
+ assertFalse(format.getKeys().remove("feature-int"));
+
+ // test that key set reflects format change in size and contains
+ assertEquals(3, featureSet.size());
+ assertTrue(featureSet.contains("int"));
+ assertTrue(featureSet.contains("long"));
+ assertFalse(featureSet.contains("float"));
+ assertTrue(featureSet.contains("string"));
+
+ // re-test iterator after removal
+ {
+ Set<String> toFind = asSet("int", "long", "string");
+ for (String k : featureSet) {
+ assertTrue(toFind.remove(k));
+ }
+ assertEquals(0, toFind.size());
+ }
+
+ // test remove via set
+ featureSet.remove("long");
+ assertEquals(2, featureSet.size());
+ assertTrue(featureSet.contains("int"));
+ assertFalse(featureSet.contains("long"));
+ assertFalse(featureSet.contains("float"));
+ assertTrue(featureSet.contains("string"));
+
+ assertTrue(format.containsFeature("int"));
+ assertFalse(format.containsFeature("long"));
+ assertFalse(format.containsFeature("float"));
+ assertTrue(format.containsFeature("string"));
+
+ assertTrue(format.getFeatureEnabled("int"));
+ try {
+ format.getFeatureEnabled("long");
+ fail("should not contain feature long");
+ } catch (IllegalArgumentException e) {}
+ try {
+ format.getFeatureEnabled("float");
+ fail("should not contain feature float");
+ } catch (IllegalArgumentException e) {}
+ assertFalse(format.getFeatureEnabled("string"));
+
+ // test iterator by its interface as well as its remove
+ {
+ Set<String> toFind = asSet("int", "string");
+ Iterator<String> it = featureSet.iterator();
+ while (it.hasNext()) {
+ String k = it.next();
+ assertTrue(toFind.remove(k));
+ if (k.equals("int")) {
+ it.remove();
+ }
+ }
+ assertEquals(0, toFind.size());
+ }
+
+ // test that removing via iterator also removes from format
+ assertEquals(1, featureSet.size());
+ assertFalse(featureSet.contains("int"));
+ assertFalse(featureSet.contains("long"));
+ assertFalse(featureSet.contains("float"));
+ assertTrue(featureSet.contains("string"));
+
+ assertFalse(format.containsFeature("int"));
+ assertFalse(format.containsFeature("long"));
+ assertFalse(format.containsFeature("float"));
+ assertTrue(format.containsFeature("string"));
+
+ try {
+ format.getFeatureEnabled("int");
+ fail("should not contain feature int");
+ } catch (IllegalArgumentException e) {}
+ try {
+ format.getFeatureEnabled("long");
+ fail("should not contain feature long");
+ } catch (IllegalArgumentException e) {}
+ try {
+ format.getFeatureEnabled("float");
+ fail("should not contain feature float");
+ } catch (IllegalArgumentException e) {}
+ assertFalse(format.getFeatureEnabled("string"));
+
+ // verify that keys are still present
+ assertEquals(123, format.getInteger("int"));
+ assertEquals(9876543210L, format.getLong("long"));
+ assertEquals(321.f, format.getFloat("float"));
+ assertEquals("value", format.getString("string"));
+ }
+
+ private void testNullOrMissingValue(MediaFormat format, String key) throws Exception {
+ // We should not be able to get a string value as any primitive type. Instead,
+ // we should receive a NullPointerException
+ try {
+ int value = format.getInteger(key);
+ throw new AssertionError("read " + key + " as int " + value);
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ long value = format.getLong(key);
+ throw new AssertionError("read " + key + " as long " + value);
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ float value = format.getFloat(key);
+ throw new AssertionError("read " + key + " as float " + value);
+ } catch (NullPointerException e) {
+ }
+
+ // We should get null for all object types (ByteBuffer, Number, String)
+ assertNull(format.getNumber(key));
+ assertNull(format.getString(key));
+ assertNull(format.getByteBuffer(key));
+
+ // We should get the default value for all getters with default
+ assertEquals(123, format.getInteger(key, 123));
+ assertEquals(321L, format.getLong(key, 321L));
+ assertEquals(321.f, format.getFloat(key, 321.f));
+ assertEquals(321.f, format.getNumber(key, 321.f));
+ assertEquals("value", format.getString(key, "value"));
+ assertEquals(defaultByteBuffer, format.getByteBuffer(key, defaultByteBuffer));
+
+ // We should not have a feature enabled for a null value
+ try {
+ boolean value = format.getFeatureEnabled(key);
+ throw new AssertionError("read " + key + " as feature " + value);
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ public void testMediaFormatConstructors() {
+ MediaFormat format;
+ {
+ format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, 48000, 6);
+ assertEquals(MediaFormat.MIMETYPE_AUDIO_AAC, format.getString(MediaFormat.KEY_MIME));
+ assertEquals(48000, format.getInteger(MediaFormat.KEY_SAMPLE_RATE));
+ assertEquals(6, format.getInteger(MediaFormat.KEY_CHANNEL_COUNT));
+ assertEquals(3, format.getKeys().size());
+ assertEquals(0, format.getFeatures().size());
+ }
+
+ {
+ format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 1920, 1080);
+ assertEquals(MediaFormat.MIMETYPE_VIDEO_AVC, format.getString(MediaFormat.KEY_MIME));
+ assertEquals(1920, format.getInteger(MediaFormat.KEY_WIDTH));
+ assertEquals(1080, format.getInteger(MediaFormat.KEY_HEIGHT));
+ assertEquals(3, format.getKeys().size());
+ assertEquals(0, format.getFeatures().size());
+ }
+
+ {
+ format = MediaFormat.createSubtitleFormat(MediaFormat.MIMETYPE_TEXT_VTT, "und");
+ assertEquals(MediaFormat.MIMETYPE_TEXT_VTT, format.getString(MediaFormat.KEY_MIME));
+ assertEquals("und", format.getString(MediaFormat.KEY_LANGUAGE));
+ assertEquals(2, format.getKeys().size());
+ assertEquals(0, format.getFeatures().size());
+
+ format.setFeatureEnabled("feature1", false);
+
+ // also test dup
+ MediaFormat other = new MediaFormat(format);
+ format.setString(MediaFormat.KEY_LANGUAGE, "un");
+ other.setInteger(MediaFormat.KEY_IS_DEFAULT, 1);
+ other.setFeatureEnabled("feature1", true);
+
+ assertEquals(MediaFormat.MIMETYPE_TEXT_VTT, format.getString(MediaFormat.KEY_MIME));
+ assertEquals("un", format.getString(MediaFormat.KEY_LANGUAGE));
+ assertEquals(2, format.getKeys().size());
+ assertFalse(format.getFeatureEnabled("feature1"));
+ assertEquals(1, format.getFeatures().size());
+
+ assertEquals(MediaFormat.MIMETYPE_TEXT_VTT, other.getString(MediaFormat.KEY_MIME));
+ assertEquals("und", other.getString(MediaFormat.KEY_LANGUAGE));
+ assertEquals(1, other.getInteger(MediaFormat.KEY_IS_DEFAULT));
+ assertEquals(3, other.getKeys().size());
+ assertTrue(other.getFeatureEnabled("feature1"));
+ assertEquals(1, other.getFeatures().size());
+ }
+ }
+}
diff --git a/tests/tests/media/src/android/media/cts/MediaMuxerTest.java b/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
index 0d1796a..c19dba5 100644
--- a/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaMuxerTest.java
@@ -464,9 +464,8 @@
verifyAttributesMatch(srcMedia, outputMediaFile, degrees);
verifyLocationInFile(outputMediaFile);
}
- // Check the sample on 1s and 0.5s.
- verifySamplesMatch(srcMedia, outputMediaFile, 1000000);
- verifySamplesMatch(srcMedia, outputMediaFile, 500000);
+ // Verify timestamp of all samples.
+ verifyTimestampsWithSamplesDropSet(srcMedia, outputMediaFile, null, null);
} finally {
new File(outputMediaFile).delete();
}
@@ -1003,15 +1002,12 @@
}
extractorSrc.selectTrack(videoTrackIndex);
extractorTest.selectTrack(videoTrackIndex);
+ checkVideoSamplesTimeStamps(extractorSrc, extractorTest, samplesDropSet,
+ videoStartOffsetUs);
+ extractorSrc.unselectTrack(videoTrackIndex);
+ extractorTest.unselectTrack(videoTrackIndex);
}
}
- if (videoTrackIndex != -1) {
- checkVideoSamplesTimeStamps(extractorSrc, extractorTest, samplesDropSet,
- videoStartOffsetUs);
- }
-
- extractorSrc.unselectTrack(videoTrackIndex);
- extractorTest.unselectTrack(videoTrackIndex);
int audioTrackIndex = -1;
int audioSampleCount = 0;
@@ -1026,14 +1022,10 @@
}
extractorSrc.selectTrack(audioTrackIndex);
extractorTest.selectTrack(audioTrackIndex);
+ checkAudioSamplesTimestamps(extractorSrc, extractorTest, audioStartOffsetUs);
}
}
- if (audioTrackIndex != -1) {
- // No audio track
- checkAudioSamplesTimestamps(extractorSrc, extractorTest, audioStartOffsetUs);
- }
-
extractorSrc.release();
extractorTest.release();
srcFd.close();
@@ -1057,10 +1049,10 @@
srcSampleTimeUs = extractorSrc.getSampleTime();
testSampleTimeUs = extractorTest.getSampleTime();
if (VERBOSE) {
- Log.d(TAG, "videoSampleCount:" + videoSampleCount);
- Log.d(TAG, "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
+ Log.i(TAG, "videoSampleCount:" + videoSampleCount);
+ Log.i(TAG, "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
" testTrackIndex:" + extractorTest.getSampleTrackIndex());
- Log.d(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
+ Log.i(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
}
if (samplesDropSet == null || !samplesDropSet.contains(videoSampleCount)) {
if (srcSampleTimeUs == -1 || testSampleTimeUs == -1) {
@@ -1114,6 +1106,7 @@
srcSampleTimeUs = extractorSrc.getSampleTime();
testSampleTimeUs = extractorTest.getSampleTime();
if(VERBOSE) {
+ Log.d(TAG, "audioSampleCount:" + audioSampleCount);
Log.v(TAG, "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
" testTrackIndex:" + extractorTest.getSampleTrackIndex());
Log.v(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
@@ -1137,22 +1130,12 @@
else if ((audioSampleCount > 1 &&
(srcSampleTimeUs + audioStartOffsetUs) != testSampleTimeUs) ||
(audioSampleCount == 1 && srcSampleTimeUs != testSampleTimeUs)) {
- if (VERBOSE) {
- Log.d(TAG, "Fail:audio timestamps didn't match");
- Log.d(TAG, "srcTrackIndex:" + extractorSrc.getSampleTrackIndex() +
- " testTrackIndex:" + extractorTest.getSampleTrackIndex());
- Log.d(TAG, "srcTSus:" + srcSampleTimeUs + " testTSus:" + testSampleTimeUs);
- Log.d(TAG, "audioSampleCount:" + audioSampleCount);
- }
fail("audio timestamps didn't match");
}
testAdvance = extractorTest.advance();
srcAdvance = extractorSrc.advance();
} while(srcAdvance && testAdvance);
if (srcAdvance != testAdvance) {
- if (VERBOSE) {
- Log.d(TAG, "audioSampleCount:" + audioSampleCount);
- }
fail("either audio track has not reached its last sample");
}
}
diff --git a/tests/tests/media/src/android/media/cts/SurfaceEncodeTimestampTest.java b/tests/tests/media/src/android/media/cts/SurfaceEncodeTimestampTest.java
new file mode 100644
index 0000000..aa9894f
--- /dev/null
+++ b/tests/tests/media/src/android/media/cts/SurfaceEncodeTimestampTest.java
@@ -0,0 +1,462 @@
+/*
+ * Copyright (C) 2019 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.media.cts;
+
+import android.graphics.Color;
+import android.graphics.Rect;
+import android.media.MediaCodec;
+import android.media.MediaCodec.BufferInfo;
+import android.media.MediaCodec.CodecException;
+import android.media.MediaCodecInfo;
+import android.media.MediaFormat;
+import android.media.MediaCodecInfo.CodecCapabilities;
+import android.opengl.GLES20;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Process;
+import android.platform.test.annotations.AppModeFull;
+import android.platform.test.annotations.RequiresDevice;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+@AppModeFull(reason = "TODO: evaluate and port to instant")
+@SmallTest
+@RequiresDevice
+public class SurfaceEncodeTimestampTest extends AndroidTestCase {
+ private static final String TAG = SurfaceEncodeTimestampTest.class.getSimpleName();
+ private static final boolean DEBUG = false;
+
+ private static final Color COLOR_BLOCK =
+ Color.valueOf(1.0f, 1.0f, 1.0f);
+ private static final Color[] COLOR_BARS = {
+ Color.valueOf(0.0f, 0.0f, 0.0f),
+ Color.valueOf(0.0f, 0.0f, 0.64f),
+ Color.valueOf(0.0f, 0.64f, 0.0f),
+ Color.valueOf(0.0f, 0.64f, 0.64f),
+ Color.valueOf(0.64f, 0.0f, 0.0f),
+ Color.valueOf(0.64f, 0.0f, 0.64f),
+ Color.valueOf(0.64f, 0.64f, 0.0f),
+ };
+ private static final int BORDER_WIDTH = 16;
+
+ private Handler mHandler;
+ private HandlerThread mHandlerThread;
+ private MediaCodec mEncoder;
+ private InputSurface mInputEglSurface;
+ private int mInputCount;
+
+ @Override
+ public void setUp() throws Exception {
+ if (mHandlerThread == null) {
+ mHandlerThread = new HandlerThread(
+ "EncoderThread", Process.THREAD_PRIORITY_FOREGROUND);
+ mHandlerThread.start();
+ mHandler = new Handler(mHandlerThread.getLooper());
+ }
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ mHandler = null;
+ if (mHandlerThread != null) {
+ mHandlerThread.quit();
+ mHandlerThread = null;
+ }
+ }
+
+ /*
+ * Test KEY_MAX_PTS_GAP_TO_ENCODER
+ *
+ * This key is supposed to cap the gap between any two frames fed to the encoder,
+ * and restore the output pts back to the original. Since the pts is not supposed
+ * to be modified, we can't really verify that the "capping" actually took place.
+ * However, we can at least verify that the pts is preserved.
+ */
+ public void testMaxPtsGap() throws Throwable {
+ long[] inputPts = {1000000, 2000000, 3000000, 4000000};
+ long[] expectedOutputPts = {1000000, 2000000, 3000000, 4000000};
+ doTest(inputPts, expectedOutputPts, (format) -> {
+ format.setLong(MediaFormat.KEY_MAX_PTS_GAP_TO_ENCODER, 33333);
+ });
+ }
+
+ /*
+ * Test that by default backward-going frames get dropped.
+ */
+ public void testBackwardFrameDroppedWithoutFixedPtsGap() throws Throwable {
+ long[] inputPts = {33333, 66667, 66000, 100000};
+ long[] expectedOutputPts = {33333, 66667, 100000};
+ doTest(inputPts, expectedOutputPts, null);
+ }
+
+ /*
+ * Test KEY_MAX_PTS_GAP_TO_ENCODER
+ *
+ * Test that when fixed pts gap is used, backward-going frames are accepted
+ * and the pts is preserved.
+ */
+ public void testBackwardFramePreservedWithFixedPtsGap() throws Throwable {
+ long[] inputPts = {33333, 66667, 66000, 100000};
+ long[] expectedOutputPts = {33333, 66667, 66000, 100000};
+ doTest(inputPts, expectedOutputPts, (format) -> {
+ format.setLong(MediaFormat.KEY_MAX_PTS_GAP_TO_ENCODER, -33333);
+ });
+ }
+
+ /*
+ * Test KEY_MAX_FPS_TO_ENCODER
+ *
+ * Input frames are timestamped at 60fps, the key is supposed to drop
+ * one every other frame to maintain 30fps output.
+ */
+ public void testMaxFps() throws Throwable {
+ long[] inputPts = {16667, 33333, 50000, 66667, 83333};
+ long[] expectedOutputPts = {16667, 50000, 83333};
+ doTest(inputPts, expectedOutputPts, (format) -> {
+ format.setFloat(MediaFormat.KEY_MAX_FPS_TO_ENCODER, 30.0f);
+ });
+ }
+
+ /*
+ * Test KEY_REPEAT_PREVIOUS_FRAME_AFTER
+ *
+ * Test that the frame is repeated at least once if no new frame arrives after
+ * the specified amount of time.
+ */
+ public void testRepeatPreviousFrameAfter() throws Throwable {
+ long[] inputPts = {16667, 33333, -100000, 133333};
+ long[] expectedOutputPts = {16667, 33333, 103333};
+ doTest(inputPts, expectedOutputPts, (format) -> {
+ format.setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, 70000);
+ });
+ }
+
+ /*
+ * Test KEY_CREATE_INPUT_SURFACE_SUSPENDED and PARAMETER_KEY_SUSPEND
+ *
+ * Start the encoder with KEY_CREATE_INPUT_SURFACE_SUSPENDED set, then resume
+ * by PARAMETER_KEY_SUSPEND. Verify only frames after resume are captured.
+ */
+ public void testCreateInputSurfaceSuspendedResume() throws Throwable {
+ // Using PARAMETER_KEY_SUSPEND (instead of PARAMETER_KEY_SUSPEND +
+ // PARAMETER_KEY_SUSPEND_TIME) to resume doesn't enforce a time
+ // for the action to take effect. Due to the asynchronous operation
+ // between the MediaCodec's parameters and the input surface, frames
+ // rendered before the resume call may reach encoder input side after
+ // the resume. Here we do a slight wait (100000us) to make sure that
+ // the resume only takes effect on the frame with timestamp 100000.
+ long[] inputPts = {33333, 66667, -100000, 100000, 133333};
+ long[] expectedOutputPts = {100000, 133333};
+ doTest(inputPts, expectedOutputPts, (format) -> {
+ format.setInteger(MediaFormat.KEY_CREATE_INPUT_SURFACE_SUSPENDED, 1);
+ }, () -> {
+ Bundle params = new Bundle();
+ params.putInt(MediaCodec.PARAMETER_KEY_SUSPEND, 0);
+ return params;
+ });
+ }
+
+ /*
+ * Test KEY_CREATE_INPUT_SURFACE_SUSPENDED,
+ * PARAMETER_KEY_SUSPEND and PARAMETER_KEY_SUSPEND_TIME
+ *
+ * Start the encoder with KEY_CREATE_INPUT_SURFACE_SUSPENDED set, then request resume
+ * at specific time using PARAMETER_KEY_SUSPEND + PARAMETER_KEY_SUSPEND_TIME.
+ * Verify only frames after the specified time are captured.
+ */
+ public void testCreateInputSurfaceSuspendedResumeWithTime() throws Throwable {
+ // Unlike using PARAMETER_KEY_SUSPEND alone to resume, using PARAMETER_KEY_SUSPEND
+ // + PARAMETER_KEY_SUSPEND_TIME to resume can be scheduled any time before the
+ // frame with the specified time arrives. Here we do it immediately after start.
+ long[] inputPts = {-1, 33333, 66667, 100000, 133333};
+ long[] expectedOutputPts = {100000, 133333};
+ doTest(inputPts, expectedOutputPts, (format) -> {
+ format.setInteger(MediaFormat.KEY_CREATE_INPUT_SURFACE_SUSPENDED, 1);
+ }, () -> {
+ Bundle params = new Bundle();
+ params.putInt(MediaCodec.PARAMETER_KEY_SUSPEND, 0);
+ params.putLong(MediaCodec.PARAMETER_KEY_SUSPEND_TIME, 100000);
+ return params;
+ });
+ }
+
+ /*
+ * Test PARAMETER_KEY_SUSPEND.
+ *
+ * Suspend/resume during capture, and verify that frames during the suspension
+ * period are dropped.
+ */
+ public void testSuspendedResume() throws Throwable {
+ // Using PARAMETER_KEY_SUSPEND (instead of PARAMETER_KEY_SUSPEND +
+ // PARAMETER_KEY_SUSPEND_TIME) to suspend/resume doesn't enforce a time
+ // for the action to take effect. Due to the asynchronous operation
+ // between the MediaCodec's parameters and the input surface, frames
+ // rendered before the request may reach encoder input side after
+ // the request. Here we do a slight wait (100000us) to make sure that
+ // the suspend/resume only takes effect on the next frame.
+ long[] inputPts = {33333, 66667, -100000, 100000, 133333, -100000, 166667};
+ long[] expectedOutputPts = {33333, 66667, 166667};
+ doTest(inputPts, expectedOutputPts, null, () -> {
+ Bundle params = new Bundle();
+ params.putInt(MediaCodec.PARAMETER_KEY_SUSPEND, 1);
+ return params;
+ }, () -> {
+ Bundle params = new Bundle();
+ params.putInt(MediaCodec.PARAMETER_KEY_SUSPEND, 0);
+ return params;
+ });
+ }
+
+ /*
+ * Test PARAMETER_KEY_SUSPEND + PARAMETER_KEY_SUSPEND_TIME.
+ *
+ * Suspend/resume with specified time during capture, and verify that frames during
+ * the suspension period are dropped.
+ */
+ public void testSuspendedResumeWithTime() throws Throwable {
+ // Unlike using PARAMETER_KEY_SUSPEND alone to suspend/resume, requests using
+ // PARAMETER_KEY_SUSPEND + PARAMETER_KEY_SUSPEND_TIME can be scheduled any time
+ // before the frame with the specified time arrives. Queue both requests shortly
+ // after start and test that they take place at the proper frames.
+ long[] inputPts = {-1, 33333, -1, 66667, 100000, 133333, 166667};
+ long[] expectedOutputPts = {33333, 66667, 166667};
+ doTest(inputPts, expectedOutputPts, null, () -> {
+ Bundle params = new Bundle();
+ params.putInt(MediaCodec.PARAMETER_KEY_SUSPEND, 1);
+ params.putLong(MediaCodec.PARAMETER_KEY_SUSPEND_TIME, 100000);
+ return params;
+ }, () -> {
+ Bundle params = new Bundle();
+ params.putInt(MediaCodec.PARAMETER_KEY_SUSPEND, 0);
+ params.putLong(MediaCodec.PARAMETER_KEY_SUSPEND_TIME, 166667);
+ return params;
+ });
+ }
+
+ /*
+ * Test PARAMETER_KEY_OFFSET_TIME.
+ *
+ * Apply PARAMETER_KEY_OFFSET_TIME during capture, and verify that the pts
+ * of frames after the request are adjusted by the offset correctly.
+ */
+ public void testOffsetTime() throws Throwable {
+ long[] inputPts = {33333, 66667, -100000, 100000, 133333};
+ long[] expectedOutputPts = {33333, 66667, 83333, 116666};
+ doTest(inputPts, expectedOutputPts, null, () -> {
+ Bundle params = new Bundle();
+ params.putLong(MediaCodec.PARAMETER_KEY_OFFSET_TIME, -16667);
+ return params;
+ });
+ }
+
+ private void doTest(long[] inputPtsUs, long[] expectedOutputPtsUs,
+ Consumer<MediaFormat> configSetter, Supplier<Bundle>... paramGetter) throws Exception {
+
+ try {
+ if (DEBUG) Log.d(TAG, "started");
+
+ // setup surface encoder format
+ mEncoder = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC);
+ MediaFormat codecFormat = MediaFormat.createVideoFormat(
+ MediaFormat.MIMETYPE_VIDEO_AVC, 1280, 720);
+ codecFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 0);
+ codecFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,
+ CodecCapabilities.COLOR_FormatSurface);
+ codecFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
+ codecFormat.setInteger(MediaFormat.KEY_BITRATE_MODE,
+ MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR);
+ codecFormat.setInteger(MediaFormat.KEY_BIT_RATE, 6000000);
+
+ if (configSetter != null) {
+ configSetter.accept(codecFormat);
+ }
+
+ CountDownLatch latch = new CountDownLatch(1);
+
+ // configure and start encoder
+ long[] actualOutputPtsUs = new long[expectedOutputPtsUs.length];
+ mEncoder.setCallback(new EncoderCallback(latch, actualOutputPtsUs), mHandler);
+ mEncoder.configure(codecFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
+
+ mInputEglSurface = new InputSurface(mEncoder.createInputSurface());
+
+ mEncoder.start();
+
+ mInputCount = 0;
+ int paramIndex = 0;
+ // perform input operations
+ for (int i = 0; i < inputPtsUs.length; i++) {
+ if (DEBUG) Log.d(TAG, "drawFrame: " + i + ", pts " + inputPtsUs[i]);
+
+ if (inputPtsUs[i] < 0) {
+ if (inputPtsUs[i] < -1) {
+ // larger negative number means that a sleep is required
+ // before the parameter test.
+ Thread.sleep(-inputPtsUs[i]/1000);
+ }
+ if (paramIndex < paramGetter.length && paramGetter[paramIndex] != null) {
+ // this means a pause to apply parameter to be tested
+ mEncoder.setParameters(paramGetter[paramIndex].get());
+ }
+ paramIndex++;
+ } else {
+ drawFrame(1280, 720, inputPtsUs[i]);
+ }
+ }
+
+ // if it worked there is really no reason to take longer..
+ latch.await(1000, TimeUnit.MILLISECONDS);
+
+ // verify output timestamps
+ assertTrue("mismatch in output timestamp",
+ Arrays.equals(expectedOutputPtsUs, actualOutputPtsUs));
+
+ if (DEBUG) Log.d(TAG, "stopped");
+ } finally {
+ if (mEncoder != null) {
+ mEncoder.stop();
+ mEncoder.release();
+ mEncoder = null;
+ }
+ if (mInputEglSurface != null) {
+ // This also releases the surface from encoder.
+ mInputEglSurface.release();
+ mInputEglSurface = null;
+ }
+ }
+ }
+
+ class EncoderCallback extends MediaCodec.Callback {
+ private boolean mOutputEOS;
+ private int mOutputCount;
+ private final CountDownLatch mLatch;
+ private final long[] mActualOutputPts;
+ private final int mMaxOutput;
+
+ EncoderCallback(CountDownLatch latch, long[] actualOutputPts) {
+ mLatch = latch;
+ mActualOutputPts = actualOutputPts;
+ mMaxOutput = actualOutputPts.length;
+ }
+
+ @Override
+ public void onOutputFormatChanged(MediaCodec codec, MediaFormat format) {
+ if (codec != mEncoder) return;
+ if (DEBUG) Log.d(TAG, "onOutputFormatChanged: " + format);
+ }
+
+ @Override
+ public void onInputBufferAvailable(MediaCodec codec, int index) {
+ if (codec != mEncoder) return;
+ if (DEBUG) Log.d(TAG, "onInputBufferAvailable: " + index);
+ }
+
+ @Override
+ public void onOutputBufferAvailable(MediaCodec codec, int index, BufferInfo info) {
+ if (codec != mEncoder || mOutputEOS) return;
+
+ if (DEBUG) {
+ Log.d(TAG, "onOutputBufferAvailable: " + index
+ + ", time " + info.presentationTimeUs
+ + ", size " + info.size
+ + ", flags " + info.flags);
+ }
+
+ if ((info.size > 0) && ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0)) {
+ mActualOutputPts[mOutputCount++] = info.presentationTimeUs;
+ }
+
+ mOutputEOS |= ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) ||
+ (mOutputCount == mMaxOutput);
+
+ codec.releaseOutputBuffer(index, false);
+
+ if (mOutputEOS) {
+ stopAndNotify(null);
+ }
+ }
+
+ @Override
+ public void onError(MediaCodec codec, CodecException e) {
+ if (codec != mEncoder) return;
+
+ Log.e(TAG, "onError: " + e);
+ stopAndNotify(e);
+ }
+
+ private void stopAndNotify(CodecException e) {
+ mLatch.countDown();
+ }
+ }
+
+ private void drawFrame(int width, int height, long ptsUs) {
+ mInputEglSurface.makeCurrent();
+ generateSurfaceFrame(mInputCount, width, height);
+ mInputEglSurface.setPresentationTime(1000 * ptsUs);
+ mInputEglSurface.swapBuffers();
+ mInputCount++;
+ }
+
+ private static Rect getColorBarRect(int index, int width, int height) {
+ int barWidth = (width - BORDER_WIDTH * 2) / COLOR_BARS.length;
+ return new Rect(BORDER_WIDTH + barWidth * index, BORDER_WIDTH,
+ BORDER_WIDTH + barWidth * (index + 1), height - BORDER_WIDTH);
+ }
+
+ private static Rect getColorBlockRect(int index, int width, int height) {
+ int blockCenterX = (width / 5) * (index % 4 + 1);
+ return new Rect(blockCenterX - width / 10, height / 6,
+ blockCenterX + width / 10, height / 3);
+ }
+
+ private void generateSurfaceFrame(int frameIndex, int width, int height) {
+ GLES20.glViewport(0, 0, width, height);
+ GLES20.glDisable(GLES20.GL_SCISSOR_TEST);
+ GLES20.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ GLES20.glEnable(GLES20.GL_SCISSOR_TEST);
+
+ for (int i = 0; i < COLOR_BARS.length; i++) {
+ Rect r = getColorBarRect(i, width, height);
+
+ GLES20.glScissor(r.left, r.top, r.width(), r.height());
+ final Color color = COLOR_BARS[i];
+ GLES20.glClearColor(color.red(), color.green(), color.blue(), 1.0f);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ }
+
+ Rect r = getColorBlockRect(frameIndex, width, height);
+ GLES20.glScissor(r.left, r.top, r.width(), r.height());
+ GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ r.inset(BORDER_WIDTH, BORDER_WIDTH);
+ GLES20.glScissor(r.left, r.top, r.width(), r.height());
+ GLES20.glClearColor(COLOR_BLOCK.red(), COLOR_BLOCK.green(), COLOR_BLOCK.blue(), 1.0f);
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+ }
+}
diff --git a/tests/tests/multiuser/AndroidTest.xml b/tests/tests/multiuser/AndroidTest.xml
index 595fcd5..8edf9d6 100644
--- a/tests/tests/multiuser/AndroidTest.xml
+++ b/tests/tests/multiuser/AndroidTest.xml
@@ -18,6 +18,7 @@
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="framework" />
<option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsMultiUserTestCases.apk" />
diff --git a/tests/tests/nativehardware/AndroidTest.xml b/tests/tests/nativehardware/AndroidTest.xml
index 24b0301..3f11774 100644
--- a/tests/tests/nativehardware/AndroidTest.xml
+++ b/tests/tests/nativehardware/AndroidTest.xml
@@ -16,6 +16,8 @@
<configuration description="Config for CTS Native Hardware test cases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="graphics" />
+ <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsNativeHardwareTestCases.apk" />
diff --git a/tests/tests/net/AndroidManifest.xml b/tests/tests/net/AndroidManifest.xml
index 0bfb650..2a57c10 100644
--- a/tests/tests/net/AndroidManifest.xml
+++ b/tests/tests/net/AndroidManifest.xml
@@ -22,6 +22,7 @@
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
diff --git a/tests/tests/neuralnetworks/benchmark/Android.mk b/tests/tests/neuralnetworks/benchmark/Android.mk
index 9670236..067db34 100644
--- a/tests/tests/neuralnetworks/benchmark/Android.mk
+++ b/tests/tests/neuralnetworks/benchmark/Android.mk
@@ -29,7 +29,7 @@
# Tag this module as a cts test artifact
LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-LOCAL_STATIC_JAVA_LIBRARIES := android-support-test androidx.test.rules \
+LOCAL_STATIC_JAVA_LIBRARIES := android-support-test \
compatibility-device-util ctstestrunner junit NeuralNetworksApiBenchmark_Lib
LOCAL_JNI_SHARED_LIBRARIES := libnnbenchmark_jni
diff --git a/tests/tests/neuralnetworks/benchmark/src/com/android/nn/benchmark/cts/NNAccuracyTest.java b/tests/tests/neuralnetworks/benchmark/src/com/android/nn/benchmark/cts/NNAccuracyTest.java
index be6d40e..827b5dd 100644
--- a/tests/tests/neuralnetworks/benchmark/src/com/android/nn/benchmark/cts/NNAccuracyTest.java
+++ b/tests/tests/neuralnetworks/benchmark/src/com/android/nn/benchmark/cts/NNAccuracyTest.java
@@ -23,10 +23,9 @@
import android.os.Bundle;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
+import android.support.test.InstrumentationRegistry;
import android.util.Pair;
-import androidx.test.InstrumentationRegistry;
-
import com.android.nn.benchmark.core.BenchmarkException;
import com.android.nn.benchmark.core.BenchmarkResult;
import com.android.nn.benchmark.core.InferenceInOutSequence;
diff --git a/tests/tests/permission/AndroidManifest.xml b/tests/tests/permission/AndroidManifest.xml
index 928da95..5400c7d 100644
--- a/tests/tests/permission/AndroidManifest.xml
+++ b/tests/tests/permission/AndroidManifest.xml
@@ -32,33 +32,8 @@
android:permissionGroup="android.permission.cts.groupC"
android:description="@string/perm_c" />
- <!-- for android.permission.cts.PermissionUsage -->
- <permission android:name="android.permission.cts.D"
- android:usageInfoRequired="true" />
-
- <!-- for android.permission.cts.PermissionUsage and LocationAccessCheckTest -->
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
- android:dataSentOffDevice="no"
- android:dataSharedWithThirdParty="no"
- android:dataUsedForMonetization="no"
- android:dataRetentionTime="notRetained" />
-
- <!-- for android.permission.cts.PermissionUsage -->
- <uses-permission android:name="android.permission.READ_PHONE_STATE"
- android:dataSentOffDevice="yes"
- android:dataSharedWithThirdParty="yes"
- android:dataUsedForMonetization="yes"
- android:dataRetentionTime="32" />
-
- <!-- for android.permission.cts.PermissionUsage -->
- <uses-permission android:name="android.permission.RECORD_AUDIO"
- android:dataSentOffDevice="userTriggered"
- android:dataSharedWithThirdParty="userTriggered"
- android:dataUsedForMonetization="userTriggered"
- android:dataRetentionTime="unlimited" />
-
- <!-- for android.permission.cts.PermissionUsage -->
- <uses-permission android:name="android.permission.READ_CALENDAR" />
+ <!-- for android.permission.cts.LocationAccessCheckTest -->
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- for android.permission.cts.PermissionGroupChange -->
<permission-group android:description="@string/perm_group_b"
diff --git a/tests/tests/permission/src/android/permission/cts/PermissionUsageTest.java b/tests/tests/permission/src/android/permission/cts/PermissionUsageTest.java
deleted file mode 100644
index 39c66a6..0000000
--- a/tests/tests/permission/src/android/permission/cts/PermissionUsageTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2018 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.permission.cts;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.Manifest;
-import android.content.Context;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PermissionInfo;
-import android.content.pm.UsesPermissionInfo;
-import android.test.InstrumentationTestCase;
-
-import org.junit.Before;
-
-public final class PermissionUsageTest extends InstrumentationTestCase {
- private PackageManager mPm;
- private Context mContext;
-
- @Override
- @Before
- public void setUp() throws Exception {
- mContext = getInstrumentation().getTargetContext();
- mPm = mContext.getPackageManager();
- assertNotNull(mPm);
- }
-
- private UsesPermissionInfo getUsesPermissionInfo(String permission) throws Exception {
- PackageInfo info = mPm.getPackageInfo(mContext.getPackageName(),
- PackageManager.GET_PERMISSIONS);
- assertNotNull(info);
- assertNotNull(info.usesPermissions);
- for (UsesPermissionInfo upi : info.usesPermissions) {
- if (permission.equals(upi.getPermission())) {
- return upi;
- }
- }
- return null;
- }
-
- public void testBasic() throws Exception {
- UsesPermissionInfo upi = getUsesPermissionInfo(Manifest.permission.ACCESS_FINE_LOCATION);
- assertEquals(UsesPermissionInfo.USAGE_NO, upi.getDataSentOffDevice());
- assertEquals(UsesPermissionInfo.USAGE_NO, upi.getDataSharedWithThirdParty());
- assertEquals(UsesPermissionInfo.USAGE_NO, upi.getDataUsedForMonetization());
- assertEquals(UsesPermissionInfo.RETENTION_NOT_RETAINED, upi.getDataRetention());
- }
-
- public void testRetentionWeeks() throws Exception {
- UsesPermissionInfo upi
- = getUsesPermissionInfo(Manifest.permission.READ_PHONE_STATE);
- assertEquals(UsesPermissionInfo.USAGE_YES, upi.getDataSentOffDevice());
- assertEquals(UsesPermissionInfo.USAGE_YES, upi.getDataSharedWithThirdParty());
- assertEquals(UsesPermissionInfo.USAGE_YES, upi.getDataUsedForMonetization());
- assertEquals(UsesPermissionInfo.RETENTION_SPECIFIED, upi.getDataRetention());
- assertEquals(32, upi.getDataRetentionWeeks());
- }
-
- public void testUserTriggered() throws Exception {
- UsesPermissionInfo upi
- = getUsesPermissionInfo(Manifest.permission.RECORD_AUDIO);
- assertEquals(UsesPermissionInfo.USAGE_USER_TRIGGERED, upi.getDataSentOffDevice());
- assertEquals(UsesPermissionInfo.USAGE_USER_TRIGGERED,
- upi.getDataSharedWithThirdParty());
- assertEquals(UsesPermissionInfo.USAGE_USER_TRIGGERED,
- upi.getDataUsedForMonetization());
- assertEquals(UsesPermissionInfo.RETENTION_UNLIMITED, upi.getDataRetention());
- }
-
- public void testUndefined() throws Exception {
- UsesPermissionInfo upi
- = getUsesPermissionInfo(Manifest.permission.READ_CALENDAR);
- assertEquals(UsesPermissionInfo.USAGE_UNDEFINED, upi.getDataSentOffDevice());
- assertEquals(UsesPermissionInfo.USAGE_UNDEFINED, upi.getDataSharedWithThirdParty());
- assertEquals(UsesPermissionInfo.USAGE_UNDEFINED, upi.getDataUsedForMonetization());
- assertEquals(UsesPermissionInfo.RETENTION_UNDEFINED, upi.getDataRetention());
- }
-
- public void testUsageInfoRequired() throws Exception {
- PermissionInfo pi = mPm.getPermissionInfo("android.permission.cts.D", 0);
- assertTrue(pi.usageInfoRequired);
- }
-}
diff --git a/tests/tests/permission/src/android/permission/cts/ShellPermissionTest.java b/tests/tests/permission/src/android/permission/cts/ShellPermissionTest.java
index cf49f50..96eef77 100644
--- a/tests/tests/permission/src/android/permission/cts/ShellPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/ShellPermissionTest.java
@@ -23,7 +23,6 @@
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
-import android.content.pm.UsesPermissionInfo;
import android.os.Process;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
@@ -65,10 +64,9 @@
String pkg = pkgs[0];
final PackageInfo packageInfo = pm.getPackageInfo(pkg, PackageManager.GET_PERMISSIONS);
- assertNotNull("No permissions found for " + pkg, packageInfo.usesPermissions);
+ assertNotNull("No permissions found for " + pkg, packageInfo.requestedPermissions);
- for (UsesPermissionInfo permInfo : packageInfo.usesPermissions) {
- final String permission = permInfo.getPermission();
+ for (String permission : packageInfo.requestedPermissions) {
Log.d(LOG_TAG, "SHELL as " + pkg + " uses permission " + permission);
assertFalse("SHELL as " + pkg + " contains the illegal permission " + permission,
blacklist.contains(permission));
diff --git a/tests/tests/preference/AndroidTest.xml b/tests/tests/preference/AndroidTest.xml
index 4287b76..1980c38 100644
--- a/tests/tests/preference/AndroidTest.xml
+++ b/tests/tests/preference/AndroidTest.xml
@@ -17,6 +17,7 @@
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="uitoolkit" />
<option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<option name="not-shardable" value="true" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
diff --git a/tests/tests/preference/OWNERS b/tests/tests/preference/OWNERS
index d20511f..827134e 100644
--- a/tests/tests/preference/OWNERS
+++ b/tests/tests/preference/OWNERS
@@ -1,2 +1,3 @@
+lpf@google.com
pavlis@google.com
clarabayarri@google.com
diff --git a/tests/tests/preference2/AndroidTest.xml b/tests/tests/preference2/AndroidTest.xml
index a3fb234..452702d 100644
--- a/tests/tests/preference2/AndroidTest.xml
+++ b/tests/tests/preference2/AndroidTest.xml
@@ -17,6 +17,7 @@
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="uitoolkit" />
<option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsPreference2TestCases.apk" />
diff --git a/tests/tests/preference2/OWNERS b/tests/tests/preference2/OWNERS
new file mode 100644
index 0000000..827134e
--- /dev/null
+++ b/tests/tests/preference2/OWNERS
@@ -0,0 +1,3 @@
+lpf@google.com
+pavlis@google.com
+clarabayarri@google.com
diff --git a/tests/tests/role/AndroidTest.xml b/tests/tests/role/AndroidTest.xml
index 8adcbc1..bdc6e71 100644
--- a/tests/tests/role/AndroidTest.xml
+++ b/tests/tests/role/AndroidTest.xml
@@ -20,6 +20,8 @@
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="framework" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
diff --git a/tests/tests/role/src/android/app/role/cts/RoleManagerTest.java b/tests/tests/role/src/android/app/role/cts/RoleManagerTest.java
index 9613c15..13caf39 100644
--- a/tests/tests/role/src/android/app/role/cts/RoleManagerTest.java
+++ b/tests/tests/role/src/android/app/role/cts/RoleManagerTest.java
@@ -206,7 +206,7 @@
boolean[] successful = new boolean[1];
CountDownLatch latch = new CountDownLatch(1);
runWithShellPermissionIdentity(() -> sRoleManager.addRoleHolderAsUser(roleName,
- packageName, user, executor, new RoleManagerCallback() {
+ packageName, 0, user, executor, new RoleManagerCallback() {
@Override
public void onSuccess() {
successful[0] = true;
@@ -229,7 +229,7 @@
boolean[] successful = new boolean[1];
CountDownLatch latch = new CountDownLatch(1);
runWithShellPermissionIdentity(() -> sRoleManager.removeRoleHolderAsUser(roleName,
- packageName, user, executor, new RoleManagerCallback() {
+ packageName, 0, user, executor, new RoleManagerCallback() {
@Override
public void onSuccess() {
successful[0] = true;
diff --git a/tests/tests/sax/AndroidTest.xml b/tests/tests/sax/AndroidTest.xml
index f81aa67..a9c5ba7 100644
--- a/tests/tests/sax/AndroidTest.xml
+++ b/tests/tests/sax/AndroidTest.xml
@@ -16,6 +16,8 @@
<configuration description="Config for CTS SAX test cases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="framework" />
+ <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
<option name="not-shardable" value="true" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
diff --git a/tests/tests/shortcutmanager/AndroidTest.xml b/tests/tests/shortcutmanager/AndroidTest.xml
index f2f6a46..512330b 100644
--- a/tests/tests/shortcutmanager/AndroidTest.xml
+++ b/tests/tests/shortcutmanager/AndroidTest.xml
@@ -18,6 +18,7 @@
<option name="config-descriptor:metadata" key="component" value="framework" />
<!-- Instant apps can't access ShortcutManager -->
<option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsShortcutManagerTestCases.apk" />
diff --git a/tests/tests/telecom/src/android/telecom/cts/CallRedirectionServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/CallRedirectionServiceTest.java
index d3e0958..6f09886 100644
--- a/tests/tests/telecom/src/android/telecom/cts/CallRedirectionServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/CallRedirectionServiceTest.java
@@ -53,7 +53,7 @@
private static final String TEST_APP_PACKAGE = "android.telecom.cts.redirectiontestapp";
private static final String TEST_APP_COMPONENT = TEST_APP_PACKAGE
+ "/android.telecom.cts.redirectiontestapp.CtsCallRedirectionService";
- private static final String ROLE_CALL_REDIRECTION = "android.app.role.PROXY_CALLING_APP";
+ private static final String ROLE_CALL_REDIRECTION = "android.app.role.CALL_REDIRECTION";
private static final Uri SAMPLE_HANDLE = Uri.fromParts(PhoneAccount.SCHEME_TEL, "0001112222",
null);
@@ -180,7 +180,7 @@
LinkedBlockingQueue<Boolean> queue = new LinkedBlockingQueue(1);
runWithShellPermissionIdentity(() -> mRoleManager.addRoleHolderAsUser(roleName,
- packageName, user, executor, new RoleManagerCallback() {
+ packageName, 0, user, executor, new RoleManagerCallback() {
@Override
public void onSuccess() {
try {
@@ -209,7 +209,7 @@
LinkedBlockingQueue<Boolean> queue = new LinkedBlockingQueue(1);
runWithShellPermissionIdentity(() -> mRoleManager.removeRoleHolderAsUser(roleName,
- packageName, user, executor, new RoleManagerCallback() {
+ packageName, 0, user, executor, new RoleManagerCallback() {
@Override
public void onSuccess() {
try {
diff --git a/tests/tests/telecom/src/android/telecom/cts/CtsRoleManagerAdapter.java b/tests/tests/telecom/src/android/telecom/cts/CtsRoleManagerAdapter.java
index 27a7010..7cd2b13 100644
--- a/tests/tests/telecom/src/android/telecom/cts/CtsRoleManagerAdapter.java
+++ b/tests/tests/telecom/src/android/telecom/cts/CtsRoleManagerAdapter.java
@@ -43,8 +43,8 @@
public class CtsRoleManagerAdapter {
private static final String TAG = CtsRoleManagerAdapter.class.getSimpleName();
- private static final String ROLE_COMPANION_APP = "android.app.role.CALL_COMPANION_APP";
- private static final String ROLE_CAR_MODE_DIALER_APP = "android.app.role.CAR_MODE_DIALER_APP";
+ private static final String ROLE_COMPANION_APP = "android.app.role.CALL_COMPANION";
+ private static final String ROLE_CAR_MODE_DIALER_APP = "android.app.role.CAR_MODE_DIALER";
private static final String COMMAND_ADD_OR_REMOVE_CALL_COMPANION_APP =
"telecom add-or-remove-call-companion-app";
private static final String COMMAND_SET_AUTO_MODE_APP = "telecom set-test-auto-mode-app";
@@ -163,7 +163,7 @@
Executor executor = mContext.getMainExecutor();
LinkedBlockingQueue<String> q = new LinkedBlockingQueue<>(1);
runWithShellPermissionIdentity(() -> {
- mRoleManager.addRoleHolderAsUser(roleName, packageName, user, executor,
+ mRoleManager.addRoleHolderAsUser(roleName, packageName, 0, user, executor,
new RoleManagerCallback() {
@Override
public void onSuccess() {
@@ -186,7 +186,7 @@
Executor executor = mContext.getMainExecutor();
LinkedBlockingQueue<String> q = new LinkedBlockingQueue<>(1);
runWithShellPermissionIdentity(() -> {
- mRoleManager.removeRoleHolderAsUser(roleName, packageName, user, executor,
+ mRoleManager.removeRoleHolderAsUser(roleName, packageName, 0, user, executor,
new RoleManagerCallback() {
@Override
public void onSuccess() {
diff --git a/tests/tests/telecom/src/android/telecom/cts/ThirdPartyCallScreeningServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/ThirdPartyCallScreeningServiceTest.java
index 7d1bae2..5ccfa3c 100644
--- a/tests/tests/telecom/src/android/telecom/cts/ThirdPartyCallScreeningServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/ThirdPartyCallScreeningServiceTest.java
@@ -62,7 +62,7 @@
"android.telecom.cts.screeningtestapp/"
+ "android.telecom.cts.screeningtestapp.CtsCallScreeningService";
private static final int ASYNC_TIMEOUT = 10000;
- private static final String ROLE_CALL_SCREENING = "android.app.role.CALL_SCREENING_APP";
+ private static final String ROLE_CALL_SCREENING = "android.app.role.CALL_SCREENING";
private static final CallIdentification SAMPLE_CALL_ID = new CallIdentification.Builder()
.setName("Joe's Laundromat")
.setDescription("1234 Dirtysocks Lane, Cleanville, USA")
@@ -454,7 +454,7 @@
LinkedBlockingQueue<Boolean> queue = new LinkedBlockingQueue(1);
runWithShellPermissionIdentity(() -> mRoleManager.addRoleHolderAsUser(roleName,
- packageName, user, executor, new RoleManagerCallback() {
+ packageName, 0, user, executor, new RoleManagerCallback() {
@Override
public void onSuccess() {
try {
@@ -483,7 +483,7 @@
LinkedBlockingQueue<Boolean> queue = new LinkedBlockingQueue(1);
runWithShellPermissionIdentity(() -> mRoleManager.removeRoleHolderAsUser(roleName,
- packageName, user, executor, new RoleManagerCallback() {
+ packageName, 0, user, executor, new RoleManagerCallback() {
@Override
public void onSuccess() {
try {
diff --git a/tests/tests/telecom/src/android/telecom/cts/ThirdPartyInCallServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/ThirdPartyInCallServiceTest.java
index ef24240..ead51f4 100644
--- a/tests/tests/telecom/src/android/telecom/cts/ThirdPartyInCallServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/ThirdPartyInCallServiceTest.java
@@ -45,8 +45,8 @@
public class ThirdPartyInCallServiceTest extends BaseTelecomTestWithMockServices {
private static final String TAG = ThirdPartyInCallServiceTest.class.getSimpleName();
- private static final String ROLE_COMPANION_APP = "android.app.role.CALL_COMPANION_APP";
- private static final String ROLE_CAR_MODE_DIALER_APP = "android.app.role.CAR_MODE_DIALER_APP";
+ private static final String ROLE_COMPANION_APP = "android.app.role.CALL_COMPANION";
+ private static final String ROLE_CAR_MODE_DIALER_APP = "android.app.role.CAR_MODE_DIALER";
private static final Uri sTestUri = Uri.parse("tel:555-TEST");
private Context mContext;
private UiModeManager mUiModeManager;
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/CellInfoTest.java b/tests/tests/telephony/current/src/android/telephony/cts/CellInfoTest.java
index 7b5024b..eaa5722 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/CellInfoTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/CellInfoTest.java
@@ -17,7 +17,6 @@
import android.content.Context;
import android.content.pm.PackageManager;
-import android.net.ConnectivityManager;
import android.os.Parcel;
import android.telephony.CellIdentityCdma;
import android.telephony.CellIdentityGsm;
@@ -35,6 +34,7 @@
import android.telephony.CellSignalStrengthLte;
import android.telephony.CellSignalStrengthNr;
import android.telephony.CellSignalStrengthWcdma;
+import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.test.AndroidTestCase;
import android.util.Log;
@@ -49,8 +49,7 @@
*/
public class CellInfoTest extends AndroidTestCase{
private final Object mLock = new Object();
- private TelephonyManager mTelephonyManager;
- private static ConnectivityManager mCm;
+ private TelephonyManager mTm;
private static final String TAG = "android.telephony.cts.CellInfoTest";
// Maximum and minimum possible RSSI values(in dbm).
private static final int MAX_RSSI = -10;
@@ -122,12 +121,17 @@
private PackageManager mPm;
+ private boolean isCamped() {
+ ServiceState ss = mTm.getServiceState();
+ if (ss == null) return false;
+ return (ss.getState() == ServiceState.STATE_IN_SERVICE
+ || ss.getState() == ServiceState.STATE_EMERGENCY_ONLY);
+ }
+
@Override
protected void setUp() throws Exception {
super.setUp();
- mTelephonyManager =
- (TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
- mCm = (ConnectivityManager)getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
+ mTm = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
mPm = getContext().getPackageManager();
}
@@ -138,14 +142,11 @@
return;
}
- if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
- Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
- return;
- }
+ if (!isCamped()) fail("Device is not camped to a cell");
// getAllCellInfo should never return null, and there should
// be at least one entry.
- List<CellInfo> allCellInfo = mTelephonyManager.getAllCellInfo();
+ List<CellInfo> allCellInfo = mTm.getAllCellInfo();
assertNotNull("TelephonyManager.getAllCellInfo() returned NULL!", allCellInfo);
assertTrue("TelephonyManager.getAllCellInfo() returned zero-length list!",
allCellInfo.size() > 0);
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthTest.java
index cb87173..a31babf 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthTest.java
@@ -86,28 +86,38 @@
Set<Class<?>> types = new HashSet<Class<?>>();
- Class<?> type = getSignalStrengthTypeForNetworkType(mTm.getDataNetworkType());
- if (type != null) types.add(type);
+ Class<?> dataType = getSignalStrengthTypeForNetworkType(mTm.getDataNetworkType());
+ if (dataType != null) types.add(dataType);
- type = getSignalStrengthTypeForNetworkType(mTm.getNetworkType());
- if (type != null) types.add(type);
+ Class<?> voiceType = getSignalStrengthTypeForNetworkType(mTm.getNetworkType());
- // Blocked by b/123096279
- /*
+ // Check if camped for Voice-Only
+ if (dataType == null && voiceType != null) {
+ types.add(voiceType);
+ }
+
+ // Check for SRLTE
+ if (dataType != null && voiceType != null
+ && dataType.equals(CellSignalStrengthLte.class)
+ && voiceType.equals(CellSignalStrengthCdma.class)) {
+ types.add(voiceType);
+ }
+
+ // Check for NR
+ if (isUsingEnDc()) {
+ types.add(CellSignalStrengthNr.class);
+ }
+
for (CellSignalStrength css : signalStrengths) {
assertTrue("Invalid SignalStrength type detected" + css.getClass(),
- types.contains(css.getClass())
- || css instanceof CellSignalStrengthNr && isUsingEnDc());
+ types.contains(css.getClass()));
}
- */
}
/** Check whether the device is LTE + NR dual connected */
private boolean isUsingEnDc() {
ServiceState ss = mTm.getServiceState();
- return false;
- // blocked by b/123096279
- // return ss != null && ss.getNrStatus() == NR_STATUS_CONNECTED;
+ return ss != null && ss.getNrStatus() == NR_STATUS_CONNECTED;
}
/** Get the CellSignalStrength class type that should be returned when using a network type */
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
index bb5857e..914660d 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
@@ -41,6 +41,7 @@
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.SubscriptionPlan;
+import android.telephony.TelephonyManager;
import com.android.compatibility.common.util.SystemUtil;
import com.android.internal.util.ArrayUtils;
@@ -167,7 +168,7 @@
@Test
public void testIsUsableSubscriptionId() throws Exception {
if (!isSupported()) return;
- assertTrue(SubscriptionManager.isUsableSubIdValue(mSubId));
+ assertTrue(SubscriptionManager.isUsableSubscriptionId(mSubId));
}
@Test
@@ -405,6 +406,15 @@
}
@Test
+ public void testSubscriptionInfoCarrierId() {
+ if (!isSupported()) return;
+
+ SubscriptionInfo info = mSm.getActiveSubscriptionInfo(mSubId);
+ int carrierId = info.getCarrierId();
+ assertTrue(carrierId >= TelephonyManager.UNKNOWN_CARRIER_ID);
+ }
+
+ @Test
public void testSettingSubscriptionMeteredNess() throws Exception {
if (!isSupported()) return;
diff --git a/tests/tests/telephony4/src/android/telephony4/cts/SimRestrictedApisTest.java b/tests/tests/telephony4/src/android/telephony4/cts/SimRestrictedApisTest.java
index 4732193..8058679 100644
--- a/tests/tests/telephony4/src/android/telephony4/cts/SimRestrictedApisTest.java
+++ b/tests/tests/telephony4/src/android/telephony4/cts/SimRestrictedApisTest.java
@@ -67,21 +67,6 @@
}
/**
- * Tests the TelephonyManager.setLine1NumberForDisplay(long, string, string) API. This makes a
- * call to setLine1NumberForDisplay() API and expects a SecurityException since the test apk is
- * not signed by the certificate on the SIM.
- */
- public void testSetLine1NumberForDisplay2() {
- try {
- if (isSimCardPresent()) {
- mTelephonyManager.setLine1NumberForDisplay(0, "", "");
- fail("Expected SecurityException. App doesn't have carrier privileges.");
- }
- } catch (SecurityException expected) {
- }
- }
-
- /**
* Tests the TelephonyManager.iccOpenLogicalChannel() API. This makes a call to
* iccOpenLogicalChannel() API and expects a SecurityException since the test apk is not signed
* by certificate on the SIM.
@@ -172,34 +157,6 @@
}
/**
- * Tests the TelephonyManager.nvWriteItem() API. This makes a call to nvWriteItem() API and
- * expects a SecurityException since the test apk is not signed by a certificate on the SIM.
- */
- public void testNvWriteItem() {
- try {
- if (isSimCardPresent()) {
- mTelephonyManager.nvWriteItem(0, "");
- fail("Expected SecurityException. App doesn't have carrier privileges.");
- }
- } catch (SecurityException expected) {
- }
- }
-
- /**
- * Tests the TelephonyManager.nvWriteCdmaPrl() API. This makes a call to nvWriteCdmaPrl() API
- * and expects a SecurityException since the test apk is not signed by a certificate on the SIM.
- */
- public void testNvWriteCdmaPrl() {
- try {
- if (isSimCardPresent()) {
- mTelephonyManager.nvWriteCdmaPrl(null);
- fail("Expected SecurityException. App doesn't have carrier privileges.");
- }
- } catch (SecurityException expected) {
- }
- }
-
- /**
* Tests the TelephonyManager.nvResetConfig() API. This makes a call to nvResetConfig() API and
* expects a SecurityException since the test apk is not signed by a certificate on the SIM.
*/
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/EdgeEffectTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/EdgeEffectTests.java
index 57462b6..955d51f 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/EdgeEffectTests.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/EdgeEffectTests.java
@@ -19,6 +19,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyFloat;
import static org.mockito.Mockito.mock;
@@ -26,6 +27,7 @@
import android.content.Context;
import android.graphics.Bitmap;
+import android.graphics.BlendMode;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
@@ -137,6 +139,17 @@
}
@Test
+ public void testSetBlendMode() {
+ assertEdgeEffect(edgeEffect -> {
+ edgeEffect.setBlendMode(null);
+ assertNull(edgeEffect.getBlendMode());
+ edgeEffect.setBlendMode(EdgeEffect.DEFAULT_BLEND_MODE);
+ assertEquals(BlendMode.SRC_ATOP, edgeEffect.getBlendMode());
+ edgeEffect.onPull(1);
+ });
+ }
+
+ @Test
public void testOnPullWithDisplacement() {
assertEdgeEffect(edgeEffect -> {
edgeEffect.onPull(1, 0);
diff --git a/tests/tests/util/AndroidTest.xml b/tests/tests/util/AndroidTest.xml
index 92c1e14..7f11f18 100644
--- a/tests/tests/util/AndroidTest.xml
+++ b/tests/tests/util/AndroidTest.xml
@@ -16,6 +16,8 @@
<configuration description="Config for CTS Util test cases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="framework" />
+ <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsUtilTestCases.apk" />
diff --git a/tests/tests/view/AndroidManifest.xml b/tests/tests/view/AndroidManifest.xml
index dabbc1a..925f3e2 100644
--- a/tests/tests/view/AndroidManifest.xml
+++ b/tests/tests/view/AndroidManifest.xml
@@ -31,6 +31,15 @@
android:supportsRtl="true">
<uses-library android:name="android.test.runner" />
+ <activity android:name="android.app.Activity"
+ android:label="Empty Activity"
+ android:theme="@style/ViewStyleTestTheme">
+ <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.ViewStubCtsActivity"
android:screenOrientation="locked"
android:label="ViewStubCtsActivity">
diff --git a/tests/tests/view/res/layout/view_style_layout.xml b/tests/tests/view/res/layout/view_style_layout.xml
new file mode 100644
index 0000000..dd488ef
--- /dev/null
+++ b/tests/tests/view/res/layout/view_style_layout.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright (C) 2019 The Android Open Source Project
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License
+ -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:orientation="vertical"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+ <View android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:id="@+id/view1"
+ android:paddingTop="7dp"
+ style="@style/ExplicitStyle1" />
+
+ <View android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:id="@+id/view2"
+ style="@style/ExplicitStyle2" />
+
+ <View android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:id="@+id/view3" />
+
+ <View android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:id="@+id/view4"
+ style="?android:attr/textAppearanceLarge"/>
+
+ <Button android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:id="@+id/button1" />
+
+ <Button android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:id="@+id/button2"
+ style="@style/ExplicitStyle1" />
+</LinearLayout>
\ No newline at end of file
diff --git a/tests/tests/view/res/values/styles.xml b/tests/tests/view/res/values/styles.xml
index 5e47363..ab984e8 100644
--- a/tests/tests/view/res/values/styles.xml
+++ b/tests/tests/view/res/values/styles.xml
@@ -187,4 +187,26 @@
<item name="android:windowContentTransitions">false</item>
<item name="android:windowAnimationStyle">@null</item>
</style>
+
+ <style name="ViewStyleTestTheme" parent="@android:Theme.Material">
+ <item name="android:buttonStyle">@style/MyButtonStyle</item>
+ </style>
+
+ <style name="MyButtonStyle" parent="@style/MyButtonStyleParent">
+ <item name="android:paddingTop">3dp</item>
+ </style>
+
+ <style name="MyButtonStyleParent">
+ <item name="android:textColor">#ff00ff</item>
+ </style>
+
+ <style name="ExplicitStyle1" parent="@style/ParentOfExplicitStyle1">
+ <item name="android:padding">1dp</item>
+ </style>
+
+ <style name="ParentOfExplicitStyle1">
+ <item name="android:paddingLeft">2dp</item>
+ </style>
+
+ <style name="ExplicitStyle2" />
</resources>
diff --git a/tests/tests/view/sdk28/Android.bp b/tests/tests/view/sdk28/Android.bp
new file mode 100644
index 0000000..87c6914
--- /dev/null
+++ b/tests/tests/view/sdk28/Android.bp
@@ -0,0 +1,46 @@
+// Copyright (C) 2019 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.
+
+android_test {
+ name: "CtsViewTestCasesSdk28",
+ defaults: ["cts_defaults"],
+
+ // Tag this module as a cts test artifact
+ test_suites: [
+ "cts",
+ "vts",
+ "general-tests",
+ "cts_instant",
+ ],
+
+ compile_multilib: "both",
+
+ libs: [
+ "android.test.runner.stubs",
+ "android.test.base.stubs",
+ ],
+
+ static_libs: [
+ "android-support-test",
+ "ctstestrunner",
+ "platform-test-annotations",
+ ],
+
+ srcs: [
+ "src/**/*.java",
+ ],
+
+ sdk_version: "28",
+
+}
diff --git a/tests/tests/view/sdk28/Android.mk b/tests/tests/view/sdk28/Android.mk
deleted file mode 100644
index 7d4f806..0000000
--- a/tests/tests/view/sdk28/Android.mk
+++ /dev/null
@@ -1,51 +0,0 @@
-# Copyright (C) 2019 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)
-
-# don't include this package in any target
-LOCAL_MODULE_TAGS := tests
-# and when built explicitly put it in the data partition
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
-
-LOCAL_MULTILIB := both
-
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs android.test.base.stubs
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
- android-support-test \
- compatibility-device-util \
- ctsdeviceutillegacy \
- ctstestrunner \
- mockito-target-minus-junit4 \
- platform-test-annotations \
- ub-uiautomator \
- truth-prebuilt
-
-
-LOCAL_JNI_SHARED_LIBRARIES := libctsview_jni libnativehelper_compat_libc++
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src) $(call all-renderscript-files-under, src)
-
-LOCAL_PACKAGE_NAME := CtsViewTestCasesSdk28
-LOCAL_SDK_VERSION := 28
-
-include $(BUILD_CTS_PACKAGE)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/view/sdk28/AndroidTest.xml b/tests/tests/view/sdk28/AndroidTest.xml
index 1a64e98..004e8b5 100644
--- a/tests/tests/view/sdk28/AndroidTest.xml
+++ b/tests/tests/view/sdk28/AndroidTest.xml
@@ -20,10 +20,10 @@
<option name="config-descriptor:metadata" key="parameter" value="instant_app" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
- <option name="test-file-name" value="CtsViewTestCases.apk" />
+ <option name="test-file-name" value="CtsViewTestCasesSdk28.apk" />
</target_preparer>
<test class="com.android.tradefed.testtype.AndroidJUnitTest" >
- <option name="package" value="android.view.cts" />
+ <option name="package" value="android.view.cts.sdk28" />
<option name="runtime-hint" value="6m47s" />
<option name="hidden-api-checks" value="false" />
</test>
diff --git a/tests/tests/view/sdk28/TEST_MAPPING b/tests/tests/view/sdk28/TEST_MAPPING
new file mode 100644
index 0000000..d2d36ce
--- /dev/null
+++ b/tests/tests/view/sdk28/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "presubmit": [
+ {
+ "name": "CtsViewTestCasesSdk28"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java b/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
index 3460525..7d6228d 100644
--- a/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
+++ b/tests/tests/view/src/android/view/cts/LayoutInflaterTest.java
@@ -19,6 +19,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
@@ -26,6 +27,7 @@
import android.content.ComponentName;
import android.content.Context;
+import android.content.ContextWrapper;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
@@ -53,6 +55,9 @@
import org.junit.runner.RunWith;
import org.xmlpull.v1.XmlPullParser;
+import java.util.ArrayList;
+import java.util.List;
+
@SmallTest
@RunWith(AndroidJUnit4.class)
public class LayoutInflaterTest {
@@ -412,6 +417,39 @@
assertNotNull(container.findViewById(R.id.include_layout_from_attr));
}
+ // API : LayoutInflater#onCreateView(Context, View, String, AttributeSet)
+ // API : LayoutInflater#createView(Context, String, prefix, AttributeSet)
+ // onCreateView with Context should be called when there is no factory to inflate and should
+ // pass the LayoutInflater's context at the root and the parent's context other times.
+ // createView with Context should be called when there is a "." in the name.
+ @Test
+ public void testCreateViewWithContext() throws Throwable {
+ final Context context = mLayoutInflater.getContext();
+ CreateViewContextInflater inflater = new CreateViewContextInflater(context);
+ final ViewGroup container = (ViewGroup) inflater.inflate(R.layout.inflater_layout, null);
+
+ // The LinearLayout and TextViews inflate with onCreateView
+ assertEquals(9, inflater.onCreateViewCalls.size());
+ assertEquals(context, inflater.onCreateViewCalls.get(0)[0]);
+ assertNull(inflater.onCreateViewCalls.get(0)[1]);
+ assertEquals("LinearLayout", inflater.onCreateViewCalls.get(0)[2]);
+
+ Context parentContext = container.getContext();
+ // This should be a wrapper context since MethodTrackerInflater changes LinearLayout context
+ assertNotSame(context, parentContext);
+ for (int i = 1; i < 9; i++) {
+ Object[] params = inflater.onCreateViewCalls.get(i);
+ assertEquals(parentContext, params[0]);
+ assertEquals(container, params[1]);
+ assertEquals("TextView", params[2]);
+ }
+
+ // Also has android.view.ct.MockViewStub
+ assertEquals(9, container.getChildCount());
+ View mockViewStub = container.getChildAt(8);
+ assertEquals(parentContext, mockViewStub.getContext());
+ }
+
static class MockLayoutInflater extends LayoutInflater {
public MockLayoutInflater(Context c) {
@@ -434,6 +472,41 @@
}
}
+ /**
+ * Used to track calling of onCreateView protected method.
+ */
+ static class CreateViewContextInflater extends LayoutInflater {
+ public final List<Object[]> onCreateViewCalls = new ArrayList<>();
+
+ CreateViewContextInflater(Context context) {
+ super(context);
+ }
+
+ @Override
+ public LayoutInflater cloneInContext(Context newContext) {
+ return null;
+ }
+
+ @Override
+ public View onCreateView(Context viewContext, View parent, String name,
+ AttributeSet attrs) throws ClassNotFoundException {
+ onCreateViewCalls.add(new Object[] {viewContext, parent, name, attrs});
+ if ("LinearLayout".equals(name)) {
+ viewContext = new ContextWrapper(viewContext);
+ }
+ String prefix = null;
+ int dotIndex = name.lastIndexOf('.');
+ if (dotIndex >= 0) {
+ prefix = name.substring(0, dotIndex + 1);
+ name = name.substring(dotIndex + 1);
+ } else {
+ prefix = "android.widget.";
+ }
+
+ return createView(viewContext, name, prefix, attrs);
+ }
+ }
+
private XmlResourceParser getParser() {
XmlResourceParser parser = null;
ActivityInfo ai = null;
diff --git a/tests/tests/view/src/android/view/cts/ViewStyleTest.java b/tests/tests/view/src/android/view/cts/ViewStyleTest.java
new file mode 100644
index 0000000..866e8b6
--- /dev/null
+++ b/tests/tests/view/src/android/view/cts/ViewStyleTest.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view.cts;
+
+import static org.junit.Assert.assertEquals;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.res.Resources;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.MediumTest;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.uiautomator.UiDevice;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.Button;
+import android.widget.LinearLayout;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.List;
+import java.util.Map;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class ViewStyleTest {
+
+ @Rule
+ public ActivityTestRule<Activity> mActivityRule =
+ new ActivityTestRule<>(Activity.class, true, false);
+
+ private static final String DISABLE_SHELL_COMMAND =
+ "settings delete global debug_view_attributes_application_package";
+
+ private static final String ENABLE_SHELL_COMMAND =
+ "settings put global debug_view_attributes_application_package android.view.cts";
+
+ private UiDevice mUiDevice;
+
+ @Before
+ public void setUp() throws Exception {
+ mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+ mUiDevice.executeShellCommand(ENABLE_SHELL_COMMAND);
+ mActivityRule.launchActivity(null);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ mUiDevice.executeShellCommand(DISABLE_SHELL_COMMAND);
+ }
+
+ @Test
+ public void testGetExplicitStyle() {
+ Context context = InstrumentationRegistry.getTargetContext();
+ LayoutInflater inflater = LayoutInflater.from(context);
+ LinearLayout rootView = (LinearLayout) inflater.inflate(R.layout.view_style_layout, null);
+ View view1 = rootView.findViewById(R.id.view1);
+ assertEquals(R.style.ExplicitStyle1, view1.getExplicitStyle());
+
+ View view2 = rootView.findViewById(R.id.view2);
+ assertEquals(R.style.ExplicitStyle2, view2.getExplicitStyle());
+
+ View view3 = rootView.findViewById(R.id.view3);
+ assertEquals(Resources.ID_NULL, view3.getExplicitStyle());
+
+ View view4 = rootView.findViewById(R.id.view4);
+ assertEquals(android.R.style.TextAppearance_Material_Large, view4.getExplicitStyle());
+ }
+
+ @Test
+ public void testGetAttributeResolutionStack() {
+ LayoutInflater inflater = LayoutInflater.from(mActivityRule.getActivity());
+ LinearLayout rootView = (LinearLayout) inflater.inflate(R.layout.view_style_layout, null);
+ // View that has an explicit style ExplicitStyle1 set via style = ...
+ View view1 = rootView.findViewById(R.id.view1);
+ List<Integer> stackView1 = view1.getAttributeResolutionStack();
+ assertEquals(3, stackView1.size());
+ assertEquals(R.layout.view_style_layout, stackView1.get(0).intValue());
+ assertEquals(R.style.ExplicitStyle1, stackView1.get(1).intValue());
+ assertEquals(R.style.ParentOfExplicitStyle1, stackView1.get(2).intValue());
+
+ // Button that has the default style MyButtonStyle set in ViewStyleTestTheme Activity theme
+ // via android:buttonStyle
+ Button button1 = rootView.findViewById(R.id.button1);
+ List<Integer> stackButton1 = button1.getAttributeResolutionStack();
+ assertEquals(3, stackButton1.size());
+ assertEquals(R.layout.view_style_layout, stackButton1.get(0).intValue());
+ assertEquals(R.style.MyButtonStyle, stackButton1.get(1).intValue());
+ assertEquals(R.style.MyButtonStyleParent, stackButton1.get(2).intValue());
+
+ // Button that has the default style MyButtonStyle set in ViewStyleTestTheme Activity theme
+ // via android:buttonStyle and has an explicit style ExplicitStyle1 set via style = ...
+ Button button2 = rootView.findViewById(R.id.button2);
+ List<Integer> stackButton2 = button2.getAttributeResolutionStack();
+ assertEquals(5, stackButton2.size());
+ assertEquals(R.layout.view_style_layout, stackButton2.get(0).intValue());
+ assertEquals(R.style.ExplicitStyle1, stackButton2.get(1).intValue());
+ assertEquals(R.style.ParentOfExplicitStyle1, stackButton2.get(2).intValue());
+ assertEquals(R.style.MyButtonStyle, stackButton2.get(3).intValue());
+ assertEquals(R.style.MyButtonStyleParent, stackButton2.get(4).intValue());
+ }
+
+ @Test
+ public void testGetAttributeSourceResourceMap() {
+ LayoutInflater inflater = LayoutInflater.from(mActivityRule.getActivity());
+ LinearLayout rootView = (LinearLayout) inflater.inflate(R.layout.view_style_layout, null);
+ // View that has an explicit style ExplicitStyle1 set via style = ...
+ View view1 = rootView.findViewById(R.id.view1);
+ Map<Integer, Integer> attributeMapView1 = view1.getAttributeSourceResourceMap();
+ assertEquals(9, attributeMapView1.size());
+ assertEquals(R.style.ExplicitStyle1,
+ (attributeMapView1.get(android.R.attr.padding)).intValue());
+ assertEquals(R.style.ParentOfExplicitStyle1,
+ (attributeMapView1.get(android.R.attr.paddingLeft)).intValue());
+ assertEquals(R.layout.view_style_layout,
+ (attributeMapView1.get(android.R.attr.paddingTop)).intValue());
+ }
+}
diff --git a/tests/tests/voicesettings/AndroidTest.xml b/tests/tests/voicesettings/AndroidTest.xml
index 6e419e0..7bdb094 100644
--- a/tests/tests/voicesettings/AndroidTest.xml
+++ b/tests/tests/voicesettings/AndroidTest.xml
@@ -16,6 +16,8 @@
<configuration description="Config for CTS Voice Settings test cases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="framework" />
+ <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+ <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
<option name="not-shardable" value="true" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
diff --git a/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java b/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
index 49b0f64..39ddda0 100644
--- a/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
@@ -69,6 +69,7 @@
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
+import android.widget.EdgeEffect;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
@@ -1127,6 +1128,27 @@
}
}
+ @SmallTest
+ @UiThreadTest
+ @Test
+ public void testEdgeEffectColors() {
+ int defaultColor = new EdgeEffect(mListView.getContext()).getColor();
+ assertEquals(mListView.getTopEdgeEffectColor(), defaultColor);
+ assertEquals(mListView.getBottomEdgeEffectColor(), defaultColor);
+
+ mListView.setEdgeEffectColor(Color.BLUE);
+ assertEquals(mListView.getTopEdgeEffectColor(), Color.BLUE);
+ assertEquals(mListView.getBottomEdgeEffectColor(), Color.BLUE);
+
+ mListView.setTopEdgeEffectColor(Color.RED);
+ assertEquals(mListView.getTopEdgeEffectColor(), Color.RED);
+ assertEquals(mListView.getBottomEdgeEffectColor(), Color.BLUE);
+
+ mListView.setBottomEdgeEffectColor(Color.GREEN);
+ assertEquals(mListView.getTopEdgeEffectColor(), Color.RED);
+ assertEquals(mListView.getBottomEdgeEffectColor(), Color.GREEN);
+ }
+
// Helper method that emulates fast scroll by dragging along the right edge of our ListView.
private void verifyFastScroll() throws Throwable {
setAdapter();
diff --git a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
index f083053..d3c685a 100644
--- a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
+++ b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
@@ -72,6 +72,7 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -901,6 +902,74 @@
() -> mPopupWindow.showAtLocation(anchorView, Gravity.BOTTOM, 0, 0), false);
}
+ @Test
+ public void testEnterExitTransitionAsDropDownWithCustomBounds() throws Throwable {
+ final View anchorView = mActivity.findViewById(R.id.anchor_upper);
+ final Rect epicenter = new Rect(20, 50, 22, 80);
+ verifyTransitionEpicenterChange(
+ () -> mPopupWindow.showAsDropDown(anchorView, 0, 0), epicenter);
+ }
+
+ private void verifyTransitionEpicenterChange(Runnable showRunnable, Rect epicenterBounds)
+ throws Throwable {
+ TransitionListener enterListener = mock(TransitionListener.class);
+ Transition enterTransition = new BaseTransition();
+ enterTransition.addListener(enterListener);
+
+ TransitionListener exitListener = mock(TransitionListener.class);
+ Transition exitTransition = new BaseTransition();
+ exitTransition.addListener(exitListener);
+
+ OnDismissListener dismissListener = mock(OnDismissListener.class);
+
+ mPopupWindow = createPopupWindow(createPopupContent(CONTENT_SIZE_DP, CONTENT_SIZE_DP));
+ mPopupWindow.setEnterTransition(enterTransition);
+ mPopupWindow.setExitTransition(exitTransition);
+ mPopupWindow.setOnDismissListener(dismissListener);
+
+ ArgumentCaptor<Transition> captor = ArgumentCaptor.forClass(Transition.class);
+
+ mActivityRule.runOnUiThread(showRunnable);
+ mInstrumentation.waitForIdleSync();
+
+ verify(enterListener, times(1)).onTransitionStart(captor.capture());
+ final Rect oldEpicenterStart = new Rect(captor.getValue().getEpicenter());
+
+ mActivityRule.runOnUiThread(mPopupWindow::dismiss);
+ mInstrumentation.waitForIdleSync();
+
+ verify(exitListener, times(1)).onTransitionStart(captor.capture());
+ final Rect oldEpicenterExit = new Rect(captor.getValue().getEpicenter());
+
+ mPopupWindow.setEpicenterBounds(epicenterBounds);
+ mActivityRule.runOnUiThread(showRunnable);
+ mInstrumentation.waitForIdleSync();
+
+ verify(enterListener, times(2)).onTransitionStart(captor.capture());
+ final Rect newEpicenterStart = new Rect(captor.getValue().getEpicenter());
+
+ mActivityRule.runOnUiThread(mPopupWindow::dismiss);
+ mInstrumentation.waitForIdleSync();
+
+ verify(exitListener, times(2)).onTransitionStart(captor.capture());
+
+ final Rect newEpicenterExit = new Rect(captor.getValue().getEpicenter());
+
+ verifyEpicenters(oldEpicenterStart, newEpicenterStart, epicenterBounds);
+ verifyEpicenters(oldEpicenterExit, newEpicenterExit, epicenterBounds);
+
+ }
+
+ private void verifyEpicenters(Rect actualOld, Rect actualNew, Rect passed) {
+ Rect oldCopy = new Rect(actualOld);
+ int left = oldCopy.left;
+ int top = oldCopy.top;
+ oldCopy.set(passed);
+ oldCopy.offset(left, top);
+
+ assertEquals(oldCopy, actualNew);
+ }
+
private void verifyEnterExitTransition(Runnable showRunnable, boolean showAgain)
throws Throwable {
TransitionListener enterListener = mock(TransitionListener.class);
@@ -1139,6 +1208,47 @@
}
@Test
+ public void testAccessClippingToScreenEnabled() {
+ mPopupWindow = new PopupWindow(mActivity);
+ assertFalse(mPopupWindow.isClipToScreenEnabled());
+
+ mPopupWindow.setClipToScreenEnabled(true);
+ assertTrue(mPopupWindow.isClipToScreenEnabled());
+ }
+
+ @Test
+ public void testAccessLayoutInScreenEnabled() {
+ mPopupWindow = new PopupWindow(mActivity);
+ assertFalse(mPopupWindow.isLayoutInScreenEnabled());
+
+ mPopupWindow.setLayoutInScreenEnabled(true);
+ assertTrue(mPopupWindow.isLayoutInScreenEnabled());
+ }
+
+ @Test
+ public void testAccessTouchModal() {
+ mPopupWindow = new PopupWindow(mActivity);
+ assertTrue(mPopupWindow.isTouchModal());
+
+ mPopupWindow.setTouchModal(false);
+ assertFalse(mPopupWindow.isTouchModal());
+ }
+
+ @Test
+ public void testAccessEpicenterBounds() {
+ mPopupWindow = new PopupWindow(mActivity);
+ assertNull(mPopupWindow.getEpicenterBounds());
+
+ final Rect epicenter = new Rect(5, 10, 15, 20);
+
+ mPopupWindow.setEpicenterBounds(epicenter);
+ assertEquals(mPopupWindow.getEpicenterBounds(), epicenter);
+
+ mPopupWindow.setEpicenterBounds(null);
+ assertNull(mPopupWindow.getEpicenterBounds());
+ }
+
+ @Test
public void testAccessOutsideTouchable() {
mPopupWindow = new PopupWindow(mActivity);
assertFalse(mPopupWindow.isOutsideTouchable());
diff --git a/tests/tests/wrap/nowrap/Android.mk b/tests/tests/wrap/nowrap/Android.mk
index 8fd1015..094f0f0 100644
--- a/tests/tests/wrap/nowrap/Android.mk
+++ b/tests/tests/wrap/nowrap/Android.mk
@@ -35,4 +35,6 @@
# Jarjar to make WrapTest unique.
LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
+
include $(BUILD_PACKAGE)
diff --git a/tests/tests/wrap/wrap_debug/Android.mk b/tests/tests/wrap/wrap_debug/Android.mk
index c67e191..71c517b 100644
--- a/tests/tests/wrap/wrap_debug/Android.mk
+++ b/tests/tests/wrap/wrap_debug/Android.mk
@@ -42,6 +42,8 @@
# Jarjar to make WrapTest unique.
LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
+
include $(BUILD_PACKAGE)
include $(CLEAR_VARS)
diff --git a/tests/tests/wrap/wrap_debug_malloc_debug/Android.mk b/tests/tests/wrap/wrap_debug_malloc_debug/Android.mk
index b768dcf..b2d4ae4 100644
--- a/tests/tests/wrap/wrap_debug_malloc_debug/Android.mk
+++ b/tests/tests/wrap/wrap_debug_malloc_debug/Android.mk
@@ -42,6 +42,8 @@
# Jarjar to make WrapTest unique.
LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
+
include $(BUILD_PACKAGE)
include $(CLEAR_VARS)
diff --git a/tests/tests/wrap/wrap_nodebug/Android.mk b/tests/tests/wrap/wrap_nodebug/Android.mk
index 3317f3c..87dc828 100644
--- a/tests/tests/wrap/wrap_nodebug/Android.mk
+++ b/tests/tests/wrap/wrap_nodebug/Android.mk
@@ -42,6 +42,8 @@
# Jarjar to make WrapTest unique.
LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
+LOCAL_USE_EMBEDDED_NATIVE_LIBS := false
+
include $(BUILD_PACKAGE)
include $(CLEAR_VARS)
diff --git a/tests/vr/AndroidTest.xml b/tests/vr/AndroidTest.xml
index 0212be6..ee9d9cb 100644
--- a/tests/vr/AndroidTest.xml
+++ b/tests/vr/AndroidTest.xml
@@ -16,6 +16,8 @@
<configuration description="Config for CTS VR test cases">
<option name="test-suite-tag" value="cts" />
<option name="config-descriptor:metadata" key="component" value="vr" />
+ <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+ <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
<target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
<option name="cleanup-apks" value="true" />
<option name="test-file-name" value="CtsVrTestCases.apk" />