Merge Android 12

Bug: 202323961
Merged-In: I9073b1d993316cc77947ac1ede4bd33a05f0960e
Change-Id: I08e98f2c2f209f144b6770729ebd25cbc1f41db6
diff --git a/tests/stats/Android.bp b/tests/stats/Android.bp
new file mode 100644
index 0000000..1a4092a
--- /dev/null
+++ b/tests/stats/Android.bp
@@ -0,0 +1,46 @@
+// Copyright (C) 2021 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "CtsRootStatsDeviceTestCases",
+    defaults: ["cts_defaults"],
+    dex_preopt: {
+        enabled: false,
+    },
+    optimize: {
+        enabled: false,
+    },
+    static_libs: [
+        "androidx.test.core",
+        "androidx.test.rules",
+        "compatibility-device-util-axt",
+        "services.core",
+        "truth-prebuilt",
+        "platform-test-annotations",
+    ],
+    libs: [
+        "android.test.runner",
+        "android.test.base",
+    ],
+    srcs: ["src/**/*.java"],
+    test_suites: [
+        "cts_root",
+        "general-tests",
+    ],
+    sdk_version: "test_current",
+}
diff --git a/tests/stats/AndroidManifest.xml b/tests/stats/AndroidManifest.xml
new file mode 100644
index 0000000..4098aaf
--- /dev/null
+++ b/tests/stats/AndroidManifest.xml
@@ -0,0 +1,28 @@
+<!--
+  ~ Copyright (C) 2021 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.stats.cts_root" >
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android"
+                     android:label="Stats CTS root tests"/>
+
+</manifest>
diff --git a/tests/stats/AndroidTest.xml b/tests/stats/AndroidTest.xml
new file mode 100644
index 0000000..55ab762
--- /dev/null
+++ b/tests/stats/AndroidTest.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2021 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+<configuration description="Runs Stats CTS root tests">
+    <option name="test-suite-tag" value="apct" />
+    <option name="test-suite-tag" value="apct-instrumentation" />
+
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true"/>
+        <option name="test-file-name" value="CtsRootStatsDeviceTestCases.apk"/>
+    </target_preparer>
+
+    <!-- Restart to clear test code from system server -->
+    <target_preparer class="com.android.tradefed.targetprep.DeviceCleaner">
+        <option name="cleanup-action" value="REBOOT" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest">
+        <option name="package" value="android.stats.cts_root"/>
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+        <option name="restart" value="false" />
+    </test>
+</configuration>
diff --git a/tests/stats/OWNERS b/tests/stats/OWNERS
new file mode 100644
index 0000000..f6525fc
--- /dev/null
+++ b/tests/stats/OWNERS
@@ -0,0 +1,6 @@
+jeffreyhuang@google.com
+jtnguyen@google.com
+muhammadq@google.com
+sharaienko@google.com
+singhtejinder@google.com
+tsaichristine@google.com
diff --git a/tests/stats/src/android/stats/cts_root/StatsHelperTest.java b/tests/stats/src/android/stats/cts_root/StatsHelperTest.java
new file mode 100644
index 0000000..e295f52
--- /dev/null
+++ b/tests/stats/src/android/stats/cts_root/StatsHelperTest.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2021 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.stats.cts_root;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.app.StatsManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import com.android.server.stats.StatsHelper;
+
+import org.junit.Test;
+
+public class StatsHelperTest {
+    private static final String TAG = StatsHelperTest.class.getSimpleName();
+
+    private static class MockReceiver extends BroadcastReceiver  {
+        protected boolean mCalledOnReceive = false;
+
+        @Override
+        public synchronized void onReceive(Context context, Intent intent) {
+            mCalledOnReceive = true;
+            onReceiveInternal(context, intent);
+            notifyAll();
+        }
+
+        protected void onReceiveInternal(Context context, Intent intent) {
+        }
+
+        public synchronized void waitForReceiver(long timeout) throws InterruptedException {
+            if (!mCalledOnReceive) {
+                wait(timeout);
+            }
+            assertThat(mCalledOnReceive).isTrue();
+        }
+    }
+
+    @Test
+    public void testSendStatsdReadyBroadcast() throws Exception {
+        final Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        final IntentFilter intentFilter = new IntentFilter(StatsManager.ACTION_STATSD_STARTED);
+        final int flags = 0x01000000; // Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
+        MockReceiver receiver = new MockReceiver() {
+            @Override
+            protected void onReceiveInternal(Context context, Intent intent) {
+                assertThat(intent.getAction()).isEqualTo(StatsManager.ACTION_STATSD_STARTED);
+                assertThat(intent.getFlags() & flags).isEqualTo(flags);
+            }
+        };
+
+        context.registerReceiver(receiver, intentFilter);
+
+        StatsHelper.sendStatsdReadyBroadcast(context);
+
+        receiver.waitForReceiver(2_000);
+    }
+}
diff --git a/tests/usage/Android.bp b/tests/usage/Android.bp
new file mode 100644
index 0000000..907383d
--- /dev/null
+++ b/tests/usage/Android.bp
@@ -0,0 +1,41 @@
+// Copyright (C) 2021 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "CtsRootUsageDeviceTestCases",
+    defaults: ["cts_defaults"],
+    srcs: ["src/**/*.java"],
+    static_libs: [
+        "androidx.test.core",
+        "androidx.test.ext.junit",
+        "androidx.test.rules",
+        "compatibility-device-util-axt",
+        "truth-prebuilt",
+    ],
+    libs: [
+        "android.test.runner",
+        "android.test.base",
+        "services.core",
+        "services.usage",
+    ],
+    test_suites: [
+        "cts_root",
+        "general-tests",
+    ],
+    sdk_version: "test_current",
+}
diff --git a/tests/usage/AndroidManifest.xml b/tests/usage/AndroidManifest.xml
new file mode 100644
index 0000000..89d007e
--- /dev/null
+++ b/tests/usage/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2021 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.usage.cts_root" >
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android"
+                     android:label="Usage CTS root tests"/>
+
+</manifest>
diff --git a/tests/usage/AndroidTest.xml b/tests/usage/AndroidTest.xml
new file mode 100644
index 0000000..ef4c8ad
--- /dev/null
+++ b/tests/usage/AndroidTest.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2021 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+<configuration description="Runs Usage CTS root tests">
+    <option name="test-suite-tag" value="apct" />
+    <option name="test-suite-tag" value="apct-instrumentation" />
+
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true"/>
+        <option name="test-file-name" value="CtsRootUsageDeviceTestCases.apk"/>
+    </target_preparer>
+
+    <!-- Restart to clear test code from system server -->
+    <target_preparer class="com.android.tradefed.targetprep.DeviceCleaner">
+        <option name="cleanup-action" value="REBOOT" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest">
+        <option name="package" value="android.usage.cts_root"/>
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+        <option name="restart" value="false" />
+    </test>
+</configuration>
diff --git a/tests/usage/OWNERS b/tests/usage/OWNERS
new file mode 100644
index 0000000..79add9e
--- /dev/null
+++ b/tests/usage/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 95221
+
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
diff --git a/tests/usage/src/android/usage/cts_root/StorageStatsManagerLocalTest.java b/tests/usage/src/android/usage/cts_root/StorageStatsManagerLocalTest.java
new file mode 100644
index 0000000..4e63b8f
--- /dev/null
+++ b/tests/usage/src/android/usage/cts_root/StorageStatsManagerLocalTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2021 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.usage.cts_root;
+
+import static android.os.storage.StorageManager.UUID_DEFAULT;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.app.usage.StorageStats;
+import android.app.usage.StorageStatsManager;
+import android.content.Context;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageStats;
+import android.os.UserHandle;
+import android.util.Log;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import com.android.server.LocalManagerRegistry;
+import com.android.server.usage.StorageStatsManagerLocal;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+import org.junit.Test;
+
+public class StorageStatsManagerLocalTest {
+    private static final String TAG = "StorageStatsManagerLocalTest";
+
+    private static final int AUGMENT_BYTES_FOR_PACKAGE = 7907;
+    private static final int AUGMENT_BYTES_FOR_UID = 6883;
+    private static final int AUGMENT_BYTES_FOR_USER = 5741;
+
+    @Test
+    public void testStorageAugmenter() throws Exception {
+        Context context = ApplicationProvider.getApplicationContext();
+        StorageStatsManager storageStatsManager =
+                context.getSystemService(StorageStatsManager.class);
+        String packageName = context.getPackageName();
+        UserHandle user = context.getUser();
+        int uid = android.os.Process.myUid();
+
+        // Collect stats before augmentation
+        StorageStats beforeStatsForPkg =
+                storageStatsManager.queryStatsForPackage(UUID_DEFAULT, packageName, user);
+        StorageStats beforeStatsForUid = storageStatsManager.queryStatsForUid(UUID_DEFAULT, uid);
+        StorageStats beforeStatsForUser = storageStatsManager.queryStatsForUser(UUID_DEFAULT, user);
+
+        // Register our augmenter
+        LocalManagerRegistry.getManager(StorageStatsManagerLocal.class)
+                .registerStorageStatsAugmenter(new TestStorageStatsAugmenter(), TAG);
+
+        // Collect stats after augmentation
+        StorageStats afterStatsForPkg =
+                storageStatsManager.queryStatsForPackage(UUID_DEFAULT, packageName, user);
+        StorageStats afterStatsForUid = storageStatsManager.queryStatsForUid(UUID_DEFAULT, uid);
+        StorageStats afterStatsForUser = storageStatsManager.queryStatsForUser(UUID_DEFAULT, user);
+
+        // Verify the storage size increase.
+        assertThat(afterStatsForPkg.getDataBytes() - beforeStatsForPkg.getDataBytes())
+                .isEqualTo(AUGMENT_BYTES_FOR_PACKAGE);
+        assertThat(afterStatsForUid.getDataBytes() - beforeStatsForUid.getDataBytes())
+                .isEqualTo(AUGMENT_BYTES_FOR_UID);
+        assertThat(afterStatsForUser.getDataBytes() - beforeStatsForUser.getDataBytes())
+                .isEqualTo(AUGMENT_BYTES_FOR_USER);
+    }
+
+    private class TestStorageStatsAugmenter implements
+            StorageStatsManagerLocal.StorageStatsAugmenter {
+        @Override
+        public void augmentStatsForPackageForUser(
+                PackageStats stats,
+                String packageName,
+                UserHandle userHandle,
+                boolean canCallerAccessAllStats) {
+            stats.dataSize += AUGMENT_BYTES_FOR_PACKAGE;
+        }
+
+        @Override
+        public void augmentStatsForUid(
+                PackageStats stats, int uid, boolean canCallerAccessAllStats) {
+            stats.dataSize += AUGMENT_BYTES_FOR_UID;
+        }
+
+        @Override
+        public void augmentStatsForUser(PackageStats stats, UserHandle userHandle) {
+            stats.dataSize += AUGMENT_BYTES_FOR_USER;
+        }
+    }
+}